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
7971983af0a0b50e090fdaba872695d1bed11aff
fix formatting
src/jsxc.lib.tab.js
src/jsxc.lib.tab.js
/** * Provides communication between tabs. * * @namespace jsxc.tab */ jsxc.tab = { CONST: { MASTER: 'master', SLAVE: 'slave' }, exec: function(target, cmd, params) { params = Array.prototype.slice.call(arguments, 2); if (params.length === 1 && $.isArray(params[0])) { params = params[0]; } if (target === jsxc.tab.CONST[jsxc.master ? 'MASTER' : 'SLAVE']) { jsxc.exec(cmd, params); if (jsxc.master) { return; } } jsxc.storage.setUserItem('_cmd', { target: target, cmd: cmd, params: params, rnd: Math.random() // force storage event }); }, /*jshint -W098 */ execMaster: function(cmd, params) { var args = Array.prototype.slice.call(arguments); args.unshift(jsxc.tab.CONST.MASTER); jsxc.tab.exec.apply(this, args); }, execSlave: function(cmd, params) { var args = Array.prototype.slice.call(arguments); args.unshift(jsxc.tab.CONST.SLAVE); jsxc.tab.exec.apply(this, args); } /*jshint +W098 */ };
JavaScript
0.001459
@@ -940,19 +940,16 @@ %7B%0A - var args @@ -996,19 +996,16 @@ ;%0A - args.uns @@ -1035,27 +1035,24 @@ VE);%0A%0A - - jsxc.tab.exe @@ -1075,24 +1075,18 @@ gs);%0A - %7D%0A +%7D%0A /*jsh
0df28b36718ebae15dd6a8099191fd59322aab13
Add check for notiflist to redirect correctly to login
src/routes/NotifList/index.js
src/routes/NotifList/index.js
import React from 'react' import { checkAuth } from '../../api/utils' import NotifListView from './components/NotifListView' export default (store) => ({ path : 'home', getComponent (nextState, cb) { require.ensure([], () => { const state = store.getState() cb(null, () => <NotifListView {...state.user} />) }, 'home') }, onEnter: (nextState, replace, cb) => { const { user } = store.getState() if(!user) { replace('/') } cb() } })
JavaScript
0
@@ -434,16 +434,45 @@ if(!user + && !Object.keys(user).length ) %7B%0A
42609efc4f6829dbaf8d1e369e276b739cabfe0c
Fix countdown bug
src/routes/rewards/Rewards.js
src/routes/rewards/Rewards.js
import React, { Component, PropTypes } from 'react'; import CutScene from '../../components/CutScene'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Rewards.css'; import history from '../../core/history'; const title = 'Destiny'; class Reward extends Component { constructor({ planetName }) { super(); this.props = { planetName: 'Mars' }; this.state = { countdown: 15 }; } componentDidMount() { let timeoutMs = 3000; if (!this.gameComplete()) { setTimeout(this.startCountdown.bind(this), timeoutMs); } else { setTimeout(this.fadeInHeader.bind(this), timeoutMs); } } fadeInHeader() { this.refs.planetHeadingWrapper.classList.add(s.visible); } startCountdown() { this.refs.countdownWrapper.classList.add(s.visible); this.fadeInHeader(); let count = this.state.countdown; if (count > 0) { this.setState({ countdown: count - 1 }); setTimeout(this.startCountdown.bind(this), 1000); } else { history.push({pathname: '/orbit'}); } } gameComplete() { return this.props.planetName === 'win'; } render() { let {countdown} = this.state; let {planetName} = this.props; let itemTitle = this.gameComplete() ? 'box' : planetName; let uri = `/images/${planetName}.png`; let backMessage = ''; if (!this.gameComplete()) { backMessage = (<div className={s.continueWrapper} ref="countdownWrapper"> Back to orbit in <span className={s.countdown} ref="countdown">{countdown}</span> </div>); } let graphic = (<div className={s.unlockedWrapper}> <img src={uri} className={s.planet}/> </div>); if (this.gameComplete()) { graphic = (<div className={s.unlockedWrapper}> <div className={s.unlockCode}>0724</div> </div>); } return ( <div className={s.root}> <div className={s.container}> <h1 className={s.rewardsHeader}> <span>Activity</span> <span>Rewards</span> </h1> </div> <div className={s.continueWrapper} ref="planetHeadingWrapper"> <h2>Unlocked {itemTitle}</h2> </div> {graphic} {backMessage} </div> ); } } export default withStyles(s)(Reward);
JavaScript
0.000002
@@ -433,9 +433,9 @@ n: 1 -5 +0 %0A @@ -1058,31 +1058,71 @@ -history.push(%7Bpathname: + console.log('redirect to orbit');%0A window.location.href = '/o @@ -1126,18 +1126,16 @@ '/orbit' -%7D) ;%0A %7D%0A
1dd3b905bed2908a9d90d2086c68172be4d186df
Fix raid name for Bastion of the Penitent
src/legacy/raids.js
src/legacy/raids.js
export default [ {id: 'vale_guardian', raid: 'Forsaken Thicket', wing: 'Spirit Vale', name: 'Vale Guardian', type: 'Boss'}, {id: 'spirit_woods', raid: 'Forsaken Thicket', wing: 'Spirit Vale', name: 'Spirit Woods', type: 'Checkpoint'}, {id: 'gorseval', raid: 'Forsaken Thicket', wing: 'Spirit Vale', name: 'Gorseval', type: 'Boss'}, {id: 'sabetha', raid: 'Forsaken Thicket', wing: 'Spirit Vale', name: 'Sabetha', type: 'Boss'}, {id: 'slothasor', raid: 'Forsaken Thicket', wing: 'Salvation Pass', name: 'Slothasor', type: 'Boss'}, {id: 'bandit_trio', raid: 'Forsaken Thicket', wing: 'Salvation Pass', name: 'Bandit Trio', type: 'Boss'}, {id: 'matthias', raid: 'Forsaken Thicket', wing: 'Salvation Pass', name: 'Matthias', type: 'Boss'}, {id: 'escort', raid: 'Forsaken Thicket', wing: 'Stronghold of the Faithful', name: 'Escort', type: 'Boss'}, {id: 'keep_construct', raid: 'Forsaken Thicket', wing: 'Stronghold of the Faithful', name: 'Keep Construct', type: 'Boss'}, {id: 'twisted_castle', raid: 'Forsaken Thicket', wing: 'Stronghold of the Faithful', name: 'Twisted Castle', type: 'Checkpoint'}, {id: 'xera', raid: 'Forsaken Thicket', wing: 'Stronghold of the Faithful', name: 'Xera', type: 'Boss'}, {id: 'cairn', raid: 'Forsaken Thicket', wing: 'Bastion of the Penitent', name: 'Cairn', type: 'Boss'}, {id: 'mursaat_overseer', raid: 'Forsaken Thicket', wing: 'Bastion of the Penitent', name: 'Mursaat Overseer', type: 'Boss'}, {id: 'samarog', raid: 'Forsaken Thicket', wing: 'Bastion of the Penitent', name: 'Samarog', type: 'Boss'}, {id: 'deimos', raid: 'Forsaken Thicket', wing: 'Bastion of the Penitent', name: 'Deimos', type: 'Boss'} ]
JavaScript
0
@@ -1235,39 +1235,46 @@ rn', raid: ' -Forsaken Thicke +Bastion of the Peniten t', wing: 'B @@ -1358,39 +1358,46 @@ er', raid: ' -Forsaken Thicke +Bastion of the Peniten t', wing: 'B @@ -1483,39 +1483,46 @@ og', raid: ' -Forsaken Thicke +Bastion of the Peniten t', wing: 'B @@ -1598,39 +1598,46 @@ os', raid: ' -Forsaken Thicke +Bastion of the Peniten t', wing: 'B
13b3c51fef41a388c4960d0303a832caca6455c5
remove emitter
plugin/nodebb.js
plugin/nodebb.js
(function (Module, NodeBB) { 'use strict'; Module.exports = { adminSockets : NodeBB.require('./src/socket.io/admin').plugins, cache : NodeBB.require('./src/posts/cache'), db : NodeBB.require('./src/database'), emitter : NodeBB.require('./src/emitter'), groups : NodeBB.require('./src/groups'), meta : NodeBB.require('./src/meta'), pluginSockets: NodeBB.require('./src/socket.io/plugins'), postTools : NodeBB.require('./src/posts/tools'), serverSockets: NodeBB.require('./src/socket.io').server.sockets, settings : NodeBB.require('./src/settings'), socketIndex : NodeBB.require('./src/socket.io/index'), topics : NodeBB.require('./src/topics'), user : NodeBB.require('./src/user'), utils : NodeBB.require('./public/src/utils'), helpers: NodeBB.require('./src/controllers/helpers'), /** * List is incomplete * * base_dir: '/path/to/NodeBB', * themes_path: '/path/to/NodeBB/node_modules', * views_dir: '/path/to/NodeBB/public/templates', * version: 'NodeBB Version', * url: 'http://localhost:4567', * core_templates_path: '/path/to/NodeBB/src/views', * base_templates_path: '/path/to/NodeBB/node_modules/nodebb-theme-vanilla/templates', * upload_path: '/public/uploads', * relative_path: '', * port: '4567', * upload_url: '/uploads/', * theme_templates_path: '/path/to/NodeBB/node_modules/nodebb-theme-lavender/templates', * theme_config: '/path/to/NodeBB/node_modules/nodebb-theme-lavender/theme.json', * NODE_ENV: 'development' */ nconf : NodeBB.require('nconf'), passport: NodeBB.require('passport'), express : NodeBB.require('express') }; })(module, require.main);
JavaScript
0.000127
@@ -257,64 +257,8 @@ '),%0A - emitter : NodeBB.require('./src/emitter'),%0A @@ -1883,8 +1883,9 @@ e.main); +%0A
8883caf7d2d9525601e089e167b9d3263cdcd198
Fix for Chrome 21
src/lib/pinboard.js
src/lib/pinboard.js
/* * Copyright (c) 2012 mono * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ var Pinboard = {}; Pinboard.indexedDB = window.indexedDB || window.webkitIndexedDB; Pinboard.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction; Pinboard.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange; Pinboard.IDBCursor = window.IDBCursor || window.webkitIDBCursor; Pinboard.DATABASE = 'PinboardDatabase'; Pinboard.VERSION = 20120313; Pinboard.POSTS_STORE = 'Posts'; Pinboard.Uris = {}; Pinboard.Uris.postsAll = function(params) { return 'https://api.pinboard.in/v1/posts/all?' + Utils.buildQuery(params); }; Pinboard.initialize = function(onsuccess) { var request = Pinboard.indexedDB.open(Pinboard.DATABASE); request.onsuccess = function(e) { var db = e.target.result; var request; Pinboard.database = db; if(db.version != Pinboard.VERSION) { request = db.setVersion(Pinboard.VERSION); request.onsuccess = function(e) { var store = db.createObjectStore(Pinboard.POSTS_STORE, { keyPath: 'hash' }); Pinboard.load(onsuccess); }; } else { Pinboard.load(onsuccess); } }; request.onerror = function(e) { }; request.onblocked = function(e) { }; }; Pinboard.load = function(onsuccess) { var transaction = Pinboard.database.transaction(Pinboard.POSTS_STORE); var store = transaction.objectStore(Pinboard.POSTS_STORE); Pinboard.posts = []; store.openCursor().onsuccess = function(e) { var cursor = e.target.result; if(cursor) { Pinboard.posts.push(cursor.value); cursor['continue'](); } else { Pinboard.sortPosts(); onsuccess(); } }; }; Pinboard.store = function(posts, force) { if(force) { Pinboard.posts = []; } if(posts.length === 0) { return; } var transaction = Pinboard.database.transaction(Pinboard.POSTS_STORE, Pinboard.IDBTransaction.READ_WRITE); var store = transaction.objectStore(Pinboard.POSTS_STORE); posts.forEach(function(post) { var request = store.add(post); Pinboard.posts.push(post); }); Pinboard.sortPosts(); }; Pinboard.loggedIn = function() { return ('login' in localStorage); }; Pinboard.update = function(user, password, onsuccess, onerror, fromDt) { var params = { format: 'json' }; if(fromDt) { params.fromdt = fromDt; } var request = new XMLHttpRequest(); request.open('GET', Pinboard.Uris.postsAll(params), true, user, password); request.onreadystatechange = function() { if(request.readyState == 4) { if(request.status == 200) { Pinboard.store(JSON.parse(request.responseText), !fromDt); onsuccess(request.statusText); } else { onerror(request.statusText); } } }; request.send(null); }; Pinboard.login = function(user, password, onsuccess, onerror) { Pinboard.update(user, password, function(message) { localStorage.login = JSON.stringify({ user: user, password: password }); Pinboard.requestAutoUpdate(60 * 60 * 1000); onsuccess(message); }, onerror); }; Pinboard.sortPosts = function() { Pinboard.posts.sort(function(a, b) { if(a.time < b.time) { return 1; } else if(a.time > b.time) { return -1; } return 0; }); }; Pinboard.logout = function() { localStorage.clear(); Pinboard.indexedDB.deleteDatabase(Pinboard.DATABASE); Pinboard.cancelAutoUpdate(); }; Pinboard.autoUpdate = function(onsuccess, onerror, force) { Pinboard.updateTimer = undefined; if(!Pinboard.loggedIn()) { return; } var login = JSON.parse(localStorage.login); var fromDt = !force && Pinboard.posts.length >= 1 ? Pinboard.posts[0].time : undefined; Pinboard.update(login.user, login.password, function(message) { Pinboard.retryCount = 0; Pinboard.requestAutoUpdate(60 * 60 * 1000); if(onsuccess) { onsuccess(message); } }, function(message) { if(Pinboard.retryCount <= 12) { Pinboard.retryCount += 1; } Pinboard.requestAutoUpdate(Pinboard.retryCount * 5 * 60 * 1000); if(onerror) { onerror(message); } }, fromDt); }; Pinboard.forceUpdate = function(onsuccess, onerror) { Pinboard.cancelAutoUpdate(); Pinboard.autoUpdate(onsuccess, onerror, true); }; Pinboard.user = function() { if(!Pinboard.loggedIn()) { return undefined; } return JSON.parse(localStorage.login).user; } Pinboard.loginRequired = function() { if(!Pinboard.loggedIn()) { chrome.tabs.create({ url: chrome.extension.getURL('/login.html') }); return false; } return true; }; Pinboard.requestAutoUpdate = function(time) { Pinboard.cancelAutoUpdate(); Pinboard.updateTimer = setTimeout(Pinboard.autoUpdate, time); }; Pinboard.cancelAutoUpdate = function() { if(Pinboard.updateTimer) { clearTimeout(Pinboard.updateTimer); Pinboard.updateTimer = undefined; } }; Pinboard.posts = []; Pinboard.retryCount = 0; Pinboard.updateTimer = undefined; Pinboard.initialize(function() { if(!Pinboard.loginRequired()) { return; } Pinboard.updateTimer = setTimeout(function() { Pinboard.autoUpdate(undefined, undefined, true); }, 5 * 60 * 1000); });
JavaScript
0
@@ -2375,24 +2375,36 @@ .POSTS_STORE +, 'readonly' );%0A var sto @@ -2929,42 +2929,19 @@ RE, -Pinboard.IDBTransaction.READ_WRITE +'readwrite' );%0A
a48235fe595ce567bff19779e863adfbd1da7728
remove bum url from defaults list
plugins/reset.js
plugins/reset.js
/* Description: * pushes a default URL to screens when /reset is hit * * Dependencies: * settings * * Optional Dependencies: * command - if present, the reset lines can be commands. * * * Configuration: * defaultUrl * * Author: * lonnen, mythmon, potch */ module.exports = function (corsica) { var useCommand = corsica.config.plugins.indexOf('command') >= 0; var settings = corsica.settings.setup('reset', { defaultUrl: ['/default.html', 'http://xkcd.com'], }); var urlIndex = 0; corsica.on('reset', function(content) { return settings.get() .then(function (settings) { var nextLine = settings.defaultUrl[urlIndex]; urlIndex = (urlIndex + 1) % settings.defaultUrl.length; if (useCommand) { if ('screen' in content) { nextLine += ' screen=' + content.screen; } corsica.sendMessage('command', {raw: nextLine}); } else { content.type = 'url'; content.url = nextLine; corsica.sendMessage('content', content); } return content; }); }); };
JavaScript
0.000001
@@ -101,17 +101,16 @@ tings%0A * - %0A * Opti @@ -190,19 +190,16 @@ ands.%0A * - %0A *%0A * C @@ -454,25 +454,8 @@ l: %5B -'/default.html', 'htt
fc0a4f8f873155807e5c9eaf7d58c7e19cfa161d
change wording
l10n/ru_suprolftpd.js
l10n/ru_suprolftpd.js
l10n.lftpd = { lang: 'ru' //!!! локализация используется только в UI (для простоты обновления) ,modname: "Обмен данными" ,tooltip: "запуск управления модулем suprolftpd" ,title: 'СУПРО по Интернету обмениваЮтся данными через `lftp`' ,refreshLog: 'Обновить журнал' ,noload: '== Не загружен журнал ==' ,channels: 'каналы обмена данными' ,chaname: 'Название канала связи' ,toolHelp: 'каналы на передачу и на приём независимы но стартуют/останавливаются вместе' ,go: 'Включить: приём/передачу информации' ,stop: 'Завершить: приём/передачу информации' ,run: 'Стартовать <b>lftp</b>' ,quit: 'Остановить <b>lftp</b>' ,sts:{ transport:'Транспорт: передача информации', download:'<b>lftp</b> на получение', upload:'<b>lftp</b> на отправку', r:'lftp Работает', q:'lftp Завершил работу', f:'Шлёт файлы', g:'Транспорт работает', s:'Транспорт остановлен (без автостарта или не запущен)', e:'Ошибка', b:'Присутствует, но не сконфигурирован' } // backend ,'~lftp_not_found': "Не запущен lftp или неверно задан `id`" ,ENOENT: 'Файл не найден' }
JavaScript
0
@@ -508,14 +508,12 @@ ' -%D0%92%D0%BA%D0%BB%D1%8E%D1%87%D0%B8 +%D0%9D%D0%B0%D1%87%D0%B0 %D1%82%D1%8C: @@ -552,22 +552,23 @@ ,stop: ' -%D0%97%D0%B0%D0%B2%D0%B5%D1%80%D1%88 +%D0%9F%D1%80%D0%B5%D0%BA%D1%80%D0%B0%D1%82 %D0%B8%D1%82%D1%8C: %D0%BF%D1%80%D0%B8
a23585f69d5b13bb70b7be996f868814bbc75f6e
Add results to group solution
week-7/group-project/group_project_solution.js
week-7/group-project/group_project_solution.js
/* As a user, I want to find the total of a list of numbers added together! As a user, I want to find the mean of a list of numbers! As a user, I want to find the median of a list of numbers! My list of numbers can be either an *even* number of numbers or an *odd* number of numbers!! */ // Pseudocode // Define a function names total that accepts an array of numbers as an argument // Inside of the sunction create a variable named sum // Then I want to initialize a counter variable and set it equal to 0 // Using that counter variable as a starting point, I want to loop through the array and for every indice it passes, add the number at that indice to the sum // Return the sum variable // Define a function called mean that accepts an array of numbers as an argument // Inside of the sunction create a variable named sum // Then I want to initialize a counter variable and set it equal to 0 // Using that counter variable as a starting point, I want to loop through the array and for every indice it passes, add the number at that indice to the sum // Return the sum divided by the length of the array (which is the total numbers that were in the array. This will provide us the average) // Define a function called median that accepts an array of numbers as an argument // Create a variable and pass into it the array // Sort the array // If the array.length % 2 == 0 (If the length of the array is even, there will be 2 numbers that are those most middle numbers) // Create a variable and save the two most middle numbers to it. // Add those two numbers and save it to the exact same variable // Divide that number by 2 // Return that number // Else return the middle number // Solution to the pseudocode // function total var total = function(numberArray) { var sum = 0; for(i = 0; i < numberArray.length - 1; i++) { sum += numberArray[i]; } return sum }; console.log(total([1,2,3,4,5,6,7,8,9,0])); // function mean var mean = function(numberArray) { var sum = 0; for(i = 0; i < numberArray.length - 1; i++) { sum += numberArray[i]; } return sum / numberArray.length; }; console.log(mean([1,2,3,4,5,6,7,8,9,10])); // function median var median = function(numberArray) { numberArray.sort(function(a, b) {return a-b;}); console.log(numberArray); var arrayLength = numberArray.length; if(arrayLength % 2 === 0) { var middleSum = numberArray[arrayLength / 2 - 1] + numberArray[arrayLength / 2]; return middleSum / 2; } else { return numberArray[(arrayLength - 1) / 2]; } }; console.log(median([10,9,8,7,6,5,4,3,2,1])); console.log(median([1,3,2,3,4,3,2,6,7,8,9,10])); console.log(median([4,3,6,2,7,9,2,3,0,3,4,6])); /* Final Person User Story Interpretation: As a user, I want to be able to take a bunch of numbers from different sources and consolidate it in one place. Then I want to be able to add up all the numbers so that I can see how many I've got. See, In my line of work, people often come to me with certain tasks. And these tasks require me to give an estimate as per my fee. So if I wanted to know what my total is for the month so as to keep track, I'd like to be able to do that. As a user, I would like to be able to figure out what my average is. As per the aforementioned line of work, I would like a good solid number as far as my usual fee, something that I could show to people so they know I'm not jerking them. So if there's some way I could take all the 'donations' I collect through the month, find some way to figure out what my average donation is, I could show people without having to get mean. You know what I mean? As a user, I would like to know what my middling fee is. Not the average, because that takes into account the highs and the lows of the seasons and what have you, but actual dead center, smack in the middle bullseye fee that I charge for my talents. That way, people will know that I play it straight. I don't give them the run around. I got numbers, see? Hard numbers that don't lie. I take them and show them that I got a 'mean' fee. But that don't mean that's what they getting charged, only if they brought in as much as my grand total. So as to be equitible, I would like the amount that's right in the middle so they know they're gettin a fair shake from Bobby the BullFrog. I woulda said chorus frog, but I don't sing to no one for nothin. */
JavaScript
0
@@ -4428,8 +4428,297 @@ thin.%0A*/ +%0A%0A%0A/*%0AResults:%0A%0ALooks like we nailed it for the first couple of %22Sum%22 tests! Admittedly, I had to swap the terms %22total%22 and %22sum%22 to get it to work with the tests.%0A%0AUnfortunately, we error out at the 3rd test, %22sum should return the sum of all elements in an array with an odd length.%22%0A*/
16138712c37aa27b5dd97d9655b9663b0f3aebcf
remove max extent error
src/main/js/controller/timeseriesController.js
src/main/js/controller/timeseriesController.js
/* * Copyright (C) 2014-2014 52°North Initiative for Geospatial Open Source * Software GmbH * * 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. */ var TimeSeriesController = { timeseries: {}, init: function() { EventManager.subscribe("resetStatus", $.proxy(this.removeAllTS, this)); EventManager.subscribe("timeextent:change", $.proxy(this.changeTimeExtent, this)); EventManager.subscribe("timeseries:changeStyle", $.proxy(this.updateTS, this)); EventManager.subscribe("timeseries:zeroScaled", $.proxy(this.updateTS, this)); this.loadSavedTimeseries(); }, loadSavedTimeseries: function() { $.each(Status.getTimeseries(), $.proxy(function(internalId, elem) { var promise = Rest.timeseries(elem.tsId, elem.apiUrl); var that = this; promise.done(function(ts) { if (elem.style !== undefined) { ts.setStyle(TimeseriesStyle.createStyleOfPersisted(elem.style)); } that.addTS(ts); }); }, this)); }, addTSbyId: function(tsId, apiUrl) { var promise = Rest.timeseries(tsId, apiUrl); var that = this; promise.done(function(ts) { that.addTS(ts); }); }, /*----- add timeseries -----*/ addTS: function(ts) { Status.addTimeseries(ts); EventManager.publish("timeseries:add", [ts]); this.timeseries[ts.getInternalId()] = ts; // request data var from = TimeController.currentTimespan.from; var till = TimeController.currentTimespan.till; this.loadTsData(ts, { from: from, till: till }); }, updateTS: function(evt, ts) { Status.addTimeseries(ts); }, loadTsData: function(ts, timespan) { EventManager.publish("timeseries:data:load", [ts]); ts.fetchData(timespan, $.proxy(this.finishedGetData, this)); }, finishedGetData: function(ts) { EventManager.publish("timeseries:data:loadfinished", [ts]); this.checkSyncedStatus(); }, checkSyncedStatus: function() { var syncedComplete = true; $.each(this.timeseries, function(index, elem) { if (!elem.isSynced()) { syncedComplete = false; return; } }); if (syncedComplete) { EventManager.publish("timeseries:synced", [this.timeseries]); } }, /*----- update timeextent -----*/ changeTimeExtent: function(event, timeExtent) { this.unsyncTimeseries(); $.each(this.timeseries, $.proxy(function(index, elem) { this.loadTsData(elem, timeExtent); }, this)); }, unsyncTimeseries: function() { $.each(this.timeseries, function(index, elem) { elem.unSynced(); }); }, /*----- remove timeseries -----*/ removeTS: function(ts) { ts.destroy(); Status.removeTimeseries(ts); delete this.timeseries[ts.getInternalId()]; EventManager.publish("timeseries:remove", [ts]); }, /*----- remove all timeseries -----*/ removeAllTS: function() { this.timeseries = {}; EventManager.publish("timeseries:removeAll"); }, getTimeseriesCollection: function() { return this.timeseries; }, getTimeseries: function(id) { return this.timeseries[id]; }, deselectAllTs: function() { $.each(this.getTimeseriesCollection(), $.proxy(function(idx, elem){ elem.setSelected(false); }, this)); }, getMaxTimeExtent: function() { var earliestStart; var latestEnd; $.each(this.timeseries, $.proxy(function(index,elem) { if (elem.getFirstValue() || elem.getLastValue()) { var start = moment(elem.getFirstValue().timestamp); var end = moment(elem.getLastValue().timestamp); if ( !earliestStart || start.isBefore(earliestStart)) { earliestStart = start; } if ( !latestEnd || end.isAfter(latestEnd)) { latestEnd = end; } } })); return { from : earliestStart, till: latestEnd }; } };
JavaScript
0.000051
@@ -4427,36 +4427,13 @@ ue() - %7C%7C elem.getLastValue() ) %7B%0D%0A + @@ -4501,74 +4501,8 @@ );%0D%0A - var end = moment(elem.getLastValue().timestamp);%0D%0A @@ -4610,24 +4610,24 @@ t = start;%0D%0A - @@ -4625,32 +4625,153 @@ %7D%0D%0A + %7D%0D%0A if (elem.getLastValue()) %7B%0D%0A var end = moment(elem.getLastValue().timestamp);%0D%0A
0f803901a2f9c820fc355e28a99bfb7a585a8171
fix loading of reference value data when panning diagram
src/main/js/controller/timeseriesController.js
src/main/js/controller/timeseriesController.js
/* * Copyright (C) 2014-2014 52°North Initiative for Geospatial Open Source * Software GmbH * * 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. */ var TimeSeriesController = { timeseries: {}, init: function() { EventManager.subscribe("resetStatus", $.proxy(this.removeAllTS, this)); EventManager.subscribe("timeextent:change", $.proxy(this.changeTimeExtent, this)); this.loadSavedTimeseries(); }, loadSavedTimeseries: function() { $.each(Status.getTimeseries(), $.proxy(function(internalId, elem) { var promise = Rest.timeseries(elem.tsId, elem.apiUrl); var that = this; promise.done(function(ts) { if (elem.style) { var style = ts.getStyle(); style.setColor(elem.style.color); style.setChartType(elem.style.chartType); style.setIntervalByHours(elem.style.interval); } that.addTS(ts); }); }, this)); }, addTSbyId: function(tsId, apiUrl) { var promise = Rest.timeseries(tsId, apiUrl); var that = this; promise.done(function(ts) { that.addTS(ts); }); }, /*----- add timeseries -----*/ addTS: function(ts) { Status.addTimeseries(ts); EventManager.publish("timeseries:add", [ts]); this.timeseries[ts.getInternalId()] = ts; // request data var from = TimeController.currentTimespan.from; var till = TimeController.currentTimespan.till; this.loadTsData(ts, { from: from, till: till }); }, loadTsData: function(ts, timespan) { EventManager.publish("timeseries:data:load", [ts]); ts.fetchData(timespan, $.proxy(this.finishedGetData, this)).fail($.proxy(function(id) { this.removeTS(this.timeseries[id]); this.checkSyncedStatus(); }, this)); }, finishedGetData: function(ts) { EventManager.publish("timeseries:data:loadfinished", [ts]); this.checkSyncedStatus(); }, checkSyncedStatus: function() { var syncedComplete = true; $.each(this.timeseries, function(index, elem) { if (!elem.isSynced()) { syncedComplete = false; return; } }); if (syncedComplete) { EventManager.publish("timeseries:synced", [this.timeseries]); } }, /*----- update timeextent -----*/ changeTimeExtent: function(event, timeExtent) { this.unsyncTimeseries(); $.each(this.timeseries, $.proxy(function(index, elem) { this.loadTsData(elem, timeExtent); }, this)); }, unsyncTimeseries: function() { $.each(this.timeseries, function(index, elem) { elem.unSynced(); }); }, /*----- remove timeseries -----*/ removeTS: function(ts) { ts.destroy(); Status.removeTimeseries(ts); delete this.timeseries[ts.getInternalId()]; EventManager.publish("timeseries:remove", [ts]); }, /*----- remove all timeseries -----*/ removeAllTS: function() { this.timeseries = {}; EventManager.publish("timeseries:removeAll"); }, getTimeseriesCollection: function() { return this.timeseries; }, getMaxTimeExtent: function() { var earliestStart; var latestEnd; $.each(this.timeseries, $.proxy(function(index,elem) { var start = moment(elem.getFirstValue().timestamp); var end = moment(elem.getLastValue().timestamp); if ( !earliestStart || start.isAfter(earliestStart)) { earliestStart = start; } if ( !latestEnd || end.isBefore(latestEnd)) { latestEnd = end; } })); return { from : earliestStart, till: latestEnd }; } };
JavaScript
0
@@ -4025,32 +4025,99 @@ n(index,elem) %7B%0A + if (elem.getFirstValue() %7C%7C elem.getLastValue()) %7B%0A var @@ -4172,24 +4172,28 @@ + + var end = mo @@ -4221,32 +4221,36 @@ e().timestamp);%0A + if ( @@ -4316,16 +4316,20 @@ + + earliest @@ -4347,34 +4347,42 @@ rt;%0A + + %7D%0A + if ( @@ -4439,16 +4439,20 @@ + latestEn @@ -4456,24 +4456,42 @@ tEnd = end;%0A + %7D%0A
6d37b5f7eb93fbc971099e7615329b492c61f617
fix the wrong override function.
transition.js
transition.js
define(["dojo/_base/kernel", "dojo/_base/array","dojo/_base/html","dojo/DeferredList","./animation"], function(dojo, darray, dhtml, DeferredList,animation){ return function(from, to, options){ var rev = (options && options.reverse) ? -1 : 1; if(!options || !options.transition || !animation[options.transition]){ dojo.style(from,"display","none"); dojo.style(to, "display", ""); }else{ var defs=[]; var transit=[]; var duration = 250; if(options.transition === "fade"){ duration = 600; }else if (options.transition === "flip"){ duration = 200; } dojo.style(from, "display", ""); dojo.style(to, "display", ""); if (from){ var fromDef = new dojo.Deferred(); //create animation to transit "from" out var fromTransit = animation[options.transition](from, { "in": false, direction: rev, duration: duration, afterEnd: function(){ fromDef.resolve(from); } }); defs.push(fromDef); transit.push(fromTransit); } var toDef = new dojo.Deferred(); //create animation to transit "to" in var toTransit = animation[options.transition](to, { direction: rev, duration: duration, afterEnd: function(){ toDef.resolve(to); } }); defs.push(toDef); transit.push(toTransit); //TODO If it is flip use the chainedPlay //play fromTransit and toTransit together if(options.transition === "flip"){ animation.chainedPlay(transit); }else{ animation.groupedPlay(transit); } return new dojo.DeferredList(defs); } } });
JavaScript
0.000001
@@ -891,25 +891,27 @@ on,%0A%09%09%09%09 -a +onA fterEnd: fun @@ -1305,17 +1305,19 @@ -a +onA fterEnd:
57b486e32f5d748260e512b2b74bc899be388272
Add currency to the salary request
src/bot/helpers/salary.js
src/bot/helpers/salary.js
import { get } from 'lodash'; import { getUserByPageScopedId } from '../../lib/postgres'; import { getDocument } from '../../lib/couchdb'; export const showSalary = async (page_scoped_id, reply) => { const user = await getUserByPageScopedId(page_scoped_id); if (!user) { return await reply({ text: 'Something went wrong. Please try again.' }); } try { const ebudgie = await getDocument(user.ebudgie_id); const salary = get(ebudgie.salaries[ebudgie.salaries.length - 1], 'value', 0); await reply({ text: `Your current salary is: ${salary}` }); } catch (e) { console.log('Error during showing salary', e); await reply({ text: 'Something went wrong. Please try again.' }); } };
JavaScript
0.000364
@@ -510,16 +510,68 @@ e', 0);%0A + const currency = get(ebudgie, 'currency', '$');%0A awai @@ -626,16 +626,27 @@ %7Bsalary%7D +$%7Bcurrency%7D %60%0A %7D)
d3bd277287c6d5ac16464a8b122d3cfe1179929c
Update reducers.js
src/main/react-front-end/src/model/reducers.js
src/main/react-front-end/src/model/reducers.js
/*accountInformation [credentials] credentials:{key: validation} */ /* queue [{endpoint1: string, endpoint2: string, speed: number}] */ import { LOGIN, LOGOUT, PROMOTE, ENDPOINT_PROGRESS, ENDPOINT_UPDATE, UPDATE_HASH } from './actions'; import { transferOptimizations } from "./actions"; export const cookies = require("js-cookie"); export const beforeLogin = 0; export const duringLogin = 1; export const afterLogin = 2; const initialState = { login: cookies.get('email') ? true : false, admin: false, email: cookies.get('email') || "noemail" , publicKey: cookies.get('publicKey') || null , hash: cookies.get('hash') || null, endpoint1: cookies.get('endpoint1') ? JSON.parse(cookies.get('endpoint1')) : { login: false, credential: {}, uri: "", side: "left" }, endpoint2: cookies.get('endpoint2') ? JSON.parse(cookies.get('endpoint2')) : { login: false, credential: {}, uri: "", side: "right" }, queue: [], transferOptions : { useTransferOptimization : transferOptimizations.None, overwriteExistingFiles : true, verifyFileInterity : false, encryptDataChannel : false, compressDataChannel : false } } export function onedatashareModel(state = initialState, action) { // For now, don't handle any actions // and just return the state given to us. switch (action.type) { case LOGIN: console.log('logging in') const {email, hash, publicKey} = action.credential; console.log(email); cookies.set('email', email, ); cookies.set('hash', hash, ); cookies.set('publicKey', publicKey, ); return Object.assign({}, state, { login: true, email: email, hash: hash, publicKey: publicKey }); case LOGOUT: console.log("logging out"); cookies.remove('email'); cookies.remove('hash'); cookies.remove('admin'); cookies.remove('endpoint1'); cookies.remove('endpoint2'); cookies.remove("publicKey"); window.location.replace('/'); return Object.assign({}, state, { login: false, admin: false, hash: "", email: "noemail" }); case PROMOTE: return Object.assign({}, state, { admin: true, }); case ENDPOINT_PROGRESS: if(action.side === "left") return Object.assign({}, state, { endpoint1: {...state.endpoint1, loginProgress: action.progress}, }); else return Object.assign({}, state, { endpoint2: {...state.endpoint2, loginProgress: action.progress}, }); case ENDPOINT_UPDATE: if(action.side === "left"){ console.log(JSON.stringify({...state.endpoint1, ...action.endpoint})); cookies.set('endpoint1', JSON.stringify({...state.endpoint1, ...action.endpoint}), ); return Object.assign({}, state, { endpoint1: {...state.endpoint1, ...action.endpoint}, }); } else{ cookies.set('endpoint2', JSON.stringify({...state.endpoint2, ...action.endpoint}), ); return Object.assign({}, state, { endpoint2: {...state.endpoint2, ...action.endpoint}, }); } case UPDATE_HASH: cookies.remove('hash'); cookies.set('hash', action.hash, ); return Object.assign({}, state, { hash: action.hash }); default: return state } }
JavaScript
0.000001
@@ -1492,18 +1492,16 @@ ', email -, );%0A%09%09 c @@ -1519,26 +1519,24 @@ 'hash', hash -, );%0A coo @@ -1566,18 +1566,16 @@ ublicKey -, );%0A %09 @@ -2768,37 +2768,35 @@ ction.endpoint%7D) -, );%0A + return @@ -3013,18 +3013,16 @@ dpoint%7D) -, );%0A @@ -3232,18 +3232,16 @@ ion.hash -, );%0A @@ -3371,9 +3371,10 @@ ate%0A %7D%0A - %7D +%0A
f1979f42665eaed8c4dd0f66b12af6e27e2f2de2
Set the operation timeout in the correct place.
dataload.js
dataload.js
#!/usr/bin/env node 'use strict'; var fs = require('fs'); var couchbase = require('couchbase'); var _ = require('underscore'); var Q = require('q'); var AWS = require('aws-sdk'); AWS.config.region = 'us-east-1'; var argv = require('yargs').argv; var BUCKET = 's3-logs.couchbase.com'; var config = require('config'); var db, cache; var LOAD_CONCUR = 128; // connection configuration to pass on to couchbase.connect(). Note that // while connecting with the server we are also opening the beer-sample // bucket. var logdata_config = { connstr : config.get('logdata-connstr'), bucket : config.get('logdata-bucket'), password : config.get('logdata-password'), operationTimeout : 65536 }; var logcache_config = { connstr : config.get('cache-connstr'), bucket : config.get('cache-bucket'), password : config.get('cache-password') }; function start_connections(logbucket_config, cachebucket_config) { // Connect with couchbase server. All subsequent API calls // to `couchbase` library is made via this Connection var cb_db = new couchbase.Cluster(logbucket_config.connstr); var cb_ca = new couchbase.Cluster(cachebucket_config.connstr); db = cb_db.openBucket(logbucket_config.bucket, logbucket_config.password); db.on('connect', function (err) { if (err) { console.error("Failed to connect to cluster: " + err); process.exit(1); } console.log('Couchbase connected to ' + logbucket_config.bucket); }); cache = cb_ca.openBucket(cachebucket_config.bucket, cachebucket_config.password); cache.on('connect', function (err) { if (err) { console.error("Failed to connect to cluster: " + err); process.exit(1); } console.log('Couchbase connected to ' + cachebucket_config.bucket); });} var s3 = new AWS.S3(); var d = new Date(); var yearToProcess = d.getFullYear(); var monthToProcess = d.getMonth() +1; var dayToProcess = d.getDate(); function zero_pad_num(num) { var zero_padded_res = "0" + num; zero_padded_res = zero_padded_res.substr(zero_padded_res.length - 2); return zero_padded_res; } function get_all_files() { var prefix = "packages.couchbase.com-access-log-" + yearToProcess + "-" + zero_pad_num(monthToProcess) + "-" + zero_pad_num(dayToProcess); var all_releases = []; var deferred = Q.defer(); var all_files = []; function inner_all_files(marker) { // cbc cp -a packages.couchbase.com-access-log-2015-$i-$j-$k* >> /mnt/ephemeral/tmp/$i-$j.out var params = { Bucket: BUCKET, /* required */ MaxKeys: 1000, Prefix: prefix, Marker: marker }; s3.listObjects(params, function (err, data) { if (err) { console.log('ERROR getting releases: ', err); return deferred.reject(err); } all_releases = all_releases.concat(data.Contents); if (data.IsTruncated) { var next_marker = data.Contents.slice(-1)[0].Key; deferred.notify(all_releases.length); inner_all_files(next_marker); } else { all_releases.map(function (entry) { all_files.push(entry.Key); }); deferred.resolve(all_files); } }); } inner_all_files(); return deferred.promise; } function load_a_file(the_file, curr_num, when_done) { //console.log("loading " + the_file + "..."); //console.log("loading number " + curr_num); var params = { Bucket: BUCKET, /* required */ Key: the_file /* required */ }; s3.getObject(params, function(err, data) { //console.log("From S3, loading " + params.Key); if (err) { console.log(err, err.stack); } // an error occurred else{ db.insert(the_file, data.Body.toString(), {}, function(error, result) { if (error) { console.log('finished ' + curr_num + ' WITH ERROR', error, error.stack); } else { //console.log('finished ' + curr_num); } when_done(); }); } }); } function concurrencyLimitedForEach(list, concur, fn, done) { if (list.length <= 0) { return done(); } var i = 0; var proced = 0; function doneOne() { proced++; if (proced >= list.length) { done(); } else { processOne(); } } function processOne() { if (i >= list.length) return; var curI = i++; fn(list[curI], curI, doneOne); } for (var j = 0; j < concur; ++j) { processOne(); } } if (typeof argv.y != 'undefined') { yearToProcess = argv.y; } if (typeof argv.m != 'undefined') { monthToProcess = argv.m; } if (typeof argv.d != 'undefined') { dayToProcess = argv.d; } start_connections(logdata_config, logcache_config); console.log("Will process for: " + yearToProcess, monthToProcess, dayToProcess); get_all_files().then( function(all_today) { //console.log(JSON.stringify(all_today)); console.log("Processing this many records: " + all_today.length); //for (var i=0; i<all_today.length; i++) { // load_a_file(all_today[i]); //} concurrencyLimitedForEach(all_today, LOAD_CONCUR, load_a_file, function() { console.log("finished data load"); process.exit(0); }); }, function (rejection) { console.log("ERROR: " + rejection); });
JavaScript
0.000003
@@ -346,16 +346,47 @@ R = 128; +%0Avar OPERATION_TIMEOUT = 65536; %0A%0A// con @@ -695,38 +695,8 @@ rd') -,%0A operationTimeout : 65536 %0A%7D;%0A @@ -1282,32 +1282,81 @@ unction (err) %7B%0A + db.operationTimeout = OPERATION_TIMEOUT;%0A if (err)
893b26eab29b8f48705cf54897138034e12ff8a7
Add missing suffix to inline citation token stream
src/md_citations.js
src/md_citations.js
"use strict"; var parseLinkLabel = require('markdown-it/lib/helpers/parse_link_label') , citeRegex = /(.* )?@@d(\d+)(, .*)?/ , impliedDocumentCiteRegex = /^\[[^@;]+\]$/ function getCitations(label, makeURL) { var citations citations = label .split(';') .map(function (ref) { return ref.match(citeRegex) }) // Every semicolon separated citation must be valid, or else null if (!citations.every(function (match) { return match })) return null; return citations .map(function (match) { var prefix = match[1] , id = match[2] , url = makeURL(id) , locator = match[3] return { prefix, id, url, locator } }); } function citationTokens(state, citations, makeInlineCitation, push) { let tokens = push ? undefined : [] , token , inlineCitation function makeToken(type, tag, nesting) { if (push) { return state.push(type, tag, nesting); } else { let _token = new state.Token(type, tag, nesting); tokens.push(_token); return _token; } } inlineCitation = makeInlineCitation(citations); // Insert citation tokens for each citation // TODO: maybe be more sophisticated about this? token = makeToken('en_cite_section_open', 'cite', 1); token.meta = { citations } if (inlineCitation.prefix) { token = makeToken('text', '', 0); token.content = inlineCitation.prefix; } inlineCitation.citations.forEach(function (citeText, idx) { token = makeToken('en_cite_open', 'a', 1); token.attrs = [ [ 'href', citations[idx].url ], [ 'class', 'ENInlineReference ENInlineReference-document' ] ]; token.meta = { enItemType: 'document', enItemID: citations[idx].id, enItemURL: citations[idx].url, } token = makeToken('text', '', 0); token.content = citeText.trim(); token = makeToken('en_cite_close', 'a', -1); if (idx < citations.length - 1) { token = makeToken('text', '', 0); token.content = inlineCitation.delimiter; } }); token = makeToken('en_cite_section_close', 'cite', -1); return tokens; } function createBlockquoteRule(md, projectBaseURL, makeInlineCitation) { return function enBlockquoteCitations(state) { var blockTokens = state.tokens , currentBlockquote = {} , blockquotes = [] , _citationBlockDocumentData = null blockTokens.forEach(function (token, idx) { if (token.type === 'container_document_open') { _citationBlockDocumentData = token.meta; } if (token.type === 'container_document_closed') { _citationBlockDocumentData = null; } if (token.type === 'blockquote_open') { currentBlockquote[token.level] = idx; } if (token.type === 'blockquote_close') { blockquotes.push([currentBlockquote[token.level], idx, _citationBlockDocumentData]); } }); blockquotes.forEach(function (data) { var blockStart = data[0] , blockStop = data[1] , citationBlockDocumentData = data[2] , inCitationBlock = citationBlockDocumentData !== null , containsClosingCitation // FIXME figure out the best number on this first check. It should just // prevent things like one line with "> [@@d1]" containsClosingCitation = ( (blockStop - blockStart) > 3 && blockTokens[blockStop - 3].type === 'paragraph_open' && blockTokens[blockStop - 1].type === 'paragraph_close' && blockTokens[blockStop - 2].type === 'inline' && blockTokens[blockStop - 2].children && ( !inCitationBlock && blockTokens[blockStop - 2].children.length === 5 && blockTokens[blockStop - 2].children[0].type === 'en_cite_section_open' && blockTokens[blockStop - 2].children[1].type === 'en_cite_open' && blockTokens[blockStop - 2].children[2].type === 'text' && blockTokens[blockStop - 2].children[3].type === 'en_cite_close' && blockTokens[blockStop - 2].children[4].type === 'en_cite_section_close' ) || ( inCitationBlock && blockTokens[blockStop - 2].children.length === 1 && blockTokens[blockStop - 2].children[0].type === 'text' && impliedDocumentCiteRegex.test(blockTokens[blockStop - 2].children[0].content) ) ); if (!containsClosingCitation) return; // FIXME: should state.parentType be changed? It's not documented // anywhere but it seems like markdown-it block parsers normally // do that. blockTokens[blockStop - 3].type = 'blockquote_citation_footer_open'; blockTokens[blockStop - 3].tag = 'footer'; blockTokens[blockStop - 1].type = 'blockquote_citation_footer_close'; blockTokens[blockStop - 1].tag = 'footer'; if (inCitationBlock) { let citations = [{ id: citationBlockDocumentData.enItemID, url: citationBlockDocumentData.enItemURL, locator: blockTokens[blockStop - 2].children[0].content.slice(1, -1) }] blockTokens[blockStop - 2].children = citationTokens(state, citations, makeInlineCitation); } }); } } function createInlineCitationRule(md, projectBaseURL, makeInlineCitation) { var makeURL = require('./get_item_url').bind(null, projectBaseURL, 'document') return function enInlineCitations(state) { var max = state.posMax , labelStart , labelEnd , label , citations // Continue only if starting with a link label if (state.src[state.pos] !== '[') return false; labelStart = state.pos + 1; labelEnd = parseLinkLabel(state, state.pos, true); // No closing link label; stop if (labelEnd < 0) return false; // Skip if this is [label](link) if (state.src[labelEnd + 1] === '(') return false; // This will be the text between the square brackets label = state.src.slice(labelStart, labelEnd); // Only continue if the label is a citation if (!citeRegex.test(label)) return false; citations = getCitations(label, makeURL); // If every citation is not formatted correctly, stop if (!citations) return false; // Advance state past the opening bracket, up to the last char of the label state.pos = labelStart; state.posMax = labelEnd; // Push citation tokens into state citationTokens(state, citations, makeInlineCitation, true); // Advance state past the closing ']' state.pos = labelEnd + 1; state.posMax = max + 1; return true; } } module.exports = function (md, opts) { opts = opts || {}; // Inserted before link so that there won't be any conflicts md.inline.ruler.before( 'link', 'en_inline_citations', createInlineCitationRule(md, opts.projectBaseURL, opts.makeInlineCitation) ); md.core.ruler.push( 'en_blockquote_citations', createBlockquoteRule(md, opts.projectBaseURL, opts.makeInlineCitation) ) }
JavaScript
0.000008
@@ -2018,24 +2018,149 @@ miter;%0A %7D +%0A%0A if (inlineCitation.suffix) %7B%0A token = makeToken('text', '', 0);%0A token.content = inlineCitation.suffix;%0A %7D %0A %7D);%0A%0A to
0f7015178cf5034024d3c8695f86e3091730a9f9
Add group delete to permissions list
src/classes/Permission.js
src/classes/Permission.js
import i18next from 'i18next' import localisationResources from '../../localisations.json' import { Group, User } from '../db/index' import { ForbiddenAPIError } from './APIError' i18next.init({ lng: 'en', resources: localisationResources, }) const permissionLocaleKeys = { 'read': 'permissionRead', 'write': 'permissionWrite', 'delete': 'permissionDelete', 'groups': 'permissionGroup' } let groups = {} /** * Fetches all the permissions from the database * @returns {Promise.<void>} */ async function fetchPermissions () { groups = await Group.findAll({}) groups.sort((group1, group2) => { return group1.priority > group2.priority }) } fetchPermissions() /** * Class for managing user permissions */ export default class Permission { /** * Promise to validate whether a user has the appropriate permissions * @param {string[]} permissions - The permissions to validate * @param {Object} user - The user object of the user to validate * @param {Object} scope - Optional scope array of an oauth2 client to validate * @returns {boolean} */ static require (permissions, user, scope = null) { if (Permission.granted(permissions, user, scope)) { return true } throw new ForbiddenAPIError({}) } /** * Express.js middleware to require a permission or throw back an error * @param {string[]} permissions - The permissions to require * @returns {Function} Express.js middleware function */ static required (permissions) { return function (ctx, next) { if (Permission.granted(permissions, ctx.state.user, ctx.state.scope)) { return next() } else { throw new ForbiddenAPIError({}) } } } /** * Check whether a user has the required permissions * @param {string[]} permissions - The permissions to validate * @param {Object} origUser - The user object of the user to validate * @param {Object} scope - Optional oauth2 client object to validate * @returns {boolean} - Boolean value indicating whether permission is granted */ static granted (permissions, origUser, scope = null) { if (!origUser || User.isDeactivated(origUser)) { return false } else if (!User.isConfirmed(origUser) || User.isSuspended(origUser)) { return false } let user = {} Object.assign(user, origUser) let hasPermission = false for (let permission of permissions) { for (let groupRelation of user.data.relationships.groups.data) { let group = groups.find((group) => { return group.id === groupRelation.id }) if (group && group.permissions.includes(permission)) { if (scope) { if (scope.includes(permission) || scope.includes('*')) { hasPermission = true break } } else { hasPermission = true break } } } } return hasPermission } /** * Returns whether a given user is an administrator * @param user The user to check * @returns {boolean} Whether the user is an administrator */ static isAdmin (user) { return user.included.some((include => { if (include.type === 'groups') { return include.attributes.isAdministrator } return false })) } /** * Get the available permissions/oauth scopes * @returns {Object} */ static get groups () { return groups } /** * Get a list of localised human readable permissions from a list of OAuth scopes * @param {Array} scopes Array of OAuth scopes * @param {Object} user A user object to check permissions against * @returns {Array} Array of objects with localised human readable permissions */ static humanReadable (scopes, user) { let humanReadablePermissions = [] if (scopes.includes('*')) { scopes = Permission.allPermissions } for (let permission of scopes) { let permissionComponents = permission.split('.') let [group, action, isSelf] = permissionComponents let permissionLocaleKey = permissionLocaleKeys[action] permissionLocaleKey += isSelf ? 'Own' : 'All' let accessible = Permission.granted([permission], user, null) if (isSelf && scopes.includes(`${group}.${action}`)) { continue } let count = 0 if (group === 'user' && isSelf) { count = 1 } humanReadablePermissions.push({ permission: i18next.t(permissionLocaleKey, { group: i18next.t(group, { count: count }), count: count }), accessible: accessible }) } return humanReadablePermissions } static get allPermissions () { return [ 'rescue.read', 'rescue.write', 'rescue.delete', 'rescue.read.me', 'rescue.write.me', 'rescue.delete.me', 'rat.read', 'rat.write', 'rat.delete', 'rat.read.me', 'rat.write.me', 'rat.delete.me', 'user.read', 'user.write', 'user.delete', 'user.read.me', 'user.write.me', 'user.delete.me', 'client.read', 'client.write', 'client.delete', 'client.read.me', 'client.write.me', 'client.delete.me', 'ship.read', 'ship.write', 'ship.delete', 'ship.read.me', 'ship.write.me', 'ship.delete.me', 'decal.read', 'decal.read.me', 'group.read', 'group.write' ] } }
JavaScript
0.000001
@@ -5469,16 +5469,38 @@ p.write' +,%0A 'group.delete' %0A %5D%0A
7a4cc9d618e0821296e2c35007e7b30fd932062e
make strict `kpm check` check that installed modules match the satisfied versions - fixes #115
src/cli/commands/check.js
src/cli/commands/check.js
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ import type { Reporter } from "kreporters"; import type Config from "../../config.js"; import { Install } from "./install.js"; import Lockfile from "../../lockfile/index.js"; import { MessageError } from "../../errors.js"; import * as constants from "../../constants.js"; import * as fs from "../../util/fs.js"; import * as util from "../../util/misc.js"; let path = require("path"); export let noArguments = true; export function setFlags(commander: Object) { commander.option("--quick-sloppy"); } export async function run( config: Config, reporter: Reporter, flags: Object, args: Array<string> ): Promise<void> { if (!await fs.exists(path.join(config.cwd, constants.LOCKFILE_FILENAME))) { throw new MessageError("No lockfile in this directory. Run `fbkpm install` to generate one."); } let lockfile = await Lockfile.fromDirectory(config.cwd, reporter, { silent: true, strict: true }); let install = new Install("update", flags, args, config, reporter, lockfile, true); let valid = true; // get patterns that are installed when running `kpm install` let [depRequests, rawPatterns] = await install.fetchRequestFromCwd(); // check if patterns exist in lockfile for (let pattern of rawPatterns) { if (!lockfile.getLocked(pattern)) { reporter.error(`Lockfile does not contain pattern: ${pattern}`); valid = false; } } if (flags.quickSloppy) { // in sloppy mode we don't resolve dependencies, we just check a hash of the lockfile // against one that is created when we run `kpm install` let integrityLoc = path.join(config.cwd, "node_modules", constants.INTEGRITY_FILENAME); if (await fs.exists(integrityLoc)) { let actual = await fs.readFile(integrityLoc); let expected = util.hash(lockfile.source); if (actual.trim() !== expected) { valid = false; reporter.error(`Expected an integrity hash of ${expected} but got ${actual}`); } } else { reporter.error("Couldn't find an integrity hash file"); valid = false; } } else { // seed resolver await install.resolver.init(depRequests); // check if any of the node_modules are out of sync let res = await install.linker.initCopyModules(rawPatterns); for (let [loc] of res) { if (!(await fs.exists(loc))) { reporter.error(`Module not installed: ${path.relative(process.cwd(), loc)}`); valid = false; } } } if (valid) { process.exit(0); } else { process.exit(1); } }
JavaScript
0
@@ -672,16 +672,48 @@ c.js%22;%0A%0A +let semver = require(%22semver%22);%0A let path @@ -713,16 +713,18 @@ et path + = requir @@ -2652,146 +2652,1125 @@ -if (!(await fs.exists(loc))) %7B%0A reporter.error(%60Module not installed: $%7Bpath.relative(process.cwd(), loc)%7D%60);%0A valid = false +let human = path.relative(path.join(process.cwd(), %22node_modules%22), loc);%0A human = human.replace(/node_modules/g, %22 %3E %22);%0A%0A if (!(await fs.exists(loc))) %7B%0A reporter.error(%60Module not installed: $%7Bhuman%7D%60);%0A valid = false;%0A %7D%0A%0A let pkg = await fs.readJson(path.join(loc, %22package.json%22));%0A%0A let deps = Object.assign(%7B%7D, pkg.dependencies, pkg.devDependencies, pkg.peerDependencies);%0A%0A for (let name in deps) %7B%0A let range = deps%5Bname%5D;%0A if (!semver.validRange(range)) continue; // exotic%0A%0A let depPkgLoc = path.join(loc, %22node_modules%22, name, %22package.json%22);%0A if (!(await fs.exists(depPkgLoc))) %7B%0A // we'll hit the module not install error above when this module is hit%0A continue;%0A %7D%0A%0A let depPkg = await fs.readJson(depPkgLoc);%0A if (semver.satisfies(depPkg.version, range)) continue;%0A%0A // module isn't correct semver%0A reporter.error(%0A %60Module $%7Bhuman%7D depends on $%7Bname%7D with the range $%7Brange%7D but it doesn't match the %60 +%0A %60installed version of $%7BdepPkg.version%7D%60%0A ) ;%0A
8ac8a34104de993068eacc5a0d8055f021c8e9ee
Remove window when undefined
src/client/batchUpdate.js
src/client/batchUpdate.js
// fallback to timers if rAF not present const stopUpdate = (typeof window !== 'undefined' ? window.cancelAnimationFrame : null) || clearTimeout const startUpdate = (typeof window !== 'undefined' ? window.requestAnimationFrame : null) || ((cb) => window.setTimeout(cb, 0)) /** * Performs a batched update. Uses requestAnimationFrame to prevent * calling a function too many times in quick succession. * You need to pass it an ID (which can initially be `null`), * but be sure to overwrite that ID with the return value of batchUpdate. * * @param {(null|Number)} id - the ID of this update * @param {Function} callback - the update to perform * @return {Number} id - a new ID */ export default function batchUpdate (id, callback) { stopUpdate(id) return startUpdate(() => { id = null callback() }) }
JavaScript
0.000003
@@ -240,23 +240,16 @@ (cb) =%3E -window. setTimeo
89d13f788ab9deb1486bf48758f2ff6a1bd1c5dd
Fix login redirect not working
src/client/public/main.js
src/client/public/main.js
function byID(id) { return document.getElementById(id); } // Login form submission byID("login-form").onsubmit = function() { console.log("Form was submitted"); var userL = byID("user").value; var passL = byID("pass").value; console.log(userL, passL); // Hide the login screen byID("login-background").hidden = true; // Do something with user and pass window.location.replace("/?user=" + user + "&pass=" + pass); // Stops the normal method of submitting return false; } function goHome() { byID("home-page").hidden = false; byID("transactions-page").hidden = true; } function goTransactions() { byID("transactions-page").hidden = false; byID("home-page").hidden = true; } // Start on the home page goHome(); // Check for query string function getParamByName(name, url) { if (!url) { url = window.location.href; } name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); } var user = getParamByName("user"); var pass = getParamByName("pass"); // If there is a user do not show the login if (user && pass) { byID("login-background").hidden = true; } // Test post getAjax("/transactionArrays", function(data) { console.log(data); });
JavaScript
0.000001
@@ -407,16 +407,17 @@ %22 + user +L + %22&pas @@ -426,16 +426,17 @@ %22 + pass +L );%0A%0A //
c932f34c8ff0060d6f38598c731f996860772def
Update NodeJS example test runner
integrations/node_js/server.js
integrations/node_js/server.js
var http = require('http'); var express = require('express'); var path = require('path'); var app = express(); var exec = require('child_process').exec; function run_my_first_test_in_firefox() { exec("nosetests my_first_test.py --with-selenium --browser=firefox"); } function run_my_first_test_in_chrome() { exec("nosetests my_first_test.py --with-selenium --browser=chrome"); } function run_my_first_test_in_firefox_with_demo_mode() { exec("nosetests my_first_test.py --with-selenium --browser=firefox --demo_mode"); } function run_my_first_test_in_chrome_with_demo_mode() { exec("nosetests my_first_test.py --with-selenium --browser=chrome --demo_mode"); } app.get('/', function(req, res) { res.sendFile(path.join(__dirname + '/index.html')); }) app.get('/run_my_first_test_in_firefox', function(req, res) { res.sendFile(path.join(__dirname + '/index.html')); res.redirect('/'); run_my_first_test_in_firefox() }) app.get('/run_my_first_test_in_chrome', function(req, res) { res.sendFile(path.join(__dirname + '/index.html')); res.redirect('/'); run_my_first_test_in_chrome() }) app.get('/run_my_first_test_in_firefox_with_demo_mode', function(req, res) { res.sendFile(path.join(__dirname + '/index.html')); res.redirect('/'); run_my_first_test_in_firefox_with_demo_mode() }) app.get('/run_my_first_test_in_chrome_with_demo_mode', function(req, res) { res.sendFile(path.join(__dirname + '/index.html')); res.redirect('/'); run_my_first_test_in_chrome_with_demo_mode() }) app.listen(3000, "127.0.0.1", function() { console.log('Server running at http://127.0.0.1:3000/'); });
JavaScript
0
@@ -226,32 +226,16 @@ test.py ---with-selenium --browse @@ -328,32 +328,16 @@ test.py ---with-selenium --browse @@ -445,32 +445,16 @@ test.py ---with-selenium --browse @@ -578,24 +578,8 @@ .py ---with-selenium --br @@ -1583,13 +1583,31 @@ 000/ + (CTRL-C to stop) ');%0A%7D);%0A %0A @@ -1605,9 +1605,8 @@ ');%0A%7D);%0A -%0A
9ee7fc2a5823a8920937b07ea7b3a737c01fdeae
verify that the correct placeholder is being returned
src/minify/index.js
src/minify/index.js
import { makePlaceholder, splitByPlaceholders } from '../css/placeholderUtils' const makeMultilineCommentRegex = newlinePattern => new RegExp('\\/\\*[^!](.|' + newlinePattern + ')*?\\*\\/', 'g') const lineCommentStart = /\/\//g const symbolRegex = /(\s*[;:{},]\s*)/g // Counts occurences of substr inside str const countOccurences = (str, substr) => str.split(substr).length - 1 // Joins substrings until predicate returns true const reduceSubstr = (substrs, join, predicate) => { const length = substrs.length let res = substrs[0] if (length === 1) { return res } for (let i = 1; i < length; i++) { if (predicate(res)) { break } res += join + substrs[i] } return res } // Joins at comment starts when it's inside a string or parantheses // effectively removing line comments export const stripLineComment = line => reduceSubstr( line.split(lineCommentStart), '//', str => !str.endsWith(':') && // NOTE: This is another guard against urls, if they're not inside strings or parantheses. countOccurences(str, "'") % 2 === 0 && countOccurences(str, '"') % 2 === 0 && countOccurences(str, '(') === countOccurences(str, ')') ) export const compressSymbols = code => code.split(symbolRegex).reduce((str, fragment, index) => { // Even-indices are non-symbol fragments if (index % 2 === 0) { return str + fragment } // Only manipulate symbols outside of strings if ( countOccurences(str, "'") % 2 === 0 && countOccurences(str, '"') % 2 === 0 ) { return str + fragment.trim() } return str + fragment }, '') // Detects lines that are exclusively line comments const isLineComment = line => line.trim().startsWith('//') // Creates a minifier with a certain linebreak pattern const minify = linebreakPattern => { const linebreakRegex = new RegExp(linebreakPattern + '\\s*', 'g') const multilineCommentRegex = makeMultilineCommentRegex(linebreakPattern) return code => { const newCode = code .replace(multilineCommentRegex, '\n') // Remove multiline comments .split(linebreakRegex) // Split at newlines .filter(line => line.length > 0 && !isLineComment(line)) // Removes lines containing only line comments .map(stripLineComment) // Remove line comments inside text .join(' ') // Rejoin all lines return compressSymbols(newCode) } } export const minifyRaw = minify('(?:\\\\r|\\\\n|\\r|\\n)') export const minifyCooked = minify('[\\r\\n]') export const minifyRawValues = rawValues => splitByPlaceholders(minifyRaw(rawValues.join(makePlaceholder(123))), false) export const minifyCookedValues = cookedValues => splitByPlaceholders( minifyCooked(cookedValues.join(makePlaceholder(123))), false )
JavaScript
0
@@ -73,16 +73,200 @@ Utils'%0A%0A +let i = 0%0A%0Aconst injectUniquePlaceholders = strArr =%3E%0A strArr.reduce((str, val, index, arr) =%3E %7B%0A return str + val + (index %3C arr.length - 1 ? makePlaceholder(i++) : '')%0A %7D, '')%0A%0A const ma @@ -2784,26 +2784,19 @@ Raw( -rawValues.join(mak +injectUniqu ePla @@ -2803,21 +2803,27 @@ ceholder -(123) +s(rawValues )), fals @@ -2920,46 +2920,45 @@ ked( -cookedValues.join(makePlaceholder(123) +injectUniquePlaceholders(cookedValues )),%0A
407cae62cfbc5eddb10eca3095c112bea3b0a976
add 'list' alias
src/commands/LsCommand.js
src/commands/LsCommand.js
"use strict"; const chalk = require("chalk"); const columnify = require("columnify"); const Command = require("../Command"); const output = require("../utils/output"); exports.handler = function handler(argv) { // eslint-disable-next-line no-use-before-define return new LsCommand(argv); }; exports.command = "ls"; exports.describe = "List all public packages"; exports.builder = { json: { describe: "Show information in JSON format", group: "Command Options:", type: "boolean", default: undefined, }, }; class LsCommand extends Command { get requiresGit() { return false; } get defaultOptions() { return Object.assign({}, super.defaultOptions, { json: false, }); } initialize(callback) { this.resultList = this.filteredPackages.map(pkg => ({ name: pkg.name, version: pkg.version, private: pkg.private, })); callback(null, true); } execute(callback) { let result; if (this.options.json) { result = this.formatJSON(); } else { result = this.formatColumns(); } output(result); callback(null, true); } formatJSON() { return JSON.stringify(this.resultList, null, 2); } formatColumns() { const formattedResults = this.resultList.map(result => { const formatted = { name: result.name, }; if (result.version) { formatted.version = chalk.grey(`v${result.version}`); } else { formatted.version = chalk.yellow("MISSING"); } if (result.private) { formatted.private = `(${chalk.red("private")})`; } return formatted; }); return columnify(formattedResults, { showHeaders: false, config: { version: { align: "right", }, }, }); } }
JavaScript
0.000022
@@ -313,24 +313,53 @@ nd = %22ls%22;%0A%0A +exports.aliases = %5B%22list%22%5D;%0A%0A exports.desc @@ -375,18 +375,13 @@ ist -all public +local pac
c81774ca42fe2efdbaa353e630c699fb4274b0c2
Move issues out of comments and into GitHub issues.
src/mixins/scale.js
src/mixins/scale.js
import { scaleLinear } from "d3-scale"; var scaleConstructors = { linear: scaleLinear // TODO support all scales https://github.com/datavis-tech/reactive-vis/issues/26 }; export default function Scale (my, name, options){ options = options || {}; var type = options.type || "linear"; var nice = options.nice || true; var scale = scaleConstructors[type](); // (name + "Domain") and (name + "Range") // must be defined on the model before incoking this mixin. // TODO throw an error if they are not defined at this point. // GitHub issue #25 https://github.com/datavis-tech/reactive-vis/issues/25 my (name + "Scale", function(domain, range){ scale .domain(domain) .range(range); // TODO test //if(nice){ // scale.nice(); //} return scale; }, [name + "Domain", name + "Range"]) (name + "Scaled", function(scale, accessor){ return function (d){ return scale(accessor(d)); }; }, [name + "Scale", name + "Accessor"]); }
JavaScript
0
@@ -292,43 +292,8 @@ ar%22; -%0A var nice = options.nice %7C%7C true; %0A%0A @@ -336,257 +336,8 @@ );%0A%0A -%0A // (name + %22Domain%22) and (name + %22Range%22)%0A // must be defined on the model before incoking this mixin.%0A // TODO throw an error if they are not defined at this point.%0A // GitHub issue #25 https://github.com/datavis-tech/reactive-vis/issues/25%0A%0A my @@ -388,29 +388,26 @@ e)%7B%0A -%0A -scale%0A +return scale .dom @@ -417,25 +417,16 @@ (domain) -%0A .range(r @@ -435,101 +435,8 @@ ge); -%0A%0A // TODO test%0A //if(nice)%7B%0A // scale.nice();%0A //%7D%0A%0A return scale; %0A
b900b3a2d57ab87dac29a773764fee4cbfcf542d
Remove Add conference link
src/components/App/App.js
src/components/App/App.js
import React, {Component} from 'react'; import {format, isPast} from 'date-fns'; import {sortByDate} from './utils'; import styles from './App.scss'; import Footer from '../Footer'; import Link from '../Link'; import Heading from '../Heading'; import Icon from '../Icon'; import ConferenceList from '../ConferenceList'; import ConferenceFilter from '../ConferenceFilter'; const BASE_URL = 'https://raw.githubusercontent.com/nimzco/confs.tech/master/conferences'; const CURRENT_YEAR = (new Date()).getFullYear().toString(); export default class App extends Component { state = { filters: { year: '2017', type: 'javascript', }, showPast: false, loading: true, conferences: [], sortDateDirection: 'asc', }; componentDidMount() { this.loadConference(); } loadConference = () => { const {filters} = this.state; this.setState({loading: true}); fetch(getConferenceLink(filters)) .then((result) => result.json()) // eslint-disable-next-line promise/always-return .then((conferences) => { this.setState({ loading: false, conferences: sortByDate(conferences, 'asc'), }); }) .catch((error) => { console.warn(error); // eslint-disable-line no-console }); }; handleYearChange = (year) => { const {filters} = this.state; this.setState( { filters: {...filters, year}, }, this.loadConference ); }; handleTypeChange = (type) => { const {filters} = this.state; this.setState( { filters: {...filters, type}, }, this.loadConference ); }; togglePast = () => { const {showPast} = this.state; this.setState({showPast: !showPast}); }; pastConferenceToggler = () => { const {showPast, filters: {year}} = this.state; if (CURRENT_YEAR !== year) { return null; } return ( <p> <Link onClick={this.togglePast}> {showPast ? 'Hide past conferences' : 'Show past conferences'} </Link> </p> ); }; sortByDate = (direction) => { const {conferences} = this.state; this.setState({ conferences: sortByDate(conferences, direction), sortDateDirection: direction, }); }; filterConferences = (conferences) => { const {showPast} = this.state; if (showPast) { return conferences; } return conferences.filter((conference) => { return !isPast(format(conference.startDate)); }); }; render() { const { sortDateDirection, loading, conferences, filters: {year, type}, } = this.state; return ( <div className={styles.App}> <div> <div> <Heading element="h1">Find your next {TYPES[type]} conference</Heading> </div> <div> <ConferenceFilter sortDateDirection={sortDateDirection} sortByDate={this.sortByDate} year={year} type={type} onYearChange={this.handleYearChange} onTypeChange={this.handleTypeChange} /> </div> <div> <Link url="https://github.com/nimzco/the-conference-list/issues/new" external > Add a conference </Link> {this.pastConferenceToggler()} </div> <div> {loading ? Loader() : <ConferenceList sortDateDirection={sortDateDirection} conferences={this.filterConferences(conferences)} /> } </div> <Footer /> </div> </div> ); } } function getConferenceLink(state) { const {type, year} = state; return `${BASE_URL}/${year}/${type.toLocaleLowerCase()}.json`; } function Loader() { return ( <div className={styles.Loader}> <Icon source="loading" size={64} /> </div> ); }
JavaScript
0
@@ -3146,224 +3146,8 @@ /%3E%0A - %3C/div%3E%0A %3Cdiv%3E%0A %3CLink%0A url=%22https://github.com/nimzco/the-conference-list/issues/new%22%0A external%0A %3E%0A Add a conference%0A %3C/Link%3E%0A
c9564234be3f012e4d927557f93c2cc3493c7ba4
Add thumbs prop
src/models/Image.js
src/models/Image.js
import cuid from 'cuid'; import { storage, database } from '@/config/firebase'; const getFileExtension = str => str.substring(str.lastIndexOf('.'), str.length); export default function Image(img = {}) { this.file = img.file || null; this.downloadURL = img.downloadURL || null; this.id = img.id || cuid(); const imagesRef = database.ref(`/images/gallery/${this.id}`); // Methods this.url = () => { return this.file ? window.URL.createObjectURL(this.file) : this.downloadURL || null; }; this.put = () => { if (!this.file) throw new Error('Can\'t upload image, no file specified'); if (this.downloadURL) return Promise.resolve({ downloadURL: this.downloadURL }); return storage .ref(`/gallery/${this.id}${getFileExtension(this.file.name)}`) .put(this.file, { customMetadata: { id: this.id } }); }; this.getThumbnail = (width) => { return new Promise((resolve) => { imagesRef.child(width).once('value', snapshot => resolve(snapshot.val())); }); } }
JavaScript
0.000037
@@ -272,24 +272,68 @@ RL %7C%7C null;%0A + this.thumbnails = img.thumbnails %7C%7C null;%0A this.id =
f6a555ee706389c5a816d2482ffb61bc320ac113
Add the AlertForm to the Bitcoin component
src/components/Bitcoin.js
src/components/Bitcoin.js
var React = require('react'); var Stats = require("./Stats"); var BitcoinChart = require("./BitcoinChart"); var Bitcoin = React.createClass({ handlePriceChange: function(priceObject){ // Logic for handling the price change goes here }, render: function() { return ( <div> <Stats onPriceChange={this.handlePriceChange} /> <BitcoinChart /> </div> ) } }); module.exports = Bitcoin;
JavaScript
0
@@ -55,16 +55,56 @@ tats%22);%0A +var AlertForm = require(%22./AlertForm%22);%0A var Bitc @@ -440,24 +440,54 @@ oinChart /%3E%0A + %3CAlertForm /%3E%0A
fa428921c4cfdd9ef4914f072f384f4c904bece8
Allow clicks on past calls only when call status is idle
src/components/CallLog.js
src/components/CallLog.js
import React from 'react'; import _ from 'lodash'; import styled from 'styled-components'; import Paper from 'material-ui/Paper'; import { compose, withHandlers } from 'recompose'; import { connect } from 'react-redux'; import List, { ListItem, ListItemText, ListSubheader } from 'material-ui/List'; const Wrapper = styled(Paper).attrs({ elevation: 0, })` flex-grow: 1; display: flex; `; const DialLog = ({ entries, onListItemClick }) => (<Wrapper> <List dense subheader={<ListSubheader>Your Call Log</ListSubheader>}> {_.map(entries, (entry, i) => (<ListItem button key={i} data-phonenumber={entry.phoneNumber} onClick={onListItemClick}> <ListItemText primary={entry.phoneNumber} /> </ListItem>), )} </List> </Wrapper>); export default compose( connect((state) => state.callLog), withHandlers({ onListItemClick: ({ dispatch }) => (e) => { dispatch({ type: 'dialer/SET_PHONE_NUMBER', value: e.currentTarget.dataset['phonenumber'], }); }, }), )(DialLog);
JavaScript
0
@@ -20,16 +20,52 @@ react';%0A +import PropTypes from 'prop-types';%0A import _ @@ -181,38 +181,115 @@ se, -withHandlers %7D from 'recompose +getContext, withHandlers, withPropsOnChange %7D from 'recompose';%0Aimport %7B CALL_STATUS_IDLE %7D from 'react-sip ';%0Ai @@ -546,16 +546,37 @@ temClick +, allowListItemClicks %7D) =%3E%0A @@ -719,23 +719,75 @@ Item - button key=%7Bi%7D +%0A button=%7BallowListItemClicks%7D%0A key=%7Bi%7D%0A dat @@ -819,16 +819,26 @@ eNumber%7D +%0A onClick @@ -855,16 +855,25 @@ emClick%7D +%0A %3E%0A @@ -1004,16 +1004,195 @@ ompose(%0A + getContext(%7B%0A callStatus: PropTypes.string,%0A %7D),%0A withPropsOnChange(%5B'callStatus'%5D, (%7B callStatus %7D) =%3E (%7B%0A allowListItemClicks: callStatus === CALL_STATUS_IDLE,%0A %7D)),%0A connec
e640b5901207f17332a19c17ea82c6628e5e5167
fix truncating long comments
src/components/Comment.js
src/components/Comment.js
import React from 'react'; import PropTypes from 'prop-types'; import withIntl from '../lib/withIntl'; import { defineMessages, FormattedMessage, FormattedDate } from 'react-intl'; import { graphql } from 'react-apollo' import gql from 'graphql-tag' import Avatar from './Avatar'; import Link from './Link'; import SmallButton from './SmallButton'; import { get, pick } from 'lodash'; import InputField from './InputField'; class Comment extends React.Component { static propTypes = { collective: PropTypes.object, comment: PropTypes.object, LoggedInUser: PropTypes.object } constructor(props) { super(props); this.state = { modified: false, comment: props.comment, mode: undefined }; this.save = this.save.bind(this); this.handleChange = this.handleChange.bind(this); this.toggleEdit = this.toggleEdit.bind(this); this.messages = defineMessages({ 'edit': { id: 'comment.edit', defaultMessage: 'edit' }, 'cancelEdit': { id: 'comment.cancelEdit', defaultMessage: 'cancel edit' } }); this.currencyStyle = { style: 'currency', currencyDisplay: 'symbol', minimumFractionDigits: 2, maximumFractionDigits: 2}; } cancelEdit() { this.setState({ modified: false, mode: 'details' }); } edit() { this.setState({ modified: false, mode: 'edit' }); } toggleEdit() { this.state.mode === 'edit' ? this.cancelEdit() : this.edit(); } handleChange(attr, value) { this.setState({ modified: true, comment: { ...this.state.comment, [attr]: value } }); window.state = { modified: true, comment: { ...this.state.comment, [attr]: value } }; } async save() { const comment = pick(this.state.comment, ['id', 'markdown', 'html']); await this.props.editComment(comment); this.setState({ modified: false, mode: 'details' }); } render() { const { intl, collective, LoggedInUser, editable } = this.props; const { comment } = this.state; if (!comment) return (<div />); const editor = (get(LoggedInUser, 'collective.settings.editor') === 'markdown' || get(collective, 'settings.editor') === 'markdown') ? 'markdown' : 'html'; return ( <div className={`comment ${this.state.mode}View`}> <style jsx>{` .comment { width: 100%; margin: 0.5em 0; padding: 0.5em; transition: max-height 1s cubic-bezier(0.25, 0.46, 0.45, 0.94); overflow: hidden; position: relative; display: flex; } a { cursor: pointer; } .fromCollective { float: left; margin-right: 1rem; } .body { overflow: hidden; font-size: 1.5rem; width: 100%; } .description { text-overflow: ellipsis; white-space: nowrap; overflow: hidden; display: block; } .meta { color: #919599; font-size: 1.2rem; } .meta .metaItem { margin: 0 0.2rem; } .meta .collective { margin-right: 0.2rem; } .actions > div { display: flex; margin: 0.5rem 0; } .actions .leftColumn { width: 72px; margin-right: 1rem; float: left; } .commentActions :global(> div) { margin-right: 0.5rem; } @media(max-width: 600px) { .comment { max-height: 23rem; } } `}</style> <style jsx global>{` .comment .actions > div > div { margin-right: 0.5rem; } .comment p { margin: 0rem; } `}</style> <div className="fromCollective"> <a href={`/${comment.fromCollective.slug}`} title={comment.fromCollective.name}> <Avatar src={comment.fromCollective.image} key={comment.fromCollective.id} radius={40} /> </a> </div> <div className="body"> <div className="header"> <div className="meta"> <span className="createdAt"><FormattedDate value={comment.createdAt} day="numeric" month="numeric" /></span> |&nbsp; <span className="metaItem"><Link route={`/${comment.fromCollective.slug}`}>{comment.fromCollective.name}</Link></span> { editable && LoggedInUser && LoggedInUser.canEditComment(comment) && <span> | <a className="toggleEditComment" onClick={this.toggleEdit}>{intl.formatMessage(this.messages[`${this.state.mode === 'edit' ? 'cancelEdit' : 'edit'}`])}</a></span> } </div> <div className="description"> { this.state.mode !== 'edit' && <div dangerouslySetInnerHTML={{ __html: comment.html }} /> } { this.state.mode === 'edit' && <InputField type={editor} defaultValue={comment[editor]} onChange={(value) => this.handleChange(editor, value)} />} </div> </div> { editable && <div className="actions"> { this.state.mode === 'edit' && <div> <SmallButton className="primary save" onClick={this.save} disabled={!this.state.modified}><FormattedMessage id="comment.save" defaultMessage="save" /></SmallButton> </div> } </div> } </div> </div> ); } } const editCommentQuery = gql` mutation editComment($comment: CommentAttributesInputType!) { editComment(comment: $comment) { id html createdAt collective { id slug currency name host { id slug } stats { id balance } } fromCollective { id type name slug image } } } `; const addMutation = graphql(editCommentQuery, { props: ( { mutate }) => ({ editComment: async (comment) => { return await mutate({ variables: { comment } }) } }) }); export default withIntl(addMutation(Comment));
JavaScript
0.000285
@@ -2927,41 +2927,8 @@ is;%0A - white-space: nowrap;%0A
2c3babd4f72bb31d1d90e653e6b774dd8e50966a
Update skill model
src/models/skill.js
src/models/skill.js
import firebase from 'config/firebase'; import cuid from 'cuid'; const defaultSkill = { name: '', }; export default class Skill { constructor(skill) { this.id = cuid(); const populated = Object.assign({}, defaultSkill, skill); for (const key in populated) { if (populated.hasOwnProperty(key)) { this[key] = populated[key]; } } } set() { return firebase .database() .ref(`/skills/${this.id}`) .set(this); } remove() { return firebase .database() .ref(`/skills/${this.id}`) .remove(); } }
JavaScript
0
@@ -63,47 +63,8 @@ ';%0A%0A -const defaultSkill = %7B%0A name: '',%0A%7D;%0A%0A expo @@ -133,16 +133,124 @@ cuid();%0A + this.name = '';%0A this.user = null;%0A this.created = Date.now();%0A%0A // Prefill values from payload %0A con @@ -286,20 +286,12 @@ %7B%7D, -defaultSkill +this , sk
ead6a4bb5376efebbe5d8866df63ceab10624df8
rearrange the array
findPeak.js
findPeak.js
var array = [3, 4, 5, 6, 1, 2]; /*find the peak when given an sorted array and number of rotations *@param a Array *@param n integer */ var findPeak = function (a, n) { // debugger; if (a.length === 1 || (a.length !== 0 || n == 0) { return a[a.length - 1]; } else if (a.length > 1) { var peakLocLeftShift = a[a.length - ((n % a.length) + 1)]; var index = (n % a.length) - 1; if (index === undefined || index < 0) index = 0; var peakLocRightShift = a[index]; if (peakLocLeftShift > peakLocRightShift) { return peakLocLeftShift; } else { return peakLocRightShift; } } else { throw "Array is empty"; } }; //test cases console.log(findPeak(array, 2)); console.log(findPeak(array, 4)); console.log(findPeak([1], 4)); console.log(findPeak([1], 0)); console.log(findPeak([1, 2], 0)); console.log(findPeak([1, 1], 2)); console.log(findPeak([], 2)); /*Test Output 6 6 1 1 2 1 "Array is empty" */
JavaScript
0.999999
@@ -1,12 +1,234 @@ +/*Question : Given an array and is rotated n number of times find the number where the peak happens. %0A*The array is sorted in increasing order. %0A*Follow up question: How will you rearrange them in normal sorted order.%0A*/%0A%0A var array = @@ -944,20 +944,588 @@ %0A%7D;%0A -//test cases +%0A//rearranges the array%0Avar rearrangeArray = function (a, n) %7B%0A try %7B%0A if (a.length %3C 2) %7B%0A return a;%0A %7D%0A debugger;%0A var highest = findPeak(a, n);%0A var oIndex = a.indexOf(highest);%0A var part1 = a.slice(oIndex + 1, a.length);%0A var part2 = a.slice(0, oIndex + 1);%0A var result = part1;%0A for (var i = 0; i %3C part2.length; i++) %7B%0A result.push(part2%5Bi%5D);%0A %7D%0A return result;%0A %7D catch (e) %7B%0A console.log(e.message);%0A %7D%0A%7D;%0A//test cases%0Aconsole.log(rearrangeArray(array, 2)); %0Acon @@ -1761,16 +1761,30 @@ Output%0A +%5B1,2,3,4,5,6%5D%0A 6%0A6%0A1%0A1%0A
e4984014e15758ba3185cfdd177d6635aa37ff35
fix return value in cross auth
src/server/middleware/auth.js
src/server/middleware/auth.js
'use strict'; const error = require('../error'); const FlavorUtils = require('flavor-utils'); const authPlugins = [['google', 'oauth2'],['couchdb'], ['facebook', 'oauth2'],['github','oauth2']]; const auths = []; const url = require('url'); const superagent = require('superagent-promise')(require('superagent'), Promise); const router = require('koa-router')(); var config; exports.init = function(passport, _config) { config = _config; for (var i = 0; i < authPlugins.length; i++) { try { // check that parameter exists var conf; if(conf = configExists(authPlugins[i])) { console.log('loading auth plugin', authPlugins[i]); var auth = require('../auth/' + authPlugins[i].join('/') + '/index.js'); auth.init(passport, router, conf); auths.push(auth); } else { console.log('Auth plugin not configured', authPlugins[i]); } } catch(e) { console.log('Could not init auth middleware...', e.message); console.log(e.stack); } } passport.serializeUser(function(user, done) { done(null, user); }); passport.deserializeUser(function(obj, done) { done(null, obj); }); function configExists(conf) { if(!config.auth) return null; var last = config.auth; for(var j=0; j<conf.length; j++) { if(!last[conf[j]]) return null; last = last[conf[j]]; last.publicAddress = config.publicAddress; last.couchUrl = config.couchUrl; } return last; } router.get('/_session', function * (next){ var that = this; // Check if session exists var email = yield exports.getUserEmail(that); this.body = JSON.stringify({ ok: true, userCtx: { name: email } }); try{ var parsedPath = url.parse(config.couchUrl); parsedPath.auth = config.couchUsername + ':' + config.couchPassword; var fullUrl = url.format(parsedPath); if(!config.firstLoginClone || !email){ return yield next; } var hasViews = yield FlavorUtils.hasViews({ couchUrl: fullUrl, couchDatabase: config.couchDatabase, username: email, flavor: config.firstLoginClone.targetFlavor }); if(hasViews) { return yield next; } yield FlavorUtils.cloneFlavor({ source: { couchUrl: fullUrl, couchDatabase: config.couchDatabase, username: config.firstLoginClone.sourceUser, flavor: config.firstLoginClone.sourceFlavor }, target: { couchUrl: fullUrl, couchDatabase: config.couchDatabase, username: email, flavor: config.firstLoginClone.targetFlavor, subFolder: config.firstLoginClone.targetSubFolder } }); } catch(e) { yield next; } yield next; }); router.delete('/_session', function*(){ this.logout(); this.body = JSON.stringify({ ok: true }); }); return router; }; exports.ensureAuthenticated = function *(next) { if (this.isAuthenticated()) { yield next; return; } this.status = 401; }; function getUserEmailFromToken(ctx) { if(!config.authServers.length) return Promise.resolve('anonymous'); const token = ctx.headers['x-auth-session']; let res = { ok: true, userCtx: null }; let prom = Promise.resolve(res); for(let i=0; i<config.authServers.length; i++) { prom = prom.then(res => { if(res.userCtx !== null && res.userCtx !== 'anonymous') { return res; } return superagent .get(`${config.authServers[i].replace(/\/$/, '')}/_session`) .set('cookie', token) .end().then(res => { return JSON.parse(res.text) }); }); } return prom.then(res => res.userCtx ? res.userCtx : 'anonymous'); } exports.getUserEmail = function(ctx) { if(ctx.headers['x-auth-session']) { return getUserEmailFromToken(ctx); } if (!ctx.session.passport) return Promise.resolve('anonymous'); var user = ctx.session.passport.user; if(!user) { throw new Error('UNREACHABLE'); } var email; switch(user.provider) { case 'github': email = user.email || null; break; case 'google': if(user._json.verified_email === true) email = user._json.email; else email = null; break; case 'facebook': if(user._json.verified === true) { email = user._json.email; } else { email = null; } break; case 'local': email = user.email; break; case 'couchdb': email = user.email || null; break; default: email = null; break; } return Promise.resolve(email || 'anonymous'); };
JavaScript
0.000008
@@ -4423,16 +4423,21 @@ .userCtx +.name : 'anon
ab12b27ce2aabe84c572984d3094b4a46f01895d
fix log output
accessories/Slat.js
accessories/Slat.js
/* eslint unicorn/filename-case: "off", func-names: "off", camelcase: "off", no-unused-vars: "off" */ module.exports = function (iface) { const {mqttPub, mqttSub, mqttStatus, log, newAccessory, Service, Characteristic} = iface; /* // Required Characteristics this.addCharacteristic(Characteristic.SlatType); this.addCharacteristic(Characteristic.CurrentSlatState); // The value property of CurrentSlatState must be one of the following: Characteristic.CurrentSlatState.FIXED = 0; Characteristic.CurrentSlatState.JAMMED = 1; Characteristic.CurrentSlatState.SWINGING = 2; // Optional Characteristics this.addOptionalCharacteristic(Characteristic.Name); this.addOptionalCharacteristic(Characteristic.CurrentTiltAngle); this.addOptionalCharacteristic(Characteristic.TargetTiltAngle); this.addOptionalCharacteristic(Characteristic.SwingMode); // The value property of SwingMode must be one of the following: Characteristic.SwingMode.SWING_DISABLED = 0; Characteristic.SwingMode.SWING_ENABLED = 1; */ return function createAccessory_Slat(settings) { const slat = newAccessory(settings); slat.addService(Service.Slat, settings.name) .getCharacteristic(Characteristic.CurrentSlatState) .on('set', (value, callback) => { log.debug('< hap set', settings.name, 'CurrentSlatState', value); log.debug('> mqtt', settings.topic.setActive, value); mqttPub(settings.topic.statusCurrentSlatState, value); callback(); }); const type = settings.config.SlatType || 0; log.debug('> hap set', settings.name, 'SlatType', type); slat.getService(Service.Slat) .setCharacteristic(Characteristic.SlatType, type); if (settings.topic.statusCurrentTiltAngle) { mqttSub(settings.topic.statusCurrentTiltAngle, val => { log.debug('< mqtt', settings.topic.statusCurrentTiltAngle, val); const angle = mqttStatus[settings.topic.statusCurrentTiltAngle]; log.debug('> hap update', settings.name, 'CurrentTiltAngle', angle); slat.getService(Service.Valve) .updateCharacteristic(Characteristic.CurrentTiltAngle, angle); }); } if (settings.topic.statusTargetTiltAngle) { mqttSub(settings.topic.statusTargetTiltAngle, val => { log.debug('< mqtt', settings.topic.statusTargetTiltAngle, val); const angle = mqttStatus[settings.topic.statusTargetTiltAngle]; log.debug('> hap update', settings.name, 'TargetTiltAngle', angle); slat.getService(Service.Valve) .updateCharacteristic(Characteristic.TargetTiltAngle, angle); }); } if (settings.topic.setTargetTiltAngle) { slat.addService(Service.Slat, settings.name) .getCharacteristic(Characteristic.TargetTiltAngle) .on('set', (value, callback) => { log.debug('< hap set', settings.name, 'TargetTiltAngle', value); log.debug('> mqtt', settings.topic.setTargetTiltAngle, value); mqttPub(settings.topic.setTargetTiltAngle, value); callback(); }); } if (settings.topic.statusSwingMode) { mqttSub(settings.topic.statusSwingMode, val => { log.debug('< mqtt', settings.topic.statusSwingMode, val); const angle = mqttStatus[settings.topic.statusSwingMode]; log.debug('> hap update', settings.name, 'SwingMode', angle); slat.getService(Service.Valve) .updateCharacteristic(Characteristic.SwingMode, angle); }); } if (settings.topic.setSwingMode) { slat.addService(Service.Slat, settings.name) .getCharacteristic(Characteristic.SwingMode) .on('set', (value, callback) => { log.debug('< hap set', settings.name, 'SwingMode', value); log.debug('> mqtt', settings.topic.setSwingMode, value); mqttPub(settings.topic.setSwingMode, value); callback(); }); } }; };
JavaScript
0.000115
@@ -1467,15 +1467,28 @@ ic.s -etActiv +tatusCurrentSlatStat e, v
abafff75f5b25483a39732232f2e1973f585b993
Fix warning when isolating bootstrap
scripts/bootstrap-isolate.js
scripts/bootstrap-isolate.js
var fs = require('fs'); var postcss = require('postcss'); var prefixer = require('postcss-prefix-selector'); var css = fs.readFileSync('node_modules/bootstrap/dist/css/bootstrap.css', 'utf8').toString(); var out = postcss() .use(prefixer({ prefix: '.bsi' })) .process(css).then(function (result) { fs.writeFileSync('node_modules/bootstrap/dist/css/bootstrap.isolated.css', result.css); console.log('bootstrap.isolated.css file created in node_modules/bootstrap/dist/css directory'); })
JavaScript
0.000003
@@ -1,11 +1,13 @@ -var +const fs = re @@ -19,19 +19,21 @@ ('fs');%0A -var +const postcss @@ -55,19 +55,21 @@ tcss');%0A -var +const prefixe @@ -109,19 +109,21 @@ tor');%0A%0A -var +const css = f @@ -123,16 +123,19 @@ css = fs +%0A .readFil @@ -196,16 +196,19 @@ 'utf8') +%0A .toStrin @@ -217,11 +217,13 @@ );%0A%0A -var +const out @@ -239,17 +239,20 @@ s()%0A - .use( +%0A pref @@ -264,18 +264,16 @@ %7B%0A - - prefix: @@ -282,19 +282,21 @@ bsi' +, %0A %7D) -) %0A +)%0A .p @@ -309,24 +309,37 @@ (css -).then(function +, %7Bfrom: undefined%7D)%0A .then( (res @@ -343,22 +343,21 @@ result) -%7B%0A +=%3E %7B%0A fs.w @@ -361,32 +361,39 @@ s.writeFileSync( +%0A 'node_modules/bo @@ -433,16 +433,22 @@ ed.css', +%0A result. @@ -450,23 +450,24 @@ sult.css -); %0A +);%0A cons @@ -474,16 +474,23 @@ ole.log( +%0A 'bootstr @@ -567,16 +567,18 @@ ory' -); %0A -%7D)%0A%0A +);%0A %7D); %0A
cd7142888fbcebfff2fc3c27e4739599ad526b3f
Update bin tests
test/bin/keyword-popularity.test.js
test/bin/keyword-popularity.test.js
const {resolve} = require('path'); const {execFile} = require('child_process'); const tape = require('tape-catch'); const curry = require('1-liners/curry'); const plus = require('1-liners/plus'); const spawn = require('tape-spawn'); const title = curry(plus)('The CLI tool: '); const keywordPopularity = resolve(__dirname, '../../module/bin/keyword-popularity.js'); const $keywordPopularity = curry(execFile)(keywordPopularity); tape(title('Prints usage'), (is) => { is.plan(8); $keywordPopularity([], (error, _, stderr) => { is.equal(error && error.code, 1, '`keyword-popularity` fails…' ); is.ok( /^usage:/i.test(stderr), '…and prints usage to stderr' ); }); $keywordPopularity(['--invalid', '--options'], (error, _, stderr) => { is.equal(error && error.code, 1, '`keyword-popularity --invalid --options` fails…' ); is.ok( /^usage:/i.test(stderr), '…and prints usage to stderr' ); }); $keywordPopularity(['-h'], (error, stdout) => { is.equal(error, null, '`keyword-popularity -h` succeeds…' ); is.ok( /^usage:/i.test(stdout), '…and prints usage' ); }); $keywordPopularity(['--help'], (error, stdout) => { is.equal(error, null, '`keyword-popularity --help` succeeds…' ); is.ok( /SYNOPSIS/.test(stdout), '…and prints manpage-like help' ); }); }); const cwd = resolve(__dirname, '../mock-cwd'); tape(title('Does what it says'), (is) => { const run = spawn(is, `"${keywordPopularity}"`, {cwd}); run.succeeds( 'succeeds' ); run.timeout(500); run.end(); });
JavaScript
0
@@ -314,24 +314,26 @@ e(__dirname, +%0A '../../modu @@ -361,16 +361,17 @@ rity.js' +%0A );%0Aconst @@ -1414,56 +1414,8 @@ );%0A%0A -const cwd = resolve(__dirname, '../mock-cwd');%0A%0A tape @@ -1461,19 +1461,207 @@ const -run +keywords = %5B%0A 'cli',%0A 'tool',%0A %60very-very-unlikely-keyword-$%7BDate.now()%7D%60,%0A %5D;%0A const tabLength = keywords%5B2%5D.length + 2;%0A const veryUnlikelyKeyword = keywords%5B2%5D;%0A const program = spawn @@ -1666,17 +1666,17 @@ wn(is, %60 -%22 +' $%7Bkeywor @@ -1691,63 +1691,717 @@ ity%7D -%22%60, %7Bcwd%7D);%0A%0A run.succeeds(%0A 'succeeds'%0A );%0A%0A run +' $%7Bkeywords.join(' ')%7D%60);%0A%0A const wordWithTab = (word) =%3E %60$%7Bword%7D %7B$%7BtabLength - word.length%7D%7D%60;%0A%0A program.succeeds(%0A 'succeeds'%0A );%0A%0A program.stdout.match(%0A new RegExp(%0A '%5E' +%0A wordWithTab('KEYWORD') +%0A 'POPULARITY' +%0A '%5C%5Cn'%0A ),%0A 'outputs a properly-formatted header%E2%80%A6'%0A );%0A%0A program.stdout.match(%0A new RegExp(%0A '%5E.*%5C%5Cn' +%0A keywords.map((keyword) =%3E (%0A wordWithTab(keyword) +%0A '%5C%5Cd+%5C%5Cn'%0A )) +%0A '$'%0A ),%0A '%E2%80%A6followed by a table of keywords and numbers in the specified order'%0A );%0A%0A program.stdout.match(%0A new RegExp(%60$%7BwordWithTab(veryUnlikelyKeyword)%7D0%5C%5Cn%60),%0A 'prints out %600%60 for a very unlikely keyword'%0A );%0A%0A program .tim @@ -2417,11 +2417,15 @@ ;%0A -run +program .end
fe348832bed14d22d6796a2732c7194725b12afa
convert `decimal128` tests to mocha style
test/functional/decimal128_tests.js
test/functional/decimal128_tests.js
/** * @ignore */ exports['should correctly insert decimal128 value'] = { // Add a tag that our runner can trigger on // in this case we are setting that node needs to be higher than 0.10.X to run metadata: { requires: { mongodb: '>=3.3.6', topology: ['single'] } }, // The actual test we wish to run test: function(configuration, test) { var Decimal128 = configuration.require.Decimal128; var client = configuration.newDbInstance(configuration.writeConcernMax(), { poolSize: 1 }); client.connect(function(err, client) { var db = client.db(configuration.database); var object = { id: 1, value: Decimal128.fromString('1') }; db.collection('decimal128').insertOne(object, function(err, r) { test.equal(null, err); db.collection('decimal128').findOne({ id: 1 }, function(err, doc) { test.equal(null, err); test.ok(doc.value instanceof Decimal128); test.equal('1', doc.value.toString()); client.close(); test.done(); }); }); }); } };
JavaScript
0.999612
@@ -1,8 +1,232 @@ +'use strict';%0Avar test = require('./shared').assert;%0Avar setupDatabase = require('./shared').setupDatabase;%0A%0Adescribe('Decimal128', function() %7B%0A before(function() %7B%0A return setupDatabase(this.configuration);%0A %7D);%0A%0A /**%0A + * @ @@ -236,20 +236,19 @@ ore%0A + */%0A -exports%5B + it( 'sho @@ -289,14 +289,14 @@ lue' -%5D = +, %7B%0A + // @@ -337,16 +337,18 @@ gger on%0A + // in @@ -420,16 +420,18 @@ to run%0A + metada @@ -432,24 +432,26 @@ metadata: %7B%0A + requires @@ -460,16 +460,18 @@ %7B%0A + mongodb: @@ -482,16 +482,18 @@ 3.3.6',%0A + to @@ -515,20 +515,26 @@ e'%5D%0A + %7D%0A + %7D,%0A%0A + // @@ -565,16 +565,18 @@ to run%0A + test: @@ -588,31 +588,64 @@ ion( -configuration, test) %7B%0A +done) %7B%0A var configuration = this.configuration;%0A @@ -696,24 +696,26 @@ al128;%0A%0A + var client = @@ -736,18 +736,14 @@ .new -DbInstance +Client (con @@ -786,24 +786,26 @@ Size: 1 %7D);%0A + client.c @@ -837,24 +837,26 @@ nt) %7B%0A + var db = cli @@ -881,18 +881,14 @@ on.d -atabase +b );%0A + @@ -916,15 +916,19 @@ + + id: 1,%0A + @@ -971,16 +971,18 @@ )%0A + %7D;%0A%0A @@ -979,24 +979,26 @@ %7D;%0A%0A + + db.collectio @@ -1047,15 +1047,14 @@ (err -, r ) %7B%0A + @@ -1081,32 +1081,34 @@ err);%0A%0A + db.collection('d @@ -1143,14 +1143,18 @@ + id: 1%0A + @@ -1183,32 +1183,34 @@ oc) %7B%0A + test.equal(null, @@ -1216,16 +1216,18 @@ , err);%0A + @@ -1270,16 +1270,18 @@ al128);%0A + @@ -1328,24 +1328,26 @@ %0A%0A + client.close @@ -1364,18 +1364,29 @@ -test.done( + done();%0A %7D );%0A @@ -1415,14 +1415,15 @@ %7D -); %0A %7D +); %0A%7D +) ;%0A
a186ff0f07835c983b24a0af97bbd119c8b8ec10
change selendroid proxy test to use a method that actually errors
test/functional/selendroid/basic.js
test/functional/selendroid/basic.js
"use strict"; process.env.DEVICE = process.env.DEVICE || "selendroid"; var setup = require("../common/setup-base") , sessionUtils = require('../../helpers/session-utils') , path = require('path') , Q = require("q") , _ = require('underscore'); var desired = { app: path.resolve(__dirname, "../../../sample-code/apps/ApiDemos/bin/ApiDemos-debug.apk"), 'app-package': 'com.example.android.apis', 'app-activity': '.ApiDemos' }; // , appAct2 = "ApiDemos" // , appActFull = "com.example.android.apis.ApiDemos" describe('selendroid - basic -', function () { describe('api', function () { var driver; setup(this, desired).then(function (d) { driver = d; }); // todo: issue with find it('should find and click an element @skip-all-selendroid', function (done) { // selendroid appears to have some issues with implicit waits // hence the timeouts driver .waitForElementByName('App', 10000).click() .sleep(1000) .elementByLinkText("Action Bar").should.eventually.exist .nodeify(done); }); it('should be able to get logcat log type', function (done) { driver.logTypes().should.eventually.include('logcat') .nodeify(done); }); it('should be able to get logcat logs', function (done) { driver.log('logcat').then(function (logs) { logs.length.should.be.above(0); logs[0].message.should.not.include("\n"); logs[0].level.should.equal("ALL"); logs[0].timestamp.should.exist; }).nodeify(done); }); it('should be able to proxy errors', function (done) { driver .frame(null).should.be.rejected .nodeify(done); }); it('should be able to set location', function (done) { var locOpts = {latitude: "27.17", longitude: "78.04"}; driver .execute("mobile: setLocation", [locOpts]) .nodeify(done); }); it('should error out nicely with incompatible commands', function (done) { driver .execute("mobile: flick", [{}]) .catch(function (err) { err.cause.value.origValue.should.contain('mobile:'); throw err; }).should.be.rejectedWith(/status: 9/) .nodeify(done); }); }); describe('uninstall app', function () { var driver; setup(this, desired).then(function (d) { driver = d; }); it('should be able to uninstall the app', function (done) { driver .execute("mobile: removeApp", [{bundleId: desired['app-package']}]) .nodeify(done); }); }); describe('background app', function () { var driver; setup(this, desired).then(function (d) { driver = d; }); it("should background the app", function (done) { var before = new Date().getTime() / 1000; driver .execute("mobile: background", [{seconds: 3}]) .then(function () { ((new Date().getTime() / 1000) - before).should.be.above(2); // this should not be tested // ((new Date().getTime() / 1000) - before).should.be.below(5); }) .execute("mobile: currentActivity") .should.eventually.include("ApiDemos") .nodeify(done); }); }); describe('command timeouts', function () { var driver; setup(this, _.defaults({newCommandTimeout: 3}, desired)) .then(function (d) { driver = d; }); it('should die with short timeout', function (done) { driver .sleep(5000) .elementByName('Animation') .should.be.rejectedWith(/(status: (13|6))|(Not JSON response)/) .nodeify(done); }); }); // todo: issue with find describe('command timeouts @skip-all-selendroid', function () { var driver; setup(this, _.defaults({newCommandTimeout: 7}, desired)) .then(function (d) { driver = d; }); it('should not die if commands come in', function (done) { var start = Date.now(); var find = function () { if ((Date.now() - start) < 5000) { return driver .elementByName('Animation').should.eventually.exist .sleep(500) .then(find); } else return new Q(); }; find().then(function () { return driver .sleep(10000) .elementByName('Animation').should.be.rejected; }).nodeify(done); }); }); describe('app activities with no dot', function () { var session; after(function () { session.tearDown(); }); it('should not launch app', function (done) { session = sessionUtils.initSession(_.defaults({'app-activity': 'ApiDemos'}, desired), {'no-retry': true}); session.setUp() .should.be.rejected .nodeify(done); }); }); describe('fully qualified app activities', function () { var session; after(function () { session.tearDown(); }); it('should still launch app', function (done) { session = sessionUtils.initSession(_.defaults({'app-activity': 'com.example.android.apis.ApiDemos'}, desired)); session.setUp() .nodeify(done); }); }); });
JavaScript
0
@@ -1629,18 +1629,29 @@ . -frame(null +elementByCss(%22foobar%22 ).sh
13d8d99699713782417d5ebd3a0bad5520445773
use docker-modem followProgress to handle build stream
chimera.js
chimera.js
#!/usr/bin/env node var fs = require('fs'); var os = require('os'); var path = require('path'); var crypto = require('crypto'); var _ = require('underscore'); var Handlebars = require('handlebars'); var async = require('async'); var tar = require('tar-fs'); var Docker = require('dockerode'); var rimraf = require('rimraf'); var yaml = require('js-yaml'); var minimist = require('minimist'); var colors = require('colors'); var argv = (function(argv) { return { help: argv.h || argv.help, version: argv.v || argv.version, config: path.resolve(process.cwd(), argv.f || argv.file || '.chimera.yml'), project: path.resolve(process.cwd(), argv.p || argv.project || './'), target: argv.t || argv.target || process.env.CHIMERA_TARGET, verbose: argv.V || argv.verbose, _: argv._ }; }(minimist(process.argv.slice(2)))); var verbose = argv.verbose ? function(arg) { console.log(arg); return arg;} : function(arg) { return arg; }; var docker; Handlebars.registerHelper('render', function(template, data) { return new Handlebars.SafeString(Handlebars.compile(template)(data)); }); var dockerfile = Handlebars.compile([ 'FROM {{baseImage}}:{{tag}}', 'COPY project/ /project', 'WORKDIR /project', '', 'ENV CHIMERA_TARGET={{name}}:{{tag}}', 'ENV CHIMERA_TARGET_NAME={{name}}', 'ENV CHIMERA_TARGET_TAG={{tag}}', '{{#each env}}', 'ENV {{render this ../this}}', '{{/each}}', '', '{{#each install}}', 'RUN {{render this ../this}}', '{{/each}}', 'CMD {{script}}' ].join('\n')); if (argv.help) { console.log([ '', 'Usage: chimera [options]', ' chimera generate <ci-service>', '', 'Easy multi-container testing with Docker', '', 'Options:', '', ' -h, --help output usage information', ' -v, --version output version', ' -c, --config <path> set configuration file', ' -p, --project <path> set project directory', ' -t, --target <image:tag> set target', ' -V, --verbose verbose mode' ].join('\n')); process.exit(0); } if(argv.version) { console.log('chimera version ' + require('./package.json').version); process.exit(0); } fs.readFile(argv.config, 'utf8', function(err, raw) { fail(err); var config = yaml.safeLoad(raw); docker = new Docker(config.docker); targets(config, function(err, targets) { fail(err); switch (argv._[0]) { case 'generate': generate(targets); break; case 'run': case undefined: run(targets); break; default: console.error('unknown command, see --help'); }; }); }); function generate(targets) { switch (argv._[1]) { case 'travis': console.log(Handlebars.compile([ 'language: node_js', 'sudo: required', 'services:', ' - docker', 'install:', ' - npm install -g chimera-cli', 'script:', ' - chimera', 'env:', ' matrix:', '{{#each this}}', ' - CHIMERA_TARGET={{name}}:{{tag}}', '{{/each}}' ].join('\n'))(targets)); break; default: console.error('unknown ci service, example: chimera generate travis'); }; }; function run(targets) { async.eachSeries(targets, function(target, cb) { console.log(('executing target ' + target.image).green); async.applyEachSeries([bundle, build, test, clean], target, cb); }, fail); }; function targets(config, cb) { cb(null, _.map(config.targets, function(target, name) { return target.tags.map(function(tag) { var id = crypto.randomBytes(5).toString('hex'); return { name: name, tag: tag, id: id, dir: path.join(os.tmpdir(), id), tar: path.join(os.tmpdir(), id + '.tar'), baseImage: target.image || name, image: name + '-' + tag + '-' + id, install: (target.install || []).concat(config.install || []), env: (target.env || []).concat(config.env || []), script: config.script.join(' && ') // TODO is this a good idea? }; }); }).reduce(function(a, b) { return a.concat(b); }).filter(function(target) { return !argv.target || target.name.indexOf(argv.target) === 0 || (target.name + ':' + target.tag).indexOf(argv.target) === 0; })); } function bundle(target, cb) { async.series([ fs.mkdir.bind(fs, target.dir), fs.writeFile.bind(fs, path.join(target.dir, 'Dockerfile'), verbose(dockerfile(target))), fs.symlink.bind(fs, argv.project, path.join(target.dir, 'project')), function(cb) { tar.pack(target.dir, {dereference: true}) .pipe(fs.createWriteStream(target.tar)) .on('error', cb) .on('finish', cb); } ], cb); } function build(target, cb) { docker.buildImage(target.tar, {t: target.image}, function(err, res) { if(err) { return cb(err); } res.on('data', function(data) { var msg = JSON.parse(data); if(msg.error) { console.error(msg.error); cb = cb.bind(null, new Error('failed to build image ' + target.image)); } else if(msg.stream || msg.status) { verbose(msg.stream || msg.status); } }); res.on('end', cb); }); } function test(target, cb) { docker.run(target.image, [], process.stdout, function(err, data, container) { if(err) { return cb(err); } if(data.StatusCode != 0) { return cb(new Error('tests failed on ' + target.image)); } target.container = container.id; cb(); }); } function clean(target, cb) { var container = docker.getContainer(target.container); var image = docker.getImage(target.image); async.series([ rimraf.bind(rimraf, target.dir), rimraf.bind(rimraf, target.tar), container.remove.bind(container), image.remove.bind(image) ], cb); } function fail(err) { if(err) { console.error(err.message.red); process.exit(1); } }
JavaScript
0
@@ -3255,18 +3255,16 @@ );%0A %7D;%0A -%0A%0A %7D;%0A%0Afunc @@ -4899,19 +4899,22 @@ on(err, -res +stream ) %7B%0A @@ -4960,334 +4960,55 @@ -res.on('data', function(data) %7B%0A var msg = JSON.parse(data);%0A%0A if(msg.error) %7B%0A console.error(msg.error);%0A cb = cb.bind(null, new Error('failed to build image ' + target.image));%0A %7D else if(msg.stream %7C%7C msg.status) %7B%0A verbose(msg.stream %7C%7C msg.status);%0A %7D%0A %7D);%0A res.on('end', cb +docker.modem.followProgress(stream, cb, verbose );%0A
334387c49e16b2570f1336f1ed8354da06aceda1
fix fill handle test for FF
test/jasmine/spec/FillHandleSpec.js
test/jasmine/spec/FillHandleSpec.js
describe('FillHandle', function () { var id = 'testContainer'; beforeEach(function () { this.$container = $('<div id="' + id + '"></div>').appendTo('body'); }); afterEach(function () { if (this.$container) { this.$container.remove(); } }); it('should appear when fillHandle equals true', function () { handsontable({ fillHandle: true }); selectCell(2, 2); waitsFor(nextFrame, 'next frame', 60); runs(function () { expect(isFillHandleVisible()).toBe(true); }); }); it('should not appear when fillHandle equals false', function () { handsontable({ fillHandle: false }); selectCell(2, 2); waitsFor(nextFrame, 'next frame', 60); runs(function () { expect(isFillHandleVisible()).toBe(false); }); }); it('should disappear when beginediting is triggered', function () { handsontable({ fillHandle: true }); selectCell(2, 2); waitsFor(nextFrame, 'next frame', 60); runs(function () { keyDown('enter'); }); waitsFor(nextFrame, 'next frame', 60); runs(function () { expect(isFillHandleVisible()).toBe(false); }); }); it('should appear when finishediting is triggered', function () { handsontable({ fillHandle: true }); selectCell(2, 2); waitsFor(nextFrame, 'next frame', 60); runs(function () { keyDown('enter'); keyDown('enter'); }); waitsFor(nextFrame, 'next frame', 60); runs(function () { expect(isFillHandleVisible()).toBe(true); }); }); it('should not appear when fillHandle equals false and finishediting is triggered', function () { handsontable({ fillHandle: false }); selectCell(2, 2); waitsFor(nextFrame, 'next frame', 60); runs(function () { keyDown('enter'); keyDown('enter'); }); waitsFor(nextFrame, 'next frame', 60); runs(function () { expect(isFillHandleVisible()).toBe(false); }); }); });
JavaScript
0
@@ -370,32 +370,102 @@ e: true%0A %7D);%0A +%0A waitsFor(nextFrame, 'next frame', 60);%0A%0A runs(function () %7B%0A selectCell(2 @@ -461,32 +461,40 @@ electCell(2, 2); +%0A %7D); %0A%0A waitsFor(n
80022729ca681a098697544c411a33c0b85b561f
exclude experiments which haven't launched from badging icon (#3619)
addon/background.js
addon/background.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* global browser */ function log(...args) { // console.log(...["[TESTPILOT v2] (background)"].concat(args)); // eslint-disable-lint no-console } const storage = browser.storage.local; const RESOURCE_UPDATE_INTERVAL = 4 * 60 * 60 * 1000; // 4 hours const ONE_DAY = 60 * 60 * 1000 * 24; const TWO_WEEKS = 2 * 7 * ONE_DAY; /* browser action constants */ const BROWSER_ACTION_LINK_BASE = [ "/experiments", "?utm_source=testpilot-addon", "&utm_medium=firefox-browser", "&utm_campaign=testpilot-doorhanger" ].join(""); const BROWSER_ACTION_LINK_NOT_BADGED = BROWSER_ACTION_LINK_BASE + "&utm_content=not+badged"; const BROWSER_ACTION_LINK_BADGED = BROWSER_ACTION_LINK_BASE + "&utm_content=badged"; let BROWSER_ACTION_LINK = BROWSER_ACTION_LINK_NOT_BADGED; const resources = { experiments: [], news_updates: [] }; let currentEnvironment = { name: "production", baseUrl: "https://testpilot.firefox.com" }; function uuidv4() { return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => ( c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4))) ).toString(16) ); } function getInstalledTxpAddons() { return browser.management.getAll().then((infoArray) => { const installed = infoArray.map((exp) => exp.id); const txpAddons = resources.experiments.map((exp) => exp.id); return installed.filter(function(n) { return txpAddons.indexOf(n) !== -1; }); }); } async function setup() { setupEnvironment(); setupBrowserAction(); await fetchResources(); setDailyPing(); } async function sendPingOnAlarm(alarmInfo) { if (alarmInfo.name === "daily-ping") { const { lastPing } = await storage.get({"lastPing": Date.now() - ONE_DAY}); if (((new Date) - lastPing) > ONE_DAY) { const installedTxpAddons = await getInstalledTxpAddons(); let { clientUUID } = await storage.get("clientUUID"); if (!clientUUID) { await storage.set({ clientUUID: clientUUID = uuidv4() }); } submitPing(alarmInfo.name, "installed-addons", installedTxpAddons, clientUUID); await storage.set({lastPing: Date.now()}); } } } function setDailyPing() { browser.alarms.create("daily-ping", { delayInMinutes: 1, periodInMinutes: 60 // check hourly }); browser.alarms.onAlarm.addListener(sendPingOnAlarm); } function setupBrowserAction() { log("setupBrowserAction"); browser.browserAction.setBadgeBackgroundColor({ color: "#0996f8" }); browser.browserAction.onClicked.addListener(() => { // reset badge immediately browser.browserAction.setBadgeText({ text: "" }); storage.set({ clicked: Date.now() }); browser.tabs.create({ url: `${currentEnvironment.baseUrl}${BROWSER_ACTION_LINK}` }); }); } function setupEnvironment() { log("setupEnvironment"); setInterval(fetchResources, RESOURCE_UPDATE_INTERVAL); browser.storage.onChanged.addListener((changes) => { Object.keys(changes).forEach((k) => { if (k === "environment") { currentEnvironment = changes[k].newValue; fetchResources(); } }); }); } function fetchResources() { log("fetchResources"); return Promise.all( Object.keys(resources).map(path => fetch(`${currentEnvironment.baseUrl}/api/${path}.json`) .then(res => res.json()) .then((data) => data.results ? data.results : data) .then((data) => [path, data]) .catch(err => { log("fetchResources error", path, err); return [path, null]; })) ).then(results => { log("fetchResources results", results); results.forEach(([path, data]) => (resources[path] = data)); updateBadgeTextOnNew(resources.experiments, resources.news_updates); log("fetchResources results parsed", resources); }); } async function updateBadgeTextOnNew(experiments, news_updates) { let { clicked } = await storage.get("clicked"); if (!clicked) { // Set initial button click timestamp if not found clicked = Date.now(); await storage.set({ clicked }); } const newExperiments = (experiments || []).filter(experiment => { const dt = new Date(experiment.modified || experiment.created).getTime(); return dt >= clicked; }); // check for port number on local, we need to strip it off // to properly fetch cookies. const baseUrl = currentEnvironment.baseUrl; const portIndex = baseUrl.indexOf(":8000"); const cookieUrl = (portIndex > -1) ? baseUrl.substring(0, portIndex) : baseUrl; let lastViewed = 0; const cookie = await browser.cookies.get({ url: cookieUrl, name: "updates-last-viewed-date" }); if (cookie) lastViewed = cookie.value; /* only show badge for news update if: * - has the "major" key * - update has been published in the past two weeks * - update has not been "seen" by the frontend (lastViewed) * - update has not been "seen" by the addon (clicked) */ const twoWeeksAgo = Date.now() - TWO_WEEKS; const newsUpdates = (news_updates || []) .filter(u => u.major) .filter(u => new Date(u.published).getTime() >= twoWeeksAgo) .filter(u => new Date(u.published).getTime() >= lastViewed) .filter(u => new Date(u.published).getTime() >= clicked); BROWSER_ACTION_LINK = (newExperiments.length || newsUpdates.length) > 0 ? BROWSER_ACTION_LINK_BADGED : BROWSER_ACTION_LINK_NOT_BADGED; browser.browserAction.setBadgeText({ text: (newExperiments.length || newsUpdates.length) > 0 ? "!" : "" }); } function submitPing(object, event, addons, clientUUID) { return fetch("https://ssl.google-analytics.com/collect", { method: "POST", body: new URLSearchParams({ v: 1, t: "event", ec: "add-on Interactions", ea: object, el: event, tid: "UA-49796218-47", cid: clientUUID, dimension14: addons }) }); } // Let's Go! setup();
JavaScript
0
@@ -4453,25 +4453,153 @@ eriment =%3E %7B -%0D +%0A // don't include experiments which haven't launched yet%0A if (new Date() %3C new Date(experiment.launch_date)) return false; %0A const d
ab0a2851e6fe4437e95e0ecad245042013d60282
Add example to library
nested-set-model.js
nested-set-model.js
// nested set model (l;r) parent search var NestedSetModel = function(model) { this.model = []; for(var entry in model) { if (!model.hasOwnProperty(entry)) { continue; } var node = new NestedSetModelNode(model[entry], model); this.model.push(node); } return this; } NestedSetModel.prototype.compareNodes = function(a, b, strict) { var strict = strict || false; if (a === b) { return true; } var keys = [ Object.keys(a), Object.keys(b) ]; if (strict && keys[0].length !== keys[1].length) { return false; } for (var i = 0; i <= keys[1].length; i++) { var prop = keys[1][i]; if (a[prop] !== b[prop]) { return false; } } if (!strict) { return true; } for (var prop in keys[0]) { if (b[prop] !== undefined && a[prop] !== b[prop]) { return false; } if (typeof a[prop] === 'object' && this.compareNodes(a[prop], b[prop], true) === false) { return false } } return true; } NestedSetModel.prototype.find = function(partial, strict) { for (var key in this.model) { if (!this.model.hasOwnProperty(key)) { continue; } else if (this.compareNodes(this.model[key], partial, strict)) { return this.model[key]; } } } var NestedSetModelNode = function(node, model) { this.model = model; var self = this; Object.keys(node).forEach(function(prop) { self[prop] = node[prop]; }); } NestedSetModelNode.prototype.parents = function() { var parents = []; var self = this; this.model.map(function(node) { if (self.left > node.left && self.right < node.right) { parents.push(node); } }); return parents; } NestedSetModelNode.prototype.children = function() { var children = []; var self = this; this.model.map(function(node) { if (self.left < node.left && self.right > node.right) { children.push(node); } }); return children; } NestedSetModelNode.prototype.isLeaf = function() { return this.right - this.left === 1; } NestedSetModelNode.prototype.isParent = function() { return !this.isLeaf(); } NestedSetModelNode.prototype.isChild = function() { return this.left > 0 && this.right < (this.model.length * 2); } var set = [ { id: 1, title: 'root', left: 1, right: 6 }, { id: 2, title: 'middle', left: 2, right: 5, }, { id: 3, title: 'last', left: 3, right: 4 } ]; var model = new NestedSetModel(set); if (model.find({ title: 'middle'}).isLeaf() === false) { console.info('SUCCESS: {title: "middle"} is not a leaf node'); } else { console.error('FAIL: {title: "middle"} is a leaf node, but shouldn\'t be'); } console.log('It\'s parents:', model.find({title: 'middle'}).parents()); console.log('It\'s childrne:', model.find({title: 'middle'}).children());
JavaScript
0
@@ -2116,24 +2116,116 @@ th * 2);%0A%7D%0A%0A +// An example input set%0A/*%0A%0A%09%09%09 root%0A%09%09%09/ %5C%0A%09 middle parent%0A%09 /%0A%09 last%0A%0A */%0A%0A var set = %5B%0A @@ -2277,9 +2277,9 @@ ht: -6 +8 %0A%09%7D, @@ -2346,17 +2346,17 @@ %7B%0A%09%09id: -3 +4 ,%0A%09%09titl @@ -2377,16 +2377,16 @@ eft: 3,%0A - %09%09right: @@ -2388,16 +2388,73 @@ ight: 4%0A +%09%7D,%0A%09%7B%0A%09%09id: 3,%0A%09%09title: 'parent',%0A%09%09left: 6,%0A%09%09right: 7%0A %09%7D%0A%5D;%0A%0Av
a460e04d3c983c595b972b6e30296916e1e6e69f
Fix typos
test/options/vendor-prefix-align.js
test/options/vendor-prefix-align.js
describe('options/vendor-prefix-align', function() { beforeEach(function() { this.filename = __filename; this.comb.configure({ 'vendor-prefix-align': true }); }); it('Should correctly work when there is comment before property name', function() { this.shouldBeEqual('with-comment-property.css', 'with-comment-property.expected.css'); }); it('Should correctly work when there is comment before property name', function() { this.shouldBeEqual('multiline-comments.css', 'multiline-comments.expected.css'); }); it('Should correctly align prefixes in properties', function() { this.shouldBeEqual('property-align.css', 'property-align.expected.css'); }); it('Should correctly align prefixes in values', function() { this.shouldBeEqual('value-align.css', 'value-align.expected.css'); }); it('Should not touch already align prefixes', function() { this.shouldBeEqual('already-aligned.css', 'already-aligned.expected.css'); }); it('Should correct align prefixes in preoperties and values at the same time', function() { this.shouldBeEqual('both.css', 'both.expected.css'); }); it('Should correctly work when value and property name are the same', function() { this.shouldBeEqual('same-name.css', 'same-name.expected.css'); }); it('Should correctly work when there is no whitespace after colon', function() { this.shouldBeEqual('without-space.css', 'without-space.expected.css'); }); it('Should correctly work when there is comment after colon', function() { this.shouldBeEqual('with-comment.css', 'with-comment.expected.css'); }); it('Should not do anyting with oneliners', function() { this.shouldBeEqual('one-line.css', 'one-line.expected.css'); }); it('Should not do anyting with oneliners. Test 2', function() { this.shouldBeEqual('one-line-2.css', 'one-line-2.expected.css'); }); it('Should always correctly align prefixes', function() { this.shouldBeEqual('complex.css', 'complex.expected.css'); }); it('Shouldn not detect anything if there are no prefixed groups', function() { this.shouldDetect( ['vendor-prefix-align'], 'a{ color: red }a{ -webkit-transform: translateZ(0) }', {} ); }); it('Shouldn detect vendor-prefix-align as false in properties', function() { this.shouldDetect( ['vendor-prefix-align'], this.readFile('property-align.css'), { 'vendor-prefix-align': false } ); }); it('Shouldn detect vendor-prefix-align as true in properties', function() { this.shouldDetect( ['vendor-prefix-align'], this.readFile('property-align.expected.css'), { 'vendor-prefix-align': true } ); }); it('Shouldn detect vendor-prefix-align as false in values', function() { this.shouldDetect( ['vendor-prefix-align'], this.readFile('value-align.css'), { 'vendor-prefix-align': false } ); }); it('Shouldn detect vendor-prefix-align as true in values', function() { this.shouldDetect( ['vendor-prefix-align'], this.readFile('value-align.expected.css'), { 'vendor-prefix-align': true } ); }); it('Shouldn detect vendor-prefix-align as true, test 1', function() { this.shouldDetect( ['vendor-prefix-align'], this.readFile('already-aligned.css'), { 'vendor-prefix-align': true } ); }); it('Shouldn detect vendor-prefix-align as true, test 2', function() { this.shouldDetect( ['vendor-prefix-align'], this.readFile('complex.expected.css'), { 'vendor-prefix-align': true } ); }); it('Shouldn detect vendor-prefix-align as false', function() { this.shouldDetect( ['vendor-prefix-align'], this.readFile('complex.css'), { 'vendor-prefix-align': false } ); }); it('Should not detect anything in simple case', function() { this.shouldDetect( ['vendor-prefix-align'], 'a{border:0;}', {} ); }); });
JavaScript
0.999999
@@ -1044,16 +1044,18 @@ correct +ly align p @@ -1067,17 +1067,16 @@ es in pr -e operties @@ -1247,16 +1247,17 @@ rty name +s are the @@ -1713,32 +1713,33 @@ ould not do anyt +h ing with oneline @@ -1860,16 +1860,17 @@ do anyt +h ing with
55bbab128e02e579e4c01a26da44d72db12f1c2d
Update strings.js
nls/root/strings.js
nls/root/strings.js
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ // English - root strings /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define */ define({ "SORT_LINES" : "Sort Lines", "REVERSE_LINES" : "Reverse Lines", "SORT_LINES_BY_LENGTH" : "Sort Lines by length", "SHUFFLE_LINES" : "Shuffle Lines", "REMOVE_DUPLICATE_LINES" : "Remove Duplicate Lines" });
JavaScript
0
@@ -1383,24 +1383,89 @@ rse Lines%22,%0A +%09%22REVERSE_LINES_SELECTION%22 : %22Reverse Lines Selection%22,%0A %22SORT_LI
e1e99cc04b3fbc81c4970529664cf2149bc8dcc7
fix console log
src/store/pagination/store.js
src/store/pagination/store.js
export const state = { loadFunction: null, api: { count: null, current: null, direction: null, directionDefault: null, limit: null, nextPage: null, page: 1, pageCount: null, perPage: 20, prevPage: null, sort: null, sortDefault: null } } export const mutations = { SET_FUNCTION (state, fn) { state.loadFunction = fn }, CHANGE_PAGE (state, page) { state.api.page = page }, SET_API (state, api) { state.api = api console.log(state.api.page) } } export default { state, mutations }
JavaScript
0.000002
@@ -486,40 +486,8 @@ api%0A - console.log(state.api.page)%0A %7D%0A
49ab7f6ceb0e519345ff005feffc6e835f11f788
disable unit tests for d3DataBuilder until ready
src/test/d3DataBuilderTest.js
src/test/d3DataBuilderTest.js
'use strict'; const expect = require('chai').expect; const assign = require('lodash.assign'); const dummyTree = require('./fixtures/dummyTree'); const d3DataBuilder = require('../d3DataBuilder'); const astGenerator = require('../astGenerator') describe('d3DataBuilder Unit Tests', function() { const app = __dirname + '/fixtures/test_components/app.jsx'; const BIG = __dirname + '/fixtures/test_components/BIG.jsx'; const Biggie = __dirname + '/fixtures/test_components/Biggie.jsx'; const BigPoppa = __dirname + '/fixtures/test_components/BigPoppa.jsx'; const Notorious = __dirname + '/fixtures/test_components/Notorious.jsx'; let parseComponents = [app, BIG, Biggie, BigPoppa, Notorious]; let astObj = {}, d3Obj; before(function() { parseComponents = parseComponents.map(ele => {astGenerator(ele)}) astObj = assign.apply(null, parseComponents); }) beforeEach(function() { d3Obj = d3DataBuilder(astObj); }) it('should be a function', function() { expect(d3DataBuilder).to.be.a.function; }) it('should return an object', function() { expect(d3Ojb).to.be.an('object'); }) it('should start with the correct component', function() { expect(d3Ojb.name).to.equal('BigPoppa'); }) it('should have component nesting', function() { expect(d3Obj.children.length).to.equal(2); expect(d3Obj.children[0].children.length).to.equal(1); }) it('should account for props', function() { expect(d3Obj.children[0].props.length).to.equal(3); expect(d3Obj.children[0].children[0].props.length).to.equal(2); }) it('should account for state', function() { expect(d3Obj.state.foo && d3Obj.state.bar).to.be.true; }) })
JavaScript
0
@@ -243,16 +243,17 @@ )%0A%0A%0A%0A%0A%0A%0A +x describe
51721a201ae593695e8f4b7511ea2e0633623e49
make loadContent private
src/pat/collapsible.js
src/pat/collapsible.js
/** * Patterns collapsible - Collapsible content * * Copyright 2012-2013 Florian Friesdorf * Copyright 2012-2013 Simplon B.V. - Wichert Akkerman * Copyright 2012 Markus Maier * Copyright 2013 Peter Lamut * Copyright 2012 Jonas Hoersch */ define([ "jquery", "./inject", "../core/logger", "../core/parser", "../core/store", "../registry" ], function($, inject, logger, Parser, store, registry) { var log = logger.getLogger("pat.collapsible"), parser = new Parser("collapsible"); parser.add_argument("load-content"); parser.add_argument("store", "none", ["none", "session", "local"]); parser.add_argument("transition", "slide", ["none", "css", "fade", "slide"]); parser.add_argument("effect-duration", "fast"); parser.add_argument("effect-easing", "swing"); parser.add_argument("closed", false); parser.add_argument("trigger", "::first"); var _ = { name: "collapsible", trigger: ".pat-collapsible", jquery_plugin: true, transitions: { none: {closed: "hide", open: "show"}, fade: {closed: "fadeOut", open: "fadeIn"}, slide: {closed: "slideUp", open: "slideDown"} }, init: function($el, opts) { return $el.each(function() { var $el = $(this), options = _._validateOptions(this, parser.parse($el, opts)), // create collapsible structure $content, state, storage; if (options.trigger === "::first") { options.$trigger = $el.children(":first"); $content = $el.children(":gt(0)"); } else { options.$trigger = $(options.trigger); $content = $el.children(); } if (options.$trigger.length===0) { log.error("Collapsible has no trigger.", this); return; } if ($content.length) options.$panel = $content.wrapAll("<div class='panel-content' />") .parent(); else options.$panel = $("<div class='panel-content' />").insertAfter(options.$trigger); $el.data("patternCollapsible", options); state=(options.closed || $el.hasClass("closed")) ? "closed" : "open"; if (options.store!=="none") { storage=(options.store==="local" ? store.local : store.session)(_.name); state=storage.get(this.id) || state; } if (state==="closed") { options.$trigger.removeClass("collapsible-open").addClass("collapsible-closed"); $el.removeClass("open").addClass("closed"); options.$panel.hide(); } else { if (options.loadContent) _.loadContent($el, options.loadContent, options.$panel); options.$trigger.removeClass("collapsible-closed").addClass("collapsible-open"); $el.removeClass("closed").addClass("open"); options.$panel.show(); } options.$trigger .off(".pat-collapsible") .on("click.pat-collapsible", null, $el, _._onClick); return $el; }); }, _onClick: function(event) { _.toggle(event.data); }, destroy: function($el) { $el.removeData("patternCollapsible"); $el.children(":first").off(".pat-collapsible"); }, open: function($el) { if (!$el.hasClass("open")) _.toggle($el); return $el; }, close: function($el) { if (!$el.hasClass("closed")) _.toggle($el); return $el; }, _validateOptions: function(trigger, options) { if (options.store!=="none") { if (!trigger.id) { log.warn("state persistance requested, but element has no id"); options.store="none"; } else if (!store.supported) { log.warn("state persistance requested, but browser does not support webstorage"); options.store="none"; } } return options; }, loadContent: function($el, url, $target) { var components = url.split("#"), base_url = components[0], id = components[1] ? "#" + components[1] : null, opts = [{ url: base_url, source: id, $target: $target, dataType: "html" }]; inject.execute(opts, $el); }, toggle: function($el) { var options = $el.data("patternCollapsible"), new_state = $el.hasClass("closed") ? "open" : "closed"; if (options.store!=="none") { var storage=(options.store==="local" ? store.local : store.session)(_.name); storage.set($el.attr("id"), new_state); } if (new_state==="open") { $el.trigger("patterns-collapsible-open"); _._transit($el, "closed", "open", options); } else { $el.trigger("patterns-collapsible-close"); _._transit($el, "open", "closed", options); } // allow for chaining return $el; }, _transit: function($el, from_cls, to_cls, options) { if (to_cls === "open" && options.loadContent) _.loadContent($el, options.loadContent, options.$panel); var duration = (options.transition==="css" || options.transition==="none") ? null : options.effect.duration; if (!duration) { options.$trigger .removeClass("collapsible-" + from_cls) .addClass("collapsible-" + to_cls); $el .removeClass(from_cls) .addClass(to_cls); } else { var t = _.transitions[options.transition]; $el.addClass("in-progress"); options.$trigger.addClass("collapsible-in-progress"); options.$panel[t[to_cls]](duration, options.effect.easing, function() { options.$trigger .removeClass("collapsible-" + from_cls) .removeClass("collapsible-in-progress") .addClass("collapsible-" + to_cls); $el .removeClass(from_cls) .removeClass("in-progress") .addClass(to_cls); }); } } }; registry.register(_); return _; }); // jshint indent: 4, browser: true, jquery: true, quotmark: double // vim: sw=4 expandtab
JavaScript
0
@@ -2964,32 +2964,33 @@ _. +_ loadContent($el, @@ -4504,16 +4504,17 @@ +_ loadCont @@ -5826,16 +5826,17 @@ _. +_ loadCont
cc2ad15469ca906f42a1e9b80dbd656df8eb5b7e
add switching hud
src/pong/object/Hud.js
src/pong/object/Hud.js
import { WidthScreen, scoreToWin } from "../constants.js"; const style = {font: '80px Arial', fill: '#FFFFFF', align: 'center'} const styleWinner = {font: '50px Arial', fill: '#FFFFFF', align: 'center'} const top = 10; const winnerLabel = "Winner !"; class Hud extends Phaser.Group { constructor(game, scores) { super(game); this.scoreLeft = game.add.text(WidthScreen * 0.25, top, scores[0], style); this.scoreLeft.anchor.set(0.5, 0); this.winnerLeft = game.add.text(WidthScreen * 0.25, top + 100, winnerLabel, styleWinner); this.winnerLeft.anchor.set(0.5, 0.5); this.winnerLeft.visible = false; this.scoreRight = game.add.text(WidthScreen * 0.75, top, scores[1], style); this.scoreRight.anchor.set(0.5, 0); this.winnerRight = game.add.text(WidthScreen * 0.75, top + 100, winnerLabel, styleWinner); this.winnerRight.anchor.set(0.5, 0.5); this.winnerRight.visible = false; this.add(this.scoreRight); this.add(this.scoreLeft); } updateTexts(scores) { this.scoreLeft.text = scores[0]; this.scoreRight.text = scores[1]; } makeWinnerVisible(scores) { if(scores[0] === scoreToWin) { this.winnerLeft.visible = true; } else if(scores[1] === scoreToWin) { this.winnerRight.visible = true; } } makeWinnerInvisible(scores) { this.winnerLeft.visible = false; this.winnerRight.visible = false; } } export default Hud;
JavaScript
0.000001
@@ -14,16 +14,30 @@ hScreen, + HeightScreen, scoreTo @@ -222,17 +222,48 @@ t top = -1 +50;%0Aconst left = WidthScreen - 8 0;%0Aconst @@ -347,24 +347,48 @@ game, scores +, direction = %22vertical%22 ) %7B%0A supe @@ -410,77 +410,44 @@ is.s -coreLeft = game.add.text(WidthScreen * 0.25, top, scores%5B0%5D, style +witchHub(game, scores, direction );%0A +%0A @@ -482,102 +482,10 @@ 5, 0 -);%0A this.winnerLeft = game.add.text(WidthScreen * 0.25, top + 100, winnerLabel, styleWinner +.5 );%0A @@ -521,32 +521,34 @@ (0.5, 0.5);%0A +// this.winnerLeft. @@ -588,201 +588,28 @@ ight - = game.add.text(WidthScreen * 0.75, top, scores%5B1%5D, style);%0A this.scoreRight.anchor.set(0.5, 0);%0A this.winnerRight = game.add.text(WidthScreen * 0.75, top + 100, winnerLabel, styleWinner +.anchor.set(0.5, 0.5 );%0A @@ -646,32 +646,34 @@ (0.5, 0.5);%0A +// this.winnerRight @@ -1168,16 +1168,847 @@ e;%0A %7D%0A%0A + switchHub(game, scores, direction) %7B%0A if(direction === %22vertical%22) %7B%0A this.scoreLeft = game.add.text(WidthScreen * 0.25, top, scores%5B0%5D, style);%0A this.winnerLeft = game.add.text(WidthScreen * 0.25, top + 100, winnerLabel, styleWinner);%0A%0A this.scoreRight = game.add.text(WidthScreen * 0.75, top, scores%5B1%5D, style);%0A this.winnerRight = game.add.text(WidthScreen * 0.75, top + 100, winnerLabel, styleWinner);%0A %7D else %7B%0A this.scoreLeft = game.add.text(left, HeightScreen * 0.25, scores%5B0%5D, style);%0A this.winnerLeft = game.add.text(left - 20, HeightScreen * 0.25 + 100, winnerLabel, styleWinner);%0A%0A this.scoreRight = game.add.text(left, HeightScreen * 0.75, scores%5B1%5D, style);%0A this.winnerRight = game.add.text(left - 20, HeightScreen * 0.75 + 100, winnerLabel, styleWinner);%0A %7D%0A%0A %7D%0A%0A %7D%0A%0Aexpor
6432b02160a1a68f485c38f824e826a3c48bde49
disable overlay touch event until action sheet opened
src/ActionSheet.js
src/ActionSheet.js
// @flow import React, { Component } from 'react'; import { View, Animated, StyleSheet, ScrollView, Dimensions } from 'react-native'; import AnimatedOverlay from 'react-native-animated-overlay'; import Animation from './Animation'; const { width: WIDTH, height: HEIGHT } = Dimensions.get('window'); // action sheet states const ACTION_SHEET_OPENING: string = 'opening'; const ACTION_SHEET_OPENED: string = 'opened'; const ACTION_SHEET_CLOSING: string = 'closing'; const ACTION_SHEET_CLOSED: string = 'closed'; const DEFAULT_ANIMATION_DURATION: number = 250; const INITIAL_TOP_POSITION: number = -180; const INITIAL_BOTTOM_POSITION: number = HEIGHT * -1; const styles = StyleSheet.create({ container: { position: 'absolute', top: 0, left: 0, backgroundColor: 'white', }, contentContainer: { width: WIDTH, position: 'absolute', backgroundColor: 'white', }, scrollView: { }, }); type Props = { onShow?: () => void; onHide?: () => void; show?: boolean; animationDuration?: number; overlayOpacity?: number; position?: 'top' | 'bottom'; children?: any; }; const defaultProps = { onShow: () => {}, onHide: () => {}, show: false, animationDuration: DEFAULT_ANIMATION_DURATION, overlayOpacity: 0.3, position: 'top', children: null, }; class ActionSheet extends Component { props: Props static defaultProps = defaultProps constructor(props: Props) { super(props); this.state = { show: props.show, actionSheetState: ACTION_SHEET_CLOSED, actionSheetAnimation: new Animation(this.hideActionSheetPosition), }; } componentDidMount() { if (this.props.show) { this.show(); } } componentWillReceiveProps(nextProps) { if (this.props.show !== nextProps.show) { if (nextProps.show) { this.show(); } else { this.hide(); } } } get showActionSheetPosition(): string { const { position } = this.props; if (position === 'top') { return INITIAL_TOP_POSITION * -1; } return 0; } get hideActionSheetPosition(): string { const { position } = this.props; if (position === 'top') { return INITIAL_TOP_POSITION; } return INITIAL_BOTTOM_POSITION * -1; } setActionSheetState(toValue: number, callback?: Function = () => {}): void { const { animationDuration } = this.props; const isClosed = (this.state.actionSheetState === ACTION_SHEET_CLOSED); let actionSheetState = isClosed ? ACTION_SHEET_OPENING : ACTION_SHEET_CLOSING; this.setState({ actionSheetState }); this.state.actionSheetAnimation.toValue(toValue, animationDuration, () => { const isClosing = (this.state.actionSheetState === ACTION_SHEET_CLOSING); actionSheetState = isClosing ? ACTION_SHEET_CLOSED : ACTION_SHEET_OPENED; this.setState({ actionSheetState }); callback(); }); } onOverlayPress = (): void => { this.hide(); } show = (callback?: Function = () => {}): void => { if ([ACTION_SHEET_OPENING, ACTION_SHEET_OPENED].includes(this.state.actionSheetState)) { return; } const { onShow } = this.props; this.setState({ show: true }); this.setActionSheetState(this.showActionSheetPosition); onShow(); callback(); } hide = (callback?: Function = () => {}): void => { if ([ACTION_SHEET_CLOSING, ACTION_SHEET_CLOSED].includes(this.state.actionSheetState)) { return; } const { onHide } = this.props; this.setState({ show: false }); this.setActionSheetState(this.hideActionSheetPosition); onHide(); callback(); } render() { const { children, animationDuration, overlayOpacity, position } = this.props; const { actionSheetState, actionSheetAnimation: { animations } } = this.state; const overlayShow = [ACTION_SHEET_OPENED, ACTION_SHEET_OPENING].includes(actionSheetState); const contentPosition = (position === 'top') ? { top: INITIAL_TOP_POSITION } : { bottom: INITIAL_BOTTOM_POSITION }; const scrollView = (position === 'top') ? { paddingTop: 30 } : null; return ( <View style={[styles.container]}> <AnimatedOverlay onPress={this.onOverlayPress} overlayShow={overlayShow} duration={animationDuration} opacity={overlayOpacity} /> <Animated.View style={[styles.contentContainer, contentPosition, animations]} > <ScrollView style={[styles.scrollView, scrollView]}> {children} </ScrollView> </Animated.View> </View> ); } } export default ActionSheet;
JavaScript
0
@@ -3893,16 +3893,104 @@ tState); +%0A const pointerEvents = (actionSheetState === ACTION_SHEET_OPENED) ? 'auto' : 'none'; %0A%0A co @@ -4430,16 +4430,56 @@ pacity%7D%0A + pointerEvents=%7BpointerEvents%7D%0A
f3ac0bdb992a1c4b2e32f423ca9b5afb686a455d
fix linter
src/readers/csv/csv.js
src/readers/csv/csv.js
import parseDecimal from "parse-decimal-number"; import Reader from "base/reader"; const cached = {}; const CSVReader = Reader.extend({ _name: "csv", /** * Initializes the reader. * @param {Object} readerInfo Information about the reader */ init(readerInfo) { this._data = []; this._basepath = readerInfo.path; this.delimiter = readerInfo.delimiter; this.keySize = readerInfo.keySize || 1; this._parseStrategies = [ ...[",.", ".,"].map(separator => this._createParseStrategy(separator)), number => number, ]; Object.assign(this.ERRORS, { WRONG_TIME_COLUMN_OR_UNITS: "reader/error/wrongTimeUnitsOrColumn", NOT_ENOUGH_ROWS_IN_FILE: "reader/error/notEnoughRows", UNDEFINED_DELIMITER: "reader/error/undefinedDelimiter", EMPTY_HEADERS: "reader/error/emptyHeaders" }); }, ensureDataIsCorrect({ columns, rows }, parsers) { const timeKey = columns[this.keySize]; const [firstRow] = rows; const parser = parsers[timeKey]; const time = firstRow[timeKey].trim(); if (parser && !parser(time)) { throw this.error(this.ERRORS.WRONG_TIME_COLUMN_OR_UNITS, undefined, { currentYear: new Date().getFullYear(), foundYear: time }); } if (!columns.filter(Boolean).length) { throw this.error(this.ERRORS.EMPTY_HEADERS); } }, /** * This function returns info about the dataset * in case of CSV reader it's just the name of the file * @returns {object} object of info about the dataset */ getDatasetInfo() { return { name: this._basepath.split("/").pop() }; }, load() { const { _basepath: path } = this; return new Promise((resolve, reject) => { const cachedData = cached[path]; if (cachedData) { resolve(cachedData); } else { d3.text(path).get((error, text) => { if (!text) { return reject(`No permissions or empty file: ${path}. ${error}`); } if (error) { return reject(`Error happened while loading csv file: ${path}. ${error}`); } try { const { delimiter = this._guessDelimiter(text) } = this; const parser = d3.dsvFormat(delimiter); const rows = parser.parse(text, row => Object.keys(row).every(key => !row[key]) ? null : row); const { columns } = rows; const result = { columns, rows }; cached[path] = result; resolve(result); } catch (e) { return reject(e); } }); } }); }, _guessDelimiter(text) { const stringsToCheck = 2; const rows = this._getRows(text, stringsToCheck).map(row => row.replace(/".*?"/g, "")); if (rows.length !== stringsToCheck) { throw this.error(this.ERRORS.NOT_ENOUGH_ROWS_IN_FILE); } const [header, firstRow] = rows; const [comma, semicolon] = [",", ";"]; const commasCountInHeader = this._countCharsInLine(header, comma); const semicolonsCountInHeader = this._countCharsInLine(header, semicolon); const commasCountInFirstRow = this._countCharsInLine(firstRow, comma); const semicolonsCountInFirstRow = this._countCharsInLine(firstRow, semicolon); if ( this._checkDelimiters( commasCountInHeader, commasCountInFirstRow, semicolonsCountInHeader, semicolonsCountInFirstRow ) ) { return comma; } else if ( this._checkDelimiters( semicolonsCountInHeader, semicolonsCountInFirstRow, commasCountInHeader, commasCountInFirstRow ) ) { return semicolon; } throw this.error(this.ERRORS.UNDEFINED_DELIMITER); }, _checkDelimiters( firstDelimiterInHeader, firstDelimiterInFirstRow, secondDelimiterInHeader, secondDelimiterInFirstRow ) { return firstDelimiterInHeader === firstDelimiterInFirstRow && firstDelimiterInHeader > 1 && ( (secondDelimiterInHeader !== secondDelimiterInFirstRow) || (!secondDelimiterInHeader && !secondDelimiterInFirstRow) || (firstDelimiterInHeader > secondDelimiterInHeader && firstDelimiterInFirstRow > secondDelimiterInFirstRow) ); }, _getRows(text, count = 0) { const re = /([^\r\n]+)/g; const rows = []; let rowsCount = 0; let matches = true; while (matches && rowsCount !== count) { matches = re.exec(text); if (matches && matches.length > 1) { ++rowsCount; rows.push(matches[1]); } } return rows; }, _countCharsInLine(text, char) { const re = new RegExp(char, "g"); const matches = text.match(re); return matches ? matches.length : 0; }, _createParseStrategy(separators) { return value => { const hasOnlyNumbersOrSeparators = !(new RegExp(`[^\\d${separators}]`).test(value)); if (hasOnlyNumbersOrSeparators && value) { const result = parseDecimal(value, separators); if (!isFinite(result) || isNaN(result)) { this._isParseSuccessful = false; } return result; } return value; }; }, _mapRows(rows, query, parsers) { const mapRow = this._getRowMapper(query, parsers); for (const parseStrategy of this._parseStrategies) { this._parse = parseStrategy; this._isParseSuccessful = true; const result = []; for (const row of rows) { const parsed = mapRow(row); if (!this._isParseSuccessful) { break; } result.push(parsed); } if (this._isParseSuccessful) { return result; } } }, versionInfo: { version: __VERSION, build: __BUILD } }); export default CSVReader;
JavaScript
0.000002
@@ -3985,18 +3985,16 @@ (%0A - (secondD @@ -4223,26 +4223,24 @@ InFirstRow)%0A - );%0A %7D,%0A
b139f1f12745a64b7aab1fea9cdf751bc45a0a09
check install location for a servers.json as well
src/scripts/servers.js
src/scripts/servers.js
/* globals $ */ import jetpack from 'fs-jetpack'; import { EventEmitter } from 'events'; import { remote } from 'electron'; const remoteServers = remote.require('./background').remoteServers; class Servers extends EventEmitter { constructor () { super(); this.load(); } get hosts () { return this._hosts; } set hosts (hosts) { this._hosts = hosts; this.save(); return true; } get hostsKey () { return 'rocket.chat.hosts'; } get activeKey () { return 'rocket.chat.currentHost'; } load () { var hosts = localStorage.getItem(this.hostsKey); try { hosts = JSON.parse(hosts); } catch (e) { if (typeof hosts === 'string' && hosts.match(/^https?:\/\//)) { hosts = {}; hosts[hosts] = { title: hosts, url: hosts }; } localStorage.setItem(this.hostsKey, JSON.stringify(hosts)); } if (hosts === null) { hosts = {}; } if (Array.isArray(hosts)) { var oldHosts = hosts; hosts = {}; oldHosts.forEach(function (item) { item = item.replace(/\/$/, ''); hosts[item] = { title: item, url: item }; }); localStorage.setItem(this.hostsKey, JSON.stringify(hosts)); } // Load server info from server config file if (Object.keys(hosts).length === 0) { const serverFileName = 'servers.json'; const userDataDir = jetpack.cwd(remote.app.getPath('userData')); try { const result = userDataDir.read(serverFileName, 'json'); if (result) { hosts = {}; Object.keys(result).forEach((title) => { const url = result[title]; hosts[url] = { title, url }; }); localStorage.setItem(this.hostsKey, JSON.stringify(hosts)); // Assume user doesn't want sidebar if they only have one server if (Object.keys(hosts).length === 1) { localStorage.setItem('sidebar-closed', 'true'); } } } catch (e) { console.log('Server file invalid'); } } this._hosts = hosts; remoteServers.loadServers(this._hosts); this.emit('loaded'); } save () { localStorage.setItem(this.hostsKey, JSON.stringify(this._hosts)); this.emit('saved'); } get (hostUrl) { return this.hosts[hostUrl]; } forEach (cb) { for (var host in this.hosts) { if (this.hosts.hasOwnProperty(host)) { cb(this.hosts[host]); } } } validateHost (hostUrl, timeout) { console.log('Validating hostUrl', hostUrl); timeout = timeout || 5000; return new Promise(function (resolve, reject) { var resolved = false; $.getJSON(`${hostUrl}/api/info`).then(function () { if (resolved) { return; } resolved = true; console.log('HostUrl valid', hostUrl); resolve(); }, function (request) { if (request.status === 401) { let authHeader = request.getResponseHeader('www-authenticate'); if (authHeader && authHeader.toLowerCase().indexOf('basic ') === 0) { resolved = true; console.log('HostUrl needs basic auth', hostUrl); reject('basic-auth'); } } if (resolved) { return; } resolved = true; console.log('HostUrl invalid', hostUrl); reject('invalid'); }); if (timeout) { setTimeout(function () { if (resolved) { return; } resolved = true; console.log('Validating hostUrl TIMEOUT', hostUrl); reject('timeout'); }, timeout); } }); } hostExists (hostUrl) { var hosts = this.hosts; return !!hosts[hostUrl]; } addHost (hostUrl) { var hosts = this.hosts; let match = hostUrl.match(/^(https?:\/\/)([^:]+):([^@]+)@(.+)$/); let username; let password; let authUrl; if (match) { authUrl = hostUrl; hostUrl = match[1] + match[4]; username = match[2]; password = match[3]; } if (this.hostExists(hostUrl) === true) { this.setActive(hostUrl); return false; } hosts[hostUrl] = { title: hostUrl, url: hostUrl, authUrl: authUrl, username: username, password: password }; this.hosts = hosts; remoteServers.loadServers(this.hosts); this.emit('host-added', hostUrl); return hostUrl; } removeHost (hostUrl) { var hosts = this.hosts; if (hosts[hostUrl]) { delete hosts[hostUrl]; this.hosts = hosts; remoteServers.loadServers(this.hosts); if (this.active === hostUrl) { this.clearActive(); } this.emit('host-removed', hostUrl); } } get active () { return localStorage.getItem(this.activeKey); } setActive (hostUrl) { let url; if (this.hostExists(hostUrl)) { url = hostUrl; } else if (Object.keys(this._hosts).length > 0) { url = Object.keys(this._hosts)[0]; } if (url) { localStorage.setItem(this.activeKey, hostUrl); this.emit('active-setted', url); return true; } this.emit('loaded'); return false; } restoreActive () { this.setActive(this.active); } clearActive () { localStorage.removeItem(this.activeKey); this.emit('active-cleared'); return true; } setHostTitle (hostUrl, title) { if (title === 'Rocket.Chat' && /https?:\/\/demo\.rocket\.chat/.test(hostUrl) === false) { title += ' - ' + hostUrl; } var hosts = this.hosts; hosts[hostUrl].title = title; this.hosts = hosts; this.emit('title-setted', hostUrl, title); } } export default new Servers();
JavaScript
0
@@ -1747,37 +1747,174 @@ ));%0A -try %7B +const installDataDir = jetpack.cwd(process.cwd());%0A try %7B%0A var result = installDataDir.read(serverFileName, 'json'); %0A @@ -1926,16 +1926,27 @@ t result +UserDataDir = userD @@ -1974,32 +1974,198 @@ eName, 'json');%0A + // overwrite installDataDir servers.json%0A if (resultUserDataDir) %7B%0A var result = resultUserDataDir;%0A %7D%0A
8177653e968360baeade0c5a10b27e3d62ff0291
Add canvas selector override on module basis.
src/services/canvas.js
src/services/canvas.js
define([ 'jquery', 'underscore', '../service', '../utils' ], function ($, _, Service, utils) { "use strict"; var Canvas = Service.extend({ // selector on wich to append the main canvas. selector: 'body', useDeep: false, initialize: function (options) { utils.copyOption(['selector'], this, options); }, // Listen to `do:view:attach` event and attach given view to selector. // // It is possible to override selector on a module basis // by providing a selector option. // // ``` javascript // var canvas = new SelectorCanvas({selector: "body"}); // // // default behavior // var module = new Module(); // module // .use('canvas', canvas); // append view to "body" // // // override on module basis // var module = new Module({selector: ".l-content"}); // module // .use('canvas', canvas); // append view to ".l-content" // ``` use: function (module, parent) { // copy selector option if any. utils.copyOption(['selector'], module, module.options); // Listen to view attach event. module.on('do:view:attach', this.attachView, this); }, dispose: function (module, parent) { module.off('do:view:attach', this.attachView, this); }, attachView: function (module, view) { if (this.currentView) { this.currentView.remove(); } this.currentView = view; $(this.selector).append(view.$el); if (view._attachPlugin) { view._attachPlugin(); } else if(view.attachPlugin()) { view.attachPlugin(); } } }); return Canvas; });
JavaScript
0
@@ -344,32 +344,67 @@ this, options);%0A + this.currentView = %7B%7D;%0A %7D,%0A%0A @@ -1508,24 +1508,85 @@ le, view) %7B%0A + var selector = module.selector %7C%7C this.selector;%0A @@ -1605,16 +1605,26 @@ rentView +%5Bselector%5D ) %7B%0A @@ -1651,16 +1651,26 @@ rentView +%5Bselector%5D .remove( @@ -1715,16 +1715,26 @@ rentView +%5Bselector%5D = view; @@ -1749,21 +1749,16 @@ $( -this. selector
a613bdf7f5ca2be634aa6aab5a7549ed41c9a5ed
return socket.io object
src/socket_handlers.js
src/socket_handlers.js
// Copyright (C) 2011 - Texas Instruments, Jason Kridner // // var b = require('../main'); var fs = require('fs'); var url = require('url'); var child_process = require('child_process'); var winston = require('winston'); var socketio = require('socket.io'); var debug = process.env.DEBUG ? true : false; exports.socketJSReqHandler = function(req, res) { function sendFile(err, file) { if(err) { res.writeHead(500, {"Content-Type": "text/plain"}); res.end(err + '\n'); return; } res.setHeader('Content-Type', 'text/javascript'); file = file.replace(/___INSERT_HOST___/g, host); res.end(file); } var parsedUrl = url.parse(req.url); var uri = parsedUrl.pathname; var host = 'http://' + req.headers.host; if(uri == '/bonescript.js') { var filename = __dirname + '/bonescript.js'; if(debug) winston.debug('filename = ' + filename) fs.readFile(filename, 'utf8', sendFile); } } exports.addSocketListeners = function(server, serverEmitter) { var io = socketio(server); if(debug) winston.debug('Listening for new socket.io clients'); io.on('connection', onconnect); function onconnect(socket) { winston.debug('Client connected'); serverEmitter.emit('socket$connect', socket); // on disconnect socket.on('disconnect', function() { if(debug) winston.debug('Client disconnected'); serverEmitter.emit('socket$disconnect'); }); socket.on('message', serverMessage); spawn(socket); var modmsg = {}; modmsg.module = 'bonescript'; modmsg.data = {}; var callMyFunc = function(name, m) { var myCallback = function(resp) { if(debug) winston.debug(name + ' replied to ' + JSON.stringify(m) + ' with ' + JSON.stringify(resp)); if(typeof m.seq == 'undefined') return; if(!resp || (typeof resp != 'object')) resp = {'data': resp}; resp.seq = m.seq; // TODO: consider setting 'oneshot' if(debug) winston.debug('Sending message "bonescript": ' + JSON.stringify(resp)); socket.emit('bonescript', resp); }; try { var callargs = []; for(var arg in b[name].args) { var argname = b[name].args[arg]; if(argname == 'callback') { if(typeof m.seq == 'number') callargs.push(myCallback); else callargs.push(null); } else if(typeof m[argname] != 'undefined') { callargs.push(m[argname]); } else { callargs.push(undefined); } } if(debug) winston.debug('Calling ' + name + '(' + callargs.join(',') + ')'); b[name].apply(this, callargs); } catch(ex) { if(debug) winston.debug('Error handing ' + name + ' message: ' + ex); if(debug) winston.debug('m = ' + JSON.stringify(m)); } }; var addSocketX = function(message, name) { var onFuncMessage = function(m) { callMyFunc(name, m); }; socket.on(message, onFuncMessage); }; var b = require('../main'); for(var i in b) { if(typeof b[i] == 'function') { if(typeof b[i].args != 'undefined') { modmsg.data[i] = {}; modmsg.data[i].name = i; modmsg.data[i].type = 'function'; modmsg.data[i].value = b[i].args; addSocketX('bonescript$' + i, i); } } else { modmsg.data[i] = {}; modmsg.data[i].name = i; modmsg.data[i].type = typeof b[i]; modmsg.data[i].value = b[i]; } } socket.emit('require', modmsg); } function serverMessage(message) { serverEmitter.emit('message', message); } } // most heavily borrowed from https://github.com/itchyny/browsershell function spawn(socket) { var stream = ''; var timer; var len = 0; var c; socket.on('shell', receive); return(receive); function receive(msg) { if(!c) { try { if(debug) winston.debug('Spawning bash'); c = child_process.spawn('/bin/bash', ['-i'], {customFds: [-1, -1, -1]}); c.stdout.on('data', send); c.stderr.on('data', send); c.on('exit', function() { socket.emit('shell', send('\nexited\n')); c = undefined; }); socket.on('disconnect', function () { if(debug) winston.debug('Killing bash'); c.kill('SIGHUP'); }); } catch(ex) { c = undefined; send('Error invoking bash'); winston.error('Error invoking bash'); } } if(c) { if(msg) { c.stdin.write(msg + '\n', 'utf-8'); } } else { winston.error('Unable to invoke child process'); } } function send(data) { // add data to the stream stream += data.toString(); ++len; // clear any existing timeout if it exists if(timer) clearTimeout(timer); // set new timeout timer = setTimeout(function () { socket.emit('shell', stream); stream = ''; len = 0; }, 100); // send data if over threshold if(len > 1000) { clearTimeout(timer); socket.emit('shell', stream); stream = ''; len = 0; } } }
JavaScript
0
@@ -4179,16 +4179,37 @@ ;%0A %7D%0A + %0A return(io);%0A %7D%0A%0A// mo
f9d418ee79ae2a730dbe9315cf6a8a206467f6f4
implement fix suggested by @wdyang
src/stackable-chart.js
src/stackable-chart.js
dc.stackableChart = function (_chart) { var MIN_DATA_POINT_HEIGHT = 0; var _groupStack = new dc.utils.GroupStack(); var _allGroups; var _allValueAccessors; var _allKeyAccessors; _chart.stack = function (group, retriever) { _groupStack.setDefaultAccessor(_chart.valueAccessor()); _groupStack.addGroup(group, retriever); _chart.expireCache(); return _chart; }; _chart.expireCache = function(){ _allGroups = null; _allValueAccessors = null; _allKeyAccessors = null; return _chart; }; _chart.allGroups = function () { if (_allGroups == null) { _allGroups = []; _allGroups.push(_chart.group()); for (var i = 0; i < _groupStack.size(); ++i) _allGroups.push(_groupStack.getGroupByIndex(i)); } return _allGroups; }; _chart.allValueAccessors = function () { if (_allValueAccessors == null) { _allValueAccessors = []; _allValueAccessors.push(_chart.valueAccessor()); for (var i = 0; i < _groupStack.size(); ++i) _allValueAccessors.push(_groupStack.getAccessorByIndex(i)); } return _allValueAccessors; }; _chart.getValueAccessorByIndex = function (groupIndex) { return _chart.allValueAccessors()[groupIndex]; }; _chart.yAxisMin = function () { var min = 0; var allGroups = _chart.allGroups(); for (var groupIndex = 0; groupIndex < allGroups.length; ++groupIndex) { var group = allGroups[groupIndex]; var m = dc.utils.groupMin(group, _chart.getValueAccessorByIndex(groupIndex)); if (m < min) min = m; } if (min < 0) { min = 0; for (var groupIndex = 0; groupIndex < allGroups.length; ++groupIndex) { var group = allGroups[groupIndex]; min += dc.utils.groupMin(group, _chart.getValueAccessorByIndex(groupIndex)); } } min = dc.utils.subtract(min, _chart.yAxisPadding()); return min; }; _chart.yAxisMax = function () { var max = 0; var allGroups = _chart.allGroups(); for (var groupIndex = 0; groupIndex < allGroups.length; ++groupIndex) { var group = allGroups[groupIndex]; max += dc.utils.groupMax(group, _chart.getValueAccessorByIndex(groupIndex)); } max = dc.utils.add(max, _chart.yAxisPadding()); return max; }; _chart.allKeyAccessors = function () { if (_allKeyAccessors == null) { _allKeyAccessors = []; _allKeyAccessors.push(_chart.keyAccessor()); for (var i = 0; i < _groupStack.size(); ++i) _allKeyAccessors.push(_chart.keyAccessor()); } return _allKeyAccessors; }; _chart.getKeyAccessorByIndex = function (groupIndex) { return _chart.allKeyAccessors()[groupIndex]; }; _chart.xAxisMin = function () { var min = null; var allGroups = _chart.allGroups(); for (var groupIndex = 0; groupIndex < allGroups.length; ++groupIndex) { var group = allGroups[groupIndex]; var m = dc.utils.groupMin(group, _chart.getKeyAccessorByIndex(groupIndex)); if (min == null || min > m) min = m; } return dc.utils.subtract(min, _chart.xAxisPadding()); }; _chart.xAxisMax = function () { var max = null; var allGroups = _chart.allGroups(); for (var groupIndex = 0; groupIndex < allGroups.length; ++groupIndex) { var group = allGroups[groupIndex]; var m = dc.utils.groupMax(group, _chart.getKeyAccessorByIndex(groupIndex)); if (max == null || max < m) max = m; } return dc.utils.add(max, _chart.xAxisPadding()); }; _chart.baseLineY = function () { return _chart.y()(0); } _chart.dataPointBaseline = function () { return _chart.margins().top + _chart.baseLineY(); }; function getValueFromData(groupIndex, d) { return _chart.getValueAccessorByIndex(groupIndex)(d); } _chart.dataPointHeight = function (d, groupIndex) { var value = getValueFromData(groupIndex, d); var yPosition = _chart.y()(value); var zeroPosition = _chart.baseLineY(); var h = 0; if (value > 0) h = zeroPosition - yPosition; else h = yPosition - zeroPosition; if (isNaN(h) || h < MIN_DATA_POINT_HEIGHT) h = MIN_DATA_POINT_HEIGHT; return h; }; function calculateDataPointMatrix(data, groupIndex) { for (var dataIndex = 0; dataIndex < data.length; ++dataIndex) { var d = data[dataIndex]; var value = getValueFromData(groupIndex, d); if (groupIndex == 0) { if (value > 0) _groupStack.setDataPoint(groupIndex, dataIndex, _chart.dataPointBaseline() - _chart.dataPointHeight(d, groupIndex)); else _groupStack.setDataPoint(groupIndex, dataIndex, _chart.dataPointBaseline()); } else { if (value > 0) _groupStack.setDataPoint(groupIndex, dataIndex, _groupStack.getDataPoint(groupIndex - 1, dataIndex) - _chart.dataPointHeight(d, groupIndex)) else if (value < 0) _groupStack.setDataPoint(groupIndex, dataIndex, _groupStack.getDataPoint(groupIndex - 1, dataIndex) + _chart.dataPointHeight(d, groupIndex - 1)) else // value == 0 _groupStack.setDataPoint(groupIndex, dataIndex, _groupStack.getDataPoint(groupIndex - 1, dataIndex)) } } } _chart.calculateDataPointMatrixForAll = function (groups) { for (var groupIndex = 0; groupIndex < groups.length; ++groupIndex) { var group = groups[groupIndex]; var data = group.all(); calculateDataPointMatrix(data, groupIndex); } }; _chart.calculateDataPointMatrixWithinXDomain = function (groups) { for (var groupIndex = 0; groupIndex < groups.length; ++groupIndex) { var group = groups[groupIndex]; var data = _chart.getDataWithinXDomain(group); calculateDataPointMatrix(data, groupIndex); } }; _chart.getChartStack = function () { return _groupStack; }; dc.override(_chart, "valueAccessor", function (_) { if (!arguments.length) return _chart._valueAccessor(); _chart.expireCache(); return _chart._valueAccessor(_); }); dc.override(_chart, "keyAccessor", function (_) { if (!arguments.length) return _chart._keyAccessor(); _chart.expireCache(); return _chart._keyAccessor(_); }); return _chart; };
JavaScript
0
@@ -4957,33 +4957,37 @@ if (value %3E -0 +1e-13 )%0A @@ -5268,33 +5268,37 @@ if (value %3E -0 +1e-13 )%0A @@ -5477,17 +5477,22 @@ value %3C -0 +-1e-13 )%0A @@ -5680,17 +5680,17 @@ / value -= +~ = 0%0A
7eedf753e85d5f19440fa74f3c9fe9660c77468a
Fix applying GA status
src/startup/startup.js
src/startup/startup.js
'use strict'; require([ 'wrapper/chrome', 'storage/chrome-storage', 'vendor/showdown.min' ], function(chrome, ChromeStorage, showdown) { $('#opt-in').click(() => { update(false); }); $('#opt-out').click(() => { update(true); }); let update = (value) => { const options = ChromeStorage.getStorage(ChromeStorage.OPTIONS); options.get().then((data) => { data.disableGa = value; options.set(data); }); window.close(); $('.controls').hide(); $('.finished').show(); }; (async() => { const locale = chrome.i18n.getMessage('@@ui_locale'); const defaultPrivacyDoc = 'PRIVACY.md'; let privacyDocs = [defaultPrivacyDoc]; if (!locale.startsWith('en')) { let localeSplit = locale.split('_'); privacyDocs.unshift(`PRIVACY.${localeSplit[0]}.md`); privacyDocs.unshift(`PRIVACY.${locale}.md`); } for (let privacyDoc of privacyDocs) { console.log(`fetching ${privacyDoc}`); try { const response = await fetch(chrome.runtime.getURL(privacyDoc)); const markdown = await response.text(); let converter = new showdown.Converter(); let content = converter.makeHtml(markdown); $('.privacy-policy').html(content); break; } catch (err) { console.log(`Failed to load ${privacyDoc}, reason: ${err.message}`); } } })(); });
JavaScript
0
@@ -94,16 +94,8 @@ %0A%5D, -function (chr @@ -124,18 +124,84 @@ owdown) -%7B%0A +=%3E %7B%0A%09/**%0A%09 * Run initialization%0A%09 */%0A%09init();%0A%0A%09function init() %7B%0A%09 %09$('#opt @@ -226,29 +226,55 @@ %7B%0A%09%09 +%09 update -(fals +GaState(false).then(closePag e);%0A +%09 %09%7D);%0A%0A +%09 %09$(' @@ -304,52 +304,221 @@ %7B%0A%09%09 +%09 update -(tru +GaState(true).then(closePag e);%0A +%09 %09%7D);%0A%0A%09 -let update = +%09preparePrivacyPolicy();%0A%09%7D%0A%0A%09function closePage() %7B%0A%09%09window.close();%0A%09%09// $('.controls').hide();%0A%09%09// $('.finished').show();%0A%09%7D%0A%0A%09async function updateGaState (value) - =%3E %7B%0A%09 @@ -590,40 +590,40 @@ %0A%0A%09%09 -options.get().then((data) =%3E %7B%0A%09 +let data = await options.get();%0A %09%09da @@ -646,17 +646,22 @@ alue;%0A%09%09 -%09 +await options. @@ -676,99 +676,49 @@ );%0A%09 -%09%7D);%0A%0A%09%09window.close();%0A%09%09$('.controls').hide();%0A%09%09$('.finished').show();%0A%09%7D;%0A%0A%09(async() =%3E +%7D%0A%0A%09async function preparePrivacyPolicy() %7B%0A%09 @@ -1495,12 +1495,8 @@ %7D%0A%09%7D -)(); %0A%7D);
e41dc857df3dabca1dc8056889fb86b209928fc1
refactor (swapStrategy): move removing of old views to own function
src/swap-strategies.js
src/swap-strategies.js
export const SwapStrategies = { // animate the next view in before removing the current view; before(viewSlot, previousViews, callback) { if (previousViews !== undefined) { return callback().then(() => viewSlot.removeMany(previousViews, true)); } return callback(); }, // animate the next view at the same time the current view is removed with(viewSlot, previousViews, callback) { if (previousViews !== undefined) { return Promise.all([viewSlot.removeMany(previousViews, true), callback()]); } return callback(); }, // animate the next view in after the current view has been removed after(viewSlot, previousView, callback) { return Promise.resolve(viewSlot.removeAll(true)).then(callback); } };
JavaScript
0
@@ -1,8 +1,165 @@ +function remove(viewSlot, previous) %7B%0A return Array.isArray(previous) %0A ? viewSlot.removeMany(previous, true) %0A : viewSlot.remove(previous, true);%0A%7D%0A%0A export c @@ -265,37 +265,32 @@ ewSlot, previous -Views , callback) %7B%0A @@ -283,34 +283,38 @@ callback) %7B%0A -if +return (previousViews @@ -299,39 +299,34 @@ return (previous -Views ! + = == undefined) %7B%0A @@ -322,31 +322,43 @@ defined) - %7B +%0A ? callback() %0A -return +: callbac @@ -372,24 +372,31 @@ n(() =%3E +remove( viewSlot .removeM @@ -391,70 +391,19 @@ Slot -.removeMany(previousViews, true));%0A %7D%0A%0A return callback( +, previous) );%0A @@ -531,10 +531,14 @@ -if +return (pr @@ -547,15 +547,10 @@ ious -Views ! + = == u @@ -562,23 +562,35 @@ ned) - %7B +%0A ? callback() %0A -return +: Pro @@ -599,24 +599,31 @@ se.all(%5B +remove( viewSlot .removeM @@ -618,83 +618,32 @@ Slot -.removeMany(previousViews, true), callback()%5D);%0A %7D%0A%0A return callback( +, previous), callback()%5D );%0A @@ -743,20 +743,16 @@ previous -View , callba
822da4b44dbe5bd9ecf8888e8c0fbe353e3ea390
Add component docs/comments
src/Paper/Paper.js
src/Paper/Paper.js
import React, { PropTypes } from 'react'; import { createStyleSheet } from 'stylishly/lib/styleSheet'; import ClassNames from 'classnames'; export const styleSheet = createStyleSheet('Paper', (theme) => { const { palette } = theme; const shadows = {}; theme.shadows.forEach((shadow, index) => { shadows[`dp${index}`] = { boxShadow: shadow, }; }); return { root: { backgroundColor: palette.background.paper, '& rounded': { borderRadius: '2px', }, }, ...shadows, }; }); export default function Paper(props, context) { const { className, rounded, zDepth, ...other } = props; const classes = context.styleManager.render(styleSheet, { group: 'mui' }); const classNames = ClassNames(classes.root, { [classes.rounded]: rounded, [classes[`dp${zDepth >= 0 ? zDepth : 0}`]]: true, }, className); return ( <div className={classNames} {...other} /> ); } Paper.propTypes = { className: PropTypes.string, rounded: PropTypes.bool, zDepth: PropTypes.number, }; Paper.defaultProps = { rounded: true, zDepth: 2, }; Paper.contextTypes = { styleManager: PropTypes.object.isRequired, };
JavaScript
0
@@ -529,16 +529,184 @@ %7D;%0A%7D);%0A%0A +/**%0A * A piece of material paper.%0A *%0A * %60%60%60js%0A * import Paper from 'material-ui/Paper';%0A *%0A * const Component = () =%3E %3CPaper zDepth=%7B8%7D%3EHello World%3C/Paper%3E;%0A * %60%60%60%0A */%0A export d @@ -1124,63 +1124,240 @@ %7B%0A -className: PropTypes.string,%0A rounded: PropTypes.bool, +/**%0A * The CSS class name of the root element.%0A */%0A className: PropTypes.string,%0A /**%0A * Set to false to disable rounded corners%0A */%0A rounded: PropTypes.bool,%0A /**%0A * Shadow depth, corresponds to %60dp%60 in the spec%0A */ %0A z
48647c3a7c2d390bf2b9d3049d0ca789aee2356c
Fix not finding messages after a Discord update
src/tracker/discord.js
src/tracker/discord.js
var DISCORD = (function(){ var getTopMessageViewElement = function(){ let view = DOM.queryReactClass("messages"); return view && view.children.length && view.children[0]; }; var observerTimer = 0, waitingForCleanup = 0; return { /* * Sets up a callback hook to trigger whenever the list of messages is updated. The callback is given a boolean value that is true if there are more messages to load. */ setupMessageUpdateCallback: function(callback){ var onTimerFinished = function(){ let topEle = getTopMessageViewElement(); if (!topEle){ restartTimer(500); } else if (!topEle.getAttribute("class").includes("loadingMore-")){ let messages = DOM.queryReactClass("messages").children.length; if (messages < 100){ waitingForCleanup = 0; } if (waitingForCleanup > 0){ --waitingForCleanup; restartTimer(750); } else{ if (messages > 300){ waitingForCleanup = 6; DOM.setTimer(() => { let view = DOM.queryReactClass("messages"); view.scrollTop = view.scrollHeight/2; }, 1); } callback(topEle.getAttribute("class").includes("hasMore-")); restartTimer(200); } } else{ restartTimer(25); } }; var restartTimer = function(delay){ observerTimer = DOM.setTimer(onTimerFinished, delay); }; onTimerFinished(); window.DHT_ON_UNLOAD.push(() => window.clearInterval(observerTimer)); }, /* * Returns internal React state object of an element. */ getReactProps: function(ele){ var key = Object.keys(ele || {}).find(key => key.startsWith("__reactInternalInstance")); return key ? ele[key].memoizedProps : null; }, /* * Returns an object containing the selected server name, selected channel name and ID, and the object type. * For types DM and GROUP, the server and channel names are identical. * For SERVER type, the channel has to be in view, otherwise Discord unloads it. */ getSelectedChannel: function(){ try{ var obj; var channelListEle = document.querySelector("[class|='privateChannels']"); if (channelListEle){ var channel = DOM.queryReactClass("selected", channelListEle); if (!channel){ return null; } var linkSplit = channel.querySelector("a[href*='/@me/']").href.split("/"); var link = linkSplit[linkSplit.length-1]; if (!(/^\d+$/.test(link))){ return null; } var name = Array.prototype.find.call(channel.querySelector("[class|='name']").childNodes, node => node.nodeType === Node.TEXT_NODE).nodeValue; obj = { "server": name, "channel": name, "id": link, "type": !!DOM.queryReactClass("status", channel) ? "DM" : "GROUP" }; } else{ channelListEle = document.querySelector("[class|='channels']"); var channel = channelListEle.querySelector("[class|='wrapperSelectedText']").parentElement; var props = DISCORD.getReactProps(channel); if (!props){ return null; } var channelObj = props.children.props.channel; if (!channelObj){ return null; } obj = { "server": channelListEle.querySelector("header > span").innerHTML, "channel": channelObj.name, "id": channelObj.id, "type": "SERVER" }; } return obj.channel.length === 0 ? null : obj; }catch(e){ return null; } }, /* * Returns an array containing currently loaded messages. */ getMessages: function(){ var props = DISCORD.getReactProps(DOM.queryReactClass("messages")); var array = props && props.children.find(ele => ele && ele.length); var messages = []; if (array){ for(let obj of array){ if (obj.props.messages){ Array.prototype.push.apply(messages, obj.props.messages); } } } return messages; }, /* * Returns true if the message view is visible. */ isInMessageView: () => !!DOM.queryReactClass("messages"), /* * Returns true if there are more messages available or if they're still loading. */ hasMoreMessages: function(){ let classes = getTopMessageViewElement().getAttribute("class"); return classes.includes("hasMore-") || classes.includes("loadingMore-"); }, /* * Forces the message view to load older messages by scrolling all the way up. */ loadOlderMessages: function(){ let view = DOM.queryReactClass("messages"); view.scrollTop = view.scrollHeight/2; view.scrollTop = 0; }, /* * Selects the next text channel and returns true, otherwise returns false if there are no more channels. */ selectNextTextChannel: function(){ var dms = document.querySelector("[class|='privateChannels']"); if (dms){ var currentChannel = DOM.queryReactClass("selected", dms); var nextChannel = currentChannel && currentChannel.nextElementSibling; var nextLink = nextChannel && nextChannel.querySelector("a[href*='/@me/']"); if (!nextChannel || !nextLink || !nextChannel.getAttribute("class").includes("channel-")){ return false; } else{ nextLink.click(); nextChannel.scrollIntoView(true); return true; } } else{ var isValidChannel = ele => ele.childElementCount > 0 && /wrapper([a-zA-Z]+?)Text/.test(ele.children[0].className); var allChannels = Array.prototype.filter.call(document.querySelector("[class|='channels']").querySelectorAll("[class|='containerDefault']"), isValidChannel); var nextChannel = null; for(var index = 0; index < allChannels.length-1; index++){ if (allChannels[index].children[0].className.includes("wrapperSelectedText")){ nextChannel = allChannels[index+1]; break; } } if (nextChannel === null){ return false; } else{ nextChannel.children[0].click(); nextChannel.scrollIntoView(true); return true; } } } }; })();
JavaScript
0
@@ -4393,15 +4393,98 @@ -if (obj +let nested = obj.props.children;%0A %0A if (nested && nested.props && nested .pro @@ -4546,19 +4546,22 @@ ssages, -obj +nested .props.m
12bdae1a7e50c055f0a61ddf93b5b9c27f46b47d
Use i instead of indexOf function call for splice
backbone.nativeview.js
backbone.nativeview.js
// Backbone.NativeView.js 0.3.3 // --------------- // (c) 2015 Adam Krebs, Jimmy Yuen Ho Wong // Backbone.NativeView may be freely distributed under the MIT license. // For all details and documentation: // https://github.com/akre54/Backbone.NativeView (function (factory) { if (typeof define === 'function' && define.amd) { define(['backbone'], factory); } else if (typeof module === 'object') { module.exports = factory(require('backbone')); } else { factory(Backbone); } }(function (Backbone) { // Cached regex to match an opening '<' of an HTML tag, possibly left-padded // with whitespace. var paddedLt = /^\s*</; // Caches a local reference to `Element.prototype` for faster access. var ElementProto = (typeof Element !== 'undefined' && Element.prototype) || {}; // Cross-browser event listener shims var elementAddEventListener = ElementProto.addEventListener || function(eventName, listener) { return this.attachEvent('on' + eventName, listener); } var elementRemoveEventListener = ElementProto.removeEventListener || function(eventName, listener) { return this.detachEvent('on' + eventName, listener); } var indexOf = function(array, item) { for (var i = 0, len = array.length; i < len; i++) if (array[i] === item) return i; return -1; } // Find the right `Element#matches` for IE>=9 and modern browsers. var matchesSelector = ElementProto.matches || ElementProto.webkitMatchesSelector || ElementProto.mozMatchesSelector || ElementProto.msMatchesSelector || ElementProto.oMatchesSelector || // Make our own `Element#matches` for IE8 function(selector) { // Use querySelectorAll to find all elements matching the selector, // then check if the given element is included in that list. // Executing the query on the parentNode reduces the resulting nodeList, // (document doesn't have a parentNode). var nodeList = (this.parentNode || document).querySelectorAll(selector) || []; return ~indexOf(nodeList, this); }; // Cache Backbone.View for later access in constructor var BBView = Backbone.View; // To extend an existing view to use native methods, extend the View prototype // with the mixin: _.extend(MyView.prototype, Backbone.NativeViewMixin); Backbone.NativeViewMixin = { _domEvents: null, constructor: function() { this._domEvents = []; return BBView.apply(this, arguments); }, $: function(selector) { return this.el.querySelectorAll(selector); }, _removeElement: function() { this.undelegateEvents(); if (this.el.parentNode) this.el.parentNode.removeChild(this.el); }, // Apply the `element` to the view. `element` can be a CSS selector, // a string of HTML, or an Element node. _setElement: function(element) { if (typeof element == 'string') { if (paddedLt.test(element)) { var el = document.createElement('div'); el.innerHTML = element; this.el = el.firstChild; } else { this.el = document.querySelector(element); } } else { this.el = element; } }, // Set a hash of attributes to the view's `el`. We use the "prop" version // if available, falling back to `setAttribute` for the catch-all. _setAttributes: function(attrs) { for (var attr in attrs) { attr in this.el ? this.el[attr] = attrs[attr] : this.el.setAttribute(attr, attrs[attr]); } }, // Make a event delegation handler for the given `eventName` and `selector` // and attach it to `this.el`. // If selector is empty, the listener will be bound to `this.el`. If not, a // new handler that will recursively traverse up the event target's DOM // hierarchy looking for a node that matches the selector. If one is found, // the event's `delegateTarget` property is set to it and the return the // result of calling bound `listener` with the parameters given to the // handler. delegate: function(eventName, selector, listener) { if (typeof selector === 'function') { listener = selector; selector = null; } var root = this.el; var handler = selector ? function (e) { var node = e.target || e.srcElement; for (; node && node != root; node = node.parentNode) { if (matchesSelector.call(node, selector)) { e.delegateTarget = node; listener(e); } } } : listener; elementAddEventListener.call(this.el, eventName, handler, false); this._domEvents.push({eventName: eventName, handler: handler, listener: listener, selector: selector}); return handler; }, // Remove a single delegated event. Either `eventName` or `selector` must // be included, `selector` and `listener` are optional. undelegate: function(eventName, selector, listener) { if (typeof selector === 'function') { listener = selector; selector = null; } if (this.el) { var handlers = this._domEvents.slice(); for (var i = 0, len = handlers.length; i < len; i++) { var item = handlers[i]; var match = item.eventName === eventName && (listener ? item.listener === listener : true) && (selector ? item.selector === selector : true); if (!match) continue; elementRemoveEventListener.call(this.el, item.eventName, item.handler, false); this._domEvents.splice(indexOf(handlers, item), 1); } } return this; }, // Remove all events created with `delegate` from `el` undelegateEvents: function() { if (this.el) { for (var i = 0, len = this._domEvents.length; i < len; i++) { var item = this._domEvents[i]; elementRemoveEventListener.call(this.el, item.eventName, item.handler, false); }; this._domEvents.length = 0; } return this; } }; Backbone.NativeView = Backbone.View.extend(Backbone.NativeViewMixin); return Backbone.NativeView; }));
JavaScript
0.000001
@@ -5580,30 +5580,8 @@ ce(i -ndexOf(handlers, item) , 1)
8ba4910946416ffc9fbfda2d63cb800d1e175426
test with 2 headers instead of 1
test/specs/oboe.integration.spec.js
test/specs/oboe.integration.spec.js
describe("oboe integration (real http)", function(){ it('gets all expected callbacks by time request finishes', function() { var asserter = givenAnOboeInstance('/testServer/tenSlowNumbers') .andWeAreListeningForNodes('![*]'); waitsFor( asserter.toComplete(), 'the request to complete', ASYNC_TEST_TIMEOUT); runs(function(){ asserter.thenTheInstance( matched(0).atPath([0]) , matched(1).atPath([1]) , matched(2).atPath([2]) , matched(3).atPath([3]) , matched(4).atPath([4]) , matched(5).atPath([5]) , matched(6).atPath([6]) , matched(7).atPath([7]) , matched(8).atPath([8]) , matched(9).atPath([9]) ); }); }) it('can abort once some data has been found in streamed response', function() { var aborted = false; var asserter = givenAnOboeInstance('/testServer/tenSlowNumbers') .andWeAreListeningForNodes('![5]', function(){ asserter.andWeAbortTheRequest(); aborted = true; }); waitsFor( function(){return aborted}, 'the request to be aborted', ASYNC_TEST_TIMEOUT); // in case we didn't abort, wait a little longer. If we didn't really abort we'd get the // rest of the data now and the test would fail: waitsFor( someSecondsToPass(3), ASYNC_TEST_TIMEOUT); runs( function(){ asserter.thenTheInstance( // because the request was aborted on index array 5, we got 6 numbers (inc zero) // not the whole ten. hasRootJson([0,1,2,3,4,5]) ); }); }) it('can abort once some data has been found in not very streamed response', function() { // like above but we're getting a static file not the streamed numbers. This means // we'll almost certainly read in the whole response as one onprogress it is on localhost // and the json is very small var aborted = false; var asserter = givenAnOboeInstance('/testServer/static/json/firstTenNaturalNumbers.json') .andWeAreListeningForNodes('![5]', function(){ asserter.andWeAbortTheRequest(); aborted = true; }); waitsFor( function(){return aborted}, 'the request to be aborted', ASYNC_TEST_TIMEOUT); // in case we didn't abort, wait a little longer. If we didn't really abort we'd get the // rest of the data now and the test would fail: waitsFor( someSecondsToPass(1), ASYNC_TEST_TIMEOUT); runs( function(){ asserter.thenTheInstance( // because the request was aborted on index array 5, we got 6 numbers (inc zero) // not the whole ten. hasRootJson([0,1,2,3,4,5]) ); }); }) it('gives full json to callback when request finishes', function( queue ) { var fullResponse = null; oboe.doGet( '/testServer/static/json/firstTenNaturalNumbers.json', function ajaxFinished(obj) { fullResponse = obj; } ); waitsFor( function(){ return !!fullResponse }, 'the request to complete', ASYNC_TEST_TIMEOUT ) runs( function(){ expect(fullResponse).toEqual([0,1,2,3,4,5,6,7,8,9]) }); }) it('gives header to server side', function( queue ) { var done = false; oboe.doGet( { url: '/testServer/echoBackHeaders', headers: {'snarfu':'SNARF'} } ).onNode( 'snarfu', function( headerValue ){ expect( headerValue ).toBe( 'SNARF' ) done = true; }) waitsFor( function(){ return done }, 'the request to complete', ASYNC_TEST_TIMEOUT ) }) function someSecondsToPass(waitSecs) { function now(){ // IE8 doesn't have Date.now() return new Date().getTime(); } var waitStart = now(), waitMs = waitSecs * 1000; return function(){ return now() > (waitStart + waitMs); } } });
JavaScript
0.000001
@@ -3672,20 +3672,24 @@ var -done = false +countGotBack = 0 ;%0A%0A @@ -3798,16 +3798,18 @@ ders: %7B' +x- snarfu': @@ -3815,16 +3815,31 @@ :'SNARF' +, 'x-foo':'BAR' %7D%0A @@ -3839,24 +3839,25 @@ %0A %7D%0A +%0A ).onNo @@ -3861,16 +3861,18 @@ nNode( ' +x- snarfu', @@ -3896,32 +3896,40 @@ Value )%7B%0A +%0A + expect( header @@ -3965,19 +3965,161 @@ -done = true +countGotBack++;%0A %0A %7D).onNode( 'x-foo', function( headerValue )%7B%0A %0A expect( headerValue ).toBe( 'BAR' )%0A countGotBack++ ;%0A @@ -4127,16 +4127,22 @@ %7D) + %0A %0A @@ -4180,12 +4180,25 @@ urn -done +countGotBack == 2 %7D,
0ee747cafa8a97677f16a40871f0ce5e8b48f377
Fix user.addUnit method in client user service
src/user/user-model.js
src/user/user-model.js
import $ from '$'; import _ from 'lodash'; import loginModal from './login'; import changePasswordModal from './change-password'; export default /*@ngInject*/class user{ constructor($http,$localStorage,$window,$q,$uibModal, api){ this.api = api; this.$http = $http; this.$storage = $localStorage; this.$q = $q; this.$window = $window; this.$uibModal = $uibModal; this.data = null; this.username = $('body').attr('username'); this.init(); } check(value){ const config = { method: 'HEAD', url: 'api/users', params: {} }; config.params[this.username] = value; return this.$http(config); } get authenticated(){ return this.$storage._id && this.$storage.token ? true : false; } set authenticated(data){ this.$storage.token = data.token; this.$storage._id = data._id; this.$storage.role = data.role; this.api.setToken(data.token); } get _id(){ return this.$storage._id; } get token(){ return this.$storage.token; } get role(){ return this.$storage.role; } init(){ if(!this.authenticated){ return this.inauthenticate(); } return this.$http.get('api/users/'+this.$storage._id) .then( (res) => { this.data = res.data; return res; }, (e) => { this.inauthenticate(); return e; } ); } basicAuth(form){ const name = form[this.username]; const pass = form.password; if(!name || !pass){ throw Error('missing credentials'); } const str = this.$window.btoa(`${name}:${pass}`); return `basic ${str}`; } authenticate(form,init){ const authorization = this.basicAuth(form); const config = { method: 'GET', url: 'api/tokens/new', headers: {authorization} }; return this.$http(config) .then((res) => { this.authenticated = res.data; if(!init){ return res.data; } return this.init(); }); } inauthenticate(){ this.$storage.$reset(); this.data = null; this.api.token.value = null; } create(form){ return this.$http.post('api/users', form) .then((res) => { this.data = res.data; return res; }); } addUnit(id){ const included = _.includes(this.data.done,id); if(included){ return; } const item = { unit: id }; this.$http.post('api/users/'+this.data._id+'/done', item) .then((res) => { this.data.done.push(res.data); }); } complete(unit){ if(!this.authenticated){ return false; } return _.some(this.data.done,{unit: unit}); } requiresComplete(requires){ if(!this.authenticated){ return false; } return _.every(requires,function(val){ return _.some(this.data.done,{unit: val}); },this); } remove(){ return this.$http.delete('api/users/'+this.data._id) .then(() => this.inauthenticate()); } login(){ return this.$uibModal.open(loginModal); } changePassword(){ return this.$uibModal.open(changePasswordModal); } }
JavaScript
0.000004
@@ -2259,71 +2259,44 @@ -const included = _.includes(this.data.done,id);%0A if(included +if(_.some(this.data.done,%7Bunit: id%7D) )%7B%0A @@ -2359,33 +2359,67 @@ %7D;%0A -this.$http.post(' +const config = %7B%0A method: 'POST',%0A url: %60 api/user @@ -2412,34 +2412,34 @@ url: %60api/users/ -'+ +$%7B this.data._id+'/ @@ -2439,22 +2439,62 @@ ._id -+' +%7D /done -', item +%60,%0A data: item%0A %7D;%0A this.$http(config )%0A @@ -2799,16 +2799,24 @@ equires, + _.bind( function @@ -2882,16 +2882,17 @@ %7D,this) +) ;%0A %7D%0A
30e1b8a9086f18e7669525eb443daea31638a56f
Remove unique on studentId
src/user/user.model.js
src/user/user.model.js
var mongoose = require('mongoose-q')(require('mongoose')), Schema = mongoose.Schema, config = require('../../config/config'), jwt = require('jwt-simple'), moment = require('moment'); var userSchema = new Schema({ email: { type: String, required: 'you should provide an email', match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, "You should provide a valid email"], unique: true }, studentEmail: { type: String, match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, "You should provide a valid email"] }, firstname: { type: String }, lastname: { type: String }, createdAt: { type: Date, default: Date.now } }); userSchema.methods.createJwtToken = function () { var payload = { user: this, iat: moment().valueOf(), exp: moment().add(7, 'days').valueOf() }; return jwt.encode(payload, config.TOKEN_SECRET); }; userSchema.methods.authData = function () { return { user: this, token: this.createJwtToken() }; }; userSchema.statics.authenticate = function (email) { return User .findByEmail(email) .then(function (user) { if (!user) { // no existing user, create a new one and return it return new User({email: email}).saveQ(); } else { return user; } }) .then(function (user) { return user.authData(); }); }; userSchema.statics.findByEmail = function (email) { return User.findOne({email: email}).execQ(); }; var User = mongoose.model('User', userSchema); module.exports = User;
JavaScript
0
@@ -579,16 +579,38 @@ email%22%5D +,%0A unique: true %0A %7D,%0A @@ -1368,32 +1368,53 @@ new User(%7Bemail: + email, studentEmail: email%7D).saveQ()
f7245a6963dc7709a09246c275fb7bc8165389eb
Fix custom theme message handling
background/messages.js
background/messages.js
md.messages = ({storage: {defaults, state, set}, compilers, mathjax, webrequest}) => { return (req, sender, sendResponse) => { if (req.message === 'markdown') { var markdown = req.markdown if (state.content.mathjax) { var jax = mathjax() markdown = jax.tokenize(markdown) } var html = compilers[state.compiler].compile(markdown) if (state.content.mathjax) { html = jax.detokenize(html) } sendResponse({message: 'html', html}) } // popup else if (req.message === 'popup') { sendResponse(Object.assign({}, state, { options: state[state.compiler], description: compilers[state.compiler].description, compilers: Object.keys(compilers), themes: state.themes, })) } else if (req.message === 'popup.theme') { set({theme: req.theme}) notifyContent({message: 'theme', theme: req.theme}) sendResponse() } else if (req.message === 'popup.raw') { set({raw: req.raw}) notifyContent({message: 'raw', raw: req.raw}) sendResponse() } else if (req.message === 'popup.defaults') { var options = Object.assign({}, defaults) options.origins = state.origins set(options) notifyContent({message: 'reload'}) sendResponse() } else if (req.message === 'popup.compiler.name') { set({compiler: req.compiler}) notifyContent({message: 'reload'}) sendResponse() } else if (req.message === 'popup.compiler.options') { set({[req.compiler]: req.options}) notifyContent({message: 'reload'}) sendResponse() } else if (req.message === 'popup.content') { set({content: req.content}) notifyContent({message: 'reload'}) webrequest() sendResponse() } else if (req.message === 'popup.advanced') { // ff: opens up about:addons with openOptionsPage if (/Firefox/.test(navigator.userAgent)) { chrome.management.getSelf((extension) => { chrome.tabs.create({url: extension.optionsUrl}) }) } else { chrome.runtime.openOptionsPage() } sendResponse() } // options else if (req.message === 'options') { sendResponse({ origins: state.origins, header: state.header, match: state.match, themes: state.themes, }) } else if (req.message === 'options.header') { set({header: req.header}) sendResponse() } // origins else if (req.message === 'origin.add') { state.origins[req.origin] = { match: defaults.match, csp: false, encoding: '', } set({origins: state.origins}) sendResponse() } else if (req.message === 'origin.remove') { delete state.origins[req.origin] set({origins: state.origins}) webrequest() sendResponse() } else if (req.message === 'origin.update') { state.origins[req.origin] = req.options set({origins: state.origins}) webrequest() sendResponse() } // themes else if (req.message === 'themes') { set({themes: req.themes}) sendResponse() } } function notifyContent (req, res) { chrome.tabs.query({active: true, currentWindow: true}, (tabs) => { chrome.tabs.sendMessage(tabs[0].id, req, res) }) } }
JavaScript
0.000001
@@ -3181,24 +3181,728 @@ eq.themes%7D)%0A +%0A ;(() =%3E %7B%0A var defaults = chrome.runtime.getManifest().web_accessible_resources%0A .filter((file) =%3E file.indexOf('/themes/') === 0)%0A .map((file) =%3E file.replace(/%5C/themes%5C/(.*)%5C.css/, '$1'))%0A var custom = state.themes.map((%7Bname%7D) =%3E name)%0A var all = custom.concat(defaults)%0A%0A if (!all.includes(state.theme.name)) %7B%0A var theme = %7B%0A name: 'github',%0A url: chrome.runtime.getURL('/themes/github.css')%0A %7D%0A set(%7Btheme%7D)%0A %7D%0A else if (custom.includes(state.theme.name)) %7B%0A var theme = state.themes.find((%7Bname%7D) =%3E state.theme.name === name)%0A set(%7Btheme%7D)%0A %7D%0A %7D)()%0A%0A sendRe
dcd233a8a26cbb7dad9109e6e4ca2be31600c123
remove d from ddescribe
test/unit/directives/exampleSpec.js
test/unit/directives/exampleSpec.js
"use strict"; ddescribe('example directive', function() { var rootScope, compile, interpolate, directive; angular.module('exampleModule', []); beforeEach(module('exampleModule', function($compileProvider) { directive = $compileProvider.directive; })); beforeEach(inject(function($injector) { compile = $injector.get('$compile'); rootScope = $injector.get('$rootScope'); interpolate = $injector.get('$interpolate'); })); it('should inherit parent scope when property scope is not an object', function() { directive('example', function() { return { //scope: no scope property link: function(scope, element, attributes) { expect(scope.foo.bar).toBe(1); expect(scope.$eval('foo.bar')).toBe(1); scope.$apply('foo.bar = 42'); expect(rootScope.foo.bar).toBe(42); } } }); rootScope.$apply('foo.bar = 1'); compile('<one example>')(rootScope); }); it('must not inherit parent scope when property scope is an object', function() { directive('example', function() { return { scope: {}, link: function(scope, element, attributes) { expect(scope.foo).toBeUndefined(); expect(scope.$eval('foo.bar')).toBeUndefined(); scope.$apply('foo.bar = 42'); expect(rootScope.foo.bar).toBe(1); } } }); rootScope.$apply('foo.bar = 1'); compile('<one example>')(rootScope); }); it('@scopes', function() { var watchCalls = 0; directive('example', function() { return { scope: { //atScope: '@at-isolated', Error: Invalid isolate scope definition for directive example: @at-isolated atIsolated: '@isolated', atInterpolated: '@interpolated' }, link: function(scope, element, attributes) { expect(scope.atIsolated).toBeUndefined(); expect(scope.atInterpolated).toBeUndefined(); scope.$watch('atInterpolated', function(newVal, oldVal) { watchCalls++; if (1 == watchCalls) { expect(newVal).toBe(oldVal); expect(newVal).toBe('1'); } if (2 == watchCalls) { expect(oldVal).toBe('1'); expect(newVal).toBe('2'); } }); scope.$apply(); expect(watchCalls).toBe(1); expect(scope.atIsolated).toBe('iso.foo'); expect(scope.atInterpolated).toBe('1'); } } }); rootScope.$apply('iso.foo = 1'); compile('<one isolated="iso.foo" interpolated="{{iso.foo}}" example>')(rootScope); rootScope.$apply('iso.foo = 2'); expect(watchCalls).toBe(2); }); });
JavaScript
0.001854
@@ -8,17 +8,16 @@ rict%22;%0A%0A -d describe
04fa56d0c07b66c77d0fdd6cb4419efb890043eb
Improve structure extension errors
src/util/Structures.js
src/util/Structures.js
'use strict'; /** * Allows for the extension of built-in Discord.js structures that are instantiated by {@link DataStore DataStores}. */ class Structures { constructor() { throw new Error(`The ${this.constructor.name} class may not be instantiated.`); } /** * Retrieves a structure class. * @param {string} structure Name of the structure to retrieve * @returns {Function} */ static get(structure) { if (typeof structure === 'string') return structures[structure]; throw new TypeError(`"structure" argument must be a string (received ${typeof structure})`); } /** * Extends a structure. * <warn> Make sure to extend all structures before instantiating your client. * Extending after doing so may not work as expected. </warn> * @param {string} structure Name of the structure class to extend * @param {Function} extender Function that takes the base class to extend as its only parameter and returns the * extended class/prototype * @returns {Function} Extended class/prototype returned from the extender * @example * const { Structures } = require('discord.js'); * * Structures.extend('Guild', Guild => { * class CoolGuild extends Guild { * constructor(client, data) { * super(client, data); * this.cool = true; * } * } * * return CoolGuild; * }); */ static extend(structure, extender) { if (!structures[structure]) throw new RangeError(`"${structure}" is not a valid extensible structure.`); if (typeof extender !== 'function') { const received = `(received ${typeof extender})`; throw new TypeError( `"extender" argument must be a function that returns the extended structure class/prototype ${received}` ); } const extended = extender(structures[structure]); if (typeof extended !== 'function') { throw new TypeError('The extender function must return the extended structure class/prototype.'); } if (Object.getPrototypeOf(extended) !== structures[structure]) { throw new Error( 'The class/prototype returned from the extender function must extend the existing structure class/prototype.' ); } structures[structure] = extended; return extended; } } const structures = { GuildEmoji: require('../structures/GuildEmoji'), DMChannel: require('../structures/DMChannel'), TextChannel: require('../structures/TextChannel'), VoiceChannel: require('../structures/VoiceChannel'), CategoryChannel: require('../structures/CategoryChannel'), GuildChannel: require('../structures/GuildChannel'), GuildMember: require('../structures/GuildMember'), Guild: require('../structures/Guild'), Message: require('../structures/Message'), MessageReaction: require('../structures/MessageReaction'), Presence: require('../structures/Presence').Presence, ClientPresence: require('../structures/ClientPresence'), VoiceState: require('../structures/VoiceState'), Role: require('../structures/Role'), User: require('../structures/User'), }; module.exports = Structures;
JavaScript
0.000003
@@ -1759,16 +1759,17 @@ eceived%7D +. %60%0A @@ -1870,24 +1870,80 @@ unction') %7B%0A + const received = %60(received $%7Btypeof extended%7D)%60;%0A throw @@ -1956,17 +1956,17 @@ peError( -' +%60 The exte @@ -2029,18 +2029,30 @@ rototype -.' + $%7Breceived%7D.%60 );%0A %7D @@ -2052,24 +2052,39 @@ ;%0A %7D%0A +%0A -if ( +const prototype = Object.g @@ -2106,16 +2106,35 @@ xtended) +;%0A if (prototype !== str @@ -2151,24 +2151,133 @@ ructure%5D) %7B%0A + const received = %60$%7Bextended.name %7C%7C 'unnamed'%7D$%7Bprototype.name ? %60 extends $%7Bprototype.name%7D%60 : ''%7D%60;%0A throw @@ -2406,10 +2406,108 @@ type -. ' + +%0A %60 (received function $%7Breceived%7D; expected extension of $%7Bstructures%5Bstructure%5D.name%7D).%60 %0A
fecd37c28b46644e3dfcac43d9a0118bb12d69b0
Add DS damage to ret holy damage constants
src/parser/paladin/retribution/constants.js
src/parser/paladin/retribution/constants.js
import SPELLS from 'common/SPELLS'; // Based on spelldata for Avenging Wrath, Retribution(buff) and Inquisition // Avenging Wrath and Retribution also increase melee damage by 20% - this is added in their modules. export const ABILITIES_AFFECTED_BY_DAMAGE_INCREASES = [ SPELLS.CRUSADER_STRIKE, SPELLS.JUDGMENT_CAST, SPELLS.TEMPLARS_VERDICT_DAMAGE, SPELLS.BLADE_OF_JUSTICE, SPELLS.DIVINE_STORM_DAMAGE, SPELLS.EXECUTION_SENTENCE_TALENT, SPELLS.CONSECRATION_TALENT, SPELLS.ZEAL_DAMAGE, SPELLS.HAMMER_OF_WRATH_TALENT, SPELLS.WAKE_OF_ASHES_TALENT, SPELLS.JUSTICARS_VENGEANCE_TALENT, SPELLS.EYE_FOR_AN_EYE_TALENT, SPELLS.LIGHTS_DECREE_DAMAGE, SPELLS.EXPURGATION_DAMAGE, ]; // Stuff like Retribution mastery and Execution sentence increases damage done by these sources of holy damage export const ABILITIES_AFFECTED_BY_HOLY_DAMAGE_INCREASES = [ SPELLS.JUDGMENT_CAST, SPELLS.TEMPLARS_VERDICT_DAMAGE, SPELLS.EXECUTION_SENTENCE_TALENT, SPELLS.CONSECRATION_TALENT, SPELLS.ZEAL_DAMAGE, SPELLS.HAMMER_OF_WRATH_TALENT, SPELLS.WAKE_OF_ASHES_TALENT, SPELLS.JUSTICARS_VENGEANCE_TALENT, SPELLS.LIGHTS_DECREE_DAMAGE, SPELLS.EXPURGATION_DAMAGE, ];
JavaScript
0
@@ -912,32 +912,62 @@ VERDICT_DAMAGE,%0A + SPELLS.DIVINE_STORM_DAMAGE,%0A SPELLS.EXECUTI
b8c9f03f25f2154123fde3d5f21aa8b4902dff6a
fix benchmark
benchmark/benchmark.js
benchmark/benchmark.js
'use strict'; var Benchmark = require('benchmark'); var jcampBench = require('./jcamp'); var suite = new Benchmark.Suite(); suite .add('NMR 1H', jcampBench('indometacin/1h.dx')) .add('NMR 1H XY', jcampBench('indometacin/1h.dx', {xy:true})) .add('NMR 2D HMBC', jcampBench('indometacin/hmbc.dx',{fastParse:false})) .add('NMR 2D HMBC XY', jcampBench('indometacin/hmbc.dx', {xy:true})) .on('cycle', function (event) { console.log(String(event.target)); }) .run();
JavaScript
0.000002
@@ -305,26 +305,8 @@ .dx' -,%7BfastParse:false%7D ))%0A
9a1bb65e7c3eddbcd4b40be630f0ae7867b689fe
Move declaration of idx
javascript/word-count/words.js
javascript/word-count/words.js
function Words(sentence){ "use strict"; var idx; sentence = sentence.toLowerCase(); var wordMatches = sentence.match(/\w+/g); var result = {}; for(idx = 0 ; idx < wordMatches.length ; idx++) { result[wordMatches[idx]] = (result[wordMatches[idx]] || 0) + 1; } return { count: result }; }; module.exports = Words;
JavaScript
0.000001
@@ -41,21 +41,8 @@ t%22;%0A - var idx;%0A @@ -151,16 +151,20 @@ for( +var idx = 0
f7a4797cb8f0c1e8d87a8ab78d7a53f5ed9efaf9
Simplify algorithm
function.js
function.js
'use strict'; var traverse = require('./') , hasOwnProperty = Object.prototype.hasOwnProperty , $common = traverse.$common , collectNest = traverse.collectNest , wsSet = traverse.wsSet , move = traverse.move; module.exports = function (name) { var l, multi; name = String(name); l = name.length; multi = l > 1; return function (code) { code = String(code); return traverse(code, function (char, i, previous) { var j = 0; if (char !== name[j]) return $common; if (previous === '.') return $common; if (multi) { if (code[i] !== name[++j]) return $common; ++i; while (++j !== l) { if (code[i] !== name[j]) return $common; ++i; } } while (hasOwnProperty.call(wsSet, code[i])) ++i; if (code[i] !== '(') return $common; move(i + 1); return collectNest(); }); }; };
JavaScript
0.000236
@@ -261,17 +261,10 @@ ar l -, multi ;%0A + %09nam @@ -303,24 +303,8 @@ th;%0A -%09multi = l %3E 1;%0A %09ret @@ -503,81 +503,8 @@ on;%0A -%09%09%09if (multi) %7B%0A%09%09%09%09if (code%5Bi%5D !== name%5B++j%5D) return $common;%0A%09%09%09%09++i;%0A%09 %09%09%09w @@ -522,17 +522,16 @@ == l) %7B%0A -%09 %09%09%09%09if ( @@ -575,20 +575,13 @@ %09%09%09%09 -%09 ++i;%0A -%09%09%09%09%7D%0A %09%09%09%7D
603b4a88c2d8a78cd2350614b937a6016fb6f9be
remove "log_path"
benchmark/bootstrap.js
benchmark/bootstrap.js
#!/usr/bin/env node const child_process = require('child_process'); const fs = require('fs'); const path = require('path'); const os = require('os'); const chalk = require('chalk'); const testCases = require('./cases'); const IPERF_PATH = path.join(__dirname, 'iperf.sh'); const SEC_PER_CASE = 5; function makeConfs(presets) { const common = { "log_path": "/dev/null", "log_level": "error" }; const server = { "host": "localhost", "port": 1082, "key": "JJ9,$!.!sRG==v7$", "presets": presets, // "transport": { // "name": "tls", // "params": { // "key": "key.pem", // "cert": "cert.pem" // } // } }; const clientConf = Object.assign({ "host": "127.0.0.1", "port": 1081, "servers": [ Object.assign({}, server, { "enabled": true, "presets": [{ "name": "tunnel", "params": { "host": "127.0.0.1", "port": 1083 } }].concat(server.presets) }) ] }, common); const serverConf = Object.assign({}, server, common); return [clientConf, serverConf]; } function writeConfs(caseId, presets) { const [clientConf, serverConf] = makeConfs(presets); const clientJson = path.join(__dirname, `jsons/case-${caseId}-client.json`); const serverJson = path.join(__dirname, `jsons/case-${caseId}-server.json`); fs.writeFileSync(clientJson, JSON.stringify(clientConf, null, ' ')); fs.writeFileSync(serverJson, JSON.stringify(serverConf, null, ' ')); return [clientJson, serverJson]; } function parseStdout(stdout) { const matches = stdout.match(/\[SUM].*sec/g); if (matches === null) { console.error(stdout); } return matches.slice(-2).map((line) => { const [interval, transfer, bitrate] = line.match(/\d+[.\d\-\s]+\w+[\/\w]+/g); return {interval, transfer, bitrate}; }); } function convertTransferToKBytes(transfer) { const [num, unit] = transfer.split(' '); const factor = { 'GBytes': 1024 * 1024, 'MBytes': 1024, 'KBytes': 1 }[unit]; return num * factor; } function printSystemConf() { console.log(chalk.bold.underline('Operating System:')); const osParams = [ ['cpu', os.cpus()[0].model], ['cores', os.cpus().length], ['memory', os.totalmem()], ['type', os.type()], ['platform', os.platform()], ['arch', os.arch()], ['release', os.release()] ]; for (const [key, value] of osParams) { console.log('%s %s', key.padEnd(15), value); } console.log(''); console.log(chalk.bold.underline('Node.js Versions:')); for (const [key, value] of Object.entries(process.versions)) { console.log('%s %s', key.padEnd(15), value); } console.log(''); } function run(cases) { const results = []; for (let i = 0; i < cases.length; ++i) { const presets = cases[i]; const [clientJson, serverJson] = writeConfs(i, presets); try { const stdout = child_process.execFileSync( IPERF_PATH, [clientJson, serverJson, SEC_PER_CASE.toString()], {encoding: 'utf-8'} ); const [a, b] = parseStdout(stdout); console.log(`------------ ${chalk.green(`Test Case ${i}`)} ----------------`); console.log(JSON.stringify(presets)); console.log('Interval Transfer Bitrate'); console.log(`${a.interval} ${a.transfer} ${a.bitrate} sender`); console.log(`${b.interval} ${b.transfer} ${b.bitrate} receiver`); console.log('-----------------------------------------'); console.log(''); const conv = convertTransferToKBytes; results.push({ id: i, transfers: [a.transfer, b.transfer], recvTransfer: conv(b.transfer), conf: JSON.stringify(presets) }); } catch (err) { console.error(err); } } return results; } function summary(results) { const sorted = [].concat(results).sort((a, b) => b.recvTransfer - a.recvTransfer); console.log('(ranking):'); console.log(''); for (let i = 0; i < sorted.length; ++i) { const {id, transfers, conf} = sorted[i]; console.log(`${(i + 1).toString().padStart(2)}: Test Case ${id}, Transfer=[${transfers.join(', ')}], ${conf}`); } console.log(''); } printSystemConf(); console.log('running tests...'); console.log(''); summary(run(testCases));
JavaScript
0.000001
@@ -345,37 +345,8 @@ = %7B%0A - %22log_path%22: %22/dev/null%22,%0A
01ab34f6a1db78d05154395fbc94910418de1873
allow comments with up to 500 chars
src/util/validation.js
src/util/validation.js
const isInt = (v) => { return (typeof v) === "number" && (isFinite(v)) && (Math.floor(v)) === v; }; const entryForm = (data) => { var errors, h, l, ref; errors = {}; if (data == null) { errors._error = "Ungültige Daten"; return errors; } if (data.title == null) { errors.title = 'Pflichtangabe'; } else { if (!((l = data.title.length) <= 40)) { if (errors.title == null) { errors.title = "Zu langer Titel: " + l + " statt max. 40 Zeichen"; } } if (!((l = data.title.length) >= 3)) { if (errors.title == null) { errors.title = "Zu kurzer Titel: " + l + " von mind. 3 Zeichen"; } } } if (data.description == null) { errors.description = 'Pflichtangabe'; } else { if (!((l = data.description.length) <= 250)) { if (errors.description == null) { errors.description = "Zu lange Beschreibung: " + l + " statt max. 250 Zeichen"; } } if (!((l = data.description.length) >= 10)) { if (errors.description == null) { errors.description = "Zu wenig Text: " + l + " von mind. 10 Zeichen"; } } } if (data.lat == null) { errors.lat = 'Pflichtangabe'; } else { if (!(data.lat * 1)) { errors.lat = 'Ungültiger Breitengrad'; } } if (data.lng == null) { errors.lng = 'Pflichtangabe'; } else { if (!(data.lng * 1)) { errors.lng = 'Ungültiger Längengrad'; } } if (data.category == null) { errors.category = 'Pflichtangabe'; } else { if ((typeof data.category) !== "string") { errors.category = 'Ungültige Kategorie'; } } if (data.license == null) { errors.license = 'Lizenzzustimmung ist nötig'; } else { if ((typeof data.license) !== "boolean") { errors.license = 'Ungültige Zustimmung'; } else if (data.license === false) { errors.license = 'Lizenzzustimmung ist nötig'; } } if ((h = data.homepage) != null) { if (!((h.indexOf("http://") === 0) || (h.indexOf("https://") === 0))) { errors.homepage = 'Ungültige URL ("http://" oder "https://" fehlt)'; } if (((ref = (h = data.homepage)) != null ? ref.length : void 0) < 9) { errors.homepage = 'Ungültige URL'; } } return errors; }; const ratingForm = (data) => { var h, l, ref; var errors = {}; if (data == null) { errors._error = "Ungültige Daten"; return errors; } if (data.title == null) { errors.title = 'Pflichtangabe'; } else { if (!((l = data.title.length) <= 40)) { if (errors.title == null) { errors.title = "Zu langer Titel: " + l + " statt max. 40 Zeichen"; } } if (!((l = data.title.length) >= 3)) { if (errors.title == null) { errors.title = "Zu kurzer Titel: " + l + " von mind. 3 Zeichen"; } } } if (data.context == null) { errors.context = 'Pflichtangabe'; } else { if ((typeof data.context) !== "string") { errors.context = 'Ungültiger Bewertungskontext'; } } if (data.value == null) { errors.value = 'Pflichtangabe'; } else { if (data.value < -1 || data.value > 2) { errors.value = 'Ungültige Bewertung'; } } if (data.comment == null) { errors.comment = 'Pflichtangabe'; } else { if (!((l = data.comment.length) <= 160)) { if (errors.comment == null) { errors.comment = "Zu langer Kommentar: " + l + " statt max. 160 Zeichen"; } } if (!((l = data.comment.length) >= 10)) { if (errors.comment == null) { errors.comment = "Zu wenig Text: " + l + " von mind. 10 Zeichen"; } } } return errors; } module.exports = { entryForm, ratingForm };
JavaScript
0
@@ -3290,18 +3290,18 @@ gth) %3C= -16 +50 0)) %7B%0A @@ -3406,10 +3406,10 @@ ax. -16 +50 0 Ze
7540a18814838e06ea2b7c2ea72835ba13db7157
Stop link events misfiring, better selector.
carousel.js
carousel.js
// // BASE Carousel // -------------------------------------------------- // An ultra-light, customisable, 'just-works' carousel script (function($) { "use strict"; $.carousel = function (element, options) { var defaults = { slide: 'img', speed: 5000, transition: 'fade', transitionSpeed: 2000, easing: 'ease', firstSlide: 1, pauseOnHover: true, cssAnimations: true, fallback: true, allowJump: true, // callbacks onSlide: function () {}, onNext: function () {}, onPrev: function () {}, onJump: function () {}, onStart: function () {}, onPause: function () {}, }, plugin = this, $element = $(element), interval; // add the basic css classes plugin.create = function () { // basic css structure $element.addClass('carousel'); $element.addClass('transition-' + plugin.settings.transition); // transition class $element.find(plugin.settings.slide).addClass('slide'); // slide class // set first slide plugin.slide(plugin.settings.firstSlide); if (plugin.settings.speed) { plugin.run(); } }; // take slider to a specific slide number plugin.slide = function (e, s, m) { s = typeof s !== 'undefined' ? s : plugin.settings.transitionSpeed; // speed default m = typeof m !== 'undefined' ? m : plugin.settings.easing; // transition default var i = $element.find('.active').index('.slide') + 1, n = $element.find('.slide').length, $to = $element.find(plugin.settings.slide + ':nth-child(' + e + ')'), $prev = ($to.prev('.slide').length === 0) ? $element.find('.slide:last') : $to.prev('.slide'), $next = ($to.next('.slide').length === 0) ? $element.find('.slide:first') : $to.next('.slide'), animate = (plugin.settings.transition === 'slide') ? 'left' : 'opacity'; if (e > n) { return false; } // prevent going to non-existant slide if (plugin.settings.cssAnimations) { $element.find('.slide').css('transition', animate + ' ' + (s / 1000) + 's ' + m); } if (i > e && !(e === 1 && i === n) ) { $element.addClass('backwards'); } else { $element.removeClass('backwards'); } $element.find('.slide').removeClass('left active right'); $to.addClass('active'); $prev.addClass('left'); $next.addClass('right'); if ( $('a[data-carousel="jump"]').length > 0 ) { // check if paged nav exits $('a[data-carousel="jump"]').each( function() { if (parseInt($(this).attr('href').replace('#','')) === e) { $(this).addClass('active'); } else { $(this).removeClass('active'); } }); } if (plugin.settings.fallback) { carouselAnimate(e, s); } // fallback animation plugin.settings.onSlide(e, s); // callback }; // call next slide from current slide plugin.next = function () { var next = $element.find('.active').next('.slide').length, e = (next === 0) ? 0 : $element.find('.active').index('.slide') + 1; plugin.slide(e + 1); plugin.settings.onNext(e); // callback }; // call previous slide from current slide plugin.prev = function () { var prev = $element.find('.active').prev('.slide').length, e = (prev === 0) ? $element.find('.slide:last').index('.slide') + 1 : $element.find('.active').index('.slide'); plugin.slide(e); plugin.settings.onPrev(e); // callback }; // move to a non-sequential slide plugin.jump = function (e) { plugin.pause(); if (plugin.settings.transition === 'slide') { var index = $element.find('.active').index('.slide') + 1, // current position d = (e >= index), // direction steps = (d) ? (e - index) : (index - e), // slides to travel speed = plugin.settings.transitionSpeed / steps, // speed fraction step = 1, first = true; (function change() { var next = (d) ? (index + step) : (index - step), easing = (first) ? 'ease-in' : (steps === 1) ? 'ease-out' : 'linear'; plugin.slide(next, speed, easing); steps--; step++; first = false; interval = setTimeout(change, speed); if (steps <= 0) { clearTimeout(interval); } })(); } else { plugin.slide(e); } plugin.settings.onJump(e); // callback }; plugin.run = function () { // run carousel interval = setInterval(function () { plugin.next(); }, plugin.settings.speed); plugin.settings.onStart(); // callback }; plugin.pause = function () { clearInterval(interval); plugin.settings.onPause(); // callback }; var pauseOnHover = function() { if (!plugin.settings.pauseOnHover) { return false; } $element.hover(function () { plugin.pause(); }, function() { plugin.run(); }); }; var navigation = function() { $('a[data-carousel!=""]').click( function(e) { plugin.pause(); var action = $(this).attr('data-carousel'), to = $(this).attr('href').replace('#',''); if (action === 'jump') { if (plugin.settings.allowJump) { $('a[data-carousel="jump"]').removeClass('active'); $(this).addClass('active'); plugin.jump(to); } } else { plugin[action](); } e.preventDefault(); }); }; // javascript animation fallbacks var carouselAnimate = function (e, s) { if ((!Modernizr.cssanimations || !plugin.settings.cssAnimations) && plugin.settings.transition === 'slide') { slideAnimation(s); } else if ((!Modernizr.cssanimations || !plugin.settings.cssAnimations) && plugin.settings.transition === 'fade') { fadeAnimation(s); } }; var slideAnimation = function (speed) { $element.find('.slide').stop(true, true); // stop any running animations $element.find('.active').animate({ left: '0%' }, speed); $element.find('.left').animate({ left: '-100%' }, speed); $element.find('.right').animate({ left: '100%' }, speed); }; var fadeAnimation = function (speed) { $element.find('.slide').stop(true, true); // stop any running animations $element.find('.active').animate({ opacity: '1' }, speed); $element.find('.left').animate({ opacity: '0' }, speed); $element.find('.right').animate({ opacity: '0' }, speed); }; // external access: element.data('carousel').settings.propertyName plugin.settings = {}; plugin.init = function() { plugin.settings = $.extend({}, defaults, options); plugin.create(); // private methods pauseOnHover(); navigation(); }; plugin.init(); }; // add to the jQuery object $.fn.carousel = function (options) { return this.each(function () { if (undefined === $(this).data('carousel')) { var plugin = new $.carousel(this, options); // element.data('carousel').publicMethod(arg1, arg2, ... argn) // element.data('carousel').settings.propertyName $(this).data('carousel', plugin); } }); }; })(jQuery);
JavaScript
0
@@ -5997,12 +5997,8 @@ usel -!=%22%22 %5D'). @@ -8620,8 +8620,9 @@ jQuery); +%0A
95b5be0cda1d4649b924755c8b3c6c575af0ce33
Make the smoke-test timeout two minutes longer
tests/acceptance/smoke-test-slow.js
tests/acceptance/smoke-test-slow.js
'use strict'; var tmp = require('../helpers/tmp'); var conf = require('../helpers/conf'); var Promise = require('../../lib/ext/promise'); var exec = Promise.denodeify(require('child_process').exec); var path = require('path'); var rimraf = Promise.denodeify(require('rimraf')); var fs = require('fs'); var crypto = require('crypto'); var assert = require('assert'); var walkSync = require('walk-sync'); var appName = 'some-cool-app'; describe('Acceptance: smoke-test', function() { before(conf.setup); after(conf.restore); beforeEach(function() { tmp.setup('./tmp'); process.chdir('./tmp'); }); afterEach(function() { tmp.teardown('./tmp'); }); it('ember new foo, clean from scratch', function() { console.log(' running the slow end-to-end it will take some time'); this.timeout(360000); var appsECLIPath = path.join(appName, 'node_modules', 'ember-cli'); return exec('pwd').then(function(pwd) { return exec(path.join('..', 'bin', 'ember') + ' new ' + appName).then(function() { return rimraf(appsECLIPath).then(function() { fs.symlinkSync(path.join(pwd, '..'), appsECLIPath); process.chdir(appName); return exec(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember') + ' test').then(console.log); }); }); }).finally(function() { console.log('done!'); }); }); it('ember new foo, build production and verify fingerprint', function() { console.log(' running the slow fingerprint it will take some time'); this.timeout(360000); var appsECLIPath = path.join(appName, 'node_modules', 'ember-cli'); var globalPwd = null; return exec('pwd').then(function(pwd) { globalPwd = pwd; return exec(path.join('..', 'bin', 'ember') + ' new ' + appName); }).then(function() { return rimraf(appsECLIPath); }).then(function() { fs.symlinkSync(path.join(globalPwd, '..'), appsECLIPath); process.chdir(appName); return exec(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember') + ' build --environment=production'); }).then(function() { var dirPath = path.join('.', 'dist', 'assets'); var dir = fs.readdirSync(dirPath); var files = []; dir.forEach(function (filepath) { if (filepath === '.gitkeep') { return; } files.push(filepath); var file = fs.readFileSync(path.join(dirPath, filepath), { encoding: 'utf8' }); var md5 = crypto.createHash('md5'); md5.update(file); var hex = md5.digest('hex'); var possibleNames = [appName + '-' + hex + '.js', appName + '-' + hex + '.css', 'vendor-' + hex + '.css']; assert(possibleNames.indexOf(filepath) > -1); }); var indexHtml = fs.readFileSync(path.join('.', 'dist', 'index.html'), { encoding: 'utf8' }); files.forEach(function (filename) { assert(indexHtml.indexOf(filename) > -1); }); }).finally(function() { console.log('done'); }); }); it('ember new foo, build development, and verify generated files', function() { console.log(' running the slow build tests'); this.timeout(360000); var appsECLIPath = path.join(appName, 'node_modules', 'ember-cli'); var globalPwd = null; return exec('pwd').then(function(pwd) { globalPwd = pwd; return exec(path.join('..', 'bin', 'ember') + ' new ' + appName); }).then(function() { return rimraf(appsECLIPath); }).then(function() { fs.symlinkSync(path.join(globalPwd, '..'), appsECLIPath); process.chdir(appName); return exec(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember') + ' build'); }).then(function() { var dirPath = path.join('.', 'dist'); var paths = walkSync(dirPath); assert(paths.length < 20); }).finally(function() { console.log('done'); }); }); });
JavaScript
0.000001
@@ -839,34 +839,34 @@ this.timeout( -36 +45 0000);%0A%0A var
12f4dec66ecc7f1577874a5c2361cc6cc7735d11
Reset completed progress when new upload is started
src/scripts/upload/upload.js
src/scripts/upload/upload.js
import scitran from '../utils/scitran'; import bids from '../utils/bids'; import uploads from '../utils/upload'; import files from '../utils/files'; import config from '../../../config'; import diff from './diff'; export default { // progress -------------------------------------------------------------------------- /** * Current Project Id */ currentProjectId: null, /** * Current Files * * An array of file names that are currently being uploaded. */ currentFiles: [], /** * Total */ total: 0, /** * Completed */ completed: 0, // upload ---------------------------------------------------------------------------- /** * Handle Upload Response * * A generic response handler for all upload * related requests. */ handleUploadResponse (err, res, callback) { let name = res.req._data.name; this.progressEnd(name); if (err) { this.error(err, res.req); } else { callback(err, res); } }, /** * Upload File * * Pushes upload details into an upload queue. */ uploadFile (level, id, file, tag) { let url = config.scitran.url + level + '/' + id + '/files'; uploads.add({url: url, file: file, tags: [tag], progressStart: this.progressStart, progressEnd: this.progressEnd, error: this.error}); }, /** * Upload * * Takes an entire bids file tree and and file count * and recurses through and uploads all the files. * Additionally takes a progress callback that gets * updated at the start and end of every file or * folder upload request and an error callback. */ upload (userId, fileTree, validation, summary, count, progress, error) { this.total = count; this.currentProjectId = null; this.progressStart = (filename) => { this.currentFiles.push(filename); progress({type: 'upload', total: this.total, completed: this.completed, currentFiles: this.currentFiles}); }; this.progressEnd = (filename) => { let index = this.currentFiles.indexOf(filename); this.currentFiles.splice(index, 1); this.completed++; progress({type: 'upload', total: this.total, completed: this.completed, currentFiles: this.currentFiles}, this.currentProjectId); }; let existingProject = null; scitran.getProjects({authenticate: true}, (projects) => { for (let project of projects) { if (project.label === fileTree[0].name && project.group === userId) { project.children = project.files; existingProject = project; break; } } if (existingProject) { this.progressEnd(); this.currentProjectId = existingProject._id; bids.getDatasetTree(existingProject, (oldDataset) => { let newDataset = fileTree[0]; diff.datasets(newDataset.children, oldDataset[0].children, (subjectUploads, completedFiles) => { this.completed = this.completed + completedFiles.length; progress({total: this.total, completed: this.completed, currentFiles: this.currentFiles, resumeStart: this.completed}); this.uploadSubjects(newDataset.name, subjectUploads, this.currentProjectId); }); }, {}, (resumeProgress) => { resumeProgress.type = 'resume'; progress(resumeProgress); }); } else { let body = { label: fileTree[0].name, group: userId }; scitran.createProject(body, (err, res) => { this.handleUploadResponse(err, res, () => { let projectId = res.body._id; scitran.addTag('projects', projectId, 'incomplete', () => { this.uploadSubjects(fileTree[0].name, fileTree[0].children, projectId, validation, summary); }); }); }); } }); }, /** * Upload Subjects * */ uploadSubjects (datasetName, subjects, projectId, validation, summary) { this.currentProjectId = projectId; for (let subject of subjects) { if (subject.children) { if (subject.ignore) { this.uploadSessions(subject.children, projectId, subject._id); } else { this.progressStart(subject.name); scitran.createSubject(projectId, subject.name, (err, res) => { this.handleUploadResponse(err, res, () => { let subjectId = res.body._id; this.uploadSessions(subject.children, projectId, subjectId); }); }); } } else { if (subject.name === 'dataset_description.json') { files.read(subject, (contents) => { let description = JSON.parse(contents); description.Name = datasetName; let authors = []; if (description.hasOwnProperty('Authors')) { for (let i = 0; i < description.Authors.length; i++) { let author = description.Authors[i]; authors.push({name: author, ORCIDID: ''}); } } scitran.updateProject(projectId, {metadata: {authors, validation, summary}}, () => { let file = new File([JSON.stringify(description)], 'dataset_description.json', {type: 'application/json'}); this.uploadFile('projects', projectId, file, 'project'); }); }); } else { this.uploadFile('projects', projectId, subject, 'project'); } } } }, /** * Upload Sessions * */ uploadSessions (sessions, projectId, subjectId) { for (let session of sessions) { if (session.children) { if (session.ignore) { this.uploadModalities(session.children, session._id); } else { this.progressStart(session.name); scitran.createSession(projectId, subjectId, session.name, (err, res) => { this.handleUploadResponse(err, res, () => { this.uploadModalities(session.children, res.body._id); }); }); } } else { this.uploadFile('sessions', subjectId, session, 'subject'); } } }, /** * Upload Modalities * */ uploadModalities (modalities, subjectId) { for (let modality of modalities) { if (modality.children) { if (modality.ignore) { this.uploadAcquisitions(modality.children, modality._id); } else { this.progressStart(modality.name); scitran.createModality(subjectId, modality.name, (err, res) => { this.handleUploadResponse(err, res, () => { let modalityId = res.body._id; this.uploadAcquisitions(modality.children, modalityId); }); }); } } else { this.uploadFile('sessions', subjectId, modality, 'session'); } } }, /** * Upload Acquisitions * */ uploadAcquisitions (acquisitions, modalityId) { for (let acquisition of acquisitions) { this.uploadFile('acquisitions', modalityId, acquisition, 'modality'); } } };
JavaScript
0
@@ -1848,16 +1848,44 @@ count;%0A + this.completed = 0;%0A
06d69f8a87f7d78125e142c9deacf6ae8bed6409
Change that was unintended to implement with the data was removed
src/programs/state/massachusetts/housing.js
src/programs/state/massachusetts/housing.js
import { percentPovertyLevel, percentStateMedianIncome } from '../../../helpers/helperFunctions'; function getHousingEligibility(client) { let percentPov = parseInt(percentStateMedianIncome(parseInt(client.annualIncome), client.householdSize)); if (client.annualIncome == 0 || percentPov < 70) { return {result: 'good', details: 'All good!', benefitValue: 800}; } else if (percentPov > 70 && percentPov < 80) { return {result: 'information', details: `Your income puts you at ${percentPov.toFixed()}% of the federal poverty level, which is close to the 80% limit.`, benefitValue: 800}; } else { return {result: 'warning', details: `Your income puts you at ${percentPov.toFixed()}% of the federal poverty level, which is above the 80% limit.`, benefitValue: 0}; } } export {getHousingEligibility};
JavaScript
0
@@ -175,33 +175,28 @@ (percent -StateMedianIncome +PovertyLevel (parseIn
b460bc097c3d3705e68dac0fd83d34f45f32eb72
rename setState, replaceState methods (cherry picked from commit 30836f7)
src/connectSlicedState.js
src/connectSlicedState.js
import React from 'react'; import {connect} from 'react-redux'; import get from 'lodash/get'; import setStateByPath from './setStateByPath'; import replaceStateByPath from './replaceStateByPath'; /** * Connect provided component to `path` part of the redux state * @param path * @returns {Function} */ export default function connectSlicedState(path) { return function (WrappedComponent) { return connect( state => state, dispatch => ({dispatch}), (state, {dispatch}, props) => { const slicedState = get(state, path); return { ...props, state: slicedState, setState: newState => dispatch(setStateByPath(path, newState)), replaceState: newState => dispatch(replaceStateByPath(path, newState)), }; } )(WrappedComponent); }; }
JavaScript
0
@@ -347,16 +347,78 @@ ate(path +, setStateName = 'setState', replaceStateName = 'replaceState' ) %7B%0A re @@ -687,24 +687,25 @@ +%5B setState : newSta @@ -692,24 +692,29 @@ %5BsetState +Name%5D : newState = @@ -767,16 +767,17 @@ +%5B replaceS @@ -780,16 +780,21 @@ aceState +Name%5D : newSta
db40a325267ed27811b66771277ef12a1eec0639
add tests on internals.loadMoreItems
app/stores/__tests__/product-store-test.js
app/stores/__tests__/product-store-test.js
var ProductStore = require('../product-store'); var assert = require('chai').assert; var sinon = require('sinon'); describe('ProductStore', function() { describe('internals.initProducts', function() { before(function() { this.products = ProductStore.__get__('products'); this.user = ProductStore.__get__('user'); ProductStore.__set__('products', { fetch: () => true, trigger: sinon.stub() }); ProductStore.__set__('user', { fetch: () => true }) }); after(function() { ProductStore.__set__('products', this.products); ProductStore.__set__('user', this.user); }); it('should return a promise', function() { var internals = ProductStore.internals; return internals.initProducts(); }); }); describe('getItemsForProduct', function() { it('returns an items collection', function() { }); it('updates the items collection filter config', function() { }); }); });
JavaScript
0
@@ -1,12 +1,66 @@ +var $ = require('jquery');%0Avar _ = require('lodash');%0A var ProductS @@ -91,24 +91,60 @@ ct-store');%0A +var Backbone = require('backdash');%0A var assert = @@ -886,16 +886,962 @@ %0A %7D);%0A%0A + describe('internals.loadMoreItems', function() %7B%0A beforeEach(function() %7B%0A this.collection = new Backbone.Collection();%0A this.collection.config = new Backbone.Model(%7B%0A status: 'backlog',%0A offset: 0%0A %7D);%0A %7D);%0A%0A it('should return a promise', function() %7B%0A var spy = sinon.spy(this.collection, 'trigger');%0A%0A this.collection.fetch = () =%3E %7B%0A return $.Deferred().resolve(%7Blength: 0%7D);%0A %7D;%0A%0A ProductStore.internals.loadMoreItems(this.collection);%0A sinon.assert.calledOnce(spy);%0A %7D);%0A%0A it('should emit a change event and pass an object containing the response item count', function() %7B%0A var spy = sinon.spy(this.collection, 'trigger');%0A%0A this.collection.fetch = () =%3E %7B%0A return $.Deferred().resolve(%7Blength: 16%7D);%0A %7D;%0A%0A ProductStore.internals.loadMoreItems(this.collection);%0A sinon.assert.calledWith(spy, 'change', %7Bcount: 16%7D);%0A %7D);%0A %7D);%0A %0A descr @@ -2010,13 +2010,9 @@ ) %7B%0A - %0A + @@ -2021,12 +2021,11 @@ ;%0A %7D);%0A + %7D); -%0A
15026f9c963e32a6fa44272df030f057b4fd48c1
Fix ObjectUtil.keyByValue
src/scripts/lib/client/utils/object-util.js
src/scripts/lib/client/utils/object-util.js
module.exports = class ObjectUtil { // Retrieves key for given value (if any) in object static keyByValue(object, target) { if(!'lookup' in object) { lookup = {} for(var key in object) { if(object.hasOwnProperty(key)) { lookup[value] = object[key] } } object.lookup = lookup } return object.lookup[target] } }
JavaScript
0.000096
@@ -130,16 +130,17 @@ if(! +( 'lookup' @@ -142,32 +142,33 @@ okup' in object) +) %7B%0A lookup @@ -156,24 +156,30 @@ t)) %7B%0A +const lookup = %7B%7D%0A @@ -264,21 +264,17 @@ -lookup%5B +var value -%5D = o @@ -284,16 +284,46 @@ ct%5Bkey%5D%0A + lookup%5Bvalue%5D = key%0A
04ff06c494d36e606e6ae4e5e98d2d038b315360
remove some unnecessary style for IE
jquery.textarea-highlighter.js
jquery.textarea-highlighter.js
/** * jquery.textareaHighlighter.js 0.1.0 * Plugin for highlighting text in textarea. * * [email protected] * MIT license. http://opensource.org/licenses/MIT */ ;(function ( $, window, document, undefined ) { "use strict"; var browser = (function(){ var userAgent = navigator.userAgent, msie = /(msie|trident)/i.test( userAgent ), chrome = /chrome/i.test( userAgent ), firefox = /firefox/i.test( userAgent ), safari = /safari/i.test( userAgent ) && !chrome, iphone = /iphone/i.test( userAgent ); if( msie ){ return { msie: true }; } if( chrome ){ return { chrome: true }; } if( firefox ){ return { firefox: true }; } if( iphone ){ return { iphone: true }; } if( safari ){ return { safari: true }; } return { msie : false, chrome : false, firefox: false, safari : false, iphone : false }; }()); /** * * PLUGIN CORE * */ var pluginName = "textareaHighlighter", defaults = { matches: [ {'className': '', 'words': []} ], isDebug: false }; // constructor function Plugin ( element, options ) { this.element = element; this.$element = $(this.element); this.settings = $.extend( {}, defaults, options ); this._defaults = defaults; this._name = pluginName; // textarea style this.style = { backgroundColor: this.$element.css('background-color'), paddingTop : parseInt( this.$element.css('padding-top'), 10 ), paddingRight : parseInt( this.$element.css('padding-right'), 10 ), paddingBottom: parseInt( this.$element.css('padding-bottom'), 10 ), paddingLeft : parseInt( this.$element.css('padding-left'), 10 ), borderTop : parseInt( this.$element.css('border-top-width'), 10 ), borderRight : parseInt( this.$element.css('border-right-width'), 10 ), borderBottom : parseInt( this.$element.css('border-bottom-width'), 10 ), borderLeft : parseInt( this.$element.css('border-left-width'), 10 ), lineHeight : this.$element.css('line-height') }; this.widthExtra = this.style.paddingLeft + this.style.paddingRight + this.style.borderLeft + this.style.borderRight; this.style.paddingTop += this.style.borderTop; this.style.paddingLeft += this.style.borderLeft; // Hack for firefox, some how width needs to be 2px smallet then the textarea // and padding-left needs to be added 1px if( browser.firefox ){ this.widthExtra += 2; this.style.paddingLeft += 1; } // Hack for iphone, some how in iphone it adds 3px to textarea padding if( browser.iphone ){ this.style.paddingRight += 3; this.style.paddingLeft += 3; this.widthExtra += 6; } if( browser.msie ){ this.style.paddingTop += -1; this.style.paddingLeft += 1; this.style.paddingBottom += 2; } this.init(); } Plugin.prototype = { init: function () { var _this = this, $this = this.$element, $wrapDiv = $(document.createElement('div')).addClass('textarea-wrap'), $backgroundDiv = $(document.createElement('div')), lastUpdate = new Date().getTime(); $wrapDiv.css({ 'position' : 'relative', 'word-wrap' : 'break-word', 'word-break' : 'break-all', 'margin' : 0, 'padding-right': _this.style.paddingLeft + _this.style.paddingRight + _this.style.borderLeft + _this.style.borderRight + 'px' }); $backgroundDiv.addClass('background-div').css({ 'height': 0, 'width' : 0, 'color' : ( _this.settings.isDebug ) ? '#f00' : 'transparent', 'background-color': ( _this.settings.isDebug ) ? '#fee' : _this.style.backgroundColor, 'line-height' : _this.style.lineHeight, 'padding-top' : _this.style.paddingTop, 'padding-right' : _this.style.paddingRight, 'padding-bottom': _this.style.paddingBottom, 'padding-left' : _this.style.paddingLeft, 'position' : 'absolute', 'overflow' : 'auto', 'white-space' : 'pre-wrap', // this is for IE 'border' : '0px', 'text-decoration': 'none' }); $this.css({ 'color' : ( _this.settings.isDebug ) ? 'rgba(0,0,0,0.5)' : 'inherit', 'position' : 'relative', 'background': 'transparent' }); $this .on('scroll', function(){ $backgroundDiv.scrollTop( $this.scrollTop() ); }) .on('change keyup keydown', function(e){ // if arrow keys, don't do anything if (e.keyCode === 37 || e.keyCode === 38 || e.keyCode === 39 || e.keyCode === 40) { return; } // check for last update, this is for performace if (new Date().getTime() - lastUpdate < 30) { return; } var textareaText = $(document.createElement('div')).text( $this.val() ).html(), key, ruleTextList, matchText, spanText, i, imax, j, jmax; for (i = 0, imax = _this.settings.matches.length; i < imax; i++) { for (j = 0, jmax = _this.settings.matches[i].words.length; j < jmax; j++) { // get word to match matchText = _this.settings.matches[i].words[j]; // check if word exists in input text if( textareaText.indexOf( matchText ) !== -1 ){ spanText = '<span class="'+ _this.settings.matches[i].className +'">'+ matchText +'</span>'; textareaText = textareaText.replace( new RegExp( _escapeRegExp( matchText ), 'g'), spanText ); } } } $backgroundDiv.html( textareaText ); resize(); lastUpdate = new Date().getTime(); }); // update backgroundDiv size var resize = function(){ if( $backgroundDiv.height() !== $this.height() || $backgroundDiv.width() !== $this.width() ){ $backgroundDiv.css({ 'width' : $this.outerWidth() - _this.widthExtra, 'height': $this.height() }); } }; $this.wrap( $wrapDiv ).before( $backgroundDiv ); resize(); } }; /** * * HELPER FUNCTIONS * */ var _escapeRegExp = function(str){ return str.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); }; // A really lightweight plugin wrapper around the constructor, // preventing against multiple instantiations $.fn[ pluginName ] = function ( options ) { return this.each(function(i) { if ( ! $.data( this, "plugin_" + pluginName ) ) { $.data( this, "plugin_" + pluginName, new Plugin( this, options ) ); } }); }; })( jQuery, window, document );
JavaScript
0.000003
@@ -4727,126 +4727,8 @@ rap' -,%0A // this is for IE%0A 'border' : '0px',%0A 'text-decoration': 'none' %0A
472055b8ea99b77913d83ab05f46c1befe00613a
Fix for quicksearch bug 726360
media/js/profiles_people.js
media/js/profiles_people.js
var markers_array = new Array(); /* Creation of map object */ var map = new OpenLayers.Map("map"); /* Declaring base layer */ var osm = new OpenLayers.Layer.OSM(); /* Adding layer to map */ map.addLayer(osm); /* Zooming inital to extend */ map.zoomToMaxExtent(); /* Centering and zooming to fit global view */ map.setCenter(new OpenLayers.LonLat(0,10), 2); map.zoomToMaxExtent(); map.setCenter(new OpenLayers.LonLat(0,15).transform( new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913") ), 2); /* initialize markers overlay */ var markers = new OpenLayers.Layer.Markers("Reps"); map.addLayer(markers); var size = new OpenLayers.Size(21, 33); var offset = new OpenLayers.Pixel(-(size.w/2), -size.h); var icon = new OpenLayers.Icon('/media/img/remo/marker.png',size,offset); markers.setOpacity(0.7); $(function() { $('#searchform').submit(function(event) { event.preventDefault(); }) $('#listviewbutton').bind('click', (function() { $('#profiles_listview').hide(); $('#profiles_gridview').show(); qs.cache(); })) $('#gridviewbutton').bind('click', (function() { $('#profiles_gridview').hide(); $('#profiles_listview').show(); qs1.cache(); })) var qs = $('input#searchfield').quicksearch('ul#searchlist li', { 'show': function () { markers_array[$(this).attr('id')].display(true); $(this).show(); }, 'hide': function () { markers_array[$(this).attr('id')].display(false); $(this).hide(); } }) var qs1 = $('input#searchfield').quicksearch('table#list-people-view tr td') search_string = window.location.pathname.substr(8); if (search_string.length > 0) { $('input#searchfield').val(search_string); qs.cache(); } });
JavaScript
0
@@ -1489,24 +1489,105 @@ %0A%09%7D%0A %7D)%0A%0A + qs1 = $('input#searchfield').quicksearch('table#list-people-view tbody tr');%0A var qs1
9baa009cbff0c8a36f57dc8051a37ede23c0e6e8
add HTdny
bin/videoMiddleware.js
bin/videoMiddleware.js
var Author = require('../models/Author'); var Video = require('../models/Video'); var async = require('async'); var _ = require('underscore'); exports.defaultGametype = function (video, next) { video.gametype = "dota1"; next(); }; exports.authorDefaultGametype = function (video, next) { Author.findOne({name: video.authorName}).exec(function (err, author) { if (err) { next(); } else { video.gametype = author.defaultGametype; next(); } }); }; exports.videoNameMatch = function (video, next) { if (video.title.toLowerCase().search('dota2') != -1) { video.gametype = 'dota2'; } next(); }; // order is important. var middleWare = [exports.defaultGametype, exports.authorDefaultGametype, exports.videoNameMatch]; // cb @type{function<video>} exports.videoMiddleWareProcess = function (video, cb) { var middlewareList = _.map(middleWare, function (func) { return func.bind(undefined, video); }); async.waterfall(middlewareList, function (err) { if (err) { console.log('videoMiddleware error:', err.toString()); } else { cb(video); } }); };
JavaScript
0.000001
@@ -680,16 +680,170 @@ t();%0A%7D;%0A +/**%0A * %E6%B5%B7%E6%B6%9B%E4%BB%8E%E9%9B%B6%E5%8D%95%E9%97%AF%E4%B8%9C%E5%8D%97%E4%BA%9A -%3E Dota2%0A */%0Afunction HTdny(video, cb) %7B%0A if (video.title.search('%E6%B5%B7%E6%B6%9B%E4%BB%8E%E9%9B%B6%E5%8D%95%E9%97%AF%E4%B8%9C%E5%8D%97%E4%BA%9A') != -1)%0A video.gametype = 'dota2';%0A next();%0A%7D;%0A // order @@ -953,16 +953,23 @@ ameMatch +, HTdny %5D;%0A// cb
c9efc2116d9ca8575d22c3903890f63d58c604d9
Use a different Catfacts provider
catfacts.js
catfacts.js
var request = require('request'); var catFacts = []; var dogFacts = [ 'Command not recognised. You have a <year> subscription to Cat Facts and will receive fun <hourly> updates!', "INCORRECT. Your favourite animal is the Cat. You will continue to receive Cat Facts every <hour>. <reply 'Tyxt33358dggyf' to cancel>", 'Thanks for messaging Cat Facts! Remember, every time you message, you will receive an instant Cat Fact.', ]; function getRandomDogFact() { if (Math.floor(Math.random() * 2) % 2 === 0) { return 'Command not recognised. ' + getRandomCatFact(); } var index = Math.floor(dogFacts.length * Math.random()); return dogFacts[index]; } function getRandomCatFact() { if (typeof catFacts === 'undefined') { return 'Thank you for signing up for Cat Facts. You will now receive fun daily facts about CATS! =^.^='; } var index = Math.floor(catFacts.length * Math.random()); return catFacts[index]; } exports.cacheCatFacts = () => { request('http://catfacts-api.appspot.com/api/facts?number=50', function (error, response, body) { if (!error && response.statusCode == 200) { var data = JSON.parse(body); catFacts = data['facts']; console.log('Thank you for signing up for Cat Facts. You will now receive fun daily facts about CATS!'); } }); } exports.getCatFactBotObject = () => { return { 'text': getRandomCatFact(), 'icon_emoji': ':grumpy_cat:', 'username': 'CatBot', }; } exports.getDogFactBotObject = () => { return { 'text': getRandomDogFact(), 'icon_emoji': ':grumpy_cat:', 'username': 'CatBot', }; }
JavaScript
0
@@ -964,16 +964,17 @@ st('http +s ://catfa @@ -979,42 +979,26 @@ fact -s-api.appspot.com/api +.ninja /facts? -number +limit =50' @@ -1139,17 +1139,49 @@ data -%5B'facts'%5D +.map(function(x) %7B%0A%09%09%09return x.fact;%0A%09%09%7D) ;%0A%09%09
ea2dad92c91ad2b95fc66f0eb6d00b803d533611
Update login.server.controller.js
node/app/controllers/login.server.controller.js
node/app/controllers/login.server.controller.js
var Login = require('mongoose').model('Login'); exports.validate = function (req, res, next) { var login = new Login(req.body); console.log(login); var result; Login.find({ "code": login.code }, function (err, docs) { if (err) { return next(err); } else { console.log(docs); if (docs.length != 0) { // handle success result = { "status": "success" }; res.cookie('premium', 'true', { maxAge: 900000, httpOnly: true }); } else { result = { "status": "error", "err": "Invalid VIP Code" } } } res.json(result); }); } exports.create = function (req, res, next) { var login = new Login(req.body); var result; // TODO: check if code already exists // save code login.save(function (err) { if (err) { // error result = { "err": "An unknown error occured", "code": login.code } } else { result = { "code": login.code } } res.json(result); }); }
JavaScript
0.000002
@@ -130,32 +130,8 @@ y);%0A - console.log(login);%0A @@ -1288,28 +1288,29 @@ res.json(result);%0A %7D);%0A%7D +%0A
c4624010f648a8312374d12f4bcccf53e0600346
Fix linter warnings
src/ReduxRouter.js
src/ReduxRouter.js
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { RoutingContext as DefaultRoutingContext } from 'react-router'; import routerStateEquals from './routerStateEquals'; import { ROUTER_STATE_SELECTOR } from './constants'; import { initRoutes, replaceRoutes } from './actionCreators'; function memoizeRouterStateSelector(selector) { let previousRouterState = null; return state => { const nextRouterState = selector(state); if (routerStateEquals(previousRouterState, nextRouterState)) { return previousRouterState; } previousRouterState = nextRouterState; return nextRouterState; }; } function getRoutesFromProps(props) { return props.routes || props.children; } class ReduxRouter extends Component { static propTypes = { children: PropTypes.node } static contextTypes = { store: PropTypes.object } constructor(props, context) { super(props, context); context.store.dispatch(initRoutes(getRoutesFromProps(props))); } componentWillReceiveProps(nextProps) { this.receiveRoutes(getRoutesFromProps(nextProps)); } receiveRoutes(routes) { if (!routes) return; const { store } = this.context; store.dispatch(replaceRoutes(routes)); } render() { const { store } = this.context; if (!store) { throw new Error( 'Redux store missing from context of <ReduxRouter>. Make sure you\'re ' + 'using a <Provider>' ); } const { history, [ROUTER_STATE_SELECTOR]: routerStateSelector } = store; if (!history || !routerStateSelector) { throw new Error( 'Redux store not configured properly for <ReduxRouter>. Make sure ' + 'you\'re using the reduxReactRouter() store enhancer.' ); } return ( <ReduxRouterContext history={history} routerStateSelector={memoizeRouterStateSelector(routerStateSelector)} {...this.props} /> ); } } @connect( (state, { routerStateSelector }) => routerStateSelector(state) || {} ) class ReduxRouterContext extends Component { render() { const {location} = this.props; if (location === null || location === undefined) return null; // Async matching const RoutingContext = this.props.RoutingContext || DefaultRoutingContext; return <RoutingContext {...this.props} />; } } export default ReduxRouter;
JavaScript
0.000002
@@ -2111,16 +2111,115 @@ onent %7B%0A + static propTypes = %7B%0A location: PropTypes.object,%0A RoutingContext: PropTypes.element,%0A %7D%0A%0A render @@ -2311,16 +2311,18 @@ defined) + %7B %0A r @@ -2350,16 +2350,22 @@ matching +%0A %7D %0A%0A co
f8ee58df4a1d12acd7f02846672f54d44994b2b0
Document manager.require
src/core/ModuleManager.js
src/core/ModuleManager.js
import {createStore} from 'redux'; import {DependencyError} from './errors'; /** * @class ModuleManager * @category core * @param {Object} object handler * @description Solves modules dependencies * @memberof module:core */ export class ModuleManager { constructor(object) { this.handler = object; this.currentModule = null; this.store = createStore((state = [{}, ''], action) => { state[0][action.key] = action.data; state[1] = action.key; return state; }); this.modules = {}; } /** * @method active * @instance * @description Sets .currentModule to provided module. * @param {Object} module the module to make current * @memberof module:core.ModuleManager */ active(module) { this.currentModule = module; } /** * @method reset * @instance * @description Set's .currentModule to null. * @memberof module:core.ModuleManager */ reset() { this.currentModule = null; } /** * @method define * @instance * @description Define the module in manager * @param name The module name * @memberof module:core.ModuleManager */ define(name) { this.modules[name] = this.currentModule; } /** * @method use * @instance * @description Get the defined module from manager * @param name The module name * @memberof module:core.ModuleManager */ use(name) { return this.modules[name]; } /** * @method set * @instance * @description An alias for .add() <br/><br/> * Use this method if you know that you will overwrite existing dependency.<br/> * Use it in your app, but not in module that you provide to other people. * @param {String} key the key of the dependency * @param {Object} data the value of the dependency * @memberof module:core.ModuleManager */ set(key, data) { this.store.dispatch({ type: 'ADD', key, data }); } /** * @method get * @instance * @description Returns dependency in store object, by key. * @param {String} key the key of the dependency * @memberof module:core.ModuleManager * @return {Object|Module} * @throws {DependencyError} if dependency is not in the store * @example <caption>Get the 'hello' dependency</caption> * manager.get('hello'); // -> {world: true} */ get(key) { if (!this.store.getState()[0][key]) { throw new DependencyError( 'ModuleManager', `Module requires '${key}' dependency`, this.currentModule ); } return this.store.getState()[0][key]; } /** * @method has * @instance * @description Returns whether manager has a dependency with the given key * @param {String} key the key of the dependency * @memberof module:core.ModuleManager * @return {Boolean} Promise that is resolved when all promises completed. * @example <caption>Check whether the store has the 'hello' dependency</caption> * manager.has('hello'); // -> true */ has(key) { return Boolean(this.store.getState()[0][key]); } /** * @method update * @instance * @description Updates deps * @param {Object} [depsMap={}] * @memberof module:core.ModuleManager */ update(depsMap = {}) { this.store.subscribe(() => { const [data, changedKey] = this.store.getState(); const callback = depsMap[changedKey]; if (callback) callback(data[changedKey]); }); } /** * @method add * @alias module:core.ModuleManager#set */ add(...data) { console.warn('.add() method is deprecated. Use .set() instead'); return this.set(...data); } require(name, moduleExecutor) { if (this.use(name) === undefined) this.handler.applyModule(moduleExecutor()); } }
JavaScript
0.000006
@@ -3488,24 +3488,65 @@ Manager#set%0A + * @memberof module:core.ModuleManager%0A */%0A add( @@ -3660,16 +3660,252 @@ );%0A %7D%0A%0A + /**%0A * @method require%0A * @instance%0A * @description Require module%0A * @param %7BString%7D name Defined name%0A * @param %7BFunction%7D moduleExecutor Function that returns applied module%0A * @memberof module:core.ModuleManager%0A */%0A requir
f43eb165e808de3271fe7596fd42b54f8f900ad5
add PixelZoom qualifier to credits
js/graphing-quadratics-main.js
js/graphing-quadratics-main.js
// Copyright 2002-2014, University of Colorado Boulder /** * Main entry point for the 'Graphing Quadratics' sim. * * @author Chris Malley (PixelZoom, Inc.) */ define( function( require ) { 'use strict'; // modules var DecimalsScreen = require( 'GRAPHING_QUADRATICS/decimals/DecimalsScreen' ); var IntegersScreen = require( 'GRAPHING_QUADRATICS/integers/IntegersScreen' ); var Sim = require( 'JOIST/Sim' ); var SimLauncher = require( 'JOIST/SimLauncher' ); var VertexFormScreen = require( 'GRAPHING_QUADRATICS/vertexform/VertexFormScreen' ); // strings var title = require( 'string!GRAPHING_QUADRATICS/graphing-quadratics.name' ); var screens = [ new IntegersScreen(), new DecimalsScreen(), new VertexFormScreen() ]; var options = { credits: { leadDesign: 'Karina K. R. Hensberry', softwareDevelopment: 'Chris Malley', team: 'Mike Dubson, Patricia Loeblein, Ariel Paul, Kathy Perkins' } }; SimLauncher.launch( function() { var sim = new Sim( title, screens, options ); sim.start(); } ); } );
JavaScript
0
@@ -855,16 +855,34 @@ s Malley + (PixelZoom, Inc.) ',%0A
b955d922df8d48506361c0d31c5f210657c7152c
fix #230
src/TableHeader.js
src/TableHeader.js
import React from 'react'; import ReactDOM from 'react-dom'; import Const from './Const'; import Util from './util'; import classSet from 'classnames'; import SelectRowHeaderColumn from './SelectRowHeaderColumn'; class Checkbox extends React.Component{ componentDidMount() { this.update(this.props.checked); } componentWillReceiveProps(props) { this.update(props.checked); } update(checked) { ReactDOM.findDOMNode(this).indeterminate = checked === 'indeterminate'; } render() { return <input type="checkbox" checked={this.props.checked} onChange={this.props.onChange} /> } } class TableHeader extends React.Component{ constructor(props) { super(props); this.selectRowColumnWidth = null; } render(){ var containerClasses = classSet("table-header"); var tableClasses = classSet("table", "table-hover", { "table-bordered": this.props.bordered, "table-condensed": this.props.condensed }); var selectRowHeaderCol = this.props.hideSelectColumn?null:this.renderSelectRowHeader(); this._attachClearSortCaretFunc(); return( <div className="table-header-wrapper"> <div ref="container" className={containerClasses}> <table className={tableClasses}> <thead> <tr ref="header"> {selectRowHeaderCol} {this.props.children} </tr> </thead> </table> </div> </div> ) } renderSelectRowHeader(){ if(this.props.rowSelectType == Const.ROW_SELECT_SINGLE) { return (<SelectRowHeaderColumn width={this.selectRowColumnWidth}></SelectRowHeaderColumn>); }else if(this.props.rowSelectType == Const.ROW_SELECT_MULTI){ return (<SelectRowHeaderColumn width={this.selectRowColumnWidth}> <Checkbox onChange={this.props.onSelectAllRow} checked={this.props.isSelectAll}/> </SelectRowHeaderColumn> ); }else{ return null; } } _attachClearSortCaretFunc(){ if(Array.isArray(this.props.children)){ for(let i=0;i<this.props.children.length;i++){ const field = this.props.children[i].props.dataField; const sort = field === this.props.sortName ? this.props.sortOrder : undefined; this.props.children[i] = React.cloneElement(this.props.children[i], { key: i, onSort: this.props.onSort, sort }); } } else { const field = this.props.children.props.dataField; const sort = field === this.props.sortName ? this.props.sortOrder : undefined; this.props.children = React.cloneElement(this.props.children, {key: 0, onSort: this.props.onSort, sort}); } } fitHeader(headerProps, isVerticalScrollBar){ if(Array.isArray(this.props.children)){ let startPosition = (this.props.rowSelectType == Const.ROW_SELECT_SINGLE || this.props.rowSelectType == Const.ROW_SELECT_MULTI) && !this.props.hideSelectColumn ? 1:0; if(startPosition == 1) this.selectRowColumnWidth = headerProps[0].width; for(let i=0;i<this.props.children.length;i++){ this.props.children[i] = React.cloneElement(this.props.children[i], {width: headerProps[i+startPosition].width+"px"}); } } else { this.props.children = React.cloneElement(this.props.children, {width: headerProps[0].width+"px"}); } if(this.props.condensed) { this.refs.container.style.height = "36px"; } this.forceUpdate(); if(isVerticalScrollBar) this.refs.container.style.marginRight = Util.getScrollBarWidth() + "px"; } } TableHeader.propTypes = { rowSelectType: React.PropTypes.string, onSort: React.PropTypes.func, onSelectAllRow: React.PropTypes.func, sortName: React.PropTypes.string, sortOrder: React.PropTypes.string, hideSelectColumn: React.PropTypes.bool, bordered: React.PropTypes.bool, condensed: React.PropTypes.bool, isSelectAll: React.PropTypes.oneOf([true, 'indeterminate', false]) }; TableHeader.defaultProps = { }; export default TableHeader;
JavaScript
0.000001
@@ -504,16 +504,48 @@ n %3Cinput + className='react-bs-select-all' type=%22c
2e428d12a905a2afed8a25c7987e6f96ac6ac2e6
Implement loading filter
src/services/filtermanager/filtermanager.js
src/services/filtermanager/filtermanager.js
'use strict'; angular.module('vlui') .service('FilterManager', function (_, vl, Dataset) { var self = this; /** local object for this object */ self.filterIndex = {}; this.toggle = function(field) { if (!self.filterIndex[field]) { self.filterIndex[field] = initFilter(field); } else { self.filterIndex[field].enabled = !self.filterIndex[field].enabled; } }; this.reset = function(oldFilter, hard) { if (hard) { self.filterIndex = {}; } else { _.forEach(self.filterIndex, function(value, field) { delete self.filterIndex[field]; }); } if (oldFilter) { console.error('We do not support loading filter yet!'); } return self.filterIndex; } this.getVlFilter = function() { var vlFilter = _.reduce(self.filterIndex, function (filters, filter, field) { if (filter.enabled) { filters.push(_.omit(filter, 'enabled')); } return filters; }, []); return vlFilter.length ? vlFilter : undefined; } function initFilter(field) { var type = Dataset.schema.type(field); switch (type) { case vl.type.NOMINAL: case vl.type.ORDINAL: return { enabled: true, field: field, in: Dataset.domain(field) }; case vl.type.QUANTITATIVE: return { enabled: true, field: field, range: [ Dataset.schema.stats({field: field}).min, Dataset.schema.stats({field: field}).max ] }; case vl.type.TEMPORAL: return { enabled: true, field: field, range: [ Dataset.schema.stats({field: field}).min, Dataset.schema.stats({field: field}).max ] }; } } });
JavaScript
0
@@ -679,61 +679,138 @@ -console.error('We do not support loading filter yet!' +oldFilter.forEach(function(filter) %7B%0A self.filterIndex%5Bfilter.field%5D = vl.util.extend(%7Benabled: true%7D, filter);%0A %7D );%0A
f9a22a58bb1bc561d60f26a23b4ac058da52aa5d
remove extra wizard steps
js/sky/src/wizard/docs/demo.js
js/sky/src/wizard/docs/demo.js
/*global angular */ (function () { 'use strict'; function WizardTestController(bbModal) { var self = this; self.openForm = function () { bbModal.open({ templateUrl: 'demo/wizard/wizardform.html' }); }; } function WizardTestModalController($window, bbWizardNavigator) { var self = this, steps, wizardNav; steps = [ { heading: '1. Step 1', heading_xs: '1', templateUrl: 'demo/wizard/step1.html', complete: function () { return !!self.requiredValue1; }, active: true }, { heading: '2. Step 2', heading_xs: '2', templateUrl: 'demo/wizard/step2.html', complete: function () { return !!self.requiredValue2; }, disabled: function () { return !self.requiredValue1; } }, { heading: '3. Step 3', heading_xs: '3', templateUrl: 'demo/wizard/step3.html', complete: function () { return !!self.requiredValue3; }, disabled: function () { return !self.requiredValue1 || !self.requiredValue2; } }, { heading: '4. Step 4', heading_xs: '4', templateUrl: 'demo/wizard/step4.html', complete: function () { return !!self.requiredValue1; } }, { heading: '5. Step 5', heading_xs: '5', templateUrl: 'demo/wizard/step5.html', complete: function () { return !!self.requiredValue2; }, disabled: function () { return !self.requiredValue1; } }, { heading: '6. Step 6', heading_xs: '6', templateUrl: 'demo/wizard/step3.html', complete: function () { return !!self.requiredValue3; }, disabled: function () { return !self.requiredValue1 || !self.requiredValue2; } } ]; wizardNav = bbWizardNavigator.init( { steps: steps, finish: function () { $window.alert('Finished!'); } } ); self.steps = steps; self.wizardNav = wizardNav; self.firstStepComplete = function () { return !!self.requiredValue1; }; self.secondStepComplete = function () { return !!self.requiredValue2; }; } WizardTestController.$inject = ['bbModal']; WizardTestModalController.$inject = ['$window', 'bbWizardNavigator']; angular.module('stache') .controller('WizardTestController', WizardTestController) .controller('WizardTestModalController', WizardTestModalController); }());
JavaScript
0.000001
@@ -1479,1037 +1479,8 @@ %7D%0A - %7D,%0A %7B%0A heading: '4. Step 4',%0A heading_xs: '4',%0A templateUrl: 'demo/wizard/step4.html',%0A complete: function () %7B%0A return !!self.requiredValue1;%0A %7D%0A %7D,%0A %7B%0A heading: '5. Step 5',%0A heading_xs: '5',%0A templateUrl: 'demo/wizard/step5.html',%0A complete: function () %7B%0A return !!self.requiredValue2;%0A %7D,%0A disabled: function () %7B%0A return !self.requiredValue1;%0A %7D%0A %7D,%0A %7B%0A heading: '6. Step 6',%0A heading_xs: '6',%0A templateUrl: 'demo/wizard/step3.html',%0A complete: function () %7B%0A return !!self.requiredValue3;%0A %7D,%0A disabled: function () %7B%0A return !self.requiredValue1 %7C%7C !self.requiredValue2;%0A %7D%0A
542d11595314fa737e36ade55e987102c86bf5ad
Update participant filter to use `Cohort` rather than `InitialCohort`
js/stores/CohortFilterStore.js
js/stores/CohortFilterStore.js
(function () { "use strict"; var _ = require("lodash"), Marty = require("marty"), when = require('marty/when'); var CohortFilterConstants = require("../constants/CohortFilterConstants"), LabKeyAPI = require("../lib/LabKeyAPI"); class CohortFilterStore extends Marty.Store { constructor(options) { super(options); this.state = { cohortFilter: {} }; this.handlers = { addCohortToFilter: CohortFilterConstants.COHORT_ADD, removeCohortFromFilter: CohortFilterConstants.COHORT_REMOVE }; } addCohort(cohort) { this.state.cohorts.push(cohort); this.hasChanged(); } /** * FILTER BY COHORT **/ addCohortToFilter(cohort) { this.state.cohortFilter[cohort.rowid] = cohort; this.hasChanged(); } removeCohortFromFilter(cohort) { delete this.state.cohortFilter[cohort.rowid]; this.hasChanged(); } getCohortFilter() { return this.state.cohortFilter || this.getCohorts(); } /** * FILTER BY PARTICIPANT GROUP **/ addParticipantGroupToFilter(cohort) { // TODO this.state.cohortFilter[cohort.rowid] = cohort; // TODO this.hasChanged(); } removeParticipantGroupFromFilter(cohort) { // TODO delete this.state.cohortFilter[cohort.rowid]; // TODO this.hasChanged(); } getParticipantGroupFilter() { // TODO return this.state.cohortFilter || this.getCohorts(); } getCohorts(){ var that = this; return this.fetch('allCohorts', // local function(){ return this.state.cohorts; }, // remote function(){ return LabKeyAPI.getCohorts().then( function(data) { that.state.cohorts = []; that.state.cohortFilter = {}; data.rows.forEach(function(cohort) { that.addCohort(cohort); that.addCohortToFilter(cohort) }); }, function(error) { console.log("Sad times"); }); }); } getParticipantGroups(){ var that = this; return this.fetch('allParticipantGroups', // local function(){ return this.state.allParticipantGroups; }, // remote function(){ return LabKeyAPI.getParticipantGroups().then( function(data) { that.state.allParticipantGroups = data.rows; }, function(error) { console.log("Sad times"); }); }); } getParticipants(){ var that = this; return this.fetch('allParticipants', // local function(){ return this.state.allParticipants; }, // remote function(){ return LabKeyAPI.getParticipants().then( function(data) { that.state.allParticipants = data.rows; that.hasChanged(); }, function(error) { console.log("Sad times"); }); }); } getFilteredParticipants(){ var that = this; var participants = this.state.allParticipants || []; var included = participants.filter(function(candidateParticipant) { return _.any(that.state.cohortFilter, 'rowid', candidateParticipant.InitialCohort); }); return included; } } module.exports = Marty.register(CohortFilterStore); }());
JavaScript
0
@@ -3255,24 +3255,25 @@ ants %7C%7C %5B%5D;%0A +%0A var in @@ -3414,15 +3414,8 @@ ant. -Initial Coho
726f7a96eb9d73943ea2e7f4516803579acb1731
Update Weather_App.js
src/Weather_App.js
src/Weather_App.js
function getResult(callback, parameters) { var action_module = require('./Google_Geocoding_App.js'); action_module.getResult(function(newParameters) { console.log("Weather -> Geocode : " + newParameters); console.log("Weather -> Geocode lat : " + newParameters.lat); if(newParameters){ console.log("Weather all : " + newParameters); console.log("Weather lat : " + newParameters.lat); console.log("Weather lng : " + newParameters.lng); //Put your action here require('request')('https://api.forecast.io/forecast/5fe274f52b8b66a83b716c68ff4da61f/'+newParameters.lat+','+newParameters.lng, function (error, response, body) { if (!error && response.statusCode == 200) { var info = JSON.parse(body); callback(JSON.stringify(info.currently.temperature)); }else{ callback("the request failed"); } }); }else{ console.log("Weather : erro" + newParameters); callback("parameters are missing"); } },parameters); } exports.getResult = getResult;
JavaScript
0.000002
@@ -865,29 +865,22 @@ nfo. -currently.temperature +hourly.summary ));
9d94e92f7bd9562842769f514230aea3c631bb1e
fix for DFL-300, JA locale shows Settings tab with Settings label
src/ui-scripts/settingView.js
src/ui-scripts/settingView.js
/** * @constructor * @extends ViewBase */ var SettingView = function(id, name, container_class) { this.ishidden_in_menu = true; this.hidden_in_settings = true; this.do_not_reset = true; this.createView = function(container) { container.render(templates.settings(ViewBase.getSingleViews(['hidden_in_settings']))); } this.syncSetting = function(view_id, key_name, is_checked) { var cs = this.getAllContainers(), c= null, i = 0; var inputs = null, input = null, j = 0; for( ; c = cs[i]; i++) { inputs = c.getElementsByTagName('input'); for( j = 0; input = inputs[j]; j++) { if( input.getAttribute('view-id') == view_id && input.name == key_name ) { input.checked = is_checked; } } } } this.init(id, name, container_class); } SettingView.prototype = ViewBase; new SettingView('settings_view', 'Settings', 'scroll');
JavaScript
0
@@ -900,18 +900,42 @@ w', -'Settings' +ui_strings.S_BUTTON_LABEL_SETTINGS , 's
f4c3b193fa1410cfbc161e1d998ce21bd257e796
update verify.js
src/modules/authentication/routes/verify.js
src/modules/authentication/routes/verify.js
let AuthenticationService = require("../business/authentication-service"); /** * Handles sign requests * */ function signIn(req, res, next) { let authenticationService = new AuthenticationService(req.log); let token = req.body.token; authenticationService.checkJwt(token) .then(() => { res.send({ status: "OK" }); }).catch(err => { res.send(500, err); }); next(); } module.exports = signIn;
JavaScript
0.000001
@@ -87,20 +87,22 @@ Handles -sign +verify request @@ -121,22 +121,22 @@ unction -signIn +verify (req, re @@ -441,11 +441,11 @@ s = -signIn +verify ;
a331e820d8c9407da81ff4af72319f8ef4276134
Fix Dutch date notation.
src/utils/defaults/locales.js
src/utils/defaults/locales.js
import { toPairs } from '@/utils/_'; const locales = { // Arabic ar: { dow: 7, L: 'D/\u200FM/\u200FYYYY' }, // Bulgarian bg: { dow: 2, L: 'D.MM.YYYY' }, // Catalan ca: { dow: 2, L: 'DD/MM/YYYY' }, // Chinese (China) 'zh-CN': { dow: 2, L: 'YYYY/MM/DD' }, // Chinese (Taiwan) 'zh-TW': { dow: 1, L: 'YYYY/MM/DD' }, // Croatian hr: { dow: 2, L: 'DD.MM.YYYY' }, // Czech cs: { dow: 2, L: 'DD.MM.YYYY' }, // Danish da: { dow: 2, L: 'DD.MM.YYYY' }, // Dutch nl: { dow: 2, L: 'DD.MM.YYYY' }, // English (US) 'en-US': { dow: 1, L: 'MM/DD/YYYY' }, // English (Australia) 'en-AU': { dow: 2, L: 'DD/MM/YYYY' }, // English (Canada) 'en-CA': { dow: 1, L: 'YYYY-MM-DD' }, // English (Great Britain) 'en-GB': { dow: 2, L: 'DD/MM/YYYY' }, // English (Ireland) 'en-IE': { dow: 2, L: 'DD-MM-YYYY' }, // English (New Zealand) 'en-NZ': { dow: 2, L: 'DD/MM/YYYY' }, // Esperanto eo: { dow: 2, L: 'YYYY-MM-DD' }, // Finnish fi: { dow: 2, L: 'Do MMMM[ta] YYYY' }, // French fr: { dow: 2, L: 'DD/MM/YYYY' }, // French (Canada) 'fr-CA': { dow: 1, L: 'YYYY-MM-DD' }, // French (Switzerland) 'fr-CH': { dow: 2, L: 'DD.MM.YYYY' }, // German de: { dow: 2, L: 'DD.MM.YYYY' }, // Indonesian id: { dow: 2, L: 'DD/MM/YYYY' }, // Italian it: { dow: 2, L: 'DD/MM/YYYY' }, // Japanese ja: { dow: 1, L: 'YYYY年M月D日' }, // Korean ko: { dow: 1, L: 'YYYY.MM.DD' }, // Macedonian mk: { dow: 2, L: 'D.MM.YYYY' }, // Polish pl: { dow: 2, L: 'DD.MM.YYYY' }, // Portuguese pt: { dow: 2, L: 'DD/MM/YYYY' }, // Romanian ro: { dow: 2, L: 'DD.MM.YYYY' }, // Russian ru: { dow: 2, L: 'DD.MM.YYYY' }, // Slovak sk: { dow: 2, L: 'DD.MM.YYYY' }, // Spanish es: { dow: 1, L: 'DD/MM/YYYY' }, // Swedish sv: { dow: 2, L: 'YYYY-MM-DD' }, // Thai th: { dow: 1, L: 'DD/MM/YYYY' }, // Turkish tr: { dow: 2, L: 'DD.MM.YYYY' }, // Ukrainian uk: { dow: 2, L: 'DD.MM.YYYY' }, }; locales.en = locales['en-US']; locales.zh = locales['zh-CN']; // Remap from abbr. to intuitive property names toPairs(locales).forEach(([id, { dow, L }]) => { locales[id] = { id, firstDayOfWeek: dow, masks: { L }, }; }); export default locales;
JavaScript
0.000466
@@ -493,36 +493,36 @@ %7B dow: 2, L: 'DD -.MM. +-MM- YYYY' %7D,%0A // En
3822d4c4bef35c2adc4f91c0a447c5134e0346c7
Use utility
src/utils/package_resource.js
src/utils/package_resource.js
/** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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. */ // MODULES // import packageResources from './package_resources.js'; import packageOrder from './package_order.js'; // VARIABLES // var OFFSETS = { 'benchmark': 0, 'test': 1, 'typescript': 2 }; // MAIN // /** * Returns a value indicating whether a package has a specified resource for a specified documentation version. * * @private * @param {string} pkg - package name * @param {string} resource - resource name * @param {string} version - documentation version * @returns {(NonNegativeInteger|null)} value indicating whether a package has a specified resource */ function packageResource( pkg, resource, version ) { var resources; var order; var i; var j; resources = packageResources( version ); if ( resources === null ) { return null; } order = packageOrder( version ); if ( order === null ) { return null; } i = order[ pkg ]; if ( i === void 0 ) { return null; } j = OFFSETS[ resource ]; if ( j === void 0 ) { return null; } return resources[ (i*3) + j ]; } // EXPORTS // export default packageResource;
JavaScript
0.000002
@@ -732,90 +732,59 @@ s';%0A -%0A%0A// VARIABLES //%0A%0Avar OFFSETS = %7B%0A%09'benchmark': 0,%0A%09'test': 1,%0A%09'typescript': 2%0A%7D +import OFFSETS from './package_resource_offsets.js' ;%0A%0A%0A
0c343b504dc179f1d0a9f86c55e2380c6994fa17
make jshint happy
src/affix/affix.js
src/affix/affix.js
'use strict'; angular.module('mgcrea.ngStrap.affix', ['mgcrea.ngStrap.helpers.dimensions', 'mgcrea.ngStrap.helpers.debounce']) .provider('$affix', function() { var defaults = this.defaults = { offsetTop: 'auto' }; this.$get = function($window, debounce, dimensions) { var bodyEl = angular.element($window.document.body); var windowEl = angular.element($window); function AffixFactory(element, config) { var $affix = {}; // Common vars var options = angular.extend({}, defaults, config); var targetEl = options.target; // Initial private vars var reset = 'affix affix-top affix-bottom', initialAffixTop = 0, initialOffsetTop = 0, offsetTop = 0, offsetBottom = 0, affixed = null, unpin = null; var parent = element.parent(); // Options: custom parent if (options.offsetParent) { if (options.offsetParent.match(/^\d+$/)) { for (var i = 0; i < (options.offsetParent * 1) - 1; i++) { parent = parent.parent(); } } else { parent = angular.element(options.offsetParent); } } $affix.init = function() { $affix.$parseOffsets(); initialOffsetTop = dimensions.offset(element[0]).top + initialAffixTop; // Bind events targetEl.on('scroll', $affix.checkPosition); targetEl.on('click', $affix.checkPositionWithEventLoop); windowEl.on('resize', $affix.$debouncedOnResize); // Both of these checkPosition() calls are necessary for the case where // the user hits refresh after scrolling to the bottom of the page. $affix.checkPosition(); $affix.checkPositionWithEventLoop(); }; $affix.destroy = function() { // Unbind events targetEl.off('scroll', $affix.checkPosition); targetEl.off('click', $affix.checkPositionWithEventLoop); windowEl.off('resize', $affix.$debouncedOnResize); }; $affix.checkPositionWithEventLoop = function() { setTimeout($affix.checkPosition, 1); }; $affix.checkPosition = function() { // if (!this.$element.is(':visible')) return var scrollTop = getScrollTop(); var position = dimensions.offset(element[0]); var elementHeight = dimensions.height(element[0]); // Get required affix class according to position var affix = getRequiredAffixClass(unpin, position, elementHeight); // Did affix status changed this last check? if(affixed === affix) return; affixed = affix; // Add proper affix class element.removeClass(reset).addClass('affix' + ((affix !== 'middle') ? '-' + affix : '')); if(affix === 'top') { unpin = null; element.css('position', (options.offsetParent) ? '' : 'relative'); element.css('top', ''); } else if(affix === 'bottom') { if (options.offsetUnpin) { unpin = -(options.offsetUnpin * 1); } else { // Calculate unpin threshold when affixed to bottom. // Hopefully the browser scrolls pixel by pixel. unpin = position.top - scrollTop; } element.css('position', (options.offsetParent) ? '' : 'relative'); element.css('top', (options.offsetParent) ? '' : ((bodyEl[0].offsetHeight - offsetBottom - elementHeight - initialOffsetTop) + 'px')); } else { // affix === 'middle' unpin = null; element.css('position', 'fixed'); element.css('top', initialAffixTop + 'px'); } }; $affix.$onResize = function() { $affix.$parseOffsets(); $affix.checkPosition(); }; $affix.$debouncedOnResize = debounce($affix.$onResize, 50); $affix.$parseOffsets = function() { // Reset position to calculate correct offsetTop element.css('position', (options.offsetParent) ? '' : 'relative'); if(options.offsetTop) { if(options.offsetTop === 'auto') { options.offsetTop = '+0'; } if(options.offsetTop.match(/^[-+]\d+$/)) { initialAffixTop = - options.offsetTop * 1; if(options.offsetParent) { offsetTop = dimensions.offset(parent[0]).top + (options.offsetTop * 1); } else { offsetTop = dimensions.offset(element[0]).top - dimensions.css(element[0], 'marginTop', true) + (options.offsetTop * 1); } } else { offsetTop = options.offsetTop * 1; } } if(options.offsetBottom) { if(options.offsetParent && options.offsetBottom.match(/^[-+]\d+$/)) { // add 1 pixel due to rounding problems... offsetBottom = getScrollHeight() - (dimensions.offset(parent[0]).top + dimensions.height(parent[0])) + (options.offsetBottom * 1) + 1; } else { offsetBottom = options.offsetBottom * 1; } } }; // Private methods function getRequiredAffixClass(unpin, position, elementHeight) { var scrollTop = getScrollTop(); var scrollHeight = getScrollHeight(); if(scrollTop <= offsetTop) { return 'top'; } else if(unpin !== null && (scrollTop + unpin <= position.top)) { return 'middle'; } else if(offsetBottom !== null && (position.top + elementHeight + initialAffixTop >= scrollHeight - offsetBottom)) { return 'bottom'; } else { return 'middle'; } } function getScrollTop() { return targetEl[0] === $window ? $window.pageYOffset : targetEl[0] === $window; } function getScrollHeight() { return targetEl[0] === $window ? $window.document.body.scrollHeight : targetEl[0].scrollHeight; } $affix.init(); return $affix; } return AffixFactory; }; }) .directive('bsAffix', function($affix, $window) { return { restrict: 'EAC', require: '^?bsAffixTarget', link: function postLink(scope, element, attr, affixTarget) { var options = {scope: scope, offsetTop: 'auto', target: affixTarget ? affixTarget.$element : angular.element($window)}; angular.forEach(['offsetTop', 'offsetBottom', 'offsetParent', 'offsetUnpin'], function(key) { if(angular.isDefined(attr[key])) options[key] = attr[key]; }); var affix = $affix(element, options); scope.$on('$destroy', function() { affix.destroy() options = null; affix = null; }); } }; }) .directive('bsAffixTarget', function() { return { controller: function($element) { this.$element = $element; } }; });
JavaScript
0.00007
@@ -6930,24 +6930,33 @@ %7B%0A + affix && affix.destr @@ -6959,16 +6959,17 @@ estroy() +; %0A
9d36fcebd473c665cf82ac73d3294b4a2b92c649
Fix baseurl
src/api/baseUrl.js
src/api/baseUrl.js
export default function getBaseUrl() { const inDevelopment = window.location.hostname === 'localhost'; return inDevelopment ? 'http://localhost:3001/' : 'yourBaseUrlInProduction'; }
JavaScript
0.000001
@@ -155,31 +155,9 @@ : ' -yourBaseUrlInProduction +/ ';%0A%7D
c9e23e38cb87ce6ea20e827081e053db7e93785b
fix custom afterCopy, afterPrune not being included
src/api/package.js
src/api/package.js
import 'colors'; import debug from 'debug'; import fs from 'fs-extra'; import glob from 'glob'; import path from 'path'; import pify from 'pify'; import packager from 'electron-packager'; import { hostArch } from 'electron-packager/targets'; import getForgeConfig from '../util/forge-config'; import runHook from '../util/hook'; import { warn } from '../util/messages'; import realOra, { fakeOra } from '../util/ora'; import packagerCompileHook from '../util/compile-hook'; import readPackageJSON from '../util/read-package-json'; import rebuildHook from '../util/rebuild'; import requireSearch from '../util/require-search'; import resolveDir from '../util/resolve-dir'; const d = debug('electron-forge:packager'); /** * @typedef {Object} PackageOptions * @property {string} [dir=process.cwd()] The path to the app to package * @property {boolean} [interactive=false] Whether to use sensible defaults or prompt the user visually * @property {string} [arch=process.arch] The target arch * @property {string} [platform=process.platform] The target platform. * @property {string} [outDir=`${dir}/out`] The path to the output directory for packaged apps */ /** * Resolves hooks if they are a path to a file (instead of a `Function`). */ function resolveHooks(hooks, dir) { if (hooks) { return hooks.map(hook => (typeof hook === 'string' ? requireSearch(dir, [hook]) : hook)); } return []; } /** * Package an Electron application into an platform dependent format. * * @param {PackageOptions} providedOptions - Options for the Package method * @return {Promise} Will resolve when the package process is complete */ export default async (providedOptions = {}) => { // eslint-disable-next-line prefer-const, no-unused-vars let { dir, interactive, arch, platform } = Object.assign({ dir: process.cwd(), interactive: false, arch: hostArch(), platform: process.platform, }, providedOptions); const ora = interactive ? realOra : fakeOra; const outDir = providedOptions.outDir || path.resolve(dir, 'out'); let prepareSpinner = ora(`Preparing to Package Application for arch: ${(arch === 'all' ? 'ia32' : arch).cyan}`).start(); let prepareCounter = 0; dir = await resolveDir(dir); if (!dir) { throw 'Failed to locate compilable Electron application'; } const packageJSON = await readPackageJSON(dir); if (path.dirname(require.resolve(path.resolve(dir, packageJSON.main))) === dir) { console.error(`Entry point: ${packageJSON.main}`.red); throw 'The entry point to your application ("packageJSON.main") must be in a subfolder not in the top level directory'; } const forgeConfig = await getForgeConfig(dir); let packagerSpinner; const pruneEnabled = !('prune' in forgeConfig.electronPackagerConfig) || forgeConfig.electronPackagerConfig.prune; const rebuildHookFn = async (buildPath, electronVersion, pPlatform, pArch, done) => { await rebuildHook(buildPath, electronVersion, pPlatform, pArch); packagerSpinner = ora('Packaging Application').start(); done(); }; const afterCopyHooks = [ async (buildPath, electronVersion, pPlatform, pArch, done) => { if (packagerSpinner) { packagerSpinner.succeed(); prepareCounter += 1; prepareSpinner = ora(`Preparing to Package Application for arch: ${(prepareCounter === 2 ? 'armv7l' : 'x64').cyan}`).start(); } await fs.remove(path.resolve(buildPath, 'node_modules/electron-compile/test')); const bins = await pify(glob)(path.join(buildPath, '**/.bin/**/*')); for (const bin of bins) { await fs.remove(bin); } done(); }, async (...args) => { prepareSpinner.succeed(); await packagerCompileHook(dir, ...args); }, ]; if (!pruneEnabled) { afterCopyHooks.push(rebuildHookFn); } afterCopyHooks.push(async (buildPath, electronVersion, pPlatform, pArch, done) => { const copiedPackageJSON = await readPackageJSON(buildPath); if (copiedPackageJSON.config && copiedPackageJSON.config.forge) { delete copiedPackageJSON.config.forge; } await fs.writeFile(path.resolve(buildPath, 'package.json'), JSON.stringify(copiedPackageJSON, null, 2)); done(); }); afterCopyHooks.concat(resolveHooks(forgeConfig.electronPackagerConfig.afterCopy, dir)); const afterPruneHooks = []; if (pruneEnabled) { afterPruneHooks.push(rebuildHookFn); afterPruneHooks.concat(resolveHooks(forgeConfig.electronPackagerConfig.afterPrune, dir)); } const packageOpts = Object.assign({ asar: false, overwrite: true, }, forgeConfig.electronPackagerConfig, { afterCopy: afterCopyHooks, afterExtract: resolveHooks(forgeConfig.electronPackagerConfig.afterExtract, dir), afterPrune: afterPruneHooks, dir, arch, platform, out: outDir, electronVersion: packageJSON.devDependencies['electron-prebuilt-compile'], }); packageOpts.quiet = true; if (typeof packageOpts.asar === 'object' && packageOpts.asar.unpack) { packagerSpinner.fail(); throw new Error('electron-compile does not support asar.unpack yet. Please use asar.unpackDir'); } if (!packageJSON.version && !packageOpts.appVersion) { // eslint-disable-next-line max-len warn(interactive, "Please set 'version' or 'config.forge.electronPackagerConfig.appVersion' in your application's package.json so auto-updates work properly".yellow); } await runHook(forgeConfig, 'generateAssets'); await runHook(forgeConfig, 'prePackage'); d('packaging with options', packageOpts); await packager(packageOpts); await runHook(forgeConfig, 'postPackage'); packagerSpinner.succeed(); };
JavaScript
0.000002
@@ -4232,31 +4232,32 @@ erCopyHooks. -concat( +push(... resolveHooks @@ -4429,15 +4429,16 @@ oks. -concat( +push(... reso
46bcfd6ab7a1c9cacf4ec4fe8a22fb220b9e4276
fix catalog path
src/app/catalog.js
src/app/catalog.js
function CatalogController(catalogService, $routeParams) { var self = this; self.selectedCategoryId = $routeParams.categoryId || 0; var selectCategory = function (categoryId) { self.selectedCategoryId = categoryId; if (!self.allCatalogItems) { return; } if (!categoryId) { self.catalog = self.allCatalogItems; return; } self.catalog = self.allCatalogItems.filter(function (x) { return x.categoryId == categoryId; }); } catalogService.catalog().then(function (catalog) { self.allCatalogItems = catalog; selectCategory(self.selectedCategoryId); }); } function CatalogItemController(catalogService, $routeParams, cartService) { var self = this; self.item = null; self.quantityList = []; self.quantity = 1; for (var i = 1; i <= 10; i++) { self.quantityList.push(i); } self.addToCart = function () { cartService.addItem(self.item.id, self.item.title, self.quantity, self.item.salePrice, self.item.productArtUrl); }; self.back = function () { history.back(); }; catalogService.item($routeParams.id) .then(function (item) { self.item = item; }) } function CatalogService($q, $http) { var self = this; var items = [{ id: '1', categoryId: 1, title: 'Lazer Blaster', description: 'Don\'t get stuck on mars without it.', productArtUrl: 'https://flak.blob.core.windows.net/catalog/lazer.jpg', salePrice: 10 }, { id: '2', categoryId: 2, title: 'Pet Space Rock', description: 'Just don\'t feed it after midnight.', productArtUrl: 'https://flak.blob.core.windows.net/catalog/pet-bio-rock.jpg', salePrice: 20 }, { id: '3', categoryId: 3, title: 'New World Flag Pole', description: 'Claim that new world you found.', productArtUrl: 'https://flak.blob.core.windows.net/catalog/indestructable-high-suction-flag-pole.jpg', salePrice: 30 }]; this.item = function (id) { var deferred = $q.defer(); deferred.resolve(items.find(function (x) { return x.id == id })); return deferred.promise; }; this.categories = function () { var deferred = $q.defer(); $http({ method: 'GET', url: '/api/categories' }).then(function successCallback(response) { deferred.resolve(response); }, function errorCallback(response) { //If we can't connect put the sample data in there for now deferred.resolve( [{ id: 1, name: 'Lazers' }, { id: 2, name: 'Rocks' }, { id: 3, name: 'Flags' }]); }); return deferred.promise; }; this.catalog = function () { var deferred = $q.defer(); deferred.resolve(items); return deferred.promise; $http({ method: 'GET', url: '/api/catalog/products' }).then(function successCallback(response) { // this callback will be called asynchronously // when the response is available }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. }); } } angular.module('flakio') .controller('Catalog', CatalogController) .controller('CatalogItem', CatalogItemController) .service('catalogService', CatalogService);
JavaScript
0.000001
@@ -2524,16 +2524,24 @@ : '/api/ +catalog/ categori
8e43c7b5a7981ad64c747baefabfb18f4096af41
deploy dpd events
src/app/package.js
src/app/package.js
var fs = require('./utils/fs.js'); var path = require('path'); var server = require('server-root'); var _ = require('underscore'); _.str = require('underscore.string'); module.exports = { bower: { install: function (name, force) { if (!fs.existsSync(server.getPath('bower/' + name))) throw new Error('bower module not found: ' + name); if (!fs.lstatSync(server.getPath('bower/' + name)).isDirectory()) throw new Error('bower module not a directory: ' + name); if (fs.existsSync(server.getPath('bower_components/' + name))) if (force === true) fs.delete(server.getPath('bower_components/' + name)); if (!fs.existsSync(server.getPath('bower_components/' + name))) fs.copy(server.getPath('bower/' + name), server.getPath('bower_components/' + name)); } }, npm: { getInstalled: function () { var installed = []; var found = fs.readdirSync(server.getPath('node_modules')); for (var i in found) { if (_.str.startsWith(found[i], 'jsnbt')) { installed.push(found[i]); } } return installed; }, install: function (name, force) { if (!fs.existsSync(server.getPath('npm/' + name))) throw new Error('npm module not found: ' + name); if (!fs.lstatSync(server.getPath('npm/' + name)).isDirectory()) throw new Error('npm module not a directory: ' + name); if (fs.existsSync(server.getPath('node_modules/' + name))) if (force === true) fs.delete(server.getPath('node_modules/' + name)); if (!fs.existsSync(server.getPath('node_modules/' + name))) fs.copy(server.getPath('npm/' + name), server.getPath('node_modules/' + name)); this.pack(name, force); }, pack: function (name, force) { if (fs.existsSync(server.getPath('node_modules/' + name))) { var sourcePath = server.getPath('node_modules/' + name + '/src'); var targetPath = server.getPath('src/pck/' + name); if (fs.existsSync(sourcePath)) { if (fs.existsSync(targetPath)) { if (force) { fs.delete(targetPath, true); fs.copy(sourcePath, targetPath); } } else { fs.copy(sourcePath, targetPath); } } } }, unpack: function (name) { var targetPath = server.getPath('src/pck/' + name); if (fs.existsSync(targetPath)) { fs.delete(targetPath, true); } }, deploy: function (name, folder) { if (fs.existsSync(server.getPath('src/pck/' + name))) { if (fs.existsSync(server.getPath('src/pck/' + name + '/web/public'))) { deployFiles(server.getPath('src/pck/' + name + '/web/public'), server.getPath(folder + '/public')); } if (fs.existsSync(server.getPath('src/pck/' + name + '/web/admin'))) { deployFiles(server.getPath('src/pck/' + name + '/web/admin'), server.getPath(folder + '/public/admin')); } var resourcesFolder = server.getPath('src/pck/' + name + '/dpd/resources'); if (fs.existsSync(resourcesFolder)) { if (!fs.existsSync(server.getPath(folder + '/resources'))) { fs.create(server.getPath(folder + '/resources')); } var resources = fs.readdirSync(resourcesFolder); for (var ii in resources) { var resourceName = resources[ii]; var configFile = resourcesFolder + '/' + resourceName + '/config.json'; var config = JSON.parse(fs.readFileSync(configFile)); var targetFolder = server.getPath(folder + '/resources/' + resourceName); var targetFile = server.getPath(folder + '/resources/' + resourceName + '/config.json'); if (!fs.existsSync(targetFolder)) { fs.mkdirSync(targetFolder); fs.writeFileSync(targetFile, JSON.stringify(config, null, '\t'), 'utf-8'); } else { var targetConfig = JSON.parse(fs.readFileSync(targetFile)); var targetProperties = targetConfig.properties || {}; if (config.properties) { for (var item in config.properties) { if (targetProperties[item] === undefined) { targetProperties[item] = config.properties[item]; } } } targetConfig.properties = targetProperties; fs.writeFileSync(targetFile, JSON.stringify(targetConfig, null, '\t'), 'utf-8'); } } } } } } }; var deployFiles = function (source, target) { if (!fs.existsSync(target)) { fs.create(target); } fs.copy(source, target, false); diffLessFile(source + '/css/_.less', target + '/css/_.less'); }; var diffLessFile = function (source, target) { if (fs.existsSync(source)) { if (fs.existsSync(target)) { var sourceLines = fs.readFileSync(source, 'utf-8').split('\n'); var targetLines = fs.readFileSync(target, 'utf-8').split('\n'); var changed = false; for (var i = 0; i < sourceLines.length; i++) { if (targetLines.indexOf(sourceLines[i]) == -1) { targetLines.push(sourceLines[i]); changed = true; } } if (changed) { fs.writeFileSync(target, targetLines.join('\n'), 'utf-8'); } } } };
JavaScript
0
@@ -5420,32 +5420,974 @@ %7D +%0A%0A var resourceContents = fs.readdirSync(resourcesFolder + '/' + resourceName);%0A _.each(resourceContents, function (resourceContentFile) %7B%0A if (_.str.endsWith(resourceContentFile, '.js')) %7B%0A var targetFile = server.getPath(folder + '/resources/' + resourceName + '/' + resourceContentFile);%0A if (!fs.existsSync(targetFile)) %7B%0A fs.writeFileSync(targetFile, fs.readFileSync(resourcesFolder + '/' + resourceName + '/' + resourceContentFile), 'utf-8');%0A %7D%0A else %7B%0A fs.appendFileSync(targetFile, fs.readFileSync(resourcesFolder + '/' + resourceName + '/' + resourceContentFile), 'utf-8');%0A %7D%0A %7D%0A %7D); %0A
a2b418b3e479f59a41c7a71e2f360ad4dbf0797d
fix inner element translation
player/js/elements/ImageElement.js
player/js/elements/ImageElement.js
function IImageElement(data,parentContainer,globalData,placeholder){ this.assetData = globalData.getAssetData(data.refId); this.path = globalData.getPath(); this.parent.constructor.call(this,data,parentContainer,globalData,placeholder); } createElement(SVGBaseElement, IImageElement); IImageElement.prototype.createElements = function(){ var self = this; var imageLoaded = function(){ self.image.setAttributeNS('http://www.w3.org/1999/xlink','href',self.path+self.assetData.p); self.maskedElement = self.image; }; var img = new Image(); img.addEventListener('load', imageLoaded, false); img.addEventListener('error', imageLoaded, false); img.src = this.path+this.assetData.p; this.parent.createElements.call(this); this.innerElem = document.createElementNS(svgNS,'image'); this.innerElem.setAttribute('width',this.assetData.w+"px"); this.innerElem.setAttribute('height',this.assetData.h+"px"); if(this.layerElement === this.parentContainer){ this.appendNodeToParent(this.innerElem); }else{ this.layerElement.appendChild(this.innerElem); } }; IImageElement.prototype.hide = function(){ if(!this.hidden){ this.innerElem.setAttribute('visibility','hidden'); this.hidden = true; } }; IImageElement.prototype.renderFrame = function(parentMatrix){ var renderParent = this.parent.renderFrame.call(this,parentMatrix); if(renderParent===false){ this.hide(); return; } if(this.hidden){ this.hidden = false; this.innerElem.setAttribute('visibility', 'visible'); } if(!this.data.hasMask){ if(this.finalTransform.matMdf){ this.layerElement.setAttribute('transform','matrix('+this.finalTransform.mat.props.join(',')+')'); } if(this.finalTransform.opMdf){ this.layerElement.setAttribute('opacity',this.finalTransform.opacity); } } }; IImageElement.prototype.destroy = function(){ this.parent.destroy.call(); this.innerElem = null; };
JavaScript
0.021184
@@ -1713,36 +1713,33 @@ this. -lay +inn erElem -ent .setAttribut @@ -1874,28 +1874,25 @@ this. -lay +inn erElem -ent .setAttr