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
6ce7fb77c8d966fa6593aaab3d5634a8c70a9eab
Update version string to 2.6.0-pre.4.dev
version.js
version.js
if (enyo && enyo.version) { enyo.version.spotlight = "2.6.0-pre.4"; }
JavaScript
0
@@ -59,13 +59,17 @@ .0-pre.4 +.dev %22;%0A%7D%0A
0c2bfae9f337fd19f7616fbfedb168098dfa88ad
Fix import-dir plugin
lib/init/assets/mincer/stylus/import-dir.js
lib/init/assets/mincer/stylus/import-dir.js
'use strict'; /** * lib **/ /** * lib.stylus **/ // stdlib var path = require('path'); var fs = require('fs'); // 3rd-party var stylus = require('stylus'); //////////////////////////////////////////////////////////////////////////////// // returns list of files under given pathname, but not deeper (no recursion) function find_files(pathname) { var files = []; fs.readdirSync(pathname).forEach(function (filename) { filename = path.join(pathname, filename); if (fs.statSync(filename).isFile()) { // we are interested in a first level child files only files.push(filename); return; } }); return files.sort(); } //////////////////////////////////////////////////////////////////////////////// /** * lib.stylus.import_dir(expr) -> Array * * Stylus extensions that allows to mixin all files in the specified directory. * * * ##### Usage * * Assuming `source` is a stylus file: * * import-dir('./foobar') * * We can define `import-dir` function like this: * * stylus(source).define('import-dir', lib.stylus.import_dir); **/ module.exports = function import_dir(expr) { var block = this.currentBlock, vals = [stylus.nodes['null']], pathname = path.resolve(path.dirname(this.filename), expr.val); find_files(pathname).forEach(function (file) { var expr = new stylus.nodes.Expression(), node = new stylus.nodes.String(file), body; expr.push(node); body = this.visitImport(new stylus.nodes.Import(expr)); vals = vals.concat(body.nodes); }, this); this.mixin(vals, block); return vals; };
JavaScript
0.000001
@@ -487,52 +487,8 @@ );%0A%0A - if (fs.statSync(filename).isFile()) %7B%0A @@ -542,16 +542,141 @@ es only%0A + // and the file must have .styl extension%0A if (fs.statSync(filename).isFile() && '.styl' == path.extname(filename)) %7B%0A fi
cc0026f6ed0a6f303293f555166829a56a6dedac
Remove nodes backwards in removeNodeContent, as this is a little faster.
methanal/js/Methanal/Util.js
methanal/js/Methanal/Util.js
// import Nevow.Athena /** * Add a class to an element's "className" attribute. * * This operation is intended to preserve any other values that were already * present. */ Methanal.Util.addElementClass = function addElementClass(node, cls) { var current = node.className; // trivial case, no className yet if (current == undefined || current.length === 0) { node.className = cls; return; } // the other trivial case, already set as the only class if (current == cls) { return; } var classes = current.split(' '); for (var i = 0; i < classes.length; ++i) { if (classes[i] === cls) { return; } } node.className += ' ' + cls; }; /** * Remove a class from an element's "className" attribute. * * This operation is intended to preserve any other values that were already * present. */ Methanal.Util.removeElementClass = function removeElementClass(node, cls) { var current = node.className; // trivial case, no className yet if (current == undefined || current.length === 0) { return; } // other trivial case, set only to className if (current == cls) { node.className = ""; return; } // non-trivial case var classes = current.split(' '); for (var i = 0; i < classes.length; ++i) { if (classes[i] === cls) { classes.splice(i, 1); node.className = classes.join(' '); return; } } }; /** * Remove all the children of a node. */ Methanal.Util.removeNodeContent = function removeNodeContent(node) { while (node.childNodes.length) node.removeChild(node.firstChild); }; /** * Replace all of a node's children with new ones. * * @type children: C{Array} */ Methanal.Util.replaceNodeContent = function replaceNodeContent(node, children) { Methanal.Util.removeNodeContent(node); for (var i = 0; i < children.length; ++i) node.appendChild(children[i]); }; /** * Replace a node's text node with new text. */ Methanal.Util.replaceNodeText = function replaceNodeText(node, text) { Methanal.Util.replaceNodeContent(node, [node.ownerDocument.createTextNode(text)]); }; // XXX: what does this do that's special again? // XXX: i think maybe it exposes more information when called by IE Methanal.Util.formatFailure = function formatFailure(failure) { var text = failure.error.description; if (!text) text = failure.toString(); return text; }; /** * Convert a string to a base-10 integer. * * Not quite as simple to do properly as one might think. */ Methanal.Util.strToInt = function strToInt(s) { if (typeof s !== 'string') return undefined; if (s.indexOf('x') !== -1) return undefined; if (isNaN(s)) return undefined; return parseInt(s, 10); }; /** * Pretty print a decimal number. * * Useful for formatting large currency amounts in a human-readable way. */ Methanal.Util.formatDecimal = function formatDecimal(value) { var value = value.toString(); var l = value.split('') var pointIndex = value.indexOf('.'); pointIndex = pointIndex > -1 ? pointIndex : value.length; for (var i = pointIndex - 3; i >= 1; i -= 3) { l.splice(i, 0, ','); } return l.join(''); }; /** * Create a callable that cycles through the initial inputs when called. */ Methanal.Util.cycle = function cycle(/*...*/) { var i = -1; var args = arguments; var n = args.length; return function () { i = ++i % n; return args[i]; }; } /** * Find the index of C{v} in the array C{a}. * * @return: Index of C{v} in C{a} or C{-1} if not found. */ Methanal.Util.arrayIndexOf = function arrayIndexOf(a, v) { for (var i = 0; i < a.length; ++i) if (a[i] === v) return i; return -1; }; Methanal.Util.detachWidget = function detachWidget(widget) { var children = widget.widgetParent.childWidgets; var index = Methanal.Util.arrayIndexOf(children, widget); if (index !== -1) children.splice(index, 1); delete Nevow.Athena.Widget._athenaWidgets[widget._athenaID]; }; Methanal.Util.nodeInserted = function nodeInserted(widget) { if (widget.nodeInserted !== undefined) widget.nodeInserted(); for (var i = 0; i < widget.childWidgets.length; ++i) Methanal.Util.nodeInserted(widget.childWidgets[i]); };
JavaScript
0
@@ -1641,25 +1641,17 @@ ode. -childNodes.length +lastChild )%0A @@ -1682,11 +1682,10 @@ ode. -fir +la stCh
ad6ba8bd8014569f91b55fe7ed819c64008a21b0
Fix previous commit keeping input invisible.
static/category_filter.js
static/category_filter.js
function initCategoryFilter() { var cin = document.getElementById("category-input"); var chi = document.getElementById("hidden-category-input"); var options = document.getElementsByTagName("option"); var currentCategoryId = chi.value; for (var i = 0; i < options.length; i++) { if (options[i].value === currentCategoryId) { cin.value = options[i].label; chi.value = options[i].value; } } function filterEmptyMatchesAll(text, input) { return (input === "") || Awesomplete.FILTER_CONTAINS(text, input); } var awc = new Awesomplete(cin); awc.minChars = 0; awc.maxItems = options.length; awc.sort = undefined; cin.addEventListener('click', function() { awc.evaluate(); }); cin.addEventListener("awesomplete-open", function() { this.classList.add("open"); }) cin.addEventListener("awesomplete-close", function() { this.classList.remove("open"); }) function set_hidden_category() { var catname = cin.value.toLocaleLowerCase(); chi.value = "all"; for (var i = 0; i < options.length; i++) { if (options[i].label.toLocaleLowerCase() == catname) { chi.value = options[i].value; } } } cin.addEventListener("awesomplete-selectcomplete", function() { set_hidden_category(); this.form.submit(); }); cin.form.addEventListener("submit", function() { set_hidden_category(); return true; }); } var iframe = document.getElementById("categories-iframe"); iframe.addEventListener("load", function() { var catlist = iframe.contentDocument.getElementById("categories"); document.body.appendChild(catlist); if (document.readyState !== "loading") { initCategoryFilter(); } else { window.addEventListener("DOMContentLoaded", function() { initCategoryFilter(); }); } });
JavaScript
0.999996
@@ -1412,16 +1412,46 @@ e;%0A %7D); +%0A%0A cin.style.visibility = ''; %0A%7D%0A%0Avar
3cf2f31b5a27d2fdf8ed9a05f1e4bab3458c8abe
Add Levene's test to namespace
lib/node_modules/@stdlib/stats/lib/index.js
lib/node_modules/@stdlib/stats/lib/index.js
/** * @license Apache-2.0 * * Copyright (c) 2018 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. */ 'use strict'; /* * When adding modules to the namespace, ensure that they are added in alphabetical order according to module name. */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); // MAIN // /** * Top-level namespace. * * @namespace ns */ var ns = {}; /** * @name anova1 * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/anova1} */ setReadOnly( ns, 'anova1', require( '@stdlib/stats/anova1' ) ); /** * @name bartlettTest * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/bartlett-test} */ setReadOnly( ns, 'bartlettTest', require( '@stdlib/stats/bartlett-test' ) ); /** * @name binomialTest * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/binomial-test} */ setReadOnly( ns, 'binomialTest', require( '@stdlib/stats/binomial-test' ) ); /** * @name chi2gof * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/chi2gof} */ setReadOnly( ns, 'chi2gof', require( '@stdlib/stats/chi2gof' ) ); /** * @name chi2test * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/chi2test} */ setReadOnly( ns, 'chi2test', require( '@stdlib/stats/chi2test' ) ); /** * @name flignerTest * @memberof ns * @readonly * @type {Namespace} * @see {@link module:@stdlib/stats/fligner-test} */ setReadOnly( ns, 'flignerTest', require( '@stdlib/stats/fligner-test' ) ); /** * @name incr * @memberof ns * @readonly * @type {Namespace} * @see {@link module:@stdlib/stats/incr} */ setReadOnly( ns, 'incr', require( '@stdlib/stats/incr' ) ); /** * @name iterators * @memberof ns * @readonly * @type {Namespace} * @see {@link module:@stdlib/stats/iter} */ setReadOnly( ns, 'iterators', require( '@stdlib/stats/iter' ) ); /** * @name kde2d * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/kde2d} */ setReadOnly( ns, 'kde2d', require( '@stdlib/stats/kde2d' ) ); /** * @name kruskalTest * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/kruskal-test} */ setReadOnly( ns, 'kruskalTest', require( '@stdlib/stats/kruskal-test' ) ); /** * @name kstest * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/kstest} */ setReadOnly( ns, 'kstest', require( '@stdlib/stats/kstest' ) ); /** * @name lowess * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/lowess} */ setReadOnly( ns, 'lowess', require( '@stdlib/stats/lowess' ) ); /** * @name padjust * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/padjust} */ setReadOnly( ns, 'padjust', require( '@stdlib/stats/padjust' ) ); /** * @name pcorrtest * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/pcorrtest} */ setReadOnly( ns, 'pcorrtest', require( '@stdlib/stats/pcorrtest' ) ); /** * @name ranks * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/ranks} */ setReadOnly( ns, 'ranks', require( '@stdlib/stats/ranks' ) ); /** * @name ttest * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/ttest} */ setReadOnly( ns, 'ttest', require( '@stdlib/stats/ttest' ) ); /** * @name ttest2 * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/ttest2} */ setReadOnly( ns, 'ttest2', require( '@stdlib/stats/ttest2' ) ); /** * @name vartest * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/vartest} */ setReadOnly( ns, 'vartest', require( '@stdlib/stats/vartest' ) ); /** * @name wilcoxon * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/wilcoxon} */ setReadOnly( ns, 'wilcoxon', require( '@stdlib/stats/wilcoxon' ) ); /** * @name ztest * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/ztest} */ setReadOnly( ns, 'ztest', require( '@stdlib/stats/ztest' ) ); /** * @name ztest2 * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/stats/ztest2} */ setReadOnly( ns, 'ztest2', require( '@stdlib/stats/ztest2' ) ); // EXPORTS // module.exports = ns;
JavaScript
0.000001
@@ -2940,32 +2940,226 @@ s/kstest' ) );%0A%0A +/**%0A* @name leveneTest%0A* @memberof ns%0A* @readonly%0A* @type %7BFunction%7D%0A* @see %7B@link module:@stdlib/stats/levene-test%7D%0A*/%0AsetReadOnly( ns, 'leveneTest', require( '@stdlib/stats/levene-test' ) );%0A%0A /**%0A* @name lowe
5ac7bf4f72eaf50a76f0a592f395d3d95d892d47
Improve typing
lib/share/components/Repository/Branches.js
lib/share/components/Repository/Branches.js
// @flow import * as React from 'react' import { connect } from 'react-redux' import { type Match } from 'react-router-dom' import type { Dispatch } from 'redux' import Panel from '../common/blocks/Panel' import List from '../common/layouts/List' import type { ReducersStateT } from '../../ducks' import * as BranchesAction from '../../ducks/repository/branches' import type { BranchT } from '../../../types/gh' export const Branches = ({ branches, defaultBranchName, match }: { branches: Array<BranchT>, defaultBranchName: string, match: $Shape<Match<{ owner: string, repo: string }>> }) => { const defaultBranch: BranchT = branches.find( branch => branch.name === defaultBranchName ) || { commit: { author: { date: '', name: '' }, message: '', sha: '' }, name: '' } const activeBranches = branches.filter( branch => branch.name !== defaultBranchName ) return ( <div> <Panel> <Panel.Header>Default branch</Panel.Header> <Panel.Body> <List lined> <li> <a href={`/${match.params.owner}/${match.params.repo}/tree/${ defaultBranch.name }`} > {defaultBranch.name} </a> &nbsp; Updated{' '} <time-ago datetime={defaultBranch.commit.author.date} /> by&nbsp; <a href={`/${defaultBranch.commit.author.name}`}> {defaultBranch.commit.author.name} </a> </li> </List> </Panel.Body> </Panel> <Panel> <Panel.Header>Active branches</Panel.Header> <Panel.Body> <List lined> {activeBranches.map((branch, i) => ( <li key={i}> <a href={`/${match.params.owner}/${match.params.repo}/tree/${ branch.name }`} > {branch.name} </a> &nbsp; Updated <time-ago datetime={branch.commit.author.date} />{' '} by&nbsp; <a href={`/${branch.commit.author.name}`}> {branch.commit.author.name} </a> </li> ))} </List> </Panel.Body> </Panel> </div> ) } export default connect<_, _, *, _, *, _>(({ branches }: ReducersStateT) => ({ branches }))( class BranchesContainer extends React.Component<{ branches: Array<BranchT>, defaultBranchName: string, dispatch: Dispatch<*>, match: $Shape<Match<{ owner: string, repo: string }>> }> { async componentDidMount() { const { dispatch, match: { params: { owner, repo } } } = this.props dispatch(await BranchesAction.fetch({ owner, repo })) } render() { return <Branches {...this.props} /> } } )
JavaScript
0.000001
@@ -412,78 +412,20 @@ h'%0A%0A -export const Branches = (%7B%0A branches,%0A defaultBranchName,%0A match%0A%7D: +type Props = %7B%0A @@ -480,16 +480,41 @@ string,%0A + dispatch: Dispatch%3C*%3E,%0A match: @@ -561,17 +561,517 @@ ing %7D%3E%3E%0A - %7D +%0Aexport default connect%3C_, ReducersStateT, *, _, *, _%3E((%7B branches %7D) =%3E (%7B%0A branches%0A%7D))(%0A class BranchesContainer extends React.Component%3CProps%3E %7B%0A async componentDidMount() %7B%0A const %7B%0A dispatch,%0A match: %7B%0A params: %7B owner, repo %7D%0A %7D%0A %7D = this.props%0A dispatch(await BranchesAction.fetch(%7B owner, repo %7D))%0A %7D%0A%0A render() %7B%0A return %3CBranches %7B...this.props%7D /%3E%0A %7D%0A %7D%0A)%0A%0Aexport const Branches = (%7B branches, defaultBranchName, match %7D: * ) =%3E %7B%0A @@ -2802,586 +2802,4 @@ )%0A%7D%0A -%0Aexport default connect%3C_, _, *, _, *, _%3E((%7B branches %7D: ReducersStateT) =%3E (%7B%0A branches%0A%7D))(%0A class BranchesContainer extends React.Component%3C%7B%0A branches: Array%3CBranchT%3E,%0A defaultBranchName: string,%0A dispatch: Dispatch%3C*%3E,%0A match: $Shape%3CMatch%3C%7B owner: string, repo: string %7D%3E%3E%0A %7D%3E %7B%0A async componentDidMount() %7B%0A const %7B%0A dispatch,%0A match: %7B%0A params: %7B owner, repo %7D%0A %7D%0A %7D = this.props%0A dispatch(await BranchesAction.fetch(%7B owner, repo %7D))%0A %7D%0A%0A render() %7B%0A return %3CBranches %7B...this.props%7D /%3E%0A %7D%0A %7D%0A)%0A
0307484ea000d395717809b9dc83398916f5f599
update leave room
webhook.js
webhook.js
const express = require('express'); const middleware = require('@line/bot-sdk').middleware; const Client = require('@line/bot-sdk').Client; const bodyParser = require('body-parser'); const app = express(); const config = { channelAccessToken: 'Aewq2lkqZvmE/54OzmL7J0IUUdw7GRHCW1Bqxj0VKvB1D2CQcZVjKCDj6Eyi13cNVpI9x+KRnNa00cUrWW8cmQgrjx/Q7FzfOqDxwNuUHgfZuUm+0qu63294G79KOc0cFG2UenM1yjxLPmchGkU1CgdB04t89/1O/w1cDnyilFU=', channelSecret: 'b712a0d41b0373f21b18bff87a5ee97d' }; const client = new Client({ channelAccessToken: 'Aewq2lkqZvmE/54OzmL7J0IUUdw7GRHCW1Bqxj0VKvB1D2CQcZVjKCDj6Eyi13cNVpI9x+KRnNa00cUrWW8cmQgrjx/Q7FzfOqDxwNuUHgfZuUm+0qu63294G79KOc0cFG2UenM1yjxLPmchGkU1CgdB04t89/1O/w1cDnyilFU=', channelSecret: 'b712a0d41b0373f21b18bff87a5ee97d' }); app.use(middleware(config)); app.use(bodyParser.json()); const server = app.listen(process.env.PORT || 5000, () => { console.log('Listening on port ' + server.address().port); }); app.post('/', (req,res) => { res.status(200).send(req.body); console.log(req.body.events[0]); if(req.body.events[0].type === 'message') { if(req.body.events[0].message.type === 'text') { const msg = req.body.events[0].message; console.log(msg.text); client.replyMessage(req.body.events[0].replyToken, { type: 'text', text: 'gak usah sok-sok ' + msg.text + ' ngentot!'}); return; } } });
JavaScript
0.000001
@@ -1008,24 +1008,23 @@ ;%0A cons -ole.log( +t ei = req.body @@ -1037,34 +1037,36 @@ s%5B0%5D -) ;%0A -if(req.body.events%5B0%5D +console.log(ei);%0A if(ei .typ @@ -1093,34 +1093,18 @@ %0A if( -req.body.events%5B0%5D +ei .message @@ -1149,35 +1149,289 @@ g = -req.body.events%5B0%5D.message; +ei.message;%0A if(msg.text === 'bye ngentott')%0A %7B%0A client.replyMessage(ei.replyToken, %7B type: 'text', text: 'jangan kangen aku yaahh!!'%7D);%0A if(ei.source.type === 'room')%0A %7B%0A client.leaveRoom(ei.source.roomId);%0A %7D%0A return;%0A %7D %0A @@ -1504,32 +1504,40 @@ s%5B0%5D.replyToken, +%0A %7B type: 'text',
877e995f7ce42de6ba6cbd6727402607cd5e3929
Use strict equality
webster.js
webster.js
(function() { var root = this; var webster = root.webster = {}; var each = webster.each = function(dict, fn, context) { if (dict == undefined) return; else if (fn == undefined) return; else if (context != undefined) return each(dict, fn.bind(context)); for (var key in dict) { if (dict.hasOwnProperty(key)) { fn(key, dict[key]); } } } var map = webster.map = function(dict, fn, context) { if (context != undefined) return map(dict, fn.bind(context)); var mapped = {}; each(dict, function(key, value) { var result = fn(key, value) mapped[result[0]] = result[1]; }); return mapped; } var foldl = webster.foldl = function(dict, start, fn, context) { if (context != undefined) return foldl(dict, start, fn.bind(context)); var accumulator = start; each(dict, function(key, value) { accumulator = fn(key, value, accumulator) }); return accumulator; } var keys = webster.keys = function(dict) { return foldl(dict, [], function(key, value, accumulator) { accumulator.push(key); return accumulator; }); } var values = webster.values = function(dict) { return foldl(dict, [], function(key, value, accumulator) { accumulator.push(value); return accumulator; }); } }).call(this);
JavaScript
0.000023
@@ -131,16 +131,17 @@ (dict == += undefin @@ -170,16 +170,17 @@ f (fn == += undefin @@ -206,32 +206,33 @@ e if (context != += undefined) retu @@ -448,32 +448,33 @@ if (context != += undefined) retu @@ -728,32 +728,32 @@ fn, context) %7B%0A - if (context @@ -754,16 +754,17 @@ ntext != += undefin
d65ca352f10d420d9bf629b4b95441ed79cfa517
Update container.js
static/views/container.js
static/views/container.js
define([ 'jquery', 'underscore', 'views/base', 'globals/eventbus', 'bootbox', 'modules/cloudstore', 'codemirror', 'cm.vim', 'cm.clike', 'cm.placeholder', //'codemirror.src', 'css!libs/codemirror/codemirror.css', 'add2home', 'css!libs/add2home/add2home.css', 'sha256', 'aes'], function($, _, BaseView, EventBus, bootbox, CloudStore, CodeMirror) { "use strict"; console.log("ContainerView."); function isiOS() { return (/iP(hone|od|ad)/.test( navigator.userAgent )); } var ContainerView = BaseView.extend({ el: $('#container'), message: undefined, editor: undefined, events: { "keyup #password": "passwordsMatch", "keyup #password2": "passwordsMatch", "click #encrypt": "encryptMessage", "click #decrypt": "decryptMessage", "click #message": "refreshMessage", "keyup #message": "refreshMessage", "click #clearMessage": "clearMessage", "click #dbChooseFile": "readFile", "click #dbSaveFile": "saveFile", "click #backToTop": "backToTop", "click #logout": "logout", "click #keyMapVim": "toggleKeyMapVim" }, logout: function () { CloudStore.logout(); }, readFile: function () { console.group("readFile"); var promise = CloudStore.readFile(); var message = this.message; promise.done( function( text, location, fileName ) { console.log("read: " + location.join('/') + ', ' + fileName); $('#message').val( text ) //message.setValue( text ); EventBus.trigger('message:updated'); console.groupEnd(); }); promise.fail( function( ) { console.log("read failed."); console.groupEnd(); }); }, saveFile: function () { console.log("saveFile"); //var promise = CloudStore.saveFile( this.message.getValue() ); var promise = CloudStore.saveFile( $('#message').val() ); promise.done( function( ) { console.log("saved: " + location.join('/') + ', ' + fileName); console.groupEnd(); }); promise.fail( function( ) { console.log("save failed."); console.groupEnd(); }); }, encrypt: function (text, pass) { //console.log('pass:' + pass + ' encrypt IN:' + text); var key = Sha256.hash(pass); var encrypted = Aes.Ctr.encrypt(text, key, 256); //console.log('encrypt OUT:' + encrypted); return encrypted; }, decrypt: function (text, pass) { //console.log('pass:' + pass + ' decrypt IN:' + text); var key = Sha256.hash(pass); var decrypted = Aes.Ctr.decrypt(text, key, 256); //console.log('decrypt OUT:' + decrypted); return decrypted; }, encryptMessage: function() { console.group("encryptMessage()"); if ( this.passwordsMatch() ) { $('#message').val( this.encrypt( $('#message').val(), $('#password').val() ) ); //this.message.setValue( this.encrypt( this.message.getValue(), $('#password').val() ) ); EventBus.trigger('message:updated'); } console.groupEnd(); }, decryptMessage: function () { console.group("decryptMessage()"); if( this.passwordsMatch() ) { $('#message').val( this.decrypt( $('#message').val(), $('#password').val() ) ); //this.message.setValue( this.decrypt( this.message.getValue(), $('#password').val() ) ); EventBus.trigger('message:updated'); } console.groupEnd(); }, refreshMessage: function () { console.log("refreshMessage()"); var m = $('#message'); $("#count").text( m.val().length ); m.autosize({ append: '\n'}); m.trigger('autosize.resize'); //$("#count").text( this.message.getValue().length ); //this.message.renderer.adjustWrapLimit() //this.message.resize(); }, clearMessage: function () { var message = this.message; bootbox.confirm("Clear message?", function(result) { if(result == true) { $('#message').val(''); $('#message').trigger('change'); //message.setValue(''); EventBus.trigger('message:updated'); } }); }, passwordsMatch: function () { console.log("passwordsMatch()"); if( $('#password').val() == $('#password2').val() ) { $('#passGroup').removeClass("has-error"); $('#passwordError').addClass("hidden"); return true; } $('#passGroup').addClass("has-error"); $('#passwordError').removeClass("hidden"); this.backToTop(); return false; }, backToTop: function () { $("html, body").animate({ scrollTop: 0 }, "slow"); }, toggleKeyMapVim: function () { if(this.editor.getOption("keyMap") == "vim") { this.editor.setOption("keyMap","default"); $('#keyMapVim').html('Mode: Vim'); } else { this.editor.setOption("keyMap","vim"); $('#keyMapVim').html('<strong>Mode: Vim</strong>'); } }, initialize: function(options) { console.log("ContainerView()"); BaseView.prototype.initialize.call(this, options); //this.message = window.ace.edit("message"); //this.message.setOptions({ // minLines: 10, // maxLines: 1000 //}); var self = this; if( ! isiOS() ) { console.log('Initializing CodeMirror.'); $('#keyMapVim').removeClass('hidden'); this.editor = CodeMirror.fromTextArea(document.getElementById("message"), { lineNumbers: true, styleActiveLine: true, matchBrackets: true, lineWrapping: true, showCursorWhenSelecting: true, viewportMargin: Infinity, mode: "text/x-csrc", keyMap: "default" }); this.editor.on("change", function(editor, change) { editor.save(); self.refreshMessage(); }); this.editor.on('keypress', function(editor, e) { //console.log(e.keyCode); }); } this.refreshMessage(); EventBus.on('message:updated', function(){ console.log('message:updated'); if( ! isiOS() ) { this.editor.setValue( $('#message').val() ); } //$('#message').select(); this.refreshMessage(); }, this); }, destroy: function() { EventBus.off('message:updated'); BaseView.prototype.destroy.call(this); } }); return ContainerView; });
JavaScript
0.000001
@@ -2016,32 +2016,50 @@ done( function( +location, fileName ) %7B%0A cons
17ca154352dc918e47840497f544b862e2b89a49
add response check to prevent unexpected exception
api/api-proxy.js
api/api-proxy.js
/** * proxy request to backend */ const request = require('request'); const _ = require('lodash'); const Promise = require('bluebird'); const logger = require('../mw/logger'); const appConfig = require('../config/env'); const debugLevel = appConfig.getProxyDebugLevel(); if (debugLevel && debugLevel > 0) { if (debugLevel >= 1) request.debug = true; if (debugLevel >= 2) require('request-debug')(request); } exports.getProxyOptions = getProxyOptions; exports.dispatchRequest = function () { return getApiPromise.apply(this, Array.from(arguments)); }; /** * * @param apiEndpoint * @param needPromise * @param options */ function getApiPromise(apiEndpoint, needPromise, options) { let apiRequest = undefined; const ctx = this; const req = ctx.req; const p = new Promise(function (resolve, reject) { apiRequest = req.pipe(request(getProxyOptions.call(ctx, apiEndpoint, options), function (err, response, body) { if (err) { logger.error(err); } if (response.statusCode !== 200) { reject({body, response, err}); } else { resolve({body, response}); } })); }); if (!needPromise) { apiRequest.pipe(ctx.res); } return p; } /** * * @param {string} apiEndPoint * @param {object} options * @returns {object} */ function getProxyOptions(apiEndPoint, options = {}) { let defaultOptions = { url: (this.url && options.prefix) ? this.url.substring(options.prefix.length) : '', baseUrl: apiEndPoint ? apiEndPoint : '', method: this.method, // json: true, // gzip: true }; if (!_.isEmpty(options)) { defaultOptions = Object.assign(defaultOptions, options); } return defaultOptions; }
JavaScript
0
@@ -996,16 +996,29 @@ if ( +!response %7C%7C response
b6fd0b2957fe118e98a2144c6c96d5a99c74c050
Add rescue operation title as an optional 256 byte string.
api/db/rescue.js
api/db/rescue.js
'use strict' module.exports = function (sequelize, DataTypes) { let Rescue = sequelize.define('Rescue', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4 }, active: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true }, client: { type: DataTypes.STRING, allowNull: true }, codeRed: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }, data: { type: DataTypes.JSONB, allowNull: true }, epic: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }, open: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true }, notes: { type: DataTypes.TEXT, allowNull: false, defaultValue: '' }, platform: { type: DataTypes.ENUM('xb', 'pc', 'unknown'), allowNull: true, defaultValue: 'pc' }, quotes: { type: DataTypes.ARRAY(DataTypes.STRING), allowNull: false, defaultValue: [] }, successful: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }, system: { type: DataTypes.STRING, allowNull: true, defaultValue: null }, unidentifiedRats: { type: DataTypes.ARRAY(DataTypes.STRING), allowNull: false, defaultValue: [] } }, { paranoid: true, classMethods: { associate: function (models) { Rescue.belongsToMany(models.Rat, { as: 'rats', through: 'RescueRats' }) Rescue.belongsTo(models.Rat, { as: 'firstLimpet' }) } } }) return Rescue }
JavaScript
0
@@ -1287,24 +1287,122 @@ null%0A %7D,%0A + title: %7B%0A type: DataTypes.STRING,%0A allowNull: true,%0A defaultValue: null%0A %7D,%0A unidenti
3ecc215f5f5cc433af4c60d03af65daa63244450
Change mechanism for transform in register.js
register.js
register.js
var fs = require('fs'); var removeTypes = require('./index'); var prev = require.extensions['.js']; require.extensions['.js'] = function(module, filename) { if (filename.indexOf('node_modules') === -1) { var source = fs.readFileSync(filename, 'utf8'); module._compile(removeTypes(source), filename); } else if (prev) { prev(module, filename); } else { var source = fs.readFileSync(filename, 'utf8'); module._compile(source, filename); } };
JavaScript
0
@@ -1,14 +1,18 @@ var -fs +Module = requi @@ -15,18 +15,22 @@ equire(' -fs +module ');%0Avar @@ -68,18 +68,26 @@ );%0A%0A -var prev = +// Rather than use req @@ -105,215 +105,304 @@ ions -%5B'.js'%5D;%0A%0Arequire.extensions%5B'.js'%5D = function(module, filename) %7B%0A if (filename.indexOf('node_modules') === -1) %7B%0A var source = fs.readFileSync(filename, 'utf8');%0A module._compile(removeTypes +, swizzle Module#_compile. Not only does%0A// this typically leverage the existing behavior of require.extensions%5B'.js'%5D,%0A// but allows for use alongside other %22require extension hook%22 if necessary.%0Avar super_compile = Module.prototype._compile;%0AModule.prototype._compile = function _compile (source -) , fi @@ -412,143 +412,157 @@ ame) -;%0A %7D else if (prev) %7B%0A - - prev(module, filename);%0A %7D else %7B%0A var source = fs.readFileSync(filename, 'utf8');%0A module._compile(s +var transformedSource = filename.indexOf('node_modules/') === -1%0A ? removeTypes(source)%0A : source;%0A super_compile.call(this, transformedS ourc @@ -579,11 +579,7 @@ e);%0A - %7D%0A %7D;%0A
0fc7244dc4742b667db267a8ac9dba606b012fed
drop unused props in a11ycss plugin
a11y.css.js
a11y.css.js
const fs = require('fs') const path = require('path') const showdown = require('showdown') const fm = require('front-matter') const prism = require('prismjs') const loadLanguages = require('prismjs/components/'); loadLanguages(['scss', 'css-extras']); const DIRECTORIES = { css: { input: './css/' }, sass: { input: './sass/themes/', output: './site/_data/sass/' }, api: { input: './sass/utils/', output: './site/_data/sass/' }, assets: { js: { input: './site/assets/js/' } }, static: './site/static/' } DIRECTORIES.assets.js.output = DIRECTORIES.static DIRECTORIES.css.output = DIRECTORIES.static + 'css/' const processSassDocumentation = file => { const inputFileExtension = path.extname(file) const inputFilename = path.basename(file, inputFileExtension) const excludeFiles = ['_all'] // Exclude files that we don't want to process if (inputFileExtension !== '.scss' || excludeFiles.includes(inputFilename)) { return } const content = fs.readFileSync(file, 'utf8') const commentBlockRegex = /\/\*doc(.)*?\*\//gs const comments = Array.from(content.matchAll(commentBlockRegex), data => { return parseSassComment(data[0]) }) // Avoid crash if output directory does not exists if (!fs.existsSync(DIRECTORIES.sass.output)) { fs.mkdirSync(DIRECTORIES.sass.output) } // Write Eleventy data files fs.writeFileSync( `${DIRECTORIES.sass.output}/${inputFilename.replace('_', '')}.json`, JSON.stringify(comments, null, 2) ) } const processApiDocumentation = file => { const content = fs.readFileSync(file, 'utf8') const commentBlockRegex = /\/\*doc(.)*?\*\//gs const comments = Array.from(content.matchAll(commentBlockRegex), data => { return parseSassComment(data[0]) }) // Avoid crash if output directory does not exists if (!fs.existsSync(DIRECTORIES.api.output)) { fs.mkdirSync(DIRECTORIES.api.output) } return comments } const parseSassComment = comment => { // Remove CSS comments syntax comment = comment.replace(/(\/\*doc|\*\/)/g, '').trim() const content = fm(comment) let processedContent = new showdown.Converter({ tables: true, customizedHeaderId: true, ghCompatibleHeaderId: true }).makeHtml(content.body) const headingsRegex = /(<h([2-5]).*>(.*)<\/h[2-5]>)/gim processedContent = processedContent.replace(headingsRegex, `<h$2>$3</h$2>`) // HTML code blocks const markupRegex = /((<pre><code class="html language-html">)(.[\s\S]+?)(\/code><\/pre>))/gm const htmlRegex = /((?<=<code class="html language-html">)(.[\s\S]+?)(?=<\/code>))/gm let htmlContent = processedContent.match(htmlRegex) htmlContent = String(htmlContent).replace(/(&lt;)+/g, '<') htmlContent = htmlContent.replace(/(&gt;)+/g, '>') let processedHTML = prism.highlight(htmlContent, prism.languages.html, 'html') processedContent = processedContent.replace(markupRegex, `<div class="pre"><div>${htmlContent}</div><pre><code class="html language-html" data-language="Example">${processedHTML}</code></pre></div>`) // CSS code blocks const stylesRegex = /((<pre><code class="css language-css">)(.[\s\S]+?)(\/code><\/pre>))/gm const cssRegex = /((?<=<code class="css language-css">)(.[\s\S]+?)(?=<\/code>))/gm let cssContent = processedContent.match(cssRegex) let processedCSS = prism.highlight(String(cssContent), prism.languages.css, 'css-extras') processedContent = processedContent.replace(stylesRegex, `<div class="pre"><pre><code class="css language-css" data-language="CSS">${processedCSS}</code></pre></div>`) // SCSS code blocks const scssBlockRegex = /((<pre><code class="scss language-scss">)(.[\s\S]+?)(\/code><\/pre>))/gm const scssRegex = /((?<=<code class="scss language-scss">)(.[\s\S]+?)(?=<\/code>))/gm let scssContent = processedContent.match(scssRegex) scssContent = String(scssContent).replace(/(&amp;)+/g, '&') let processedSCSS = prism.highlight(String(scssContent), prism.languages.scss, 'scss') processedContent = processedContent.replace(scssBlockRegex, `<div class="pre"><pre><code class="scss language-scss" data-language="Sass">${processedSCSS}</code></pre></div>`) // Sass code blocks const sassBlockRegex = /((<pre><code class="sass language-sass">)(.[\s\S]+?)(\/code><\/pre>))/gm const sassRegex = /((?<=<code class="sass language-sass">)(.[\s\S]+?)(?=<\/code>))/gm const sassContent = processedContent.match(sassRegex) let processedSASS = prism.highlight(String(sassContent), prism.languages.scss, 'scss') processedContent = processedContent.replace(sassBlockRegex, `<div class="pre"><pre><code class="scss language-scss" data-language="Sass">${processedSASS}</code></pre></div>`) return { attributes: content.attributes, body: processedContent } } const generateJsonDocumentation = () => { /** * Remove output directory before creating it again * @note This is an experimental feature and requires Node v12.10.0 at least * @see https://nodejs.org/api/fs.html#fs_fs_rmdirsync_path_options */ fs.rmSync(DIRECTORIES.sass.output, { recursive: true, force: true }) fs.rmSync(DIRECTORIES.api.output, { recursive: true, force: true }) fs.readdirSync(DIRECTORIES.sass.input).forEach(file => { processSassDocumentation(DIRECTORIES.sass.input + file) }) let contentAPI = [] fs.readdirSync(DIRECTORIES.api.input).forEach((file) => { if (['_all'].includes(path.basename(file, '.scss'))) { return } contentAPI = contentAPI.concat(processApiDocumentation(DIRECTORIES.api.input + file)) }) // Write Eleventy data files fs.writeFileSync( `${DIRECTORIES.api.output}/api.json`, JSON.stringify(contentAPI, null, 2) ) } module.exports = function () { generateJsonDocumentation() }
JavaScript
0.000001
@@ -272,42 +272,8 @@ = %7B%0A - css: %7B%0A input: './css/'%0A %7D,%0A sa @@ -274,24 +274,24 @@ %7B%0A sass: %7B%0A + input: ' @@ -422,208 +422,10 @@ %0A %7D -,%0A assets: %7B%0A js: %7B%0A input: './site/assets/js/'%0A %7D%0A %7D,%0A static: './site/static/'%0A%7D%0A%0ADIRECTORIES.assets.js.output = DIRECTORIES.static%0ADIRECTORIES.css.output = DIRECTORIES.static + 'css/' +%0A%7D %0A%0Aco
08722872d4e6983da30def389882b87f09e249f7
Use regular `computed()` instead of `ember-awesome-macros`
ember/app/controllers/index.js
ember/app/controllers/index.js
import Controller from '@ember/controller'; import { inject as service } from '@ember/service'; import { conditional } from 'ember-awesome-macros'; import raw from 'ember-macro-helpers/raw'; export default Controller.extend({ account: service(), notificationsTarget: conditional('account.user', raw('notifications'), raw('timeline')), });
JavaScript
0
@@ -50,25 +50,16 @@ t %7B -inject as service +computed %7D f @@ -74,19 +74,17 @@ ber/ -service +object ';%0A -%0A impo @@ -88,27 +88,33 @@ mport %7B -conditional +inject as service %7D from @@ -118,71 +118,22 @@ om ' +@ ember --awesome-macros';%0Aimport raw from 'ember-macro-helpers/raw +/service ';%0A%0A @@ -219,17 +219,14 @@ : co -nditional +mputed ('ac @@ -238,20 +238,60 @@ .user', -raw( +function() %7B%0A return this.account.user ? 'notific @@ -301,15 +301,11 @@ ons' -), raw( + : 'tim @@ -310,16 +310,20 @@ imeline' -) +;%0A %7D ),%0A%7D);%0A
b3eb24b1afa72e0174a940c14cdcdebd3f4e5145
Remove unneeded \
add-keys.js
add-keys.js
#!/usr/bin/env node 'use strict'; const winston = require('winston'), program = require('commander'), cpr = require('cpr'), path = require('path'), exec = require('./lib/exec'), list = (val) => val ? val.split(',') : []; program .version(require('./package.json').version) .description(`Creates a new Keychain and sets as the default. Imports keys and certificates to it and enables build tool access. WARNING: Changes your default keychain.`) .option('-k, --keychain-name <name>', 'Keychain Name - default APP_NAME', process.env.APP_NAME || 'build-tools') .option('--timeout <timeout>', 'Keychain password timeout - default 1 hour', parseInt, 3600) .option('--apple-cert <cert>', 'Apple WWDR certificate - default download from apple', process.env.APPLE_CERT) .option('--app-certs <cert>', 'List of app sigining certificates - default APP_CER', list, list(process.env.APP_CERT)) .option('--app-keys <key>', 'List app sigining keys - default APP_KEY', list, list(process.env.APP_KEY)) .option('--app-key-passwords <pass>', 'App sigining key password or list of passwords - default KEY_PASSWORD', list, list(process.env.KEY_PASSWORD)) .option('--provisioning-profiles <profile>', 'Provisioning profiles - default PROVISIONING_PROFILE', list, list(process.env.PROVISIONING_PROFILE)) .option('--codesign <programs>', 'Programs that should be able to use the certificates - default codesign, productbuild', list, [ '/usr/bin/codesign', '/usr/bin/productbuild' ]) .parse(process.argv); const commands = [ // delete existing keychain `security delete-keychain "${program.keychainName}.keychain" || :`, // Create a custom keychain `security create-keychain -p gitlab "${program.keychainName}.keychain"`, // Add it to the list `security list-keychains -s "${program.keychainName}.keychain"`, // Make the custom keychain default, so xcodebuild will use it for signing `security default-keychain -s "${program.keychainName}.keychain"`, // Unlock the keychain `security unlock-keychain -p gitlab "${program.keychainName}.keychain"`, // Set keychain timeout to 1 hour for long builds `security set-keychain-settings -t ${program.timeout} -l "${program.keychainName}.keychain"` ], codesign = program.codesign.map((p) => `-T "${p}"`).join(' '); // Add the Apple developer root cert if (program.appleCert) { commands.push(`security import "${program.appleCert}" -k "${program.keychainName}.keychain" ${codesign}`); } else { commands.push( 'curl "https://developer.apple.com/certificationauthority/AppleWWDRCA.cer" > apple.cer', `security import apple.cer -k "${program.keychainName}.keychain" ${codesign}`, `rm apple.cer` ); } // Add certificates to keychain and allow codesign to access them program.appCerts && program.appCerts.forEach((appCert) => { commands.push( `security import "${appCert}" -k "${program.keychainName}.keychain" ${codesign}` ); }); program.appKeys && program.appKeys.forEach((appKey, idx) => { const password = program.appKeyPasswords[idx] || program.appKeyPasswords[0]; if (password) { commands.push( `security import "${appKey}" -k "${program.keychainName}.keychain" -P "${password}" ${codesign}` ); } else { commands.push( `security import "${appKey}" -k "${program.keychainName}.keychain" ${codesign}` ); } }); let commandPromise = exec(commands.shift()); commands.forEach((command) => { commandPromise = commandPromise.then(() => { return exec(command); }); }); commandPromise.catch((err) => { winston.error('Error setting up keychain', err); process.exit(1); }); // Put the provisioning profiles in place program.provisioningProfiles && program.provisioningProfiles.forEach((profile) => { let name = path.basename(profile, path.extname(profile)); cpr(profile, `~/Library/MobileDevice/Provisioning\ Profiles/${name}.mobileprovision`, { overwrite: true }, (err) => { if (err) { winston.error('Error copying profiles', err); process.exit(1); } }) });
JavaScript
0.000002
@@ -4071,9 +4071,8 @@ ning -%5C Pro
436927591681934174a69825d7b428913a368ac7
Clean up
rssmaker.js
rssmaker.js
//Make an rss feed for the source code of a web page var cheerio = require('cheerio'); var RSS = require('rss'); var createFeed = function createFeed (html, feed_param, params) { //Utilize cheerio to get jquery functionality var $ = cheerio.load(html); //Create the new feed var feed= new RSS(feed_param); //Get the feed entries $(params.argument_items_section).filter(function () { $(this).find(params.argument_item).each(function (index, value){ var title, url, description; title = $(this).find(params.argument_item_title).text(); url = $(this).find('a').attr('href'); //Change relative links into absolute if needed if (url.indexOf('//') == -1) { url = feed_param.site_url + url; } description = $(this).find(params.argument_item_description).text(); console.log(title, url); feed.item({ title: title, url: url, //new Date(), description: description }); }); }); var xmlString = feed.xml(); return xmlString; }; module.exports = createFeed;
JavaScript
0.000002
@@ -13,18 +13,19 @@ s feed f -o r +om the sou @@ -174,17 +174,16 @@ rams) %7B%0A -%0A //Ut @@ -490,32 +490,58 @@ var title,%0A + site_url,%0A @@ -572,17 +572,43 @@ cription -; +,%0A rootUrl;%0A %0A @@ -719,16 +719,97 @@ href');%0A + description = $(this).find(params.argument_item_description).text();%0A @@ -860,16 +860,60 @@ needed%0A + site_url = feed_param.site_url;%0A @@ -967,39 +967,181 @@ -url = feed_param.site_url + url +//get the root url from the site url%0A if (feed_param.site_url.indexOf('://') %3E -1) %7B%0A rootUrl = site_url.substr(0,site_url.indexOf('/', 8)) ;%0A @@ -1150,17 +1150,28 @@ -%7D + %7D else %7B %0A @@ -1179,113 +1179,222 @@ -description = $(this).find(params.argument_item_description).text();%0A console.log(title, url); + rootUrl = site_url.substr(0,site_url.indexOf('/', 1));%0A %7D%0A url = rootUrl + url;%0A %7D%0A //console.log(title, url);%0A //Add the new entry to the feed %0A @@ -1585,35 +1585,25 @@ -var xmlString = feed.xml(); +//Create the feed %0A @@ -1614,17 +1614,18 @@ urn -xmlString +feed.xml() ;%0A%7D;
edd538e24260f5fcfb79e091f008bf7e2fc9b91d
update InvertedIndex class to handle bad json
src/js/inverted-index.js
src/js/inverted-index.js
/* Inverted index class */ class InvertedIndex { /** * @constructor */ constructor() { this.indexMap = {}; } /** * createIndex * create an index map of an array of object * @param {Object} jsonContent an array of objects * @return {Object} */ createIndex(jsonContent) { if (!(this.isValidJson(jsonContent))) { return "invaid json"; } jsonContent.forEach((currentDocument, docId) => { let wordsInDocument = `${currentDocument.title} ${currentDocument.text}`; let currentDocumentTokens = this.getCleanTokens(wordsInDocument); this.indexBot(currentDocumentTokens, docId) }); } /** * getIndex * @return {Object} indexMap */ getIndex() { return this.indexMap; } /** * searchIndex * @param {String} terms string of terms to search for * @return {Object} An array of the search terms index */ searchIndex(terms) { let searchTermTokens = this.getCleanTokens(terms); let foundInDocuments = []; searchTermTokens.forEach((word) => { if (this.search(word)) { foundInDocuments.push(this.search(word)); } }) return foundInDocuments; } /* Helper methods */ /** * isValidJson * Check if all items in an array is a JSON valid. * @param {Object} jsonArray Array of JSON objects * @return {Boolean} */ isValidJson(jsonArray) { if (typeof jsonArray !== "object" || jsonArray.length === 0) { return false } jsonArray.forEach((currentBook) => { if (!(currentBook.hasOwnProperty("title") && currentBook.hasOwnProperty("text"))) { return false; } }); return true; } /** * getCleanTokens * sanitizes and splits a string * @param {String} string string to sanitize and tokenize * @return {Object} An array of clean splitted string */ getCleanTokens(string) { let invalidCharaters = /[^a-z0-9\s]/gi; return string.replace(invalidCharaters, " ") .toLowerCase() .split(" ") .filter((word) => { return Boolean(word); }); } /** * indexBot * maps an arrays their it docs index * @param {Object} tokens An array of words */ indexBot(tokens, docId) { tokens.forEach((token) => { if (token in this.indexMap) { if (this.indexMap[token].indexOf(docId) === -1) { this.indexMap[token].push(docId); } } else { this.indexMap[token] = [docId]; } }); } /** * search * returns an array containing document id in which a search term exist * @param {String} searchTerm A single search term string * @return {Object} An array containing index of a search term */ search(searchTerm) { let indexDatabase = this.indexMap; if (indexDatabase.hasOwnProperty(searchTerm)) { return indexDatabase[searchTerm]; } else { return false; } } }
JavaScript
0
@@ -1480,16 +1480,29 @@ %0A %7D%0A%0A + try %7B%0A%0A json @@ -1530,24 +1530,26 @@ tBook) =%3E %7B%0A + if (!( @@ -1630,24 +1630,26 @@ ) %7B%0A + return false @@ -1646,24 +1646,26 @@ turn false;%0A + %7D%0A @@ -1664,20 +1664,24 @@ %7D%0A + %7D);%0A + retu @@ -1689,16 +1689,67 @@ n true;%0A +%0A %7D%0A catch (err) %7B%0A return false%0A %7D%0A%0A %7D%0A%0A /
74e617733bb8c9efa08748abbe011d7ec52c9495
fix lint
src/lib/createActions.js
src/lib/createActions.js
// @flow import R from 'ramda'; import { createTypes as reduxSauceCreateTypes } from 'reduxsauce'; import warn from './warn'; import type { dict, thunk, CreateOfflineActionsConfigs, CreateOfflineActionsOptions, } from './types'; // matches on capital letters (except at the start & end of the string) const RX_CAPS = /(?!^)([A-Z])/g; // converts a camelCaseWord into a SCREAMING_SNAKE_CASE word const camelToScreamingSnake: string => string = R.pipe( R.replace(RX_CAPS, '_$1'), R.toUpper, ); // noop const noop = () => ({}); const omitActionMeta = R.omit(['action', 'meta']); function createTypes(config, options): { [string]: string } { /* eslint no-underscore-dangle: ["off"] */ const typesCreator = R.curry(reduxSauceCreateTypes)(R.__, options); return R.pipe( R.keys, // just the keys R.map(camelToScreamingSnake), // CONVERT_THEM R.join(' '), // space separated typesCreator, // make them into Redux Types )(config); } function transformAction(action: thunk | dict): { action: thunk, meta?: Array<string|dict> } { if (typeof action === 'object') { return { action: noop, ...action, }; } else if (typeof action === 'function') { return { action }; } return { action: noop }; } function getMeta(metaArray: ?Array<string|dict> = [], context: dict) : dict { return R.pipe( R.converge(R.concat, [ R.pipe( R.filter(v => typeof v === 'string'), R.map(v => ({ [v]: context[v] })), ), R.filter(v => typeof v === 'object'), ]), R.mergeAll, )(metaArray); } function addPayloadToEffectBody(effect, payload) : ?dict { if (typeof effect === 'object') { const { body, ...rest } = effect; return { effect: { ...rest, body: { ...body, ...payload, }, }, }; } return undefined; } function createActionCreator({ offline, commit, rollback, effect, meta, }, options) { /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "type", "argsIgnorePattern": "options" }]*/ if (typeof offline !== 'function' && typeof offline !== 'object') { throw new Error('[redux-offline-sauce] config.offline must be either a function or object'); } const offlineObj = transformAction(offline); const commitObj = transformAction(commit); const rollbackObj = transformAction(rollback); const offlineRest = omitActionMeta(offlineObj); const commitRest = omitActionMeta(commitObj); const rollbackRest = omitActionMeta(rollbackObj); return (...args) => { const offlineAction = offlineObj.action(...args); const commitAction = commitObj.action(...args); const rollbackAction = rollbackObj.action(...args); const { type: offlineType, ...payload } = offlineAction; return { type: offlineType, ...payload, payload, ...offlineRest, meta: { offline: { ...addPayloadToEffectBody(effect, payload), commit: { ...commitAction, ...commitRest, meta: getMeta(commitObj.meta, payload), }, rollback: { ...rollbackAction, ...rollbackRest, meta: getMeta(rollbackObj.meta, payload), }, }, ...meta, }, }; }; } function createCreators(config, options) { return R.pipe( R.map(value => createActionCreator(value, options)), )(config); } export default (config: ?CreateOfflineActionsConfigs, options: CreateOfflineActionsOptions) => { if (R.isNil(config)) { throw new Error('an object is required to setup types and creators'); } if (R.isEmpty(config)) { warn('empty object passed in for createOfflineActions', options); return { Types: {}, Creators: {}, merge: (Types: dict, Creators: dict): { Types: dict, Creators: dict } => ({ Types, Creators }), }; } const Types = createTypes(config, options); const Creators = createCreators(config, options); return { Types, Creators, merge: (mTypes: dict, mCreators: dict): { Types: dict, Creators: dict } => ({ Types: R.merge(mTypes, Types), Creators: R.merge(mCreators, Creators), }), }; };
JavaScript
0.000013
@@ -1095,25 +1095,27 @@ Array%3Cstring -%7C + %7C dict%3E %7D %7B%0A @@ -1348,17 +1348,19 @@ y%3Cstring -%7C + %7C dict%3E = @@ -1377,17 +1377,16 @@ t: dict) - : dict %7B @@ -1677,17 +1677,16 @@ payload) - : ?dict
9e68fbf19fd2b4fdad9d59b33bbf2c839f53202d
fix syntax error
src/lib/events/guilds.js
src/lib/events/guilds.js
/** * @file Guild events file. * @author Capuccino * @author Ovyerus */ module.exports = bot => { bot.on('guildCreate', async guild => { if (guild.members.filter(m => m.bot).filter / guild.members.size >= 0.50) { logger.info(`Detected bot collection guild '${guild.name}' (${guild.id}). Autoleaving...`); await guild.leave(); } else { if (!bot.config.url && bot.config.gameURL) { await bot.editStatus('online', { name: `${bot.config.gameName || `${bot.config.mainPrefix}help for commands!`} | ${bot.guilds.size} ${bot.guilds.size === 1 ? 'server' : 'servers'}`, type : 0, url: null }); } else { await bot.editStatus('online', { name: `${bot.config.gameName || `${bot.config.mainPrefix}help for commands!`} | ${bot.guilds.size} ${bot.guilds.size === 1 ? 'server' : 'servers'}`, type : 1, url: bot.config.gameURL }); } await bot.postGuildCount(); } }); bot.on('guildDelete', async guild => { if (!bot.config.url && bot.config.gameURL) { await bot.editStatus('online', { name: `${bot.config.gameName || `${bot.config.mainPrefix}help for commands!`} | ${bot.guilds.size} ${bot.guilds.size === 1 ? 'server' : 'servers'}`, type : 0, url: null }); } else { await bot.editStatus('online', { name: `${bot.config.gameName || `${bot.config.mainPrefix}help for commands!`} | ${bot.guilds.size} ${bot.guilds.size === 1 ? 'server' : 'servers'}`, type : 1, url: bot.config.gameURL }); } await bot.postGuildCount(); }; }); bot.on('guildMemberAdd', async (guild, member) => { let res = await bot.getGuildSettings(guild.id); if (!res || !res.greeting || !res.greeting.enabled || !res.greeting.channelID || !res.greeting.message) return; let msg = res.greeting.message.replace(/{{user}}/g, member.mention).replace(/{{name}}/g, utils.formatUsername(member)); return guild.channels.get(res.greeting.channelID).createMessage(msg); }); bot.on('guildMemberDelete', async (guild, member) => { let res = await bot.guildSettings(guild.id); if (!res || !res.goodbye || !res.goodbye.enabled || !res.goodbye.channelID || !res.goodbye.message) return; let msg = res.goodbye.message.replace(/{{user}}/g, utils.formatUsername(member)).replace(/{{name}/gi, member.username); await guild.channels.get(res.goodbye.channelID).createMessage(msg); }); };
JavaScript
0.000003
@@ -1748,19 +1748,8 @@ ();%0A - %7D;%0A
d291471c9ecbe808abf15fe0d4fe56c2feee2a49
Use standard Redux dispatch.
src/lightbox/Lightbox.js
src/lightbox/Lightbox.js
/* @flow */ import React, { PureComponent } from 'react'; import { View, StyleSheet, Dimensions, Easing } from 'react-native'; import PhotoView from 'react-native-photo-view'; import { connectActionSheet } from '@expo/react-native-action-sheet'; import type { Actions, Auth, Message } from '../types'; import connectWithActions from '../connectWithActions'; import { getAuth } from '../selectors'; import { getResource } from '../utils/url'; import AnimatedLightboxHeader from './AnimatedLightboxHeader'; import AnimatedLightboxFooter from './AnimatedLightboxFooter'; import { constructActionSheetButtons, executeActionSheetAction } from './LightboxActionSheet'; import { NAVBAR_SIZE } from '../styles'; import { getGravatarFromEmail } from '../utils/avatar'; const styles = StyleSheet.create({ img: { height: 300, flex: 1, }, header: {}, overlay: { backgroundColor: 'black', opacity: 0.8, position: 'absolute', zIndex: 1, }, container: { flex: 1, justifyContent: 'space-between', alignItems: 'center', }, }); type Props = { auth: Auth, actions: Actions, src: string, message: Message, handleImagePress: (movement: string) => void, showActionSheetWithOptions: (Object, (number) => void) => void, }; type State = { movement: 'in' | 'out', }; class Lightbox extends PureComponent<Props, State> { props: Props; state: State; state = { movement: 'out', }; handleImagePress = () => { this.setState(({ movement }, props) => ({ movement: movement === 'out' ? 'in' : 'out', })); }; handleOptionsPress = () => { const options = constructActionSheetButtons(); const cancelButtonIndex = options.length - 1; const { showActionSheetWithOptions, src, auth } = this.props; showActionSheetWithOptions( { options, cancelButtonIndex, }, buttonIndex => { executeActionSheetAction({ title: options[buttonIndex], src, auth, }); }, ); }; handlePressBack = () => { const { actions } = this.props; actions.navigateBack(); }; getAnimationProps = () => ({ easing: Easing.bezier(0.075, 0.82, 0.165, 1), duration: 300, movement: this.state.movement, }); render() { const { src, message, auth } = this.props; const footerMessage = message.type === 'stream' ? `Shared in #${message.display_recipient}` : 'Shared with you'; const resource = getResource(src, auth); const { width, height } = Dimensions.get('window'); return ( <View style={styles.container}> <AnimatedLightboxHeader onPressBack={this.handlePressBack} style={[styles.overlay, styles.header, { width }]} from={-NAVBAR_SIZE} to={0} timestamp={message.timestamp} avatarUrl={message.avatar_url || getGravatarFromEmail(message.sender_email)} senderName={message.sender_full_name} realm={auth.realm} {...this.getAnimationProps()} /> <PhotoView source={resource} style={[styles.img, { width }]} resizeMode="contain" onTap={this.handleImagePress} /> <AnimatedLightboxFooter style={[styles.overlay, { width, bottom: height - 44 }]} displayMessage={footerMessage} onOptionsPress={this.handleOptionsPress} from={height} to={height - 44} {...this.getAnimationProps()} /> </View> ); } } export default connectActionSheet( connectWithActions(state => ({ auth: getAuth(state), }))(Lightbox), );
JavaScript
0
@@ -5,16 +5,56 @@ flow */%0A +import %7B connect %7D from 'react-redux';%0A%0A import R @@ -87,24 +87,24 @@ om 'react';%0A - import %7B Vie @@ -299,19 +299,20 @@ %7B A -ctions, Aut +uth, Dispatc h, M @@ -341,64 +341,8 @@ s';%0A -import connectWithActions from '../connectWithActions';%0A impo @@ -738,16 +738,59 @@ avatar'; +%0Aimport %7B navigateBack %7D from '../actions'; %0A%0Aconst @@ -1119,24 +1119,26 @@ ,%0A -actions: Actions +dispatch: Dispatch ,%0A @@ -2092,23 +2092,24 @@ const %7B -actions +dispatch %7D = thi @@ -2125,16 +2125,17 @@ -actions. +dispatch( navi @@ -2144,16 +2144,17 @@ teBack() +) ;%0A %7D;%0A%0A @@ -3598,16 +3598,16 @@ nSheet(%0A + connec @@ -3611,19 +3611,8 @@ nect -WithActions (sta
7c545e06dbae0ac4aa433d96068dbf32a9c94f00
Fix type of cluster
cluster.js
cluster.js
/* * Copyright 2012 The Closure Compiler 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. */ /** * @fileoverview Definitions for node's cluster module. Depends on the events module. * @see http://nodejs.org/api/cluster.html * @see https://github.com/joyent/node/blob/master/lib/cluster.js * @externs * @author Daniel Wirtz <[email protected]> */ /** BEGIN_NODE_INCLUDE var cluster = require('cluster'); END_NODE_INCLUDE */ /** * @extends events.EventEmitter */ var cluster = function() {}; /** * @typedef {{exec: string, args: Array.<string>, silent: boolean}} */ cluster.Settings; /** * @type {cluster.Settings} */ cluster.settings; /** * @type {boolean} */ cluster.isMaster; /** * @type {boolean} */ cluster.isWorker; /** * @param {cluster.Settings=} settings */ cluster.setupMaster = function(settings) {}; /** * @param {Object.<string,*>} env * @return {cluster.Worker} */ cluster.fork = function(env) {}; /** * @param {function()=} callback */ cluster.disconnect = function(callback) {}; /** * @type {?cluster.Worker} */ cluster.worker; /** * @type {?Object.<string,cluster.Worker>} */ cluster.workers; /** * @constructor * @extends events.EventEmitter */ cluster.Worker = function() {}; /** * @type {string} */ cluster.Worker.prototype.id; /** * @type {child_process.ChildProcess} */ cluster.Worker.prototype.process; /** * @type {boolean} */ cluster.Worker.prototype.suicide; /** * @param {Object} message * @param {*=} sendHandle */ cluster.Worker.prototype.send = function(message, sendHandle) {}; /** */ cluster.Worker.prototype.destroy = function() {}; /** */ cluster.Worker.prototype.disconnect = function() {};
JavaScript
0.000001
@@ -950,31 +950,28 @@ */%0A%0A/**%0A * @ -extends +type events.Even @@ -994,32 +994,16 @@ cluster - = function() %7B%7D ;%0A%0A/**%0A
171880104606052a63c353afca623d1db4721674
Fix Path in /api/arch.js
api/arch.js
api/arch.js
var badges_info_list = require(process.cwd() + '/document/badges_info_list.json'); module.exports = { get_arch_list: function(Models) { return function(req, res, next) { Models['arch'].find({ uid: req.user.uid, provider: 'arch' }, function(err, result) { var temp_result = result; return res.send(temp_result); }); }; }, create_arch: function(Models) { return function(req, res, next) { var _item = req.body; Models['arch'].find({ uid: req.user.uid, provider: 'arch' }, function(err, result) { var temp_result = result; for (var i = 0; i < temp_result.length - 1; i++) { if (temp_result[i].arch_name === _item.arch_name) { return res.send({ error: true, data: temp_result[i] }); } if ((i + 1) === temp_result.length) { Models('arch').create({ aid: req.user.uid + (temp_result.length + 1), uid: req.user.uid, provider: 'arch', arch_name: _item.arch_name, information: _item.information, content: _item.content, frequency: 1, finish: false, create_time: new Date() }, function(err, result) { return res.send({ error: null, data: result[i] }); }); } } }); }; }, create_badge: function(Models) { return function(req, res, next) { var _item = req.body; Models['arch'].find({ uid: req.user.uid, provider: 'badge' }, function(err, result) { var temp_result = result; for (var i = 0; i < temp_result.length - 1; i++) { if (temp_result[i].arch_name === _item.arch_name) { return res.send({ error: true, data: temp_result[i] }); } if ((i + 1) === temp_result.length) { Models('arch').create({ aid: req.user.uid + (temp_result.length + 1), uid: req.user.uid, provider: 'arch', arch_name: _item.arch_name, information: _item.information, content: _item.content, frequency: 1, finish: false, create_time: new Date() }, function(err, result) { return res.send({ error: null, data: result[i] }); }); } } }); }; }, get_badge: function(Models) { return function(req, res, next) { Models['arch'].findOne({ uid: req.user.uid, provider: 'badge', content: req.params.aid }, function(err, result) { var temp_result = result; return res.send(temp_result); }); }; }, get_badge_list: function(Models) { return function(req, res, next) { Models['arch'].find({ uid: req.user.uid, provider: 'badge' }, function(err, result) { var temp_result = result; return res.send(temp_result); }); }; }, update_badge: function(Modals) { return function(req, res, next) { if (!!req.user.uid && !!req.body.badge_name) { Modals['arch'].findOne({ uid: req.user.uid, provider: 'badge', content: req.body.badge_name }, function(err, badge_info) { if (badge_info.finish) { return res.send(badge_info); } else { Modals['arch'].update({ uid: req.user.uid, provider: 'badge', content: req.body.badge_name }, { finish: true }, function(err, update_date) { if (/step_/.test(req.body.badge_name)) { Modals['user'].findOne({ uid: req.user.uid }, function(err, user_result) { var step_level = req.body.badge_name.replace('step_', ''); console.log(step_level); if (user_result.step_level < step_level) { Modals['user'].update({ uid: req.user.uid }, { step_level: step_level }, function(err, update_user) {}); } }); } return res.send(badge_info); }); } }); } else { return next(); } }; } }
JavaScript
0.000004
@@ -1,12 +1,40 @@ +var path = require('path');%0A var badges_i @@ -52,16 +52,26 @@ require( +path.join( process. @@ -75,18 +75,17 @@ ss.cwd() - + +, '/docum @@ -111,16 +111,17 @@ t.json') +) ;%0Amodule
0f3c00ef8271ff8da17bca311c3fb2c8d4aafd9b
remove unnecessary nesting; #345
imports/i18n/en/errors.js
imports/i18n/en/errors.js
const error = { error: { '403': 'This username already exists', nameRequired: 'Please enter the name of this vessel', callsignUnique: 'A vessel with this call sign is already existing', eniUnique: 'A vessel with this ENI number is already existing', imoUnique: 'A vessel with this IMO number is already existing', mmsiUnique: 'A vessel with this MMSI number is already existing', missingField: 'Please fill out all fields', incorrectPassword: 'This password seems to be incorrect', noAccountFound: 'No account with this username or email could be found', multipleAccountsFound: 'There are multiple accounts with this email. Please use the username', passwordsDoNotMatch: 'The passwords do not match', passwordTooShort: 'The password has to have at least 8 characters' } } export default error
JavaScript
0.000011
@@ -13,21 +13,8 @@ = %7B%0A - error: %7B%0A '4 @@ -50,18 +50,16 @@ xists',%0A - nameRe @@ -106,18 +106,16 @@ essel',%0A - callsi @@ -176,18 +176,16 @@ sting',%0A - eniUni @@ -244,18 +244,16 @@ ing',%0A - - imoUniqu @@ -308,18 +308,16 @@ sting',%0A - mmsiUn @@ -376,18 +376,16 @@ sting',%0A - missin @@ -422,18 +422,16 @@ ields',%0A - incorr @@ -482,18 +482,16 @@ rrect',%0A - noAcco @@ -559,18 +559,16 @@ und',%0A - - multiple @@ -654,18 +654,16 @@ rname',%0A - passwo @@ -707,18 +707,16 @@ match',%0A - passwo @@ -780,12 +780,8 @@ rs'%0A - %7D%0A %7D%0A%0Ae
8ccd20761b7cfad064a548a7b79a6bce274795a2
use super-fancy destructuring, because i can
test/date.js
test/date.js
describe('rfc2822 dates', function() { const { expect } = require('chai'); const { date } = require('../email'); var d_utc = dt => date.getRFC2822DateUTC(new Date(dt)); var d = (dt, utc = false) => date.getRFC2822Date(new Date(dt), utc); it('should match standard regex', function(done) { // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 // thanks to moment.js for the listing: https://github.com/moment/moment/blob/a831fc7e2694281ce31e4f090bbcf90a690f0277/src/lib/create/from-string.js#L101 var rfc2822re = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/; expect(d(0)).to.match(rfc2822re); expect(d(329629726785)).to.match(rfc2822re); expect(d(729629726785)).to.match(rfc2822re); expect(d(1129629726785)).to.match(rfc2822re); expect(d(1529629726785)).to.match(rfc2822re); done(); }); it('should produce proper UTC dates', function(done) { expect(d_utc(0)).to.equal('Thu, 01 Jan 1970 00:00:00 +0000'); expect(d_utc(0)).to.equal(d(0, true)); expect(d_utc(329629726785)).to.equal('Thu, 12 Jun 1980 03:48:46 +0000'); expect(d_utc(329629726785)).to.equal(d(329629726785, true)); expect(d_utc(729629726785)).to.equal('Sat, 13 Feb 1993 18:55:26 +0000'); expect(d_utc(729629726785)).to.equal(d(729629726785, true)); expect(d_utc(1129629726785)).to.equal('Tue, 18 Oct 2005 10:02:06 +0000'); expect(d_utc(1129629726785)).to.equal(d(1129629726785, true)); expect(d_utc(1529629726785)).to.equal('Fri, 22 Jun 2018 01:08:46 +0000'); expect(d_utc(1529629726785)).to.equal(d(1529629726785, true)); done(); }); });
JavaScript
0.000002
@@ -81,14 +81,57 @@ st %7B - date +%0A%09%09date: %7B getRFC2822Date, getRFC2822DateUTC %7D,%0A%09 %7D = @@ -167,29 +167,24 @@ utc = dt =%3E -date. getRFC2822Da @@ -238,13 +238,8 @@ =%3E -date. getR
1d096d4aaaab9ab345e7ceb954224f3f6cc8370a
test typo
test/json.js
test/json.js
var connect = require('../') , should = require('./shared'); var app = connect(); app.use(connect.bodyParser()); app.use(function(req, res){ res.end(JSON.stringify(req.body)); }); app.use(function(err, req, res, next){ res.end(err.message); }); describe('connect.bodyParser()', function(){ should['default request body'](app); it('should ignore GET', function(done){ app.request() .get('/') .set('Content-Type', 'application/json') .write('{"user":"tobi"}') .end(function(res){ res.body.should.equal('{}'); done(); }); }) it('should parse JSON', function(done){ app.request() .post('/') .set('Content-Type', 'application/json') .write('{"user":"tobi"}') .end(function(res){ res.body.should.equal('{"user":"tobi"}'); done(); }); }) it('should fail gracefully', function(done){ app.request() .post('/') .set('Content-Type', 'application/json') .write('{"user"') .end(function(res){ res.body.should.equal('Unexpected end of input'); done(); }); }) })
JavaScript
0.000454
@@ -96,26 +96,20 @@ connect. -bodyParser +json ());%0A%0Aap
f24bea00259f8fcea7a6a8efc75e2e430208d85c
Fix undefined UnsupportedModal reference
troposphere/static/js/modals/UnsupportedModal.react.js
troposphere/static/js/modals/UnsupportedModal.react.js
import React from 'react'; import BootstrapModalMixin from 'components/mixins/BootstrapModalMixin.react'; import modernizrTest from 'components/modals/unsupported/modernizrTest.js'; import BreakingFeatureList from 'components/modals/unsupported/BreakingFeatureList.react'; import chrome from 'images/google_chrome_icon.png'; import firefox from 'images/firefox_icon.png'; import safari from 'images/safari_icon.png'; export default React.createClass({ displayName: "UnsupportedModal", mixins: [BootstrapModalMixin], confirm: function () { this.hide(); this.props.onConfirm(); }, render: function () { var content = ( <div> <h4>This application uses features your browser does not support</h4> <p>For the best user experience please update your browser. We recomend using a desktop or laptop with one of the following browsers.</p> <div className="browser-list text-center clearfix"> <div className="browser col-sm-4"> <a href="https://google.com/chrome/browser"> <img src={chrome} alt="Chrome Browser" /> <p>Chrome</p> </a> </div> <div className="browser col-sm-4"> <a href="https://mozilla.org/en-US/firefox/new"> <img src={firefox} alt="Firefox Browser" /> <p>Firefox</p> </a> </div> <div className="browser col-sm-4"> <a href="https://support.apple.com/en_US/downloads/safari"> <img src={safari} alt="Safari Browser" /> <p>Safari</p> </a> </div> </div> <hr /> <h4>Features that may cause problems with your browser</h4> <BreakingFeatureList /> </div> ); return ( <div className="modal fade"> <div className="modal-dialog"> <div className="modal-content"> <div className="modal-header"> <h3>Unsupported Features</h3> </div> <div className="modal-body"> {content} </div> <div className="modal-footer"> <button className="btn btn-primary" onClick={this.confirm} >Try Anyway</button> </div> </div> </div> </div> ); } }); const showModal = function(callback) { let props = { backdrop:"static", keyboard:false }; ModalHelpers.renderModal(UnsupportedModal, props, callback); } export { UnsupportedModal as default }; export { showModal };
JavaScript
0.000009
@@ -414,24 +414,93 @@ g';%0A -%0A%0Aex +im port -default +ModalHelpers from 'components/modals/ModalHelpers';%0A%0A%0Aconst UnsupportedModal = Rea
85745950c5c0fa1792db7b73562eaf772a8a5f8b
Fix Unit test to detect Bug for arguments in different case.
tests/connectControllerLoadTest.js
tests/connectControllerLoadTest.js
'use strict' const controller = require('./../lib/connectController') const userCtr = { 'groups': function (nr, res) { res.render('viewName', nr) }, 'index': function () {return 'I am index'}, 'index_id': function (id) {return id}, 'index_id_members': function () {return 'I am index_id_members'}, 'dummy_nr_members': function (nr) {return nr}, 'dummy_nr_teams': function (nr, arg1, arg2) {return { 'nr': nr, 'arg1': arg1, 'arg2': arg2 }}, } /** * mws is a Middleware of Middlewares (Router objects). * Each mws element is a Router corresponding to each controller. * In this case there is a single Router corresponding to userCtr source. * In turn, each Router contains a Middleware for each method of the controller. */ const mws = controller(userCtr) module.exports.testLoadControllers = function(test) { test.expect(1) test.equal(mws.stack.length, 6) // 5 actions/handlers for userCtr object test.done() } module.exports.testControllerIndex = function(test) { test.expect(1) const router = mws const req = { 'url': '/', 'method': 'get'} const res = { 'render': (view, ctx) => test.equal(ctx, 'I am index')} router(req, res) test.done() } module.exports.testControllerIndexId = function(test) { test.expect(1) const router = mws const req = { 'url': '/27', 'method': 'get'} const res = { 'render': (view, ctx) => test.equal(ctx, '27')} router(req, res) test.done() } module.exports.testControllerDummyNrMembers = function(test) { test.expect(1) const router = mws const req = { 'url': '/dummy/31/members', 'method': 'get'} const res = { 'render': (view, ctx) => test.equal(ctx, '31')} router(req, res) test.done() } module.exports.testControllerGroups = function(test) { test.expect(1) const router = mws const req = { 'url': '/groups?nr=24', 'method': 'get', 'query': {'nr': '24' } } const res = { 'render': (view, ctx) => test.equal(ctx, '24')} router(req, res) test.done() } module.exports.testControllerRouteAndQueryParameters = function(test) { test.expect(3) const router = mws const req = { 'url': '/dummy/71/teams?arg1=abc&arg2=super', 'method': 'get', 'query': {'arg1': 'abc', 'arg2': 'super'} } const res = { 'render': (view, ctx) => { test.equal(ctx.nr, '71') test.equal(ctx.arg1, 'abc') test.equal(ctx.arg2, 'super') test.done() }} router(req, res) }
JavaScript
0
@@ -215,17 +215,21 @@ 'index_ -i +teamI d': func @@ -234,17 +234,21 @@ nction ( -i +teamI d) %7Bretu @@ -250,17 +250,21 @@ %7Breturn -i +teamI d%7D, %0D%0A
cb39a7ae594c39155e544e41c99b4f983a3000e1
Fix throw assertions on plan specs
test/plan.js
test/plan.js
import 'babel-register'; import is from 'check-types'; import test from 'ava'; import Pagarme from '../src/pagarme'; import Plan from '../src/plan'; test.beforeEach(t => Pagarme.setApiKey('ak_test_TSgC3nvXtdYnDoGKgNLIOfk3TFfkl9')); test('create a plan', async t => { let plan = new Plan({ amount: 1000, days: 30, name: 'test-api' }); let p = await plan.create(); t.ok(is.not.undefined(p)); t.ok(is.object(p)); t.is(p.object, 'plan'); t.is(p.amount, 1000); t.is(p.days, 30); t.is(p.name, 'test-api'); }); test('create a plan without the mandatory fields', t => { let plan = new Plan(); t.throws(plan.create()); }); test('create a plan with an id', t => { let plan = new Plan({ amount: 1000, days: 30, name: 'test-api', id: 25000 }); t.throws(plan.create()); }); test('find all plans', async t => { let plan = new Plan(); let plans = await plan.findAll(); t.ok(is.not.undefined(plans)); t.ok(is.array(plans)); t.is(plans[0].object, 'plan'); }); test('find a plan with an id', async t => { let plan = new Plan({ id: 25937 }); let p = await plan.find(); t.ok(is.not.undefined('object')); t.ok(is.object(p)); t.is(p.object, 'plan'); t.is(p.id, 25937); }); test('find a plan passing an id', async t => { let plan = new Plan(); let p = await plan.find(25937); t.ok(is.not.undefined('object')); t.ok(is.object(p)); t.is(p.object, 'plan'); t.is(p.id, 25937); }); test('find a plan with no id', t => { let plan = new Plan(); t.throws(plan.find()); });
JavaScript
0
@@ -654,32 +654,38 @@ ;%0A%0A t.throws( +() =%3E plan.create());%0A @@ -676,32 +676,32 @@ plan.create());%0A - %7D);%0A%0Atest('creat @@ -858,24 +858,30 @@ t.throws( +() =%3E plan.create( @@ -1333,33 +1333,35 @@ id, 25937);%0A%7D);%0A +// %0A - test('find a pla @@ -1633,32 +1633,32 @@ = new Plan();%0A%0A - t.throws(pla @@ -1654,16 +1654,22 @@ .throws( +() =%3E plan.fin
263bb3a2640f29e9f5d3dc867e1f0150d8da507f
update Nightwatch.js E2E tests to pass with updated homepage designs
tests/e2e/pattern-lab-compiling.js
tests/e2e/pattern-lab-compiling.js
// tests/e2e/pattern-lab-compiling.js const sauce = require('../../scripts/nightwatch-sauce'); const url = require('url'); const querystring = require('querystring'); const fetch = require('node-fetch'); const { spawnSync } = require('child_process'); const { NOW_TOKEN } = process.env; if (!NOW_TOKEN) { console.error('Need to have env var of NOW_TOKEN set'); process.exit(1); } const getDeployUrl = async () => { // @todo determine if this is even needed since we have `deployedUrl` from deploy command const nowEndpoint = url.resolve('https://api.zeit.co/v2/now/deployments', `?${querystring.stringify({ teamId: 'boltdesignsystem', })}`); const nowDeploys = await fetch(nowEndpoint, { headers: { 'Authorization': `Bearer ${NOW_TOKEN}`, 'Content-Type': 'application/json', }, }).then(res => res.json()); if (!nowDeploys) { console.error('Did not get any info on latest now deploys...'); process.exit(1); } nowDeploys.deployments.sort((a, b) => { return a.created - b.created; }).reverse(); const latestDeploy = nowDeploys.deployments[0]; console.log('Latest now.sh Deploy:'); console.log(latestDeploy); return 'https://' + latestDeploy.url; } let testingUrl = ''; // cached deploy url we grab from the now.sh API module.exports = { async beforeEach(browser, done) { async function getUrl() { return await getDeployUrl(); } // log the url being tested against to make it easier to debug failed deploys function logTestingUrl(){ console.log(`Running tests against the ${testingUrl} deploy url.`); } // grab the latest testing URL from now.sh if we haven't grabbed it yet. if (testingUrl === '') { getUrl().then(deployUrl => { testingUrl = deployUrl; // logTestingUrl(); done(); }); // otherwise let's be efficient and use the deploy url we already got } else { logTestingUrl(); done(); } }, 'Bolt Docs: Verify Docs Site Compiled + Deployed': function (browser) { browser .url(`${testingUrl}`) .waitForElementVisible('body.c-bolt-site', 1000) .assert.containsText('h1', 'Bolt Design System') .end() }, 'Pattern Lab: Confirm Successful Now.sh Deploy + Pattern Lab Compiled': function (browser) { browser .url(`${testingUrl}/pattern-lab/index.html`) .waitForElementVisible('.pl-c-body', 1000) .verify.title('Pattern Lab - components-overview') .end(); }, tearDown: sauce, };
JavaScript
0
@@ -205,18 +205,16 @@ %0Aconst %7B -%0A spawnSy @@ -215,17 +215,17 @@ pawnSync -%0A + %7D = requ @@ -542,16 +542,21 @@ resolve( +%0A 'https:/ @@ -588,16 +588,20 @@ yments', +%0A %60?$%7Bque @@ -625,16 +625,18 @@ y(%7B%0A + teamId: @@ -659,14 +659,20 @@ m',%0A + %7D)%7D%60 +,%0A );%0A%0A @@ -740,17 +740,16 @@ %7B%0A -' Authoriz @@ -753,17 +753,16 @@ rization -' : %60Beare @@ -997,16 +997,21 @@ loyments +%0A .sort((a @@ -1016,24 +1016,26 @@ (a, b) =%3E %7B%0A + return a @@ -1058,18 +1058,25 @@ ated;%0A -%7D) + %7D)%0A .reverse @@ -1240,17 +1240,17 @@ y.url;%0A%7D -%0A +; %0A%0Alet te @@ -1551,16 +1551,17 @@ ingUrl() + %7B%0A @@ -1867,16 +1867,18 @@ );%0A%0A + // other @@ -2054,33 +2054,32 @@ loyed': function - (browser) %7B%0A @@ -2144,20 +2144,16 @@ isible(' -body .c-bolt- @@ -2197,10 +2197,34 @@ xt(' -h1 +.c-bolt-navbar__title-text ', ' @@ -2256,16 +2256,17 @@ .end() +; %0A %7D,%0A%0A @@ -2350,17 +2350,25 @@ tion - ( +%0A browser +,%0A ) %7B%0A
2c7d77206c6d03384e2ab27ed430c33821140592
correct where external link icon appears
src/app/components/msp/application/confirmation/i18n/data/en/index.js
src/app/components/msp/application/confirmation/i18n/data/en/index.js
module.exports = { pageTitle: '<i class="fa fa-check success" aria-hidden="true"></i> Your application has been submitted.', secondTitle: 'What happens next', nextStep1: "<a>Print this confirmation page</a> for your records", nextStep2: "Allow 21 business days for your application to be processed", nextStep3: "Once your application is processed, you will receive a letter in the mail indicating your eligibility for MSP and the date your basic health coverage will begin (if applicable). You may have a <a href='http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents/eligibility-and-enrolment/how-to-enrol/coverage-wait-period' target='_blank'>wait period</a>.", nextStep4: "Once you receive your first bill, you can get your <a href='http://www2.gov.bc.ca/gov/content/governments/government-id/bc-services-card' target='blank'>BC Services Card</a> – visit <a href='http://www.icbc.com/Pages/default.aspx'target='_blank'>ICBC</a> or <a href='http://www2.gov.bc.ca/gov/content/governments/organizational-structure/ministries-organizations/ministries/technology-innovation-and-citizens-services/servicebc' target='blank'>Service BC</a> to get one", nextStep5: "Low income individuals or families who have lived in Canada for at least a year, may also be eligible for financial help with paying the monthly premium – <a href='http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents/premiums/regular-premium-assistance' target='_blank'>find out about premium assistance</a> <i class='fa fa-external-link' aria-hidden='true'></i>", nextStep6: "Depending on your income, you may be eligible for <a href='http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/pharmacare-for-bc-residents/who-we-cover/fair-pharmacare-plan' target='_blank'>FairPharmacare</a> <i class='fa fa-external-link' aria-hidden='true'></i>, to help with the cost of eligible prescription drugs and designated medical supplies", nextStep7: "If you have questions, contact <a href='http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents-contact-us' target='_blank'>Health Insurance BC</a>" }
JavaScript
0
@@ -957,16 +957,70 @@ k'%3EICBC%3C +i class='fa fa-external-link' aria-hidden='true'%3E%3C/i%3E%3C /a%3E or %3C @@ -1583,63 +1583,8 @@ %3C/a%3E - %3Ci class='fa fa-external-link' aria-hidden='true'%3E%3C/i%3E %22,%0A @@ -1818,63 +1818,8 @@ %3C/a%3E - %3Ci class='fa fa-external-link' aria-hidden='true'%3E%3C/i%3E , to
59ef775e3eb75e2e4d35b56b1beb8a49835c51eb
Add a "generateToken" function in user repository
lib/api/core/models/repositories/userRepository.js
lib/api/core/models/repositories/userRepository.js
module.exports = function (kuzzle) { var _ = require('lodash'), jwt = require('jsonwebtoken'), q = require('q'), uuid = require('node-uuid'), User = require('../security/user'), Repository = require('./repository'), InternalError = require('../../errors/internalError'), UnauthorizedError = require('../../errors/unauthorizedError'); function UserRepository (opts) { var options = opts || {}; if (options.ttl !== undefined) { this.ttl = options.ttl; } } UserRepository.prototype = new Repository(kuzzle, { collection: '%kuzzle/users', ObjectConstructor: User, cacheEngine: kuzzle.services.list.userCache }); UserRepository.prototype.loadFromToken = function (userToken) { var deferred = q.defer(), decodedToken, error; if (userToken === null) { return this.anonymous(); } try { decodedToken = jwt.verify(userToken, kuzzle.config.jsonWebToken.secret); if (decodedToken._id === 'admin') { return this.admin(); } this.loadFromCache(decodedToken._id) .then(function (user) { if (user === null) { this.loadOneFromDatabase(decodedToken._id) .then(function (userFromDatabase) { if (userFromDatabase === null) { deferred.resolve(this.anonymous()); } else { this.persistToCache(userFromDatabase); deferred.resolve(userFromDatabase); } }.bind(this)) .catch(function (err) { deferred.reject(err); }); } else { this.refreshCacheTTL(user); deferred.resolve(user); } }.bind(this)) .catch(function (err) { deferred.reject(err); }); } catch (err) { if (err instanceof jwt.TokenExpiredError) { error = new UnauthorizedError('Token expired', 401); error.details = { subCode: error.subCodes.TokenExpired, expiredAt: err.expiredAt }; } else if (err instanceof jwt.JsonWebTokenError) { error = new UnauthorizedError('Json Web Token Error', 401); error.details = { subCode: error.subCodes.JsonWebTokenError, description: err.message }; } else { error = new InternalError('Error loading User'); error.details = err; } deferred.reject(error); } return deferred.promise; }; UserRepository.prototype.persist = function (user) { if (user._id === undefined || user._id === null) { user._id = uuid.v4(); } this.persistToDatabase(user); return this.persistToCache(user); }; UserRepository.prototype.anonymous = function () { var user = new User(); return this.hydrate(user, { _id: -1, name: 'Anonymous', profile: 'anonymous' }); }; UserRepository.prototype.admin = function () { var user = new User(); return this.hydrate(user, { _id: 'admin', name: 'Administrator', profile: 'admin' }); }; UserRepository.prototype.hydrate = function (user, data) { var deferred = q.defer(), result; if (!_.isObject(data)) { return Promise.resolve(user); } Repository.prototype.hydrate(user, data) .then(u => { result = u; if (!u.profile || u._id === undefined || u._id === null) { return this.anonymous() .then(anonymousUser => { result = anonymousUser; return Promise.resolve(anonymousUser.profile); }); } return kuzzle.repositories.profile.loadProfile(u.profile); }) .then(function (profile) { result.profile = profile; deferred.resolve(result); }) .catch(function (error) { deferred.reject(error); }); return deferred.promise; }; UserRepository.prototype.serializeToCache = function (user) { var result = {}; Object.keys(user).forEach(function (key) { if (key !== 'profile') { result[key] = user[key]; } }); result.profile = user.profile._id; return result; }; UserRepository.prototype.serializeToDatabase = UserRepository.prototype.serializeToCache; return UserRepository; };
JavaScript
0.000008
@@ -678,16 +678,657 @@ %0A %7D);%0A%0A + UserRepository.prototype.generateToken = function (username) %7B%0A var%0A deferred = q.defer(),%0A encodedToken,%0A error;%0A%0A if (username === null) %7B%0A error = new InternalError('Unknown User : cannot generate token');%0A return deferred.reject(error);%0A %7D%0A%0A try %7B%0A encodedToken = jwt.sign(%7B_id: username%7D, kuzzle.config.jsonWebToken.secret, %7Balgorithm: kuzzle.config.jsonWebToken.algorithm%7D);%0A deferred.resolve(encodedToken);%0A %7D%0A catch (err) %7B%0A error = new InternalError('Error loading User');%0A error.details = err;%0A deferred.reject(error);%0A %7D%0A%0A return deferred.promise;%0A %7D;%0A%0A UserRe
bc4e9e6fcfcc08a0a7d8121f989dab484479d6be
Fix resizing from the legends tab
lib/assets/javascripts/builder/embed/embed-view.js
lib/assets/javascripts/builder/embed/embed-view.js
var Backbone = require('backbone'); var _ = require('underscore'); var Ps = require('perfect-scrollbar'); var CoreView = require('backbone/core-view'); var checkAndBuildOpts = require('builder/helpers/required-opts'); var TabsView = require('./tabs/tabs-view'); var template = require('./embed.tpl'); var EmbedOverlayView = require('./embed-overlay-view'); var TAB_NAMES = { map: 'map', legends: 'legends' }; var MOBILE_VIEWPORT_BREAKPOINT = 759; var REQUIRED_OPTS = [ 'title', 'description', 'showMenu', 'showLegends' ]; var EmbedView = CoreView.extend({ className: 'CDB-Embed-view', initialize: function (options) { checkAndBuildOpts(options, REQUIRED_OPTS, this); if (this._showLegends) { var selectedTab = _.find(this._tabs, function (tab) { return tab.isSelected; }); this._tabsModel = new Backbone.Model({ selected: selectedTab ? selectedTab.name : TAB_NAMES.map }); this._initBinds(); } }, render: function () { this.$el.html(template({ title: this._title, description: this._description, showMenu: this._showMenu, showLegends: this._showLegends })); if (this._showLegends) { var tabsView = new TabsView({ model: this._tabsModel, tabs: [ { name: 'map', isSelected: true }, { name: 'legends' } ] }); this.addView(tabsView); this.$('.js-tabs').replaceWith(tabsView.render().$el); } return this; }, _initBinds: function () { this.listenTo(this._tabsModel, 'change:selected', this._onSelectedTabChanged); window.addEventListener('resize', this.onWindowResized.bind(this), { passive: true }); }, _onSelectedTabChanged: function () { var contentId = '.js-embed-' + this._tabsModel.get('selected'); var content = this.$(contentId); content.siblings().removeClass('is-active'); content.addClass('is-active'); // Update PerfectScrollbar var perfectScrollbarContainer = content.find('.ps-container').get(0); if (perfectScrollbarContainer) { Ps.update(perfectScrollbarContainer); } }, injectTitle: function (mapEl) { var legendsEl = mapEl.find('.CDB-Legends-canvasInner'); var titleView = new EmbedOverlayView({ title: this._title, description: this._description, showMenu: this._showMenu }); this.addView(titleView); legendsEl.prepend(titleView.render().el); legendsEl.find('.CDB-LayerLegends') .detach() .appendTo(legendsEl.find('.CDB-Overlay-inner')); }, onWindowResized: function () { if (window.innerWidth > MOBILE_VIEWPORT_BREAKPOINT && this._tabsModel.get('selected') !== TAB_NAMES.map) { this._tabsModel.set({ selected: TAB_NAMES.map }); } } }); module.exports = EmbedView;
JavaScript
0
@@ -445,11 +445,11 @@ T = -759 +600 ;%0A%0Av
de1bcba3ef4104d06f8164f05e040d41d7c46abb
remove unneeded import
lib/components/narrative/connected-trip-details.js
lib/components/narrative/connected-trip-details.js
import { connect } from 'react-redux' import coreUtils from '@opentripplanner/core-utils' import styled from 'styled-components' import TripDetailsBase from '@opentripplanner/trip-details' const TripDetails = styled(TripDetailsBase)` b { font-weight: 600; } margin-left: 5px; margin-right: 5px; ` // Connect imported TripDetails class to redux store. const mapStateToProps = (state) => { const { itinerary } = state.otp.config return { defaultFareKey: itinerary?.defaultFareKey || undefined, fareDetailsLayout: itinerary?.fareDetailsLayout || undefined, fareKeyNameMap: itinerary?.fareKeyNameMap || {} } } export default connect(mapStateToProps)(TripDetails)
JavaScript
0.000004
@@ -35,60 +35,8 @@ ux'%0A -import coreUtils from '@opentripplanner/core-utils'%0A impo
a2819f2a0fe2c7192e201363f443581e199f0b87
Add model methods
src/models/ImageModel.js
src/models/ImageModel.js
import mongoose from 'mongoose'; import shortid from 'shortid'; import { getThumbUrl, getSrcset } from 'src/config/constants'; const { Schema } = mongoose; export const ImageSchema = new Schema({ name: { type: String, default: '', }, url: { type: String, required: true, }, shortid: { type: String, default: shortid.generate, }, }); ImageSchema.virtual('thumbUrl').get(function thumbUrl() { return getThumbUrl(this.url, 640); }); ImageSchema.virtual('srcset').get(function srcset() { return getSrcset(this.url); }); export default mongoose.model('Image', ImageSchema);
JavaScript
0.000001
@@ -88,16 +88,37 @@ etSrcset +, constructThumborUrl %7D from @@ -411,41 +411,137 @@ al(' -thumbUrl').get(function thumbUrl( +srcset').get(function srcset() %7B%0A return getSrcset(this.url);%0A%7D);%0A%0AImageSchema.methods.getThumbnail = function getThumbnail(size ) %7B%0A @@ -575,17 +575,16 @@ rl, -640 +size );%0A%7D -); %0A%0AIm @@ -597,83 +597,116 @@ ema. -virtual('srcset').get(function srcset() %7B%0A return getSrcset(this.url +methods.getThumborUrl = function getThumborUrl(options) %7B%0A return constructThumborUrl(this.url, options );%0A%7D -); %0A%0Aex
4bf14920b4cac450da55a018f59a2fcbff8a1a59
Assumed synthetic route is behind nat
mod/rest/location_service.js
mod/rest/location_service.js
/** * @author Pedro Sanders * @since v1 */ const postal = require('postal') const validator = require('validator') const CoreUtils = require('@routr/core/utils') const { Status } = require('@routr/core/status') const SipFactory = Java.type('javax.sip.SipFactory') const addressFactory = SipFactory.getInstance().createAddressFactory() const get = Java.type('spark.Spark').get const post = Java.type('spark.Spark').post const del = Java.type('spark.Spark').delete module.exports = function (locator) { /** * Expects json with: address, port, user, expires */ post('/location/:aor', (req, res) => { const aor = req.params(':aor') try { const body = JSON.parse(req.body()) if (!validator.isIP(body.address) || !validator.isPort(body.port + '') || !validator.isInt(body.expires + '') || !body.user ) throw 'Bad Request' const route = { isLinkAOR: false, thruGw: false, sentByAddress: body.address, sentByPort: body.port, received: body.address, rport: body.port, contactURI: addressFactory.createSipURI(body.user, `${body.address}:${body.port}`), registeredOn: Date.now(), expires: body.expires, nat: false } postal.publish({ channel: "locator", topic: "endpoint.add", data: { addressOfRecord: aor, route: route } }) res.status(200) res.body('{\"status\": \"200\", \"message\":\"Added location entry.\"}') return '{\"status\": \"200\", \"message\":\"Added location entry.\"}' } catch(e) { res.status(401) res.body('{\"status\": \"400\", \"message\":\"Bad Request\"}') return '{\"status\": \"400\", \"message\":\"Bad Request\"}' } }) get('/location', (req, res) => JSON.stringify(CoreUtils.buildResponse(Status.OK, locator.listAsJSON()))) del('/location/:aor', (req, res) => { const aor = req.params(':aor') postal.publish({ channel: "locator", topic: "endpoint.remove", data: { addressOfRecord: aor, isWildcard: true } }) res.status(200) res.body('{\"status\": \"200\", \"message\":\"Location entry evicted.\"}') return '{\"status\": \"200\", \"message\":\"Location entry evicted.\"}' }) }
JavaScript
0.999457
@@ -1391,20 +1391,19 @@ nat: -fals +tru e%0A
b7b8218b9bb289fc601bf15f7311c0869173ae9e
Update abilities.js
mods/tervari/abilities.js
mods/tervari/abilities.js
/* Ratings and how they work: -2: Extremely detrimental The sort of ability that relegates Pokemon with Uber-level BSTs into NU. ex. Slow Start, Truant -1: Detrimental An ability that does more harm than good. ex. Defeatist, Klutz 0: Useless An ability with no net effect on a Pokemon during a battle. ex. Pickup, Illuminate 1: Ineffective An ability that has a minimal effect. Should never be chosen over any other ability. ex. Pressure, Damp 2: Situationally useful An ability that can be useful in certain situations. ex. Blaze, Insomnia 3: Useful An ability that is generally useful. ex. Volt Absorb, Iron Fist 4: Very useful One of the most popular abilities. The difference between 3 and 4 can be ambiguous. ex. Technician, Intimidate 5: Essential The sort of ability that defines metagames. ex. Drizzle, Magnet Pull */ exports.BattleAbilities = { "hotshot": { desc: "If this Pokemon is active while Sunny Day is in effect, its speed is temporarily doubled.", shortDesc: "If Sunny Day is active, this Pokemon's Speed is doubled.", onModifySpe: function(spe) { if (this.isWeather('sunnyday')) { return spe * 2; } }, id: "hotshot", name: "Hotshot", rating: 2, num: 34 }, "rawpower": { desc: "As health decreases, physical attack damage increases drastically.", shortDesc: "Physical attacks have a power increase equal to the percent of health lost.", onBasePower: function(basePower, attacker, defender, move) { if (move.category === 'Physical') { this.debug('Raw Power boost'); var raw = (2 - (attacker.hp/(attacker.maxhp))); return basePower * raw; } }, id: "rawpower", name: "Raw Power", rating: 4, num: 9001 }, "timetwister": { desc: "When this Pokemon enters the battlefield, it causes a permanent Trick Room that only stops 5 turns after the user switches out.", shortDesc: "On switch-in, this Pokemon summons Trick Room which lasts 5 turns after the user switches out.", onStart: function(source) { this.setWeather('trickroom'); this.weatherData.duration = 5; }, id: "timetwister", name: "Time Twister", rating: 5, num: 2 }, };
JavaScript
0.000001
@@ -905,16 +905,1306 @@ ies = %7B%0A +%09%22frisk%22: %7B%0A inherit: true,%0A onStart: function(pokemon) %7B%0A var target = pokemon.side.foe.randomActive();%0A if (target && target.item) %7B%0A this.add('-item', target, target.getItem().name, '%5Bfrom%5D ability: Frisk', '%5Bof%5D '+pokemon);%0A %7D%0A %7D%0A %7D,%0A %22keeneye%22: %7B%0A inherit: true,%0A onModifyMove: function() %7B%7D%0A %7D,%0A %22oblivious%22: %7B%0A inherit: true,%0A onUpdate: function(pokemon) %7B%0A if (pokemon.volatiles%5B'attract'%5D) %7B%0A pokemon.removeVolatile('attract');%0A this.add(%22-message%22, pokemon.name+%22 got over its infatuation. (placeholder)%22);%0A %7D%0A %7D,%0A onTryHit: function(pokemon, target, move) %7B%0A if (move.id === 'captivate') %7B%0A this.add('-immune', pokemon, '%5Bmsg%5D', '%5Bfrom%5D Oblivious');%0A return null;%0A %7D%0A %7D%0A %7D,%0A %22overcoat%22: %7B%0A inherit: true,%0A onTryHit: function() %7B%7D%0A %7D,%0A %09%22hotsho
eb19029e5fa24a6c3c75f0d1e128d08986a4e962
Fix streams sidebar layout (#92)
src/nav/StreamSidebar.js
src/nav/StreamSidebar.js
import React from 'react'; import { StyleSheet, ScrollView, View, Text, } from 'react-native'; import Icon from 'react-native-vector-icons/Ionicons'; import { homeNarrow, privateNarrow, streamNarrow, mentionedNarrow, starredNarrow, } from '../lib/narrow'; import SidebarRow from './SidebarRow'; import { NAVBAR_HEIGHT, STATUSBAR_HEIGHT, BRAND_COLOR } from '../common/styles'; const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', backgroundColor: '#444', }, streams: { flex: 1, flexDirection: 'column', }, account: { height: NAVBAR_HEIGHT + STATUSBAR_HEIGHT, backgroundColor: BRAND_COLOR, }, mainMenu: { fontWeight: 'bold', }, colorBar: { width: 30, height: 30, margin: 5, }, icon: { width: 30, height: 30, margin: 5, fontSize: 30, color: '#fff', textAlign: 'center', }, streamName: { padding: 10, fontSize: 16, color: '#fff', }, }); export default class StreamSidebar extends React.Component { render() { const sortedSubscriptions = this.props.subscriptions.toList() .sort((a, b) => a.get('name').localeCompare(b.get('name'))); return ( <View style={styles.container}> <Text style={styles.account} onPress={this.props.logout} /> <ScrollView scrollsToTop={false} > <View style={styles.streams}> <SidebarRow name="Home" customStyles={[styles.streamName, styles.mainMenu]} onPress={() => this.props.narrow(homeNarrow)} icon={<Icon style={styles.icon} name="md-home" />} /> <SidebarRow name="Private Messages" customStyles={[styles.streamName, styles.mainMenu]} onPress={() => this.props.narrow(privateNarrow())} icon={<Icon style={styles.icon} name="md-chatboxes" />} /> <SidebarRow name="Starred" customStyles={[styles.streamName, styles.mainMenu]} onPress={() => this.props.narrow(starredNarrow)} icon={<Icon style={styles.icon} name="md-star" />} /> <SidebarRow name="@-mentions" customStyles={[styles.streamName, styles.mainMenu]} onPress={() => this.props.narrow(mentionedNarrow)} icon={<Icon style={styles.icon} name="md-at" />} /> {sortedSubscriptions.map(x => <SidebarRow key={x.get('stream_id')} name={x.get('name')} customStyles={styles.streamName} onPress={() => this.props.narrow(streamNarrow(x.get('name')))} icon={<View style={[styles.colorBar, { backgroundColor: x.get('color') }]} />} /> )} </View> </ScrollView> </View> ); } }
JavaScript
0
@@ -1363,16 +1363,49 @@ ollView%0A + style=%7Bstyles.streams%7D%0A @@ -1441,50 +1441,8 @@ %3E%0A - %3CView style=%7Bstyles.streams%7D%3E%0A @@ -1451,34 +1451,32 @@ %3CSidebarRow%0A - name @@ -1483,18 +1483,16 @@ =%22Home%22%0A - @@ -1551,34 +1551,32 @@ u%5D%7D%0A - onPress=%7B() =%3E t @@ -1597,34 +1597,32 @@ ow(homeNarrow)%7D%0A - icon @@ -1670,39 +1670,35 @@ %22 /%3E%7D%0A - - /%3E%0A - %3CSideb @@ -1695,34 +1695,32 @@ %3CSidebarRow%0A - name @@ -1743,34 +1743,32 @@ es%22%0A - customStyles=%7B%5Bs @@ -1807,34 +1807,32 @@ u%5D%7D%0A - onPress=%7B() =%3E t @@ -1870,34 +1870,32 @@ ))%7D%0A - - icon=%7B%3CIcon styl @@ -1936,39 +1936,35 @@ %22 /%3E%7D%0A - /%3E%0A - %3CSideb @@ -1977,26 +1977,24 @@ - name=%22Starre @@ -1996,18 +1996,16 @@ tarred%22%0A - @@ -2064,34 +2064,32 @@ u%5D%7D%0A - - onPress=%7B() =%3E t @@ -2113,34 +2113,32 @@ starredNarrow)%7D%0A - icon @@ -2180,26 +2180,24 @@ d-star%22 /%3E%7D%0A - /%3E @@ -2199,34 +2199,32 @@ /%3E%0A - %3CSidebarRow%0A @@ -2211,34 +2211,32 @@ %3CSidebarRow%0A - name @@ -2253,34 +2253,32 @@ ns%22%0A - - customStyles=%7B%5Bs @@ -2317,34 +2317,32 @@ u%5D%7D%0A - onPress=%7B() =%3E t @@ -2380,34 +2380,32 @@ w)%7D%0A - - icon=%7B%3CIcon styl @@ -2439,39 +2439,35 @@ %22 /%3E%7D%0A - /%3E%0A - %7Bsorte @@ -2494,34 +2494,32 @@ =%3E%0A - %3CSidebarRow%0A @@ -2506,34 +2506,32 @@ %3CSidebarRow%0A - ke @@ -2563,26 +2563,24 @@ - - name=%7Bx.get( @@ -2584,26 +2584,24 @@ et('name')%7D%0A - @@ -2635,18 +2635,16 @@ amName%7D%0A - @@ -2722,26 +2722,24 @@ - icon=%7B%3CView @@ -2809,34 +2809,32 @@ /%3E%7D%0A - /%3E%0A ) @@ -2834,31 +2834,11 @@ - - )%7D%0A - %3C/View%3E%0A
03324f4fcce7dda06b5d8e1276d1218eb3696d73
add async functions for deleting videos
app/api/index.js
app/api/index.js
import DropBox from 'dropbox'; import database from './firebase'; const endpoint = '/videos/'; const apiToken = 'KaR5yR5U9kAAAAAAAAAACEtwlnZ-37Qv8Pa403MeFDKOs8Ss7eakvlypcyEqJSG-'; const dbx = new DropBox({ accessToken: apiToken, }); const flatten = (object) => { const arr = []; Object.keys(object).forEach((key) => { arr.push(object[key]); }); return arr; }; const createPromises = (ids) => { const promises = []; for (const id of ids) { promises.push(removeVideo(id)); } return promises; }; export const removeVideos = (ids) => Promise.all(createPromises(ids)) .then(() => ids) .catch((err) => { throw new Error(`Failed to delete videos: ${err}`); }); export const removeVideo = (id) => database.ref(endpoint + id) .remove() .then(() => id) .catch((err) => { throw new Error(`Failed to delete video ${id}: ${err}`); }); export const fetchVideos = (filter) => database.ref(endpoint).once('value').then((snapshot) => { const videos = flatten(snapshot.val()); return filterVideos(videos, filter); }, (err) => { throw new Error(err); }); const getToggledVideo = (video) => { const toggledVideo = Object.assign({}, video, { flagged: !video.flagged, }); return toggledVideo; }; export const toggleVideo = (video) => addVideoEntry(getToggledVideo(video)); const filterVideos = (videos, filter) => { switch (filter) { case 'All': return videos; case 'Uploaded': return videos.filter(v => v.uploaded); case 'Flagged': return videos.filter(v => v.flagged); default: throw new Error(`Unknown filter ${filter}`); } }; export const addVideoEntry = (video) => database.ref(endpoint + video.id).set(video) .then(() => video) .catch((err) => { throw new Error(`Failed to add video to database ${err}`); }); export const uploadVideo = (videoId, contents) => dbx.filesUpload({ path: `/${videoId}`, contents }) .then((response) => response) .catch((err) => { throw new Error(`Upload Error: ${err}`); }); export const getSharedLink = (videoId) => dbx.sharingCreateSharedLink({ path: `/${videoId}`, }) .then((response) => response) .catch((err) => { throw new Error(`Shared Link Error ${err}`); });
JavaScript
0
@@ -380,24 +380,30 @@ const create +Remove Promises = ( @@ -582,16 +582,22 @@ l(create +Remove Promises @@ -2294,16 +2294,739 @@ $%7Berr%7D%60);%0A %7D);%0A +%0Aconst getIdFromUri = (uri) =%3E %7B%0A const start = uri.lastIndexOf('/');%0A const end = uri.lastIndexOf('?');%0A return uri.slice(start + 1, end);%0A%7D;%0A%0Aconst createDeletePromises = (uris) =%3E %7B%0A const promises = %5B%5D;%0A for (const uri of uris) %7B%0A promises.push(removeVideo(uri));%0A %7D%0A%0A return promises;%0A%7D;%0A%0Aexport const deleteVideo = (videoUri) =%3E%0A dbx.filesDelete(%7B%0A path: %60/$%7BgetIdFromUri(videoUri)%7D%60,%0A %7D)%0A .then((response) =%3E response)%0A .catch((err) =%3E %7B%0A throw new Error(%60Error Deleting Video $%7Berr%7D%60);%0A %7D);%0A%0Aexport const deleteVideos = (videoUris) =%3E%0A Promise.all(createDeletePromises(videoUris))%0A .then(() =%3E videoUris)%0A .catch((err) =%3E %7B%0A throw new Error(%60Error Deleting Videos $%7Berr%7D%60);%0A %7D);%0A
5dcbb6f96d188625db719205d5c3028962040cad
Add missing flairs
modules/flair/RimWorld.js
modules/flair/RimWorld.js
const base = require( './base.js' ); module.exports = Object.assign( {}, base, { list: [ 'community', 'extralife', 'fun', 'gold', 'granite', 'jade', 'limestone', 'marble', 'mod', 'mod2', 'plasteel', 'pmfaf', 'sandstone', 'ship', 'silver', 'slate', 'steel', 'uranium', 'war', 'wood', ], type: 'author_flair_css_class', } );
JavaScript
0.000236
@@ -87,16 +87,34 @@ list: %5B%0A + 'bestof',%0A
5f4ddb9a6428710dac0f24c0ebdde14fff2b487d
Manage i18next's option "returnObjects" in helper
app/helpers/t.js
app/helpers/t.js
import Ember from 'ember'; /** * An HTMLBars helper function that exposes the i18next `t()` function. Automatically * refreshes the translated text if the application's selected locale changes. */ export default Ember.Helper.extend({ i18n: Ember.inject.service(), /** * @private * Outputs translated text using the i18next `t()` function. * * @param {Array} params - positional parameters passed to the helper. The first * element must be the translation key. * * @param {Object} hash - an object containing the hash parameters passed to the * helper. Used for translation substitutions. * * @return {String} text localized for the current locale. */ compute(params, hash) { const path = params[0]; return Ember.String.htmlSafe(this.get('i18n').t(path, hash)); }, refreshText: Ember.observer('i18n._locale', function () { this.recompute(); }) });
JavaScript
0.000001
@@ -637,22 +637,17 @@ return %7B -String +* %7D text l @@ -747,37 +747,20 @@ -return Ember.String.htmlSafe( +const res = this @@ -785,16 +785,82 @@ h, hash) +;%0A%0A return hash.returnObjects ? res : Ember.String.htmlSafe(res );%0A %7D,%0A
c247d2e222e106b839f95fd9f0e2311bdf4add66
fix pull conflict
routes/quotesRouter.js
routes/quotesRouter.js
var express = require('express'); var CandidateQuote = require(__dirname + '/../models/candidateQuote'); var DictatorQuote = require(__dirname + '/../models/dictatorQuote'); var quoteChoices = [CandidateQuote, DictatorQuote]; var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var handleError = require(__dirname + '/../lib/handleError'); var randInt = require(__dirname + '/../lib/randInt'); var percentCorrect = require(__dirname + '/../lib/percentcorrect'); quotesRouter = exports = module.exports = express.Router(); var choiceKey = {'Candidate': CandidateQuote, 'Dictator': DictatorQuote}; quotesRouter.get('/', function(req, res) { var choice = randInt(0,2); quoteChoices[choice].find({}, function(err, data) { if (err) return handleError(err, res); res.json(JSON.stringify(data[randInt(0, data.length)])); }); }); quotesRouter.post('/', bodyParser.json(), function (req, res){ var person = req.body.quoteObj; if(req.body.answer === 'correct') { choiceKey[person.category].update({_id: person._id}, { $inc: {correctGuesses: 1}}, function(err, data) { if (err) return handleError(err, res); res.json({msg: 'update successful'}); }); } else { choiceKey[person.category].update({_id: person._id}, { $inc: {incorrectGuesses: 1}}, function(err, data) { if (err) return handleError(err, res); res.json({msg: 'update successful'}); }); } }); quotesRouter.get('/stats', function(req, res) { DictatorQuote.find({}, function(err, dictatorData) { if (err) return handleError(err, res); CandidateQuote.find({}, function(err, candidateData) { if (err) return handleError(err, res); var all = dictatorData.concat(candidateData); var sorted = all.sort(function (a, b) { return percentCorrect(b) - percentCorrect(a); }); var results = {top: sorted.slice(0, 10), bottom: sorted.slice(-10)}; res.send(JSON.stringify(results)); }); }); });
JavaScript
0.000002
@@ -1423,24 +1423,192 @@ );%0A %7D%0A%7D);%0A%0A +function total(quoteObj) %7B%0A var correct = quoteObj.correctGuesses;%0A var incorrect = quoteObj.incorrectGuesses;%0A var total = correct + incorrect;%0A%0A return total;%0A%7D%0A%0A quotesRouter @@ -1911,59 +1911,282 @@ var -sorted = all.sort(function (a, b) %7B%0A return +correct = all.sort(function (a, b) %7B%0A return b.correctGuesses - a.correctGuesses;%0A %7D);%0A var incorrect = all.slice().sort(function (a, b) %7B%0A return b.incorrectGuesses - a.incorrectGuesses;%0A %7D); // sorted.sort(function(a, b) %7B%0A // if ( perc @@ -2200,12 +2200,21 @@ ect( -b) - +a) === 100 && per @@ -2229,22 +2229,133 @@ ect( -a);%0A +b) === 100) %7B%0A // return total(b) - total(a);%0A // %7D else %7B%0A // return 0;%0A // %7D%0A // %7D);%0A +%0A @@ -2376,22 +2376,23 @@ = %7Btop: -sorted +correct .slice(0 @@ -2431,22 +2431,27 @@ om: -sorted +incorrect .slice( -- +0, 10)%7D
d566d1780bf3f1156c26dec34d527995f7aac17b
Revert 336a198..d06a688
routes/views/signin.js
routes/views/signin.js
var keystone = require('../../'), session = require('../../lib/session'); exports = module.exports = function(req, res) { var renderView = function() { keystone.render(req, res, 'signin', { submitted: req.body, from: req.query.from, logo: keystone.get('signin logo') }); } // If a form was submitted, process the login attempt if (req.method == "POST") { if (!req.body.email || !req.body.password) { req.flash('error', 'Please enter your email address and password.'); return renderView(); } var onSuccess = function(user) { if (req.query.from && req.query.from.match(/^(?!http|\/\/|javascript).+/)) { res.redirect(req.query.from); } else if ('string' == typeof keystone.get('signin redirect')) { res.redirect(keystone.get('signin redirect')); } else if ('function' == typeof keystone.get('signin redirect')) { keystone.get('signin redirect')(user, req, res); } else { res.redirect('/keystone'); } } var onFail = function() { req.flash('error', 'Sorry, that email and password combo are not valid.'); renderView(); } session.signin(req.body, req, res, onSuccess, onFail); } else { renderView(); } }
JavaScript
0
@@ -117,17 +117,18 @@ res) %7B%0A +%09 %0A - %09var ren @@ -370,17 +370,19 @@ OST%22) %7B%0A +%09%09 %0A - %09%09if (!r @@ -516,25 +516,27 @@ View();%0A%09%09%7D%0A +%09%09 %0A - %09%09var onSucc @@ -558,16 +558,19 @@ user) %7B%0A +%09%09%09 %0A%09%09%09if ( @@ -587,63 +587,8 @@ from - && req.query.from.match(/%5E(?!http%7C%5C/%5C/%7Cjavascript).+/) ) %7B%0A @@ -911,22 +911,27 @@ );%0A%09%09%09%7D%0A +%09%09%09 %0A - %09%09%7D%0A +%09%09 %0A - %09%09var on @@ -1049,17 +1049,19 @@ ();%0A%09%09%7D%0A +%09%09 %0A - %09%09sessio @@ -1109,17 +1109,19 @@ nFail);%0A +%09%09 %0A - %09%7D%0A%09else @@ -1142,11 +1142,12 @@ w();%0A%09%7D%0A +%09 %0A%7D%0A
2da52e7162ed844eea4a149f274a838661d1f216
Fix code style in live-blda
src/offline/live-blda.js
src/offline/live-blda.js
/* Given a TRAINING_RECORD, a TEST_RECORD and optionally a MODEL, this file classifies the test recording with a BLDA and prints out the predictions. */ const { trainBLDA, getEpochData, prepareElectrodesData, getSessionFromRecording, } = require('../lib/methods'); const numeric = require('../lib/numeric'); const BLDA = require('../lib/blda'); const _ = require('lodash'); const b = new BLDA(); const channelsMap = { F3: 1, F4: 1, FC5: 1, FC6: 1, F7: 1, F8: 1, P7: 1, P8: 1, O1: 1, O2: 1, T7: 1, T8: 1, AF3: 1, AF4: 1, }; const channels = Object.keys(channelsMap).filter(c => channelsMap[c]); const recording = require(process.env.TRAINING_RECORD); function work(channels) { const session = getSessionFromRecording(recording, channels); const trainingData = numeric.transpose(_.flatten(_.toArray(session).map(s => s.epochs.map(e => e.data)))); const trainingLabels = _.flatten(_.toArray(session).map(s => s.epochs.map(e => (e.label ? 1 : -1)))); const data = { vectors: trainingData, labels: trainingLabels }; const testRecording = require(process.env.TEST_RECORD); const electrodesData = prepareElectrodesData(testRecording.data.electrodes, channels); const matrixKeys = Object.keys(testRecording.data.matrix); const reset = matrixKeys.filter((k, i) => matrixKeys[i + 1] > +k + 500).map(k => matrixKeys.indexOf(k)) const epochs = matrixKeys.map(Number) .map(key => getEpochData(electrodesData, key)); trainBLDA(data, channels, process.env.MODEL, (classifier) => { let predictions = {}; let counter = 0; let totalCounter = 0; epochs.forEach((e, i) => { counter++; totalCounter++; let score = classifier.classify(e.map(v => [v]))[0]; if (!process.env.MATLAB_EIG_SERVER) score /= 10; const matrix = testRecording.data.matrix[matrixKeys[i]]; const setName = matrix.map(m => m[1]).join(''); predictions[setName] = predictions[setName] || 0; predictions[setName] += score; console.log(matrix.map(m => m[1]).join(' ')); console.log(`output ${score} ${counter}`); const prediction = getPredictedSymbol(testRecording.meta.matrixSettings.alphabet, predictions, 2); console.log('======='); if (prediction) { console.log(`predicted ${prediction} in ${counter} trials`); } if (totalCounter == reset[0]) { counter = 0; predictions = {}; reset.shift(); } }); console.log('done'); }); } function getPredictedSymbol(alphabet, predictions, coeff = 1) { let matrix = {}; Object.keys(predictions).forEach(set => { set.split('').forEach(char => matrix[char] = predictions[set] + (matrix[char] || 0)) }); matrix = _.map(matrix, (v, k) => [k, 2 ** v]); matrix.sort((a, b) => b[1] - a[1]); console.log('leading predictions:', matrix[0].join(':'), matrix[1].join(':'), matrix[2].join(':')); if (matrix[1][1] > 0 && matrix[0][1] > matrix[1][1] * 2 * coeff && matrix[0][1] > matrix[2][1] * 4) { return matrix[0]; } return null; } work(channels);
JavaScript
0.000013
@@ -1423,16 +1423,17 @@ exOf(k)) +; %0A%0A co @@ -2840,19 +2840,21 @@ forEach( +( set +) =%3E %7B%0A @@ -2943,16 +2943,17 @@ %5D %7C%7C 0)) +; %0A %7D);
6ca736183cfeab70af7ae8a077920628642973f1
fix undefined reference in JS
rtcheck/static/main.js
rtcheck/static/main.js
"use strict"; function initOrder(strings, edges) { // Hook into the graph edges. var labelRe = /^l([0-9]+)-l([0-9]+)$/; $.each(edges, function(_, edge) { var g = $(document.getElementById(edge.EdgeID)); // Increase the size of the click target by making a second, // invisible, larger path element. var path = $("path:first", g); path.clone().attr("stroke-width", "10px").attr("stroke", "transparent").appendTo(path.parent()); // On click, update the info box. g. css({cursor: "pointer"}). on("click", function(ev) { showEdge(strings, edge); }); }); enableHighlighting($("#graph")[0]); zoomify($("#graph")[0], $("#graphWrap")[0]); $("#graph").css("visibility", "visible"); } function showEdge(strings, edge) { var info = $("#info"); info.empty().scrollTop(0); // Show summary information. $("<p>").appendTo(info).text( edge.Paths.length + " path(s) acquire " + edge.Locks[0] + ", then " + edge.Locks[1] + ":" ).css({fontWeight: "bold"}); $.each(edge.Paths, function(_, path) { var p = $("<p>").appendTo(info).css("white-space", "nowrap"); $("<div>").appendTo(p).text(strings[path.RootFn]); function posText(pathID, line) { // Keep only the trailing part of the path. return strings[pathID].replace(/.*\//, "") + ":" + line; } function renderStack(stack) { var elided = []; var elideDiv; // Render each frame. $.each(stack.Op, function(i) { var div = $("<div>").appendTo(p); var indent = i == 0 ? "1em" : "2em"; var showFirst = 2, showLast = 3; if (i >= showFirst && stack.Op.length - i > showLast) { // Elide middle of the path. if (elided.length === 0) { elideDiv = $("<div>").appendTo(p).css("padding-left", indent); } elided.push(div[0]); } div.appendTo(p); // TODO: Link to path somehow. div.text(strings[stack.Op[i]] + " at " + posText(stack.P[i], stack.L[i])); div.css("padding-left", indent); }); // If we elided frames, update the show link. if (elided.length === 1) { // No point in eliding one frame. elidedDiv.hide(); } else if (elided.length > 0) { elideDiv.text("... show " + elided.length + " elided frames ...").css({color: "#00e", cursor: "pointer"}); $(elided).hide(); elideDiv.on("click", function(ev) { elideDiv.hide(); $(elided).show(); }) } } renderStack(path.From); renderStack(path.To); }); } // enableHighlighting takes an GraphViz-generated SVG and enables // interactive highlighting when the mouse hovers over nodes and // edges. function enableHighlighting(svg) { var nodes = {}, edges = {}; function all(opacity) { $.each(nodes, function(_, node) { $(node.dom).clearQueue().fadeTo('fast', opacity); }) $.each(edges, function(_, edge) { $(edge.dom).clearQueue().fadeTo('fast', opacity); }) } function highlight(dom) { $(dom).clearQueue().fadeTo('fast', 1); } // Process nodes. $(".node", svg).each(function(_, node) { var id = $("title", node).text(); var info = {dom: node, edges: []}; nodes[id] = info; $(node).on("mouseenter", function() { all(0.25); highlight(node); $.each(info.edges, function(_, edge) { highlight(edge.dom); if (edge.from !== id) highlight(nodes[edge.from].dom); if (edge.to !== id) highlight(nodes[edge.to].dom); }); }).on("mouseleave", function() { all(1); }); }); // Process edges. $(".edge", svg).each(function(_, edge) { var id = $("title", edge).text(); var m = id.match(/^(.*)->(.*)$/); var info = {dom: edge, from: m[1], to: m[2]}; edges[edge.id] = info; nodes[info.from].edges.push(info); nodes[info.to].edges.push(info); $(edge).on("mouseenter", function() { all(0.25); highlight(edge); highlight(nodes[info.from].dom); highlight(nodes[info.to].dom); }).on("mouseleave", function() { all(1); }); }); } // zoomify makes drags and wheel events on element fill pan and zoom // svg. It initially centers the svg at (0, 0) and scales it down to // fit in fill. Hence, the caller should center the svg element within // fill. function zoomify(svg, fill) { var svg = $(svg); var fill = $(fill); // Wrap svg in a group we can transform. var g = $(document.createElementNS("http://www.w3.org/2000/svg", "g")); g.append(svg.children()).appendTo(svg); // Create an initial transform to center and fit the svg. var bbox = g[0].getBBox(); var scale = Math.min(fill.width() / bbox.width, fill.height() / bbox.height); if (scale > 1) scale = 1; var mat = svg[0].createSVGMatrix(). translate(-bbox.x, -bbox.y). scale(scale). translate(-bbox.width/2, -bbox.height/2); var transform = svg[0].createSVGTransform(); transform.setMatrix(mat); g[0].transform.baseVal.insertItemBefore(transform, 0); // Handle drags. var lastpos; function mousemove(ev) { if (ev.buttons == 0) { fill.off("mousemove"); return; } var deltaX = ev.pageX - lastpos.pageX; var deltaY = ev.pageY - lastpos.pageY; lastpos = ev; var transform = svg[0].createSVGTransform(); transform.setTranslate(deltaX, deltaY); g[0].transform.baseVal.insertItemBefore(transform, 0); g[0].transform.baseVal.consolidate(); ev.preventDefault(); } fill.on("mousedown", function(ev) { lastpos = ev; fill.on("mousemove", mousemove); ev.preventDefault(); }); fill.on("mouseup", function(ev) { fill.off("mousemove"); ev.preventDefault(); }); // Handle zooms. var point = svg[0].createSVGPoint(); fill.on("wheel", function(ev) { var delta = ev.originalEvent.deltaY; // rates is the delta required to scale by a factor of 2. var rates = [ 500, // WheelEvent.DOM_DELTA_PIXEL 30, // WheelEvent.DOM_DELTA_LINE 0.5, // WheelEvent.DOM_DELTA_PAGE ]; var factor = Math.pow(2, -delta / rates[ev.originalEvent.deltaMode]); point.x = ev.clientX === undefined ? ev.originalEvent.clientX : ev.clientX; point.y = ev.clientY === undefined ? ev.originalEvent.clientY : ev.clientY; var center = point.matrixTransform(svg[0].getScreenCTM().inverse()); // Scale by factor around center. var mat = svg[0].createSVGMatrix(). translate(center.x, center.y). scale(factor). translate(-center.x, -center.y); var transform = svg[0].createSVGTransform(); transform.setMatrix(mat); g[0].transform.baseVal.insertItemBefore(transform, 0); g[0].transform.baseVal.consolidate(); ev.preventDefault(); }); }
JavaScript
0
@@ -2501,17 +2501,16 @@ elide -d Div.hide
6cc70d80cd4c172c13fdfe8cef118c4f8c5e4c1f
correct typo of the github checks API name used to change the build status
scripts/utils/handle-now-aliases.js
scripts/utils/handle-now-aliases.js
#!/usr/bin/env node const shell = require('shelljs'); const { TRAVIS } = require('./travis-vars'); const { normalizeUrlAlias } = require('./normalize-url-alias'); let setCheckRun, outputBanner; const { NOW_TOKEN } = process.env; async function aliasNowUrl(originalUrl, prefix) { console.log( 'Creating now.sh alias off of the ' + originalUrl + ' deployment URL.', ); if (TRAVIS) { setCheckRun = require('../check-run').setCheckRun; outputBanner = require('ci-utils').outputBanner; await setCheckRun({ name: 'Deploy - now.sh (basic)', status: 'in_progress', }); outputBanner('Starting deploy...'); } const deployedUrl = originalUrl.trim(); let aliasedUrl; if (prefix) { aliasedUrl = normalizeUrlAlias(prefix); } else { aliasedUrl = 'https://boltdesignsystem.com'; } console.log(`Attempting to alias ${originalUrl} to ${aliasedUrl}...`); if (TRAVIS) { await setCheckRun({ status: 'in_progress', name: 'Deploy - now.sh (alias)', }); } const aliasOutput = shell.exec( `npx now alias ${deployedUrl} ${aliasedUrl} --team=boltdesignsystem --token=${NOW_TOKEN}`, ); if (aliasOutput.code !== 0) { console.log('Error aliasing:'); console.log(aliasOutput.stdout, aliasOutput.stderr); if (TRAVIS) { await setCheckRun({ status: 'completed', name: 'Deploy - now.sh (alias)', conclusion: 'failure', output: { title: 'Now.sh Deploy failure', summary: ` ${aliasOutput.stdout} ${aliasOutput.stderr} `.trim(), }, }); } process.exit(1); } else { // console.log('Success Aliasing!'); console.log(aliasOutput.stdout); // console.log(deployedUrl); // console.log(aliasedUrl); if (TRAVIS) { await setCheckRun({ status: 'completed', name: 'Deploy - now.sh (alias)', conclusion: 'success', output: { title: 'Now.sh Deploy', summary: ` - ${deployedUrl} - ${aliasedUrl} `.trim(), }, }); } } } module.exports = { aliasNowUrl, };
JavaScript
0.000002
@@ -555,13 +555,13 @@ sh ( -basic +alias )',%0A
9a69cc40a1e013133a5cf7380dfeda5bfb01679b
Revert last commit
src/process-directory.js
src/process-directory.js
'use strict'; import fs from 'fs'; import path from 'path'; /******************************************************************************/ function findSuffixes (name, files) { let result = []; for (let file of files) { const regex = new RegExp (`${name}\.([a-zA-Z]+)\.js`); const match = file.match (regex); if (match) { result.push (match[1]); } } return result; } /******************************************************************************/ export default function processDirectory (root, dir, suffix, next) { if (typeof dir === 'string') { dir = [dir]; } if (Array.isArray (dir) === false) { throw new Error ('dir should be a string or an array of strings'); } const filter = new RegExp (suffix.replace ('.', '\\.') + '$'); const pattern = new RegExp ('([^\\/\\\\]+)' + filter.source); let result = []; function extract (dirs, file, files) { const matches = file.match (pattern); if (matches) { const name = matches[1]; const filePath = [...dirs, file].join (path.sep); const suffixes = findSuffixes (name, files.filter (x => x !== file)); result.push ([name, filePath, suffixes]); } } traverse (root, dir, extract, err => { if (err) { next (err); } else { result.sort ((a, b) => a[1].localeCompare (b[1])); next (err, result); } }); } /******************************************************************************/ function traverse (root, dirs, collect, next) { const rootPath = path.join (root, ...dirs); fs.lstat (rootPath, (err, stats) => { if (err) { next (err); } else { fs.readdir (rootPath, (err, files) => { let pending = files.length; for (let file of files) { const filePath = path.join (root, ...dirs, file); fs.lstat (filePath, (err, stats) => { if (err) { next (err); } else { if (stats.isDirectory ()) { traverse (root, [...dirs, file], collect, err => { if (err) { next (err); } else { if (--pending === 0) { next (); } } }); } else { if (stats.isFile ()) { collect (dirs, file, files); if (--pending === 0) { next (); } } } } }); } }); } }); } /******************************************************************************/
JavaScript
0
@@ -1051,16 +1051,11 @@ in ( -path.sep +'/' );%0A
08a167ff768317f41e962545a09517ffb9dd0c4e
Update Twitter.js
src/providers/Twitter.js
src/providers/Twitter.js
/** * Vic Shóstak <[email protected]> * Copyright (c) 2019 True web artisans https://1wa.co * http://opensource.org/licenses/MIT The MIT License (MIT) * * goodshare.js * * Twitter (https://twitter.com) provider. */ import { ProviderMixin } from "../utils/ProviderMixin"; export class Twitter extends ProviderMixin { constructor(url = document.location.href, title = document.title) { super(); this.url = encodeURIComponent(url); this.title = encodeURIComponent(title); this.createEvents = this.createEvents.bind(this); } getPreparedData(item) { const url = item.dataset.url ? encodeURIComponent(item.dataset.url) : this.url; const title = item.dataset.title ? encodeURIComponent(item.dataset.title) : this.title; const share_url = `https://twitter.com/share?url=${url}&text=${title}`; return { callback: this.callback, share_url: share_url, windowTitle: "Share this", windowWidth: 640, windowHeight: 480 }; } // Share event shareWindow() { const share_elements = document.querySelectorAll('[data-social="twitter"]'); return this.createEvents(share_elements); } }
JavaScript
0.000002
@@ -398,20 +398,35 @@ nt.title +, hashtags = %22%22 ) %7B%0A - supe @@ -514,16 +514,203 @@ title);%0A + // Allow easy discovery of Tweets by topic by including a comma-separated list of hashtag values without the preceding # character.%09%0A this.hashtags = encodeURIComponent(hashtags);%0A this @@ -986,16 +986,299 @@ .title;%0A + // Allow easy discovery of Tweets by topic by including a comma-separated list of hashtag values without the preceding # character.%09%0A // example: nature,sunset%0A const hashtags = item.dataset.hashtags%0A ? encodeURIComponent(item.dataset.hashtags)%0A : this.hashtags;%0A cons @@ -1342,16 +1342,37 @@ $%7Btitle%7D +&hashtags=$%7Bhashtags%7D %60;%0A%0A
3334605a9455d9903499b4bd9dfb30942a733037
error properties are non-enumerable
server/middleware/error-handling.js
server/middleware/error-handling.js
const logger = require('../lib/logger'); module.exports = () => (err, req, res, next) => { res.statusCode = err.status || 500; res.body = { error: err.message }; if (res.statusCode >= 500) { req.error = err; logger.error({ error: req, }); req.body = { error: 'Internal Error' }; } next(); };
JavaScript
0.999318
@@ -217,19 +217,81 @@ error = -err +%7B%0A message: err.message,%0A stack: err.stack,%0A %7D ;%0A
2055a86276b7b3ae62faa5df4e4c3e25e3720b45
rollback to snake case
services/personality_insights/v2.js
services/personality_insights/v2.js
/** * Copyright 2014 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var extend = require('extend'); var requestFactory = require('../../lib/requestwrapper'); var pick = require('object.pick'); var omit = require('object.omit'); /** * Return true if 'text' is html * @param {String} text The 'text' to analyze * @return {Boolean} true if 'text' has html tags */ function isHTML(text){ return /<[a-z][\s\S]*>/i.test(text); } function PersonalityInsights(options) { // Default URL var serviceDefaults = { url: 'https://gateway.watsonplatform.net/personality-insights/api' }; // Replace default options with user provided this._options = extend(serviceDefaults, options); } /** * @param params {Object} The parameters to call the service * The accepted parameters are: * - text: The text to analyze. * - contentItems: A JSON input (if 'text' not provided). * - includeRaw: include raw results * - acceptLanguage : The language expected for the output. * - language: The language of the input. * * @param callback The callback. */ PersonalityInsights.prototype.profile = function(params, callback) { if (!params || (!params.text && !params.contentItems)) { callback(new Error('Missing required parameters: text or contentItems')); return; } // include_raw var queryString = { }; if (params.include_raw || params.includeRaw) queryString.include_raw = true; // Content-Type var contentType = null; if (params.text) contentType = isHTML(params.text) ? 'text/html' : 'text/plain'; else contentType = 'application/json'; var parameters = { options: { method: 'POST', url: '/v2/profile', body: params.text || params.html || pick(params, ['contentItems']), json: true, qs: queryString, headers: { 'Content-type' : contentType, 'Content-language': params.language ? params.language : 'en', 'Accept-language' : params.acceptLanguage ? params.acceptLanguage : 'en' } }, defaultOptions: this._options }; return requestFactory(parameters, callback); }; module.exports = PersonalityInsights;
JavaScript
0.000009
@@ -1500,17 +1500,18 @@ include -R +_r aw: incl @@ -1537,25 +1537,26 @@ - accept -L +_l anguage : Th @@ -1908,127 +1908,23 @@ // -include_raw%0A var queryString = %7B %7D;%0A if (params.include_raw %7C%7C params.includeRaw)%0A queryString.include_raw = true; +Accept language %0A%0A @@ -1948,25 +1948,26 @@ var content -T +_t ype = null;%0A @@ -1992,25 +1992,26 @@ %0A content -T +_t ype = isHTML @@ -2072,17 +2072,18 @@ content -T +_t ype = 'a @@ -2291,19 +2291,37 @@ qs: -queryString +pick(params, %5B'include_raw'%5D) ,%0A @@ -2370,17 +2370,18 @@ content -T +_t ype,%0A @@ -2488,25 +2488,26 @@ s.accept -L +_l anguage ? params @@ -2490,33 +2490,34 @@ accept_language -? +%7C%7C params.acceptLa @@ -2519,25 +2519,26 @@ eptLanguage -: +%7C%7C 'en'%0A
538a8603031f759c24c309662c1485419d986cc7
Add read depth fragment to dof shader
shaders/post-processing/dof.frag.js
shaders/post-processing/dof.frag.js
module.exports = /* glsl */ ` precision highp float; varying vec2 vTexCoord0; uniform sampler2D image; //Image to be processed uniform sampler2D depthMap; //Linear depth, where 1.0 == far plane uniform vec2 uPixelSize; //The size of a pixel: vec2(1.0/width, 1.0/height) uniform float uFar; // Far plane uniform float uNear; uniform float uFocusPoint; uniform float uFocusScale; const float GOLDEN_ANGLE = 2.39996323; const float MAX_BLUR_SIZE = 20.0; const float RAD_SCALE = 0.5; // Smaller = nicer blur, larger = faster float readDepth(const in sampler2D depthMap, const in vec2 coord, const in float near, const in float far) { float z_b = texture2D(depthMap, coord).r; float z_n = 2.0 * z_b - 1.0; float z_e = 2.0 * near * far / (far + near - z_n * (far - near)); return z_e; } float getBlurSize(float depth, float focusPoint, float focusScale) { float coc = clamp((1.0 / focusPoint - 1.0 / depth)*focusScale, -1.0, 1.0); return abs(coc) * MAX_BLUR_SIZE; } vec3 depthOfField(vec2 texCoord, float focusPoint, float focusScale) { float centerDepth = readDepth(depthMap, texCoord,uNear,uFar); float centerSize = getBlurSize(centerDepth, focusPoint, focusScale); //return vec3(centerSize/2.0); vec3 color = texture2D(image, vTexCoord0).rgb; float tot = 1.0; float radius = RAD_SCALE; for (float ang = 0.0; ang < 180.0; ang += GOLDEN_ANGLE){ vec2 tc = texCoord + vec2(cos(ang), sin(ang)) * uPixelSize * radius; vec3 sampleColor = texture2D(image, tc).rgb; float sampleDepth = readDepth(depthMap, tc,uNear,uFar); float sampleSize = getBlurSize(sampleDepth, focusPoint, focusScale); if (sampleDepth > centerDepth) sampleSize = clamp(sampleSize, 0.0, centerSize*2.0); float m = smoothstep(radius-0.5, radius+0.5, sampleSize); color += mix(color/tot, sampleColor, m); tot += 1.0; radius += RAD_SCALE/radius; if(radius > MAX_BLUR_SIZE){ break; } } return color /= tot; } void main () { vec3 color = depthOfField(vTexCoord0,uFocusPoint,uFocusScale); gl_FragColor = vec4(color,1); } `
JavaScript
0
@@ -1,8 +1,54 @@ +const SHADERS = require('../chunks/index.js')%0A module.e @@ -576,282 +576,27 @@ r%0A%0A%0A -float readDepth(const in sampler2D depthMap, const in vec2 coord, const in float near, const in float far) %7B%0A float z_b = texture2D(depthMap, coord).r;%0A float z_n = 2.0 * z_b - 1.0;%0A float z_e = 2.0 * near * far / (far + near - z_n * (far - near));%0A return z_e;%0A +$%7BSHADERS.depthRead %7D%0A%0Af
6127f227c6ba64508e6cb53f265ec529923c8aad
Modify styling for stories list
simul/app/components/userStories.js
simul/app/components/userStories.js
import React, { Component } from 'react'; import { StyleSheet, Text, View, ListView, TouchableHighlight, } from 'react-native'; class UserStories extends Component{ constructor(props) { super(props); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { dataSource: ds.cloneWithRows([ 'Story 1', 'Story 2', 'Story 3', 'Story 4', 'Story 5', 'Story 6', 'Story 7', 'Story 8', 'Story 9', 'Story 10', 'Story 11' ]) }; } _onPressStory() { this.props.navigator.push({ title: 'Story', component: Story }) } newestStory() { return( <View style={{backgroundColor: 'lightgrey'}}> <Text style={{color: 'purple', textAlign: 'left'}}>Monday August 24, 2016</Text> <Text>"My day today was very interesting. First I woke up late and I couldn't find my clean clothes and my mom......"</Text> <Text>كان يوم لي اليوم مثيرة جدا للاهتمام. أولا استيقظت في وقت متأخر، وأنا لا يمكن أن تجد لي ملابس نظيفة وأمي</Text> </View> ) } render() { return ( <View style={styles.container}> <Text>Smeagles Stories</Text> <ListView style={styles.listItems} dataSource={this.state.dataSource} renderRow={(rowData) => <TouchableHighlight onPress={ () => this._onPressStory()}><Text style={styles.listText}>{rowData}</Text></TouchableHighlight>} renderHeader={ () => this.newestStory() } /> </View> ) } }; var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, title: { fontSize: 20, alignSelf: 'center', margin: 40 }, }); module.exports = UserStories;
JavaScript
0
@@ -354,16 +354,223 @@ %0A + 'Tuesday August 23, 2016', 'Wednesday August 10, 2016', 'Wednesday August 3, 2016', 'Thursday July 28, 2016', 'Monday July 18, 2016', 'Thursday July 14, 2016', 'Saturday July 2, 2016', 'Story 8', 'Story 9', 'Story @@ -570,16 +570,17 @@ 'Story 1 +0 ', 'Stor @@ -581,17 +581,18 @@ 'Story -2 +11 ', 'Stor @@ -593,17 +593,17 @@ 'Story -3 +8 ', 'Stor @@ -604,17 +604,17 @@ 'Story -4 +9 ', 'Stor @@ -619,9 +619,10 @@ ory -5 +10 ', ' @@ -627,17 +627,18 @@ 'Story -6 +11 ', 'Stor @@ -643,9 +643,44 @@ ory -7 +8', 'Story 9', 'Story 10', 'Story 11 ', ' @@ -722,16 +722,63 @@ tory 11' +, 'Story 8', 'Story 9', 'Story 10', 'Story 11', %0A %5D @@ -1938,16 +1938,28 @@ itle: %7B%0A + flex: 2,%0A fontS @@ -2010,16 +2010,90 @@ 40%0A %7D,%0A + listText: %7B%0A fontSize: 20,%0A flex: 2,%0A textAlign: 'center',%0A %7D%0A %7D);%0A%0Amod
5f8690729e3e4432b4776f9e56f65589b21f9050
fix the integration test
src/secure-handlebars.js
src/secure-handlebars.js
/* Copyright (c) 2015, Yahoo Inc. All rights reserved. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. Authors: Nera Liu <[email protected]> Albert Yu <[email protected]> Adonis Fung <[email protected]> */ var Handlebars = require('handlebars'), ContextParserHandlebars = require("context-parser-handlebars"), xssFilters = require('xss-filters'); function preprocess(template) { try { if (template) { var parser = new ContextParserHandlebars({printCharEnable: false}); return parser.analyzeContext(template); } } catch (err) { console.log('====================='); console.log("[WARNING] SecureHandlebars: falling back to the original template"); Object.keys(err).forEach(function(k){console.log(k.toUpperCase() + ':\n' + err[k]);}); console.log("TEMPLATE:\n" + template); console.log('====================='); } return template; } function override(h) { var c = h.compile, pc = h.precompile, privateFilters = xssFilters._privFilters; // override precompile function to preprocess the template first h.precompile = function (template, options) { return pc.call(this, preprocess(template), options); }; // override compile function to preprocess the template first h.compile = function (template, options) { return c.call(this, preprocess(template), options); }; // register below the filters that are automatically applied by context parser [ 'y', 'yd', 'yc', 'yavd', 'yavs', 'yavu', 'yu', 'yuc', 'yubl', 'yufull' ].forEach(function(filterName){ h.registerHelper(filterName, privateFilters[filterName]); }); // register below the filters that might be manually applied by developers [ 'inHTMLData', 'inHTMLComment', 'inSingleQuotedAttr', 'inDoubleQuotedAttr', 'inUnQuotedAttr', 'uriInSingleQuotedAttr', 'uriInDoubleQuotedAttr', 'uriInUnQuotedAttr', 'uriInHTMLData', 'uriInHTMLComment', 'uriPathInSingleQuotedAttr', 'uriPathInDoubleQuotedAttr', 'uriPathInUnQuotedAttr', 'uriPathInHTMLData', 'uriPathInHTMLComment', 'uriQueryInSingleQuotedAttr', 'uriQueryInDoubleQuotedAttr', 'uriQueryInUnQuotedAttr', 'uriQueryInHTMLData', 'uriQueryInHTMLComment', 'uriComponentInSingleQuotedAttr', 'uriComponentInDoubleQuotedAttr', 'uriComponentInUnQuotedAttr', 'uriComponentInHTMLData', 'uriComponentInHTMLComment', 'uriFragmentInSingleQuotedAttr', 'uriFragmentInDoubleQuotedAttr', 'uriFragmentInUnQuotedAttr', 'uriFragmentInHTMLData', 'uriFragmentInHTMLComment' ].forEach(function(filterName){ h.registerHelper(filterName, xssFilters[filterName]); }); return h; } if (module && module.exports) { module.exports = override(Handlebars.create()); } else { override(Handlebars); }
JavaScript
0.000094
@@ -1241,32 +1241,65 @@ ate, options) %7B%0A + options = options %7C%7C %7B%7D;%0A return p @@ -1456,32 +1456,65 @@ ate, options) %7B%0A + options = options %7C%7C %7B%7D;%0A return c
bce61e972df216d188f76acbb67e912d8a63ee20
Fix unexpected character in log output
src/services/Terminal.js
src/services/Terminal.js
const {gray, yellow, red, blue} = require('chalk'); const readline = require('../lib/readline/readline'); const EventEmitter = require('events'); const {Readable} = require('stream'); const boxen = require('boxen'); module.exports = class Terminal extends EventEmitter { static create(options) { const readlineInterface = readline.createInterface({ input: options.interactive ? process.stdin : new Readable({read: () => undefined}), output: process.stdout, prompt: options.interactive ? blue('>> ') : '', historySize: 0 }); return new Terminal(console, readlineInterface); } /** * @param {Console} console * @param {readline.Interface} readlineInterface */ constructor(console, readlineInterface) { super(); if (!console) { throw new Error('console is missing'); } if (!readlineInterface) { throw new Error('readlineInterface is missing'); } this._line = null; this._console = console; this._readline = readlineInterface; this._promptEnabled = false; this._ignoreInput = true; this._readline.on('close', () => this.emit('close')); this._readline.on('line', line => { if (this._ignoreInput) { return; } if (line) { this.emit('line', line); } else { this.clearInput(); } }); this._readline.input.prependListener('keypress', (_ev, key) => { if (key.name === 'return') { this._replacePromptInLineWith(gray('>> ')); } }); this._readline.input.on('keypress', (ev, key) => { if (!this._ignoreInput) { this.emit('keypress', key); } }); } clearInput(line = '') { if (line && !this.promptEnabled) { throw new Error('Prompt disabled'); } this._clearLine(); this._line = line; this._restorePrompt(); } set promptEnabled(enabled) { if (enabled && !this._promptEnabled) { this._promptEnabled = true; this._restorePrompt(); } else if (!enabled && this._promptEnabled) { this._hidePrompt(); this._promptEnabled = false; } } get promptEnabled() { return this._promptEnabled; } infoBlock({title, body}) { const indentedBody = body.split(/\n/).map(line => ` ${blue(line)}`).join('\n'); this._hidePrompt(); this._console.log(boxen( yellow(title) + '\n' + indentedBody , {padding: {left: 1, right: 1}, borderStyle: 'round'})); this._restorePrompt(); } message(text) { this._hidePrompt(); this._console.log(yellow(text)); this._restorePrompt(); } output(text) { this._hidePrompt(); this._console.log(text); this._restorePrompt(); } log(text) { this._hidePrompt(); this._console.log(`️ ${text}`); this._restorePrompt(); } info(text) { this._hidePrompt(); this._console.log(blue(`> ${text}`)); this._restorePrompt(); } debug(text) { this._hidePrompt(); this._console.log(` ${text}`); this._restorePrompt(); } warn(text) { this._hidePrompt(); this._console.log(yellow(`> ${text}`)); this._restorePrompt(); } error(text) { this._hidePrompt(); this._console.error(red(`> ${text}`)); this._restorePrompt(); } returnValue(text) { this._hidePrompt(); this._console.log(`${gray('<-')} ${text}`); this._restorePrompt(); } _replacePromptInLineWith(prefix) { this._clearLine(); this._readline.output.write(prefix + this._readline.line); } _hidePrompt() { if (this._promptEnabled) { if (this._line === null) { this._line = this._readline.line; } this._ignoreInput = true; this._clearLine(); } } _restorePrompt() { if (this._promptEnabled) { const command = this._line || ''; this._readline.line = command; this._readline.cursor = command.length; this._readline.prompt(true); this._ignoreInput = false; this._line = null; } } _clearLine() { this._readline.output.write('\x1b[2K\r'); } };
JavaScript
0.999993
@@ -2750,9 +2750,8 @@ og(%60 -%EF%B8%8F $%7B
8037fe69f4ef837c31f1aa32c34f5d293de5e3ea
Add 3 more drivers.
src/teamcity/buildIds.js
src/teamcity/buildIds.js
module.exports = { "Drivers.ION": "Drivers_Ion_Ci", "Drivers.Ziv": "Drivers_ZIV_Ci", "Drivers.SL7000": "Drivers_SL7000_Ci", "Drivers.Q1000": "Drivers_Q1000_Ci", "Drivers.Nexus": "Drivers_Nexus_Ci", "Way2 Abnt": "Drivers_Abnt_Ci", "Drivers.E3": "Drivers_E3_Ci", }
JavaScript
0
@@ -268,10 +268,125 @@ E3_Ci%22,%0A + %22Drivers.Ansi%22: %22Drivers_Ansi_Ci%22,%0A %22Drivers.Cylec%22: %22Drivers_Cylec_Ci%22,%0A %22Integracao.Wits%22: %22Drivers_Wits_Ci%22%0A %7D%0A
8d4b821d9879fb84fb2c545691c5f6d6017ab07c
return empty set for invisible bar trace
src/traces/bar/select.js
src/traces/bar/select.js
/** * Copyright 2012-2017, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var DESELECTDIM = require('../../constants/interactions').DESELECTDIM; module.exports = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd; var selection = []; var trace = cd[0].trace; var node3 = cd[0].node3; var i; if(trace.visible !== true) return; if(polygon === false) { // clear selection for(i = 0; i < cd.length; i++) { cd[i].dim = 0; } } else { for(i = 0; i < cd.length; i++) { var di = cd[i]; if(polygon.contains(di.ct)) { selection.push({ pointNumber: i, x: di.x, y: di.y }); di.dim = 0; } else { di.dim = 1; } } } node3.selectAll('.point').style('opacity', function(d) { return d.dim ? DESELECTDIM : 1; }); node3.selectAll('text').style('opacity', function(d) { return d.dim ? DESELECTDIM : 1; }); return selection; };
JavaScript
0.000013
@@ -494,16 +494,19 @@ ) return + %5B%5D ;%0A%0A i
3a19125e1c3e030edb9f0cf84f8cbdc494c7fe1d
refactor transition.remove
src/transition/remove.js
src/transition/remove.js
import "transition"; d3_transitionPrototype.remove = function() { var ns = this.namespace; return this.each("end.transition", function() { var p; if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this); }); };
JavaScript
0.000016
@@ -1,66 +1,20 @@ -im +%0Aex port -%22transition%22;%0A%0Ad3_transitionPrototype.remove = function () %7B @@ -5,24 +5,31 @@ ort function + remove () %7B%0A var n @@ -102,19 +102,8 @@ ) %7B%0A - var p;%0A @@ -131,13 +131,8 @@ 2 && - (p = thi @@ -148,11 +148,33 @@ ode) -) p + %7B%0A this.parentNode .rem @@ -193,13 +193,18 @@ s);%0A + %7D%0A %7D);%0A%7D -; %0A
e8bff70fcb22b41ff248cba23f42770eebc75b0a
remove redundant comments
src/util/config/build.js
src/util/config/build.js
import fs from 'fs'; import convict from 'convict'; import path from 'path'; /** * This module provides a single source of truth for application configuration * info. It uses node-convict to read configuration info from, in increasing * order of precedence: * * 1. Default value * 2. File (`config.loadFile()`) - app root `config.<NODE_ENV>.json` * 3. Environment variables * 4. Command line arguments * 5. Set and load calls (config.set() and config.load()) * * Note that environment variables have _higher_ precedence than values in * config files, so the config files will only work if environment variables * are cleared. * * The only values that _must_ be in environment variables are the secrets that * are used to interact with external systems: * * - `MUPWEB_OAUTH_SECRET` * - `MUPWEB_OAUTH_KEY` * - `PHOTO_SCALER_SALT` * * @module config */ export const PROTOCOL_ERROR = 'Protocol must be http or https'; export const validateProtocol = protocol => { if (!['http', 'https'].includes(protocol)) { throw new Error(PROTOCOL_ERROR); } }; export const schema = { env: { format: ['production', 'development', 'test'], default: 'development', env: 'NODE_ENV', }, asset_server: { host: { format: String, default: 'beta2.dev.meetup.com', env: 'ASSET_SERVER_HOST', }, path: { format: String, default: '/static', env: 'ASSET_PATH', }, port: { format: 'port', default: 8001, arg: 'asset-port', env: process.env.NODE_ENV !== 'test' && 'ASSET_SERVER_PORT', // don't read env in tests }, }, app_server: { protocol: { format: validateProtocol, default: 'http', env: 'DEV_SERVER_PROTOCOL', // legacy naming }, host: { format: String, default: 'beta2.dev.meetup.com', env: 'DEV_SERVER_HOST', // legacy naming }, port: { format: 'port', default: 8000, arg: 'app-port', env: process.env.NODE_ENV !== 'test' && 'DEV_SERVER_PORT', // don't read env in tests }, }, disable_hmr: { format: Boolean, default: false, env: 'DISABLE_HMR', }, isDev: { format: Boolean, default: true, }, isProd: { format: Boolean, default: false, }, }; export const config = convict(schema); // Load environment dependent configuration const configPath = path.resolve( process.cwd(), `config.${config.get('env')}.json` ); export const localBuildConfig = fs.existsSync(configPath) ? require(configPath).buildtime || {} : {}; config.load(localBuildConfig); config.set('isProd', config.get('env') === 'production'); config.set('isDev', config.get('env') === 'development'); config.validate(); export default config.getProperties();
JavaScript
0.000005
@@ -95,779 +95,46 @@ le p -rovides a single source of truth for application configuration%0A * info. It uses node-convict to read configuration info from, in increasing%0A * order of precedence:%0A *%0A * 1. Default value%0A * 2. File (%60config.loadFile()%60) - app root %60config.%3CNODE_ENV%3E.json%60%0A * 3. Environment variables%0A * 4. Command line arguments%0A * 5. Set and load calls (config.set() and config.load())%0A *%0A * Note that environment variables have _higher_ precedence than values in%0A * config files, so the config files will only work if environment variables%0A * are cleared.%0A *%0A * The only values that _must_ be in environment variables are the secrets that%0A * are used to interact with external systems:%0A *%0A * - %60MUPWEB_OAUTH_SECRET%60%0A * - %60MUPWEB_OAUTH_KEY%60%0A * - %60PHOTO_SCALER_SALT%60%0A *%0A * @module config +opulates build time configuration data %0A */
bb4c609fb8f9f838ba88672d3c8673a862bb211f
Change facebooks authorization endpoint
src/utils/oauthConfig.js
src/utils/oauthConfig.js
import clientConfig from "utils/clientConfig" // const getRandomString = (length) => { // const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' // let text = '' // for (let i = 0; i < length; i += 1) { // text += possible.charAt(Math.floor(Math.random() * length)) // } // return text // } const oauthConfig = { google: { name: "Google", url: "/auth/google", authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth", clientId: clientConfig.google.clientId, redirectUrl: `${window.location.origin}/google/callback`, requiredUrlParams: [["response_type", "code"]], scopes: ["email"], scopeDelimiter: " ", optionalUrlParams: [["state", "google"]], popupOptions: { width: 1020, height: 633 }, }, facebook: { name: "Facebook", url: "/auth/facebook", authorizationEndpoint: "https://www.facebook.com/v2.5/dialog/oauth", clientId: clientConfig.facebook.clientId, redirectUrl: `${window.location.origin}/facebook/callback`, scopes: ["email"], scopeDelimiter: ",", optionalUrlParams: [["state", "facebook"], ["response_type", "code"]], popupOptions: { width: 1028, height: 640 }, }, linkedin: { name: "LinkedIn", url: "/auth/linkedin", authorizationEndpoint: "https://www.linkedin.com/uas/oauth2/authorization", clientId: clientConfig.linkedin.clientId, redirectUrl: `${window.location.origin}/linkedin/callback`, scopes: ["r_emailaddress"], scopeDelimiter: " ", requiredUrlParams: [["state", "linkedin"], ["response_type", "code"]], popupOptions: { width: 1028, height: 640 }, }, orcid: { name: "ORCID", url: "/auth/orcid", authorizationEndpoint: "https://orcid.org/oauth/authorize", clientId: clientConfig.orcid.clientId, redirectUrl: `${window.location.origin}/orcid/callback`, scopes: ["/authenticate"], scopeDelimiter: " ", requiredUrlParams: [["response_type", "code"]], popupOptions: { width: 1028, height: 640 }, }, } export default oauthConfig
JavaScript
0.000001
@@ -892,13 +892,8 @@ com/ -v2.5/ dial
b22186f153235896b74cd1b3bd8283cc50d35ea0
Add fetch mode to support stats in chrome
src/utils/performance.js
src/utils/performance.js
import Vue from 'vue' import { Platform } from 'quasar' import router from '@/base/router' import datastore from '@/base/datastore' import axios from '@/base/api/axios' import { debounceAndFlushOnUnload, underscorizeKeys } from '@/utils/utils' const SAVE_INTERVAL_MS = 5000 // batch saves to the backend const performance = window.performance const fetch = window.fetch // Make sure we have all the required performance methods // and fetch to avoid needing the polyfill (we don't need all browser support) // and that vue's performance mode is not enabled (don't want to fight it) const ENABLED = fetch && performance && performance.clearMeasures && performance.clearMarks && performance.measure && performance.mark && !Vue.config.performance // For each load we measure up to the point where the first v-measure is measured // the set done to true so we don't record beyond that, until the next page load let done = false // The first load is the main page load from the server, after that we record the page // loads within the browser let firstLoad = true // When using performance.measure() we don't use a start mark initially, which causes it to // measure from the start of that whole page load, subsequent javascript page loads are only // measured from when we create the mark in router beforeEach() let startMark // What we will eventually save for this measurement run // Keeping it up here so its possible to add things to it as we go along... // ... well basically the firstLoad flag let currentStat = {} // Stats waiting to be saved const pendingStats = [] function initialize () { startMark = 'karrot-start' done = false currentStat = {} performance.clearMarks() performance.clearMeasures() performance.clearResourceTimings() performance.mark(startMark) } function measure (name, qualifier) { if (!ENABLED || done) return const label = ['karrot', name, qualifier].join(' ').trim() if (startMark) { performance.measure(label, startMark) } else { performance.measure(label) } } function save () { const stats = [...pendingStats] pendingStats.length = 0 const data = { stats } // Using fetch() API instead of axios, just for this keepalive thing ... fetch('/api/stats/', { method: 'POST', // keepalive is to help the request still work when called in the "unload" event // See https://fetch.spec.whatwg.org/#request-keepalive-flag keepalive: true, headers: { 'Content-Type': 'application/json', [axios.defaults.xsrfHeaderName]: readCookie(axios.defaults.xsrfCookieName), }, body: JSON.stringify(underscorizeKeys(data)), }).catch(() => {}) // ignore errors, we can't do anything about it } const debouncedSave = debounceAndFlushOnUnload(save, SAVE_INTERVAL_MS, { maxWait: SAVE_INTERVAL_MS * 2 }) function finish () { const firstMeaningfulMount = performance.getEntriesByName('karrot MM')[0] if (!firstMeaningfulMount) return pendingStats.push({ ...currentStat, ms: firstMeaningfulMount && firstMeaningfulMount.duration, msResources: performance .getEntriesByType('resource') .reduce((total, entry) => total + entry.duration, 0), loggedIn: datastore.getters['auth/isLoggedIn'], group: datastore.getters['currentGroup/id'], routeName: router.currentRoute.name, routePath: router.currentRoute.fullPath, mobile: Boolean(Platform.is.mobile), browser: Platform.is.name, os: Platform.is.platform, dev: Boolean(__ENV.DEV), app: Boolean(__ENV.CORDOVA), }) debouncedSave() } if (ENABLED) { router.beforeEach((to, from, next) => { if (firstLoad) { firstLoad = false currentStat.firstLoad = true } else { initialize() currentStat.firstLoad = false } next() }) Vue.directive('measure', { inserted () { if (done) return measure('MM') // MM = "Meaningful Mount" inspired by FMP (First Meaningful Paint) done = true finish() }, }) } else { // measurement is not enabled // we create an empty directive so we don't have invalid use of v-measure directives in the rest of the code Vue.directive('measure', {}) } function readCookie (name) { // Stolen from axios implementation // See https://github.com/axios/axios/blob/a17c70cb5ae4acd7aa307b7f7dc869953dea22c4/lib/helpers/cookies.js#L35-L36 const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')) return (match ? decodeURIComponent(match[3]) : null) }
JavaScript
0
@@ -2436,16 +2436,226 @@ : true,%0A + // without this mode set, chrome will attempt a preflight (cors) request, but fails with:%0A // %22Preflight request for request with keepalive specified is currently not supported%22%0A mode: 'same-origin',%0A head
2cf4d6e86110a1f935822b9c9b69fc1b12368e99
Update Budget_Control.js
release/Budget_Control.js
release/Budget_Control.js
function main() { var SLACK_URL = 'https://hooks.slack.com/services/xxxxxxxx/zzzzzzzz/yyyyyyyy'; var SCRIPT_LABEL = 'Budget_Control'; // =================================================================== ensureAccountLabels(); // Проверяем и создаем ярлык var campaignSelector = AdWordsApp.campaigns() .withCondition('LabelNames CONTAINS_ANY ["' + SCRIPT_LABEL + '"]'); var campaignIterator = campaignSelector.get(); while (campaignIterator.hasNext()) { var campaign = campaignIterator.next(); var budget = campaign.getBudget(); var stats = campaign.getStatsFor('TODAY'); var cost = parseFloat(stats.getCost()).toFixed(2); if (budget.isExplicitlyShared() == true) { var budgetCampaignIterator = budget.campaigns().get(); var allAssociatedCost = +0; while (budgetCampaignIterator.hasNext()) { var associatedCampaign = budgetCampaignIterator.next(); // Logger.log(associatedCampaign.getName()); var associatedCampaignStats = associatedCampaign.getStatsFor('TODAY'); var associatedCost = associatedCampaignStats.getCost(); // Logger.log('Budget spend: ' + associatedCost); allAssociatedCost = allAssociatedCost + +associatedCost; } allAssociatedCost = parseFloat(allAssociatedCost).toFixed(2) if (allAssociatedCost > budget.getAmount()) { if (campaign.isEnabled() == true) { campaign.pause(); Logger.log('Campaign ' + campaign.getName() + ' paused'); Logger.log('Budget amount: ' + budget.getAmount()); Logger.log('Budget spend: ' + allAssociatedCost); Logger.log('-------------------------------------------------'); var message = ':double_vertical_bar: В кампании ' + campaign.getName() + ', сегодня расход ' + allAssociatedCost + ' при бюджете ' + budget.getAmount() + '. Кампания остановлена. \n\n'; sendSlackMessage(message); } } else { if (campaign.isPaused() == true) { campaign.enable(); Logger.log('Campaign ' + campaign.getName() + ' enabled'); Logger.log('Budget amount: ' + budget.getAmount()); Logger.log('Budget spend: ' + allAssociatedCost); Logger.log('-------------------------------------------------'); } } } else { if (cost > budget.getAmount()) { if (campaign.isEnabled() == true) { campaign.pause(); Logger.log('Campaign ' + campaign.getName() + ' paused'); Logger.log('Budget amount: ' + budget.getAmount()); Logger.log('Budget spend: ' + cost); Logger.log('-------------------------------------------------'); var message = ':double_vertical_bar: В кампании ' + campaign.getName() + ', сегодня расход ' + cost + ' при бюджете ' + budget.getAmount() + '. Кампания остановлена. \n\n'; sendSlackMessage(message); } } else { if (campaign.isPaused() == true) { campaign.enable(); Logger.log('Campaign ' + campaign.getName() + ' enabled'); Logger.log('Budget amount: ' + budget.getAmount()); Logger.log('Budget spend: ' + cost); Logger.log('-------------------------------------------------'); } } } } function ensureAccountLabels() { function getAccountLabelNames() { var labelNames = []; var iterator = AdWordsApp.labels().get(); while (iterator.hasNext()) { labelNames.push(iterator.next().getName()); } return labelNames; } var labelNames = getAccountLabelNames(); if (labelNames.indexOf(SCRIPT_LABEL) == -1) { AdWordsApp.createLabel(SCRIPT_LABEL); } } function sendSlackMessage(text, opt_channel) { var slackMessage = { text: text, icon_url: 'https://www.gstatic.com/images/icons/material/product/1x/adwords_64dp.png', username: 'AdWords Scripts', channel: opt_channel || '#adwords' }; var options = { method: 'POST', contentType: 'application/json', payload: JSON.stringify(slackMessage) }; UrlFetchApp.fetch(SLACK_URL, options); } }
JavaScript
0.000001
@@ -11,18 +11,16 @@ ain() %7B%0A - %0A var @@ -20,16 +20,35 @@ var +CONFIG = %7B%0A SLACK_UR @@ -48,18 +48,17 @@ LACK_URL - = +: 'https: @@ -111,25 +111,62 @@ yyyyyyy' -; +, %0A -var + // %D0%92%D0%B5%D0%B1%D1%85%D1%83%D0%BA %D0%B4%D0%BB%D1%8F %D0%A1%D0%BB%D0%B0%D0%BA%D0%B0%0A %0A SCRIPT_ @@ -170,18 +170,17 @@ PT_LABEL - = +: 'Budget @@ -188,20 +188,81 @@ Control' -; %0A + // %D0%A1%D0%BB%D0%B5%D0%B4%D0%B8%D0%BC %D0%B7%D0%B0 %D0%BA%D0%B0%D0%BC%D0%BF%D0%B0%D0%BD%D0%B8%D1%8F%D0%BC%D0%B8 %D0%BF%D0%BE%D0%BC%D0%B5%D1%87%D0%B5%D0%BD%D0%BD%D1%8B%D0%BC%D0%B8 %D1%8D%D1%82%D0%B8%D0%BC %D1%8F%D1%80%D0%BB%D1%8B%D0%BA%D0%BE%D0%BC%0A %7D;%0A %0A // @@ -329,19 +329,17 @@ =======%0A - %0A + ensu @@ -386,19 +386,17 @@ %D0%BC %D1%8F%D1%80%D0%BB%D1%8B%D0%BA%0A - %0A + var @@ -491,16 +491,23 @@ Y %5B%22' + +CONFIG. SCRIPT_L @@ -1102,69 +1102,8 @@ ();%0A - // Logger.log(associatedCampaign.getName());%0A @@ -1177,32 +1177,32 @@ tsFor('TODAY');%0A + @@ -1261,74 +1261,8 @@ ();%0A - // Logger.log('Budget spend: ' + associatedCost);%0A @@ -3736,35 +3736,33 @@ %7D%0A %7D%0A - %0A + function ens @@ -4147,16 +4147,23 @@ indexOf( +CONFIG. SCRIPT_L @@ -4212,16 +4212,23 @@ teLabel( +CONFIG. SCRIPT_L @@ -4250,19 +4250,17 @@ %7D%0A %7D%0A - %0A + func @@ -4712,16 +4712,16 @@ %7D;%0A - @@ -4738,16 +4738,23 @@ p.fetch( +CONFIG. SLACK_UR
31baebc9cf2cab77359a1c94eeb7c036da56048c
add test case
test/test.js
test/test.js
var fs = require('fs'), path = require('path'), ADODB = require('../index'), expect = require('expect.js'); var source = path.join(__dirname, 'node-adodb.mdb'), mdb = fs.readFileSync(path.join(__dirname, '../examples/node-adodb.mdb')); fs.writeFileSync(source, mdb); // Variable declaration var adodb = path.join(__dirname, 'adodb.js'), sysroot = process.env['systemroot'] || process.env['windir'], x64 = fs.existsSync(path.join(sysroot, 'SysWOW64')), cscript = path.join(sysroot, x64 ? 'SysWOW64' : 'System32', 'cscript.exe'); console.log(cscript); console.log(adodb); describe('ADODB', function (){ // Variable declaration var connection = ADODB.open('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + source + ';'); it('execute', function (next){ connection .execute('INSERT INTO Users(UserName, UserSex, UserAge) VALUES ("Nuintun", "Male", 25)') .on('done', function (data){ expect(data).to.eql({ valid: true, message: 'Execute SQL: INSERT INTO Users(UserName, UserSex, UserAge) VALUES ("Nuintun", "Male", 25) success !' }); next(); }).on('fail', function (error){ expect(error).to.have.key('valid'); next(); }); }); it('executeScalar', function (next){ connection .executeScalar('INSERT INTO Users(UserName, UserSex, UserAge) VALUES ("Alice", "Female", 25)', 'SELECT @@Identity AS id') .on('done', function (data){ expect(data).to.eql({ valid: true, message: 'Execute Scalar SQL: INSERT INTO Users(UserName, UserSex, UserAge) VALUES ("Alice", "Female", 25) / SELECT @@Identity AS id success !', records: [{ id: 5 }] }); next(); }).on('fail', function (error){ expect(error).to.have.key('valid'); next(); }); }); it('query', function (next){ connection .query('SELECT * FROM Users') .on('done', function (data){ expect(data).to.eql({ valid: true, message: 'Execute SQL: SELECT * FROM Users success !', records: [ { UserId: 1, UserName: "Nuintun", UserSex: "Male", UserAge: 25 }, { UserId: 2, UserName: "Angela", UserSex: "Female", UserAge: 23 }, { UserId: 3, UserName: "Newton", UserSex: "Male", UserAge: 25 }, { UserId: 4, UserName: "Nuintun", UserSex: "Male", UserAge: 25 }, { UserId: 5, UserName: "Alice", UserSex: "Female", UserAge: 25 } ] }); next(); }).on('fail', function (error){ expect(error).to.have.key('valid'); next(); }); }); });
JavaScript
0.000059
@@ -580,16 +580,53 @@ (adodb); +%0Aconsole.log(fs.existsSync(cscript)); %0A%0Adescri
8bf399b30fa6356be49cc6afa856ede24fc7d1da
set priority on subscription item (#43)
js/src/forum/addSubscriptionControls.js
js/src/forum/addSubscriptionControls.js
import { extend } from 'flarum/extend'; import Button from 'flarum/components/Button'; import DiscussionPage from 'flarum/components/DiscussionPage'; import DiscussionControls from 'flarum/utils/DiscussionControls'; import SubscriptionMenu from './components/SubscriptionMenu'; export default function addSubscriptionControls() { extend(DiscussionControls, 'userControls', function(items, discussion, context) { if (app.session.user && !(context instanceof DiscussionPage)) { const states = { none: {label: app.translator.trans('flarum-subscriptions.forum.discussion_controls.follow_button'), icon: 'fas fa-star', save: 'follow'}, follow: {label: app.translator.trans('flarum-subscriptions.forum.discussion_controls.unfollow_button'), icon: 'far fa-star', save: null}, ignore: {label: app.translator.trans('flarum-subscriptions.forum.discussion_controls.unignore_button'), icon: 'fas fa-eye', save: null} }; const subscription = discussion.subscription() || 'none'; items.add('subscription', Button.component({ icon: states[subscription].icon, onclick: discussion.save.bind(discussion, {subscription: states[subscription].save}) }, states[subscription].label)); } }); extend(DiscussionPage.prototype, 'sidebarItems', function(items) { if (app.session.user) { const discussion = this.discussion; items.add('subscription', SubscriptionMenu.component({discussion})); } }); }
JavaScript
0
@@ -1460,16 +1460,20 @@ ussion%7D) +, 80 );%0A %7D
ec9b160d1b203acb6e4dcd3926ecf8dd4a63b395
Test fire return value.
test/test.js
test/test.js
describe('delegated event listeners', function() { describe('firing custom events', function() { it('fires custom events with detail', function(done) { const observer = function(event) { document.removeEventListener('test:event', observer); assert(event.bubbles); assert(event.cancelable); assert.equal(event.type, 'test:event'); assert.deepEqual(event.detail, {id: 42, login: 'hubot'}); assert.strictEqual(document.body, event.target); assert.instanceOf(event, CustomEvent); done(); }; document.addEventListener('test:event', observer); $.fire(document.body, 'test:event', {id: 42, login: 'hubot'}); }); it('fires custom events without detail', function(done) { const observer = function(event) { document.removeEventListener('test:event', observer); assert.isUndefined(event.detail); assert.instanceOf(event, CustomEvent); done(); }; document.addEventListener('test:event', observer); $.fire(document.body, 'test:event'); }); }); describe('registering event observers', function() { it('observes custom events', function(done) { const observer = function(event) { $.off('test:event', '*', observer); assert(event.bubbles); assert(event.cancelable); assert.equal(event.type, 'test:event'); assert.deepEqual({id: 42, login: 'hubot'}, event.detail); assert.strictEqual(document.body, event.target); assert.strictEqual(document.body, this); assert.instanceOf(event, CustomEvent); done(); }; $.on('test:event', '*', observer); $.fire(document.body, 'test:event', {id: 42, login: 'hubot'}); }); it('removes event observers', function() { const observer = function() { assert.fail(); }; $.on('test:event', '*', observer); $.off('test:event', '*', observer); $.fire(document.body, 'test:event'); }); }); describe('event propagation', function() { before(function() { this.parent = document.querySelector('.js-test-parent'); this.child = document.querySelector('.js-test-child'); }); it('fires observers in tree order', function() { const order = []; const parent = this.parent; const one = function(event) { assert.strictEqual(this, parent); order.push(1); }; const child = this.child; const two = function(event) { assert.strictEqual(this, child); order.push(2); }; $.on('test:event', '.js-test-parent', one); $.on('test:event', '.js-test-child', two); $.fire(this.child, 'test:event'); $.off('test:event', '.js-test-parent', one); $.off('test:event', '.js-test-child', two); assert.deepEqual([2, 1], order); }); it('stops propagation bubbling to parent', function() { const one = function(event) { assert.fail(); }; const two = function(event) { event.stopPropagation(); }; $.on('test:event', '.js-test-parent', one); $.on('test:event', '.js-test-child', two); $.fire(this.child, 'test:event'); $.off('test:event', '.js-test-parent', one); $.off('test:event', '.js-test-child', two); }); it('stops immediate propagation', function() { const one = function(event) { event.stopImmediatePropagation(); }; const two = function(event) { assert.fail(); }; $.on('test:event', '.js-test-child', one); $.on('test:event', '.js-test-child', two); $.fire(this.child, 'test:event'); $.off('test:event', '.js-test-child', one); $.off('test:event', '.js-test-child', two); }); it('stops immediate propagation but not bubbling', function(done) { const one = function(event) { assert.ok(event); done(); }; const two = function(event) { event.stopImmediatePropagation(); }; $.on('test:event', '.js-test-parent', one); $.on('test:event', '.js-test-child', two); $.fire(this.child, 'test:event'); $.off('test:event', '.js-test-parent', one); $.off('test:event', '.js-test-child', two); }); }); });
JavaScript
0
@@ -1075,32 +1075,638 @@ event');%0A %7D); +%0A%0A it('returns canceled when default prevented', function() %7B%0A const observer = function(event) %7B event.preventDefault(); %7D;%0A document.addEventListener('test:event', observer);%0A const canceled = !$.fire(document.body, 'test:event');%0A assert.equal(canceled, true);%0A %7D);%0A%0A it('returns not canceled when default is not prevented', function(done) %7B%0A const observer = function(event) %7B assert.ok(event); done(); %7D;%0A document.addEventListener('test:event', observer);%0A const canceled = !$.fire(document.body, 'test:event');%0A assert.equal(canceled, false);%0A %7D); %0A %7D);%0A%0A descri
7e846a6df5937da22d13fe0489c947639a5d0f6e
Update appsngen-cli-login.js
commands/appsngen-cli-login.js
commands/appsngen-cli-login.js
var readlineSync = require('readline-sync'); var request = require('request'); var jsonfile = require('jsonfile'); var path = require('path'); var authcontroller = require('./../src/authcontroller'); var config = require('./../cli-config'); authcontroller.authorize() .then(function (response) { var config; var configFilePath = path.join(__dirname, '/../cli-config.json'); if (response.statusCode === 201) { config = jsonfile.readFileSync(configFilePath); config.credentials = response.body; config.credentials.received = Date.now(); jsonfile.writeFileSync(configFilePath, config, { spaces: 4 }); console.log('Authorization completed successfully.'); } else { console.log(response.body.message); console.log('Unexpected response: ' + response.statusCode); process.exit(1); } }) .catch(function(error) { console.log('catcher catch'); console.error(error); process.exit(1); });
JavaScript
0.000001
@@ -1,83 +1,4 @@ -var readlineSync = require('readline-sync');%0Avar request = require('request');%0A var @@ -992,12 +992,13 @@ (1);%0A %7D); +%0A
6bf5216c9a45f9c4143e16c821c0920a009f7a55
remove TODO comment
test/test.js
test/test.js
var should = require('should'); var request = require('request'); var utils = require('./utils'); var Couch = require('../lib/couch.js'); var testPort = 12500; var dbName = 'ws_mocks'; var dbConfig = {pathname: dbName}; var serverConfig = {db: dbName, port: testPort}; var newId = ''; // TODO maybe move this to 'before' script // before script must create couch db and maybe create some new docs there // after script must remove couchdb // all test must be independent (don't use results of previous test in next one!) var Graft = require('graftjs/server'); require('graftjs/middleware/REST.graft.js'); require('../middleware/CouchDB.graft.js'); Graft.load(__dirname); Graft.start(serverConfig); function cleanup(done) { this.dbDel(function(err) { done(); }); } // Install and destroy database. // ----------------------------- describe('install', function() { var db = new Couch(dbConfig); before(cleanup.bind(db)); after(cleanup.bind(db)); it('should install the database', function(done) { utils.install(dbConfig, done); }); it('check that database exists', function(done) { db.get('_design/backbone', function(err, doc) { if (err) throw err; should.ok(doc._rev); should.ok(doc.language); should.ok(doc.views); should.ok(doc.rewrites); done(); }); }); it('should delete the database', function(done) { db.dbDel(done); }); it('check that database does not exist anymore', function(done) { db.get('_design/backbone', function(err, doc) { should.deepEqual(err.error, 'not_found'); done(); }); }); }); describe('Reading model', function() { describe('Install DB', function() { var db = new Couch(dbConfig); before(cleanup.bind(db)); it('should install the database', function(done) { utils.install(dbConfig, done); }); }); describe('POST /api/Mock', function() { var doc = { "id": 'one', "someVal": "Ronald McDonald", // was "Emily Baker" "favColor": "yello" // new field }; before(utils.requestUrl(testPort, '/api/Mock', 'POST', doc)); // This is for the new location the server told us to go. var newLocation = ''; it ('should have a location', function() { this.resp.should.have.header('Location'); }); it ('should return status 303', function() { this.resp.should.have.status(303); }); it('response should be json', function() { this.resp.should.be.json; }); it ('should have a body', function() { should.exist(this.body); }); }); describe('GET /api/Mock/one', function() { before(utils.requestUrl(testPort, '/api/Mock/one')); it ('should return status 200', function() { this.resp.should.have.status(200); }); it('response should be json', function() { this.resp.should.be.json; }); it ('should have a body', function() { should.exist(this.body); }); it('should have the correct id', function() { this.body.should.have.property('id', 'one'); }); it ('should respect the default values', function() { this.body.should.have.property('name', 'name'); }); }); describe('destroy DB', function() { var db = new Couch(dbConfig); it('should delete the database', function(done) { db.dbDel(done); }); }); }); // describe('Reading model', function() { // describe('GET /api/Mock/one', function() { // before(utils.requestUrl(testPort, '/api/Mock/one')); // it ('should return status 200', function() { // this.resp.should.have.status(200); // }); // it('response should be json', function() { // this.resp.should.be.json; // }); // it ('should have a body', function() { // should.exist(this.body); // }); // it('should have the correct id', function() { // this.body.should.have.property('id', 'one'); // }); // it ('should respect the default values', function() { // this.body.should.have.property('name', 'name'); // }); // }); // });
JavaScript
0
@@ -283,244 +283,8 @@ ';%0A%0A -// TODO maybe move this to 'before' script%0A// before script must create couch db and maybe create some new docs there%0A// after script must remove couchdb%0A// all test must be independent (don't use results of previous test in next one!)%0A var
5944345ef69a5b340f28abe41cbe07e176291ff8
Rename test description
test/client/scripts/arcademode/actions/test.spec.js
test/client/scripts/arcademode/actions/test.spec.js
// // 'use strict'; // // export const OUTPUT_CHANGED = 'OUTPUT_CHANGED'; // export const TESTS_STARTED = 'TESTS_STARTED'; // export const TESTS_FINISHED = 'TESTS_FINISHED'; // // // export function onOutputChange(newOutput) { // return { // type: OUTPUT_CHANGED, // userOutput: newOutput // }; // } // // /* Thunk action which runs the test cases against user code. */ // export function runTests(userCode, currChallenge) { // return dispatch => { // dispatch(actionTestsStarted()); // // // Eval user code inside worker // // http://stackoverflow.com/questions/9020116/is-it-possible-to-restrict-the-scope-of-a-javascript-function/36255766#36255766 // function createWorker () { // return new Promise((resolve, reject) => { // const wk = new Worker('../../public/js/worker.bundle.js'); // wk.postMessage([userCode, currChallenge]); // wk.onmessage = e => { // console.log(`worker onmessage result: ${e.data}`); // resolve(e.data); // }; // }); // } // // createWorker() // .then(workerData => { // dispatch(onOutputChange(workerData[0].output)); // if (workerData.length > 1) { // dispatch(actionTestsFinished(workerData.slice(1))); // } // }); // }; // } // // /* Dispatched when a user starts running the tests.*/ // export function actionTestsStarted () { // return { // type: TESTS_STARTED // }; // } // // /* Dispatched when the tests finish. */ // export function actionTestsFinished (testResults) { // return { // type: TESTS_FINISHED, // testResults // }; // } /* Unit tests for file client/scripts/arcademode/actions/test.js. */ import { expect } from 'chai'; import sinon from 'sinon'; import { OUTPUT_CHANGED, TESTS_STARTED, TESTS_FINISHED, onOutputChange, runTests, actionTestsStarted, actionTestsFinished } from '../../../../..//client/scripts/arcademode/actions/test'; describe('test actions', () => { it('should dispatch an action on runTests', () => { const dispatch = sinon.spy(); const action = runTests(); action(dispatch).then(() => { expect(dispatch.called).to.be.true; }); }); it('should return correct type for actionTestsStarted', () => { expect(actionTestsStarted().type).to.equal(TESTS_STARTED); }); it('should return correct type for actionTestsFinished()', () => { expect(actionTestsFinished().type).to.equal(TESTS_FINISHED); }); it('should return correct type for onOutputChange()', () => { expect(onOutputChange().type).to.equal(OUTPUT_CHANGED); }); });
JavaScript
0.000018
@@ -1980,20 +1980,21 @@ be(' -test actions +Actions: test ', (
191b60b3f66f3b2cf10f12ebfa358155cac7b5a2
add test for movie/xxxx/dislike route
test/test.js
test/test.js
process.env.NODE_ENV = 'test'; const mongoose = require('mongoose'); let chai = require('chai'); let chaiHttp = require('chai-http'); const server = 'https://private-77bd5f-spotamovie.apiary-mock.com'; let should = chai.should(); chai.use(chaiHttp); describe('Movies', () => { // Test Login describe('/login POST user', () => { it('it should allow user to login using Spotify credentials', (done) => { chai.request(server) .post('/login') .field('code', 'auth_code_3838383838383') .field('redirect_uri','spotamovie://callback') .end((err, res) => { res.should.have.status(200); res.body.should.be.a('object'); res.body.should.have.property('userToken'); done(); }); }); }); describe('/movies/{movie_id}/like POST like', () => { it('it should allow posting an item liked by a particular user', (done) => { const movie_id = 'TESTxxxxxxxx'; chai.request(server) .post(`/movies/${movie_id}/like`) .field('token', '2j3j3k3kl2lk34j2lsois') .end((err, res) => { res.should.have.status(201); done(); }); }); }); });
JavaScript
0.000162
@@ -196,16 +196,59 @@ k.com';%0A +const token = 'test2j3j3k3kl2lk34j2lsois';%0A let shou @@ -1089,31 +1089,421 @@ n', -'2j3j3k3kl2lk34j2lsois' +token)%0A .end((err, res) =%3E %7B%0A res.should.have.status(201);%0A done();%0A %7D);%0A %7D);%0A %7D);%0A%0A describe('/movies/%7Bmovie_id%7D/dislike POST dislike', (movie_id) =%3E %7B%0A it('it should allow posting an item disliked by a particular user', (done) =%3E %7B%0A const movie_id = 'TESTyyyyyyyy';%0A chai.request(server)%0A .post(%60/movies/$%7Bmovie_id%7D/dislike%60)%0A .field('token', token )%0A
a26ab2eb282343cba3effc4bf21a54519e8e3c65
Add the expected test spec file to the module test.
test/test.js
test/test.js
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var helpers = require('yeoman-generator').test; var assert = require('assert'); var expected = [ // Project files '.jshintrc', '.editorconfig', '.htaccess', // Bower '.bowerrc', 'bower.json', // Pkg 'package.json', // Git '.gitattributes', '.gitignore', // Travis '.travis.yml', // Robots 'robots.txt', // HTML 'templates/header.html', 'templates/index.html', 'templates/footer.html', 'pages.json', // Karma 'karma.conf.js', // Humans 'humans.txt', // Grunt 'Gruntfile.js', 'tasks/config.js', 'tasks/options/clean.js', 'tasks/options/concat.js', 'tasks/options/connect.js', 'tasks/options/copy.js', 'tasks/options/imagemin.js', 'tasks/options/jshint.js', 'tasks/options/karma.js', 'tasks/options/modernizr.js', 'tasks/options/replace.js', 'tasks/options/requirejs.js', 'tasks/options/sass.js', 'tasks/options/watch.js', // Javascript 'js/modules/module.js', 'js/plugins/console.js', 'js/config.js', 'js/main.js', // Authors 'AUTHORS', // Ico 'apple-touch-icon-precomposed.png', 'favicon.ico', // Contribuiting 'CONTRIBUTING.md', // Cossdomain 'crossdomain.xml', // 404 '404.html', // Test 'test/specs/example.spec.js', 'test/spec.js', 'test/test-main.js' ]; // ---- Main generator describe('main generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('init:app', [ '../../app' ]); done(); }.bind(this)); }); it('the generator can be required without throwing', function () { // not testing the actual run of generators yet var app = require('../app'); assert(app !== undefined); }); it('creates expected files for SCSS preprocessor', function (done) { helpers.mockPrompt(this.app, { 'cssPreprocessor': 'Compass' }); var expectedSCSS = [ 'scss/main.scss', 'scss/elements/_typography.scss', 'scss/helpers/_helpers.scss', 'scss/helpers/_variables.scss', 'scss/media/_print.scss', 'scss/modules/_box.scss', 'scss/page/_base.scss', 'scss/page/_footer.scss', 'scss/page/_header.scss', 'scss/page/_main.scss' ]; expectedSCSS.concat(expectedSCSS, expected); this.app.options['skip-install'] = true; this.app.run({}, function () { helpers.assertFiles(expectedSCSS); done(); }); }); it('creates expected files for LESS preprocessor', function (done) { helpers.mockPrompt(this.app, { 'cssPreprocessor': 'LESS' }); var expectedLESS = [ 'less/main.less', 'less/elements/_typography.less', 'less/helpers/_helpers.less', 'less/helpers/_variables.less', 'less/media/_print.less', 'less/modules/_box.less', 'less/page/_base.less', 'less/page/_footer.less', 'less/page/_header.less', 'less/page/_main.less' ]; expectedLESS.concat(expectedLESS, expected); this.app.options['skip-install'] = true; this.app.run({}, function () { helpers.assertFiles(expectedLESS); done(); }); }); }); // ---- Page sub-generator describe('page sub-generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('init:page', [ '../../page' ], ['test-page']); done(); }.bind(this)); }); it('creates expected files for the page sub-generator', function (done) { var expected = [ 'templates/test-page.html' ]; this.app.options['skip-install'] = true; this.app.run({}, function () { helpers.assertFiles(expected); done(); }); }); }); // ---- Module sub-generator describe('module sub-generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('init:module', [ '../../module' ], ['test']); done(); }.bind(this)); }); it('creates expected files for the module sub-generator', function (done) { var expected = [ 'js/modules/test.js' ]; this.app.options['skip-install'] = true; this.app.run({}, function () { helpers.assertFiles(expected); done(); }); }); }); // ---- Jqueryplugin sub-generator describe('jqueryplugin sub-generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('init:jqueryplugin', [ '../../jqueryplugin' ], ['test']); done(); }.bind(this)); }); it('creates expected files for the jqueryplugin sub-generator', function (done) { var expected = [ 'js/plugins/jquery.test.js' ]; this.app.options['skip-install'] = true; this.app.run({}, function () { helpers.assertFiles(expected); done(); }); }); });
JavaScript
0
@@ -4485,32 +4485,65 @@ modules/test.js' +,%0A 'test/specs/test.spec.js' %0A %5D;%0A%0A thi
49a92c39064ba085e8f9eaea53ee5fbfa873d328
load log
static/js/angular-app.js
static/js/angular-app.js
var app = angular.module('PIR', ['ui.grid', 'ui.grid.edit', 'ui.grid.cellNav', 'ngRoute', 'chart.js', 'ngResource']); var sort_by = function(field, reverse, primer){ var key = primer ? function(x) {return primer(x[field])} : function(x) {return x[field]}; reverse = !reverse ? 1 : -1; return function (a, b) { return a = key(a), b = key(b), reverse * ((a > b) - (b > a)); } }; ['User', 'ReportClass', 'VariableCat_1', 'VariableCat_2', 'VariableCat_3', 'VariableDef', 'vVariableDef'] .forEach((urlobject)=>{ app.factory(urlobject, ['$resource', function($resource) { return $resource(`/restful/${urlobject}/:where/:value`, {}, { get: {method: 'GET', cache: false, isArray: false}, query: {method:'GET', isArray:true, transformResponse: function (data) { return angular.fromJson(data); }, }, save: {method: 'POST', cache: false, isArray: false}, update: {method: 'PUT', cache: false, isArray: false}, delete: {method: 'DELETE', cache: false, isArray: false} }); }] ); }); ['Log'] .forEach((urlobject)=>{ app.factory(urlobject, ['$resource', function($resource) { return $resource(`/restful/${urlobject}/:where`, {}, { 'get': {method:'GET'}, //'save': {method:'POST'}, //'query': {method:'GET', isArray:true}, //'remove': {method:'DELETE'}, //'delete': {method:'DELETE'} }); }] ); }); //controllers for resources ['Log', 'User', 'ReportClass', 'VariableCat_1', 'VariableCat_2', 'VariableCat_3', 'VariableDef', 'vVariableDef'] .forEach((urlobject)=>{ app.controller(urlobject + 'Controller',['$scope', urlobject, function ($scope, resource) { const newitem = -2; $scope.init = function(handler) { handler(); $scope.$on('eventUpdateSelected', handler); }; $scope.get = function (where) { //console.log(where); var res = resource.get(where, function() { $scope.load(res); }); }; $scope.getlatestselectedhandler = function() { var _where = (urlobject === 'Log') ? $scope.getlatestselected('User') : $scope.getlatestselected(urlobject); if (_where >= 0) { var res = resource.get({where: _where}, function() { if(urlobject === 'Log') { $scope.log = ''; res.data.forEach((item)=>{$scope.log += item.message + " @ " + item.timestamp + "\n"}); } else { //$scope.data = [res]; //console.log(res); $scope.load(res); }; }); } } $scope.query = function (where, callback) { if(urlobject!=='Log') { $scope.registerSelected(urlobject); var res = resource.query(where, function(data) { if (urlobject !== 'User') { $scope.data = res.sort(sort_by('code')); } else { $scope.data = res.sort(sort_by('lname')); } if (callback !== undefined) { callback($scope.data); } /* if ($scope.getlatestselected(urlobject) > -1) { var i = 0; while(data[i++].id !== $scope.getlatestselected(urlobject)); $scope.load(data[i-1]); } */ }); }; }; $scope.isSelected = function (id) { return $scope.selectedHas(urlobject, id); }; $scope.selectitem = function (id) { $scope.updateSelected(urlobject, id); }; $scope.load = function (item) { $scope.item = item; /* for (key in item) { if (item.hasOwnProperty(key)){ $scope[key] = item[key]; } } */ }; $scope.addnew = function () { $scope.updateSelected(urlobject, newitem); } }]); }); app.controller('selectController', function ($scope) { var selected = {}; $scope.registerSelected = function(key) { if (!(key in selected)) { selected[key] = new Set(); } } $scope.updateSelected = function(key, value) { if (selected[key].has(value)) { selected[key].delete(value); } else { selected[key].add(value); } /* for (key_ in callbacks) { callbacks[key_](); } */ $scope.$broadcast("eventUpdateSelected", {key: key, value: value}); } $scope.selectedHas = function(key, value) { return selected[key].has(value); } $scope.selectedIsEmpty = function(key) { return (selected[key].size === 0) } $scope.getlatestselected = (key) => { return ((key in selected) && selected[key].size>0) ? [...selected[key]][selected[key].size-1] : -1; }; $scope.filter = function (item) { var show = true; var hasrelation = false; for (key in selected) { var _key = key.toLowerCase() + '_id'; if (_key !== 'user_id') { if (!item.hasOwnProperty(_key)) { continue; } hasrelation = true; show = show && (($scope.selectedIsEmpty(key)) || $scope.selectedHas(key, item[_key])); } else { for (many in item) { if (many.substring(0, 5) === 'user_') { hasrelation = true; show = show && (($scope.selectedIsEmpty(key)) || $scope.selectedHas(key, item[many])); } } } } return !hasrelation || show; }; }); app.controller('scopeUpdater', function ($scope) { $scope.setVar = function (varName, x) { $scope[varName] = x; } }); app.directive("searchresult", function() { return { link: function(scope, el, attrs) { if(scope.results === undefined) { scope.results = {}; } scope.results[attrs.searchQuery] = [ { text: attrs.searchQuery }, { text: attrs.searchQuery } ] } }; });
JavaScript
0.000001
@@ -2556,24 +2556,71 @@ $scope. +item = %7B%7D;%0A $scope.item. log = '';%0A @@ -2674,16 +2674,21 @@ %7B$scope. +item. log += i
753b9480e2d0140ef6387282dd5fdb44610af897
Fix #23 pull message is not correct for tag
static/js/controllers.js
static/js/controllers.js
'use strict'; /* Use JQuery.gritter to popup success message */ function alert_success(message) { $.gritter.add({ title: 'Success!', text: message, image: 'static/img/pirate-logo.png', time: 3000 }); } /* Use JQuery.gritter to popup error message */ function alert_error(message) { $.gritter.add({ title: 'Error!', text: message, image: 'static/img/pirate-logo.png', time: 3000 }); } /* All angular application controllers */ var seagullControllers = angular.module('seagullControllers', []); /* This controller to get comment from beego api */ seagullControllers.controller('HomeController', ['$scope', '$routeParams', 'dockerService', function ($scope, $routeParams, dockerService) { /* Get the version object */ dockerService.getVersion().then(function (version) { $scope.version = version; $scope.Os = version.Os; $scope.KernelVersion = version.KernelVersion; $scope.GoVersion = version.GoVersion; $scope.Version = version.Version; }); /* Get the info object */ dockerService.getInfo().then(function (info) { $scope.info = info; $scope.Containers = info.Containers; $scope.Images = info.Images; }); }]); /* Images controller requests beego API server to get/delete images */ seagullControllers.controller('ImagesController', ['$scope', '$routeParams', '$http', 'dockerService', '$modal', function ($scope, $routeParams, $http, dockerService, $modal) { dockerService.getVersion().then(function (version) { $scope.version = version; dockerService.getImages().then(function (images) { $scope.images = images; }); }); $scope.pullImage = function (image) { if ($scope.version) { $scope.pullUrl = $scope.version.PirateUrlAlias + "/" + image.Name + "/" + image.Tag; var modalInstance = $modal.open({ templateUrl: '/static/html/modal.html', controller: 'ModalController', resolve: { pullUrl: function () { return $scope.pullUrl; } } }); modalInstance.result.then(function () { }, function () { }); } }; $scope.deleteImage = function (image) { var id = image.Id.substring(0, 12); dockerService.deleteImage(image).then(function (data) { alert_success("Delete image " + id); dockerService.getImages().then(function (images) { $scope.images = images; }); }, function (reason) { alert_error("Delete image " + id); }); }; $scope.isReadonly = function () { if ($scope.version && $scope.version.PirateMode !== 'readonly') { return false; } return true; } }]); /* * Modal controller */ seagullControllers.controller('ModalController', [ '$scope', '$modalInstance', 'pullUrl', function ($scope, $modalInstance, pullUrl) { $scope.pullCmd = "docker pull " + pullUrl; $scope.close = function () { $modalInstance.close(); } }]); /* * Image controller requests beego API server to get image */ seagullControllers.controller('ImageController', ['$scope', '$routeParams', 'dockerService', function ($scope, $routeParams, dockerService) { function getImageInfo(image) { dockerService.getImageInfo(image.id).then(function (info) { $scope.mdInfo = info.Comment; }); } if (typeof $routeParams.id === 'undefined' || $routeParams.id == null) { dockerService.getImageByUserAndRepo($routeParams.user, $routeParams.repo).then(function (image) { $scope.image = image; getImageInfo(image); }); } else { dockerService.getImageById($routeParams.id).then(function (image) { $scope.image = image; getImageInfo(image); }); } }]); /* Contaienrs controller requests beego API server to get configuration */ seagullControllers.controller('ConfigurationController', ['$scope', '$routeParams', 'dockerService', function ($scope, $routeParams, dockerService) { dockerService.getVersion().then(function (version) { $scope.version = version; }); dockerService.getInfo().then(function (info) { $scope.info = info; }); }]); /* Dockerhub controller requests beego API server to get search images */ seagullControllers.controller('DockerhubController', ['$scope', '$routeParams', 'dockerService', function ($scope, $routeParams, dockerService) { /* Display the loading icon before get search images */ $scope.isSearching = true; /* Request beego API server to get search images, default is seagull */ dockerService.searchImages('seagull').then(function (images) { $scope.isSearching = false; $scope.images = images; }); /* Request beego API server to get search images */ $scope.getSearchImages = function (term) { $scope.isSearching = true; dockerService.searchImages(term).then(function (images) { $scope.isSearching = false; $scope.images = images; alert_success("Search images of " + term); }, function (reason) { $scope.isSearching = false; alert_error("Search images of " + term); }); }; /* Generate the image link by judging it's official images or not */ $scope.getImageLink = function (name) { var address; if (name.indexOf('/') === -1) { // Example: https://registry.hub.docker.com/_/golang address = "https://registry.hub.docker.com/_/" + name; } else { // Example: https://registry.hub.docker.com/u/tobegit3hub/seagull address = "https://registry.hub.docker.com/u/" + name; } return address; }; }]);
JavaScript
0
@@ -1985,25 +1985,25 @@ age.Name + %22 -/ +: %22 + image.Ta
b1d35443c4b5d41e05ce06f8f3c45e3224472719
Fix require path
lib/node_modules/@stdlib/datasets/savoy-stopwords-fr/benchmark/benchmark.non_browser.js
lib/node_modules/@stdlib/datasets/savoy-stopwords-fr/benchmark/benchmark.non_browser.js
'use strict'; // MODULES // var bench = require( '@stdlib/bench' ); var pkg = require( './../package.json' ).name; var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; var stopwords = require( './../lib/savoy_stopwords_fin.js' ); // MAIN // bench( pkg+'::non_browser', function benchmark( b ) { var data; var i; b.tic(); for ( i = 0; i < b.iterations; i++ ) { data = stopwords(); if ( data.length === 0 ) { b.fail( 'should have a length greater than 0' ); } } b.toc(); if ( !isStringArray( data ) ) { b.fail( 'should return a string array' ); } b.pass( 'benchmark finished' ); b.end(); });
JavaScript
0.000003
@@ -238,18 +238,17 @@ pwords_f -in +r .js' );%0A
c73550b4829d97d8d5fc7d2503a58a5ce471b375
Remove console.log
test/tile.js
test/tile.js
import { should } from "chai"; import { Tile } from "../src"; should(); /** @test {Tile} */ describe("Tile", () => { /** @test {Tile#constructor} */ describe("#constructor", () => { it("creates from objects", () => { let tile = new Tile({ tileId: 56, tilesetId: 1 }); tile.tileId.should.equal(56); tile.tilesetId.should.equal(1); }); it("creates from strings", () => { let tile = new Tile("224:5"); tile.tileId.should.equal(224); tile.tilesetId.should.equal(5); }); it("has empty default values", () => { const tile = new Tile(); tile.tilesetId.should.equal(-1); tile.tilesetId.should.equal(-1); }); }); /** @test {Tile#emitEvents} */ describe("#emitEvents", () => { it("starts fowarding data events when set", done => { const tile = new Tile(); tile.emitEvents = true; tile.on("data-change", () => { done(); }); tile.setData(0, 0); }); it("starts fowarding property events when set", done => { const tile = new Tile(); tile.emitEvents = true; tile.on("property-change", () => { console.log("hi"); done(); }); tile.properties.set("is", "something"); }); it("doesn't forward anything when not set", () => { const tile = new Tile(); tile.emitEvents = true; tile.emitEvents = false; tile.on("data-change", () => { throw new Error(); }); tile.on("property-change", () => { throw new Error(); }); tile.setData(0, 0); tile.properties.set("is", "something"); }); }); /** @test {Tile#setData} */ describe("#setData", () => { let tile; beforeEach(() => { tile = new Tile("10:8"); }); it("can replace only tile ID", () => { tile.setData(15); tile.tileId.should.equal(15); tile.tilesetId.should.equal(8); }); it("can replace both tile ID and tileset ID", () => { tile.setData(84, 2); tile.tileId.should.equal(84); tile.tilesetId.should.equal(2); }); it("doesn't replace if ID is -1", () => { tile.setData(-1, -1); tile.tileId.should.equal(10); tile.tilesetId.should.equal(8); }); it("does replace empty if told so", () => { tile.setData(-1, -1, true); tile.tileId.should.equal(-1); tile.tilesetId.should.equal(-1); }); }); /** @test {Tile#toJSON} */ describe("#toJSON", () => { it("stringifies with properties", () => { let tile = new Tile({ tileId: 14, tilesetId: 3, properties: [ ["property", "is a string"] ] }); JSON.stringify(tile).should.contain("[\"property\",\"is a string\"]"); }); it("stringifies without properties", () => { let tile = new Tile("456:3"); JSON.stringify(tile).should.equal("\"456:3\""); }); }); /** @test {Tile#clone} */ describe("#clone", () => { let tile; beforeEach(() => { tile = new Tile({ tileId: 14, tilesetId: 3, properties: [ ["property", "is a string"] ] }); }); it("clones all the properties of a tile", () => { tile.clone().should.deep.equal(tile); }); it("doesn't become the same tile", () => { tile.clone().should.not.equal(tile); }); }); });
JavaScript
0.000004
@@ -1069,31 +1069,8 @@ %3E %7B%0A -%09%09%09%09console.log(%22hi%22);%0A %09%09%09%09
365a5dcbf3f89dcb41b89d34752be0816b48d5a8
Update error code for test based on updated controller value for User
test/integration/controllers/UserController.test.js
test/integration/controllers/UserController.test.js
var request = require('supertest'); describe('UserController', function () { var credentials = { username: 'user', password: 'testtesttest', email: '[email protected]'}; var existingEmailCredentials = { username: 'test1', password: 'gg', email: '[email protected]'}; var existingUsernameCredentials = { username: 'test', password: 'testtesttest', email: '[email protected]'}; var vid1 = {title: 'Mission Impossible', thumbnailDir: '/video/1/a.jpg'}; var vid2 = {title: 'Mission Possible', thumbnailDir: '/video/1/a.jpg'}; describe('#signup', function () { var agent = request.agent('http://localhost:1337'); it('should be able to signup for a new account', function (done) { request(sails.hooks.http.app) .post('/api/user/signup') .send(credentials) .expect(200, done); }); it('should not able to signup for a new account using used email address', function (done) { request(sails.hooks.http.app) .post('/api/user/signup') .send(existingEmailCredentials) .expect(409, done); }); it('should not able to signup for a new account using used username', function (done) { request(sails.hooks.http.app) .post('/api/user/signup') .send(existingUsernameCredentials) .expect(400, done); }); }); describe('#login', function () { var agent = request.agent('http://localhost:1337'); it('should be able to login with correct credentials', function (done) { request(sails.hooks.http.app) .post('/api/user/login') .send(credentials) .expect(200, done); }); it('should not be able to login with wrong credentials', function (done) { request(sails.hooks.http.app) .post('/api/user/login') .send(existingEmailCredentials) .expect(404, done); }); }); describe('#logout', function () { var agent = request.agent('http://localhost:1337'); it('should be able to logout after signed in', function (done) { agent .post('/api/user/login') .send(credentials) .expect(200) .end(function (err, res) { if (err) done(err); agent .get('/api/user/logout') .expect(200, done); }); }); it('should be able to logout if not signed in', function (done) { agent .get('/api/user/logout') .expect(200, done); }); }); });
JavaScript
0
@@ -1693,17 +1693,17 @@ xpect(40 -4 +1 , done); @@ -2221,8 +2221,9 @@ %09%7D);%0A%7D); +%0A
eb4d54b1e668a6339f76effe445c74f91bb88bd5
update the geojson map
test/renderer/components/transforms/geojson-spec.js
test/renderer/components/transforms/geojson-spec.js
import React from 'react'; import Immutable from 'immutable'; import { mount } from 'enzyme'; import chai, { expect } from 'chai'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; chai.use(sinonChai); import GeoJSONTransform from '../../../../src/notebook/components/transforms/geojson'; const geojson = Immutable.fromJS({ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "popupContent": "18th & California Light Rail Stop" }, "geometry": { "type": "Point", "coordinates": [-104.98999178409576, 39.74683938093904] } },{ "type": "Feature", "properties": { "popupContent": "20th & Welton Light Rail Stop" }, "geometry": { "type": "Point", "coordinates": [-104.98689115047453, 39.747924136466565] } } ] }); describe('GeoJSONTransform', () => { it('renders a map', () => { const geoComponent = mount( <GeoJSONTransform data={geojson} /> ); expect(geoComponent.instance().shouldComponentUpdate({ theme: 'light', data: geojson, })).to.be.false; expect(geoComponent.find('.leaflet-container')).to.have.length(1); }); });
JavaScript
0.000009
@@ -1312,16 +1312,522 @@ ngth(1); +%0A %7D);%0A%0A it('updates the map', () =%3E %7B%0A const geoComponent = mount(%0A %3CGeoJSONTransform%0A data=%7Bgeojson%7D%0A /%3E%0A );%0A%0A const instance = geoComponent.instance();%0A%0A expect(instance.shouldComponentUpdate(%7B%0A theme: 'light',%0A data: geojson,%0A %7D)).to.be.false;%0A%0A expect(geoComponent.find('.leaflet-container')).to.have.length(1);%0A%0A geoComponent.setProps(%7B%0A data: geojson.setIn(%5B%22features%22, 0, %22properties%22, %22popupContent%22%5D, %22somewhere%22),%0A theme: 'dark',%0A %7D) %0A%0A %7D);%0A
081f2304e6f4022e4b8b6b04a5f9647beef27e6b
resolve glslify dirs correctly
transform.js
transform.js
const format = require('kindred-shader-formatter') const staticModule = require('static-module') const isRequire = require('is-require')() const combine = require('stream-combiner') const through = require('through2') const glslify = require('glslify') const shortid = require('shortid') const falafel = require('falafel') const xtend = require('xtend') const path = require('path') const parseOptions = { ecmaVersion: 6, sourceType: 'module', allowReserved: true, allowReturnOutsideFunction: true, allowHashBang: true } module.exports = transform function transform (filename, opts) { return combine( templateTransform(filename, opts), fileTransform(filename, opts) ) } function templateTransform (filename, transformOpts) { var stream = through(write, flush) var cwd = path.dirname(filename) var buffer = [] return stream function write (chunk, _, next) { buffer.push(chunk) next() } function flush () { var src = buffer.join('') var requires = [] var queue = 0 if (src.indexOf('kindred-shader') === -1) { this.push(src) this.push(null) return } try { src = falafel(src, parseOptions, function (node) { scrapeRequires(node) scrapeTemplates(node) }) } catch (e) { return stream.emit('error', e) } checkQueue() function scrapeRequires (node) { if (!isRequire(node)) return var args = node.arguments if (args.length < 1) return var target = args[0] if (target.type !== 'Literal') return var value = target.value if (value !== 'kindred-shader') return if (node.parent.type !== 'VariableDeclarator') return if (node.parent.id.type !== 'Identifier') return var varName = node.parent.id.name requires.push(varName) } function scrapeTemplates (node) { if (node.type !== 'TaggedTemplateExpression') return if (node.tag.type !== 'Identifier') return if (requires.indexOf(node.tag.name) === -1) return var textBits = node.quasi.quasis var expressions = node.quasi.expressions var replaceMap = [] var combined = [] for (var i = 0; i + 1 < textBits.length; i++) { var mapping = '_' + shortid.generate() var expr = expressions[i].source().trim() replaceMap[expr] = replaceMap[expr] || mapping combined.push(textBits[i].source()) combined.push(mapping) } combined.push(textBits[textBits.length - 1].source()) combined = combined.join('') queue++ glslify.bundle(combined, { cwd: cwd, inline: true }, function (err, source) { if (err) return stream.emit('error', err) var jsReplacement = splitAndFormat(source, replaceMap) node.update(jsReplacement) checkQueue(queue--) }).on('file', function (file) { stream.emit('file', file) }) } function checkQueue () { if (queue) return stream.push(src.toString()) stream.push(null) } } } function fileTransform (filename, transformOpts) { var cwd = path.dirname(filename) var stream = staticModule({ 'kindred-shader': { file: replaceStream, raw: function (vert, frag) { var prefix = '(require("kindred-shader/raw")(' var args = [JSON.stringify(vert), JSON.stringify(frag)] return prefix + args.join(',') + '))' } } }, { vars: { __dirname: cwd, __filename: filename }, varModules: { path: path } }) return stream function replaceStream (glslFile, opts) { var replacer = through() opts = xtend({ basedir: cwd }, transformOpts || {}, opts || {}) glslify.bundle(glslFile, opts, function (err, bundled) { if (err) return stream.emit('error', err) var jsReplacement = splitAndFormat(bundled) replacer.push(jsReplacement) replacer.push(null) }).on('file', function (file) { stream.emit('file', file) }) return replacer } } function splitAndFormat (source, replaceMap) { var vert = JSON.stringify(format.vert(source)) var frag = JSON.stringify(format.frag(source)) var bundled = '' if (replaceMap) { Object.keys(replaceMap).forEach(function (value) { var key = replaceMap[value] vert = vert.replace(new RegExp(key, 'g'), '"+(' + value + ')+"') frag = frag.replace(new RegExp(key, 'g'), '"+(' + value + ')+"') }) } bundled += 'require("kindred-shader/raw")(' bundled += vert bundled += ',' bundled += frag bundled += ')' return bundled }
JavaScript
0.000555
@@ -2609,19 +2609,23 @@ -cwd +basedir : cwd,%0A
e97c56564f018bd5cafaeae0976828f8c913c44f
update test case for single instance with open method in Mac
tests/automatic_tests/single_instance/mocha_test.js
tests/automatic_tests/single_instance/mocha_test.js
var func = require('./' + global.tests_dir +'/start_app/script.js'); var execPath = func.getExecPath(); var fs = require('fs-extra'); var os = require('os'); var spawn = require('child_process').spawn; var exec = require('child_process').exec; var app = new Array(); var child1, child2; var mac_app_path = path.join('tmp-nw', 'node-webkit.app'); function make_execuable_file(folder_path, done) { func.copyExecFiles(function() { func.copySourceFiles(folder_path); func.zipSourceFiles(function() { func.makeExecuableFile(); if (os.platform() == 'darwin') { var app_path = 'tmp-nw/node-webkit.app/Contents/Resources/app.nw'; fs.mkdir(app_path, function(err) { if(err && err.code !== 'EEXIST') throw err fs.copy('tmp-nw/index.html', path.join(app_path, 'index.html')); fs.copy('tmp-nw/package.html', path.join(app_path, 'package.html')); }); } done(); }); }); } function check_have(i, cmd, options, msg, last, done) { var result = false; app[i] = spawn(cmd, options); app[i].on('exit', function() { result = true; }); if (last == 2) { setTimeout(function() { if (result) { done(); } else { done(msg); } app[i].kill(); app[i - 1].kill(); }, 3000); } else { setTimeout(function() { if (result) { done(msg); } else { done(); } if (last == 1) { app[i].kill(); app[i - 1].kill(); } }, 3000); } } describe('single-instance', function() { this.timeout(0); describe('single-instance false', function() { before(function(done) { make_execuable_file('single_instance/mul', done); }); after(function() { fs.remove('tmp-nw', function (er) { if (er) throw er; }); }); it('should have a instance', function(done) { check_have(0, execPath, "", 'not have a instance', 0, done); }); it('should have a second instance', function(done) { check_have(1, execPath, "", 'not have a second instance', 1, done); }); }); describe('single-instance default', function() { before(function(done) { setTimeout(function() { make_execuable_file('single_instance/single', done); }, 3000); }); after(function() { fs.remove('tmp-nw', function (er) { if (er) throw er; }); }); it('should have a instance', function(done) { check_have(2, execPath, "", 'not have a instance', 0, done); }); it('should not have a second instance', function(done) { check_have(3, execPath, "", 'have a second instance', 2, done); }); }); if (os.platform() == 'darwin') { describe('single-instance false(open app)', function(){ before(function(done) { setTimeout(function() { make_execuable_file('single_instance/open_mul', done); }, 3000); }); after(function() { fs.remove('tmp-nw', function (er) { if (er) throw er; }); }); it('should have a instance (open app)', function(done) { child1 = exec('open ' + mac_app_path); setTimeout(function () { var content = fs.readFileSync('tmp-nw/msg'); if (content + "" != "") done(); else done("not have a instance"); }, 6000); }); it('should have a second instance (open app)', function(done) { child2 = exec('open ' + mac_app_path); var content = fs.readFileSync('tmp-nw/msg'); if (content + "" == "11") done(); else done("not have a instance"); }); }); describe('single-instance default(open app)', function(){ before(function(done) { setTimeout(function() { make_execuable_file('single_instance/open_single', done); }, 3000); }); after(function() { fs.remove('tmp-nw', function (er) { if (er) throw er; }); }); it('should have a instance (open app)', function(done) { child1 = exec('open ' + mac_app_path); setTimeout(function () { var content = fs.readFileSync('tmp-nw/msg_s'); if (content + "" != "") done(); else done("not have a instance"); }, 6000); }); it('should not have a second instance (open app)', function(done) { child2 = exec('open ' + mac_app_path); var content = fs.readFileSync('tmp-nw/msg_s'); if (content + "" == "11") done("have a second instance"); else done(); }); }); } });
JavaScript
0
@@ -3707,32 +3707,36 @@ it('should +not have a second in @@ -3979,32 +3979,56 @@ done( +%22have a second instance%22 );%0A @@ -4076,37 +4076,16 @@ done( -%22not have a instance%22 );%0A
8e782956ee8ed7f5249ff7b77f3e427480372595
Make jshint pass again
jquery.cookie.js
jquery.cookie.js
/*! * jQuery Cookie Plugin * https://github.com/carhartl/jquery-cookie * * Copyright 2011, Klaus Hartl * Dual licensed under the MIT or GPL Version 2 licenses. * http://www.opensource.org/licenses/mit-license.php * http://www.opensource.org/licenses/GPL-2.0 */ (function($, document) { $.cookie = function(key, value, options) { // key and at least value given, set cookie... if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value == null)) { options = $.extend({}, $.cookie.defaults, options); if (value == null) { options.expires = -1; } if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } value = String(value); return (document.cookie = [ encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // key and possibly options given, get cookie... options = value || $.cookie.defaults || {}; var decode = options.raw ? function(s) { return s; } : decodeURIComponent; var cookies = document.cookie.split('; '); for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) { if (decode(parts.shift()) === key) { return decode(parts.join('=')); } } return null; }; $.cookie.defaults = {}; })(jQuery, document);
JavaScript
0.000001
@@ -1,8 +1,32 @@ +/*jshint eqnull:true */%0A /*!%0A * j
ade7f9c4364367e6d1026135a0e1025f41228256
Replace |Date.now()| with |(new Date).getTime()| (Opera needs this)
public/js/online.js
public/js/online.js
$(document).ready(function() { var parser; var buildAndParseTimer = null; var parseTimer = null; var oldGrammar = null; var oldParserVar = null; var oldStartRule = null; var oldInput = null; function build() { oldGrammar = $("#grammar").val(); oldParserVar = $("#parser-var").val(); oldStartRule = $("#start-rule").val(); try { var timeBefore = Date.now(); parser = PEG.buildParser($("#grammar").val(), $("#start-rule").val()); var timeAfter = Date.now(); $("#build-message") .attr("class", "message info") .html("Parser built successfully.") .append( "<span class=\"time\" title=\"Parser build time and speed\">" + (timeAfter - timeBefore) + "&nbsp;ms, " + ($("#grammar").val().length / (timeAfter - timeBefore)).toPrecision(2) + "&nbsp;kB/s" + "</span>" ); var parserUrl = "data:text/plain;charset=utf-8;base64," + Base64.encode($("#parser-var").val() + " = " + parser.toSource() + ";\n"); $("#parser-download").show().attr("href", parserUrl); $("#input").removeAttr("disabled"); return true; } catch (e) { var message = e.line !== undefined && e.column !== undefined ? "Line " + e.line + ", column " + e.column + ": " + e.message : e.message; $("#build-message") .attr("class", "message error") .text(message); var parserUrl = "data:text/plain;charset=utf-8;base64," + Base64.encode("Parser not available."); $("#parser-download").hide(); $("#input").attr("disabled", "disabled"); $("#parse-message") .attr("class", "message disabled") .text("Parser not available."); $("#output").addClass("not-available").text("(no output available)"); } } function parse() { oldInput = $("#input").val(); try { var timeBefore = Date.now(); var output = parser.parse($("#input").val()); var timeAfter = Date.now(); $("#parse-message") .attr("class", "message info") .text("Input parsed successfully.") .append( "<span class=\"time\" title=\"Parsing time and speed\">" + (timeAfter - timeBefore) + "&nbsp;ms, " + ($("#input").val().length / (timeAfter - timeBefore)).toPrecision(2) + "&nbsp;kB/s" + "</span>" ); $("#output").removeClass("not-available").html(jsDump.parse(output)); return true; } catch (e) { var message = e.line !== undefined && e.column !== undefined ? "Line " + e.line + ", column " + e.column + ": " + e.message : e.message; $("#parse-message") .attr("class", "message error") .text(message) $("#output").addClass("not-available").text("(no output available)"); return false; } } function buildAndParse() { build() && parse(); } function scheduleBuildAndParse() { var nothingChanged = $("#grammar").val() === oldGrammar && $("#parser-var").val() === oldParserVar && $("#start-rule").val() === oldStartRule; if (nothingChanged) { return; } if (buildAndParseTimer !== null) { clearTimeout(buildAndParseTimer); buildAndParseTimer = null; } if (parseTimer !== null) { clearTimeout(parseTimer); parseTimer = null; } buildAndParseTimer = setTimeout(function() { buildAndParse(); buildAndParseTimer = null; }, 500); } function scheduleParse() { if ($("#input").val() === oldInput) { return; } if (buildAndParseTimer !== null) { return; } if (parseTimer !== null) { clearTimeout(parseTimer); parseTimer = null; } parseTimer = setTimeout(function() { parse(); parseTimer = null; }, 500); } jsDump.HTML = true; $("#grammar, #start-rule, #parser-var") .change(scheduleBuildAndParse) .mousedown(scheduleBuildAndParse) .mouseup(scheduleBuildAndParse) .click(scheduleBuildAndParse) .keydown(scheduleBuildAndParse) .keyup(scheduleBuildAndParse) .keypress(scheduleBuildAndParse); $("#input") .change(scheduleParse) .mousedown(scheduleParse) .mouseup(scheduleParse) .click(scheduleParse) .keydown(scheduleParse) .keyup(scheduleParse) .keypress(scheduleParse); $("#settings-link").toggle(function() { $(this).html("&laquo; Detailed settings"); $("#settings").slideDown(); return false; }, function() { $(this).html("Detailed settings &raquo;"); $("#settings").slideUp(); return false; }); $("#grammar").focus(); buildAndParse(); });
JavaScript
0.008609
@@ -392,32 +392,42 @@ imeBefore = -Date.now +(new Date).getTime ();%0A pa @@ -513,32 +513,42 @@ timeAfter = -Date.now +(new Date).getTime ();%0A%0A $ @@ -1959,24 +1959,34 @@ efore = -Date.now +(new Date).getTime ();%0A @@ -2059,16 +2059,26 @@ r = -Date.now +(new Date).getTime ();%0A
866614b95078cad3404134fd900f7dbf9e09be66
declare variable
jquery.sticky.js
jquery.sticky.js
// Sticky Plugin v1.0.0 for jQuery // ============= // Author: Anthony Garand // Improvements by German M. Bravo (Kronuz) and Ruud Kamphuis (ruudk) // Improvements by Leonardo C. Daronco (daronco) // Created: 2/14/2011 // Date: 2/12/2012 // Website: http://labs.anthonygarand.com/sticky // Description: Makes an element on the page stick on the screen as you scroll // It will only set the 'top' and 'position' of your element, you // might need to adjust the width in some cases. (function($) { var defaults = { topSpacing: 0, bottomSpacing: 0, className: 'is-sticky', wrapperClassName: 'sticky-wrapper', center: false, getWidthFrom: '' }, $window = $(window), $document = $(document), sticked = [], windowHeight = $window.height(), scroller = function() { var scrollTop = $window.scrollTop(), documentHeight = $document.height(), dwh = documentHeight - windowHeight, extra = (scrollTop > dwh) ? dwh - scrollTop : 0; for (var i = 0; i < sticked.length; i++) { var s = sticked[i], elementTop = s.stickyWrapper.offset().top, etse = elementTop - s.topSpacing - extra; if (scrollTop <= etse) { if (s.currentTop !== null) { s.stickyElement .css('position', '') .css('top', ''); s.stickyElement.parent().removeClass(s.className); s.currentTop = null; } } else { var newTop = documentHeight - s.stickyElement.outerHeight() - s.topSpacing - s.bottomSpacing - scrollTop - extra; if (newTop < 0) { newTop = newTop + s.topSpacing; } else { newTop = s.topSpacing; } if (s.currentTop != newTop) { s.stickyElement .css('position', 'fixed') .css('top', newTop); if (typeof s.getWidthFrom !== 'undefined') { s.stickyElement.css('width', $(s.getWidthFrom).width()); } s.stickyElement.parent().addClass(s.className); s.currentTop = newTop; } } } }, resizer = function() { windowHeight = $window.height(); }, methods = { init: function(options) { var o = $.extend(defaults, options); return this.each(function() { var stickyElement = $(this); stickyId = stickyElement.attr('id'); wrapper = $('<div></div>') .attr('id', stickyId + '-sticky-wrapper') .addClass(o.wrapperClassName); stickyElement.wrapAll(wrapper); if (o.center) { stickyElement.parent().css({width:stickyElement.outerWidth(),marginLeft:"auto",marginRight:"auto"}); } if (stickyElement.css("float") == "right") { stickyElement.css({"float":"none"}).parent().css({"float":"right"}); } var stickyWrapper = stickyElement.parent(); stickyWrapper.css('height', stickyElement.outerHeight()); sticked.push({ topSpacing: o.topSpacing, bottomSpacing: o.bottomSpacing, stickyElement: stickyElement, currentTop: null, stickyWrapper: stickyWrapper, className: o.className, getWidthFrom: o.getWidthFrom }); }); }, update: scroller }; // should be more efficient than using $window.scroll(scroller) and $window.resize(resizer): if (window.addEventListener) { window.addEventListener('scroll', scroller, false); window.addEventListener('resize', resizer, false); } else if (window.attachEvent) { window.attachEvent('onscroll', scroller); window.attachEvent('onresize', resizer); } $.fn.sticky = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method ) { return methods.init.apply( this, arguments ); } else { $.error('Method ' + method + ' does not exist on jQuery.sticky'); } }; $(function() { setTimeout(scroller, 0); }); })(jQuery);
JavaScript
0.000001
@@ -2442,24 +2442,28 @@ %0A%0A +var stickyId = s @@ -2493,24 +2493,28 @@ ;%0A +var wrapper = $(
3836ef54cade51da29556fadc28ea850a222a3d5
add event delegation hash to main view
public/js/tksweb.js
public/js/tksweb.js
(function($) { 'use strict'; var TKSWeb = window.TKSWeb = { day_name : [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ], month_name : [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], hour_label_width : 50, hour_label_height : 48, day_label_width : 200, day_label_height : 28 }; var week_days, hours, column_for_date; function init_hours() { hours = [ '' ]; for(var i = 1; i < 24; i++) { hours.push({ hour: pad2(i) + ':00' }); } } function init_week_days(days) { column_for_date = {}; week_days = []; for(var i = 0; i < 7; i++) { column_for_date[ days[i] ] = i; var part = days[i].split('-'); week_days.push({ date : days[i], day : part[2], month : part[1], year : part[0], day_name : TKSWeb.day_name[ i ], month_name: TKSWeb.month_name[ parseInt(part[1], 10) - 1 ], }); } }; function pad2(num) { return num < 10 ? '0' + num : '' + num; } var Activity = Backbone.Model.extend({ defaults: { date : '', start_time : 0, duration : 60, wr_number : '', description : '' }, initialize: function() { this.set('column', column_for_date[ this.get('date') ]); } }); var Activities = Backbone.Collection.extend({ model: Activity, url: '/activity', comparator: function(activity) { return activity.get("date") + ' ' + ('0000' + activity.get("start_time")).substr(-4); } }); var ActivityView = Backbone.View.extend({ tagName: 'div', className: 'activity', initialize: function() { this.week_view = this.model.collection.view; this.listenTo(this.model, "change:wr_number change:description", this.render); this.position_element(); this.size_element(); }, render: function() { var context = this.model.toJSON(); this.$el.html( this.week_view.activity_template(context) ); return this; }, position_element: function() { var activity = this.model; this.$el.css({ left: activity.get('column') * 200, top: (activity.get('start_time') * TKSWeb.hour_label_height) / 60 }); }, size_element: function() { var activity = this.model; this.$el.height(activity.get('duration') * TKSWeb.hour_label_height / 60); } }); var WeekView = Backbone.View.extend({ initialize: function(options) { var view = this; this.compile_templates(); this.render(); this.collection.on('add', this.add_activity, this); this.$('.activities').on('mousewheel', $.proxy(this.mousewheel, this)); $(window).resize( $.proxy(view.resize, view) ); }, compile_templates: function() { this.template = Handlebars.compile( $('#week-view-template').html() ); this.activity_template = Handlebars.compile( $('#activity-template').html() ); }, render: function() { var context = { week_days: week_days, hours: hours }; this.$el.html( this.template(context) ); this.size_activities(); this.enable_workspace_drag(); this.resize(); this.set_initial_scroll(); }, size_activities: function() { this.activities_width = TKSWeb.day_label_width * 7; this.activities_height = TKSWeb.hour_label_height * 24; this.$('.activities') .width(this.activities_width) .height(this.activities_height); this.$('.day-labels') .width(this.activities_width); this.$('.hour-labels') .height(this.activities_height); }, enable_workspace_drag: function() { var view = this; this.$('.activities').draggable({ drag: function(event, ui) { view.drag( ui.position ); } }); }, resize: function() { this.app_width = Math.min(this.activities_width + TKSWeb.hour_label_width, window.innerWidth); this.app_height = Math.min(this.activities_height + TKSWeb.day_label_height, window.innerHeight); this.$el.width( this.app_width ).height( this.app_height ); this.set_drag_constraints(); }, set_drag_constraints: function() { this.min_y = this.app_height - this.activities_height; this.max_y = TKSWeb.day_label_height + 1; this.$('.activities').draggable("option", { containment: [ this.app_width - this.activities_width, this.min_y, TKSWeb.hour_label_width + 1, this.max_y ] }); }, drag: function(pos) { this.$('.day-labels ul').css('left', pos.left - TKSWeb.hour_label_width); this.$('.hour-labels ul').css('top', pos.top - TKSWeb.day_label_height); }, set_initial_scroll: function() { var $activities = this.$('.activities'); var day_height = (18 - 8) * TKSWeb.hour_label_height; var y = -8 * TKSWeb.hour_label_height; if(day_height < this.app_height) { y = y + (this.app_height - day_height) / 2 } $activities.css('top', y); this.$('.hour-labels ul').css('top', y - TKSWeb.day_label_height); }, mousewheel: function(e, delta) { var $activities = this.$('.activities'); var y = parseInt($activities.css('top'), 10) + delta * 12; y = Math.min( Math.max(y, this.min_y), this.max_y); $activities.css('top', y); this.$('.hour-labels ul').css('top', y - TKSWeb.day_label_height); }, add_activity: function(activity) { this.$('.activities').append( new ActivityView({ model: activity }).render().el ); } }); TKSWeb.show_week = function (el, days, activities_data) { init_week_days(days); init_hours(); var activities = new Activities(); activities.view = new WeekView({ el: el, monday: days[0], collection: activities }); activities.add(activities_data); }; })(jQuery);
JavaScript
0
@@ -2928,32 +2928,112 @@ e.View.extend(%7B%0A + events: %7B%0A %22mousewheel .activities%22: %22mousewheel%22%0A %7D,%0A initiali @@ -3218,92 +3218,8 @@ s);%0A - this.$('.activities').on('mousewheel', $.proxy(this.mousewheel, this));%0A
0ed002fc441561e114b77babd3c68df6d3b8eb22
Fix bugs that creating moment object is invalid.
js/attendance.js
js/attendance.js
$(function() { const LENGTH_OF_WEEK = 6; const SUNDAY_NUMBER = 0; const SATURDAY_NUMBER = 6; var myAttendInfo = []; var selectedDate = moment(); updateCurrentTime(); getMyAttend(); function getMyAttend() { $.ajax({ type: "GET", url: '/attend', data: {}, success: function(data) { myAttendInfo = _.map(data.result, function (record) { return moment().format(record); }); getMyAttendSuccessCallback(); }, error: function(data) { alert('서버 에러' + JSON.stringify(data)); location.href = "error.html"; }, dataType: 'json' }); } function getMyAttendSuccessCallback() { makeAttendanceCalendar(); addEvent(); } function updateCurrentTime() { var date = moment().format('MMMM Do YYYY, h:mm:ss a'); var currentTime = date; $('#current_time').text(currentTime); setTimeout(updateCurrentTime, 1000); } function addEvent() { addRewardEvent(); $('#attend_button').click(function() { $.ajax({ type: "POST", url: '/attend', data: {}, xhrFields: { withCredentials:true }, success: function(data) { if(data.status === "ok") { alert('지각은 마음의 병 출첵 완료!!'); location.reload(); } else { alert('에러' + JSON.stringify(data)); } }, error: function(data) { alert('서버 에러' + JSON.stringify(data)); location.href = "error.html"; }, dataType: 'json' }); }); $('#go_before_month_button').click(function() { selectedDate.subtract(1, 'month'); makeAttendanceCalendar(); addRewardEvent(); }); $('#go_next_month_button').click(function() { selectedDate.add(1, 'month'); makeAttendanceCalendar(); addRewardEvent(); }); function addRewardEvent() { $('.attendance_table_attend_reward').click(function() { alert("뿌듯함 +100"); }); } } function makeAttendanceCalendar() { removeAllRowsExceptTableFrame(); var calendarTable = $('#attendance_table'); var year = selectedDate.year(); var month = selectedDate.month(); var date = selectedDate.date(); var query = ''; query += createDummyColumnQueryBeforeFirstDay(year, month); query += createMonthColumnQuery(year, month); query += createDummyColumnQueryAfterLastDay(year, month); calendarTable.append(query); setCurrentYearAndMonthUI(); } function removeAllRowsExceptTableFrame() { $('#attendance_table tr:not(.attendance_table_frame)').remove(); } function setCurrentYearAndMonthUI () { var currentYearAndMonthUi = $('#current_year_month'); currentYearAndMonthUi.text(selectedDate.format("YYYY년 MM월")); } function createMonthColumnQuery (year, month) { var query = ''; for (var i = 1; i <= getLastDateOfMonth(year, month); i++) { if(isSunday(year, month, i)) { query += makeSundayColumnQuery(year, month, i); } else if (isSaturday(year, month, i)) { query += makeSaturdayColumnQuery(year, month, i); } else { query += makeWeekdayColumnQuery(year, month, i); } } return query; } function createDummyColumnQueryBeforeFirstDay(year, month) { var query = ''; if (getFirstDayOfMonth(year, month) != SUNDAY_NUMBER) { query += '<tr class="active attendance_table_row">'; } for (var i = SUNDAY_NUMBER; i < getFirstDayOfMonth(year, month); i++) { query += '<td></td>'; } return query; } function createDummyColumnQueryAfterLastDay (year, month) { var query = ''; for (var i = getLastDayOfMonth(year, month); i < LENGTH_OF_WEEK; i++) { query += '<td></td>'; } if (getLastDayOfMonth(year, month) != LENGTH_OF_WEEK) { query += '</tr>'; } return query; } function makeSundayColumnQuery(year, month, date) { var createNewRowQuery = '<tr class="active attendance_table_row">'; if (isToday(year, month, date)) return createNewRowQuery + '<td class="sunday_text attendance_table_today">' + date + '</td>'; else return createNewRowQuery + '<td class="sunday_text">' + date + '</td>'; } function makeSaturdayColumnQuery(year, month, date) { var endRowQuery = '</tr>'; var rewardObject = '<div class="attendance_table_attend_reward"></div>'; if (isToday(year, month, date)) return '<td class="saturday_text attendance_table_today">' + date + rewardObject + '</td>' + endRowQuery; else return '<td class="saturday_text">' + date + rewardObject + '</td>' + endRowQuery; } function makeWeekdayColumnQuery(year, month, date) { var attendanceRecordDate = getAttendanceRecordDate(year, month, date); if (isToday(year, month, date)) { if (attendanceRecordDate) { $('#attend_button').attr('disabled', 'disabled'); var attenanceQuery = '<span class="attendance_table_attend_time">' + attendanceRecordDate.format("hh:mm A") + '</span>'; return '<td class="attendance_table_today">' + date + attenanceQuery + '</td>'; } else { return '<td class="attendance_table_today">' + date + '</td>'; } } else if (attendanceRecordDate) { var attenanceQuery = '<span class="attendance_table_attend_time">' + attendanceRecordDate.format("hh:mm A") + '</span>'; return '<td>' + date + attenanceQuery + '</td>'; } else { return '<td>' + date + '</td>'; } } function getAttendanceRecordDate (year, month, date) { var dateToFind = moment(new Date(year, month, date)); var filteredData = _.filter(myAttendInfo, function(record) { return record.year() === dateToFind.year() && record.month() === dateToFind.month() && record.date() === dateToFind.date(); }); if (filteredData.length === 0) return null; else return filteredData[0]; } //Sunday function isSunday(year, month, date) { return moment(new Date(year, month, date)).day() === SUNDAY_NUMBER; } //Saturday function isSaturday(year, month, date) { return moment(new Date(year, month, date)).day() === LENGTH_OF_WEEK; } function getFirstDayOfMonth(year, month) { return moment(new Date(year, month, 1)).day(); } function getLastDayOfMonth(year, month) { return moment(new Date(year, month, getLastDateOfMonth(year, month))).day(); } function getLastDateOfMonth(year, month) { return moment(new Date(year, month + 1, 1)).subtract(1, 'day').date(); } function isToday(year, month, date) { var date = moment(new Date(year, month, date)); var today = moment(); return date.year() === today.year() && date.month() === today.month() && date.date() === today.date(); } });
JavaScript
0
@@ -405,25 +405,16 @@ moment( -).format( record);
b32cf44f1a5731de74ed01d5ee4c899c7b5f65fc
Fix firefox not showing page action icon (#640)
js/background.js
js/background.js
var options; // Performs an ajax request function ajaxRequest(request, callback) { var xhr = new XMLHttpRequest(); var response = request.response; xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { if (response === 'URL') { callback(xhr.responseURL); } else { callback(xhr.responseText); } } else { callback(null); } } } xhr.open(request.method, request.url, true); for (var i in request.headers) { xhr.setRequestHeader(request.headers[i].header, request.headers[i].value); } xhr.send(request.data); } function onMessage(message, sender, callback) { switch (message.action) { case 'downloadFile': chrome.permissions.request({ permissions: ['downloads'] }, function (granted) { if (granted) { chrome.downloads.download({url: message.url, filename: message.filename}); return true; } else { return false; } }); case 'ajaxGet': ajaxRequest({url:message.url, response:message.response, method:'GET'}, callback); return true; case 'ajaxRequest': ajaxRequest(message, callback); return true; case 'showPageAction': showPageAction(sender.tab); callback(); return true; case 'addUrlToHistory': chrome.permissions.contains({permissions: ['history']}, function(granted) { if (granted) { chrome.history.addUrl({url:message.url}); } }); break; case 'getOptions': callback(options); return true; case 'setOption': options[message.name] = message.value; localStorage.options = JSON.stringify(options); sendOptions(message.options); break; case 'optionsChanged': options = message.options; break; case 'saveOptions': localStorage.options = JSON.stringify(message.options); sendOptions(message.options); break; case 'setItem': localStorage.setItem(message.id, message.data); break; case 'getItem': callback(localStorage.getItem(message.id)); return true; case 'removeItem': localStorage.removeItem(message.id); break; case 'openViewWindow': var url = message.createData.url; if (url.indexOf('facebook.com/photo/download') !== -1) { message.createData.url = 'data:text/html,<img src="' + url + '">'; } chrome.windows.create(message.createData, function (window) { chrome.tabs.executeScript(window.tabs[0].id, {file:'js/viewWindow.js'}); }); break; case 'openViewTab': chrome.tabs.query({active: true}, function (tabs) { message.createData.index = tabs[0].index; if (!message.createData.active) message.createData.index++; var url = message.createData.url; if (url.indexOf('facebook.com/photo/download') !== -1) { message.createData.url = 'data:text/html,<img src="' + url + '">'; } chrome.tabs.create(message.createData, function (tab) { chrome.tabs.executeScript(tab.id, {file:'js/viewTab.js'}); }); }); break; } } function showPageAction(tab) { if (!tab) { return; } if (!options.extensionEnabled || isExcludedSite(tab.url)) { chrome.pageAction.setIcon({tabId:tab.id, path:'../images/icon19d.png'}); } else { chrome.pageAction.setIcon({tabId:tab.id, path:'../images/icon19.png'}); } chrome.pageAction.show(tab.id); } function init() { // Load options options = loadOptions(); // Bind events chrome.runtime.onMessage.addListener(onMessage); } init();
JavaScript
0
@@ -1499,24 +1499,203 @@ ageAction':%0A + // Firefox url is located at sender.url, copy sender.url to sender.tab.url%0A if (!sender.tab.url && sender.url) %0A sender.tab.url = sender.url%0A
8d90c0514d3c2694eb4a31516c22ba2e055fcf4f
handle install event (#2)
js/background.js
js/background.js
var WORKBENCH_URL = "http://localhost:1999/recording/events?type=chrome"; var INTERVAL = 1000; var IGNORED_PREFIXES = [ "https://loadster.app", "https://speedway.app" ] var requests = {}; // Requests are stored here until they are uploaded var ports = []; // Listeners from the Loadster website that want to receive recording events // // Stores a request if we haven't seen it before; otherwise updates it. // function requestUpdated (info) { chrome.tabs.get(info.tabId, function (tab) { if (tab.url) { for (var i = 0; i < IGNORED_PREFIXES.length; i++) { if (tab.url.indexOf(IGNORED_PREFIXES[i]) === 0) { return; } } } else if (info.url === WORKBENCH_URL) { return; } // Track the request start time if it's a new request if (!requests[info.requestId]) { requests[info.requestId] = { timeStarted: new Date().getTime() }; } // Base64 encode the body parts if necessary if (info.requestBody && info.requestBody.raw) { for (var i = 0; i < info.requestBody.raw.length; i++) { var part = info.requestBody.raw[i]; if (part.bytes) { part.base64 = toBase64(part.bytes); } else if (part.file) { } } } // Copy properties for (var prop in info) { if (info.hasOwnProperty(prop)) { requests[info.requestId][prop] = info[prop]; } } }) }; // // Updates a request and checks if it's being redirected. // function headersReceived (info) { requestUpdated(info); if (info.statusCode == 301 || info.statusCode == 302) { requestRedirected(info); } }; // // Clones a request when it is redirected, marking the redirected one as complete and // keeping the original for further updates. // function requestRedirected (info) { var request = requests[info.requestId]; var redirected = {}; for (var prop in request) { if (request.hasOwnProperty(prop)) { redirected[prop] = request[prop]; } } request.timeStarted = new Date().getTime(); redirected.requestId = request.requestId + '_' + Math.round(Math.random() * 1000000); redirected.completed = true; redirected.timeCompleted = new Date().getTime(); requests[redirected.requestId] = redirected; }; // // Finishes a normal request, marking it completed. // function finishRequest (info) { info.completed = true; info.timeCompleted = new Date().getTime(); requestUpdated(info); }; // // Checks if recording is enabled // function isEnabled () { return localStorage["loadster.recording.enabled"] == "true"; } // // Reads an array buffer into a Base64 string // function toBase64 (buffer) { var binary = ''; var bytes = new Uint8Array(buffer); var length = bytes.byteLength; for (var i = 0; i < length; i++) { binary += String.fromCharCode(bytes[i]); } return window.btoa(binary); } // // Create a catch-all filter so we see all types of content // var filter = { urls: ["*://*/*"], types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"] }; // // Listen to all types of events // chrome.webRequest.onBeforeRequest.addListener(requestUpdated, filter, ['blocking', 'requestBody']); chrome.webRequest.onBeforeSendHeaders.addListener(requestUpdated, filter, ['requestHeaders', 'extraHeaders']); chrome.webRequest.onSendHeaders.addListener(requestUpdated, filter, ['requestHeaders', 'extraHeaders']); chrome.webRequest.onHeadersReceived.addListener(headersReceived, filter, ['blocking', 'responseHeaders']); chrome.webRequest.onResponseStarted.addListener(requestUpdated, filter, ['responseHeaders']); chrome.webRequest.onCompleted.addListener(finishRequest, filter, ['responseHeaders']); // // Listen for messages from the Loadster dashboard // chrome.runtime.onConnectExternal.addListener(function (port) { console.assert(port.name === 'loadster-recorder', 'Only accepting incoming messages from loadster-recorder') console.log('Adding port ', port); ports.push(port); port.onMessage.addListener(function (msg) { if (msg.type === 'Ping') { port.postMessage({type: 'Pong', enabled: isEnabled()}) } else { console.log('got unexpected message: ', msg); } }) port.onDisconnect.addListener(function () { console.log('Removing port ', port); ports.splice(ports.indexOf(port, 1)); }) }) // // Upload events to Loadster at set intervals // setInterval(function () { var upload = {}; for (var requestId in requests) { if (requests.hasOwnProperty(requestId)) { if (requests[requestId].completed) { upload[requestId] = requests[requestId]; delete requests[requestId]; } } } if (Object.keys(upload).length && isEnabled()) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { var status = xhr.status; if (status === 200 || status === 201) { console.log("Uploaded " + Object.keys(upload).length + " recording events to " + WORKBENCH_URL); } else { console.warn("Failed to upload " + Object.keys(upload).length + " recording events to " + WORKBENCH_URL); } } }; xhr.open("POST", WORKBENCH_URL, true); xhr.setRequestHeader("Content-Type", "application/json"); xhr.send(JSON.stringify(upload)); console.log('Sending recording events to ' + ports.length + ' port(s)') ports.forEach(function (port) { port.postMessage({type: "RecordingEvents", data: upload}); }); } }, INTERVAL);
JavaScript
0
@@ -337,16 +337,161 @@ events%0A%0A +function handleFirstRun (details) %7B%0A if(details.reason === 'install') %7B%0A localStorage%5B%22loadster.recording.enabled%22%5D = %22true%22;%0A %7D%0A%7D%0A%0A //%0A// St @@ -4144,16 +4144,71 @@ ers'%5D);%0A +chrome.runtime.onInstalled.addListener(handleFirstRun); %0A//%0A// L
698d419b50ddde343b449b934e7e36d952f79c36
Make unary not (!) operator usage consistent.
js/budget-app.js
js/budget-app.js
var bb = bb || {}; bb.BudgetApp = function(pageDom) { this.budget = new bb.Budget(); this.dataManager = new bb.DataManager(new bb.DataStore()); this.expense = new bb.Transaction(); this.income = new bb.Transaction(); this.page = new bb.Page(pageDom); this.routes = { 'accounts': { 'tagName': 'bb-page-accounts' }, 'account/new': { 'tagName': 'bb-page-account-new' }, 'budget/view': { 'tagName': 'bb-page-budget' }, 'category/new': { 'tagName': 'bb-page-category-new' }, 'expense/account': { 'tagName': 'bb-page-expense-account', 'opts': { 'transaction': this.expense } }, 'expense/amount': { 'tagName': 'bb-page-expense-amount', 'opts': { 'transaction': this.expense } }, 'expense/category': { 'tagName': 'bb-page-expense-category', 'opts': { 'transaction': this.expense } }, 'expense/summary': { 'tagName': 'bb-page-expense-summary', 'opts': { 'transaction': this.expense } }, 'expense/when': { 'tagName': 'bb-page-expense-when', 'opts': { 'transaction': this.expense } }, 'expense/who': { 'tagName': 'bb-page-expense-who', 'opts': { 'transaction': this.expense } }, 'history/account': { 'tagName': 'bb-page-history-account' }, 'history/all': { 'tagName': 'bb-page-history-all' }, 'history/category': { 'tagName': 'bb-page-history-category' }, 'history/search': { 'tagName': 'bb-page-history-search' }, 'income/account': { 'tagName': 'bb-page-income-account', 'opts': { 'transaction': this.income } }, 'income/amount': { 'tagName': 'bb-page-income-amount', 'opts': { 'transaction': this.income } }, 'income/category': { 'tagName': 'bb-page-income-category', 'opts': { 'transaction': this.income } }, 'income/summary': { 'tagName': 'bb-page-income-summary', 'opts': { 'transaction': this.income } }, 'income/when': { 'tagName': 'bb-page-income-when', 'opts': { 'transaction': this.income } }, 'income/who': { 'tagName': 'bb-page-income-who', 'opts': { 'transaction': this.income } } }; route(this.route.bind(this)); }; bb.BudgetApp.prototype.route = function(page, subPage, id) { if ( ! page) { route('budget'); return; } if ((page === 'budget') && ! subPage) { subPage = 'view'; } var path = (subPage ? page + '/' + subPage : page); var routeData = this.routes[path]; if (routeData != undefined) { routeData.opts = routeData.opts || {}; routeData.opts.id = id; routeData.opts.dm = this.dataManager; try { this.page.showTag(routeData.tagName, routeData.opts); } catch (e) { console.log(e); this.page.showTag('bb-page-error', { 'error': e }); } } else { this.page.showTag('bb-page-not-found', { 'route': path }); } };
JavaScript
0.000003
@@ -2631,19 +2631,17 @@ %0D%0A if ( - ! +! page) %7B%0D @@ -2713,17 +2713,16 @@ t') && ! - subPage)
0190590fd8232033d42d90deb72a9b2829b02f74
Update contact_me.js
js/contact_me.js
js/contact_me.js
$(function() { $("input,textarea").jqBootstrapValidation({ preventSubmit: true, submitError: function($form, event, errors) { // additional error messages or events }, submitSuccess: function($form, event) { event.preventDefault(); // prevent default submit behaviour // get values from FORM var name = $("input#name").val(); var email = $("input#email").val(); var phone = $("input#phone").val(); var message = $("textarea#message").val(); var firstName = name; // For Success/Failure Message // Check for white space in name for Success/Fail message if (firstName.indexOf(' ') >= 0) { firstName = name.split(' ').slice(0, -1).join(' '); } $.ajax({ type: 'POST', url: "https://mandrillapp.com/api/1.0/messages/send.json", dataType: 'json', data: { key: 'h7nP27VyRFNZ8MTSaqmW6g', message: { text: "Example text content", subject: "example subject", from_email: "[email protected]", from_name: "Example Name", to: [{ "email": "[email protected]", "name": "Recipient Name" }] } }, cache: false, success: function() { // Success message $('#success').html("<div class='alert alert-success'>"); $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;") .append("</button>"); $('#success > .alert-success') .append("<strong>Your message has been sent. </strong>"); $('#success > .alert-success') .append('</div>'); //clear all fields $('#contactForm').trigger("reset"); }, error: function() { // Fail message $('#success').html("<div class='alert alert-danger'>"); $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;") .append("</button>"); $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"); $('#success > .alert-danger').append('</div>'); //clear all fields $('#contactForm').trigger("reset"); }, }) }, filter: function() { return $(this).is(":visible"); }, }); $("a[data-toggle=\"tab\"]").click(function(e) { e.preventDefault(); $(this).tab("show"); }); }); /*When clicking on Full hide fail/success boxes */ $('#name').focus(function() { $('#success').html(''); });
JavaScript
0
@@ -1119,30 +1119,44 @@ xt: -%22Example text content%22 +message + %22%5Cn%5Cn%22 + %22Phone: %22 + phone ,%0A @@ -1191,23 +1191,25 @@ t: %22 -example subject +Contact Engineers %22,%0A @@ -1243,34 +1243,21 @@ _email: -%22 +e mail [email protected]%22 ,%0A @@ -1289,22 +1289,12 @@ me: -%22Example N +n ame -%22 ,%0A
1d5471c3181544d565721b300635e968082a2b5f
Fix search tests
js/emoji_util.js
js/emoji_util.js
/* * vim: ts=4:sw=4:expandtab */ ;(function() { 'use strict'; window.emoji_util = window.emoji_util || {}; // EmojiConverter overrides EmojiConvertor.prototype.init_env = function() { if (this.inits.env) { return; } this.inits.env = 1; this.include_title = true; this.img_sets.apple.path = '/images/emoji/apple/'; this.replace_mode = 'img'; }; EmojiConvertor.prototype.replace_unified = function(str) { var self = this; self.init_unified(); return str.replace(self.rx_unified, function(m, p1, p2) { var val = self.map.unified[p1]; if (!val) { return m; } var idx = null; if (p2 == '\uD83C\uDFFB') { idx = '1f3fb'; } if (p2 == '\uD83C\uDFFC') { idx = '1f3fc'; } if (p2 == '\uD83C\uDFFD') { idx = '1f3fd'; } if (p2 == '\uD83C\uDFFE') { idx = '1f3fe'; } if (p2 == '\uD83C\uDFFF') { idx = '1f3ff'; } if (idx) { return self.replacement(val, null, null, { idx : idx, actual : p2, wrapper : ':' }); } // wrap names in :'s return self.replacement(val, ':' + self.data[val][3][0] + ':'); }); }; window.emoji = new EmojiConvertor(); emoji.init_colons(); window.emoji_util.parse = function($el) { $el.html(emoji.replace_unified($el.html())); }; })();
JavaScript
0
@@ -1449,24 +1449,89 @@ tion($el) %7B%0A + if (!$el %7C%7C !$el.length) %7B%0A return;%0A %7D%0A $el.
3dd87717c92d9b498ce0d9d2a13ef130eeb90cff
Fix thunker and logger priority
js/flux/store.js
js/flux/store.js
//jshint -W067 'use strict'; import * as todosreducers from 'todosreducers'; import {default as DevTools} from 'devtools'; var { Immutable, Redux } = window, { List } = Immutable; const finalCreateStore = Redux.compose( DevTools.instrument(), window.ReduxDevTools.persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)) )(Redux.applyMiddleware(window.ReduxThunk)(Redux.createStore)); const rootReducer = Redux.combineReducers({ ...todosreducers }); export default finalCreateStore(rootReducer, { todos: List() });
JavaScript
0
@@ -238,16 +238,57 @@ Store = +Redux.applyMiddleware(window.ReduxThunk)( Redux.co @@ -422,49 +422,8 @@ /))%0A -)(Redux.applyMiddleware(window.ReduxThunk )(Re
3cca6f9e21634d69ac1b697f286a931d572ce6e5
update data
js/forceGraph.js
js/forceGraph.js
var width = 960, height = 500; var color = d3.scale.category20(); var force = d3.layout.force() .charge(-120) .linkDistance(250) .size([width, height]); var k = 0; while ((force.alpha() > 1e-2) && (k < 150)) { force.tick(), k = k + 1; } var forceSvg = d3.select("div#chord_chart").append("svg") .attr("width", width) .attr("height", height); var node_drag = d3.behavior.drag() .on("dragstart", dragstart) .on("drag", dragmove) .on("dragend", dragend); function dragstart(d, i) { force.stop() // stops the force auto positioning before you start dragging } function dragmove(d, i) { d.px += d3.event.dx; d.py += d3.event.dy; d.x += d3.event.dx; d.y += d3.event.dy; } function dragend(d, i) { d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff force.resume(); } function releasenode(d) { d.fixed = false; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff //force.resume(); }; d3.json("newsGraph.json", function(error, graph) { testGraph = JSON.parse(JSON.stringify(graph)) console.log(graph); console.log(testGraph); selectedList = ['up','police','china','labor','union']; selectedData1 = $.map(testGraph.nodes, function(element){ return ($.inArray(element.name,selectedList)>-1?element:null); }); selectedData2 = $.map(testGraph.links, function(element){ return ($.inArray(element['name1'],selectedList)>-1?element:null); }); console.log(selectedData2); selectedData3 = $.map(selectedData2, function(element){ return ($.inArray(element.name2,selectedList)>-1?element:null); }); new_graph = {}; new_graph['nodes'] = graph.nodes; new_graph['links'] = selectedData3; console.log(new_graph); drawGraph(graph, selectedData1, selectedData3); function drawGraph(graph, nodes, links){ console.log(nodes); force .nodes(graph.nodes) .links(graph.links) .start(); var graphMin = d3.min(graph.links, function(d){ return d.size; }); var graphMax = d3.max(graph.links, function(d){ return d.size; }); var fill = d3.scale.ordinal() .domain([graphMin, graphMax]) .range(["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4", "#41ae76","#238b45","#006d2c","#00441b"]); var div = d3.select('div#chord_chart').append('div') .attr('class', 'tooltip') .style('opacity', 0); var link = forceSvg.selectAll(".link") .data(graph.links) .enter().append("line") .attr("class", "link") .style('stroke-width', 1) .style('stroke', function(d){ return fill(d.value); }); //.style("stroke-width", function(d) { return Math.sqrt(d.value); }); var node = forceSvg.selectAll(".node") .data(graph.nodes) .enter().append("circle") .attr("class", "node") .attr("r", 5) .style("fill", function(d) { return color(d.group); }) .on('click', releasenode) .on('dblclick', connectedNodes) .call(node_drag); //.call(force.drag); node .on('mouseover', function(d,i,j){ d3.select(this).transition().duration(600) .attr('r', 8).style('opacity', 1); div.transition() .duration(500) .style('opacity', 1); div.html(d.name) .style('left', '300px') .style('top', '10px'); //.style('left', (d3.event.pageX) + 10 + "px") //.style('top', (d3.event.pageY) + 2 + "px") //.style('color', line_color(used_data[j].term)); }) .on('mouseout', function(d){ d3.select(this).transition().duration(600) .attr('r', 5).style('opacity', 1); div.transition() .duration(500) .style('opacity', 0); }); node.append("title") .text(function(d) { return d.name; }); force.on("tick", function() { link.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node.attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); }); //Toggle stores whether the highlighting is on var toggle = 0; //Create an array logging what is connected to what var linkedByIndex = {}; for (i = 0; i < graph.nodes.length; i++) { linkedByIndex[i + "," + i] = 1; }; graph.links.forEach(function (d) { linkedByIndex[d.source.index + "," + d.target.index] = 1; }); //This function looks up whether a pair are neighbours function neighboring(a, b) { return linkedByIndex[a.index + "," + b.index]; } function connectedNodes() { if (toggle == 0) { //Reduce the opacity of all but the neighbouring nodes d = d3.select(this).node().__data__; node.style("opacity", function (o) { return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1; }); link.style("opacity", function (o) { return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1; }); //Reduce the op toggle = 1; } else { //Put them back to opacity=1 node.style("opacity", 1); link.style("opacity", 1); toggle = 0; } } } });
JavaScript
0.000001
@@ -169,101 +169,8 @@ );%0A%0A -var k = 0;%0Awhile ((force.alpha() %3E 1e-2) && (k %3C 150)) %7B%0A force.tick(),%0A k = k + 1;%0A%7D%0A%0A var @@ -1151,56 +1151,8 @@ ph)) -%0A console.log(graph);%0A console.log(testGraph); %0A%0A @@ -4346,24 +4346,137 @@ );%0A %7D);%0A%0A + var k = 0;%0A while ((force.alpha() %3E 1e-2) && (k %3C 150)) %7B%0A force.tick(),%0A k = k + 1;%0A %7D%0A%0A //Toggle
4d82cd6e951103888c8039f052c31fff8c149d64
update data
js/forceGraph.js
js/forceGraph.js
var width = 960, height = 500; var color = d3.scale.category20(); var force = d3.layout.force() .charge(-120) .linkDistance(200) .size([width, height]); var forceSvg = d3.select("div#chord_chart").append("svg") .attr("width", width) .attr("height", height); d3.json("newsGraph.json", function(error, graph) { testGraph = JSON.parse(JSON.stringify(graph)) console.log(graph); console.log(testGraph); selectedList = ['up','police','china','labor','union']; selectedData1 = $.map(testGraph.nodes, function(element){ return ($.inArray(element.name,selectedList)>-1?element:null); }); selectedData2 = $.map(testGraph.links, function(element){ return ($.inArray(element['name1'],selectedList)>-1?element:null); }); console.log(selectedData2); selectedData3 = $.map(selectedData2, function(element){ return ($.inArray(element.name2,selectedList)>-1?element:null); }); new_graph = {}; new_graph['nodes'] = graph.nodes; new_graph['links'] = selectedData3; console.log(new_graph); drawGraph(graph, selectedData1, selectedData3); function drawGraph(graph, nodes, links){ console.log(nodes); force .nodes(graph.nodes) .links(graph.links) .start(); var graphMin = d3.min(graph.links, function(d){ return d.size; }); var graphMax = d3.max(graph.links, function(d){ return d.size; }); var fill = d3.scale.ordinal() .domain([graphMin, graphMax]) .range(["#DB704D", "#D2D0C6", "#ECD08D", "#F8EDD3"]); var link = forceSvg.selectAll(".link") .data(graph.links) .enter().append("line") .attr("class", "link") .style('stroke-width', 1) .style('stroke', function(d){ return fill(d.value); }); //.style("stroke-width", function(d) { return Math.sqrt(d.value); }); var node = forceSvg.selectAll(".node") .data(graph.nodes) .enter().append("circle") .attr("class", "node") .attr("r", 5) .style("fill", function(d) { return color(d.group); }) .call(force.drag) .on('dblclick', connectedNodes); node.append("title") .text(function(d) { return d.name; }); force.on("tick", function() { link.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node.attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); }); } //Toggle stores whether the highlighting is on var toggle = 0; //Create an array logging what is connected to what var linkedByIndex = {}; for (i = 0; i < graph.nodes.length; i++) { linkedByIndex[i + "," + i] = 1; }; graph.links.forEach(function (d) { linkedByIndex[d.source.index + "," + d.target.index] = 1; }); //This function looks up whether a pair are neighbours function neighboring(a, b) { return linkedByIndex[a.index + "," + b.index]; } function connectedNodes() { if (toggle == 0) { //Reduce the opacity of all but the neighbouring nodes d = d3.select(this).node().__data__; node.style("opacity", function (o) { return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1; }); link.style("opacity", function (o) { return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1; }); //Reduce the op toggle = 1; } else { //Put them back to opacity=1 node.style("opacity", 1); link.style("opacity", 1); toggle = 0; } } });
JavaScript
0.000001
@@ -2577,20 +2577,12 @@ %7D);%0A - %7D); +%0A %0A -%7D%0A // @@ -3711,16 +3711,29 @@ %7D%0A%0A%7D%0A + %7D);%0A %7D%0A%0A %0A%7D);%0A
8e396b7fc2e05cb07865ba790ae050a7e4be3da8
trying to make cors work. attempt 2
js/foursquare.js
js/foursquare.js
function loadUserData(config){ var data, url, xmlHttp; //VARS from config var callback = config.customCallback; url = 'https://api.jh0.eu/swarm?fetch=user'; xmlHttp = new XMLHttpRequest(); xmlHttp.setRequestHeader('Access-Control-Allow-Origin', '*'); xmlHttp.setRequestHeader('Access-Control-Allow-Methods', 'GET'); xmlHttp.onreadystatechange = function(data) { if(xmlHttp.readyState == 4 && xmlHttp.status == 200){ var answer = JSON.parse(xmlHttp.responseText) var niceAnswer = answer[0]; callback(niceAnswer); } } xmlHttp.open("GET", url, true); xmlHttp.send(); } function loadCheckins(config){ var data, url, xmlHttp; //VARS from config var count = config.count; var callback = config.customCallback; //Setup config.ignore with help of these references: https://developer.foursquare.com/categorytree var vague = false; if(count > 0 && count < 50){ url = 'https://api.jh0.eu/swarm?fetch=checkins&count=' + count; xmlHttp = new XMLHttpRequest(); xmlHttp.setRequestHeader('Access-Control-Allow-Origin', '*'); xmlHttp.setRequestHeader('Access-Control-Allow-Methods', 'GET'); xmlHttp.onreadystatechange = function(data) { if(xmlHttp.readyState == 4 && xmlHttp.status == 200){ var answer = JSON.parse(xmlHttp.responseText) var niceAnswer = answer[0]; if(typeof config.ignore === 'object'){ for(var i = config.ignore.length - 1; i >= 0; i--) { var ignoreListItem = config.ignore[i]; for(var i = niceAnswer.venue.categories.length - 1; i >= 0; i--) { var categoryItem = niceAnswer.venue.categories[i].name; if(ignoreListItem == categoryItem){ vague = true; } } } } if(vague){ var checkin = { "venue": { "name": niceAnswer.venue.location.city, "location": { "neighborhood": '', "city": '', "cc": niceAnswer.venue.location.cc, "country": niceAnswer.venue.location.country, "state": niceAnswer.venue.location.state, }, "categories": niceAnswer.venue.categories } } }else{ var checkin = { "venue": { "name": niceAnswer.venue.name, "location": { "neighborhood": niceAnswer.venue.location.neighborhood, "city": niceAnswer.venue.location.city, "cc": niceAnswer.venue.location.cc, "country": niceAnswer.venue.location.country, "state": niceAnswer.venue.location.state, }, "categories": niceAnswer.venue.categories } } } callback(checkin); } } } xmlHttp.open("GET", url, true); xmlHttp.send(); }
JavaScript
0.999325
@@ -155,25 +155,25 @@ h=user';%0A - +%09 xmlHttp = ne @@ -196,137 +196,8 @@ ();%0A -%09xmlHttp.setRequestHeader('Access-Control-Allow-Origin', '*');%0A%09xmlHttp.setRequestHeader('Access-Control-Allow-Methods', 'GET');%0A @@ -892,139 +892,8 @@ ();%0A -%09%09xmlHttp.setRequestHeader('Access-Control-Allow-Origin', '*');%0A%09%09xmlHttp.setRequestHeader('Access-Control-Allow-Methods', 'GET');%0A %09
aa88fc15da4492964991fa6f03dd68fbda388053
update copyright dates from daily grunt work
js/grunt/lint.js
js/grunt/lint.js
// Copyright 2017-2020, University of Colorado Boulder /** * Runs the lint rules on the specified files. * * @author Sam Reid (PhET Interactive Simulations) */ 'use strict'; // modules const _ = require( 'lodash' ); // eslint-disable-line require-statement-match const { ESLint } = require( 'eslint' ); // eslint-disable-line const fs = require( 'fs' ); const grunt = require( 'grunt' ); const md5 = require( 'md5' ); // constants const EXCLUDE_PATTERNS = [ // patterns that have no code that should be linted '../babel', '../decaf', '../phet-android-app', '../phet-info', '../phet-io-client-guides', '../phet-io-website', '../phet-io-wrapper-arithmetic', '../phet-io-wrapper-hookes-law-energy', '../phet-ios-app', '../smithers', '../tasks' ]; /** * Lints the specified repositories. * @public * * @returns {Promise} - results from linting files, see ESLint.lintFiles */ const lint = async ( patterns, options ) => { options = _.assignIn( { cache: true, format: false, // append an extra set of rules for formatting code. fix: false, // whether fixes should be written to disk warn: true // whether errors should reported with grunt.warn }, options ); // filter out all unlintable pattern. An unlintable repo is one that has no `js` in it, so it will fail when trying to // lint it. Also, if the user doesn't have some repos checked out, those should be skipped patterns = patterns.filter( pattern => !EXCLUDE_PATTERNS.includes( pattern ) && fs.existsSync( pattern ) ); // 1. Create an instance with the `fix` option. const eslintConfig = { // optional auto-fix fix: options.fix, // Caching only checks changed files or when the list of rules is changed. Changing the implementation of a // custom rule does not invalidate the cache. Caches are declared in .eslintcache files in the directory where // grunt was run from. cache: options.cache, // Where to store the target-specific cache file cacheLocation: `../chipper/eslint/cache/${md5( patterns.join( ',' ) )}.eslintcache`, ignorePath: '../chipper/eslint/.eslintignore', resolvePluginsRelativeTo: '../chipper/', // Our custom rules live here rulePaths: [ '../chipper/eslint/rules' ] }; if ( options.format ) { eslintConfig.baseConfig = { extends: [ '../chipper/eslint/format_eslintrc.js' ] }; } const eslint = new ESLint( eslintConfig ); grunt.verbose.writeln( `linting: ${patterns.join( ', ' )}` ); // 2. Lint files. This doesn't modify target files. const results = await eslint.lintFiles( patterns ); // 3. Modify the files with the fixed code. if ( options.fix ) { await ESLint.outputFixes( results ); } // 4. Parse the results. const totalWarnings = _.sum( results.map( result => result.warningCount ) ); const totalErrors = _.sum( results.map( result => result.errorCount ) ); // 5. Output results on errors. if ( totalWarnings + totalErrors > 0 ) { const formatter = await eslint.loadFormatter( 'stylish' ); const resultText = formatter.format( results ); console.log( resultText ); options.warn && grunt.fail.warn( `${totalErrors} errors and ${totalWarnings} warnings` ); } return results; }; // Mark the version so that the pre-commit hook will only try to use the promise-based API, this means // it won't run lint precommit hook on SHAs before the promise-based API lint.chipperAPIVersion = 'promises1'; module.exports = lint;
JavaScript
0
@@ -14,17 +14,17 @@ 2017-202 -0 +1 , Univer
e29383dd868ca72ae80a478837373a85cc5cab74
add QA to list of sims that should not be linted
js/grunt/lint.js
js/grunt/lint.js
// Copyright 2017-2021, University of Colorado Boulder /** * Runs the lint rules on the specified files. * * @author Sam Reid (PhET Interactive Simulations) */ 'use strict'; // modules const _ = require( 'lodash' ); // eslint-disable-line require-statement-match const { ESLint } = require( 'eslint' ); // eslint-disable-line const fs = require( 'fs' ); const grunt = require( 'grunt' ); const md5 = require( 'md5' ); // constants const EXCLUDE_PATTERNS = [ // patterns that have no code that should be linted '../babel', '../decaf', '../phet-android-app', '../phet-info', '../phet-io-client-guides', '../phet-io-website', '../phet-io-wrapper-arithmetic', '../phet-io-wrapper-hookes-law-energy', '../phet-ios-app', '../smithers', '../tasks' ]; /** * Lints the specified repositories. * @public * * @returns {Promise} - results from linting files, see ESLint.lintFiles */ const lint = async ( patterns, options ) => { options = _.assignIn( { cache: true, format: false, // append an extra set of rules for formatting code. fix: false, // whether fixes should be written to disk warn: true // whether errors should reported with grunt.warn }, options ); // filter out all unlintable pattern. An unlintable repo is one that has no `js` in it, so it will fail when trying to // lint it. Also, if the user doesn't have some repos checked out, those should be skipped patterns = patterns.filter( pattern => !EXCLUDE_PATTERNS.includes( pattern ) && fs.existsSync( pattern ) ); // 1. Create an instance with the `fix` option. const eslintConfig = { // optional auto-fix fix: options.fix, // Caching only checks changed files or when the list of rules is changed. Changing the implementation of a // custom rule does not invalidate the cache. Caches are declared in .eslintcache files in the directory where // grunt was run from. cache: options.cache, // Where to store the target-specific cache file cacheLocation: `../chipper/eslint/cache/${md5( patterns.join( ',' ) )}.eslintcache`, ignorePath: '../chipper/eslint/.eslintignore', resolvePluginsRelativeTo: '../chipper/', // Our custom rules live here rulePaths: [ '../chipper/eslint/rules' ] }; if ( options.format ) { eslintConfig.baseConfig = { extends: [ '../chipper/eslint/format_eslintrc.js' ] }; } const eslint = new ESLint( eslintConfig ); grunt.verbose.writeln( `linting: ${patterns.join( ', ' )}` ); // 2. Lint files. This doesn't modify target files. const results = await eslint.lintFiles( patterns ); // 3. Modify the files with the fixed code. if ( options.fix ) { await ESLint.outputFixes( results ); } // 4. Parse the results. const totalWarnings = _.sum( results.map( result => result.warningCount ) ); const totalErrors = _.sum( results.map( result => result.errorCount ) ); // 5. Output results on errors. if ( totalWarnings + totalErrors > 0 ) { const formatter = await eslint.loadFormatter( 'stylish' ); const resultText = formatter.format( results ); console.log( resultText ); options.warn && grunt.fail.warn( `${totalErrors} errors and ${totalWarnings} warnings` ); } return results; }; // Mark the version so that the pre-commit hook will only try to use the promise-based API, this means // it won't run lint precommit hook on SHAs before the promise-based API lint.chipperAPIVersion = 'promises1'; module.exports = lint;
JavaScript
0
@@ -731,24 +731,35 @@ t-ios-app',%0A + '../QA',%0A '../smithe
db53532fe58179e4bedb18bffb99942d6bbddf32
Update index.js
js/main/index.js
js/main/index.js
(function(win, $) { var items = []; var $el; var init = function() { $el = $('div[node-type="apps"]'); appTodo(); }; var appTodo = function() { var numobj = $el.find('b[node-type="num"]'); var partMash=$el.find('div[node-type="sm"]'); var mask= $('.screen_mask'); var group = new Group(); group.callback(function(mistake,index,compound,result){ if(!mistake){ numobj.text(result[2]); renderNumArea(index,compound,result); }else{ mask.show(); } }); group.setDefine(function(){ partMash.hide(); numobj.text(result[0]); }); var renderNumArea=function(){ var color=''; return function(index,compound,result){ color || (color=getColor()); partMash.eq(index).show().css('background-color','#'+color); if(compound){ color=getColor(); } }; }(); $el.find('a[node-type="btn-l"]').tap(function() { group.left(); // numobj.text('L'); }) $el.find('a[node-type="btn-r"]').tap(function() { group.right(); // numobj.text('R'); }); mask.find('a.errbtn').tap(function(){ group.reset(); }); }; var getColor=function(){ var colors=["ff9800","e65100","795548","b0120a","c2185b","f57c00","#dd2c00","e91e63"]; var colorLen=colors.length; var index=0; return function(){ var color=colors[index]; index = (index+1)%colorLen; console.log(index) return color; } }(); var Group = function() { this.flag = [0, 0]; this.result=[0,0,0]; this._callback=null; this.mistake=false;//错误 }; $.extend(Group.prototype, { init: function() { }, left: function() { var flag = this.flag; var result=this.result; if(this._check(0)){ flag[0] = 1; result[0] = this.result[0]+1; } this._result(0); }, right: function() { var flag = this.flag; var result=this.result; if(this._check(1)){ flag[1] = 1; result[1] = this.result[1]+1; } this._result(1); }, _check: function(inx) { var val=this.flag[inx]; var flag; if(val>0){ flag = false; this.mistake = true; } flag = true; return flag; }, _result:function(inx){ var flag=this.flag; var result=this.result; var compound=false; //一对成功 if(!this.mistake && (flag[0] & flag[1])){ this.flag=[0,0]; result[2] = result[2]+1; compound=true; } this._callback(this.mistake,inx,compound,result); }, //flag [true,false] callback: function(fn) { this._callback = fn; }, reset: function(fn) { this.flag = [0, 0]; this.result=[0,0,0]; this._callback=null; this.mistake=false;//错误 this._defineFn(); }, setDefine:function(fn){ this._defineFn= fn|| function(){}; }, getResult:function(){ return this.result; } }); init(); })(this, $);
JavaScript
0.000002
@@ -1115,28 +1115,33 @@ =%22btn-l%22%5D'). +on(' tap -( +', function() %7B @@ -1253,20 +1253,25 @@ n-r%22%5D'). +on(' tap -( +', function @@ -1381,12 +1381,17 @@ n'). +on(' tap -( +', func
6af42acf6a29afefaae5001974c1b3fa00cb4869
switch to bolus groups for managing boluses enter() and exit() selections; add bolus.x for easy getting of x-coords
js/plot/bolus.js
js/plot/bolus.js
module.exports = function(pool, opts) { var opts = opts || {}; var defaults = { xScale: pool.xScale().copy(), width: 8 }; _.defaults(opts, defaults); function carbs(selection) { selection.each(function(currentData) { var rects = d3.select(this) .selectAll('rect') .data(currentData, function(d) { // leveraging the timestamp of each datapoint as the ID for D3's binding return d.normalTime; }); rects.enter() .append('rect') .attr({ 'x': function(d) { return opts.xScale(Date.parse(d.normalTime)) - opts.width/2; }, 'y': function(d) { return opts.yScale(d.value); }, 'width': opts.width, 'height': function(d) { return opts.yScale.range()[0] - opts.yScale(d.value); }, 'class': 'd3-rect-bolus d3-bolus', 'id': function(d) { return d.normalTime + ' ' + d.value; } }); rects.exit().remove(); }); } return carbs; };
JavaScript
0
@@ -174,20 +174,20 @@ unction -carb +bolu s(select @@ -246,20 +246,22 @@ var -rect +boluse s = d3.s @@ -292,20 +292,17 @@ ectAll(' -rect +g ')%0A @@ -469,20 +469,40 @@ ;%0A -rect +var bolusGroups = boluse s.enter( @@ -511,16 +511,150 @@ +.append('g')%0A .attr(%7B%0A 'class': 'd3-bolus-group'%0A %7D);%0A var top = opts.yScale.range()%5B0%5D;%0A bolusGroups .append( @@ -729,60 +729,18 @@ urn -opts.xScale(Date.parse(d.normalTime)) - opts.width/2 +bolus.x(d) ;%0A @@ -917,38 +917,19 @@ return +t op -ts.yScale.range()%5B0%5D - opts. @@ -1080,16 +1080,55 @@ d.value + + ' ' + d.recommended + ' recommended' ;%0A @@ -1155,14 +1155,14 @@ - rect +boluse s.ex @@ -1192,22 +1192,121 @@ %7D%0A + %0A -return carb +bolus.x = function(d) %7B%0A return opts.xScale(Date.parse(d.normalTime)) - opts.width/2;%0A %7D;%0A%0A return bolu s; %0A
5a2edebc4711c630ac5965c98ef37bfefe8f4f9a
Generalize clipping for multiple tilesets
js/tilemapper.js
js/tilemapper.js
(function() { var TileMap = function(options) { this.canvas = options.canvas; this.context = this.canvas.getContext('2d'); this.images = options.images; this.map = options.map; // Normalize layers to a zero indexed map this.map.layers.forEach(function(layer) { layer.data.forEach(function(number, index, layer) { layer[index] = number - 1; }); }); } TileMap.prototype.clip = function(index) { // TODO Generalize for multiple tilesets var tileset = this.map.tilesets[0]; var row = Math.floor((index * tileset.tilewidth) / tileset.imagewidth); return { image: this.images[0], x: (index * tileset.tilewidth) % tileset.imagewidth, y: (row * tileset.tileheight) % tileset.imageheight, width: tileset.tilewidth, height: tileset.tileheight, } } TileMap.prototype.draw = function() { this.map.layers.forEach(function(layer) { layer.data.forEach(function(number, index) { var x = index % layer.width; var y = Math.floor(index / layer.width); var clip = this.clip(number); this.context.drawImage(clip.image, clip.x, clip.y, clip.width, clip.height, x * Map.tilewidth, y * Map.tileheight, Map.tilewidth, Map.tileheight); }, this) }, this); } window.TileMap = TileMap; })();
JavaScript
0.000002
@@ -139,45 +139,375 @@ his. -images = options.images;%0A this.map +map = options.map;%0A%0A // Add each image to the appropriate tileset and patch a function to verify%0A // it's index boundaries%0A this.map.tilesets.forEach(function(tileset, index, tilesets) %7B%0A var tiles = Math.floor(tileset.imagewidth / tileset.tilewidth) *%0A Math.floor(tileset.imageheight / tileset.tileheight);%0A%0A tilesets%5Bindex%5D.image = o @@ -505,35 +505,353 @@ image = options. +i ma -p +ges%5Bindex%5D;%0A tilesets%5Bindex%5D.min = tileset.firstgid - 1;%0A tilesets%5Bindex%5D.max = tilesets%5Bindex%5D.min + tiles;%0A%0A // Check whether the 'number' is in this tileset or not%0A tilesets%5Bindex%5D.inside = function(number) %7B%0A return number %3E= this.min && this.max %3E= number;%0A %7D.bind(tileset);%0A %7D) ;%0A%0A // Normal @@ -1098,56 +1098,112 @@ -// TODO Generalize for multiple tilesets +var tileset = null;%0A this.map.tilesets.forEach(function(set) %7B%0A if (set.inside(index)) %7B %0A -var + til @@ -1213,28 +1213,27 @@ t = -this.map.tilesets%5B0%5D +set;%0A %7D%0A %7D) ;%0A @@ -1338,21 +1338,20 @@ e: t -his +ileset .image -s%5B0%5D ,%0A
f2e5a9884eed39603e61b83a56beed70c80c83ed
Replace method once with one and update jQuery call accordingly
js/web-worker.js
js/web-worker.js
/*eslint no-native-reassign:0 */ (function ($) { 'use strict'; var WebWorker = null, BrowserWorker = null, context = null, className = null, defaultContext = window, defaultClassName = 'WebWorker', Event = null, eventPrefix = 'webworker:', Error = null; var windowConsole = window.console, console = null; console = { log: function (data, suppressNoise) { suppressNoise = suppressNoise || false; if (suppressNoise) { windowConsole.log(data); } else { windowConsole.log({ '>>>>>>>> internal': true, 'log': data }); } return; }, warn: windowConsole.warn, error: windowConsole.error }; context = context || defaultContext; className = className || defaultClassName; WebWorker = context[className] || null; if (WebWorker !== null) { return; } BrowserWorker = window.Worker; WebWorker = function () { this._constructor.apply(this, arguments); return; }; WebWorker.prototype.$ = null; WebWorker.prototype._workerUrl = null; WebWorker.prototype._workerBlobUrl = null; WebWorker.prototype._workerScript = null; WebWorker.prototype._worker = null; WebWorker.prototype._lastError = null; WebWorker.prototype._hasLoaded = false; WebWorker.prototype._constructor = function (opts) { var $scriptElement = null, scriptContents = null, workerUrl = null; this.$ = $(this); opts = opts || null; if (opts === null) { this.throwError(Error.INVALID_ARGUMENTS); return; } if (typeof opts === 'string') { opts = $.trim(opts); try { $scriptElement = $(opts); } catch (err) { // Cannot be resolved as a selector } if ($scriptElement !== null && $scriptElement.length > 0) { // Matching script element found // Cache its contents scriptContents = $scriptElement.text(); this._workerScript = scriptContents; } else { workerUrl = opts; } } this._workerUrl = workerUrl; this.trigger(Event.INITIALIZED); return; }; WebWorker.prototype.getUrl = function () { return this._workerUrl; }; WebWorker.prototype.getBlobUrl = function () { return this._workerBlobUrl; }; WebWorker.prototype.load = function () { var worker = this, workerUrl = null, onScriptLoaded = null; workerUrl = worker.getUrl() || null; onScriptLoaded = function () { var blob = null, scriptContents = null; scriptContents = worker._workerScript; blob = new window.Blob([scriptContents], { type: "text/javascript" }); worker._workerBlobUrl = window.URL.createObjectURL(blob); worker._createWorker(); return; }; if (workerUrl === null) { // Script already available onScriptLoaded(); } else { // Ajax request $.ajax({ async: true, url: workerUrl, dataType: 'text', crossDomain: true, success: function (responseText) { worker._workerScript = responseText; onScriptLoaded(); return; }, error: function (event) { // TODO: trigger error event return; } }); } return worker; }; WebWorker.prototype._createWorker = function () { var worker = this; worker._worker = new BrowserWorker(worker._workerUrl); // TODO: remove after work is done worker.on(Event.WORKER_LOADED, function () { console.log('worker has loaded'); return; }); $(worker._worker).on('message', function (event) { console.log(event, true); var actionMessage = event.originalEvent.data; if ((typeof actionMessage === 'object') && ('action' in actionMessage) && actionMessage.action === 'trigger') { worker.trigger.apply(worker, actionMessage.data.args); return; } worker.trigger.apply(worker, [event]); return; }); worker._assignEventHandlers(); worker._initializeWorker(); return; }; WebWorker.prototype._assignEventHandlers = function () { console.log('pending >> assign event handlers'); return; }; WebWorker.prototype.start = function () { console.log('pending >> start the worker'); var worker = this; return worker; }; WebWorker.prototype._initializeWorker = function () { this._worker.postMessage({ action: 'init', data: { args: [] } }); return; }; WebWorker.prototype.terminate = function () { var worker = this, nativeWorker = worker._worker || null; if (nativeWorker !== null) { nativeWorker.terminate(); } return; }; WebWorker.prototype.on = function () { var $worker = this.$; $worker.on.apply($worker, arguments); return this; }; WebWorker.prototype.once = function () { var $worker = this.$; $worker.once.apply($worker, arguments); return this; }; WebWorker.prototype.off = function () { var $worker = this.$; $worker.off.apply($worker, arguments); return this; }; WebWorker.prototype.trigger = function (event) { var worker = this, $worker = null, eventType = null, eventArgs = null; if (typeof event === 'string') { eventType = event; event = new $.Event(eventType); } event.worker = worker; eventArgs = [event]; if (arguments.length > 1) { eventArgs = eventArgs.concat(Array.slice(arguments, 1)); } $worker = worker.$; $worker.trigger.apply($worker, eventArgs); return this; }; WebWorker.prototype.throwError = function (error, throwException) { error = error || Error.UNKNOWN; throwException = throwException || false; this._lastError = error; WebWorker._lastError = error; console.log('error'); console.log(error); console.log('pending >>> trigger error event'); if (throwException) { throw new window.Error(error); } return; }; WebWorker.prototype.getLastError = function () { return this._lastError; }; // Static WebWorker._lastError = null; Event = { INITIALIZED: 'initialized', WORKER_LOADING: 'worker-loading', WORKER_LOADED: 'worker-loaded', WORKER_STARTING: 'worker-starting', WORKER_STARTED: 'worker-started', WORKER_TERMINATED: 'worker-terminated' }; WebWorker.Event = Event; // Add eventPrefix to all event types for (var key in Event) { Event[key] = eventPrefix + Event[key]; } Error = { UNKNOWN: "An unknown error occured.", INVALID_ARGUMENTS: "Invalid arguments were supplied to this method.", WORKER_NOT_LOADED: "Unable to load worker." }; WebWorker.Error = Error; WebWorker.throwError = WebWorker.prototype.throwError; // TODO: Make this method more manageable and consistent with the way jQuery handles things. WebWorker.noConflict = function (context, className) { context = context || defaultContext; className = className || defaultClassName; context[className] = WebWorker; return WebWorker; }; WebWorker.noConflict(context, className); return; })(jQuery);
JavaScript
0
@@ -5860,17 +5860,16 @@ otype.on -c e = func @@ -5926,17 +5926,16 @@ orker.on -c e.apply(
4f9209feb020bf11c260195e7c8960a33f3a80fa
Change the input in the effects test to a text input. This fixes failing tests in IE8 that could not focus the input.
tests/unit/effects/effects_core.js
tests/unit/effects/effects_core.js
(function($) { function present( value, array, message ) { QUnit.push( jQuery.inArray( value, array ) !== -1 , value, array, message ); } function notPresent( value, array, message ) { QUnit.push( jQuery.inArray( value, array ) === -1 , value, array, message ); } // minDuration is used for "short" animate tests where we are only concerned about the final var minDuration = 15, // duration is used for "long" animates where we plan on testing properties during animation duration = 200, // mid is used for testing in the "middle" of the "duration" animations mid = duration / 2; module( "effects.core" ); test( "Immediate Return Conditions", function() { var hidden = $( "div.hidden" ), count = 0; expect( 3 ); hidden.hide( "blind", function() { equal( ++count, 1, "Hide on hidden returned immediately" ); }).show().show( "blind", function() { equal( ++count, 2, "Show on shown returned immediately" ); }); equal( ++count, 3, "Both Functions worked properly" ); }); test( "createWrapper and removeWrapper retain focused elements (#7595)", function() { expect( 2 ); var test = $( "div.hidden" ).show(), input = $( "<input>" ).appendTo( test ).focus(); $.effects.createWrapper( test ); equal( document.activeElement, input[ 0 ], "Active element is still input after createWrapper" ); $.effects.removeWrapper( test ); equal( document.activeElement, input[ 0 ], "Active element is still input after removeWrapper" ); }); module( "effects.core: animateClass" ); asyncTest( "animateClass works with borderStyle", function() { var test = $("div.animateClass"), count = 0; expect(3); test.toggleClass("testAddBorder", minDuration, function() { test.toggleClass("testAddBorder", minDuration, function() { equal( test.css("borderLeftStyle"), "none", "None border set" ); start(); }); equal( test.css("borderLeftStyle"), "solid", "None border not immedately set" ); }); equal( test.css("borderLeftStyle"), "solid", "Solid border immedately set" ); }); asyncTest( "animateClass works with colors", function() { var test = $("div.animateClass"), count = 0; expect(2); test.toggleClass("testChangeBackground", duration, function() { present( test.css("backgroundColor"), [ "#ffffff", "#fff", "rgb(255, 255, 255)" ], "Color is final" ); start(); }); setTimeout(function() { var color = test.css("backgroundColor"); notPresent( color, [ "#000000", "#ffffff", "#000", "#fff", "rgb(0, 0, 0)", "rgb(255,255,255)" ], "Color is not endpoints in middle." ); }, mid); }); asyncTest( "animateClass works with children", function() { var test = $("div.animateClass"), h2 = test.find("h2"); expect(4); setTimeout(function() { notPresent( h2.css("fontSize"), ["10px","20px"], "Font size is neither endpoint when in middle."); }, mid); test.toggleClass("testChildren", { children: true, duration: duration, complete: function() { equal( h2.css("fontSize"), "20px", "Text size is final during complete"); test.toggleClass("testChildren", duration, function() { equal( h2.css("fontSize"), "10px", "Text size revertted after class removed"); start(); }); setTimeout(function() { equal( h2.css("fontSize"), "20px", "Text size unchanged during animate with children: undefined" ); }, mid); }}); }); asyncTest( "animateClass clears style properties when stopped", function() { var test = $("div.animateClass"), style = test[0].style, orig = style.cssText; expect( 2 ); test.addClass( "testChangeBackground", duration ); notEqual( orig, style.cssText, "cssText is not the same after starting animation" ); test.stop( true, true ); equal( orig, $.trim( style.cssText ), "cssText is the same after stopping animation midway" ); start(); }); asyncTest( "animateClass: css and class changes during animation are not lost (#7106)", function() { var test = $( "div.ticket7106" ); // add a class and change a style property after starting an animated class test.addClass( "animate", minDuration, animationComplete ) .addClass( "testClass" ) .height( 100 ); // ensure the class stays and that the css property stays function animationComplete() { ok( test.hasClass( "testClass" ), "class change during animateClass was not lost" ); equal( test.height(), 100, "css change during animateClass was not lost" ); start(); } }); $.each( $.effects.effect, function( effect ) { if ( effect === "transfer" ) { return; } module( "effect."+effect ); asyncTest( "show/hide", function() { var hidden = $( "div.hidden" ); expect( 8 ); var count = 0, test = 0; function queueTest( fn ) { count++; var point = count; return function( next ) { test++; equal( point, test, "Queue function fired in order" ); if ( fn ) { fn(); } else { setTimeout( next, minDuration ); } }; } hidden.queue( queueTest() ).show( effect, minDuration, queueTest(function() { equal( hidden.css("display"), "block", "Hidden is shown after .show(\"" +effect+ "\", time)" ); })).queue( queueTest() ).hide( effect, minDuration, queueTest(function() { equal( hidden.css("display"), "none", "Back to hidden after .hide(\"" +effect+ "\", time)" ); })).queue( queueTest(function(next) { deepEqual( hidden.queue(), ["inprogress"], "Only the inprogress sentinel remains"); start(); })); }); asyncTest( "relative width & height - properties are preserved", function() { var test = $("div.relWidth.relHeight"), width = test.width(), height = test.height(), cssWidth = test[0].style.width, cssHeight = test[0].style.height; expect( 4 ); test.toggle( effect, minDuration, function() { equal( test[0].style.width, cssWidth, "Inline CSS Width has been reset after animation ended" ); equal( test[0].style.height, cssHeight, "Inline CSS Height has been rest after animation ended" ); start(); }); equal( test.width(), width, "Width is the same px after animation started" ); equal( test.height(), height, "Height is the same px after animation started" ); }); }); })(jQuery);
JavaScript
0
@@ -1144,16 +1144,28 @@ %22%3Cinput + type='text' %3E%22 ).app
18c25627943de8722fd343f360fe7def5f658718
Use static member construct.
conduit.js
conduit.js
// An evented message queue. const Queue = require('avenue') const Interrupt = require('interrupt') const Destructible = require('destructible') const Flood = require('./flood') class Conduit { constructor () { this._destructible = new Destructible('conduit') this._identifier = 0n this._written = 0n this._read = 0n this._queues = {} } destroy () { this._destructible.destroy() } pump (shifter, queue, responder) { const throttle = new Flood(responder) this._destructible.durable('responder', throttle.promise) this._queue = queue this._destructible.durable('queue', shifter.pump(async (entry) => { if (entry == null) { for (const key in this._queues) { const split = key.split(':') if (split[1] == 'inbox') { await this._receive({ module: 'conduit', to: split[0], method: 'envelope', series: this._read, identifier: split[2], body: null }) break } } for (const key in this._queues) { await this._queues[key].queue.shifter().end } this._queue.push(null) throttle.destroy() } else if (entry.module == 'conduit') { Conduit.Error.assert(this._read.toString(16) == entry.series, 'series.mismatch', { read: this._read.toString(16), written: this._written.toString(16), entry: entry }) this._read++ switch (entry.to) { case 'server': switch (entry.method) { case 'connect': const down = this._queues['server:outbox:' + entry.identifier] = new Queue const request = { entry: entry, queue: null, shifter: null } request.queue = down if (entry.queue) { const up = new Queue this._queues[`server:inbox:${entry.identifier}`] = up request.shifter = up.shifter() } this._destructible.ephemeral([ 'server', 'outbox', entry.identifier ], request.queue.shifter().pump(async (subEntry) => { if (subEntry == null) { delete this._queues[`server:outbox:${entry.identifier}`] } this._queue.push({ module: 'conduit', to: 'client', method: 'envelope', series: (this._written++).toString(16), identifier: entry.identifier, body: subEntry }) })) throttle.respond(request) break case 'envelope': const identifier = `server:inbox:${entry.identifier}` this._queues[identifier].push(envelope.body) if (envelope.body == null) { delete this._queues[identifier] } break } break case 'client': switch (entry.method) { case 'envelope': this._queues[`client:inbox:${entry.identifier}`].push(entry.body) if (entry.body == null) { delete this._queues[`client:inbox:${entry.identifier}`] } } break } } })) return this._destructible.promise } async request (header, splicer = false, queue = false) { const identifier = (this._identifier++).toString(16) const inbox = this._queues[`client:inbox:${identifier}`] = new Queue const response = { queue: null, shifter: inbox.shifter() } const request = { header, splicer, queue } if (queue) { const outbox = this._queues[`client:outbox:${identifier}`] = response.queue = new Queue this._destructible.ephemeral([ 'client', 'outbox', indentifier ], (entry) => { if (entry == null) { delete this._queues[`client:outbox:${identifier}`] } else { Conduit.Error.assert(this._queues[`client:outbox:${identifier}`], 'missing.outbox') } this._queue.push({ module: 'conduit', to: 'server', method: 'envelope', series: this._written = increment(this._written), identifier: identifier, body: envelope }) }) } this._queue.push({ module: 'conduit', to: 'server', method: 'connect', series: (this._written++).toString(16), identifier: identifier, body: request }) if (splicer || queue) { return response } const result = await response.shifter.shift() response.shifter.destroy() return result } } Conduit.Error = Interrupt.create('Conduit.Error') module.exports = Conduit
JavaScript
0
@@ -188,16 +188,70 @@ nduit %7B%0A + static Error = Interrupt.create('Conduit.Error')%0A%0A cons @@ -5876,59 +5876,8 @@ %0A%7D%0A%0A -Conduit.Error = Interrupt.create('Conduit.Error')%0A%0A modu
21394cb5e53bdbba7f66be02944a808f1d6dab0b
check to make sure cached test page appears
tests/unit/select/select_cached.js
tests/unit/select/select_cached.js
/* * mobile select unit tests */ (function($){ var resetHash; resetHash = function(timeout){ $.testHelper.openPage( location.hash.indexOf("#default") >= 0 ? "#" : "#default" ); }; // https://github.com/jquery/jquery-mobile/issues/2181 asyncTest( "dialog sized select should alter the value of its parent select", function(){ var selectButton, value; $.testHelper.pageSequence([ resetHash, function(){ $.mobile.changePage( "cached.html" ); }, function(){ selectButton = $( "#cached-page-select" ).siblings( 'a' ); selectButton.click(); }, function(){ ok( $.mobile.activePage.hasClass('ui-dialog-page'), "the dialog came up" ); var option = $.mobile.activePage.find( "li a" ).not(":contains('" + selectButton.text() + "')").last(); value = option.text(); option.click(); }, function(){ same( value, selectButton.text(), "the selected value is propogated back to the button text" ); start(); } ]); }); // https://github.com/jquery/jquery-mobile/issues/2181 asyncTest( "dialog sized select should prevent the removal of its parent page from the dom", function(){ var selectButton, parentPageId; expect( 2 ); $.testHelper.pageSequence([ resetHash, function(){ $.mobile.changePage( "cached.html" ); }, function(){ selectButton = $.mobile.activePage.find( "#cached-page-select" ).siblings( 'a' ); parentPageId = $.mobile.activePage.attr( 'id' ); same( $("#" + parentPageId).length, 1, "establish the parent page exists" ); selectButton.click(); }, function(){ same( $( "#" + parentPageId).length, 1, "make sure parent page is still there after opening the dialog" ); $.mobile.activePage.find( "li a" ).last().click(); }, start ]); }); asyncTest( "dialog sized select shouldn't rebind its parent page remove handler when closing, if the parent page domCache option is true", function(){ expect( 3 ); $.testHelper.pageSequence([ resetHash, function(){ $.mobile.changePage( "cached-dom-cache-true.html" ); }, function(){ $.mobile.activePage.find( "#domcache-page-select" ).siblings( 'a' ).click(); }, function(){ ok( $.mobile.activePage.hasClass('ui-dialog-page'), "the dialog came up" ); $.mobile.activePage.find( "li a" ).last().click(); }, function(){ ok( $.mobile.activePage.is( "#dialog-select-parent-domcache-test" ), "the dialog closed" ); $.mobile.changePage( $( "#default" ) ); }, function(){ same( $("#dialog-select-parent-domcache-test").length, 1, "make sure the select parent page is still cached in the dom after changing page" ); start(); } ]); }); asyncTest( "menupage is removed when the parent page is removed", function(){ var dialogCount = $(":jqmData(role='dialog')").length; $.testHelper.pageSequence([ resetHash, function(){ $.mobile.changePage( "uncached-dom-cached-false.html" ); }, function(){ same( $(":jqmData(role='dialog')").length, dialogCount + 1 ); window.history.back(); }, function() { same( $(":jqmData(role='dialog')").length, dialogCount ); start(); } ]); }); })(jQuery);
JavaScript
0
@@ -474,32 +474,125 @@ %0A%09%09%09function()%7B%0A +%09%09%09%09ok( $.mobile.activePage.is(%22#dialog-select-parent-cache-test%22), %22cached page appears%22 );%0A %09%09%09%09selectButton
fdc65a625824c545bd44a33764be3d5bd94b1e3c
improve test to stop using deprecated syntax
tests/unit/services/stripe-test.js
tests/unit/services/stripe-test.js
/* global sinon, Stripe */ import Ember from 'ember'; import { moduleFor, test } from 'ember-qunit'; import QUnit from 'qunit'; moduleFor('service:stripe', 'StripeService', { // Specify the other units that are required for this test. // needs: ['service:foo'] }); var cc = { number: 4242424242424242, exp_year: 2018, exp_month: 10, cvc: 123, address_zip: 12345 }; test('card.createToken sets the token and returns a promise', function(assert) { var service = this.subject(); var response = { id: 'the_token' }; var createToken = sinon.stub(Stripe.card, 'createToken', function(card, cb) { assert.equal(card, cc, 'called with sample creditcard'); cb(200, response); }); return service.card.createToken(cc) .then(function(res) { assert.equal(res.id, 'the_token'); createToken.restore(); }); }); test('card.createToken rejects the promise if Stripe errors', function(assert) { var service = this.subject(); var response = { error : { code: "invalid_number", message: "The 'exp_month' parameter should be an integer (instead, is Month).", param: "exp_month", type: "card_error" } }; var createToken = sinon.stub(Stripe.card, 'createToken', function(card, cb) { cb(402, response); }); return service.card.createToken(cc) .then(undefined, function(res) { assert.equal(res, response, 'error passed'); createToken.restore(); }); }); test('createToken syntax is still supported', function(assert) { var service = this.subject(); var response = { id: 'the_token' }; var createToken = sinon.stub(Stripe.card, 'createToken', function(card, cb) { assert.equal(card, cc, 'called with sample creditcard'); cb(200, response); }); return service.createToken(cc) .then(function(res) { assert.equal(res.id, 'the_token'); createToken.restore(); }); }); // Bank accounts var ba = { country: 'US', routingNumber: '123124112', accountNumber: '125677688', }; test('bankAccount.createToken sets the token and returns a promise', function(assert) { var service = this.subject(); var response = { id: 'the_token' }; var createBankAccountToken = sinon.stub( Stripe.bankAccount, 'createToken', function(bankAccount, cb) { assert.equal(bankAccount, ba, 'called with sample bankAccount'); cb(200, response); } ); return service.bankAccount.createToken(ba) .then(function(res) { assert.equal(res.id, 'the_token'); createBankAccountToken.restore(); }); }); test('bankAccount.createToken rejects the promise if Stripe errors', function(assert) { var service = this.subject(); var response = { error : { code: "invalid_number", message: "The 'exp_month' parameter should be an integer (instead, is Month).", param: "exp_month", type: "bank_account_errror" } }; var createBankAccountToken = sinon.stub( Stripe.bankAccount, 'createToken', function(bankAccount, cb) { cb(402, response); } ); return service.bankAccount.createToken(ba) .then(undefined, function(res) { assert.equal(res, response, 'error passed'); createBankAccountToken.restore(); }); }); // LOG_STRIPE_SERVICE is set to true in dummy app test('it logs when LOG_STRIPE_SERVICE is set in env config', function(assert) { var service = this.subject(); var info = sinon.stub(Ember.Logger, 'info'); var createToken = sinon.stub(Stripe.card, 'createToken', function(card, cb) { var response = { id: 'my id' }; cb(200, response); }); return service.createToken(cc) .then(function(err) { assert.ok(info.calledWith('StripeService: getStripeToken - card:', cc)); createToken.restore(); info.restore(); }); }); /** * @todo figure out how to change env variables at runtime */ QUnit.skip('it logs if LOG_STRIPE_SERVICE is false'); QUnit.skip('it throws an error if config.stripe.publishableKey is not set');
JavaScript
0
@@ -3618,32 +3618,37 @@ return service. +card. createToken(cc)%0A