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
7941195033156cc24ff63c9214aa42f6876ab8ad
Allow breakpoints in editor to always update (#6486)
src/components/Editor/Breakpoint.js
src/components/Editor/Breakpoint.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */ // @flow import React, { Component } from "react"; import ReactDOM from "react-dom"; import classnames from "classnames"; import Svg from "../shared/Svg"; import { getDocument, toEditorLine } from "../../utils/editor"; import { features } from "../../utils/prefs"; import type { Source, Breakpoint as BreakpointType } from "../../types"; const breakpointSvg = document.createElement("div"); ReactDOM.render(<Svg name="breakpoint" />, breakpointSvg); function makeMarker(isDisabled: boolean) { const bp = breakpointSvg.cloneNode(true); bp.className = classnames("editor new-breakpoint", { "breakpoint-disabled": isDisabled, "folding-enabled": features.codeFolding }); return bp; } type Props = { breakpoint: BreakpointType, selectedSource: Source, editor: Object }; class Breakpoint extends Component<Props> { addBreakpoint: Function; constructor() { super(); } addBreakpoint = () => { const { breakpoint, editor, selectedSource } = this.props; // Hidden Breakpoints are never rendered on the client if (breakpoint.hidden) { return; } // NOTE: we need to wait for the breakpoint to be loaded // to get the generated location if (!selectedSource || breakpoint.loading) { return; } const sourceId = selectedSource.id; const line = toEditorLine(sourceId, breakpoint.location.line); editor.codeMirror.setGutterMarker( line, "breakpoints", makeMarker(breakpoint.disabled) ); editor.codeMirror.addLineClass(line, "line", "new-breakpoint"); if (breakpoint.condition) { editor.codeMirror.addLineClass(line, "line", "has-condition"); } else { editor.codeMirror.removeLineClass(line, "line", "has-condition"); } }; shouldComponentUpdate(nextProps: any) { const { editor, breakpoint, selectedSource } = this.props; return ( editor !== nextProps.editor || breakpoint.disabled !== nextProps.breakpoint.disabled || breakpoint.hidden !== nextProps.breakpoint.hidden || breakpoint.condition !== nextProps.breakpoint.condition || breakpoint.loading !== nextProps.breakpoint.loading || selectedSource !== nextProps.selectedSource ); } componentDidMount() { this.addBreakpoint(); } componentDidUpdate() { this.addBreakpoint(); } componentWillUnmount() { const { editor, breakpoint, selectedSource } = this.props; if (!selectedSource) { return; } if (breakpoint.loading) { return; } const sourceId = selectedSource.id; const doc = getDocument(sourceId); if (!doc) { return; } const line = toEditorLine(sourceId, breakpoint.location.line); // NOTE: when we upgrade codemirror we can use `doc.setGutterMarker` if (doc.setGutterMarker) { doc.setGutterMarker(line, "breakpoints", null); } else { editor.codeMirror.setGutterMarker(line, "breakpoints", null); } doc.removeLineClass(line, "line", "new-breakpoint"); doc.removeLineClass(line, "line", "has-condition"); } render() { return null; } } export default Breakpoint;
JavaScript
0
@@ -1967,473 +1967,8 @@ %7D;%0A%0A - shouldComponentUpdate(nextProps: any) %7B%0A const %7B editor, breakpoint, selectedSource %7D = this.props;%0A return (%0A editor !== nextProps.editor %7C%7C%0A breakpoint.disabled !== nextProps.breakpoint.disabled %7C%7C%0A breakpoint.hidden !== nextProps.breakpoint.hidden %7C%7C%0A breakpoint.condition !== nextProps.breakpoint.condition %7C%7C%0A breakpoint.loading !== nextProps.breakpoint.loading %7C%7C%0A selectedSource !== nextProps.selectedSource%0A );%0A %7D%0A%0A co
39366457b046806d690f83b92e9200466ba17a22
Update decompressors.js
src/decompressors.js
src/decompressors.js
/* * Decompression of gzipped files using ukyo's jsziptools.js (jz) * Requires ukyo's jsziptools.js to be in global scope when decompressing gzipped files * https://github.com/ukyo/jsziptools * http://ukyo.github.io/jsziptools/jsziptools.js */ var gzip = (function () { return { decompress: function(arrayBuffer) { var hexarr = jz.gz.decompress(arrayBuffer); return _hextostring(hexarr); }, }; function _hextostring(hexarr){ for (var w = '', i = 0, l = hexarr.length; i < l; i++) { w += String.fromCharCode(hexarr[i]) } return decodeURIComponent(escape(w)); } })(); var DECOMPRESSORS = { gz: function (x) {return gzip.decompress(x);} };
JavaScript
0.000001
@@ -1,10 +1,8 @@ -%0A%0A /*%0A* Dec
b7d525b4b776662ba0a4d75b304534e421fa3336
Add /eval command
commands.js
commands.js
module.exports = { say: function(target, user) { this.send(target); } };
JavaScript
0.000004
@@ -12,16 +12,389 @@ rts = %7B%0A + eval: function(target, user) %7B%0A var name = user.name.toLowerCase();%0A if (name !== 'mom' && name !== 'darkpoo') return;%0A this.send('%7C%7C%3E%3E ' + target);%0A try %7B%0A this.send('%7C%7C%3C%3C ' + eval(target));%0A %7D catch (e) %7B%0A this.send('%7C%7C%3C%3C error: ' + e.message);%0A var stack = '%7C%7C' + ('' + e.stack).replace(/%5Cn/g, '%5Cn%7C%7C');%0A this.send(stack);%0A %7D%0A %7D,%0A say: f
81d87a32526f858e7aaaaa7c70b7f61ee88a44d4
env.localPackage should be env.modulePackage
bin/gulp.js
bin/gulp.js
#!/usr/bin/env node 'use strict'; var gutil = require('gulp-util'); var prettyTime = require('pretty-hrtime'); var chalk = require('chalk'); var semver = require('semver'); var archy = require('archy'); var Liftoff = require('liftoff'); var taskTree = require('../lib/taskTree'); var cli = new Liftoff({ name: 'gulp', completions: require('../lib/completion') }); cli.on('require', function (name) { gutil.log('Requiring external module', chalk.magenta(name)); }); cli.on('requireFail', function (name) { gutil.log(chalk.red('Failed to load external module'), chalk.magenta(name)); }); cli.launch(handleArguments); function handleArguments(env) { var argv = env.argv; var cliPackage = require('../package'); var versionFlag = argv.v || argv.version; var tasksFlag = argv.T || argv.tasks; var tasks = argv._; var toRun = tasks.length ? tasks : ['default']; if (versionFlag) { gutil.log('CLI version', cliPackage.version); if (env.localPackage) { gutil.log('Local version', env.modulePackage.version); } process.exit(0); } if (!env.modulePath) { gutil.log(chalk.red('No local gulp install found in'), chalk.magenta(env.cwd)); gutil.log(chalk.red('Try running: npm install gulp')); process.exit(1); } if (!env.configPath) { gutil.log(chalk.red('No gulpfile found')); process.exit(1); } // check for semver difference between cli and local installation if (semver.gt(cliPackage.version, env.modulePackage.version)) { gutil.log(chalk.red('Warning: gulp version mismatch:')); gutil.log(chalk.red('Running gulp is', cliPackage.version)); gutil.log(chalk.red('Local gulp (installed in gulpfile dir) is', env.modulePackage.version)); } var gulpFile = require(env.configPath); gutil.log('Using gulpfile', chalk.magenta(env.configPath)); var gulpInst = require(env.modulePath); logEvents(gulpInst); if (process.cwd() !== env.cwd) { process.chdir(env.cwd); gutil.log('Working directory changed to', chalk.magenta(env.cwd)); } process.nextTick(function () { if (tasksFlag) { return logTasks(gulpFile, gulpInst); } gulpInst.start.apply(gulpInst, toRun); }); } function logTasks(gulpFile, localGulp) { var tree = taskTree(localGulp.tasks); tree.label = 'Tasks for ' + chalk.magenta(gulpFile); archy(tree).split('\n').forEach(function (v) { if (v.trim().length === 0) return; gutil.log(v); }); } // format orchestrator errors function formatError(e) { if (!e.err) return e.message; if (e.err.message) return e.err.message; return JSON.stringify(e.err); } // wire up logging events function logEvents(gulpInst) { gulpInst.on('task_start', function (e) { gutil.log('Starting', "'" + chalk.cyan(e.task) + "'..."); }); gulpInst.on('task_stop', function (e) { var time = prettyTime(e.hrDuration); gutil.log('Finished', "'" + chalk.cyan(e.task) + "'", 'after', chalk.magenta(time)); }); gulpInst.on('task_err', function (e) { var msg = formatError(e); var time = prettyTime(e.hrDuration); gutil.log("'" + chalk.cyan(e.task) + "'", 'errored after', chalk.magenta(time), chalk.red(msg)); }); gulpInst.on('task_not_found', function (err) { gutil.log(chalk.red("Task '" + err.task + "' was not defined in your gulpfile but you tried to run it.")); gutil.log('Please check the documentation for proper gulpfile formatting.'); process.exit(1); }); }
JavaScript
0.999998
@@ -960,21 +960,22 @@ if (env. -local +module Package)
9fba95fb65d86b955664f0df9e60cd836181f6cb
clean up linter warnings
src/components/KeyControlledList.js
src/components/KeyControlledList.js
import React from 'react' import { findDOMNode } from 'react-dom' import { find, indexOf, isEmpty, omit } from 'lodash/fp' import { getKeyCode, keyMap } from '../util/textInput' var { array, func, object, bool, number } = React.PropTypes export class KeyControlledList extends React.Component { static propTypes = { onChange: func, children: array, selectedIndex: number, tabChooses: bool } static defaultProps = { selectedIndex: 0, tabChooses: false } constructor (props) { super(props) let { selectedIndex } = props this.state = {selectedIndex} } componentWillReceiveProps (nextProps) { var max = nextProps.children.length - 1 if (this.state.selectedIndex > max) { this.setState({selectedIndex: max}) } } changeSelection = delta => { if (isEmpty(this.props.children)) return var i = this.state.selectedIndex var length = React.Children.count(this.props.children) i += delta if (i < 0) i += length i = i % length this.setState({selectedIndex: i}) } // this method is called from other components handleKeys = event => { switch (getKeyCode(event)) { case keyMap.UP: event.preventDefault() this.changeSelection(-1) return true case keyMap.DOWN: event.preventDefault() this.changeSelection(1) return true case keyMap.TAB: if (!this.props.tabChooses) return true // otherwise execution continues in the next case case keyMap.ENTER: if (!isEmpty(this.props.children)) { const elementChoice = this.childrenWithRefs[this.state.selectedIndex] const nodeChoice = findDOMNode(this.refs[elementChoice.ref]) this.change(elementChoice, nodeChoice, event) } return true } } change = (element, node, event) => { event.preventDefault() this.props.onChange(element, node, event) } // FIXME use more standard props e.g. {label, value} instead of {id, name}, or // provide an API for configuring them render () { const { selectedIndex } = this.state const { children, onChange, tabChooses, ...props } = this.props this.childrenWithRefs = React.Children.map(children, (element, i) => { const className = selectedIndex === i ? element.props.className + ' active' : element.props.className return element && element.props ? React.cloneElement(element, {ref: i, className}) : element }) return <ul {...omit('selectedIndex', props)}> {this.childrenWithRefs} </ul> } } export class KeyControlledItemList extends React.Component { static propTypes = { onChange: func.isRequired, items: array, selected: object, tabChooses: bool } // this method is called from other components handleKeys = event => { this.refs.kcl.handleKeys(event) } change = (choice, event) => { event.preventDefault() this.props.onChange(choice, event) } onChangeExtractingItem = (element, node, event) => { const item = find(i => i.id === element.key, this.props.items) this.change(item, event) } // FIXME use more standard props e.g. {label, value} instead of {id, name}, or // provide an API for configuring them render () { const { items, selected, onChange, ...props } = this.props const selectedIndex = indexOf(selected, items) return <KeyControlledList ref='kcl' tabChooses selectedIndex={selectedIndex} onChange={this.onChangeExtractingItem} {...props}> {items.map((c, i) => <li key={c.id || 'blank'}> <a onClick={event => this.change(c, event)}>{c.name}</a> </li>)} </KeyControlledList> } }
JavaScript
0
@@ -1398,17 +1398,55 @@ Map.TAB: + // eslint-disable-line no-fallthrough %0A - @@ -1543,16 +1543,41 @@ xt case%0A + case keyMap.SPACE:%0A ca @@ -2205,30 +2205,8 @@ ren, - onChange, tabChooses, ... @@ -2593,16 +2593,43 @@ ...omit( +%5B'onChange', 'tabChooses', 'selecte @@ -2635,16 +2635,17 @@ edIndex' +%5D , props) @@ -3419,18 +3419,8 @@ ted, - onChange, ... @@ -3621,21 +3621,39 @@ em%7D %7B... +omit('onChange', props +) %7D%3E%0A
1286b1137cbe6b6a555b5f495875ab29224886cc
increase size of FEN inputbox
demo/App.js
demo/App.js
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import Chessdiagram from '../src/chessdiagram.js'; import './App.css'; const pieces=[ 'R@a1', 'N@b1', 'B@c1', 'Q@d1', 'K@e1', 'B@f1', 'N@g1', 'R@h1', 'P@a2', 'P@b2', 'P@c2', 'P@d2', 'P@e2', 'P@f2', 'P@g2', 'P@h2', 'p@a7', 'p@b7', 'p@c7', 'p@d7', 'p@e7', 'p@f7', 'p@g7', 'p@h7', 'r@a8', 'n@b8', 'b@c8', 'q@d8', 'k@e8', 'b@f8', 'n@g8', 'r@h8', ]; class App extends Component { constructor(props) { super(props); this.state = { lightSquareColor: "#2492FF", // light blue darkSquareColor: "#005EBB", // dark blue currentPosition: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", // starting position flip: false, lastMessage: '', }; } // event handlers: _onPositionChanged(evt) { // user inputted new position this.setState({currentPosition: evt.target.value}); } _onFlipChanged(evt) { //flip board this.setState({flip: evt.target.checked}); } _onLightSquareColorChanged(evt) { this.setState({lightSquareColor: evt.target.value}); } _onDarkSquareColorChanged(evt) { this.setState({darkSquareColor: evt.target.value}); } _onMovePiece(piece, fromSquare, toSquare) { // user moved a piece // echo move back to user: let message = 'You moved ' + piece + fromSquare + " to " + toSquare + ' !'; this.setState({lastMessage: message}, (()=> { setTimeout(()=> { this.setState({lastMessage: ''}); }, 2000); // clear message after 2s })); } // the render() function: render() { return ( <div className="demo"> <h1>Chess Diagram</h1> <div> <p> Enter a position (using a FEN string) here:</p> <input type="text" value={this.state.currentPosition} size="60" onChange={this._onPositionChanged.bind(this)} autoCapitalize="off" autoCorrect="off" autoComplete="off" spellCheck="false"/> <p>Flip Board ?<input type="checkbox" value={this.state.flip} onChange={this._onFlipChanged.bind(this)} /></p> <p>Light Square Color:<input type="color" value={this.state.lightSquareColor} onChange={this._onLightSquareColorChanged.bind(this)} /></p> <p>Dark Square Color:<input type="color" value={this.state.darkSquareColor} onChange={this._onDarkSquareColorChanged.bind(this)} /></p> <p/> </div> <Chessdiagram flip={this.state.flip} fen={this.state.currentPosition} squareSize={30} lightSquareColor={this.state.lightSquareColor} darkSquareColor={this.state.darkSquareColor} onMovePiece={this._onMovePiece.bind(this)}/> <p><strong>{this.state.lastMessage}</strong></p> </div> ); } } ReactDOM.render( <App />, document.getElementById('root') );
JavaScript
0
@@ -1734,9 +1734,9 @@ ze=%22 -6 +7 0%22 o
1668c7760bcf97a6222a8001221e46eb43941688
Use enhanced object literals
web/app/scripts/util.js
web/app/scripts/util.js
function parseQueryString() { if (!document.location.search) return; var querys = document.location.search.split('?')[1].split('&'); var params = {}; querys.forEach(function(q) { var qs, key, value; qs = q.split('='); key = qs[0]; value = qs[1]; if (params[key]) { if (!(params[key] instanceof Array)) { params[key] = [params[key]]; } if (params[key].indexOf(value) === -1) { params[key].push(value); } } else { params[key] = value; } }); return params; } function pprDate(dateString) { var date = new Date(dateString); var year, month, dayOfMonth; year = date.getFullYear(); month = date.getMonth() + 1; dayOfMonth = date.getDate(); return [year, month, dayOfMonth].join('-'); } export default { parseQueryString: parseQueryString, pprDate: pprDate };
JavaScript
0.000001
@@ -812,38 +812,11 @@ ring -: parseQueryString,%0A pprDate: +,%0A ppr
8cf25704e37ce0e712cece6feb9cb4f29f3410a8
Fix pageX/Y, start censorship on mousedown
censored.js
censored.js
;(function(global) { 'use strict'; function Censored(el) { this.md = false; this.eraser = false; var img = document.getElementById(el); var t = this; t.toggleEraser = function(val) { t.eraser = val; }; var canvas1 = document.createElement('canvas'); var ctx1 = canvas1.getContext('2d'); var canvas2 = document.createElement('canvas'); var ctx2 = canvas2.getContext('2d'); var canvas3 = document.createElement('canvas'); var ctx3 = canvas3.getContext('2d'); img.onload = function() { var wrapper = document.createElement('div'); wrapper.style.position = 'relative' var parent = img.parentNode; parent.insertBefore(wrapper, img); canvas1.height = img.height; canvas1.width = img.width; canvas1.style.position = 'absolute'; ctx1.mozImageSmoothingEnabled = false; ctx1.webkitImageSmoothingEnabled = false; ctx1.imageSmoothingEnabled = false; var w = img.width * 0.1; var h = img.height * 0.1; ctx1.drawImage(img, 0, 0, w, h); ctx1.drawImage(canvas1, 0, 0, w, h, 0, 0, canvas1.width, canvas1.height); canvas2.height = img.height; canvas2.width = img.width; canvas2.style.position = 'absolute'; ctx2.drawImage(img, 0, 0); canvas3.height = img.height; canvas3.width = img.width; canvas3.style.position = 'absolute'; wrapper.appendChild(canvas1); wrapper.appendChild(canvas2); wrapper.appendChild(canvas3); parent.removeChild(img); }; canvas3.addEventListener('mousedown', function() { t.md = true; }); canvas3.addEventListener('mouseup', function() { t.md = false; }); canvas3.addEventListener('mousemove', function(e) { if (t.md) { if (t.eraser) { ctx3.clearRect(e.pageX - 20, e.pageY - 20, 40, 40); } else { ctx3.putImageData(ctx1.getImageData(e.pageX - 20, e.pageY - 20, 40, 40), e.pageX - 20, e.pageY - 20); } } }); document.addEventListener('keydown', function(e) { if (e.altKey) { t.toggleEraser(true); } }); document.addEventListener('keyup', function(e) { t.toggleEraser(false); }); }; global.Censored = Censored; })(window);
JavaScript
0.000001
@@ -1835,34 +1835,379 @@ rRect(e. -pageX - 20, e.page +layerX - 20, e.layerY - 20, 40, 40);%0A %7D else %7B%0A ctx3.putImageData(ctx1.getImageData(e.layerX - 20, e.layerY - 20, 40, 40), e.layerX - 20, e.layerY - 20);%0A %7D%0A %7D%0A %7D);%0A%0A canvas3.addEventListener('mousedown', function(e) %7B%0A console.log(e)%0A if (t.md) %7B%0A if (t.eraser) %7B%0A ctx3.clearRect(e.layerX - 20, e.layer Y - 20, @@ -2280,20 +2280,21 @@ eData(e. -page +layer X - 20, @@ -2291,28 +2291,29 @@ erX - 20, e. -page +layer Y - 20, 40, @@ -2319,20 +2319,21 @@ 40), e. -page +layer X - 20, @@ -2338,12 +2338,13 @@ , e. -page +layer Y -
4df6f5a05532bc43af7c42affc17172c183af225
refresh the lsit only once on startup
www/js/radioListPage.js
www/js/radioListPage.js
function refreshRadioListData() { $.mobile.loading( 'show',{text:'loading'} ); var jqxhr = $.getJSON('http://api.jamendo.com/v3.0/radios?client_id='+g_clientId+'&callback=?', null, null,'application/json') .done(function(result) { radioListPageLoaded=true; console.log(result); $.mobile.loading( 'hide' ); var list = $("#radioList").listview(); $(result.results).each(function(index){ $(list).append('<li><a href="index.html#radioPage" data-transition="slide" onclick="sessionStorage.radioId=' + this.id+ '">' + '<img src="'+this.image+'" class="ui-li-icon"/> <h3>' + this.dispname + '</h3></a> </li>'); }); $("#radioList").listview('refresh'); }) .fail(function() { radioListPageLoaded = false; jQuery.mobile.changePage("#errorPage"); }); } $( document ).delegate("#radioListPage", "pageinit", function() { refreshRadioListData(); }); $( document ).delegate("#radioListPage", "pagebeforeshow", function() { if(radioListPageLoaded == true) return; //page is not loaded continue refreshRadioListData(); });
JavaScript
0
@@ -834,106 +834,8 @@ %0A%7D%0A%0A -$( document ).delegate(%22#radioListPage%22, %22pageinit%22, function() %7B%0A refreshRadioListData();%0A%7D);%0A%0A $( d
c295e68475696be818b2c9877e5a85853805b326
Update stream.js
examples/stream.js
examples/stream.js
'use strict'; var d3 = require('d3'); // Require the library and give it a reference to d3 var Prerender = require('d3-pre'); var prerender = Prerender(d3); // Then, when you start drawing svg call `prerender.start()` // this modifies some d3 functions to allow it to be // aware of SVGs that already exist on the page. prerender.start(); var n = 20, // number of layers m = 200, // number of samples per layer stack = d3.layout.stack().offset("wiggle"), layers0 = stack(d3.range(n).map(function() { return bumpLayer(m); })), layers1 = stack(d3.range(n).map(function() { return bumpLayer(m); })); var width = 960, height = 500; var x = d3.scale.linear() .domain([0, m - 1]) .range([0, width]); var y = d3.scale.linear() .domain([0, d3.max(layers0.concat(layers1), function(layer) { return d3.max(layer, function(d) { return d.y0 + d.y; }); })]) .range([height, 0]); var color = d3.scale.linear() .range(["#aad", "#556"]); var area = d3.svg.area() .x(function(d) { return x(d.x); }) .y0(function(d) { return y(d.y0); }) .y1(function(d) { return y(d.y0 + d.y); }); d3.select('#interactive').append('button').text('Update').on('click', transition); var svg = d3.select("#interactive").append("svg") .attr('viewBox', '0 0 ' + width + ' ' + height); if (prerender.isPreprocessing) { svg.selectAll("path") .data(layers0) .enter().append("path") .attr("d", area) .style("fill", function() { return color(Math.random()); }); } function transition() { d3.selectAll("path") .data(function() { var d = layers1; layers1 = layers0; return layers0 = d; }) .transition() .duration(2500) .attr("d", area); } // Inspired by Lee Byron's test data generator. function bumpLayer(n) { function bump(a) { var x = 1 / (.1 + Math.random()), y = 2 * Math.random() - .5, z = 10 / (.1 + Math.random()); for (var i = 0; i < n; i++) { var w = (i / n - y) * z; a[i] += x * Math.exp(-w * w); } } var a = [], i; for (i = 0; i < n; ++i) a[i] = 0; for (i = 0; i < 5; ++i) bump(a); return a.map(function(d, i) { return {x: i, y: Math.max(0, d)}; }); }
JavaScript
0.000002
@@ -1306,16 +1306,152 @@ ight);%0A%0A +// This if-statement is only necessary because the %0A// initial data is random. We don't want to %0A// render new random data on pageload.%0A if (prer
62bc1ec26ad607e42a2495257b3e0156830b42dd
Refresh data for the user settings page when it is being accessed
app/templates/src/main/webapp/scripts/app/account/settings/_settings.controller.js
app/templates/src/main/webapp/scripts/app/account/settings/_settings.controller.js
'use strict'; angular.module('<%=angularAppName%>') .controller('SettingsController', function ($scope, Principal, Auth) { $scope.success = null; $scope.error = null; Principal.identity().then(function(account) { $scope.settingsAccount = account; }); $scope.save = function () { Auth.updateAccount($scope.settingsAccount).then(function() { $scope.error = null; $scope.success = 'OK'; Principal.identity().then(function(account) { $scope.settingsAccount = account; }); }).catch(function() { $scope.success = null; $scope.error = 'ERROR'; }); }; });
JavaScript
0
@@ -200,32 +200,36 @@ ncipal.identity( +true ).then(function(
e6829291803525dffd847b3df860467ea6e9c8eb
Fix docu in page
library/CM/Page/Abstract.js
library/CM/Page/Abstract.js
/** * @class CM_Page_Abstract * @extends CM_Component_Abstract */ var CM_Page_Abstract = CM_Component_Abstract.extend({ /** @type String */ _class: 'CM_Page_Abstract', /** @type String[] */ _stateParams: null, /** @type String|Null */ _fragment: null, _ready: function() { if (this.hasStateParams()) { var location = window.location; var params = queryString.parse(location.search); var state = _.pick(params, _.intersection(_.keys(params), this.getStateParams())); this.routeToState(state, location.pathname + location.search); } CM_Component_Abstract.prototype._ready.call(this); }, /** * @returns {String|Null} */ getFragment: function() { return this._fragment; }, /** * @returns {Boolean} */ hasStateParams: function() { return null !== this._stateParams; }, /** * @returns {String[]} */ getStateParams: function() { if (!this.hasStateParams()) { cm.error.triggerThrow('Page has no state params'); } return this._stateParams; }, /** * @param {Object} state * @param {String} fragment */ routeToState: function(state, fragment) { this._fragment = fragment; this._changeState(state); }, /** * @param {Object} state */ _changeState: function(state) { } });
JavaScript
0
@@ -190,16 +190,21 @@ String%5B%5D +%7CNull */%0A _s
70c690894f9a27ba772961860e775dd9a2935c90
Fix #5632 - Reset column loading status after fetch fail (#5659)
app/javascript/mastodon/reducers/notifications.js
app/javascript/mastodon/reducers/notifications.js
import { NOTIFICATIONS_UPDATE, NOTIFICATIONS_REFRESH_SUCCESS, NOTIFICATIONS_EXPAND_SUCCESS, NOTIFICATIONS_REFRESH_REQUEST, NOTIFICATIONS_EXPAND_REQUEST, NOTIFICATIONS_REFRESH_FAIL, NOTIFICATIONS_EXPAND_FAIL, NOTIFICATIONS_CLEAR, NOTIFICATIONS_SCROLL_TOP, } from '../actions/notifications'; import { ACCOUNT_BLOCK_SUCCESS, ACCOUNT_MUTE_SUCCESS, } from '../actions/accounts'; import { TIMELINE_DELETE } from '../actions/timelines'; import { Map as ImmutableMap, List as ImmutableList } from 'immutable'; const initialState = ImmutableMap({ items: ImmutableList(), next: null, top: true, unread: 0, loaded: false, isLoading: true, }); const notificationToMap = notification => ImmutableMap({ id: notification.id, type: notification.type, account: notification.account.id, status: notification.status ? notification.status.id : null, }); const normalizeNotification = (state, notification) => { const top = state.get('top'); if (!top) { state = state.update('unread', unread => unread + 1); } return state.update('items', list => { if (top && list.size > 40) { list = list.take(20); } return list.unshift(notificationToMap(notification)); }); }; const normalizeNotifications = (state, notifications, next) => { let items = ImmutableList(); const loaded = state.get('loaded'); notifications.forEach((n, i) => { items = items.set(i, notificationToMap(n)); }); if (state.get('next') === null) { state = state.set('next', next); } return state .update('items', list => loaded ? items.concat(list) : list.concat(items)) .set('loaded', true) .set('isLoading', false); }; const appendNormalizedNotifications = (state, notifications, next) => { let items = ImmutableList(); notifications.forEach((n, i) => { items = items.set(i, notificationToMap(n)); }); return state .update('items', list => list.concat(items)) .set('next', next) .set('isLoading', false); }; const filterNotifications = (state, relationship) => { return state.update('items', list => list.filterNot(item => item.get('account') === relationship.id)); }; const updateTop = (state, top) => { if (top) { state = state.set('unread', 0); } return state.set('top', top); }; const deleteByStatus = (state, statusId) => { return state.update('items', list => list.filterNot(item => item.get('status') === statusId)); }; export default function notifications(state = initialState, action) { switch(action.type) { case NOTIFICATIONS_REFRESH_REQUEST: case NOTIFICATIONS_EXPAND_REQUEST: case NOTIFICATIONS_REFRESH_FAIL: case NOTIFICATIONS_EXPAND_FAIL: return state.set('isLoading', true); case NOTIFICATIONS_SCROLL_TOP: return updateTop(state, action.top); case NOTIFICATIONS_UPDATE: return normalizeNotification(state, action.notification); case NOTIFICATIONS_REFRESH_SUCCESS: return normalizeNotifications(state, action.notifications, action.next); case NOTIFICATIONS_EXPAND_SUCCESS: return appendNormalizedNotifications(state, action.notifications, action.next); case ACCOUNT_BLOCK_SUCCESS: case ACCOUNT_MUTE_SUCCESS: return filterNotifications(state, action.relationship); case NOTIFICATIONS_CLEAR: return state.set('items', ImmutableList()).set('next', null); case TIMELINE_DELETE: return deleteByStatus(state, action.id); default: return state; } };
JavaScript
0
@@ -2590,32 +2590,73 @@ EXPAND_REQUEST:%0A + return state.set('isLoading', true);%0A case NOTIFICAT @@ -2734,35 +2734,36 @@ et('isLoading', -tru +fals e);%0A case NOTIF
c8983f6ddb879c7986995ea4c8b4a7218a3a3ee2
converted to es6 arrow function
src/components/markdown-render/a.js
src/components/markdown-render/a.js
import React from 'react'; function A(props) { return ( <a className="sprk-b-Link" {...props}/> ); } export default A;
JavaScript
0.999745
@@ -25,36 +25,26 @@ ';%0A%0A -function A(props) %7B%0A return +const A = props =%3E (%0A @@ -94,10 +94,8 @@ ); -%0A%7D %0A%0Aex
9b23c1efd8322515a9628203449bb50a8e41fe73
replace var
src/client/src/services/executionService.js
src/client/src/services/executionService.js
import Rx from 'rx'; import { OpenFin } from '../system/openFin'; import { ExecuteTradeRequest, ExecuteTradeResponse } from './model'; import { TradeMapper } from './mappers'; import { logger, SchedulerService } from '../system'; import { Connection, ServiceBase } from '../system/service'; import { ReferenceDataService } from './'; const _log:logger.Logger = logger.create('ExecutionService'); export default class ExecutionService extends ServiceBase { static EXECUTION_TIMEOUT_MS = 2000; constructor(serviceType:string, connection:Connection, schedulerService:SchedulerService, referenceDataService:ReferenceDataService, openFin:OpenFin) { super(serviceType, connection, schedulerService); this._openFin = openFin; this._tradeMapper = new TradeMapper(referenceDataService); } executeTrade(executeTradeRequest:ExecuteTradeRequest):Rx.Observable<ExecuteTradeResponse> { let _this = this; return Rx.Observable.create( o => { _log.info(`executing: ${executeTradeRequest.toString()}`, executeTradeRequest); let disposables = new Rx.CompositeDisposable(); disposables.add( _this._openFin .checkLimit(executeTradeRequest.SpotRate, executeTradeRequest.Notional, executeTradeRequest.CurrencyPair) .take(1) .subscribe(limitCheckResult => { if (limitCheckResult) { disposables.add( _this._serviceClient .createRequestResponseOperation('executeTrade', executeTradeRequest) .map(dto => { var trade = _this._tradeMapper.mapFromTradeDto(dto.Trade); _log.info(`execute response received for: ${executeTradeRequest.toString()}. Status: ${trade.status}`, dto); return ExecuteTradeResponse.create(trade); }) .timeout(ExecutionService.EXECUTION_TIMEOUT_MS, Rx.Observable.return(ExecuteTradeResponse.createForError('Trade execution timeout exceeded'))) .subscribe(o) ); } else { //TODO o.onError(new Error('Openfin integration not finished')); } }) ); return disposables; } ); } }
JavaScript
0.001948
@@ -1652,11 +1652,13 @@ -var +const tra
bb481639006540428b2805db5bf632c05e2a9627
simplify error handling on app boot
back/app.js
back/app.js
/** * aspen * Node.js web application boilerplate. * * @author Theodore Keloglou * @file Main application boot file. */ const express = require('express'); const logger = require('morgan'); const path = require('path'); const favicon = require('serve-favicon'); const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); const session = require('express-session'); const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const routes = require('./routes/index'); const models = require('./models'); const helpers = require('./util/helpers'); const listeners = require('./util/listeners'); const app = express(); app.set('views', path.join(__dirname, '../front/views')); app.set('view engine', 'pug'); // Enable CORS app.use(function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); app.use(favicon(path.join(__dirname, '../front/static', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: false, })); app.use(passport.initialize()); app.use(passport.session()); passport.use(new LocalStrategy({ usernameField: 'username', passwordField: 'password', // session: false, }, function (username, password, done) { models.User.findOne({ where: { username: username } }).then(function (user) { if (!user) { return done(null, false, { message: 'Incorrect username.' }); } if (!user.validPassword(password)) { return done(null, false, { message: 'Incorrect password.' }); } return done(null, user); }).catch(function (err) { console.log('Passport error:', err); }); } )); passport.serializeUser(function (user, done) { done(null, user.username); }); passport.deserializeUser(function (username, done) { models.User.findOne({ where: { username } }).then(function (user) { done(null, user); }); }); app.use(express.static(path.join(__dirname, '../front/static'))); app.use('/', routes); // catch 404 and forward to error handler app.use(function (req, res, next) { const err = new Error('Not Found'); err.status = 404; next(err); }); // development error handler, will print stacktrace if (app.get('env') === 'development') { app.use(function (err, req, res) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler, no stacktraces leaked to user app.use(function (err, req, res) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); const port = helpers.normalizePort(process.env.PORT || '3000'); app.set('port', port); models.sequelize.sync() .then(function () { app.listen(port); app.on('error', listeners.onError); app.on('listening', listeners.onListening); console.log('Server running on port ' + port); }); module.exports = app;
JavaScript
0.000004
@@ -258,24 +258,58 @@ -favicon');%0A +const config = require('config');%0A const cookie @@ -608,98 +608,8 @@ s'); -%0Aconst helpers = require('./util/helpers');%0Aconst listeners = require('./util/listeners'); %0A%0Aco @@ -1388,18 +1388,16 @@ sword',%0A - // ses @@ -2842,20 +2842,18 @@ );%0A%7D);%0A%0A -cons +le t port = @@ -2857,30 +2857,64 @@ t = -helpers.normalizePort( +config.webserver.port;%0Aif (process.env.PORT) %7B%0A port = proc @@ -2929,20 +2929,11 @@ PORT - %7C%7C '3000'); +;%0A%7D %0Aapp @@ -2953,16 +2953,58 @@ port);%0A%0A +// models.sequelize.sync(%7B force: true %7D)%0A models.s @@ -3087,73 +3087,97 @@ r', -listeners.onE +function (e rror) -; + %7B %0A -app.on('listening', listeners.onListening + console.error('App error:', error);%0A process.exit(1);%0A %7D );%0A @@ -3218,12 +3218,11 @@ port - ' + +:', por
3a60cb9a06e5d0489d222c35388f15bbd71a0793
Remove unused component
app/routes/events/components/EventDetail/index.js
app/routes/events/components/EventDetail/index.js
// @flow import styles from './EventDetail.css'; import React, { Component } from 'react'; import { Image } from 'app/components/Image'; import CommentView from 'app/components/Comments/CommentView'; import Button from 'app/components/Button'; import Icon from 'app/components/Icon'; import JoinEventForm from '../JoinEventForm'; import RegisteredCell from '../RegisteredCell'; import RegisteredSummary from '../RegisteredSummary'; import { AttendanceStatus, ModalParentComponent } from 'app/components/UserAttendance'; import Tag from 'app/components/Tag'; import Time from 'app/components/Time'; import LoadingIndicator from 'app/components/LoadingIndicator'; import { Flex } from 'app/components/Layout'; import { EVENT_TYPE_TO_STRING, styleForEvent } from '../../utils.js'; import Admin from '../Admin'; import RegistrationMeta from '../RegistrationMeta'; import Content from 'app/components/Layout/Content'; import cx from 'classnames'; type InterestedButtonProps = { isInterested: boolean }; const InterestedButton = ({ isInterested }: InterestedButtonProps) => { const icon = isInterested ? 'star' : 'star-outline'; return <Icon className={styles.star} name={icon} />; }; /** * */ type Props = { eventId: string, event: Object, loggedIn: boolean, currentUser: Object, actionGrant: Array<string>, comments: Array<Object>, error?: Object, loading: boolean, pools: Array<Object>, registrations: Array<Object>, currentRegistration: Object, waitingRegistrations: Array<Object>, register: ( eventId: string, captchaResponse: string, feedback: string ) => Promise<*>, follow: (eventId: string, userId: string) => Promise<*>, unfollow: (eventId: string, userId: string) => Promise<*>, unregister: (eventId: string, registrationId: number) => Promise<*>, payment: (eventId: string, token: string) => Promise<*>, updateFeedback: ( eventId: string, registrationId: number, feedback: string ) => Promise<*>, deleteEvent: (eventId: string) => Promise<*>, updateUser: Object => void }; /** * */ export default class EventDetail extends Component { props: Props; handleRegistration = ({ captchaResponse, feedback, type }: Object) => { const { eventId, currentRegistration, register, unregister, updateFeedback } = this.props; switch (type) { case 'feedback': return updateFeedback(eventId, currentRegistration.id, feedback); case 'register': return register(eventId, captchaResponse, feedback); case 'unregister': return unregister(eventId, currentRegistration.id); default: return undefined; } }; handleToken = (token: Object) => { this.props.payment(this.props.event.id, token.id); }; render() { const { event, loggedIn, currentUser, updateUser, actionGrant, comments, error, loading, pools, registrations, currentRegistration, deleteEvent, follow, unfollow } = this.props; if (!event.id) { return null; } if (loading) { return <LoadingIndicator loading />; } if (error) { return <div>{error.message}</div>; } const styleType = styleForEvent(event.eventType); const onRegisterClick = event.isUserFollowing ? () => unfollow(event.isUserFollowing.id, event.id) : () => follow(currentUser.id, event.id); return ( <div> <div className={styles.coverImage}> <Image src={event.cover} /> </div> <Content className={styles.content}> <div> <h2 onClick={onRegisterClick} className={cx(styleType, styles.title)} > <InterestedButton isInterested={event.isUserFollowing} /> {event.title} </h2> </div> <Flex wrap className={styles.mainRow}> <Flex column className={styles.description}> <div className={styles.text} dangerouslySetInnerHTML={{ __html: event.text }} /> <Flex className={styles.tagRow}> {event.tags.map((tag, i) => <Tag key={i} tag={tag} />)} </Flex> </Flex> <Flex column className={cx(styles.meta)}> <ul> {event.company && ( <li> Arrangerende bedrift <strong>{event.company.name}</strong> </li> )} <li> <span className={styles.metaDescriptor}>Hva</span> <strong>{EVENT_TYPE_TO_STRING(event.eventType)}</strong> </li> <li> <span className={styles.metaDescriptor}>Starter</span> <strong> <Time time={event.startTime} format="DD.MM.YYYY HH:mm" /> </strong> </li> <li> <span className={styles.metaDescriptor}>Slutter</span> <strong> <Time time={event.endTime} format="DD.MM.YYYY HH:mm" /> </strong> </li> <li> Finner sted i <strong>{event.location}</strong> </li> {event.activationTime && ( <li> Påmelding åpner <strong style={{ marginLeft: 5 }}> <Time time={event.activationTime} format="DD.MM.YYYY HH:mm" style={{ marginLeft: '5px' }} /> </strong> </li> )} {event.isPriced && ( <div> <li>Dette er et betalt arrangement</li> <li> Pris: <strong>{event.priceMember / 100},-</strong> </li> </div> )} </ul> {loggedIn && ( <Flex column> <h3>Påmeldte</h3> <Flex className={styles.registeredThumbnails}> {registrations .slice(0, 10) .map(reg => ( <RegisteredCell key={reg.user.id} user={reg.user} /> ))} </Flex> <ModalParentComponent pools={pools} title="Påmeldte"> <RegisteredSummary registrations={registrations} /> <AttendanceStatus /> </ModalParentComponent> <RegistrationMeta registration={currentRegistration} isPriced={event.isPriced} /> <Admin actionGrant={actionGrant} event={event} deleteEvent={deleteEvent} /> </Flex> )} </Flex> </Flex> {loggedIn && ( <JoinEventForm event={event} registration={currentRegistration} currentUser={currentUser} updateUser={updateUser} onToken={this.handleToken} onSubmit={this.handleRegistration} /> )} {event.commentTarget && ( <CommentView style={{ marginTop: 20 }} user={currentUser} commentTarget={event.commentTarget} loggedIn={loggedIn} comments={comments} /> )} </Content> </div> ); } }
JavaScript
0.000003
@@ -198,52 +198,8 @@ w';%0A -import Button from 'app/components/Button';%0A impo
e53ba74471cef0364e6076679364b3f4b1ee7dc2
update trackjs
src/botPage/view/logger.js
src/botPage/view/logger.js
import { observer as globalObserver } from '../../common/utils/observer'; import { getToken } from '../../common/utils/storageManager'; import { isProduction } from '../../common/utils/tools'; const log = (type, ...args) => { if (type === 'warn') { console.warn(...args); // eslint-disable-line no-console } else { console.log(...args); // eslint-disable-line no-console } const date = new Date(); const timestamp = `${date.toISOString().split('T')[0]} ${date.toTimeString().slice(0, 8)} ${ date.toTimeString().split(' ')[1] }`; globalObserver.emit('bot.notify', { type, timestamp, message: args.join(':') }); }; const notify = ({ className, message, position = 'left', sound = 'silent' }) => { log(className, message); $.notify(message, { position: `bottom ${position}`, className }); if (sound !== 'silent') { $(`#${sound}`) .get(0) .play(); } }; export class TrackJSError extends Error { constructor(type, message, optCustomData) { super(message); this.name = type; this.code = type; this.data = optCustomData; } } const notifyError = error => { if (!error) { return; } let message; let code; if (typeof error === 'string') { code = 'Unknown'; message = error; } else if (error.error) { if (error.error.error) { ({ message } = error.error.error); ({ code } = error.error.error); } else { ({ message } = error.error); ({ code } = error.error); } } else { ({ message } = error); ({ code } = error); } // Exceptions: if (message === 'Cannot read property \'open_time\' of undefined') { // SmartCharts error workaround, don't log nor show. return; } notify({ className: 'error', message, position: 'right' }); if (trackJs) { trackJs.console.log(error); if (isProduction()) { trackJs.track(code || error.name); } } }; const waitForNotifications = () => { const notifList = ['success', 'info', 'warn', 'error']; globalObserver.register('Notify', notify); globalObserver.register('Error', notifyError); notifList.forEach(className => globalObserver.register(`ui.log.${className}`, message => notify({ className, message, position: 'right' })) ); }; const logHandler = () => { const token = $('.account-id') .first() .attr('value'); const userId = getToken(token).accountName; if (trackJs) { trackJs.configure({ userId }); } waitForNotifications(); }; export default logHandler;
JavaScript
0.000001
@@ -1935,36 +1935,54 @@ %0A if (trackJs + && isProduction() ) %7B%0A - trackJs. @@ -2005,42 +2005,8 @@ r);%0A - if (isProduction()) %7B%0A @@ -2044,29 +2044,60 @@ .name);%0A - %7D +%7D else %7B%0A console.log(error); %0A %7D%0A%7D;%0A%0Ac
85d9235a13cbe536d227b4e3a802a1a9fb1d2ff7
Increment an elsewhere receiver's "people ready to give"
js/gittip/tips.js
js/gittip/tips.js
Gittip.tips = {}; Gittip.tips.init = function() { // Check the tip value on change, or 0.7 seconds after the user stops typing. // If the user presses enter, the browser should natively submit the form. // If the user presses cancel, we reset the form to its previous state. var timer; $('input.my-tip').change(checkTip).keyup(function(e) { if (e.keyCode === 27) // escape $(this).parents('form').trigger('reset'); else if (e.keyCode === 38 || e.keyCode === 40) // up & down return; // causes inc/decrement in HTML5, triggering the change event else { clearTimeout(timer); timer = setTimeout(checkTip.bind(this), 700); } }); function checkTip() { var $this = $(this), $parent = $this.parents('form'), $confirm = $parent.find('.confirm-tip'), amount = parseFloat($this.val(), 10) || 0, oldAmount = parseFloat(this.defaultValue, 10), max = parseFloat($this.prop('max')), min = parseFloat($this.prop('min')), inBounds = amount <= max && amount >= min, same = amount === oldAmount; // dis/enables confirm button as needed $confirm.prop('disabled', inBounds ? same : true); if (same) $parent.removeClass('changed'); else $parent.addClass('changed'); // show/hide the payment prompt if (amount) $('#payment-prompt').addClass('needed'); else $('#payment-prompt').removeClass('needed'); } $('.my-tip .cancel-tip').click(function(event) { event.preventDefault(); $(this).parents('form').trigger('reset'); }); $('.my-tip .tip-suggestions a').click(function(event) { event.preventDefault(); var $this = $(this), $myTip = $this.parents('form').find('.my-tip'); $myTip.val($this.text().match(/\d+/)[0] / ($this.hasClass('cents') ? 100 : 1)).change(); }); $('form.my-tip').on('reset', function() { $(this).removeClass('changed'); $(this).find('.confirm-tip').prop('disabled', true); }); $('form.my-tip').submit(function(event) { event.preventDefault(); var $this = $(this), $myTip = $this.find('.my-tip'), amount = parseFloat($myTip.val(), 10), oldAmount = parseFloat($myTip[0].defaultValue, 10), tippee = $myTip.data('tippee'), isAnon = $this.hasClass('anon'); if (amount == oldAmount) return; if(isAnon) alert("Please sign in first"); else { // send request to change tip $.post('/' + tippee + '/tip.json', { amount: amount }, function(data) { // lock-in changes $myTip[0].defaultValue = amount; $myTip.change(); // update display $('.total-giving').text(data.total_giving); $('.total-receiving').text( // check and see if we are on our giving page or not new RegExp('/' + tippee + '/').test(window.location.href) ? data.total_receiving_tippee : data.total_receiving); // update quick stats $('.quick-stats a').text('$' + data.total_giving + '/wk'); alert("Tip changed to $" + amount + "!"); }) .fail(function() { alert('Sorry, something went wrong while changing your tip. :('); console.log.apply(console, arguments); }) } }); };
JavaScript
0
@@ -3357,24 +3357,276 @@ eceiving);%0A%0A + // Increment an elsewhere receiver's %22people ready to give%22%0A if(!oldAmount)%0A $('.on-elsewhere .ready .number').text(%0A parseInt($('.on-elsewhere .ready .number').text(),10) + 1);%0A%0A
50ae4fe91a297340e5c4943a071c6c939a365a24
Update app.js
script/app.js
script/app.js
(function($){ $.particleText = function(el, options){ // To avoid scope issues, use 'base' instead of 'this' // to reference this class from internal events and functions. var base = this; // Access to jQuery and DOM versions of element base.$el = $(el); base.el = el; // Add a reverse reference to the DOM object base.$el.data("particleText", base); base.init = function(){ base.options = $.extend({},$.particleText.defaultOptions, options); var scaler = 200; base.$el .empty() .html(base.$el.data('text')) .lettering(); //wrap all the individual characters into a temporary div base.$el.find("span").wrapAll("<div class='src'></div>"); base.$el.find(".src").css("fontSize",scaler+"px") //number of rows and columns var count=8; var offsetX=0; var offsetY=0; var whitespace = /\s/g; var container = base.$el.find(".src"); var containerWidth = container.width(); var containerHeight = container.height(); base.$el.css("height",containerHeight); base.$el.css("width",containerWidth); base.$el.find("span").each(function(k,val){ var width = $(val).width(); var height = containerHeight; if(!whitespace.test($(val).text())){ var rows = Math.ceil(height/count); var columns = Math.ceil(width/count); var letter = $("<div class='letter'></div>").appendTo(base.$el); var color = "#"+Math.floor(Math.random()*16777215).toString(16); for(var i=0;i<count;i++){ for(var j=0;j<count;j++){ $(val) .clone() .appendTo(letter) .wrap('<div></div>') .css({ fontSize: scaler+'px', position: 'absolute', visibility: 'visible', left:-(j*columns), top: -(i*rows) }) .parent() .addClass('explode') .attr("data-left",(j*columns)+offsetX+"px") .attr("data-top",(i*rows)+"px") .css({ position: 'absolute', // color:color, overflow: 'hidden', width: columns, height:rows, left:(j*columns)+offsetX, top: (i*rows) }); } offsetY+=height/count; } //character offest offsetX+=width } else { //space offset offsetX+=width; } }) base.animate(count); }; base.animate = function (count) { var maxX = window.innerWidth, maxY = $(window).height(); base.$el.find('.letter').each(function (i, element) { $(element).find('.explode').each(function (i, el) { var subTl; subTl = new TimelineMax({ delay: i/count , repeat : -1, yoyo:true }); subTl.from($(el),0.1, { css: { y:count }, }); }); }); }; base.init(); }; $.particleText.defaultOptions = { }; $.fn.particleText = function(options){ return this.each(function(){ (new $.particleText(this, options)); }); }; })(jQuery); $(document).ready(function(){ $(".canvas").particleText(); });
JavaScript
0.000002
@@ -2876,18 +2876,16 @@ -// colo @@ -2886,21 +2886,38 @@ color: +base.$el.data(' color +') ,%0A @@ -4738,8 +4738,9 @@ ();%0A%0A%7D); +%0A
9d39794154ce4247b9ebec392986b4429f27cbb8
Improve error statement for modules that could not be found during compilation
compiler.js
compiler.js
var fs = require('fs'), path = require('path'), child_process = require('child_process'), util = require('./lib/util') module.exports = { compile: compileFile, compileCode: compileCode, addPath: util.addPath } /* compilation *************/ function compileFile(filePath, level, basePath, callback) { if (!callback) { callback = basePath basePath = null } fs.readFile(filePath, function(err, code) { if (err) { return callback(err) } _compile(code.toString(), level, basePath || path.dirname(filePath), callback) }) } function compileCode(code, level, basePath, callback) { if (!callback) { callback = basePath basePath = null } _compile(code, level, basePath || process.cwd(), callback) } var _compile = function(code, level, basePath, callback) { try { var code = 'var require = {}\n' + _compileModule(code, basePath) } catch(e) { return callback(e) } if (level) { _compress(code, level, callback) } else { callback(null, _indent(code)) } } // TODO: Look into // provide a closure to make all variables local: code = '(function(){'+code+'})()' // --compilation_level [WHITESPACE_ONLY | SIMPLE_OPTIMIZATIONS | ADVANCED_OPTIMIZATIONS] // --compute_phase_ordering: Runs the compile job many times, then prints out the best phase ordering from this run // --define (--D, -D) VAL Override the value of a variable annotated @define. The format is <name>[=<val>], where <name> is the name of a @define variable and <val> is a boolean, number, or a single-quot ed string that contains no single quotes. If [=<val>] is omitted, the variable is marked true // --print_ast, --print_pass_graph, --print_tree var _compressionLevels = [null, 'WHITESPACE_ONLY', 'SIMPLE_OPTIMIZATIONS', 'ADVANCED_OPTIMIZATIONS'] function _compress(code, level, callback) { var closureArgs = ['-jar', __dirname + '/lib/google-closure.jar', '--compilation_level', _compressionLevels[level]], closure = child_process.spawn('java', closureArgs), stdout = [], stderr = [] closure.stdout.on('data', function(data) { stdout.push(data); }); closure.stderr.on('data', function(data) { stderr.push(data); }); closure.on('exit', function(code) { if (code == 0) { callback(null, stdout.join('')) } else { callback(new Error(stderr.join(''))) } }) closure.stdin.write(code) closure.stdin.end() } /* util ******/ var _indent = function(code) { var lines = code.replace(/\t/g, '').split('\n'), result = [], indentation = 0 for (var i=0, line; i < lines.length; i++) { line = lines[i] if (line.match(/^\s*\}/)) { indentation-- } result.push(_repeat('\t', indentation) + line) if (!line.match(/^\s*\/\//) && line.match(/\{\s*$/)) { indentation++ } } return result.join('\n') } var _compileModule = function(code, pathBase) { var mainModule = '__main__', modules = [mainModule] _replaceRequireStatements(mainModule, code, modules, pathBase) code = _concatModules(modules) code = _minifyRequireStatements(code, modules) return code } var _minifyRequireStatements = function(code, modules) { for (var i=0, modulePath; modulePath = modules[i]; i++) { var escapedPath = modulePath.replace(/\//g, '\\/'), regex = new RegExp('require\\["'+ escapedPath +'"\\]', 'g') code = code.replace(regex, 'require["_'+ i +'"]') } return code } var _globalRequireRegex = /require\s*\(['"][\w\/\.-]*['"]\)/g, _pathnameGroupingRegex = /require\s*\(['"]([\w\/\.-]*)['"]\)/ var _replaceRequireStatements = function(modulePath, code, modules, pathBase) { var requireStatements = code.match(_globalRequireRegex) if (!requireStatements) { modules[modulePath] = code return } for (var i=0, requireStatement; requireStatement = requireStatements[i]; i++) { var rawModulePath = requireStatement.match(_pathnameGroupingRegex)[1], isRelative = (rawModulePath[0] == '.'), // use node's resolution system is it's an installed package, e.g. require('socket.io/support/clients/socket.io') searchPath = isRelative ? path.join(pathBase, rawModulePath) : (util.resolve(rawModulePath) || '').replace(/\.js$/, ''), subModulePath = _findTruePath(searchPath, modules) code = code.replace(requireStatement, 'require["' + subModulePath + '"].exports') if (!modules[subModulePath]) { modules[subModulePath] = true var newPathBase = path.dirname(subModulePath), newModuleCode = fs.readFileSync(subModulePath + '.js').toString() _replaceRequireStatements(subModulePath, newModuleCode, modules, newPathBase) modules.push(subModulePath) } } modules[modulePath] = code } var _concatModules = function(modules) { var code = function(modulePath) { return [ ';(function() {', ' // ' + modulePath, ' var module = require["'+modulePath+'"] = {exports:{}}, exports = module.exports;', modules[modulePath], '})()' ].join('\n') } var moduleDefinitions = [] for (var i=1, modulePath; modulePath = modules[i]; i++) { moduleDefinitions.push(code(modulePath)) } moduleDefinitions.push(code(modules[0])) // __main__ return moduleDefinitions.join('\n\n') } var _findTruePath = function(modulePath, modules) { function tryPath(p) { return (!!modules[p] || path.existsSync(p+'.js')) } if (tryPath(modulePath)) { return modulePath } if (tryPath(modulePath + '/index')) { return modulePath + '/index' } if (tryPath(modulePath + 'index')) { return modulePath + 'index' } if (path.existsSync(modulePath + '/package.json')) { var main = JSON.parse(fs.readFileSync(modulePath + '/package.json').toString()).main.split('.')[0] if (main && tryPath(modulePath + '/' + main)) { return modulePath + '/' + main } } throw new Error('require compiler: could not resolve "' + modulePath + '"') } var _repeat = function(str, times) { if (times < 0) { return '' } return new Array(times + 1).join(str) }
JavaScript
0
@@ -4093,16 +4093,147 @@ dules)%0A%0A +%09%09if (!subModulePath) %7B%0A%09%09%09throw new Error('require compiler: could not resolve %22'+ subModulePath +'%22 in %22'+ modulePath +'%22')%0A%09%09%7D%0A%0A %09%09code = @@ -5711,85 +5711,8 @@ %0A%09%7D%0A -%09throw new Error('require compiler: could not resolve %22' + modulePath + '%22')%0A %7D%0A%0Av
a17a78c337cb5d47eea80feabbca987153368b45
Change block size
libs/services/cloudflare.js
libs/services/cloudflare.js
(function(module) { var _ = require("underscore"), CloudflareApi = require('./cloudflare/api'), Log = require('../models/log'), Repeater = require('../utils/repeater'); function Cloudflare(config) { this.api = new CloudflareApi(config.zoneId, config.authEmail, config.authKey); this.loadSize = 2000; _.bindAll(this, 'fetch', '_finish', '_process', 'initStartTime'); this.repeater = new Repeater(this.fetch, this, 1); this.logs = []; } var fn = Cloudflare.prototype; fn.fetchAll = function() { if (this.latest) { this.repeater.call(); } else { this.initStartTime(this.repeater.call); } }; fn.fetch = function() { if (this.latest) { this.api.logs({ count: this.loadSize, start: this.latest }, { process: this._process, finish: this._finish }); } }; fn._process = function(json) { var log = new Log(json).enrich(); this.logs.push(log); }; fn._finish = function(count) { var that = this; Log.insertBatch(this.logs); this.latest = this.logs.pop().timestamp / 1000000000; this.logs = []; console.info('Loaded: %s', count); this.initStartTime(function() { that.repeater.callback(count >= (that.loadSize / 2.0)) }); }; fn.initStartTime = function(callback) { var that = this; Log.lastTimestamp(function(timestamp){ timestamp = timestamp || that.startTime() * 1000000000; that.latest = Math.ceil(timestamp / 1000000000); console.info('Latest %s', new Date(that.latest * 1000)); callback(); }); }; fn.startTime = function() { return Math.floor((new Date().getTime() / 1000) - 3600 * 24 * 2) }; module.exports = Cloudflare; })(module);
JavaScript
0.000001
@@ -319,17 +319,17 @@ dSize = -2 +1 000;%0A%0A @@ -448,16 +448,17 @@ this, 1 +0 );%0A t
9b65e4d29f430f353a2db688b998348903366e15
fix height calculation for box-sizing:border-box with a border
src/calculateNodeHeight.js
src/calculateNodeHeight.js
/** * calculateNodeHeight(uiTextNode, useCache = false) */ const HIDDEN_TEXTAREA_STYLE = ` height:0; visibility:hidden; overflow:hidden; position:absolute; z-index:-1000; top:0; right:0 `; const SIZING_STYLE = [ 'letter-spacing', 'line-height', 'padding-top', 'padding-bottom', 'font-family', 'font-weight', 'font-size', 'text-transform', 'width', 'padding-left', 'padding-right', 'border-width', 'box-sizing' ]; let computedStyleCache = {}; let hiddenTextarea; export default function calculateNodeHeight(uiTextNode, useCache = false, minRows = null, maxRows = null) { if (!hiddenTextarea) { hiddenTextarea = document.createElement('textarea'); document.body.appendChild(hiddenTextarea); } // Copy all CSS properties that have an impact on the height of the content in // the textbox let {sizingStyle, sumVerticalPaddings} = calculateNodeStyling(uiTextNode, useCache); // Need to have the overflow attribute to hide the scrollbar otherwise // text-lines will not calculated properly as the shadow will technically be // narrower for content hiddenTextarea.setAttribute('style', sizingStyle + ';' + HIDDEN_TEXTAREA_STYLE); hiddenTextarea.value = uiTextNode.value; let height = hiddenTextarea.scrollHeight - sumVerticalPaddings; let minHeight = -Infinity; let maxHeight = Infinity; if (minRows !== null || maxRows !== null) { // measure height of a textarea with a single row hiddenTextarea.value = 'x'; let singleRowHeight = hiddenTextarea.scrollHeight - sumVerticalPaddings; if (minRows !== null) { minHeight = singleRowHeight * minRows; height = Math.max(minHeight, height); } if (maxRows !== null) { maxHeight = singleRowHeight * maxRows; height = Math.min(maxHeight, height); } } return {height, minHeight, maxHeight}; } function calculateNodeStyling(node, useCache = false) { let nodeRef = ( node.getAttribute('id') || node.getAttribute('data-reactid') || node.getAttribute('name') ); if (useCache && computedStyleCache[nodeRef]) { return computedStyleCache[nodeRef]; } let compStyle = window.getComputedStyle(node); let sumPaddings = 0; // If the textarea is set to border-box, it's not necessary to // subtract the padding. if ( compStyle.getPropertyValue('box-sizing') !== 'border-box' && compStyle.getPropertyValue('-moz-box-sizing') !== 'border-box' && compStyle.getPropertyValue('-webkit-box-sizing') !== 'border-box' ) { sumPaddings = ( parseFloat(compStyle.getPropertyValue('padding-bottom')) + parseFloat(compStyle.getPropertyValue('padding-top')) ); } let nodeInfo = { sizingStyle: SIZING_STYLE .map(name => `${name}:${compStyle.getPropertyValue(name)}`) .join(';'), sumVerticalPaddings: sumPaddings }; if (useCache && nodeRef) { computedStyleCache[nodeRef] = nodeInfo; } return nodeInfo; }
JavaScript
0
@@ -869,35 +869,32 @@ gStyle, -sumVerticalPaddings +heightAdjustment %7D = calc @@ -1282,37 +1282,34 @@ lHeight -- sumVerticalPaddings ++ heightAdjustment ;%0A let @@ -1550,29 +1550,26 @@ ght -- sumVerticalPaddings ++ heightAdjustment ;%0A @@ -2192,193 +2192,291 @@ %0A%0A -let sumPaddings = 0;%0A%0A // If the textarea is set to border-box, it's not necessary to%0A // subtract the padding.%0A if (%0A compStyle.getPropertyValue('box-sizing') !== 'border-box' && +// scrollHeight = content + padding; depending on what box-sizing is%0A // set to, we'll need an adjustment when we set the new height%0A let heightAdjustment = 0;%0A%0A let boxSizing = (%0A compStyle.getPropertyValue('box-sizing') %7C%7C%0A compStyle.getPropertyValue('-moz-box-sizing') %7C%7C %0A @@ -2497,35 +2497,38 @@ PropertyValue('- -moz +webkit -box-sizing') != @@ -2528,123 +2528,386 @@ ng') - !== 'border-box' &&%0A compStyle.getPropertyValue('-webkit-box-sizing') !== 'border-box'%0A ) %7B%0A sumPaddings = +%0A );%0A // border-box: add border, since height = content + padding + border%0A if (boxSizing === 'border-box') %7B%0A heightAdjustment = (%0A parseFloat(compStyle.getPropertyValue('border-bottom')) +%0A parseFloat(compStyle.getPropertyValue('border-top'))%0A );%0A %7D else if (boxSizing === 'content-box') %7B // remove padding, since height = content%0A heightAdjustment = - (%0A @@ -3182,40 +3182,24 @@ -sumVerticalPaddings: sumPaddings +heightAdjustment %0A %7D
f56efd64719cf780163c914f1e690704e6ae0482
Fix exceptions in ProxyContext when drawing bitmaps.
src/canvas/ProxyContext.js
src/canvas/ProxyContext.js
/* * Paper.js - The Swiss Army Knife of Vector Graphics Scripting. * http://paperjs.org/ * * Copyright (c) 2011 - 2014, Juerg Lehni & Jonathan Puckey * http://scratchdisk.com/ & http://jonathanpuckey.com/ * * Distributed under the MIT license. See LICENSE file for details. * * All rights reserved. */ /** * @name ProxyContext * * @class The ProxyContext is a helper class that helps Canvas debugging * by logging all interactions with a 2D Canvas context. * * @private * * @classexample * view._context = new ProxyContext(view._context); */ var ProxyContext = new function() { var descriptions = [ 'save()', 'restore()', 'scale(x,y)', 'rotate(angle)', 'translate(x,y)', 'transform(a,b,c,d,e,f)', 'setTransform(a,b,c,d,e,f)', 'globalAlpha', 'globalCompositeOperation', 'strokeStyle', 'fillStyle', 'createLinearGradient(x0,y0,x1,y1)', 'createRadialGradient(x0,y0,r0,x1,y1,r1)', 'createPattern(image,repetition)', 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'shadowOffsetX', 'shadowOffsetY', 'shadowBlur', 'shadowColor', 'clearRect(x,y,w,h)', 'fillRect(x,y,w,h)', 'strokeRect(x,y,w,h)', 'beginPath()', 'closePath()', 'moveTo(x,y)', 'lineTo(x,y)', 'quadraticCurveTo(cpx,cpy,x,y)', 'bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y)', 'arcTo(x1,y1,x2,y2,radius)', 'rect(x,y,w,h)', 'arc(x,y,radius,startAngle,endAngle,anticlockwise)', 'fill()', 'stroke()', 'drawSystemFocusRing()', 'drawCustomFocusRing()', 'scrollPathIntoView()', 'clip()', 'isPointInPath(x,y)', 'font', 'textAlign', 'textBaseline', 'fillText(text,x,y,maxWidth)', 'strokeText(text,x,y,maxWidth)', 'measureText(text)', 'drawImage(image,dx,dy)', 'drawImage(image,dx,dy,dw,dh)', 'drawImage(image,sx,sy,sw,sh,dx,dy,dw,dh)', 'createImageData(sw,sh)', 'createImageData(imagedata)', 'getImageData(sx,sy,sw,sh)', 'putImageData(imagedata,dx,dy,dirtyX,dirtyY,dirtyWidth,dirtyHeight)', 'setLineDash(array)', 'lineDashOffset' ]; var fields = /** @lends ProxyContext# */ { initialize: function(context) { this._ctx = context; this._indents = 0; }, getIndentation: function() { var str = ''; for (var i = 0; i < this._indents; i++) { str += ' '; } return str; } }; Base.each(descriptions, function(description) { var match = description.match(/^([^(]+)(\()*/), name = match[1], isFunction = !!match[2]; if (isFunction) { fields[name] = function() { if (name === 'restore') this._indents--; console.log(this.getIndentation() + 'ctx.' + name + '(' + Array.prototype.slice.call(arguments, 0) .map(JSON.stringify).join(', ') + ');'); if (name === 'save') this._indents++; return this._ctx[name].apply(this._ctx, arguments); }; } else { fields[name] = { get: function() { return this._ctx[name]; }, set: function(value) { console.log(this.getIndentation() + 'ctx.' + name + ' = ' + JSON.stringify(value) + ';'); return this._ctx[name] = value; } }; } }); return Base.extend(fields); };
JavaScript
0
@@ -2200,16 +2200,133 @@ %09%09%7D%0A%09%7D;%0A +%0A%09function stringify(value) %7B%0A%09%09try %7B%0A%09%09%09return JSON.stringify(value);%0A%09%09%7D catch (e) %7B%0A%09%09%09return value + '';%0A%09%09%7D%0A%09%7D%0A%0A %09Base.ea @@ -2686,21 +2686,16 @@ %09%09%09.map( -JSON. stringif @@ -3012,16 +3012,16 @@ + ' = '%0A + %09%09%09%09%09%09%09+ @@ -3021,21 +3021,16 @@ %09%09%09%09%09%09+ -JSON. stringif
3a79bea2d1134369251e4b7876a39c18b552bc38
Add support for resolving module aliases to stripes config plugin
webpack/stripes-config-plugin.js
webpack/stripes-config-plugin.js
// This webpack plugin generates a virtual module containing the stripes configuration // To access this configuration simply import 'stripes-config' within your JavaScript: // import { okapi, config, modules } from 'stripes-config'; const path = require('path'); const assert = require('assert'); const _ = require('lodash'); const VirtualModulesPlugin = require('webpack-virtual-modules'); const serialize = require('serialize-javascript'); // Loads description, version, and stripes configuration from a module's package.json function loadDefaults(context, moduleName) { const aPath = require.resolve(path.join(context, 'node_modules', moduleName, '/package.json')); const { stripes, description, version } = require(aPath); // eslint-disable-line assert(_.isObject(stripes, `included module ${moduleName} does not have a "stripes" key in package.json`)); assert(_.isString(stripes.type, `included module ${moduleName} does not specify stripes.type in package.json`)); return { stripes, description, version }; } function appendOrSingleton(maybeArray, newValue) { const singleton = [newValue]; if (Array.isArray(maybeArray)) return maybeArray.concat(singleton); return singleton; } // Generates stripes configuration for the tenant's enabled modules function parseStripesModules(enabledModules, context) { const moduleConfigs = {}; _.forOwn(enabledModules, (moduleConfig, moduleName) => { const { stripes, description, version } = loadDefaults(context, moduleName); const stripeConfig = Object.assign({}, stripes, moduleConfig, { module: moduleName, getModule: eval(`() => require('${moduleName}').default`), // eslint-disable-line no-eval description, version, }); delete stripeConfig.type; moduleConfigs[stripes.type] = appendOrSingleton(moduleConfigs[stripes.type], stripeConfig); }); return moduleConfigs; } module.exports = class StripesConfigPlugin { constructor(options) { assert(_.isObject(options.modules), 'stripes-config-plugin was not provided a "modules" object for enabling stripes modules'); this.options = options; } apply(compiler) { const enabledModules = this.options.modules; const moduleConfigs = parseStripesModules(enabledModules, compiler.context); const mergedConfig = Object.assign({}, this.options, { modules: moduleConfigs }); // Create a virtual module for Webpack to include in the build compiler.apply(new VirtualModulesPlugin({ 'node_modules/stripes-config.js': `module.exports = ${serialize(mergedConfig, { space: 2 })}`, })); } };
JavaScript
0
@@ -567,27 +567,156 @@ duleName -) %7B%0A const +, alias) %7B%0A let aPath;%0A if (alias%5BmoduleName%5D) %7B%0A aPath = require.resolve(path.join(alias%5BmoduleName%5D, 'package.json'));%0A %7D else %7B%0A aPath = @@ -798,16 +798,21 @@ son'));%0A + %7D%0A%0A const @@ -1454,16 +1454,23 @@ context +, alias ) %7B%0A co @@ -1630,16 +1630,23 @@ duleName +, alias );%0A c @@ -2334,16 +2334,16 @@ odules;%0A - cons @@ -2412,16 +2412,48 @@ .context +, compiler.options.resolve.alias );%0A c
caa04034ccb9e04b56605e6988d945880b5e172f
Add more stability around ffmpeg starting. prevent twice
src/encoder/index.js
src/encoder/index.js
const ffmpeg = require('fluent-ffmpeg') const bunyan = require('bunyan') const path = require('path') const buildUrl = require('build-url') const mkdirp = require('mkdirp') const _ = require('lodash') ;(function () { let localConfig = {} let deviceState = {} let ffmpegProcess let logger let ignoreNextError = false process.on('exit', function () { if (ffmpegProcess) { ignoreNextError = true ffmpegProcess.kill() ffmpegProcess = null } }) function getInput (config, state) { if (!_.isEmpty(config.inputSourceOverride)) { return config.inputSourceOverride } else { // TODO: verify cameraIp, cameraPort, rtmpStreamPath let baseUrl = 'rtsp://' + state.cameraIp + ':' + state.cameraPort let fullUrl = buildUrl(baseUrl, { path: state.rtmpStreamPath }) return fullUrl } } function startEncoder () { // start ffmpeg const outputFile = path.join(localConfig.tmpDirectory, '/video/', 'output%Y-%m-%d_%H-%M-%S.ts') const inputFile = getInput(localConfig, deviceState) ignoreNextError = false ffmpegProcess = ffmpeg(inputFile) .format('segment') .outputOptions([ '-segment_time 8', '-reset_timestamps 1', '-strftime 1', '-segment_start_number 1', '-segment_time_delta 0.3', // '-segment_format mp4', '-c copy' ]) .on('start', function () { logger.info({ input: inputFile, output: outputFile }, 'ffmpeg started.') }) .on('error', function (err, stdout, stderr) { // if graceful exit (ie remote encoder stop) if (ignoreNextError) { ignoreNextError = false return } logger.info({ input: inputFile, output: outputFile, error: err }, 'ffmpeg error') // attempt to restart ffmpeg if applicable if (deviceState.encoderEnabled) { ffmpegProcess = null setTimeout(function () { startEncoder() }, 5000) } }) .on('end', function () { logger.info({ input: inputFile, output: outputFile }, 'ffmpeg ended.') // attempt to restart ffmpeg if applicable if (deviceState.encoderEnabled) { ffmpegProcess = null setTimeout(function () { startEncoder() }, 10000) } }) .save(outputFile) } function stopEncoder () { if (ffmpegProcess) { ignoreNextError = true ffmpegProcess.kill() ffmpegProcess = null } } function init (config) { localConfig = config logger = bunyan.createLogger({ name: 'encoder-log', deviceId: localConfig.deviceId, streams: [{ type: 'rotating-file', level: 'info', path: path.join(config.loggingPath, 'encoder-log.log'), period: '1d', // daily rotation count: 3 // keep 3 back copies }, { stream: process.stdout, level: 'debug' }] }) mkdirp(path.join(localConfig.tmpDirectory, '/video/')) } function ProcessUpdatedDeviceState (state) { deviceState = state if (deviceState.encoderEnabled && !ffmpegProcess) { startEncoder() } else if (!deviceState.encoderEnabled && !!ffmpegProcess) { stopEncoder() } } function buildEncoderStatusMessage () { return { type: 'StatusUpdate', payload: { ffmpegRunning: !!ffmpegProcess } } } process.on('message', function (msg) { if (!msg) return if (msg.type === 'Init') { init(msg.payload) } else if (msg.type === 'DeviceStateChanged') { ProcessUpdatedDeviceState(msg.payload) } }) setInterval(function () { process.send(buildEncoderStatusMessage()) }, 10000) })()
JavaScript
0.000025
@@ -319,16 +319,45 @@ = false +%0A let ffmpegStarting = false %0A%0A proc @@ -431,32 +431,61 @@ extError = true%0A + ffmpegStarting = false%0A ffmpegProc @@ -1152,24 +1152,50 @@ ror = false%0A + ffmpegStarting = true%0A ffmpegPr @@ -1725,32 +1725,83 @@ , function () %7B%0A + ffmpegStarting = false%0A @@ -2070,24 +2070,75 @@ , stderr) %7B%0A + ffmpegStarting = false%0A @@ -3026,32 +3026,83 @@ , function () %7B%0A + ffmpegStarting = false%0A @@ -3780,32 +3780,61 @@ extError = true%0A + ffmpegStarting = false%0A ffmpegProc @@ -4481,16 +4481,121 @@ = state%0A + // if it should be running, and it isn't currently starting, and it isn't current running - start it%0A if ( @@ -4623,16 +4623,35 @@ abled && + !ffmpegStarting && !ffmpeg @@ -4678,24 +4678,91 @@ rtEncoder()%0A + // if it should be off - but it is currently running - stop it%0A %7D else i
8a2e339cb5d5d96d22c58dd2b8a2ca7ee9457567
fix browserify watch log
src/tasks/js.js
src/tasks/js.js
'use strict'; function jsTask(gulp) { var source = require('vinyl-source-stream'); var watchify = require('watchify'); var browserify = require('browserify'); var gutil = require('gulp-util'); var uglify = require('gulp-uglify'); var streamify = require('gulp-streamify'); var rev = require('gulp-rev'); var errorLog = require('../errorLog'); var config = require('../internalOptions'); gulp.task('js', ['bower'], function() { var bundler; function rebundle() { var stream; stream = bundler.bundle(); if (config.dev) { stream = stream.on('error', errorLog('Browserify')); } stream = stream.pipe(source('index.js')); if (!config.dev) { stream = stream .pipe(streamify(uglify())) .pipe(streamify(rev())); } stream = stream .pipe(gulp.dest(config.dev ? 'dev/' : 'dist/')) .on('end', function() { gutil.log(gutil.colors.magenta('browserify'), 'finished'); }); return stream; } gutil.log(gutil.colors.magenta('browserify'), 'starting...'); bundler = browserify({ cache: {}, packageCache: {}, fullPaths: true, entries: ['./src/index.js'], debug: config.dev }); bundler.transform(require('debowerify')); bundler.transform(require('browserify-ngannotate')); if (config.dev) { bundler = watchify(bundler); bundler.on('update', function(changedFiles) { gutil.log('Starting', gutil.colors.cyan('browserify'), 'file', event.path, 'changed'); }); bundler.on('update', rebundle); } return rebundle(); }); } module.exports = jsTask;
JavaScript
0.000001
@@ -1551,18 +1551,20 @@ e', -event.path +changedFiles , 'c
278c88f9cd58f1fda6e96164900a23baa61af63f
Remove this useless assignment to local variable
generators/client/templates/src/main/webapp/app/components/util/_base64.service.js
generators/client/templates/src/main/webapp/app/components/util/_base64.service.js
(function() { /*jshint bitwise: false*/ 'use strict'; angular .module('<%=angularAppName%>') .factory('Base64', Base64); function Base64 () { var keyStr = 'ABCDEFGHIJKLMNOP' + 'QRSTUVWXYZabcdef' + 'ghijklmnopqrstuv' + 'wxyz0123456789+/' + '='; var service = { decode : decode, encode : encode }; return service; function encode (input) { var output = '', chr1, chr2, chr3 = '', enc1, enc2, enc3, enc4 = '', i = 0; while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); chr1 = chr2 = chr3 = ''; enc1 = enc2 = enc3 = enc4 = ''; } return output; } function decode (input) { var output = '', chr1, chr2, chr3 = '', enc1, enc2, enc3, enc4 = '', i = 0; // remove all characters that are not A-Z, a-z, 0-9, +, /, or = input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); while (i < input.length) { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 !== 64) { output = output + String.fromCharCode(chr2); } if (enc4 !== 64) { output = output + String.fromCharCode(chr3); } chr1 = chr2 = chr3 = ''; enc1 = enc2 = enc3 = enc4 = ''; } return output; } } })();
JavaScript
0.000001
@@ -533,37 +533,32 @@ chr1, chr2, chr3 - = '' ,%0A @@ -573,37 +573,32 @@ enc2, enc3, enc4 - = '' ,%0A @@ -1337,97 +1337,8 @@ 4);%0A - chr1 = chr2 = chr3 = '';%0A enc1 = enc2 = enc3 = enc4 = '';%0A @@ -1481,21 +1481,16 @@ r2, chr3 - = '' ,%0A @@ -1521,21 +1521,16 @@ c3, enc4 - = '' ,%0A @@ -2395,16 +2395,16 @@ (chr3);%0A + @@ -2416,98 +2416,8 @@ %7D -%0A%0A chr1 = chr2 = chr3 = '';%0A enc1 = enc2 = enc3 = enc4 = ''; %0A
6ce99ce4acbed8c57b672706c4b26dfc063bb04b
Allow a block to be specified for loading
extensionloader.js
extensionloader.js
/* Load a block from github.io. Accepts a url as a parameter which can include url parameters e.g. https://megjlow.github.io/extension2.js?name=SUN&ip=10.0.0.1 */ new (function() { var ext = this; var descriptor = { blocks: [ [' ', 'Load extension block %s', 'loadBlock', 'url', 'url'], ], url: 'http://www.warwick.ac.uk/tilesfortales' }; ext._shutdown = function() {}; ext._getStatus = function() { return {status: 2, msg: 'Device connected'} }; ext.loadBlock = function(url) { ScratchExtensions.loadExternalJS(url); }; ScratchExtensions.register("extensionloader", descriptor, ext); });
JavaScript
0.000001
@@ -194,16 +194,537 @@ this;%0A%09%0A +%09var getUrlParameter = function getUrlParameter(sParam) %7B%0A%09 var sPageURL = decodeURIComponent(document.currentScript.src.split(%22?%22)%5B1%5D),%0A%09 sURLVariables = sPageURL.split('&'),%0A%09 sParameterName,%0A%09 i;%0A%09%0A%09 for (i = 0; i %3C sURLVariables.length; i++) %7B%0A%09 sParameterName = sURLVariables%5Bi%5D.split('=');%0A%09%0A%09 if (sParameterName%5B0%5D === sParam) %7B%0A%09 return sParameterName%5B1%5D === undefined ? true : sParameterName%5B1%5D;%0A%09 %7D%0A%09 %7D%0A%09%7D;%0A%09%0A%09ext.url = getUrlParameter(%22extUrl%22);%0A%09%0A %09var des @@ -1171,13 +1171,81 @@ , ext);%0A + %09%0A %09if(ext.url != undefined) %7B%0A %09%09ext.loadBlock(ext.url);%0A %7D%0A %09%0A%7D);
8a08717f71f466090e91894400a2e9beaf9e0404
make install command resolve a boolean value
lib/commands/install.js
lib/commands/install.js
'use strict' var path = require('path') var fs = require('fs') var Promise = require('bluebird') var childProcess = require('child_process') var platform = require('os').platform() var description = 'WINDOWS ONLY - install app as windows service, For other platforms see http://jsreport.net/on-prem/downloads' var command = 'install' exports.command = command exports.description = description exports.builder = function (yargs) { return ( yargs .usage(description + '\nUsage: $0 ' + command) .check(function (argv, hash) { if (argv.serverUrl) { throw new Error('serverUrl option is not supported in this command') } return true }) ) } exports.handler = function (argv) { return new Promise(function (resolve, reject) { var cwd = argv.context.cwd var existsPackageJson = fs.existsSync(path.join(cwd, './package.json')) var hasEntry = false var userPkg var serviceName var pathToWinser var env console.log('Platform is ' + platform) if (platform !== 'win32') { console.log('Installing app as windows service only works on windows platforms..') console.log('Installing jsreport as startup service for your platform should be described at http://jsreport.net/downloads') return resolve() } if (!existsPackageJson) { return reject(new Error('To install app as windows service you need a package.json file..')) } userPkg = require(path.join(cwd, './package.json')) if (!userPkg.name) { return reject(new Error('To install app as windows service you need a "name" field in package.json file..')) } serviceName = userPkg.name if (userPkg.scripts && userPkg.scripts.start) { hasEntry = true } else if (userPkg.main) { hasEntry = true } if (!hasEntry) { return reject(new Error('To install app as windows service you need to have a "start" script or a "main" field in package.json file..')) } console.log('Installing windows service "' + serviceName + '" for app..') try { pathToWinser = path.dirname(require.resolve('winser')) pathToWinser = path.resolve(pathToWinser, '../.bin/winser.cmd') pathToWinser = '"' + pathToWinser + '"' env = ' --env NODE_ENV=' + process.env.NODE_ENV || 'development' } catch (e) { if (e.code === 'MODULE_NOT_FOUND') { return reject(new Error('couldn\'t find "winser" package')) } return reject(new Error('Unexpected error happened: ' + e.message)) } childProcess.exec(pathToWinser + ' -i ' + env, { cwd: cwd }, function (error, stdout, stderr) { if (error) { return reject(error) } console.log('Starting windows service "' + serviceName + '".') childProcess.exec('net start ' + serviceName, function (error, stdout, stder) { if (error) { return reject(error) } console.log('Service "' + serviceName + '" is running.') resolve() }) }) }) }
JavaScript
0.000038
@@ -1282,24 +1282,29 @@ urn resolve( +false )%0A %7D%0A%0A @@ -3001,16 +3001,20 @@ resolve( +true )%0A
997ef4147d96618cd4f1c57289e98004b7b7eb7d
Stop relying on `ts-node` from the global scope
extra/_buildAll.js
extra/_buildAll.js
const childProcess = require("child_process"); const fs = require("fs"); if (process.argv.length !== 3) { throw new Error("Requires the base path as argument."); } const basePath = process.argv[2]; if (!basePath.match(/[\\\/]$/)) { throw new Error("Path must end with a slash - any slash will do."); } else if (!fs.existsSync(basePath)) { throw new Error(`Invalid path, '${basePath}' does not exist or is not readable.`); } fs.readdirSync(basePath) .filter(directory => { if (directory.indexOf('.') !== 0 && fs.statSync(basePath + directory).isDirectory()) { // filter by known repository name patterns if (directory === "WCF" || directory.indexOf("com.woltlab.") === 0) { return true; } } return false; }) .forEach(directory => { console.log(`##### Building ${directory} #####\n`); let path = basePath + directory; if (directory === "WCF") { childProcess.execSync(`node _buildCore.js`, { stdio: [0, 1, 2] }); } else { childProcess.execSync(`node _buildExternal.js ${path}`, { stdio: [0, 1, 2] }); } childProcess.execSync(`ts-node syncTemplates.ts ${path}`, { stdio: [0, 1, 2] }); console.log("\n"); });
JavaScript
0
@@ -1258,16 +1258,20 @@ ecSync(%60 +npx ts-node
a49c5eaebc86184d861a17f1aca7cb28b6b6d799
remove existing files
extract-locales.js
extract-locales.js
/** * Copyright (c) ppy Pty Ltd <contact@ppy.sh>. * * This file is part of osu!web. osu!web is distributed with the hope of * attracting more community contributions to the core ecosystem of osu!. * * osu!web is free software: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License version 3 * as published by the Free Software Foundation. * * osu!web is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with osu!web. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; const { spawnSync } = require('child_process'); const fs = require('fs'); const path = require('path'); const mkdirp = require('mkdirp'); const buildPath = path.resolve(__dirname, 'resources/assets/build'); const localesPath = path.resolve(buildPath, 'locales'); const messagesPath = path.resolve(buildPath, 'messages.json'); function extractLanguages() { console.log('Extracting localizations...') const messages = getAllMesssages(); const languages = new Map(); for (const key in messages) { const index = key.indexOf('.'); const language = key.substring(0, index); if (!languages.has(language)) { languages.set(language, {}); } languages.get(language)[key] = messages[key]; } return languages; } function getAllMesssages() { const content = fs.readFileSync(messagesPath); return JSON.parse(content); } function generateTranslations() { spawnSync('php', ['artisan', 'lang:js', '--json', messagesPath], { stdio: 'inherit' }); } function writeTranslations(languages) { for (const lang of languages.keys()) { const json = JSON.stringify(languages.get(lang)); const filename = path.resolve(localesPath, `${lang}.js`); const script = `(function() { 'use strict'; Object.assign(Lang.messages, ${json}); })();`; fs.writeFileSync(filename, script); console.log(`Created: ${filename}`); } } mkdirp.sync(localesPath); generateTranslations(); writeTranslations(extractLanguages()); // copy lang.js fs.copyFileSync( path.resolve(__dirname, 'vendor/mariuzzo/laravel-js-localization/lib/lang.min.js'), path.resolve(buildPath, 'lang.js') ); // cleanup fs.unlinkSync(messagesPath); console.log(`Removed: ${messagesPath}`);
JavaScript
0.000003
@@ -863,24 +863,54 @@ uire('fs');%0A +const glob = require('glob');%0A const path = @@ -2185,16 +2185,148 @@ %0A %7D%0A%7D%0A%0A +// Remove previous existing files and ensure directory exists.%0Aglob.sync(path.resolve(localesPath, '*.js')).forEach(fs.unlinkSync);%0A mkdirp.s @@ -2343,16 +2343,17 @@ sPath);%0A +%0A generate
b0140c63641193e218f7aa398f66ce77fb398b88
Add rating tooltip
src/chrome/RatingButton.js
src/chrome/RatingButton.js
/** * Copyright 2018-present Facebook. * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * @format */ import {Component, type Element} from 'react'; import {Glyph} from 'flipper'; import {getInstance as getLogger} from '../fb-stubs/Logger'; import GK from '../fb-stubs/GK'; type Props = { rating: ?number, onRatingChanged: number => void, }; type State = { hoveredRating: ?number, }; export default class RatingButton extends Component<Props, State> { state = { hoveredRating: null, }; onRatingChanged(rating: number) { const previousRating = this.props.rating; if (rating === previousRating) { return; } this.props.onRatingChanged(rating); getLogger().track('usage', 'flipper-rating-changed', { rating, previousRating, }); } render() { if (!GK.get('flipper_rating')) { return null; } const rating = this.props.rating || 0; if (rating < 0 || rating > 5) { throw new Error(`Rating must be between 0 and 5. Value: ${rating}`); } const stars = Array(5) .fill(true) .map<Element<*>>((_, index) => ( <div role="button" tabIndex={0} onMouseEnter={() => { this.setState({hoveredRating: index + 1}); }} onMouseLeave={() => { this.setState({hoveredRating: null}); }} onClick={() => { this.onRatingChanged(index + 1); }}> <Glyph name="star" color="grey" variant={ (this.state.hoveredRating ? index < this.state.hoveredRating : index < rating) ? 'filled' : 'outline' } /> </div> )); return stars; } }
JavaScript
0.000001
@@ -206,16 +206,26 @@ Element +, Fragment %7D from ' @@ -245,16 +245,25 @@ t %7BGlyph +, Tooltip %7D from ' @@ -1867,20 +1867,204 @@ -return stars +const button = %3CFragment%3E%7Bstars%7D%3C/Fragment%3E;%0A return (%0A %3CTooltip%0A options=%7B%7Bposition: 'toLeft'%7D%7D%0A title=%22How would you rate Flipper?%22%0A children=%7Bbutton%7D%0A /%3E%0A ) ;%0A
f5191515265021eff799e62f03a010d34cf93b42
Add localized urls test to ReportSelector.test.js
src/tests/Main/ReportSelector.test.js
src/tests/Main/ReportSelector.test.js
import ReportSelecter from 'Main/ReportSelecter'; describe('ReportSelector', () => { test('getCode accepts report code', () => { expect(ReportSelecter.getCode('AB1CDEf2G3HIjk4L')).toBe('AB1CDEf2G3HIjk4L'); }); test('getCode accepts base url', () => { expect(ReportSelecter.getCode('https://www.warcraftlogs.com/reports/AB1CDEf2G3HIjk4L')).toBe('AB1CDEf2G3HIjk4L'); expect(ReportSelecter.getCode('https://www.warcraftlogs.com/reports/AB1CDEf2G3HIjk4L/')).toBe('AB1CDEf2G3HIjk4L'); }); test('getCode accepts relative url', () => { expect(ReportSelecter.getCode('reports/AB1CDEf2G3HIjk4L')).toBe('AB1CDEf2G3HIjk4L'); expect(ReportSelecter.getCode('reports/AB1CDEf2G3HIjk4L/')).toBe('AB1CDEf2G3HIjk4L'); }); test('getCode accepts report code with hashtag', () => { expect(ReportSelecter.getCode('AB1CDEf2G3HIjk4L#fight=6&type=healing&source=10')).toBe('AB1CDEf2G3HIjk4L'); expect(ReportSelecter.getCode('AB1CDEf2G3HIjk4L/#fight=6&type=healing&source=10')).toBe('AB1CDEf2G3HIjk4L'); }); test('getCode accepts full url with hashtag', () => { expect(ReportSelecter.getCode('https://www.warcraftlogs.com/reports/AB1CDEf2G3HIjk4L#fight=6&type=healing&source=10')).toBe('AB1CDEf2G3HIjk4L'); expect(ReportSelecter.getCode('https://www.warcraftlogs.com/reports/AB1CDEf2G3HIjk4L/#fight=6&type=healing&source=10')).toBe('AB1CDEf2G3HIjk4L'); }); test('getCode knows to only match the part between reports and #', () => { expect(ReportSelecter.getCode('https://www.AAAAAAAAAAAAAAAA.com/reports/AB1CDEf2G3HIjk4L#fight=6&type=healing&source=10')).toBe('AB1CDEf2G3HIjk4L'); expect(ReportSelecter.getCode('https://www.AAAAAAAAAAAAAAAA.com/reports/AB1CDEf2G3HIjk4L#fight=6&type=AAAAAAAAAAAAAAAA&source=10')).toBe('AB1CDEf2G3HIjk4L'); }); test('getCode does not accept malformed report codes', () => { expect(ReportSelecter.getCode('https://www.warcraftlogs.com/reports/AB1CDEf2G3HIjk4#fight=6&type=healing&source=10')).toBe(null); expect(ReportSelecter.getCode('https://www.warcraftlogs.com/reports/AB1CDEf2G3HIjk-4#fight=6&type=healing&source=10')).toBe(null); expect(ReportSelecter.getCode('https://www.warcraftlogs.com/reports/AB1CDEf2G3HIjk4AA#fight=6&type=healing&source=10')).toBe(null); expect(ReportSelecter.getCode('https://www.warcraftlogs.com/reports/#fight=6&type=healing&source=10')).toBe(null); expect(ReportSelecter.getCode('https://www.warcraftlogs.com/')).toBe(null); }); });
JavaScript
0.000001
@@ -95,32 +95,41 @@ getCode accepts +just the report code', () @@ -126,32 +126,32 @@ code', () =%3E %7B%0A - expect(Repor @@ -250,16 +250,23 @@ ts base +report url', () @@ -1389,32 +1389,330 @@ HIjk4L');%0A %7D);%0A + test('getCode accepts localized urls', () =%3E %7B%0A expect(ReportSelecter.getCode('https://de.warcraftlogs.com/reports/AB1CDEf2G3HIjk4L')).toBe('AB1CDEf2G3HIjk4L');%0A expect(ReportSelecter.getCode('https://kr.warcraftlogs.com/reports/AB1CDEf2G3HIjk4L/#fight=3')).toBe('AB1CDEf2G3HIjk4L');%0A %7D);%0A test('getCode @@ -2674,32 +2674,32 @@ ')).toBe(null);%0A - expect(Repor @@ -2762,16 +2762,117 @@ (null);%0A + expect(ReportSelecter.getCode('https://www.warcraftlogs.com/reports/%3Creport code%3E')).toBe(null);%0A %7D);%0A%7D)
8e228a60a648b43b84fb9ec017a8cda790234ad3
Add in naked domain
iptorrents-combine-upload-totals.user.js
iptorrents-combine-upload-totals.user.js
// ==UserScript== // @name IPTorrents - Combine Upload Totals // @namespace http://github.com/taeram/user-scripts // @description Combine "Uploaded" totals on the Peers page // @match https://www.iptorrents.com/peers?*;o=4 // @grant none // @copyright Jesse Patching // @version 1.2.2 // @license MIT https://github.com/taeram/user-scripts/blob/master/LICENSE // @updateURL https://raw.github.com/taeram/user-scripts/master/iptorrents-combine-upload-totals.user.js // @downloadURL https://raw.github.com/taeram/user-scripts/master/iptorrents-combine-upload-totals.user.js // ==/UserScript== /* jshint -W097 */ 'use strict'; var sortedRows = []; var rows = $('table.t1 tr'); for (var i=1; i < rows.length; i++) { // Grab the Uploaded column var uploadedEl = $(rows[i]).find('td:nth-child(4)'); if (!uploadedEl.length > 0) { $(rows[i]).remove(); continue; } // If this torrent has been seeded for >= 2 weeks, colour it's background green if ($(rows[i]).find('td:nth-child(8)').text().match(/to go/) == null) { $(rows[i]).attr('style', 'background-color: #1F351F'); } // Extract the "currently uploaded (uploaded from previous IP address)" values var uploaded = uploadedEl.text().match(/([\d+\.]+) (\w+)( \(([\d+\.]+) (\w+)\))*$/); if (uploaded == null) { // Skip rows with no uploaded values continue; } // Grab the Seeding Time column var daysSeeding = null; var seedingTime = null; var seedingTimeEl = $(rows[i]).find('td:nth-child(8)'); if (seedingTimeEl) { var time = null; var unit = null; if (seedingTimeEl.text().match(/to go/)) { seedingTime = seedingTimeEl.text().match(/([\d+\.]+) (\w+) to go$/); time = parseFloat(seedingTime[1]); unit = seedingTime[2]; if (unit == 'weeks') { daysSeeding = 14 - time * 7; } else if (unit == 'days') { daysSeeding = 14 - time; } } else { seedingTime = seedingTimeEl.text().match(/([\d+\.]+) (\w+)$/); time = parseFloat(seedingTime[1]); unit = seedingTime[2]; if (unit == 'weeks') { daysSeeding = time * 7; } else if (unit == 'months') { daysSeeding = time * 30; } else if (unit == 'days') { daysSeeding = time; } } console.log(seedingTimeEl.text(), daysSeeding); } // Add in the currently uploaded values var currentUploaded = parseFloat(uploaded[1]); if (uploaded[2] == 'GB') { currentUploaded *= 1000; } // Add in the previously uploaded values, if they exist var oldUploaded = 0; if (uploaded[3]) { oldUploaded = parseFloat(uploaded[4]); if (uploaded[5] == 'GB') { oldUploaded *= 1000; } } // Total the values, and create an indexed array var totalUploaded = Math.round(parseFloat(currentUploaded + oldUploaded)); while (sortedRows[totalUploaded] !== undefined) { totalUploaded++; } var mbPerDay = totalUploaded / daysSeeding; sortedRows[mbPerDay] = rows[i]; var label = 'MB'; if (totalUploaded > 1000) { label = 'GB'; totalUploaded /= 1000; totalUploaded = parseFloat(totalUploaded, 2).toFixed(2); } $(uploadedEl).html(totalUploaded + ' ' + label + ' (' + parseFloat(mbPerDay).toFixed(0) + ' MB/day)'); } sortedRows = ksort(sortedRows); // Add the rows back to the table sorted by upload totals, descending for (var i in sortedRows) { var html = $(sortedRows[i])[0].outerHTML; sortedRows[i].remove(); $('table.t1 tr:nth-child(1)').after(html); } function ksort(inputArr) { var tmp_arr = {}, keys = [], sorter, i, k, that = this, strictForIn = false, populateArr = {}; // compare items numerically sorter = function(a, b) { return ((a + 0) - (b + 0)); }; // Make a list of key names for (k in inputArr) { if (inputArr.hasOwnProperty(k)) { keys.push(k); } } keys.sort(sorter); // Rebuild array with sorted key names for (i = 0; i < keys.length; i++) { k = keys[i]; tmp_arr[k] = inputArr[k]; if (strictForIn) { delete inputArr[k]; } } for (i in tmp_arr) { if (tmp_arr.hasOwnProperty(i)) { populateArr[i] = tmp_arr[i]; } } return populateArr; }
JavaScript
0.000001
@@ -247,16 +247,71 @@ s?*;o=4%0A +// @match https://iptorrents.com/peers?*;o=4%0A // @gran @@ -388,11 +388,11 @@ 1. -2.2 +3.0 %0A//
bcdc249356ab8c5d24fd5741bbf94ba38dcee6d0
Add help text for most common Unicamp email typos
lib/config/at_config.js
lib/config/at_config.js
AccountsTemplates.configure({ // Behaviour confirmPassword: true, enablePasswordChange: true, enforceEmailVerification: true, forbidClientAccountCreation: false, overrideLoginErrors: false, sendVerificationEmail: true, // Appearance showAddRemoveServices: false, showForgotPasswordLink: true, showLabels: false, showPlaceholders: true, // Client-side Validation continuousValidation: false, negativeFeedback: true, negativeValidation: true, positiveValidation: true, positiveFeedback: true, showValidating: true, // Privacy Policy and Terms of Use privacyUrl: 'https://www.facebook.com/groups/GrupoUnicamp/permalink/10152879705420446/', termsUrl: 'https://www.facebook.com/groups/GrupoUnicamp/permalink/10152879705420446/', // Redirects homeRoutePath: '/', redirectTimeout: 1000, // Hooks // onLogoutHook: myLogoutFunc, // onSubmitHook: mySubmitFunc, // Texts texts: { button: { signUp: "Fazer pré-cadastro" }, socialSignUp: "Register", socialIcons: { "meteor-developer": "fa fa-rocket" }, title: { forgotPwd: "Recover Your Passwod" }, }, }); _(['changePwd', 'enrollAccount', 'forgotPwd', 'resetPwd', 'verifyEmail', 'signUp']).each(function (routeCode) { AccountsTemplates.configureRoute(routeCode); } ); AccountsTemplates.configureRoute('signIn', { redirect: 'ridesList' }); Router.route('/sign-out', { name: 'signOut', onBeforeAction: AccountsTemplates.logout }); if (Meteor.isServer) { Accounts.validateNewUser(function (user) { var re = new RegExp(Meteor.settings.public.site.emailValidationRegExp, 'i'); var OK = re.exec(user.emails[0].address); if (OK) { return true; } else { throw new Meteor.Error(403, "Você precisa de um email @unicamp.br ou @xyz.unicamp.br (ex.: " + "@dac.unicamp.br, @students.ic.unicamp.br, @ifi.unicamp.br, etc.)." ); } }); }
JavaScript
0.000083
@@ -1558,24 +1558,64 @@ on (user) %7B%0A + var email = user.emails%5B0%5D.address;%0A var re = @@ -1708,47 +1708,784 @@ xec( -user.emails%5B0%5D.address);%0A if (OK) %7B%0A +email);%0A if (OK) %7B%0A if (%0A // Check if user attempted to use Unicamp's DAC/Alumni email but got%0A // it wrong.%0A // Example: 012345@unicamp.br, j012345@unicamp.br, ra012345@unicamp.br%0A /%5E%5Ba-z%5D*%5Cd%7B6%7D@unicamp.br$/i.exec(email) %7C%7C%0A // Example: ra012345@dac.unicamp.br, 012345@dac.unicamp.br%0A /@(dac%7Calumni).unicamp.br$/i.exec(email) &&%0A ! /%5E%5Ba-z%5D%7B1%7D%5Cd%7B6%7D@/i.exec(email)%0A ) %7B%0A throw new Meteor.Error(403,%0A %22Endere%C3%A7os de email da DAC devem seguir o padr%C3%A3o primeira letra do %22 +%0A %22primeiro nome + RA (6 d%C3%ADgitos) @dac.unicamp.br. Se voc%C3%AA %C3%A9 %22 +%0A %22ex-aluno(a), use @alumni.unicamp.br. Exemplos: %22 +%0A %22j123456@dac.unicamp.br, m654321@alumni.unicamp.br.%22%0A );%0A %7D else %7B%0A @@ -2499,16 +2499,24 @@ n true;%0A + %7D%0A %7D el
730f3f64d40d07fdd6bb69265b453f286058872a
fix label
js/orientation.js
js/orientation.js
//Manage the orientation jviz.modules.karyoviewer.prototype.orientation = function(value) { //Check the orientation value if(typeof value !== 'string'){ return this._orientation.actual; } //convert to lower case value = value.toLowerCase(); //Save the orientation this._orientation.actual = (this._orientation.values.indexOf(value) === -1) ? this._orientation.default : value; //Resize the canvas this.resize(); //Check the orientation if(this.isLandscape() === true) { //Set the feature name tooltip position this._features.name.tooltip.position('bottom'); } else { //Set the feature name tooltip position this._features.name.tooltip.position('right'); } //Continue return this; }; //Check if is landscape jviz.modules.karyoviewer.prototype.isLandscape = function() { //Check if the actual orientation is landscape return this._orientation.actual === 'landscape'; }; //Set landscape orientation jviz.modules.karyoviewer.prototype.setLandscape = function() { //Set landscape orientation return this.orientation('landscape'); }; //Check if orientation is protrait jviz.modules.karyoviewer.prototype.isPortrait = function() { //Check if actual orientation is portrait return this._orientation.actual === 'portrait'; }; //Set portrait orientation jviz.modules.karyoviewer.prototype.setPortrait = function() { //Set portrait orientation return this.orientation('portrait'); };
JavaScript
0.000037
@@ -499,36 +499,29 @@ //Set the -feature name +label tooltip pos @@ -532,37 +532,29 @@ n%0A this._ -features.name +label .tooltip.pos @@ -542,32 +542,35 @@ ._label.tooltip. +el. position('bottom @@ -606,20 +606,13 @@ the -feature name +label too @@ -639,21 +639,13 @@ is._ -features.name +label .too @@ -649,16 +649,19 @@ tooltip. +el. position
82da4b8e1ea708ea2fe48e598138c5e46ff2abb9
Resolve non-conditionals as-is
core/acs.js
core/acs.js
/* jslint node: true */ 'use strict'; // ENiGMA½ const checkAcs = require('./acs_parser.js').parse; const Log = require('./logger.js').log; // deps const assert = require('assert'); const _ = require('lodash'); class ACS { constructor(client) { this.client = client; } check(acs, scope, defaultAcs) { acs = acs ? acs[scope] : defaultAcs; acs = acs || defaultAcs; try { return checkAcs(acs, { client : this.client } ); } catch(e) { Log.warn( { exception : e, acs : acs }, 'Exception caught checking ACS'); return false; } } // // Message Conferences & Areas // hasMessageConfRead(conf) { return this.check(conf.acs, 'read', ACS.Defaults.MessageConfRead); } hasMessageAreaRead(area) { return this.check(area.acs, 'read', ACS.Defaults.MessageAreaRead); } // // File Base / Areas // hasFileAreaRead(area) { return this.check(area.acs, 'read', ACS.Defaults.FileAreaRead); } hasFileAreaWrite(area) { return this.check(area.acs, 'write', ACS.Defaults.FileAreaWrite); } hasFileAreaDownload(area) { return this.check(area.acs, 'download', ACS.Defaults.FileAreaDownload); } getConditionalValue(condArray, memberName) { assert(_.isArray(condArray)); assert(_.isString(memberName)); const matchCond = condArray.find( cond => { if(_.has(cond, 'acs')) { try { return checkAcs(cond.acs, { client : this.client } ); } catch(e) { Log.warn( { exception : e, acs : cond }, 'Exception caught checking ACS'); return false; } } else { return true; // no acs check req. } }); if(matchCond) { return matchCond[memberName]; } } } ACS.Defaults = { MessageAreaRead : 'GM[users]', MessageConfRead : 'GM[users]', FileAreaRead : 'GM[users]', FileAreaWrite : 'GM[sysops]', FileAreaDownload : 'GM[users]', }; module.exports = ACS;
JavaScript
0.000456
@@ -1169,24 +1169,25 @@ me) %7B%0A%09%09 -assert(_ +if(!Array .isArray @@ -1198,17 +1198,84 @@ dArray)) -; + %7B%0A%09%09%09//%09no cond array, just use the value%0A%09%09%09return condArray;%0A%09%09%7D%0A %0A%09%09asser
bbe7815af3f5618bf3c88191ddc4fddf1800c9c0
Fix wrong syntax
message_generator.js
message_generator.js
'use strict' const splitter = '==================\n' const smileyFace = '≧◡≦' const usd_thb = 32 module.exports = { usdToTHB (amountInUSD) { return (parseFloat(amountInUSD) * usd_thb).toFixed(2) }, sunnDokkMessage (bx, cmk, bfn) { let omg = bx.omg let btc = bx.btc let eth = bx.eth let ltc = bx.ltc let knc = cmk.knc let zrx = cmk.zrx let qsp = cmk.qsp let knc_thb = this.usdToTHB(knc.price_usd) let zrx_thb = this.usdToTHB(zrx.price_usd) let qsp_thb = this.usdToTHB(qsp.price_usd) let omg_bfn = bfn.omg let neo_bfn = bfn.neo let bfn_omg_thb = this.usdToTHB(omg_bfn.last_price) let bfn_neo_thb = this.usdToTHB(neo_bfn.last_price) return `✿✿\n` + `1 BTC : ${btc.last_price} THB [BX]\n` + `1 ETH : ${eth.last_price} THB [BX]\n` + `1 LTC : ${ltc.last_price} THB [BX]\n` + `1 OMG : ${omg.last_price} THB [BX]\n` + `1 OMG : ${bfn_omg_thb} THB [Bitfinex]\n` + `1 NEO : ${bfn_neo_thb} THB [Bitfinex]\n` + `1 KNC : ${knc_thb} THB\n` + `1 ZRX : ${zrx_thb} THB\n` + `1 QSP : ${qsp_thb} THB\n` + smileyFace }ม cryptoLoverMessage (bx, cmk) { let omg = bx.omg let btc = bx.btc let eth = bx.eth let ltc = bx.ltc let qsp = cmk.qsp let qsp_thb = this.usdToTHB(qsp.price_usd) return `✿CryptoLover✿\n` + `1 BTC : ${btc.last_price} THB\n` + `1 ETH : ${eth.last_price} THB\n` + `1 LTC : ${ltc.last_price} THB [BX]\n` + `1 OMG : ${omg.last_price} THB\n` + `1 QSP : ${qsp_thb} THB\n` + smileyFace }, omsLoverMessage (bx, bfn) { let omg = bx.omg let btc = bx.btc let eth = bx.eth let xrp = bx.xrp let omg_bfn = bfn.omg let bfn_omg_thb = this.usdToTHB(omg_bfn.last_price) return `✿OMG✿\n` + `1 OMG : ${omg.last_price} THB [BX]\n` + `1 OMG : ${bfn_omg_thb} THB [Bitfinex]\n` + `1 BTC : ${btc.last_price} THB [BX]\n` + `1 ETH : ${eth.last_price} THB [BX]\n` + `1 XRP : ${xrp.last_price} THB [BX]\n` + smileyFace } }
JavaScript
0.999999
@@ -1120,9 +1120,9 @@ %0A %7D -%E0%B8%A1 +, %0A%0A
dc54ce9b104c78d96334edbf47e723f7c0d1a0b4
Fix linter error.
src/client/app/app.core.js
src/client/app/app.core.js
"use strict"; (function () { angular .module("conpa") .config(config); config.$inject = ["$httpProvider", "$locationProvider", "$mdThemingProvider", "localStorageServiceProvider"]; /*eslint-disable max-len */ function config($httpProvider, $locationProvider, $mdThemingProvider, localStorageServiceProvider) { /*eslint-enable */ var interceptors = $httpProvider.interceptors; interceptors.push(["$q", "$rootScope", function ($q, $rootScope) { var nLoadings = 0; return { request: function (request) { nLoadings += 1; $rootScope.isLoadingView = true; return request; }, "response": function (response) { nLoadings -= 1; if (nLoadings === 0) { $rootScope.isLoadingView = false; } return response; }, "responseError": function (response) { nLoadings -= 1; if (!nLoadings) { $rootScope.isLoadingView = false; } return $q.reject(response); } }; }]); $locationProvider.html5Mode(true); localStorageServiceProvider.setPrefix("conpa"); $mdThemingProvider.theme("default") .primaryPalette("pink") .accentPalette("orange"); } }());
JavaScript
0
@@ -154,28 +154,16 @@ ider%22,%0D%0A -
26fe9e9d8a85c835f39f00b0403572fa5285f863
Update app.js
server/app.js
server/app.js
'use strict'; /** * app.js * IBX Approval Backend * * Created by Thomas Beckmann on 02.03.2015 * Copyright (c) * 2015 * M-Way Solutions GmbH. All rights reserved. * http://www.mwaysolutions.com * Redistribution and use in source and binary forms, with or without * modification, are not permitted. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ // PLEASE DON'T CHANGE OR REMOVE COMMENTS // which starts with //build:: // These comments are necessary for the generator var express = require('express'); var app = express(); //build::require // Assign middlewares app.use(express.bodyParser()); //build::middleware // global variables global.app = app; // install routes require('./routes/approvals.js'); require('./routes/routes.js'); //starts express webserver app.listen();
JavaScript
0.000002
@@ -27,29 +27,8 @@ s%0A * - IBX Approval Backend %0A *%0A
fb7546e9c85f9fa0d4180ca033df89ed0a567972
Update CORS middleware to use arrow functions
server/app.js
server/app.js
const express = require('express'); const app = express(); const bodyParser = require('body-parser'); const lodash = require('lodash'); const moment = require('moment'); const TimeEntry = require('./models/TimeEntry'); // Use body parsing app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(express.static('build')); // Allow CORS app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); // Display a listing of all time entries app.get('/api/time-entry', (req, res) => { TimeEntry .find() .sort({ started_at: -1 }) .exec((err, entries) => { res.json(lodash.groupBy(entries, (entry) => { return moment(entry.started_at).format('YYYY-MM-DD'); })); }); }); // Create a new time entry app.post('/api/time-entry', (req, res) => { const timeEntry = new TimeEntry(req.body); timeEntry.save(); res.json(timeEntry); }); // Delete the given time entry app.delete('/api/time-entry/:id', (req, res) => { TimeEntry.remove({ _id: req.params.id }).exec(); res.sendStatus(200); }); // Boot server app.listen(1748, () => { console.log('Example app listening on port 1748!'); });
JavaScript
0
@@ -312,16 +312,69 @@ json()); +%0A%0A// Use the static build folder for front-end assets %0Aapp.use @@ -427,16 +427,8 @@ use( -function (req @@ -439,16 +439,19 @@ s, next) + =%3E %7B%0A res
9e4f1de081be847f9c274da90df809c24810b1ff
add clip_update
server/app.js
server/app.js
const app = require('express')() const http = require('http').Server(app) const io = require('socket.io').listen(http) const nedb_module = require ("../nedb_module") const async = require('async') const bodyParser = require('body-parser') let nedb = new nedb_module() let readid let writeid //set portnumber const PORTNUMBER = 6277 http.listen(PORTNUMBER,() => { console.log('Open 6277') }) app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.json()) app.post('/api/save_tile',(req,res) => { nedb.insert_tile(req.body,(save_doc) => { res.send(save_doc._id) }) }) app.get('/',(req,res) => { res.sendfile('./server/index.html') }) app.get(/\/html\/*/,(req,res) => { res.sendfile(__dirname + req.url) }) app.get(/\/css\/*/,(req, res) => { res.sendfile(__dirname + req.url) }) app.get(/\/img\/*/, (req, res) => { res.sendfile(__dirname + req.url) }) app.get(/\/js\/*/,(req,res) => { res.sendfile(__dirname + req.url) }) app.get(/\/node_modules\/*/,(req,res) => { let redir = __dirname redir = redir.replace(/\/server$/,"") res.sendfile(redir + req.url) }) io.sockets.on('connection',(socket) => { socket.emit("send_connect") socket.on('send_writeconnect',() => { writeid = socket.id }) socket.on('send_readconnect',(rec) => { readid = socket.id nedb.find_tile_cidid(rec.cid,rec.tid,(tile) => { io.to(writeid).emit('res_reloadevent',tile.con) }) }) //send pathdata socket.on('send_pathdata', (rec) => { io.to(readid).emit('res_pathdata', rec) }) //send before button push event socket.on('send_beforeevent', () => { io.to(readid).emit('res_beforeevent') }) //send after button push event socket.on('send_afterevent', (rec) => { io.to(readid).emit('res_afterevent', rec) }) //save clip data socket.on('save_clip',(rec) => { //clip data send DB nedb.insert_clip(rec,(newclip) => { //send newcilp.id send electron socket.emit('res_cid',newclip._id) }) }) //save tile data socket.on('save_tile',(rec) => { //tile data send database nedb.insert_tile(rec,(save_doc) => { socket.emit('res_tid',save_doc._id) }) }) //return all tag socket.on('get_allcliptags',() => { nedb.find_allclipstags((alltags) => { //send all tag socket.emit('res_allcliptags',alltags) }) }) //return all tile tags socket.on('send_clipsearchdata',(rec) => { nedb.find_clipids_tags(rec.cliptags,new Date(rec.startdate),new Date(rec.enddate),(cids) => { let tiletags = [] async.each(cids,(cid,callback) => { nedb.find_alltilestags_cid(cid._id,(tiletag) => { tiletags = tiletags.concat(tiletag) callback() }) }, (err) => { if(err){ console.error(err) } let alltiletags = Array.from(new Set(tiletags).values()) socket.emit('res_alltiletags',alltiletags) }) }) }) //return search clip socket.on('send_clipsearchdata',(rec) => { nedb.find_clips_tags(rec.cliptags,new Date(rec.startdate),new Date(rec.enddate),(clips) => { socket.emit('res_clips',clips) }) }) //return search tile socket.on('send_tilesearchdata',(rec) => { nedb.find_clipids_tags(rec.cliptags,new Date(rec.startdate),new Date(rec.enddate),(cids) => { let tiles = [] async.each(cids,(cid,callback) => { nedb.find_tiles_cidtags(cid._id,rec.tiletags,(tile) => { tiles = tiles.concat(tile) callback() }) }, (err) => { if(err){ console.error(err) } socket.emit('res_tiles',tiles) }) }) }) socket.on('update_tiletag',(rec) => { nedb.update_tiletags_cidid(rec.tag,rec.cid,rec.tid,() => { }) }) socket.on('update_tilecon',(rec) => { nedb.update_tilecon_cidid(rec.con,rec.cid,rec.tid,() => { }) }) socket.on('update_tilecol',(rec) => { nedb.update_tilecol_cidid(rec.col,tile.cid,rec.tid,() => { }) }) socket.on('update_tileidx',(rec) => { nedb.update_tileidx_cidid(rec.idx,rec.cid,rec.tid,() => { }) }) socket.on('delete_clip',(rec) => { nedb.delete_clip_id(rec,() => { }) }) socket.on('delete_tile',(rec) => { nedb.delete_tile_cidid(rec.cid,rec.tid,() => { }) }) })
JavaScript
0.000001
@@ -4378,11 +4378,126 @@ )%0A %7D)%0A%0A + socket.on('update_cliptag',(rec) =%3E %7B%0A nedb.update_cliptags_id(rec.clip_tags,rec.cid,(clip) =%3E %7B%0A %7D)%0A %7D)%0A%0A %7D)%0A
11dc9b6329fc51e1c3f7a4a9c5d4c4f0aeddb04b
Change readBytesEndOffset to nBytesToRead so that we don't depend on offset aways increasing.
js/encoding/BinaryXMLStructureDecoder.js
js/encoding/BinaryXMLStructureDecoder.js
/* * This class uses BinaryXMLDecoder to follow the structure of a ccnb binary element to * determine its end. * * @author: Jeff Thompson * See COPYING for copyright and distribution information. */ var BinaryXMLStructureDecoder = function BinaryXMLDecoder() { this.gotElementEnd = false; this.offset = 0; this.level = 0; this.state = BinaryXMLStructureDecoder.READ_HEADER_OR_CLOSE; this.headerStartOffset = 0; this.readBytesEndOffset = 0; }; BinaryXMLStructureDecoder.READ_HEADER_OR_CLOSE = 0; BinaryXMLStructureDecoder.READ_BYTES = 1; /* * Continue scanning input starting from this.offset. If found the end of the element * which started at offset 0 then return true, else false. * If this returns false, you should read more into input and call again. * You have to pass in input each time because the array could be reallocated. * This throws an exception for badly formed ccnb. */ BinaryXMLStructureDecoder.prototype.findElementEnd = function( // byte array input) { if (this.gotElementEnd) // Someone is calling when we already got the end. return true; var decoder = new BinaryXMLDecoder(input); while (true) { if (this.offset >= input.length) // All the cases assume we have some input. return false; switch (this.state) { case BinaryXMLStructureDecoder.READ_HEADER_OR_CLOSE: // First check for XML_CLOSE. if (this.offset == this.headerStartOffset && input[this.offset] == XML_CLOSE) { ++this.offset; // Close the level. --this.level; if (this.level == 0) // Finished. return true; if (this.level < 0) throw new Error("BinaryXMLStructureDecoder: Unexepected close tag at offset " + (this.offset - 1)); // Get ready for the next header. this.headerStartOffset = this.offset; break; } while (true) { if (this.offset >= input.length) return false; if (input[this.offset++] & XML_TT_NO_MORE) // Break and read the header. break; } decoder.seek(this.headerStartOffset); var typeAndVal = decoder.decodeTypeAndVal(); if (typeAndVal == null) throw new Error("BinaryXMLStructureDecoder: Can't read header starting at offset " + this.headerStartOffset); // Set the next state based on the type. var type = typeAndVal.t; if (type == XML_DATTR) // We already consumed the item. READ_HEADER_OR_CLOSE again. // ccnb has rules about what must follow an attribute, but we are just scanning. this.headerStartOffset = this.offset; else if (type == XML_DTAG || type == XML_EXT) { // Start a new level and READ_HEADER_OR_CLOSE again. ++this.level; this.headerStartOffset = this.offset; } else if (type == XML_TAG || type == XML_ATTR) { if (type == XML_TAG) // Start a new level and read the tag. ++this.level; // Minimum tag or attribute length is 1. this.readBytesEndOffset = this.offset + typeAndVal.v + 1; this.state = BinaryXMLStructureDecoder.READ_BYTES; // ccnb has rules about what must follow an attribute, but we are just scanning. } else if (type == XML_BLOB || type == XML_UDATA) { this.readBytesEndOffset = this.offset + typeAndVal.v; this.state = BinaryXMLStructureDecoder.READ_BYTES; } else throw new Error("BinaryXMLStructureDecoder: Unrecognized header type " + type); break; case BinaryXMLStructureDecoder.READ_BYTES: if (input.length < this.readBytesEndOffset) { // Need more. this.offset = input.length; return false; } // Got the bytes. Read a new header or close. this.offset = this.readBytesEndOffset; this.headerStartOffset = this.offset; this.state = BinaryXMLStructureDecoder.READ_HEADER_OR_CLOSE; break; default: // We don't expect this to happen. throw new Error("BinaryXMLStructureDecoder: Unrecognized state " + this.state); } } };
JavaScript
0
@@ -439,34 +439,28 @@ this. -read +n Bytes -EndOffset +ToRead = 0;%0A%7D; @@ -3747,42 +3747,22 @@ his. -read +n Bytes -EndOffset = this.offset + +ToRead = typ @@ -4061,42 +4061,22 @@ his. -read +n Bytes -EndOffset = this.offset + +ToRead = typ @@ -4399,28 +4399,46 @@ -if ( +var nRemainingBytes = input.length @@ -4442,33 +4442,78 @@ gth -%3C +- this. -readBytesEndOffset +offset;%0A if (nRemainingBytes %3C this.nBytesToRead ) %7B%0A @@ -4578,30 +4578,92 @@ .offset ++ = -input.length +nRemainingBytes;%0A this.nBytesToRead -= nRemainingBytes ;%0A @@ -4803,33 +4803,28 @@ set ++ = this. -read +n Bytes -EndOffset +ToRead ;%0A
b103bcc38fe54445d27164d5d51714f2b61c92e6
Fix deprecated warning
server/app.js
server/app.js
var SLACK_BOT_NAME = process.env.SLACK_BOT_NAME || 'Tesla Model S'; var env = process.env.NODE_ENV || 'dev'; if (env === 'production') { require('newrelic'); } var express = require('express'), tesla = require('./tesla'), Bacon = require('baconjs').Bacon; var app = express(); app.use(require('body-parser')()); app.use(require('logfmt').requestLogger()); function sendJson(res) { return function (message) { res.json(message); }; } function toSlackMessage(text) { return { text: text, username: SLACK_BOT_NAME }; } function hasCommand(req, name) { return req.body.text.indexOf(name) >= 0; } app.post('/slack', function (req, res) { if (req.body.token === process.env.SLACK_RECEIVE_TOKEN) { if (hasCommand(req, 'battery')) { tesla.chargeState().map(toSlackMessage).onValue(sendJson(res)); } else if (hasCommand(req, 'climate')) { tesla.climateState().map(toSlackMessage).onValue(sendJson(res)); } else if (hasCommand(req, 'position')) { tesla.formattedDriveState().map(toSlackMessage).onValue(sendJson(res)); } else if (hasCommand(req, 'vehicle')) { tesla.vehicleState().map(toSlackMessage).onValue(sendJson(res)); } else if (hasCommand(req, 'honk')) { res.json(toSlackMessage(':trumpet: TÖÖÖÖÖT-TÖÖÖÖÖÖÖÖÖÖÖT!')); } else { res.json(toSlackMessage('Supported commands: battery, honk, position, vehicle, climate')); } } else { res.send(403); } }); app.get('/', function (req,res) { res.send('ok'); // used for newrelic monitoring at Heroku }); var port = process.env.PORT || 5000; app.listen(port, function () { console.log("Listening on " + port); });
JavaScript
0.000005
@@ -261,16 +261,57 @@ ').Bacon +,%0A bodyParser = require('body-parser') ;%0A%0Avar a @@ -334,38 +334,31 @@ app.use( -require(' body --p +P arser -') +.json ());%0Aapp
f491eeace76cb037a9c295dcca2c7f0c84dca4fb
remove focus. update prop types
src/widgets/JSONForm/widgets/Radio.js
src/widgets/JSONForm/widgets/Radio.js
/* eslint-disable react/forbid-prop-types */ import React from 'react'; import { StyleSheet, View } from 'react-native'; import PropTypes from 'prop-types'; import { RadioButton, RadioButtonInput, RadioButtonLabel } from 'react-native-simple-radio-button'; import { APP_FONT_FAMILY } from '../../../globalStyles/fonts'; import { GREY, SUSSOL_ORANGE } from '../../../globalStyles/colors'; import { useJSONFormOptions } from '../JSONFormContext'; export const Radio = ({ options, value, disabled, readonly, onChange }) => { const { enumOptions, enumDisabled } = options; const { focusController } = useJSONFormOptions(); const ref = focusController.useRegisteredRef(); const row = options ? options.inline : false; // return <RadioForm ref={ref} radio_props={radioProps} initial={0} onPress={onChange} />; const radioButtons = enumOptions.map((option, i) => { const itemDisabled = enumDisabled && enumDisabled.indexOf(option.value) !== -1; const itemSelected = value === option.value; return ( <RadioButton labelHorizontal={true} key={option.value} ref={ref}> <RadioButtonInput obj={option} index={i} isSelected={itemSelected} onPress={onChange} buttonInnerColor={SUSSOL_ORANGE} buttonOuterColor={itemSelected ? SUSSOL_ORANGE : GREY} disabled={disabled || itemDisabled || readonly} buttonSize={10} buttonOuterSize={20} borderWidth={2} /> <RadioButtonLabel obj={option} index={i} labelHorizontal={row} onPress={onChange} labelStyle={styles.label} /> </RadioButton> ); }); return <View style={styles.root}>{radioButtons}</View>; }; const styles = StyleSheet.create({ root: { paddingLeft: 10, paddingTop: 10 }, label: { fontFamily: APP_FONT_FAMILY, marginLeft: 10 }, }); Radio.propTypes = { disabled: PropTypes.bool, value: PropTypes.string, onChange: PropTypes.func.isRequired, options: PropTypes.shape({ enumOptions: PropTypes.arrayOf(PropTypes.any), enumDisabled: PropTypes.bool, inline: PropTypes.bool, }), readonly: PropTypes.bool, }; Radio.defaultProps = { disabled: false, value: '', options: undefined, readonly: false, };
JavaScript
0.00004
@@ -385,65 +385,8 @@ rs'; -%0Aimport %7B useJSONFormOptions %7D from '../JSONFormContext'; %0A%0Aex @@ -513,110 +513,8 @@ ns;%0A - const %7B focusController %7D = useJSONFormOptions();%0A const ref = focusController.useRegisteredRef();%0A co @@ -913,26 +913,16 @@ n.value%7D - ref=%7Bref%7D %3E%0A @@ -1797,14 +1797,52 @@ pes. -string +oneOf(%5BPropTypes.string, PropTypes.boolean%5D) ,%0A
b91c1bd25280d474247d53b2559aed76949c381d
Make server example clearer
example/server.js
example/server.js
var http = require('http') , pushup = require('../index.js') , getProps = require('../lib/getProps.js') , commit http.createServer(function (req, res) { var p = pushup(getProps(), function (err, c) { var code = isNotModified(c) ? 304 : 204 commit = c res.writeHead(code) res.end() }) p.on('commit', function (c) { if (isNotModified(c)) { p.end() } }) }).listen(7000) function isNotModified (c) { return c === commit }
JavaScript
0.000145
@@ -105,17 +105,21 @@ s')%0A , -c +lastC ommit%0A%0Ah @@ -202,16 +202,21 @@ (err, c +ommit ) %7B%0A @@ -241,16 +241,21 @@ dified(c +ommit ) ? 304 @@ -264,14 +264,42 @@ 204%0A -%0A c + if (err) code = 500%0A%0A lastC ommi @@ -303,16 +303,21 @@ mmit = c +ommit %0A%0A re @@ -382,16 +382,21 @@ ction (c +ommit ) %7B%0A @@ -414,16 +414,21 @@ dified(c +ommit )) %7B%0A @@ -491,16 +491,21 @@ ified (c +ommit ) %7B%0A re @@ -514,14 +514,23 @@ rn c - === c +ommit === lastC ommi
8e700082d389e0233debdad57ab478a876fa5478
Update timeFilters.js
js/timeFilters.js
js/timeFilters.js
var url = '../data/ams_vondelpark_5-01-2017.geojson'; map.on('load', function() { var filterHour = ['==', 'Hour', 12]; var filterDay = ['!=', 'Day', 'Bob']; var filterPollutant = ['==', 'Pollutant', 'NO2']; map.getSource('pollutants').setData(url); map.addSource('pollutants', { type: 'geojson', data: url }); map.addLayer({ id: 'pollutants', type: 'circle', filter: ['all', filterHour, filterDay, filterPollutant], source: 'pollutants', paint: { 'circle-radius': { property: 'Concentration', stops: [ [0, 3], [150, 15] ] }, 'circle-color': { property: 'Concentration', stops: [ [0, '#2DC4B2'], [25, '#3BB3C3'], [75, '#669EC4'], [100, '#8B88B6'], [125, '#A2719B'], [150, '#AA5E79'] ] }, 'circle-opacity': 0.8 }, 'admin-2-boundaries-dispute'}); // place the layer beneath this layer in the basemap }); document.getElementById('slider').addEventListener('input', function(e) { // get the current hour as an integer var hour = parseInt(e.target.value); //string argument //hour = hour < 10 ? '0' + '' + hour + ':00:00+02:00': hour; // map.setFilter(layer-name, filter) filterHour = ['==', 'Hour', hour]; map.setFilter('pollutants', ['all', filterHour, filterDay, filterPollutant]); // converting 0-23 hour to AMPM format var ampm = hour >= 12 ? 'PM' : 'AM'; var hour12 = hour % 12 ? hour % 12 : 12; // update text in the UI document.getElementById('active-hour').innerText = hour12 + ampm; }); document.getElementById('filters').addEventListener('change', function(e) { var day = e.target.value; if (day === 'all') { // `null` would not work for combining filters filterDay = ['!=', 'Day', 'Bob']; } else if (day === 'weekday') { filterDay = ['!in', 'Day', 'Sat', 'Sun']; } else if (day === 'weekend') { filterDay = ['in', 'Day', 'Sat', 'Sun']; } else { console.log('error'); } map.setFilter('pollutants', filterHour, filterDay, filterPollutant); }); /* map.on('load', function() { map.addLayer({ id: 'collisions', type: 'circle', filter: ['==', 'Hour', 12], source: { type: 'geojson', data: 'https://embed.github.com/view/geojson/dannyhecht/ams-air-quality/data/ams_stadhouderskade_5-01-2017_test.geojson' }, paint: { 'circle-radius': { property: 'Concentration', stops: [ [0, 3], [5, 15] ] }, 'circle-color': { property: 'Concentration', stops: [ [0, '#2DC4B2'], [1, '#3BB3C3'], [2, '#669EC4'], [3, '#8B88B6'], [4, '#A2719B'], [5, '#AA5E79'] ] }, 'circle-opacity': 0.8 } }, 'admin-2-boundaries-dispute'); // place the layer beneath this layer in the basemap }); document.getElementById('slider').addEventListener('input', function(e) { // get the current hour as an integer var hour = parseInt(e.target.value); // map.setFilter(layer-name, filter) map.setFilter('collisions', ['==', 'Hour', hour]); // converting 0-23 hour to AMPM format var ampm = hour >= 12 ? 'PM' : 'AM'; var hour12 = hour % 12 ? hour % 12 : 12; // update text in the UI document.getElementById('active-hour').innerText = hour12 + ampm; }); document.getElementById('filters').addEventListener('change', function(e) { var day = e.target.value; var filterDay; if (day === 'all') { filterDay = null; } else if (day === 'weekday') { filterDay = ['!in', 'Day', 'Sat', 'Sun']; } else if (day === 'weekend') { filterDay = ['in', 'Day', 'Sat', 'Sun']; } else { console.log('error'); } map.setFilter('collisions', filterDay); }); */
JavaScript
0
@@ -359,19 +359,58 @@ data: -url +'../data/ams_vondelpark_5-01-2017.geojson' %0A
292096cc5a9b686e823812a35099189388ff722e
Make the control panel active by default
controls.js
controls.js
$(document) .ready(function() { anim.reset(); anim.start(); $("#controls") .click(function(e) { $("#controls") .toggleClass('active'); }); $("#canvas") .click(function(e) { var x = e.pageX - $("#canvas") .offset() .left; var y = e.pageY - $("#canvas") .offset() .top; var type = $('input:radio[name=c_clicking]:checked') .val(); anim.clicks.push([x, y, type]); }); $('#c_stop') .click(function(e) { anim.stopRunning(); }); $('#c_reset') .click(function(e) { anim.reset(); }); $('#c_start') .click(function(e) { anim.start(); }); $('#c_restart') .click(function(e) { anim.stop(); anim.reset(); // starter bees anim.bees.push(bee(util.random(0, (anim.cols - 1)), util.random(0, (anim.rows - 1)), util.random( 0, 3))); anim.bees.push(bee(util.random(0, (anim.cols - 1)), util.random(0, (anim.rows - 1)), util.random( 0, 3))); anim.start(); }); $('#c_speed') .change(function() { anim.stop(); anim.fps = $('#c_speed') .val(); anim.start(); $('#c_speed_indicator') .html($('#c_speed') .val()); }); $('#c_cellsize') .change(function() { $('#c_cellsize_indicator') .html($('#c_cellsize') .val()); }); });
JavaScript
0.000001
@@ -65,32 +65,87 @@ anim.start();%0A +%09%09$(%22#controls%22)%0A .toggleClass('active');%0A%09%09 %0A $(%22#con
7701db6a6e335ac0516213d5b61f3b414dde0b66
compress js
www/static/app/webpack.config.js
www/static/app/webpack.config.js
var webpack = require("webpack"); var path = require("path"); var jspath = path.resolve(__dirname); module.exports = { entry: { day: jspath + "/day.js", blog: jspath + "/blog.js", spentries: jspath + "/spentries.js", vote: jspath + "/vote.js", rss: jspath + "/rss.js", spiders: jspath + "/spiders.js" }, output: { path: jspath + "/js/", filename: "[name].js", }, module: { loaders: [ { test: /\.js/, loader: "babel-loader", exclude: /node_modules/, query: { presets:["react", "es2015", "stage-0"] } } ] }, plugins: [ new webpack.ProvidePlugin({$: "jquery", jQuery: "jquery", "window.jQuery": "jquery"}), ], };
JavaScript
0.000016
@@ -698,16 +698,331 @@ uery%22%7D), +%0A%0A new webpack.DefinePlugin(%7B%0A %22process.env%22: %7B%0A NODE_ENV: JSON.stringify(%22production%22)%0A %7D%0A %7D),%0A%0A new webpack.optimize.UglifyJsPlugin(%7B%0A compress: %7B%0A warnings: false,%0A %7D,%0A output: %7B%0A comments: false,%0A %7D,%0A %7D), %0A %5D,%0A%7D;
820c8150bd29fcfa7463e158e3d121173830d05a
Tweak plain formatter.
src/formats/plain.js
src/formats/plain.js
/*globals exports */ 'use strict'; exports.format = format; function format (reports) { var formatted = '', i; for (i = 0; i < reports.length; i += 1) { formatted += formatModule(reports[i]); } return formatted; } function formatModule (report) { return [ '\n', report.module, '\n\n', 'Aggregate complexity: ', report.aggregate.complexity.cyclomatic, formatFunctions(report.functions) ].join(''); } function formatFunctions (report) { var formatted = '', i; for (i = 0; i < report.length; i += 1) { formatted += '\n\n' + formatFunction(report[i]); } return formatted; } function formatFunction (report) { return [ 'Function: ', report.name, '\n', 'Cyclomatic complexity: ', report.complexity.cyclomatic ].join(''); }
JavaScript
0
@@ -178,16 +178,25 @@ atted += + '%5Cn%5Cn' + formatM @@ -292,30 +292,16 @@ eturn %5B%0A - '%5Cn',%0A
1ee1fda181bfafe5ba89fab04e199cf2d1129027
support for mobile devices that cannot do hover
bs-an-dd.js
bs-an-dd.js
function BindAnimatedDropdown($dd) { $dd.find('li.dropdown').each(function(){ var $li = $(this); $li.hover(function(){ clearTimeout(l); $li.addClass('active').children('ul').slideDown(200); $('li.dropdown').not($li).removeClass('active').children('ul').fadeOut(400); }, function(){ l = setTimeout(function(){ $li.removeClass('active').children('ul').fadeOut(400); },300); }); }); }
JavaScript
0
@@ -1,46 +1,79 @@ -function BindAnimatedDropdown($dd +var l; // needs a global variable for timeout%0D%0Afunction BindMenu($m ) %7B%0D%0A%09$ -dd +m .fin @@ -171,24 +171,66 @@ imeout(l);%0D%0A +%09%09%09if(!$('.active-click').length)%0D%0A%09%09%09%7B%0D%0A%09 %09%09%09$li.addCl @@ -275,16 +275,17 @@ (200);%0D%0A +%09 %09%09%09$('li @@ -357,16 +357,22 @@ (400);%0D%0A +%09%09%09%7D%0D%0A %09%09%7D, fun @@ -381,16 +381,58 @@ ion()%7B%0D%0A +%09%09%09if(!$('.active-click').length)%0D%0A%09%09%09%7B%0D%0A%09 %09%09%09l = s @@ -454,16 +454,17 @@ ion()%7B%0D%0A +%09 %09%09%09%09$li. @@ -518,16 +518,17 @@ 0);%0D%0A%09%09%09 +%09 %7D,300);%0D @@ -530,19 +530,566 @@ 00);%0D%0A%09%09 -%7D); +%09%7D%0D%0A%09%09%7D);%0D%0A%09%09$li.click(function(e)%7B%0D%0A%09%09%09e.preventDefault();%0D%0A%09%09%09clearTimeout(l);%0D%0A%09%09%09if($li.hasClass('active-click'))%0D%0A%09%09%09%7B%0D%0A%09%09%09%09$li%0D%0A%09%09%09%09.removeClass('active')%0D%0A%09%09%09%09.children('ul')%0D%0A%09%09%09%09.fadeOut(400);%0D%0A%09%09%09%09$('.active-click').removeClass('active-click');%0D%0A%09%09%09%7D%0D%0A%09%09%09else%7B%0D%0A%09%09%09%09$li%0D%0A%09%09%09%09.addClass('active-click')%0D%0A%09%09%09%09.addClass('active')%0D%0A%09%09%09%09.children('ul')%0D%0A%09%09%09%09.slideDown(200);%0D%0A%09%09%09%09$('li.dropdown').not($li).removeClass('active').children('ul').fadeOut(400);%0D%0A%09%09%09%7D%0D%0A%09%09%7D);%0D%0A%09%09%0D%0A%09%09$li.find('li').click(function(e)%7B%0D%0A%09%09%09e.stopPropagation();%0D%0A%09%09%7D);%0D%0A%09%09 %0D%0A%09%7D);%0D%0A @@ -1089,8 +1089,10 @@ %0A%09%7D);%0D%0A%7D +%0D%0A
3111078e9f602108e0afe11c8e6726669da14901
Align tool tips bottom-start
src/common/ListItemBase.js
src/common/ListItemBase.js
import React from 'react'; import AudioRecorder from '../audio/AudioRecorder'; import ApiUtils from '../utils/ApiUtils'; import AuthUtils from '../utils/AuthUtils'; import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import DialogTitle from '@material-ui/core/DialogTitle'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogActions from '@material-ui/core/DialogActions'; import Snackbar from '@material-ui/core/Snackbar'; import TextField from '@material-ui/core/TextField'; import Tooltip from '@material-ui/core/Tooltip'; import './ListItemBase.css'; class ListItemBase extends React.Component { constructor(props) { super(props); this.handleClose_ = this.handleClose_.bind(this); this.deleteItem = this.deleteItem.bind(this); this.handleDialogClose_ = this.handleDialogClose_.bind(this); this.handleDeleteConfirm_ = this.handleDeleteConfirm_.bind(this); this.showDeleteConfirm_ = this.showDeleteConfirm_.bind(this); const { english_word, primary_word, id, frequency, sound_link, translation, transliteration, // For flagged items only. curr_sound_link, curr_translation, curr_transliteration, content, } = this.props.item; this.state = { id, english_word, primary_word, sound_link, translation, transliteration, frequency, content, curr_sound_link, curr_translation, curr_transliteration, promo_message: null, promo_open: false, deleted: false, showDeleteConfirm: false, collectionName: '', }; } async showPopup(message) { await this.setState({promo_message: message, promo_open: true}) } showDeleteConfirm_() { this.setState({ showDeleteConfirm: true, }); } handleTranslationChange = (e) => { const newTranslation = e.target.value; this.setState({ translation: newTranslation, }); } handleTransliterationChange = (e) => { const newTransliteration = e.target.value; this.setState({ transliteration: newTransliteration, }); } deleteItem = async (e) => { try { const { id, collectionName } = this.state; await fetch(`${ApiUtils.origin}${ApiUtils.path}deleteRow`, { method: 'DELETE', body: JSON.stringify({ id, collectionName, }), headers: { 'Content-Type': 'application/json', 'Authorization': await AuthUtils.getAuthHeader(), } }); this.setState({ deleted: true, }); } catch(err) { console.error(err); } } renderBaseWord() { if (AuthUtils.getPrimaryLanguage()==="English"){ return ( <Tooltip title={this.state.english_word} placement="bottom"> <div className="base-word"> {this.state.english_word} </div> </Tooltip> ); }else{ const primary_word = (!this.state.primary_word || this.state.primary_word==="")?this.state.english_word:this.state.primary_word; return ( <Tooltip title={primary_word} placement="bottom"> <div className="base-word">{primary_word} <div className="english-word-small">{this.state.english_word} </div> </div> </Tooltip> ); } } renderPrimaryWord() { //placeholder for TranslationItemBase to overwrite return; } renderTranslation() { return ( <TextField value={this.state.translation} label="Translation" variant="outlined" margin="normal" onChange={this.handleTranslationChange} className="translation-text-field" /> ); } renderTransliteration() { return ( <TextField value={this.state.transliteration} label="Transliteration" variant="outlined" margin="normal" onChange={this.handleTransliterationChange} className="transliteration-text-field" /> ); } onSavedAudio(e) { console.log('onSavedAudio_', e); this.setState({sound_blob: e.data, disabled: false}); } renderAudioRecorder() { return ( <AudioRecorder audioUrl={this.state.sound_link} onSavedAudio={(blob) => this.onSavedAudio(blob)} key={0} /> ); } renderEndOfRow() { // To be overridden. return null; } handleClose_() { this.setState({promo_open: false}); } renderPromoMessage() { if (!this.state.promo_message || !this.state.promo_open) { return null; } return ( <Snackbar anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }} message={<span id="message-id">{this.state.promo_message}</span>} onClose={this.handleClose_} open /> ); } handleDeleteConfirm_(e) { e && e.stopPropagation(); this.setState({showDeleteConfirm: false, deleted: true}); this.deleteItem(); } handleDialogClose_() { this.setState({showDeleteConfirm: false}); } renderDeleteConfirmAlert() { if (!this.state.showDeleteConfirm) { return; } return ( <Dialog open onClose={this.handleDialogClose_}> <DialogTitle>Are you sure?</DialogTitle> <DialogContent> <DialogContentText> This will delete this word and all data associated with it. </DialogContentText> </DialogContent> <DialogActions> <Button onClick={this.handleDialogClose_} color="primary"> Cancel </Button> <Button onClick={this.handleDeleteConfirm_} color="primary" autoFocus className="delete-confirm"> Yes </Button> </DialogActions> </Dialog> ); } render() { if (this.state.deleted) { return null; } return ( <li className="translation-list-item"> {this.renderBaseWord()} {this.renderPrimaryWord()} {this.renderTranslation()} {this.renderTransliteration()} {this.renderAudioRecorder()} {this.renderEndOfRow()} {this.renderPromoMessage()} {this.renderDeleteConfirmAlert()} </li> ); } } export default ListItemBase;
JavaScript
0
@@ -2875,32 +2875,38 @@ lacement=%22bottom +-start %22%3E%0A %3C @@ -3245,16 +3245,22 @@ =%22bottom +-start %22%3E%0A
fb9d1b3ba48bd89926691843ba9a7560a5616d73
Add extra plugin.
xadmin/static/xadmin/gulpfile.js
xadmin/static/xadmin/gulpfile.js
var gulp = require('gulp'); function genericTask() { var srcs = [ "bower_components/**/css/*.css", "bower_components/**/css/*.less", "bower_components/**/js/*.js", "bower_components/**/locales/*.js", "bower_components/**/img/**", "!bower_components/flot/**", "!bower_components/datejs/**", "!bower_components/bootstrap-datepicker/js/**", "!bower_components/sifter/**", "!bower_components/bootstrap/**", "!bower_components/**/src/**", "!bower_components/**/jquery/**", "!bower_components/**/jquery.js", "!bower_components/**/js-packages/**", "!bower_components/**/docs/**", ]; return gulp.src(srcs) .pipe(gulp.dest('vendor')); } function jqueryTask() { return gulp.src("bower_components/jquery/dist/**") .pipe(gulp.dest('vendor/jquery')); } function flotTask() { return gulp.src("bower_components/flot/src/*.js") .pipe(gulp.dest('vendor/flot/js')); } function sifterTask() { return gulp.src("bower_components/sifter/*.js") .pipe(gulp.dest('vendor/sifter/js')); } function datejsTask() { return gulp.src("bower_components/datejs/src/**") .pipe(gulp.dest('vendor/datejs/js')); } function jqueryUITask() { var srcs = [ "bower_components/jquery-ui/**/core.js", "bower_components/jquery-ui/**/effect.js", "bower_components/jquery-ui/**/widget.js", ]; return gulp.src(srcs) .pipe(gulp.dest('vendor/jquery-ui')); } function bootstrapTask() { var srcs = [ "bower_components/bootstrap/dist/**/*.css", "bower_components/bootstrap/dist/**/*.js", "bower_components/bootstrap/js/dist/**", "!bower_components/bootstrap/build/**", ]; return gulp.src(srcs) .pipe(gulp.dest('vendor/bootstrap')); } exports.default = gulp.series( genericTask, jqueryTask, flotTask, sifterTask, datejsTask, jqueryUITask, bootstrapTask );
JavaScript
0
@@ -1008,24 +1008,169 @@ /js'));%0A%0A%7D%0A%0A +function micropluginTask() %7B%0A return gulp.src(%22bower_components/microplugin/src/*.js%22)%0A .pipe(gulp.dest('vendor/microplugin/js'));%0A%0A%7D%0A%0A function sif @@ -2101,24 +2101,45 @@ sifterTask,%0A + micropluginTask,%0A datejsTa
4f406c682da65df91a280f26f42d8635722ea5f4
use fully qualified path instead of relative path
server/app.js
server/app.js
const express = require("express"); const process = require("process"); const ws = require("ws"); const Lobby = require("./lobby").Lobby; const port = process.env.PORT || 8080; const app = express(); app.use(express.static("client")); const server = app.listen(port, () => console.log(`Example HTTP app listening on port ${port}!`)); const lobby = new Lobby(); const wss = new ws.Server({server}); wss.on("connection", ws => { lobby.addConnection(ws); });
JavaScript
0
@@ -25,24 +25,54 @@ %22express%22);%0A +const path = require(%22path%22);%0A const proces @@ -91,24 +91,24 @@ %22process%22);%0A - const ws = r @@ -224,16 +224,66 @@ ress();%0A +const client = path.join(__dirname, %22../client%22);%0A app.use( @@ -301,16 +301,14 @@ tic( -%22 client -%22 ));%0A @@ -374,16 +374,29 @@ HTTP app + on $%7Bclient%7D listeni
34fe2575e3f8dd915ca8f6094882a9af6327848c
Adjust dates to fetch
fetch-new-jster.js
fetch-new-jster.js
#!/usr/bin/env node const fs = require("fs"); const path = require("path"); const fetch = require("./fetch"); const transformGitHubTitles = require('./transforms/github_titles') const dir = path.join(__dirname, "./jsters"); fs.readdir(dir, (err, list) => { const files = list.map(file => { const filePath = path.join(dir, file); return { file, filePath: filePath, stats: fs.statSync(filePath), // mtime/ctime }; }); // Sort to find the last. In-place sort :( files.sort((a, b) => b.stats.mtimeMs - a.stats.mtimeMs); const newest = files[0]; const jsterNumber = parseInt( newest.file .split("jster") .filter(a => a)[0] .split(".")[0], 10 ); const parseFrom = new Date(); parseFrom.setDate(parseFrom.getDate() - 25); fetch( { config: "./jster_config.js", date: parseFrom, }, (err, output) => { if (err) { return console.error("Failed to fetch a new jster dump"); } const outputPath = path.join(dir, `jster${jsterNumber + 1}.json`); fs.writeFileSync(outputPath, JSON.stringify(transformGitHubTitles(output), null, 4)); console.log(outputPath); process.exit(); } ); });
JavaScript
0.999067
@@ -786,9 +786,9 @@ - 2 -5 +0 );%0A%0A
e7370888e78af399eecedd09ac164f471b98578d
fix default opts override
src/front/coreNLP.js
src/front/coreNLP.js
const _ = require('lodash'); function coreNLP (text, opts) { opts = _.merge({}, opts, coreNLP.DEFAULT_OPTS); let url = new URL(opts.url); url.searchParams.append('properties', JSON.stringify(opts.props)); return fetch(url, Object.assign({body: text}, opts.req)).then(res => res.json()); } coreNLP.DEFAULT_OPTS = { url: 'http://corenlp.run', req: {method: 'POST', mode: 'cors'}, props: { annotators: 'tokenize,ssplit,pos,ner,depparse,openie', // date: new Date().toISOString(), // 'coref.md.type': 'dep', // 'coref.mode': 'statistical' } }; module.exports = coreNLP;
JavaScript
0.000002
@@ -79,14 +79,8 @@ (%7B%7D, - opts, cor @@ -96,16 +96,22 @@ ULT_OPTS +, opts );%0A let
16b0056e66f90dcb68ddf3dc4c4bc3cd5e8326b8
Update component snippet: export style
snippets/component.js
snippets/component.js
'use strict'; /** * Module dependencies */ /** * View */ exports.component = React.createClass({ displayName: 'componentName', render: function() { return ( ); } });
JavaScript
0.000012
@@ -61,25 +61,22 @@ */%0A%0A +module. exports -.component = R
3308722e28f4726cc60a8fe1f8553598c1c033d4
add event.timeStamp to prevent multiple callback firing
src/component/shortcuts.js
src/component/shortcuts.js
import React from 'react' import ReactDOM from 'react-dom' import invariant from 'invariant' import Combokeys from 'combokeys' let shortcuts = React.createFactory('shortcuts') export default class extends React.Component { static displayName = 'Shortcuts' static contextTypes = { shortcuts: React.PropTypes.object.isRequired } static propTypes = { handler: React.PropTypes.func.isRequired, name: React.PropTypes.string.isRequired, tabIndex: React.PropTypes.number, className: React.PropTypes.string, eventType: React.PropTypes.string, stopPropagation: React.PropTypes.bool, preventDefault: React.PropTypes.bool, targetNodeSelector: React.PropTypes.string, global: React.PropTypes.bool } static defaultProps = { tabIndex: null, className: null, eventType: null, stopPropagation: true, preventDefault: false, targetNodeSelector: null, global: false } // NOTE: combokeys must be instance per component _combokeys = null _bindShortcuts = (shortcutsArr) => { let element = this._getElementToBind() element.setAttribute('tabindex', this.props.tabIndex || -1) this._combokeys = new Combokeys(element) this._decorateCombokeys() this._combokeys.bind(shortcutsArr, this._handleShortcuts, this.props.eventType) if (this.props.global) { element.addEventListener('shortcuts:global', this._customGlobalHandler) } } _customGlobalHandler = (e) => { let { character, modifiers, event } = e.detail let targetNode = null if (this.props.targetNodeSelector) { targetNode = document.querySelector(this.props.targetNodeSelector) } if (e.target !== ReactDOM.findDOMNode(this) && e.target !== targetNode) { this._combokeys.handleKey(character, modifiers, event, true) } } _decorateCombokeys = () => { let element = this._getElementToBind() let originalHandleKey = this._combokeys.handleKey.bind(this._combokeys) // NOTE: stopCallback is a method that is called to see // if the keyboard event should fire this._combokeys.stopCallback = function(event, element, combo) { let isInputLikeElement = element.tagName === 'INPUT' || element.tagName === 'SELECT' || element.tagName === 'TEXTAREA' || (element.contentEditable && element.contentEditable === 'true') let isReturnString = event.key && event.key.length === 1 if (isInputLikeElement && isReturnString) { return true } return false } this._combokeys.handleKey = (character, modifiers, event, customEvent) => { if (!customEvent) { element.dispatchEvent(new CustomEvent('shortcuts:global', { detail: {character, modifiers, event}, bubbles: true, cancelable: true })) } if (this.props.preventDefault) { event.preventDefault() } if (this.props.stopPropagation && !customEvent) { event.stopPropagation() } originalHandleKey(character, modifiers, event) } } _getElementToBind = () => { if (this.props.targetNodeSelector) { var element = document.querySelector(this.props.targetNodeSelector) invariant(element, `Node selector '${this.props.targetNodeSelector}' was not found.`) } else { var element = ReactDOM.findDOMNode(this) } return element } _unbindShortcuts = () => { let element = this._getElementToBind() element.removeAttribute('tabindex') if (this._combokeys) { this._combokeys.detach() this._combokeys.reset() } } _onUpdate = () => { let shortcutsArr = this.context.shortcuts.getShortcuts(this.props.name) this._unbindShortcuts() this._bindShortcuts(shortcutsArr) } componentDidMount() { this._onUpdate() this.context.shortcuts.addUpdateListener(this._onUpdate) } componentWillUnmount() { let shortcutsArr = this.context.shortcuts.getShortcuts(this.props.name) this._unbindShortcuts(shortcutsArr) this.context.shortcuts.removeUpdateListener(this._onUpdate) if (this.props.global) { let element = this._getElementToBind() element.removeEventListener('shortcuts:global', this._customGlobalHandler) } } _handleShortcuts = (event, keyName) => { let shortcutName = this.context.shortcuts.findShortcutName(keyName, this.props.name) this.props.handler(shortcutName, event) } render() { return ( shortcuts({ tabIndex: this.props.tabIndex || -1, className: this.props.className }, this.props.children) ) } }
JavaScript
0.000001
@@ -1004,16 +1004,46 @@ = null%0A%0A + _lastEventTimestamp = null%0A%0A _bindS @@ -1687,24 +1687,128 @@ tor)%0A %7D%0A%0A + if (event.timeStamp === this._lastTimestamp) %7B return %7D%0A%0A this._lastTimestamp = event.timeStamp%0A%0A if (e.ta
d94638071b50af055d8b99f2adfe5a12b7a1d66e
add middleware to enable cors
server/app.js
server/app.js
var express = require('express'), app = express(), mongoose = require('mongoose'), bodyParser = require('body-parser'), methodOverride = require('method-overrride'), port = process.env.PORT || 8080; app.use(bodyParser.json()); // parse application/json app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded app.listen(port, function(){ console.log('listening on port: ', port); });
JavaScript
0
@@ -458,16 +458,260 @@ lencoded +%0Aapp.use(function(req, res, next)%7B // enable CORS (will refactor into middleware later)%0A%09res.header('Access-Control-Allow-Origin', %22*%22);%0A%09res.header('Access-Control-Allow-Headers', %22Origin, X-Requested-With, Content-Type, Accept%22);%0A%09next();%0A%7D); %0A%0Aapp.li
10b421f1bfba985a30ae155ab6e6f0e58609af5e
Correct module paths in app.js.
server/app.js
server/app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var index = require('./routes/index'); var users = require('./routes/users'); var sessions = require('./routes/authenticate'); var passport = require('./config/auth/passport'); var app = express(); app.use(passport.initialize()); // view engine setup // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, '../public/dist/src'))); app.use('/users', users); app.use('/authenticate', authenticate); app.use('*', (req, res, next) => { res.sendFile(path.resolve(__dirname, '../public/index.html')); }); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app;
JavaScript
0
@@ -233,24 +233,28 @@ require('./ +src/ routes/index @@ -276,24 +276,28 @@ require('./ +src/ routes/users @@ -326,16 +326,20 @@ uire('./ +src/ routes/a @@ -380,16 +380,20 @@ uire('./ +src/ config/a
353db44682b24e90cf710629c8e97e9c497f3e03
update example index
examples/index.js
examples/index.js
'use strict'; import 'babel-polyfill'; import React from 'react'; import {render} from 'react-dom'; import createHashHistory from 'history/createHashHistory'; import {renderRoutes} from 'react-router-config'; import {Provider} from 'react-redux'; import {ConnectedRouter} from 'react-router-redux'; import configureStore from 'reduxes/store'; import configureRoutes from './config.routes'; import 'sass/index.scss'; const history = createHashHistory(), store = configureStore(history); render( <Provider store={store}> <ConnectedRouter history={history}> {renderRoutes(configureRoutes(store))} </ConnectedRouter> </Provider>, document.getElementById('app-container') );
JavaScript
0.000001
@@ -12,33 +12,8 @@ ';%0A%0A -import 'babel-polyfill';%0A impo
442260183bb51d43f25e77d7d542685705eb8d0b
fix typo in contract section
src/components/Contract.js
src/components/Contract.js
import React from 'react' import styled from 'styled-components' import SectionContainer from '../components/SectionContainer' import BackgroundContentContainer from '../components/BackgroundContentContainer' //import {headerColor} from '../styles/colors' import {contentWidth} from '../styles/dimens' import strings from '../../data/strings' const TableColumn = styled.div` flex: 1 1 auto; margin-bottom: 1.58rem; background: #f0f0f0; border-top: 4px solid #d0d0d0; ` const ColumnHeader = styled.div` background: #e0e0e0; padding: 12px; ` const ColumnBody = styled.div` display: flex; flex-direction: column; justify-content: center; padding: 12px; ul, li, p { margin-bottom: 0; margin-left: 0; } ol { margin-bottom: 0; margin-left: 1rem; } ` class Contract extends React.Component { render() { return ( <BackgroundContentContainer background='white'> <div css={{ width: '100%', textAlign: 'center', }}> </div> <SectionContainer> <div css={{ }}> <h1>Antrag beim Jugendamt</h1> <p>Die Betreuung bei mir erfolgt über das Jugendamt. Zunächst wird dafür ein Gutschein benötigt. Dieser kann 9 Monate vor Betreuungsbeginn (spätestens 2 Monate vorher) beim Jugendamt beantragt werden.</p> <div css={{ display: 'flex', flexDirection: 'row', width: '100%', '@media(max-width: 800px)': { flexDirection: 'column', } }}> <TableColumn> <ColumnHeader>Ihr benötigt:</ColumnHeader> <ColumnBody> <ol> <li>Antragsformular (<a href='http://www.berlin.de/jugendamt-pankow/dienste-und-leistungen/kindertagesbetreuung/kita/'>Link</a>)</li> <li>Unterschrift beider Sorgeberechtigter</li> <li>Einkommensnachweis</li> <li>Bescheinigung des Arbeitgebers</li> </ol> </ColumnBody> </TableColumn> <TableColumn> <ColumnHeader>Antragsstellung an:</ColumnHeader> <ColumnBody> <ul css={{ listStyleType: 'none', }}> <li>Bezirksamt Pankow von Berlin</li> <li>AG Gutschein</li> <li>Fröbelstr.17/ Haus 4</li> <li>10405 Berlin</li> </ul> </ColumnBody> </TableColumn> <TableColumn> <ColumnHeader>Öffnungszeiten:</ColumnHeader> <ColumnBody> <div css={{ display: 'flex' }}> <div>Montag, Dienstag, Freitag:</div> <div style={{ flex: '1 1 auto', marginLeft: '1rem', textAlign: 'right', }}>9 – 12 Uhr</div> </div> <br/> <div css={{ display: 'flex' }}> <div>Donnerstag:</div> <div style={{ flex: '1 1 auto', marginLeft: '1rem', textAlign: 'right', }}>14 – 18 Uhr</div> </div> </ColumnBody> </TableColumn> </div> <p>Vereinbart am besten einen Termin über <a href='https://service.berlin.de/terminvereinbarung/termin/tag.php?termin=1&dienstleister=324903&anliegen%5B%5D=324873&herkunft=http%3A%2F%2Fservice.berlin.de%2Fdienstleistung%2F324873%2F'>die Webite des Jugendamts Pankow</a> oder telefonisch unter 9 02 95 56 89 während der Öffnungszeiten.</p> <p>Die Kosten der Kinderbetreuung sind einkommensabhängig und bei Kita und Tagespflege gleich.</p> </div> </SectionContainer> </BackgroundContentContainer> ) } } export default Contract
JavaScript
0.000029
@@ -3596,16 +3596,17 @@ %3Edie Web +s ite des
5d63823a0dc037a90a8aab4df79914e75760cfd5
Update HomePage.js
src/components/HomePage.js
src/components/HomePage.js
import React from 'react'; import {Link} from 'react-router'; // Since this component is simple and static, there's no parent container for it. const HomePage = () => { return ( <div> <h1>React Material-UI Components</h1> <h2>Get Started</h2> <ol> <li>View the <Link to="/speed-dial">SpeedDial Component</Link></li> <li>View the <Link to="/number-input">NumberInput Component </Link></li> </ol> </div> ); }; export default HomePage;
JavaScript
0
@@ -299,17 +299,16 @@ ink to=%22 -/ speed-di @@ -374,17 +374,16 @@ ink to=%22 -/ number-i
cb60a12b7ecfb6d018a148db61ebc2912b3e3156
Update index.js
Node.js/index.js
Node.js/index.js
var server = require('./server'); var router = require('./router'); var requestHandlers = require('./requestHandlers'); var handle = {} handle["/"] = requestHandlers.start; handle["/start"] = requestHandlers.start; handle["/upload"] = requestHandlers.upload; server.start(router.route, handle);
JavaScript
0.000002
@@ -252,16 +252,56 @@ .upload; +%0Ahandle%5B%22/show%22%5D = requestHandlers.show; %0A%0Aserver
c6652df227ade009e6def0113a93c3639a15c294
use markdown helper to parse element
src/components/HtmlView.js
src/components/HtmlView.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { View, Platform } from 'react-native'; import RNFS from 'react-native-fs'; import Api from '../utils/api'; import AppStyle from '../theme/styles'; import Dialog from './dialog'; import CustomWebView from './CustomWebView'; export const NATIVE = 'native'; export const NET = 'net'; const marked = require('marked'); class HtmlView extends Component { static componentName = 'HtmlView'; static propTypes = { type: PropTypes.string, url: PropTypes.string, domain: PropTypes.string, slug: PropTypes.string, dialogContent: PropTypes.string, isFullSlug: PropTypes.bool, }; static defaultProps = { type: NATIVE, url: '', domain: '', slug: '', dialogContent: '', isFullSlug: false, }; constructor(props) { super(props); this.state = { visible: true, html: '', }; } componentDidMount() { if (this.props.type === NET) { Api.get(this.props.url) .then(response => this.setState({ visible: false, html: marked(response.data) })) .catch(err => this.setState({ visible: false, html: err.message, })); } else { const basePath = Platform.OS === 'ios' ? RNFS.MainBundlePath : RNFS.ExternalDirectoryPath; if (basePath) { let slug = ''; if (this.props.isFullSlug) { slug = this.props.slug; } else { slug = `/growth-content/${this.props.domain}/${this.props.slug}.html`; } RNFS.readFile(basePath.concat(slug), 'utf8') .then((result) => { this.setState({ html: result, visible: false, }); }); } } } render() { return ( <View style={[AppStyle.detailBasisStyle, { flex: 1 }]} > { this.props.type === NATIVE ? null : <Dialog show={this.state.visible} content={this.props.dialogContent} /> } <CustomWebView html={this.state.html} /> </View>); } } export default HtmlView;
JavaScript
0
@@ -301,16 +301,70 @@ ebView'; +%0Aimport MarkdownHelper from '../utils/MarkdownHelper'; %0A%0Aexport @@ -420,43 +420,8 @@ ';%0A%0A -const marked = require('marked');%0A%0A clas @@ -1125,14 +1125,30 @@ ml: -m +M ark -e d +ownHelper.convert (res
1f79f73d2b41b60e1c440165a0c309aeeafbad55
Simplify normalize function
distance.js
distance.js
// distance.js // Finds the closest user match with n dimensions of compatability // Expects a tag:count map from the user and a tag:count map from a blog module.exports = { match: function(userTags, blogTags) { var counts = []; for (var tag in userTags) { if (tag in blogTags) { counts.push([userTags[tag], blogTags[tag]]); } else { counts.push([userTags[tag], 0]); } }; var sum = 0; for (var i = counts.length - 1; i >= 0; i--) { sum += Math.pow((counts[i][0] - counts[i][1]), 2); }; return Math.sqrt(sum); }, normalize: function(distances) { var values = []; for (var i = distances.length - 1; i >= 0; i--) { values.push(distances[i].distance); }; var min = values.slice(0).sort()[0]; var max = values.slice(0).sort().reverse()[0]; for (var i = distances.length - 1; i >= 0; i--) { distances[i].distance = (max - distances[i].distance)/(max-min); }; return distances; } }
JavaScript
0.000018
@@ -584,100 +584,59 @@ %7B%0A%09%09 -var values = %5B%5D;%0A%09%09for (var i = distances.length - 1; i %3E= 0; i--) %7B%0A%09%09%09values.push( +distances.sort(function(a,b) %7B%0A%09%09%09return a. distance s%5Bi%5D @@ -623,36 +623,36 @@ eturn a.distance -s%5Bi%5D + - b .distance);%0A%09%09%7D; @@ -648,106 +648,34 @@ ance -) ;%0A%09%09%7D +) ;%0A - %09%09var min = values.slice(0).sort()%5B0%5D;%0A %09%09var max = values.slice(0).sort().reverse()%5B0%5D +%09%09distances.sort() ;%0A%09%09 @@ -726,16 +726,17 @@ --) %7B%0A%09%09 + %09distanc @@ -756,73 +756,16 @@ e = -(max - distances%5Bi%5D.distance)/(max-min);%0A%09%09%7D;%0A%09%09return distances; +i;%0A%09%09%7D; %0A%09%7D%0A
8dfd2ef13714d03a3d6f2a33070fbf4d782cc42d
Update PushNotification.js
www/PushNotification.js
www/PushNotification.js
var PushNotification = function() { }; // Call this to register for push notifications. Content of [options] depends on whether we are working with APNS (iOS) or GCM (Android) PushNotification.prototype.register = function(successCallback, errorCallback, options) { if (errorCallback == null) { errorCallback = function() {}} if (typeof errorCallback != "function") { console.log("PushNotification.register failure: failure parameter not a function"); return } if (typeof successCallback != "function") { console.log("PushNotification.register failure: success callback parameter must be a function"); return } cordova.exec(successCallback, errorCallback, "PushPlugin", "register", [options]); }; // Call this to unregister for push notifications PushNotification.prototype.unregister = function(successCallback, errorCallback, options) { if (errorCallback == null) { errorCallback = function() {}} if (typeof errorCallback != "function") { console.log("PushNotification.unregister failure: failure parameter not a function"); return } if (typeof successCallback != "function") { console.log("PushNotification.unregister failure: success callback parameter must be a function"); return } cordova.exec(successCallback, errorCallback, "PushPlugin", "unregister", [options]); }; // Call this if you want to show toast notification on WP8 PushNotification.prototype.showToastNotification = function (successCallback, errorCallback, options) { if (errorCallback == null) { errorCallback = function () { } } if (typeof errorCallback != "function") { console.log("PushNotification.register failure: failure parameter not a function"); return } cordova.exec(successCallback, errorCallback, "PushPlugin", "showToastNotification", [options]); } // Call this to set the application icon badge PushNotification.prototype.setApplicationIconBadgeNumber = function(successCallback, errorCallback, badge) { if (errorCallback == null) { errorCallback = function() {}} if (typeof errorCallback != "function") { console.log("PushNotification.setApplicationIconBadgeNumber failure: failure parameter not a function"); return } if (typeof successCallback != "function") { console.log("PushNotification.setApplicationIconBadgeNumber failure: success callback parameter must be a function"); return } cordova.exec(successCallback, errorCallback, "PushPlugin", "setApplicationIconBadgeNumber", [{badge: badge}]); }; if ( device.platform == 'iOS' || device.platform == 'ios' || device.platform == "IOS" ){ PushNotification.prototype.setAutoMessageCount = function(count) { cordova.exec(null, null, "PushPlugin", "setAutoMessageCount", [count]); }; // https://github.com/phonegap-build/PushPlugin/issues/288#issuecomment-72121589 //Try to change the function's name below to didCompleteBackgroundProcess PushNotification.prototype.backgroundDone = function(successCallback, errorCallback) { if (errorCallback == null) { errorCallback = function() { // Try to add in the Javascript function here!!!! alert("errorsync1"); console.log("PushNotification.backgroundDone failure: success callback parameter must be a function"); // iossync(); }} if (typeof successCallback != "function") { //iossync(); alert("success sync"); console.log("PushNotification.backgroundDone failure: success callback parameter must be a function"); return } alert("success sync3"); cordova.exec(successCallback, errorCallback, "PushPlugin", "didCompleteBackgroundProcess", []); } } //------------------------------------------------------------------- if(!window.plugins) { window.plugins = {}; } if (!window.plugins.pushNotification) { window.plugins.pushNotification = new PushNotification(); } if (typeof module != 'undefined' && module.exports) { module.exports = PushNotification; }
JavaScript
0
@@ -3689,104 +3689,8 @@ - cordova.exec(successCallback, errorCallback, %22PushPlugin%22, %22didCompleteBackgroundProcess%22, %5B%5D); %0A%7D%0A%7D
03fcd0e1b662209770445151c36be93efbfa7219
Fix material update referencing the sceneEl when it has not loaded (#2120)
src/components/material.js
src/components/material.js
/* global Promise */ var utils = require('../utils/'); var component = require('../core/component'); var THREE = require('../lib/three'); var shader = require('../core/shader'); var error = utils.debug('components:material:error'); var registerComponent = component.registerComponent; var shaders = shader.shaders; var shaderNames = shader.shaderNames; /** * Material component. * * @member {object} shader - Determines how material is shaded. Defaults to `standard`, * three.js's implementation of PBR. Another standard shading model is `flat` which * uses MeshBasicMaterial. */ module.exports.Component = registerComponent('material', { schema: { depthTest: {default: true}, flatShading: {default: false}, opacity: {default: 1.0, min: 0.0, max: 1.0}, shader: {default: 'standard', oneOf: shaderNames}, side: {default: 'front', oneOf: ['front', 'back', 'double']}, transparent: {default: false}, visible: {default: true} }, init: function () { this.material = null; }, /** * Update or create material. * * @param {object|null} oldData */ update: function (oldData) { var data = this.data; if (!this.shader || data.shader !== oldData.shader) { this.updateShader(data.shader); } this.shader.update(this.data); this.updateMaterial(); }, updateSchema: function (data) { var newShader = data.shader; var currentShader = this.data && this.data.shader; var shader = newShader || currentShader; var schema = shaders[shader] && shaders[shader].schema; if (!schema) { error('Unknown shader schema ' + shader); } if (currentShader && newShader === currentShader) { return; } this.extendSchema(schema); this.updateBehavior(); }, updateBehavior: function () { var scene = this.el.sceneEl; var schema = this.schema; var self = this; var tickProperties = {}; var tick = function (time, delta) { var keys = Object.keys(tickProperties); keys.forEach(update); function update (key) { tickProperties[key] = time; } self.shader.update(tickProperties); }; var keys = Object.keys(schema); keys.forEach(function (key) { if (schema[key].type === 'time') { self.tick = tick; tickProperties[key] = true; scene.addBehavior(self); } }); if (Object.keys(tickProperties).length === 0) { scene.removeBehavior(this); } }, updateShader: function (shaderName) { var data = this.data; var Shader = shaders[shaderName] && shaders[shaderName].Shader; var shaderInstance; if (!Shader) { throw new Error('Unknown shader ' + shaderName); } // Get material from A-Frame shader. shaderInstance = this.shader = new Shader(); shaderInstance.el = this.el; shaderInstance.init(data); this.setMaterial(shaderInstance.material); this.updateSchema(data); }, updateMaterial: function () { var data = this.data; var material = this.material; material.side = parseSide(data.side); material.opacity = data.opacity; material.transparent = data.transparent !== false || data.opacity < 1.0; material.depthTest = data.depthTest !== false; material.shading = data.flatShading ? THREE.FlatShading : THREE.SmoothShading; material.visible = data.visible; }, /** * Remove material on remove (callback). * Dispose of it from memory and unsubscribe from scene updates. */ remove: function () { var defaultMaterial = new THREE.MeshBasicMaterial(); var material = this.material; var object3D = this.el.getObject3D('mesh'); if (object3D) { object3D.material = defaultMaterial; } disposeMaterial(material, this.system); }, /** * (Re)create new material. Has side-effects of setting `this.material` and updating * material registration in scene. * * @param {object} data - Material component data. * @param {object} type - Material type to create. * @returns {object} Material. */ setMaterial: function (material) { var mesh = this.el.getOrCreateObject3D('mesh', THREE.Mesh); var system = this.system; if (this.material) { disposeMaterial(this.material, system); } this.material = mesh.material = material; system.registerMaterial(material); } }); /** * Returns a three.js constant determining which material face sides to render * based on the side parameter (passed as a component property). * * @param {string} [side=front] - `front`, `back`, or `double`. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide. */ function parseSide (side) { switch (side) { case 'back': { return THREE.BackSide; } case 'double': { return THREE.DoubleSide; } default: { // Including case `front`. return THREE.FrontSide; } } } /** * Dispose of material from memory and unsubscribe material from scene updates like fog. */ function disposeMaterial (material, system) { material.dispose(); system.unregisterMaterial(material); }
JavaScript
0
@@ -1795,41 +1795,8 @@ ) %7B%0A - var scene = this.el.sceneEl;%0A @@ -2126,24 +2126,51 @@ ys(schema);%0A + this.tick = undefined;%0A keys.for @@ -2304,142 +2304,17 @@ - scene.addBehavior(self);%0A %7D%0A %7D);%0A if (Object.keys(tickProperties).length === 0) %7B%0A scene.removeBehavior(this);%0A %7D +%7D%0A %7D); %0A %7D
3198ff488e613151d9ceab04095a8f5c4ae667bf
range slider component
pages/about.js
pages/about.js
import React from "react"; import PropTypes from 'prop-types' import {Link} from "react-router"; import {prefixLink} from "gatsby-helpers"; import {config} from "config"; import RangeSlider from '../components/rangeSlider' class About extends React.Component { constructor(props) { super(props) this.state = { minValue: 0, maxValue: 100, step: 5, firstRange: 50, secondRange: 50, thirdRange: 50 } } handleChange = (event, name) => { let value = event.target.value; let name2 = event.target.name let obj = {} obj[name2] = value return this.setState(obj) } handleChange2 = (event) => { let value = event.target.value; let name = event.target.name let obj = {} obj[name] = value console.log(obj) return this.setState(obj) } render() { return ( <div> <br/> <br/> <br/> <RangeSlider minValue='0' maxValue='100' rangeValue={this.state.firstRange} rangeName='firstRange' step={this.state.step} handleChange={this.handleChange2} /> <RangeSlider minValue='0' maxValue='100' rangeValue={this.state.secondRange} rangeName='secondRange' step={this.state.step} handleChange={this.handleChange2} /> <RangeSlider minValue='0' maxValue='100' rangeValue={this.state.thirdRange} rangeName='thirdRange' step={this.state.step} handleChange={this.handleChange2} /> <br/> <br/> <br/> <br/> <p>Welcome to page 2</p> <Link to={prefixLink('/')}>Go back to the homepage</Link> <br/> <br/> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium ad deleniti dicta eaque explicabo harum necessitatibus repellendus sint. Facilis labore maxime officiis rerum similique. Ab fugiat quisquam reiciendis reprehenderit sunt.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias aliquid aperiam debitis dolor dolores, eveniet fuga fugiat id magnam molestiae nihil quaerat, repellendus velit. Ipsa maiores quisquam repellendus sint totam.</p> </div> ) } } export default About
JavaScript
0
@@ -520,214 +520,8 @@ ge = - (event, name) =%3E %7B%0A let value = event.target.value;%0A let name2 = event.target.name%0A let obj = %7B%7D%0A obj%5Bname2%5D = value%0A return this.setState(obj)%0A %7D%0A%0A handleChange2 = (ev @@ -1119,33 +1119,32 @@ his.handleChange -2 %7D /%3E%0A @@ -1419,25 +1419,24 @@ handleChange -2 %7D /%3E%0A @@ -1717,17 +1717,16 @@ leChange -2 %7D /%3E%0A%0A%0A%0A @@ -1761,32 +1761,253 @@ %3Cbr/%3E%0A + %3Ch1%3ETotal sum :%0A %7BparseInt(this.state.firstRange) +%0A parseInt(this.state.secondRange) +%0A parseInt(this.state.thirdRange)%7D%0A %3C/h1%3E%0A
12292eb56c82dd065cd2ff0bd971c2cf36ea190e
Update PushNotification.js
www/PushNotification.js
www/PushNotification.js
var PushNotification = function() { }; // Call this to register for push notifications. Content of [options] depends on whether we are working with APNS (iOS) or GCM (Android) PushNotification.prototype.register = function(successCallback, errorCallback, options) { if (errorCallback == null) { errorCallback = function() {}} if (typeof errorCallback != "function") { console.log("PushNotification.register failure: failure parameter not a function"); return } if (typeof successCallback != "function") { console.log("PushNotification.register failure: success callback parameter must be a function"); return } cordova.exec(successCallback, errorCallback, "PushPlugin", "register", [options]); }; // Call this to unregister for push notifications PushNotification.prototype.unregister = function(successCallback, errorCallback, options) { if (errorCallback == null) { errorCallback = function() {}} if (typeof errorCallback != "function") { console.log("PushNotification.unregister failure: failure parameter not a function"); return } if (typeof successCallback != "function") { console.log("PushNotification.unregister failure: success callback parameter must be a function"); return } cordova.exec(successCallback, errorCallback, "PushPlugin", "unregister", [options]); }; // Call this if you want to show toast notification on WP8 PushNotification.prototype.showToastNotification = function (successCallback, errorCallback, options) { if (errorCallback == null) { errorCallback = function () { } } if (typeof errorCallback != "function") { console.log("PushNotification.register failure: failure parameter not a function"); return } cordova.exec(successCallback, errorCallback, "PushPlugin", "showToastNotification", [options]); } // Call this to set the application icon badge PushNotification.prototype.setApplicationIconBadgeNumber = function(successCallback, errorCallback, badge) { if (errorCallback == null) { errorCallback = function() {}} if (typeof errorCallback != "function") { console.log("PushNotification.setApplicationIconBadgeNumber failure: failure parameter not a function"); return } if (typeof successCallback != "function") { console.log("PushNotification.setApplicationIconBadgeNumber failure: success callback parameter must be a function"); return } cordova.exec(successCallback, errorCallback, "PushPlugin", "setApplicationIconBadgeNumber", [{badge: badge}]); }; if ( device.platform == 'ios' || device.platform == 'IOS' || device.platform == 'iOS'){ // Call this to set/reset/unset auto increment of android message number PushNotification.prototype.setAutoMessageCount = function(count) { cordova.exec(null, null, "PushPlugin", "setAutoMessageCount", [count]); }; // https://github.com/phonegap-build/PushPlugin/issues/288#issuecomment-72121589 //Try to change the function's name below to didCompleteBackgroundProcess PushNotification.prototype.didCompleteBackgroundProcess = function(successCallback, errorCallback) { if (errorCallback == null) { errorCallback = function() { // Try to add in the Javascript function here!!!! alert("errorsync1"); console.log("PushNotification.backgroundDone failure: success callback parameter must be a function"); // iossync(); }} if (typeof successCallback != "function") { //iossync(); alert("success sync"); console.log("PushNotification.backgroundDone failure: success callback parameter must be a function"); return } cordova.exec(successCallback, errorCallback, "PushPlugin", "didCompleteBackgroundProcess", []); } }; //------------------------------------------------------------------- if(!window.plugins) { window.plugins = {}; } if (!window.plugins.pushNotification) { window.plugins.pushNotification = new PushNotification(); } if (typeof module != 'undefined' && module.exports) { module.exports = PushNotification; }
JavaScript
0
@@ -3131,28 +3131,17 @@ ototype. -didCompleteB +b ackgroun @@ -3141,23 +3141,20 @@ ckground -Process +Done = funct
34177ae045e6531fa402ccc431c13fca5ecf4140
remove temp code
client/app/repo_chooser/repo_chooser_view.js
client/app/repo_chooser/repo_chooser_view.js
Nimble.RepoChooserView = Ember.View.extend({ didInsertElement: function() { $("#repos-modal").modal("show") .on("hidden.bs.modal", function() { return this.controller.send("close_modal"); }.bind(this)); }, test: function() { return this.contentIndex; }.property(), repos: function() { return this.controller.get("repos").map(function(i, idx) { return {repo: i, active: idx === 0}; }); }.property("controller.repos"), actions: { selected_repo: function(owner, name) { var repo = {owner: owner, name: name}; this.controller.cache.set("selected_repo", repo); $("#repos-modal").modal("hide").on("hidden.bs.modal", function() { var storageKey = "nimble.saw_repo_chooser_hint", sawHint = localStorage.getItem(storageKey); this.controller.transitionToRoute("issues", repo); if (!sawHint) { localStorage.setItem(storageKey, true); $("#repo-chooser-center").popover("show") .on("shown.bs.popover", function() { $("#close-repo-chooser-popover").click(function() { $(this).popover("destroy"); }.bind(this)); }); } }.bind(this)); } } });
JavaScript
0.000002
@@ -260,84 +260,8 @@ %7D,%0A%0A - test: function() %7B%0A return this.contentIndex;%0A %7D.property(),%0A%0A
fef099ceccb3a1e43d906fc123e0c83b791b300d
Update braintree-plugin.js
www/braintree-plugin.js
www/braintree-plugin.js
"use strict"; var exec = require("cordova/exec"); /** * The Cordova plugin ID for this plugin. */ var PLUGIN_ID = "BraintreePlugin"; /** * The plugin which will be exported and exposed in the global scope. */ var BraintreePlugin = {}; /** * Used to initialize the Braintree client. * * The client must be initialized before other methods can be used. * * @param {string} token - The client token or tokenization key to use with the Braintree client. * @param [function] successCallback - The success callback for this asynchronous function. * @param [function] failureCallback - The failure callback for this asynchronous function; receives an error string. */ BraintreePlugin.initialize = function initialize(token, successCallback, failureCallback) { if (!token || typeof(token) !== "string") { failureCallback("A non-null, non-empty string must be provided for the token parameter."); return; } exec(successCallback, failureCallback, PLUGIN_ID, "initialize", [token]); }; /** * Shows Braintree's drop-in payment UI. * * @param [function] successCallback - The success callback for this asynchronous function; receives a result object. * @param [function] failureCallback - The failure callback for this asynchronous function; receives an error string. */ BraintreePlugin.presentDropInPaymentUI = function showDropInUI(options, successCallback, failureCallback) { if (!options) { options = {}; } if (typeof(options.cancelText) !== "string") { options.cancelText = "Cancel"; } if (typeof(options.title) !== "string") { options.title = ""; }; var pluginOptions = [ cancelText, title ]; exec(successCallback, failureCallback, PLUGIN_ID, "presentDropInPaymentUI", pluginOptions); }; module.exports = BraintreePlugin;
JavaScript
0
@@ -1646,16 +1646,18 @@ %7D;%0A%0A +/* var plu @@ -1711,16 +1711,18 @@ e%0A %5D; +*/ %0A%0A ex @@ -1795,23 +1795,17 @@ entUI%22, -pluginO +o ptions);
7931b19c144057b8bc35e0154d189c0e92122825
put controls in right place
suave/static/js/jquery.badmanforms.js
suave/static/js/jquery.badmanforms.js
/* -------------------------------- * GENERIC TING * ------------------------------ */ function init_special_select(element, type) { old = element.parent().parent().find('div.' + type); old.remove(); var controls = jQuery('<div/>', { class: type, }); jQuery('<ul/>').appendTo(controls); hide = jQuery('<div/>').appendTo(controls).hide(); controls.prependTo(element.parent()); element.addClass('orig'); element.appendTo(hide); return controls; } /* -------------------------------- * MULTIFILTER * ------------------------------ */ function killa(li) { var a = jQuery('<a/>', { href: 'javascript:void(0)', html: 'x', class: 'kill', }); a.appendTo(li); } function create_dropdown(options, selected) { if (selected == undefined) { selected = { value: -1 } } var li = jQuery('<li/>'); var select = jQuery('<select/>'); var option = jQuery('<option/>', { value: -1, text: '- Select One -' }); option.appendTo(select); $.each(options, function(k, v) { v = $(v); var option = jQuery('<option/>', { value: v.val(), text: v.text(), }); if (v.val() == selected.value) { option.attr('selected', true); } option.appendTo(select); }) select.appendTo(li); if (selected.value > 0) { killa(li); } return li; } function multifilter_update(controls) { var orig = $('select.orig', controls); var ul = $('ul', controls); $('ul li', controls).each(function(k, v) { var select = $('select', $(v)); if (select.val() > 0) { } else { select.closest('li').remove(); select.remove(); } }) var o = []; $('ul li', controls).each(function(k, v) { var li = $(v); var select = li.find('select'); if (select.val() != -1) { o.push(select.val()); if ($('a', li).length == 0) { killa(li); } } }); orig.val(o); var li = create_dropdown($('option', orig)); li.appendTo(ul); } function multifilter_change(event) { event.preventDefault(); var select = $(event.currentTarget); var controls = $(event.delegateTarget); multifilter_update(controls); } var multifilter_change_debounced = _.debounce(multifilter_change, 10); function multifilter_kill(event) { event.preventDefault(); controls = $(event.delegateTarget); var li = $(event.currentTarget).closest('li') var select = li.find('select'); select.val(-1); multifilter_update(controls); } var multifilter_kill_debounced = _.debounce(multifilter_kill, 10); $.fn.multifilter = function(options) { $(this).each(function(i, element) { var element = $(element); var options = $('option', element); var selected = $('option:selected', element); var controls = init_special_select(element, 'multifilter'); $.each(selected, function(k, v) { var li = create_dropdown(options, v); li.appendTo($('ul', controls)); }) var li = create_dropdown(options); li.appendTo($('ul', controls)); controls.on('change', 'select', multifilter_change_debounced); controls.on('click', 'a.kill', multifilter_kill_debounced); }); } /* -------------------------------- * CHECKGROUP * ------------------------------ */ function create_check(value, selected, title, element) { if (selected) { var ch = ' checked'; } else { var ch = ''; } check_id = 'check_' + element.attr('name') + '_' + value; var li = jQuery('<li/>'); var input_attrs = { 'v': value, id: check_id, type: 'checkbox' } if (selected) { input_attrs['checked'] = true; } var input = jQuery('<input/>', input_attrs); var label = jQuery('<label/>', { 'for': check_id, 'text': title, }); input.appendTo(li); label.appendTo(li); var br = jQuery('<br/>'); br.appendTo(li); return li; } function checkgroup_change(event) { event.preventDefault(); var check = $(event.currentTarget); var controls = $(event.delegateTarget); var orig = $('select', controls); var option = $('option[value=' + check.attr('v') + ']', orig); var o = orig.val(); if (o == null) { var o = []; } if (check.attr('checked')) { o.push(check.attr('v')); orig.val(o); } else { orig.val(jQuery.grep(o, function(value) { return value != check.attr('v'); })); } }; var checkgroup_change_debounced = _.debounce(checkgroup_change, 10); $.fn.checkgroup = function(options) { $(this).each(function(i, element) { var element = $(element); var options = $('option', element); var selected = $('option:selected', element); var controls = init_special_select(element, 'checkgroup'); $.each(options, function(k, option) { title = $(option).text(); $('ul', controls).append(create_check(option.value, option.selected, title, element)); }); controls.on('change', 'input', checkgroup_change); }); };
JavaScript
0.000001
@@ -383,34 +383,28 @@ ols. -prependTo(element.parent() +insertBefore(element );%0A
17b6371a2b3f59a836e732e60a3bcdcac67366b6
Fix require in ES6 code
pages/index.js
pages/index.js
import React from 'react'; import LoadChart from './components/LoadChart.js'; import 'isomorphic-fetch'; import io from 'socket.io-client'; import { getURL, sockets, api } from '../common/configuration.js'; import css, { merge } from 'next/css'; const { getConsoleTimestamp } = require('../common/log.js'); const getLoadsFromMeasure = (measure, cores) => { const timestamp = new Date(measure.timestamp); return { loadOne: { load: measure.load[0]/cores, timestamp }, loadFive: { load: measure.load[1]/cores, timestamp }, loadFifteen: { load: measure.load[2]/cores, timestamp }, }; }; const getLoadArrays = (measures, cores, arrays = [[], [], []]) => { return measures.reduce((arrays, measure) => { const loads = getLoadsFromMeasure(measure, cores); arrays[0].push(loads.loadOne); arrays[1].push(loads.loadFive); arrays[2].push(loads.loadFifteen); return arrays; }, arrays); }; const style = { chart: css({ display: 'inline-block' }), alerts: css({ display: 'inline-block', width: '300px', verticalAlign: 'top', padding: '16px' }), alert: css({ padding: '4px 8px', border: '1px solid black', borderRadius: '4px', marginBottom: '4px' }) }; style.alertStart = merge(style.alert, css({ borderColor: '#EE605E', backgroundColor: '#F09393', color: '#A32828' })); style.alertEnd = merge(style.alert, css({ borderColor: '#99CCE6', backgroundColor: '#C4E4F4', color: '#266687' })); export default class Dashboard extends React.Component { static getInitialProps() { return fetch(getURL(api.load)) .then(response => response.json()) .then(data => ({ machine: data.machine, measures: data.measures, alerts: data.alerts })); } constructor(props) { super(props); const loadArrays = getLoadArrays(props.measures, props.machine.cores); this.state = { loadOne: loadArrays[0], loadFive: loadArrays[1], loadFifteen: loadArrays[2], alerts: props.alerts }; } componentDidMount() { const socket = io.connect(getURL(sockets.dashboard)); socket.on('new.measure', data => { const newLoadArrays = getLoadArrays([data], this.props.machine.cores, [ this.state.loadOne.slice(0), this.state.loadFive.slice(0), this.state.loadFifteen.slice(0) ]); this.setState({ loadOne: newLoadArrays[0], loadFive: newLoadArrays[1], loadFifteen: newLoadArrays[2] }); }); socket.on('alert.start', alert => { const newAlertArray = this.state.alerts.concat(Object.assign(alert, { type: 'start' })); this.setState({ alerts: newAlertArray }); }); socket.on('alert.end', alert => { const newAlertArray = this.state.alerts.concat(Object.assign(alert, { type: 'end' })); this.setState({ alerts: newAlertArray }); }); } render() { return ( <div> <div className={style.chart}> <LoadChart loadOne={this.state.loadOne} loadFive={this.state.loadFive} loadFifteen={this.state.loadFifteen} /> </div> <div className={style.alerts}> {this.state.alerts.map((alert, index) => <div className={alert.type === 'start' ? style.alertStart : style.alertEnd} key={index}> {`${getConsoleTimestamp(alert.timestamp)} ${alert.message}`} </div> )} </div> </div> ); } }
JavaScript
0
@@ -239,20 +239,21 @@ t/css';%0A -cons +impor t %7B getC @@ -274,18 +274,13 @@ p %7D -= require( +from '../ @@ -293,17 +293,16 @@ /log.js' -) ;%0A%0Aconst
50a5457341f75ebb3d7e0532d9d915fad407bf44
return regions cursor directly
client/views/frames/propose/frame.propose.js
client/views/frames/propose/frame.propose.js
import Metatags from '/imports/Metatags.js'; Router.map(function () { this.route('framePropose', { path: '/frame/propose', template: 'framePropose', layoutTemplate: 'frameLayout', waitOn: function () { this.filter = Filtering(EventPredicates).read(this.params.query).done(); var filterParams = this.filter.toParams(); filterParams.after = minuteTime.get(); var limit = parseInt(this.params.query.count, 10) || 6; return [ Meteor.subscribe('eventsFind', filterParams, limit*2), Meteor.subscribe('regions') ]; }, data: function() { regions = Regions.find(); return regions; }, onAfterAction: function() { Metatags.setCommonTags(mf('course.propose.windowtitle', 'Propose new course')); } }); });
JavaScript
0.000001
@@ -576,15 +576,12 @@ %09%09re -gions = +turn Reg @@ -597,27 +597,8 @@ ();%0A -%09%09%09return regions;%0A %09%09%7D,
c8b317aeebe0b790df6e6177751b3395eb332e0a
fix typo with transitionend
src/util/dom.js
src/util/dom.js
const nativeRaf= window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame const nativeCancelRaf = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame export const raf = nativeRaf || function(callback) { return window.setTimeout(callback, 16.6667) } export const rafCancel = nativeRaf ? nativeCancelRaf : function(id) { return window.cancelTimeout(id) } export function rafPromise() { return new Promise(resolve => raf(resolve)) } // We only need to test for webkit in our supported browsers. Webkit is the only browser still // using prefixes. // Code adapted from angular-animate.js export let css = {} if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) { css.prefix = 'webkit' css.transition = 'webkitTransition' css.transform = 'webkitTransform' css.transitionEnd = 'webkitTransitionEnd transitionend' } else { css.prefix = '' css.transform = 'transform' css.transition = 'transition' css.transitionEnd = 'tranistionend' } export function transitionEndPromise(el:Element) { return new Promise(resolve => { css.transitionEnd.split(' ').forEach(eventName => { el.addEventListener(css.transitionEnd, onTransitionEnd) }) function onTransitionEnd(ev) { // Don't allow bubbled transitionend events if (ev.target !== el) { return } css.transitionEnd.split(' ').forEach(eventName => { el.removeEventListener(css.transitionEnd, onTransitionEnd) }) resolve(ev) } }) }
JavaScript
0.000001
@@ -1082,18 +1082,18 @@ = 'tran -i s +i tionend' @@ -1264,33 +1264,88 @@ istener( -css.transitionEnd +eventName, onTransitionEnd)%0A console.log('eventListener', eventName , onTran
2d547a7d2f68d4a3ba69dd08cab21edf0e0f29a9
Add noop function
src/utils/fn.js
src/utils/fn.js
/** * Function module. * @module base/utils/func */ /** * Returns a function, that, as long as it continues to be invoked, will not * be triggered. The function will be called after it stops being called for * N milliseconds. If `immediate` is passed, trigger the function on the * leading edge, instead of the trailing. The function also has a property 'clear' * that is a function which will clear the timer to prevent previously scheduled executions. * * @source underscore.js * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/ * @param {Function} func * Function to wrap. * @param {Number} wait * Timeout in ms (`60`). * @param {Boolean} immediate * Whether to execute at the beginning (`false`). * * @returns {Function} * A new function that wraps the `func` function passed in. */ export function debounce(func, wait = 60, immediate = false) { var timeout, args, context, timestamp, result function later() { var last = Date.now() - timestamp if (last < wait && last > 0) { timeout = setTimeout(later, wait - last) } else { timeout = null if (!immediate) { result = func.apply(context, args) context = args = null } } } var debounced = function() { context = this args = arguments timestamp = Date.now() var callNow = immediate && !timeout if (!timeout) timeout = setTimeout(later, wait) if (callNow) { result = func.apply(context, args) context = args = null } return result } debounced.clear = function() { if (timeout) { clearTimeout(timeout) timeout = null } } return debounced } /** * Returns a new function that, when invoked, invokes `func` at most once per `wait` milliseconds. * * @param {Function} func * Function to wrap. * @param {Number} wait * Number of milliseconds that must elapse between `func` invocations. * * @returns {Function} * A new function that wraps the `func` function passed in. */ export function throttle(func, wait = 60) { var ctx, args, rtn, timeoutID // caching var last = 0 return function throttled() { ctx = this args = arguments var delta = new Date() - last if (!timeoutID) if (delta >= wait) call() else timeoutID = setTimeout(call, wait - delta) return rtn } function call() { timeoutID = 0 last = +new Date() rtn = func.apply(ctx, args) ctx = null args = null } } /** * Execute functionality just once. * * @param {Function} fn - Function to execute just once. * @param {*} context - Context to execute the function in. * * @returns {Function} */ export function once(fn, context) { var result return function() { if (fn) { result = fn.apply(context || this, arguments) fn = null } return result } } /** * Request animation frame polyfill method. * * @see https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ * @see https://developer.mozilla.org/de/docs/Web/API/window/requestAnimationFrame */ export var rAF = (function() { return ( window.requestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60) } ) })().bind(window) export default { debounce, throttle, once, rAF }
JavaScript
0
@@ -2483,24 +2483,272 @@ null%0A %7D%0A%7D%0A%0A +/**%0A * Returns undefined irrespective of the arguments passed to it.%0A *%0A * Using the noop the intent of a default callback is clear.%0A * An empty function might indicate unfinished business.%0A *%0A * @returns %7Bundefined%7D%0A */%0Aexport function noop() %7B%7D%0A%0A /**%0A * Execu @@ -3558,16 +3558,24 @@ rottle,%0A + noop,%0A once,%0A
27d9c03935850eac1600a016f71d9424e742ad85
Create initial content entity methods.
lib/entities/content.js
lib/entities/content.js
module.exports = function(app){ "use strict"; var content = {}; content.getRandomContent = function(params){ }; /** * Initialize the content object with a configuration * @param config Object that includes information that this object needs like contentid. */ content.init = function(config){ this.config = config; }; return content; };
JavaScript
0
@@ -1,21 +1,5 @@ -module.exports = +( func @@ -7,11 +7,8 @@ ion( -app )%7B%0A @@ -49,235 +49,335 @@ = %7B%7D -;%0A%0A content.getRandomContent = function(params +,%0A db = require(%22../db%22);%0A%0A content.create = function(obj, callback )%7B%0A -%0A -%7D;%0A%0A /**%0A * Initialize the content object with a configuration%0A * @param config Object that includes information that this object needs like contentid. + db.content.create(obj, callback);%0A %7D;%0A%0A content.getById = function(id, callback)%7B%0A db.content.getById(id, callback);%0A %7D;%0A%0A content.deleteById = function(id, callback)%7B%0A db.content.deleteById(id, callback); %0A - */ +%7D;%0A %0A @@ -389,12 +389,14 @@ ent. -init +update = f @@ -407,65 +407,94 @@ ion( -config)%7B%0A this.config = config;%0A %7D;%0A%0A return +obj, callback)%7B%0A db.content.update(obj, callback);%0A %7D;%0A%0A module.exports = con @@ -500,9 +500,14 @@ ntent;%0A%7D -; +)();%0A%0A
7a408d861e3d8adeca1c9c7623351630f8fc02a8
Fix for match
src/helpers/match.js
src/helpers/match.js
export default function match(original, search, replace) { // This also works with "startsWithNot" (see below) // !search === replace becomes search !== replace // original === replace is evaluated before the code below if (search === replace || original === replace) { return false } var startsWithNot = search.charAt(0) === '!' var startsWithStar = search.charAt(0) === '*' var endsWithStar = search.slice(-1) === '*' if (startsWithNot) { return match(original, search.slice(1), replace) } if (startsWithStar && endsWithStar) { return original.includes(search.slice(1, -1)) } if (startsWithStar) { return original.endsWith(search.slice(1)) } if (endsWithStar) { return original.startsWith(search.slice(0, -1)) } return original === search }
JavaScript
0.000001
@@ -1,19 +1,4 @@ -export default func @@ -454,16 +454,17 @@ return +! match(or @@ -782,8 +782,30 @@ earch%0A%7D%0A +%0Aexport default match%0A
f2deae15b14070b796a23689525288b4318f33d0
remove some whitespace
data2xml.js
data2xml.js
// -------------------------------------------------------------------------------------------------------------------- // // data2xml.js - A data to XML converter with a nice interface (for NodeJS). // // Copyright (c) 2011 Andrew Chilton - http://chilts.org/ // Written by Andrew Chilton <andychilton@gmail.com> // // License: http://opensource.org/licenses/MIT // // -------------------------------------------------------------------------------------------------------------------- var valid = { 'omit' : true, // no element is output : '' 'empty' : true, // an empty element is output : '<element></element>' 'closed' : true // a closed element is output : '<element/>' }; var defaults = { 'attrProp' : '_attr', 'valProp' : '_value', 'undefined' : 'omit', 'null' : 'omit', 'xmlDecl' : true }; var xmlHeader = '<?xml version="1.0" encoding="utf-8"?>\n'; module.exports = function(opts) { opts = opts || {}; opts.attrProp = opts.attrProp || defaults.attrProp; opts.valProp = opts.valProp || defaults.valProp; if (typeof opts.xmlDecl === 'undefined') { opts.xmlDecl = defaults.xmlDecl; } if ( opts['undefined'] && valid[opts['undefined']] ) { // nothing, this is fine } else { opts['undefined'] = defaults['undefined']; } if ( opts['null'] && valid[opts['null']] ) { // nothing, this is fine } else { opts['null'] = defaults['null']; } return function(name, data) { var xml = opts.xmlDecl ? xmlHeader : ''; xml += makeElement(name, data, opts); return xml; }; }; function entitify(str) { str = '' + str; str = str .replace(/&/g, '&amp;') .replace(/</g,'&lt;') .replace(/>/g,'&gt;') .replace(/'/g, '&apos;') .replace(/"/g, '&quot;'); return str; } function makeElementAttrs(attr) { var attributes = ''; for(var a in attr) { attributes += ' ' + a + '="' + entitify(attr[a]) + '"'; } return attributes; } function makeStartTag(name, attr) { attr = attr || {}; var tag = '<' + name; tag += makeElementAttrs(attr); tag += '>'; return tag; } function makeClosedElement(name, attr) { attr = attr || {}; var tag = '<' + name; tag += makeElementAttrs(attr); tag += '/>'; return tag; } function undefinedElement(name, attr, opts) { if ( opts['undefined'] === 'omit' ) { return ''; } if ( opts['undefined'] === 'empty' ) { return makeStartTag(name, attr) + makeEndTag(name); } else if ( opts['undefined'] === 'closed' ) { return makeClosedElement(name, attr); } } function nullElement(name, attr, opts) { if ( opts['null'] === 'omit' ) { return ''; } if ( opts['null'] === 'empty' ) { return makeStartTag(name, attr) + makeEndTag(name); } else if ( opts['null'] === 'closed' ) { return makeClosedElement(name, attr); } } function makeEndTag(name) { return '</' + name + '>'; } function makeElement(name, data, opts) { var element = ''; if ( Array.isArray(data) ) { data.forEach(function(v) { element += makeElement(name, v, opts); }); return element; } else if ( typeof data === 'undefined' ) { return undefinedElement(name, null, opts); } else if ( data === null ) { return nullElement(name, null, opts); } else if ( typeof data === 'object' ) { var valElement; if (data.hasOwnProperty(opts.valProp)) { valElement = data[opts.valProp]; if (typeof valElement === 'undefined') { return undefinedElement(name, data[opts.attrProp], opts); } else if (valElement === null) { return nullElement(name, data[opts.attrProp], opts); } } element += makeStartTag(name, data[opts.attrProp]); if (valElement) { element += entitify(valElement); } for (var el in data) { if ( el === opts.attrProp || el === opts.valProp ) { continue; } element += makeElement(el, data[el], opts); } element += makeEndTag(name); return element; } else { // a piece of data on it's own can't have attributes return makeStartTag(name) + entitify(data) + makeEndTag(name); } throw 'Unknown data ' + data; } // -------------------------------------------------------------------------------------------------------------------- module.exports.makeStartTag = makeStartTag; module.exports.makeEndTag = makeEndTag; module.exports.makeElement = makeElement; module.exports.entitify = entitify; // --------------------------------------------------------------------------------------------------------------------
JavaScript
0.999999
@@ -3772,32 +3772,16 @@ opts);%0A - %0A @@ -3901,17 +3901,16 @@ %7D - %0A @@ -4508,17 +4508,16 @@ ata;%0A%7D%0A%0A -%0A // -----
de0d97dadeffb04bd61f2842aaa05778d073cf7d
location.replace and assign order (#1043)
src/history/html5.js
src/history/html5.js
/* @flow */ import type VueRouter from '../index' import { assert } from '../util/warn' import { inBrowser } from '../util/dom' import { cleanPath } from '../util/path' import { History } from './base' import { saveScrollPosition, getScrollPosition, isValidPosition, normalizePosition, getElementPosition } from '../util/scroll-position' // use User Timing api (if present) for more accurate key precision const Time = inBrowser ? (window.performance || Date) : Date const genKey = () => String(Time.now()) let _key: string = genKey() export class HTML5History extends History { constructor (router: VueRouter, base: ?string) { super(router, base) const expectScroll = router.options.scrollBehavior window.addEventListener('popstate', e => { _key = e.state && e.state.key const current = this.current this.transitionTo(getLocation(this.base), next => { if (expectScroll) { this.handleScroll(next, current, true) } }) }) if (expectScroll) { window.addEventListener('scroll', () => { saveScrollPosition(_key) }) } } go (n: number) { window.history.go(n) } push (location: RawLocation) { const current = this.current this.transitionTo(location, route => { pushState(cleanPath(this.base + route.fullPath)) this.handleScroll(route, current, false) }) } replace (location: RawLocation) { const current = this.current this.transitionTo(location, route => { replaceState(cleanPath(this.base + route.fullPath)) this.handleScroll(route, current, false) }) } ensureURL (push?: boolean) { if (getLocation(this.base) !== this.current.fullPath) { const current = cleanPath(this.base + this.current.fullPath) push ? pushState(current) : replaceState(current) } } handleScroll (to: Route, from: Route, isPop: boolean) { const router = this.router if (!router.app) { return } const behavior = router.options.scrollBehavior if (!behavior) { return } if (process.env.NODE_ENV !== 'production') { assert(typeof behavior === 'function', `scrollBehavior must be a function`) } // wait until re-render finishes before scrolling router.app.$nextTick(() => { let position = getScrollPosition(_key) const shouldScroll = behavior(to, from, isPop ? position : null) if (!shouldScroll) { return } const isObject = typeof shouldScroll === 'object' if (isObject && typeof shouldScroll.selector === 'string') { const el = document.querySelector(shouldScroll.selector) if (el) { position = getElementPosition(el) } else if (isValidPosition(shouldScroll)) { position = normalizePosition(shouldScroll) } } else if (isObject && isValidPosition(shouldScroll)) { position = normalizePosition(shouldScroll) } if (position) { window.scrollTo(position.x, position.y) } }) } } export function getLocation (base: string): string { let path = window.location.pathname if (base && path.indexOf(base) === 0) { path = path.slice(base.length) } return (path || '/') + window.location.search + window.location.hash } function pushState (url: string, replace?: boolean) { // try...catch the pushState call to get around Safari // DOM Exception 18 where it limits to 100 pushState calls const history = window.history try { if (replace) { history.replaceState({ key: _key }, '', url) } else { _key = genKey() history.pushState({ key: _key }, '', url) } saveScrollPosition(_key) } catch (e) { window.location[replace ? 'assign' : 'replace'](url) } } function replaceState (url: string) { pushState(url, true) }
JavaScript
0.998896
@@ -3739,26 +3739,26 @@ ? ' -assign' : 'replace +replace' : 'assign '%5D(u
f997ce72b7dca69cc2d40fa3ba0937c46536eeb3
make config optional
bin/tail.js
bin/tail.js
#!/usr/bin/env node /** * Copyright 2014 Netsend. * * This file is part of Mastersync. * * Mastersync is free software: you can redistribute it and/or modify it under the * terms of the GNU Affero General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * Mastersync is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along * with Mastersync. If not, see <https://www.gnu.org/licenses/>. */ 'use strict'; var _db = require('./_db'); var program = require('commander'); var properties = require('properties'); var fs = require('fs'); program .version('0.1.0') .usage('[-g] -c collection -f config') .description('tail the given collection') .option('-d, --database <database>', 'name of the database') .option('-c, --collection <collection>', 'name of the collection') .option('-f, --config <config>', 'an ini config file') .option('-o, --oplog', 'shortcut for "-d local -c oplog.$main"') .option('-n, --number <number>', 'the number of last items to show, defaults to 10') .option('-g, --follow', 'keep the cursor open (only on capped collections)') .parse(process.argv); if (!program.config) { program.help(); } if (!program.collection) { program.help(); } var config = program.config; var collection = program.collection; // if relative, prepend current working dir if (config[0] !== '/') { config = process.cwd() + '/' + config; } config = properties.parse(fs.readFileSync(config, { encoding: 'utf8' }), { sections: true, namespaces: true }); program.number = program.number || 10; if (program.oplog) { config.database.name = 'local'; collection = 'oplog.$main'; } function tail(db) { var coll = db.db(config.database.name || 'local').collection(collection); // start at the end coll.count(function(err, counter) { if (err) { console.error(err); process.exit(1); } console.log('offset', counter); var opts = { skip: counter - program.number }; if (program.follow) { opts.tailable = true; } var stream = coll.find({}, opts).stream(); // if tailable, skip won't work so do this manually if (opts.tailable) { console.log('seeking...'); var i = 0; var offsetReached; stream.on('data', function(item) { if (!offsetReached) { i++; if (i <= opts.skip) { return; } offsetReached = true; } console.log(JSON.stringify(item)); }); } else { stream.on('data', function(item) { console.log(JSON.stringify(item)); }); } stream.on('error', function() { process.exit(1); }); stream.on('close', function() { process.exit(); }); }); } var database = config.database; var dbCfg = { dbName: database.name || 'local', dbHost: database.path || database.host, dbPort: database.port, dbUser: database.user, dbPass: database.pass, authDb: database.authDb }; // open database _db(dbCfg, function(err, db) { if (err) { throw err; } tail(db); });
JavaScript
0.000007
@@ -936,16 +936,28 @@ ge('%5B-g%5D + %5B-f config%5D -c coll @@ -966,18 +966,8 @@ tion - -f config ')%0A @@ -1177,19 +1177,16 @@ fig%3E', ' -an ini conf @@ -1457,54 +1457,85 @@ );%0A%0A -if (!program.config) %7B program.help(); %7D%0Aif (! +var config = %7B%7D;%0Avar dbCfg = %7B dbName: program.database %7D;%0A%0Avar collection = prog @@ -1552,20 +1552,23 @@ tion -) %7B +;%0A%0Aif ( program. help @@ -1567,130 +1567,171 @@ ram. -help(); %7D%0A%0Avar config = program.config;%0Avar collection = program.collection;%0A%0A// if relative, prepend current working dir%0A +oplog) %7B%0A dbCfg.dbName = 'local';%0A collection = 'oplog.$main';%0A%7D%0A%0A// if relative, prepend current working dir%0Aif (program.config) %7B%0A config = program.config;%0A if ( @@ -1747,24 +1747,26 @@ !== '/') %7B%0A + config = p @@ -1794,19 +1794,23 @@ config;%0A + %7D%0A%0A + config = @@ -1918,134 +1918,347 @@ );%0A%0A -program.number = program.number %7C%7C 10;%0A%0Aif (program.oplog) %7B%0A config.database.name = 'local';%0A collection = 'oplog.$main';%0A%7D + if (config.database) %7B%0A dbCfg.dbHost = config.database.path %7C%7C config.database.host;%0A dbCfg.dbPort = config.database.port;%0A dbCfg.dbUser = config.database.user;%0A dbCfg.dbPass = config.database.pass;%0A dbCfg.authDb = config.database.authDb;%0A %7D%0A%7D%0A%0Aif (!collection) %7B program.help(); %7D%0A%0Aprogram.number = program.number %7C%7C 10; %0A%0Afu @@ -2298,25 +2298,17 @@ .db( -config.database.n +dbCfg.dbN ame @@ -3302,237 +3302,8 @@ %0A%7D%0A%0A -var database = config.database;%0Avar dbCfg = %7B%0A dbName: database.name %7C%7C 'local',%0A dbHost: database.path %7C%7C database.host,%0A dbPort: database.port,%0A dbUser: database.user,%0A dbPass: database.pass,%0A authDb: database.authDb%0A%7D;%0A%0A // o
ae72994cfb8ab915ae23df107ae7845c3b584798
Undo changes on ./bin/test.js
bin/test.js
bin/test.js
/** * Copyright (c) 2019 The xterm.js authors. All rights reserved. * @license MIT */ const cp = require('child_process'); const path = require('path'); const COVERAGE_LINES_THRESHOLD = 60; // Add `out` to the NODE_PATH so absolute paths can be resolved. const env = { ...process.env }; env.NODE_PATH = path.resolve(__dirname, '../out'); let testFiles = [ './out/*test.js', './out/**/*test.js', './addons/**/out/*test.js', ]; let flagArgs = []; if (process.argv.length > 2) { const args = process.argv.slice(2); flagArgs = args.filter(e => e.startsWith('--')); // ability to inject particular test files via // yarn test [testFileA testFileB ...] files = args.filter(e => !e.startsWith('--')); if (files.length) { testFiles = files; } } const checkCoverage = flagArgs.indexOf('--coverage') >= 0; if (checkCoverage) { flagArgs.splice(flagArgs.indexOf('--coverage'), 1); const executable = npmBinScript('nyc'); const args = ['--check-coverage', `--lines=${COVERAGE_LINES_THRESHOLD}`, npmBinScript('mocha'), ...testFiles, ...flagArgs]; console.info('executable', executable); console.info('args', args); const run = cp.spawnSync( executable, args, { cwd: path.resolve(__dirname, '..'), env, stdio: 'inherit' } ); process.exit(run.status); } const checkDebug = flagArgs.indexOf('--debug') >= 0; if (checkDebug) { env.DEBUG = 'debug'; } if (env.DEBUG) { console.log('poll result', result); } const run = cp.spawnSync( npmBinScript('mocha'), [...testFiles, ...flagArgs], { cwd: path.resolve(__dirname, '..'), env, stdio: 'inherit' } ); function npmBinScript(script) { return path.resolve(__dirname, `../node_modules/.bin/` + (process.platform === 'win32' ? `${script}.cmd` : script)); } process.exit(run.status);
JavaScript
0.000001
@@ -1321,164 +1321,8 @@ %0A%7D%0A%0A -const checkDebug = flagArgs.indexOf('--debug') %3E= 0;%0A%0Aif (checkDebug) %7B%0A env.DEBUG = 'debug';%0A%7D%0A%0Aif (env.DEBUG) %7B%0A console.log('poll result', result);%0A%7D%0A%0A cons
6dd16e5cc453aead4ce8b97a0b3ee9f39df8af6a
Add alternative to fs.existsSync
bindings.js
bindings.js
/** * Module dependencies. */ var fs = require('fs') , path = require('path') , join = path.join , dirname = path.dirname , exists = fs.existsSync || path.existsSync , defaults = { arrow: process.env.NODE_BINDINGS_ARROW || ' → ' , compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled' , platform: process.platform , arch: process.arch , version: process.versions.node , bindings: 'bindings.node' , try: [ // node-gyp's linked version in the "build" dir [ 'module_root', 'build', 'bindings' ] // node-waf and gyp_addon (a.k.a node-gyp) , [ 'module_root', 'build', 'Debug', 'bindings' ] , [ 'module_root', 'build', 'Release', 'bindings' ] // Debug files, for development (legacy behavior, remove for node v0.9) , [ 'module_root', 'out', 'Debug', 'bindings' ] , [ 'module_root', 'Debug', 'bindings' ] // Release files, but manually compiled (legacy behavior, remove for node v0.9) , [ 'module_root', 'out', 'Release', 'bindings' ] , [ 'module_root', 'Release', 'bindings' ] // Legacy from node-waf, node <= 0.4.x , [ 'module_root', 'build', 'default', 'bindings' ] // Production "Release" buildtype binary (meh...) , [ 'module_root', 'compiled', 'version', 'platform', 'arch', 'bindings' ] ] } /** * The main `bindings()` function loads the compiled bindings for a given module. * It uses V8's Error API to determine the parent filename that this function is * being invoked from, which is then used to find the root directory. */ function bindings (opts) { // Argument surgery if (typeof opts == 'string') { opts = { bindings: opts } } else if (!opts) { opts = {} } opts.__proto__ = defaults // Get the module root if (!opts.module_root) { opts.module_root = exports.getRoot(exports.getFileName()) } // Ensure the given bindings name ends with .node if (path.extname(opts.bindings) != '.node') { opts.bindings += '.node' } var tries = [] , i = 0 , l = opts.try.length , n , b , err for (; i<l; i++) { n = join.apply(null, opts.try[i].map(function (p) { return opts[p] || p })) tries.push(n) try { b = opts.path ? require.resolve(n) : require(n) if (!opts.path) { b.path = n } return b } catch (e) { if (!/not find/i.test(e.message)) { throw e } } } err = new Error('Could not locate the bindings file. Tried:\n' + tries.map(function (a) { return opts.arrow + a }).join('\n')) err.tries = tries throw err } module.exports = exports = bindings /** * Gets the filename of the JavaScript file that invokes this function. * Used to help find the root directory of a module. * Optionally accepts an filename argument to skip when searching for the invoking filename */ exports.getFileName = function getFileName (calling_file) { var origPST = Error.prepareStackTrace , origSTL = Error.stackTraceLimit , dummy = {} , fileName Error.stackTraceLimit = 10 Error.prepareStackTrace = function (e, st) { for (var i=0, l=st.length; i<l; i++) { fileName = st[i].getFileName() if (fileName !== __filename) { if (calling_file) { if (fileName !== calling_file) { return } } else { return } } } } // run the 'prepareStackTrace' function above Error.captureStackTrace(dummy) dummy.stack // cleanup Error.prepareStackTrace = origPST Error.stackTraceLimit = origSTL return fileName } /** * Gets the root directory of a module, given an arbitrary filename * somewhere in the module tree. The "root directory" is the directory * containing the `package.json` file. * * In: /home/nate/node-native-module/lib/index.js * Out: /home/nate/node-native-module */ exports.getRoot = function getRoot (file) { var dir = dirname(file) , prev while (true) { if (dir === '.') { // Avoids an infinite loop in rare cases, like the REPL dir = process.cwd() } if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) { // Found the 'package.json' file or 'node_modules' dir; we're done return dir } if (prev === dir) { // Got to the top throw new Error('Could not find module root given file: "' + file + '". Do you have a `package.json` file? ') } // Try the parent dir next prev = dir dir = join(dir, '..') } }
JavaScript
0
@@ -137,16 +137,135 @@ exists = + ((fs.accessSync && function (path) %7B try %7B fs.accessSync(path); %7D catch (e) %7B return false; %7D return true; %7D)%0A %7C%7C fs.exis @@ -289,16 +289,17 @@ istsSync +) %0A , def
112a8bee00e8b11b1facaf9499976ab4f92bd185
add fcm push
src/web/main.js
src/web/main.js
"use strict"; const _ = require("ramda") require("./pcss/main.pcss") const DB = require("./local-pouch-db") const sound = require("./sound") const $ = require("jquery") window.jQuery = $ require("./jquery.trap") require("jquery-ui/ui/position") boot().catch(console.error) async function boot() { $("#root").trap(); let syncList = [] const dbMap = { "todo-db": await DB("todo-db"), "project-db": await DB("project-db"), "context-db": await DB("context-db") } // _.mapObjIndexed(db=>db.startRemoteSync(), dbMap) const todos = await dbMap["todo-db"].find({selector: {"_id": {"$ne": null}}}) const projects = await dbMap["project-db"].find({selector: {"_id": {"$ne": null}}}) const contexts = await dbMap["context-db"].find({selector: {"_id": {"$ne": null}}}) const flags = { now: Date.now(), encodedTodoList: todos, encodedProjectList: projects, encodedContextList: contexts, pouchDBRemoteSyncURI: localStorage.getItem("pouchdb.remote-sync-uri") || "" } const Elm = require("elm/Main.elm") const app = Elm["Main"] .embed(document.getElementById("elm-app-container"), flags) app.ports["syncWithRemotePouch"].subscribe(async (uri) => { localStorage.setItem("pouchdb.remote-sync-uri", uri) await Promise.all(_.map(sync => sync.cancel())(syncList)) syncList = _.compose(_.map(db => db.startRemoteSync(uri, "sgtd2-")), _.values)(dbMap) }) app.ports["pouchDBUpsert"].subscribe(async ([dbName, id, doc]) => { // console.log("upserting", dbName, doc, id) const upsertResult = await dbMap[dbName].upsert(id, doc) if (_.F()) { console.log("upsertResult", upsertResult) } }); setupNotifications(app) .catch(console.error) app.ports["focusSelector"].subscribe((selector) => { setTimeout(() => { requestAnimationFrame(() => { $(selector).focus() }) }, 0) }) app.ports["login"].subscribe(()=>{ const intervalId = setInterval(()=>{ let googleAuth = document.getElementById('google-auth'); if(!googleAuth) return googleAuth .signInWithRedirect() .then(console.info) .catch(console.error) clearTimeout(intervalId); },500) }) app.ports["focusPaperInput"].subscribe((selector) => { setTimeout(() => { requestAnimationFrame(() => { const toFocus = document.querySelector(selector) // console.log("toFocus", toFocus, document.activeElement) if (toFocus && document.activeElement !== toFocus) { toFocus.focus() } else { // console.log("not focusing") } if (toFocus) { // console.log(toFocus.inputElement, toFocus.$.input) toFocus.inputElement.focus() // toFocus.$.input.focus() } }) }, 0) }) app.ports["startAlarm"].subscribe(() => { sound.start() }) app.ports["stopAlarm"].subscribe(() => { sound.stop() }) } /* //noinspection JSUnresolvedVariable if (!WEB_PACK_DEV_SERVER && 'serviceWorker' in navigator) { //noinspection JSUnresolvedVariable navigator.serviceWorker.register('/service-worker.js'); } */
JavaScript
0.000001
@@ -3300,19 +3300,16 @@ %7D)%0A%7D%0A%0A -%0A%0A%0A /*%0A //no
cd9ea583b3ff201f936c5b967ec59398871a84c3
Change size of products image
database.js
database.js
const PouchDB = require('pouchdb'); const Product = require('./models/product.js'); const User = require('./models/user.js'); const Faker = require('faker'); const Constants = require('./constants.js'); // let database = new PouchDB('market'); module.exports = class Database { constructor() { this.database = new PouchDB('market'); } /** * Fill the database with some mock data */ fillDatabaseWithMockData(howManyProduct) { this.hasDatabase(); var i = 0; for(i; i < howManyProduct; i++) { let fakeUser = Faker.helpers.userCard(); fakeUser.avatar = Faker.internet.avatar(50, 50); delete fakeUser.website; delete fakeUser.company; this.add( Constants.typeProduct, new Product( this.generateUniqueID(Constants.typeProduct), Faker.commerce.product(), Faker.lorem.sentence(20), Faker.commerce.price(), Faker.commerce.color(), Faker.commerce.department(), Faker.commerce.productMaterial(), Faker.image.food(50, 50), Faker.image.food(300, 200) ) ); this.add( Constants.typeUser, new User( this.generateUniqueID(Constants.typeUser), fakeUser.username, fakeUser.name, fakeUser.email, fakeUser.address, fakeUser.phone, fakeUser.avatar ) ); } } /** * Generate unique ID */ generateUniqueID(type) { return type + '/' + Math.random().toString(36).substr(2, 9); } /** * Delete database * Call this function is you want to reset all data */ deleteMockData() { return this.database.destroy().then((response) => { if (response.ok) { this.database = null; console.log('*************************************'); console.log('* Database successfully destroyed ! *'); console.log('*************************************'); return Promise.resolve(response); } }).catch((error) => { console.log('********************************************************'); console.log('* Error happened, the database couln\'t be destroyed ! *'); console.log('********************************************************'); }); } /** * Add product into database * @param {string} type Type of doc products/users * @param {object} obj Object to add */ add(type, obj) { this.hasDatabase(); return this.database.put(obj).then((result) => { if (result.ok) { console.log( type + ' successfully added ! With ID : ' + result.id); return Promise.resolve(result); } }).catch((error) => { console.log('Error happened, the ' + type + ' couln\'t be added !', error); return Promise.reject({ success: false, message: 'Error happened, the ' + type + ' couln\'t be added !', error: error }); }); } /** * Update product into database * @param {string} type Type of doc product or user * @param {object} object Contain the new value of the product/user */ update(type, obj) { this.hasDatabase(); let insert = {}; if (type === Constants.typeUser) { insert = { _id: obj._id, _rev: obj._rev, username: obj.username, name: obj.name, email: obj.email, address: obj.address, phone: obj.phone, avatar: obj.avatar }; } if (type === Constants.typeProduct) { insert = { _id: obj._id, _rev: obj._rev, title: obj.title, description: obj.description, price: obj.price, color: obj.color, department: obj.department, material: obj.material, thumb: obj.thumb, image: obj.image }; } return this.database.put(insert).then((result) => { if (result.ok) { console.log(type + ' successfully updated !', result); return Promise.resolve(result); } }).catch((error) => { console.log('Error happened, ' + type + ' couln\'t be updated !', error); return Promise.reject({ success: false, message: 'Error happened, ' + type + ' couln\'t be updated !', error: error }); }); } /** * Delete a product into the database * @param {string} type Type of doc products/users * @param {string} id Doc ID */ delete(type, id) { this.hasDatabase(); return this.database.get(id).then((doc) => { return this.database.remove(doc); }).then((result) => { if (result.ok) { console.log(type + ' successfully deleted !', result); return Promise.resolve(result); } }).catch((error) => { console.log('Error happened, ' + type + ' couln\'t be deleted !', error); return Promise.reject({ success: false, message: 'Error happened, ' + type + ' couln\'t be deleted !', error: error }); }); } /** * Fetch a product from the database * @param {string} type Type of doc products/users * @param {string} id Doc ID */ get(type, id) { this.hasDatabase(); return this.database.get(id).then((doc) => { if (doc) { console.log(type + ' successfully fetched !', doc); return Promise.resolve(doc); } }).catch((error) => { console.log('Error happened, ' + type + ' couln\'t be fetched !', error); return Promise.reject({ success: false, message: 'Error happened, ' + type + ' couln\'t be fetched !', error: error }); }); } /** * Fetch all doc from the database by type */ getAll(type) { this.hasDatabase(); return this.database.allDocs({ include_docs: true, startkey: type, endkey: type + '\uffff' }).then((result) => { console.log(type + ' successfully fetched !', result); let data = []; for (var i in result.rows) { data.push(result.rows[i].doc); } return new Promise((resolve, reject) => { resolve(data); }); }).catch((error) => { console.log('Error happened, ' + type + ' couln\'t be fetched !', error); return Promise.reject(error); }); } /** * Check if the database is created */ hasDatabase() { if (this.database === null) { this.database = new PouchDB('market'); } } }
JavaScript
0.000002
@@ -1211,21 +1211,23 @@ ge.food( -50, 5 +200, 10 0),%0A @@ -1263,14 +1263,14 @@ ood( -3 +8 00, -2 +4 00)%0A
24495ee6098a3d3f35b5e9c30b3f55e39295b024
remove erroneous args=null
src/main/js/ephox/katamari/api/Throttler.js
src/main/js/ephox/katamari/api/Throttler.js
define( 'ephox.katamari.api.Throttler', [ 'global!clearTimeout', 'global!setTimeout' ], function (clearTimeout, setTimeout) { // Run a function fn afer rate ms. If another invocation occurs // during the time it is waiting, update the arguments f will run // with (but keep the current schedule) var adaptable = function (fn, rate) { var timer = null; var args = null; var cancel = function() { if (timer !== null) { clearTimeout(timer); timer = null; args = null; } }; var throttle = function () { args = arguments; if (timer === null) { timer = setTimeout(function () { fn.apply(null, args); timer = null; args = null; }, rate); } }; return { cancel: cancel, throttle: throttle }; }; // Run a function fn after rate ms. If another invocation occurs // during the time it is waiting, ignore it completely. var first = function (fn, rate) { var timer = null; var cancel = function() { if (timer !== null) { clearTimeout(timer); timer = null; args = null; } }; var throttle = function () { var args = arguments; if (timer === null) { timer = setTimeout(function () { fn.apply(null, args); timer = null; args = null; }, rate); } }; return { cancel: cancel, throttle: throttle }; }; // Run a function fn after rate ms. If another invocation occurs // during the time it is waiting, reschedule the function again // with the new arguments. var last = function (fn, rate) { var timer = null; var cancel = function() { if (timer !== null) { clearTimeout(timer); timer = null; args = null; } }; var throttle = function () { var args = arguments; if (timer !== null) clearTimeout(timer); timer = setTimeout(function () { fn.apply(null, args); timer = null; args = null; }, rate); }; return { cancel: cancel, throttle: throttle }; }; return { adaptable: adaptable, first: first, last: last }; } );
JavaScript
0.999609
@@ -1217,39 +1217,16 @@ = null;%0A - args = null;%0A @@ -1928,39 +1928,16 @@ = null;%0A - args = null;%0A
3109fdbe99320421460776ea3c68f2491f02242f
Create shared AudioContext and masterGain node.
src/core/audio/AudioAPI.js
src/core/audio/AudioAPI.js
define([ "core/framework/Tundra", "core/framework/ITundraAPI", "core/asset/AssetFactory", "core/audio/asset/AudioAsset", "core/audio/entity-components/EC_Sound_WebAudio", "core/audio/entity-components/EC_SoundListener_WebAudio" ], function(Tundra, ITundraAPI, AssetFactory, AudioAsset, EC_Sound_WebAudio, EC_SoundListener_WebAudio) { var AudioAPI = ITundraAPI.$extend( { __init__ : function(name, options) { this.$super(name, options); }, __classvars__: { getDefaultOptions : function() { return { enabled : true, followActiveCamera : false }; } }, registerComponents : function() { Tundra.scene.registerComponent(EC_Sound_WebAudio); Tundra.scene.registerComponent(EC_SoundListener_WebAudio); }, registerAssetFactories : function() { Tundra.asset.registerAssetFactory(new AssetFactory("Audio", AudioAsset, { ".ogg" : "arraybuffer", ".mp3" : "arraybuffer" })); }, /// ITundraAPI override initialize : function() { this.registerAssetFactories(); this.registerComponents(); }, /// ITundraAPI override postInitialize : function() { } }); return AudioAPI; });
JavaScript
0
@@ -499,16 +499,394 @@ tions);%0A +%0A // define audio context%0A this.audioCtx = new (window.AudioContext %7C%7C window.webkitAudioContext)();%0A %0A // Master GainNode to be used as destination of other sources%0A this.masterGainNode = this.audioCtx.createGain();%0A this.masterGainNode.connect(this.audioCtx.destination);%0A this.masterGainNode.gain.value = options.masterGain;%0A%0A %7D,%0A%0A @@ -1068,16 +1068,59 @@ : false +,%0A masterGain : 0.5 %0A
2e47ac2f1b606358871959b66df9fbb6a6112f6b
Update gdpr LS namespace for OpenWrap script
src_new/gdpr.js
src_new/gdpr.js
var localStorageKey = "PubMatic"; var DUMMY_PUB_ID = 909090; // Adding util here creating cyclic dependecies between the modules so avoided it & added two util function manually function isA(object, testForType) { return toString.call(object) === "[object " + testForType + "]"; } var isFunction = function (object) { return isA(object, "Function"); }; var isLocalStoreEnabled = (function () { try { return window.localStorage && isFunction(window.localStorage.getItem) && isFunction(window.localStorage.setItem); } catch (e) { return false; } })(); /* localStorage = { localStorageKey : { pubID: { c: "encoded user consent" } } } */ var setConsentDataInLS = function (pubId, dataType, data, gdprApplies) { var pm; if (!isLocalStoreEnabled) { return; } try { pm = window.localStorage.getItem(localStorageKey); } catch (e) {} if (pm && typeof pm === "string") { try { pm = JSON.parse(pm); } catch (e) { pm = {}; } } else { pm = {}; } if (pm) { if (!pm.hasOwnProperty(pubId)) { pm[pubId] = {}; } pm[pubId].t = (new Date()).getTime(); pm[pubId][dataType] = data; if (dataType == "c") { pm[pubId]["g"] = gdprApplies ? 1 : 0; } } try { window.localStorage.setItem(localStorageKey, JSON.stringify(pm)); } catch (e) {} }; /* start-test-block */ exports.setConsentDataInLS = setConsentDataInLS; /* end-test-block */ exports.isCmpFound = function () { return !!window.__cmp; }; /** * getUserConsentDataFromCMP() method return nothing * Here, We try to call get the ConsentData for vendorConsents from CMP using getConsentData() method * Once, We get that we will this data in Local Storage againg a dummy ID * If CMP is not detected in current document we try to look into upper iframe & fetch the infoa */ exports.getUserConsentDataFromCMP = function () { // Adding dummy pubId to store data against var pubId = DUMMY_PUB_ID; //CONFIG.getPublisherId(); var callId = 0; var getConsentDataReq = { __cmp: { callId: "iframe:" + (++callId), command: "getConsentData" } }; function receiveMessage(event) { if (event && event.data && event.data.__cmp && event.data.__cmp.result) { var result = event.data.__cmp.result; if (result.consentData) { /** * CMP API 1.1 - result is object which includes * { * consentData: base64 string, * gdprApplies: boolean * } */ setConsentDataInLS(pubId, "c", result.consentData, result.gdprApplies); } else if (typeof result === "string") { // CMP API 1.0 - result is base64 consent string setConsentDataInLS(pubId, "c", result); } } } function callCMP() { window.__cmp("getConsentData", "vendorConsents", function (result) { if (result.consentData) { setConsentDataInLS(pubId, "c", result.consentData, result.gdprApplies); } else if (typeof result === "string") { setConsentDataInLS(pubId, "c", result); } }); } if (window.__cmp) { if (typeof window.__cmp === "function") { callCMP(); } else { setTimeout(function () { if (typeof window.__cmp === "function") { callCMP(); } }, 500); } } else { // we may be inside an iframe and CMP may exist outside, so we"ll use postMessage to interact with CMP window.top.postMessage(getConsentDataReq, "*"); window.addEventListener("message", receiveMessage); } }; /** * getUserConsentDataFromLS() method return the object { c: "XXX", g: 0/1 } * Here c is Consent String We got from CMP APIs * & g is gdpr flag i.e. gdprApplies in terms of CMP 1.1 API * @return {object} { c: String, g: Number 0/1 } */ exports.getUserConsentDataFromLS = function () { // Adding dummy pubId to store data against var pubId = DUMMY_PUB_ID; var data = {c: "", g: 0}; if (!isLocalStoreEnabled) { return data; } var pm; try { pm = window.localStorage.getItem(localStorageKey); } catch (e) {} if (pm && typeof pm === "string") { try { pm = JSON.parse(pm); } catch (e) { pm = {}; } if (pm.hasOwnProperty(pubId)) { var pmRecord = pm[pubId]; if (pmRecord && pmRecord.c && pmRecord.t) { // check timestamp of data and current; if older than a day do not use it if (pmRecord.t && parseInt(pmRecord.t, 10) > ((new Date()).getTime() - (24 * 60 * 60 * 1000))) { data.c = pmRecord.c; data.g = pmRecord.g; } } } } return data; };
JavaScript
0
@@ -20,16 +20,16 @@ = %22 -PubMatic +OpenWrap %22;%0Av
d0b9574d4c90d51b8808217cc48bcb0c2ea16a97
Tidy `t/coverage/balancer-cached-right.t.js`.
t/coverage/balancer-cached-right.t.js
t/coverage/balancer-cached-right.t.js
#!/usr/bin/env node require('./proof')(2, function (step, Strata, tmp, load, serialize, objectify, gather, assert) { var strata = new Strata({ directory: tmp, leafSize: 3, branchSize: 3 }) step(function () { serialize(__dirname + '/fixtures/balancer-cached-right.json', tmp, step()) }, function () { strata.open(step()) }, function () { strata.mutator('e', step()) }, function (cursor) { step(function () { cursor.insert('e', 'e', ~ cursor.index, step()) }, function () { cursor.unlock() }) }, function () { strata.mutator('a', step()) }, function (cursor) { step(function () { cursor.remove(cursor.index, step()) }, function () { cursor.unlock() }) }, function () { gather(step, strata) }, function (records) { assert(records, [ 'b', 'c', 'd', 'e' ], 'records') strata.balance(step()) }, function () { gather(step, strata) }, function (records) { assert(records, [ 'b', 'c', 'd', 'e' ], 'merged') }, function() { strata.close(step()) }) })
JavaScript
0
@@ -68,14 +68,8 @@ tmp, - load, ser @@ -79,19 +79,8 @@ ize, - objectify, gat
f9be675ac9f2524b75f7e8502554e078d9aa8f54
make builder faster, change priorities to match strength of economy.
stage.stable.js
stage.stable.js
var work = [WORK, WORK, WORK, WORK, WORK, MOVE, MOVE, MOVE, MOVE, CARRY]; var heavy = [WORK, MOVE, WORK, MOVE, WORK, MOVE, WORK, WORK, WORK, WORK, WORK, CARRY]; var extract = [MOVE, WORK, WORK, WORK, WORK, WORK, CARRY]; var logistic = [CARRY, MOVE, CARRY, MOVE, CARRY, MOVE, CARRY, MOVE, CARRY, MOVE, CARRY, MOVE, CARRY, MOVE, CARRY, MOVE, CARRY]; var defend = [MOVE, MOVE, ATTACK, ATTACK, ATTACK, ATTACK]; var scout = [MOVE]; var raider = [MOVE, ATTACK]; module.exports = { desiredHarvesters: 0, desiredFatHarvesters: 2, desiredFatUpgraders: 1, desiredUpgraders: 0, desiredBuilders: 0, desiredSherpas: 3, desiredDefenders: 0, desiredScouts: 0, desiredRaiders: 0, harvester: work, scout: scout, raider: raider, fatHarvester: extract, fatUpgrader: heavy, upgrader: work, defender: defend, builder: work, sherpa: logistic, hitsWall: 250000, hitsRampart: 250000, name:'stable' };
JavaScript
0
@@ -63,24 +63,101 @@ VE, CARRY%5D;%0A +var build = %5BWORK, MOVE, WORK, MOVE, WORK, MOVE, CARRY, MOVE, CARRY, MOVE,%5D;%0A var heavy = @@ -227,24 +227,24 @@ RK, CARRY%5D;%0A - var extract @@ -496,16 +496,40 @@ %5BMOVE%5D; + // , CLAIM, MOVE, CLAIM %0Avar rai @@ -694,25 +694,25 @@ edBuilders: -0 +1 ,%0A desire @@ -725,9 +725,9 @@ as: -3 +4 ,%0A @@ -955,28 +955,29 @@ builder: -work +build ,%0A sherpa
eb0bbc83c594c7088e2925a91addd1090270c53b
Add export to convertToList
src/helpers/reformat.js
src/helpers/reformat.js
import flatten from 'flat'; export function reformatColumns(items) { const flatList = items.map((item) => flatten(item, { maxDepth: 2 })); const reformattedList = rotateOnTeam(flatList); // const itemsByFeature = groupByFeature(reformattedList); const concatObj = concatOnProperties(reformattedList); const concatList = convertToList(concatObj); return concatList; } function rotateOnTeam(list) { // convert columns const rotatedList = list.map((item) => ({ ...item, // Put the hours in the right column [item['budgetHours.column']]: item['budgetHours.value'], })); return rotatedList; } // function groupByFeature(reformattedList) { // const itemsByFeature = reformattedList.reduce((features, item) => { // features[item.feature] = [ // ...features[item.feature] || [], // item, // ]; // return features; // }, {}); // return itemsByFeature; // } function concatOnProperties(list) { let concatObj = {}; // combine on feature list.map((item) => { // Feature isn't already in the object if (typeof concatObj[item.feature] === 'undefined') { concatObj[item.feature] = item; } else { // Add to existing feature for (const property in item) { if(Array.isArray(item[property])) { concatObj[item.feature][property] = [ ...concatObj[item.feature][property], ...item[property], ]; } else if(typeof item[property] === 'number') { // Sum the numbers concatObj[item.feature][property] = concatObj[item.feature][property] + item[property] || item[property]; } } } return item; }); return concatObj; } // convert concatObj from properties to array elements function convertToList(object) { let list = []; for (const element in object) { if(object.hasOwnProperty(element)) { list = [...list, object[element]]; } } return list; }
JavaScript
0
@@ -1710,16 +1710,23 @@ lements%0A +export function
84b5b9ca2ee77a04bdd8c089850cd8ac18d05f65
Add platform detection
src/js/javascript.js
src/js/javascript.js
// Initial timer length in seconds var timerCount = 15, remote = require('electron').remote, arguments = remote.getGlobal('sharedObject').prop1; // debug mode ensures that computer doesnt shut down while testing // npm start --debug if (arguments[2] == '--debug') { console.log('Debug mode enabled'); var debug = true; } // Timer constructor var TimerFunc = function() { window.onload = function() { this.timerID = document.getElementById('timer'); // Disply initial timer length, currently in seconds this.timerID.innerHTML = timerCount; if (debug) { document.getElementById('titleHeader').innerHTML += '**DEBUG**'; }; }; }; // Function to start countdown, decrements timerCount in seconds TimerFunc.prototype.startTimer = function() { var self = this; if (timerCount > 0) { self.countdown = window.setInterval(function() { timerCount--; this.timerID.innerHTML = timerCount; if (timerCount <= 0) { self.endTimer(); shutdown(); } }, 1000); }; }; // Function to manually stop timer from counting TimerFunc.prototype.endTimer = function() { clearInterval(this.countdown); }; var timer = new TimerFunc(); function shutdown() { if (debug) { alert('Debug: Shutting it down!'); } else { var exec = require('child-process').exec; var cmd = 'shutdown -t 15 -s'; exec(cmd, function(error, stdout, stderr) {}); }; };
JavaScript
0
@@ -1287,16 +1287,49 @@ else %7B%0A + var plat = process.platform;%0A var @@ -1385,26 +1385,206 @@ = ' -shutdown -t 15 -s' +';%0A if (plat === 'win32') %7B%0A cmd = 'shutdown -t 15 -s';%0A %7D else if (plat === 'darwin') %7B%0A cmd = '';//OSX shutdown command;%0A %7D else %7B%0A cmd = '';//linux shutdown command;%0A %7D ;%0A%0A
275dc5b09b27d5441814aa423cddaa7472344dbf
Add use of navigation focus custom hook in usePopOver hook
src/hooks/usePopover.js
src/hooks/usePopover.js
import React, { useState, useCallback, useRef } from 'react'; /** * Hook which manages popover position over a DOM element. * Pass a ref created by React.createRef. Receive callbacks, */ export const usePopover = () => { const [visibilityState, setVisibilityState] = useState(false); const ref = useRef(React.createRef()); const showPopover = useCallback(() => setVisibilityState(true), []); const closePopover = useCallback(() => setVisibilityState(false), []); return [ref, visibilityState, showPopover, closePopover]; };
JavaScript
0
@@ -54,16 +54,75 @@ 'react'; +%0Aimport %7B useNavigationFocus %7D from './useNavigationFocus'; %0A%0A/**%0A * @@ -269,18 +269,26 @@ pover = -() +navigation =%3E %7B%0A @@ -463,16 +463,16 @@ ), %5B%5D);%0A - const @@ -537,16 +537,71 @@ , %5B%5D);%0A%0A + useNavigationFocus(navigation, null, closePopover);%0A%0A return
7a4c6c35ae543dc43ba6766f3a0a4c4db4c88938
convert text to string in tag-translator
lib/components/helpers/tag-translator.js
lib/components/helpers/tag-translator.js
'use strict'; function buildChoicesMap(replaceChoices) { var choices = {}; replaceChoices.forEach(function (choice) { var key = choice.value; choices[key] = choice.label; }); return choices; } /* Creates helper to translate between tags like {{firstName}} and an encoded representation suitable for use in CodeMirror. */ function TagTranslator(replaceChoices, humanize) { // Map of tag to label 'firstName' --> 'First Name' var choices = buildChoicesMap(replaceChoices); return { /* Get label for tag. For example 'firstName' becomes 'First Name'. Returns a humanized version of the tag if we don't have a label for the tag. */ getLabel: function (tag) { var label = choices[tag]; if (!label) { // If tag not found and we have a humanize function, humanize the tag. // Otherwise just return the tag. label = humanize && humanize(tag) || tag; } return label; }, tokenize: function (text) { if (typeof text !== 'string') { return []; } var regexp = /(\{\{|\}\})/; var parts = text.split(regexp); var tokens = []; var inTag = false; parts.forEach(function (part) { if (part === '{{') { inTag = true; } else if (part === '}}') { inTag = false; } else if (inTag) { tokens.push({type: 'tag', value: part}); } else { tokens.push({type: 'string', value: part}); } }); return tokens; }, getTagPositions: function (text) { var lines = text.split('\n'); var re = /\{\{.+?\}\}/g; var positions = []; var m; for(var i = 0; i < lines.length; i++) { while ((m = re.exec(lines[i])) !== null) { var tag = m[0].substring(2, m[0].length-2); positions.push({ line: i, start: m.index, stop: m.index + m[0].length, tag: tag }); } } return positions; } }; } module.exports = TagTranslator;
JavaScript
0.999999
@@ -1009,66 +1009,28 @@ -if (typeof text !== 'string') %7B%0A return %5B%5D;%0A %7D +text = String(text); %0A%0A
70ab749b96524f5410d2439c00c4bd7b44d599b2
Update erb.js to mark @kassio as a contributor to the language.
src/languages/erb.js
src/languages/erb.js
/* Language: ERB (Embedded Ruby) Requires: xml.js, ruby.js Authors: Lucas Mazza <lucastmazza@gmail.com> Kassio Borges <kassioborgesm@gmail.com> */ function(hljs) { return { aliases: ['erb'], case_insensitive: true, subLanguage: 'xml', subLanguageMode: 'continuous', contains: [ { relevance: 10, begin: '<%[%#=-]?', end: '[%-]?%>', subLanguage: 'ruby', excludeBegin: true, excludeEnd: true } ] }; }
JavaScript
0
@@ -61,17 +61,16 @@ %0A Author -s : Lucas @@ -99,25 +99,29 @@ il.com%3E%0A - +Contributors: Kassio
73e5ad6a12161609952ebba43c5ffcf1bbdc9561
Update recommended r5 version to v4.7.0
lib/modules/r5-version/constants.js
lib/modules/r5-version/constants.js
// // Bucket where R5 JARs are to be found export const R5_BUCKET = 'https://r5-builds.s3.amazonaws.com' // Recommended r5 version export const RECOMMENDED_R5_VERSION = 'v4.6.1' // R5 v4 has numerous breaking changes in worker/broker communication export const MINIMUM_R5_VERSION = 'v4.0.0' // Determine if a particular version is a release version export const RELEASE_VERSION_REGEX = /^v[0-9]+\.[0-9]+\.[0-9]+$/ // Parse a version into its constituent pieces (major, minor, patch, distance from last release, commit) export const VERSION_PARSE_REGEX = /^v([0-9]+).([0-9]+).([0-9]+)-?([0-9]+)?-?(.*)?$/
JavaScript
0
@@ -172,11 +172,11 @@ 'v4. -6.1 +7.0 '%0A%0A/
fac5fbafe825da300e2f8240455c5cfd1119c527
Update payment token logic
packages/components/containers/payments/paymentTokenHelper.js
packages/components/containers/payments/paymentTokenHelper.js
import { PAYMENT_METHOD_TYPES, PAYMENT_TOKEN_STATUS } from 'proton-shared/lib/constants'; import { createToken, getTokenStatus } from 'proton-shared/lib/api/payments'; import { wait } from 'proton-shared/lib/helpers/promise'; import { c } from 'ttag'; const { STATUS_PENDING, STATUS_CHARGEABLE, STATUS_FAILED, STATUS_CONSUMED, STATUS_NOT_SUPPORTED } = PAYMENT_TOKEN_STATUS; const { CARD, PAYPAL } = PAYMENT_METHOD_TYPES; const DELAY_PULLING = 5000; const DELAY_LISTENING = 1000; const pull = async ({ timer = 0, Token, api }) => { if (timer > DELAY_PULLING * 30) { throw new Error(c('Error').t`Payment process cancelled`); } const { Status } = await api(getTokenStatus(Token)); if (Status === STATUS_FAILED) { throw new Error(c('Error').t`Payment process failed`); } if (Status === STATUS_CONSUMED) { throw new Error(c('Error').t`Payment process consumed`); } if (Status === STATUS_NOT_SUPPORTED) { throw new Error(c('Error').t`Payment process not supported`); } if (Status === STATUS_CHARGEABLE) { return; } if (Status === STATUS_PENDING) { await wait(DELAY_PULLING); return pull({ Token, api, timer: timer + DELAY_PULLING }); } throw new Error(c('Error').t`Unknown payment token status`); }; /** * * @param {String} ApprovalURL * @param {String} String * @param {Object} api useApi * @param {Object} tab window instance */ const process = ({ ApprovalURL, Token, api, tab }) => { return new Promise((resolve, reject) => { let listen = false; const reset = () => { listen = false; window.removeEventListener('message', onMessage, false); tab.close(); }; const listenTab = async () => { if (!listen) { return; } if (tab.closed) { reject(new Error(c('Error').t`Tab closed`)); } await wait(DELAY_LISTENING); return listenTab(tab); }; const onMessage = (event) => { const origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object. if (origin !== 'https://secure.protonmail.com') { return; } if (event.source !== tab) { return; } reset(); const { cancel } = event.data; if (cancel === '1') { return reject(); } pull({ Token, api }) .then(resolve) .catch(reject); }; tab.location = ApprovalURL; window.addEventListener('message', onMessage, false); listen = true; listenTab(); }); }; const toParams = (params, Token) => { return { ...params, Payment: { Type: 'token', Details: { Token } } }; }; export const handle3DS = async (params = {}, api) => { const { Payment = {} } = params; const { Type } = Payment; if (![CARD, PAYPAL].includes(Type)) { return params; } // We open a tab first because Safari is blocking by default tab if it's not a direct interaction const tab = window.open(''); // It's important to keep it before await try { const { Token, Status, ApprovalURL } = await api(createToken(params)); if (Status === STATUS_CHARGEABLE) { tab.close(); return toParams(params, Token); } await process({ ApprovalURL, Token, api, tab }); return toParams(params, Token); } catch (error) { tab.close(); throw error; } };
JavaScript
0
@@ -157,24 +157,86 @@ /payments';%0A +import %7B isSafari %7D from 'proton-shared/lib/helpers/browser';%0A import %7B wai @@ -459,28 +459,29 @@ const %7B -CARD, PAYPAL +BITCOIN, CASH %7D = PAY @@ -2758,35 +2758,137 @@ -tab.location = ApprovalURL; +if (isSafari()) %7B%0A tab.location = ApprovalURL;%0A %7D else %7B%0A tab = window.open(ApprovalURL);%0A %7D%0A %0A @@ -3249,24 +3249,37 @@ , api) =%3E %7B%0A + let tab;%0A const %7B @@ -3346,22 +3346,22 @@ if ( -! %5BCA -RD, PAYPAL +SH, BITCOIN %5D.in @@ -3402,24 +3402,50 @@ ams;%0A %7D%0A%0A + if (isSafari()) %7B%0A // We op @@ -3538,21 +3538,19 @@ ion%0A -const + tab = w @@ -3568,50 +3568,14 @@ ''); - // It's important to keep it before await +%0A %7D %0A%0A @@ -3709,32 +3709,39 @@ E) %7B%0A + tab && tab.close();%0A @@ -3916,24 +3916,31 @@ r) %7B%0A + tab && tab.close()
7bb62e8fef54023368cd82614055966c0dda6270
add an assertion to ExecutionContext test
packages/execution-context/__tests__/ExecutionContext-test.js
packages/execution-context/__tests__/ExecutionContext-test.js
import ExecutionContext from '../ExecutionContext'; import ImmediateExecutor from '../ImmediateExecutor'; describe('ExecutionContext', () => { const executor = new ImmediateExecutor(); const context = new ExecutionContext(executor); it('should execute code and return the result', async () => { const value = {}; const routine = jest.fn(() => value); const result = context.execute(routine); expect(result instanceof Promise).toBeTruthy(); expect(routine).not.toHaveBeenCalled(); await Promise.resolve(); // wait for the next tick expect(routine).toHaveBeenCalled(); expect(await result).toBe(value); }); it('should execute a set of tasks asynchronously', async () => { const routineA = jest.fn(); const routineB = jest.fn(); context.execute(routineA); context.execute(routineB); expect(routineA).not.toHaveBeenCalled(); expect(routineB).not.toHaveBeenCalled(); await Promise.resolve(); // wait for the next tick expect(routineA).toHaveBeenCalled(); expect(routineB).not.toHaveBeenCalled(); await Promise.resolve(); // wait for the next tick expect(routineB).toHaveBeenCalled(); }); it('should continue executing code after a failure', async () => { const routineA = jest.fn(() => { throw new Error('Boooom') }); const routineB = jest.fn(); let failure = null; context.execute(routineA).catch(error => { failure = error; }); context.execute(routineB); await Promise.resolve(); // wait for the next tick await Promise.resolve(); // wait for the next tick, thanks catch expect(failure.message).toEqual('Boooom'); await Promise.resolve(); // wait for the next tick expect(routineB).toHaveBeenCalled(); }); it('should execute a set of tasks concurrently', async () => { const context = new ExecutionContext(executor, 2); const routineA = jest.fn(); const routineB = jest.fn(); const routineC = jest.fn(); context.execute(routineA); context.execute(routineB); context.execute(routineC); await Promise.resolve(); // wait for the next tick expect(routineA).toHaveBeenCalled(); expect(routineB).toHaveBeenCalled(); expect(routineC).not.toHaveBeenCalled(); await Promise.resolve(); // wait for the next tick expect(routineC).toHaveBeenCalled(); }); it('should execute code by request in manual mode', async () => { const context = new ExecutionContext(executor, 1, true); const routine = jest.fn(); context.execute(routine); await Promise.resolve(); // wait for the next tick expect(routine).not.toHaveBeenCalled(); const result = await context.flush(); expect(result).toBe(true); expect(routine).toHaveBeenCalled(); }); });
JavaScript
0.000001
@@ -1518,24 +1518,65 @@ e next tick%0A + expect(routineA).toHaveBeenCalled();%0A await Pr