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
d724b97c06c609befce0cca7d42a7b28d1e91c8b
remove knobbedthemeprovider props table
packages/dropdown/src/__stories__/Dropdown.stories.js
packages/dropdown/src/__stories__/Dropdown.stories.js
import { storiesOf } from "@storybook/react"; import { withInfo } from "@storybook/addon-info"; import infoOptions from "./infoOptions"; import renderStory from "./renderStory"; import stories from "./stories"; const storybook = storiesOf("Forms|Dropdown", module); stories.forEach(({ description, getProps }) => { storybook.add( description, withInfo(infoOptions)(() => { const props = getProps(); return renderStory(props); }) ); });
JavaScript
0
@@ -88,16 +88,117 @@ n-info%22; +%0Aimport KnobbedThemeProvider from %22@hig/storybook/storybook-support/decorators/KnobbedThemeProvider%22; %0A%0Aimport @@ -459,27 +459,93 @@ ithInfo( -infoOptions +%7B%0A ...infoOptions,%0A propTablesExclude: %5BKnobbedThemeProvider%5D%0A %7D )(() =%3E
dc2357bc9e088267abfdfee1c38df622440b8325
remove flexgrow from columns
packages/insights-web/src/scenes/explorer/table/index.js
packages/insights-web/src/scenes/explorer/table/index.js
import React, { Component } from 'react' import { connect } from 'kea' import { Table, Column, Cell } from 'fixed-data-table-2' import 'fixed-data-table-2/dist/fixed-data-table-base.css' import './styles.scss' import Dimensions from 'react-dimensions' import TableCell from './table-cell' import TableHeader from './table-header' import TableSettings from './table-settings' import explorerLogic from 'scenes/explorer/logic' const defaultColumnWidth = (meta) => { if (meta) { if (meta.type === 'boolean') { return 50 } else if (meta.type === 'time') { if (meta.transform) { return 75 } else { return 175 } } else if (meta.type === 'number') { return 75 } else { return 100 } } else { return 100 } } const logic = connect({ actions: [ explorerLogic, [ 'setPagination', 'setVisibleRows', 'setColumnWidth', 'setColumns', 'digDeeper', 'addFilter', 'removeFiltersByKey' ] ], props: [ explorerLogic, [ 'columns', 'columnsMeta', 'results', 'count', 'offset', 'limit', 'filter', 'columnWidths', 'scrollingResetCounter' ] ] }) class ExplorerTable extends Component { constructor (props) { super(props) this.state = { scrollToRow: null } } componentDidMount () { this.handleScrollEnd(0, 0) } componentWillUpdate (nextProps) { if (nextProps.scrollingResetCounter !== this.props.scrollingResetCounter) { this.setState({ scrollToRow: 0 }) this.updateVisibleRows(nextProps, 0) } } handleScrollEnd = (x, y) => { this.setState({ scrollToRow: null }) this.updateVisibleRows(this.props, y) } handleColumnReorder = (event) => { const { columns } = this.props const { setColumns } = this.props.actions let columnOrder = columns.filter((columnKey) => columnKey !== event.reorderColumn) if (event.columnAfter) { var index = columnOrder.indexOf(event.columnAfter) columnOrder.splice(index, 0, event.reorderColumn) } else { columnOrder.push(event.reorderColumn) } setColumns(columnOrder) } updateVisibleRows = (props, y) => { const { count } = props const { setPagination, setVisibleRows } = this.props.actions const tableHeight = this.tableHeight() if (tableHeight > 0) { const start = Math.floor(y / 30) const end = Math.floor((y + tableHeight) / 30) const pageCount = end - start if (pageCount > 0) { setVisibleRows(start + 1, Math.min(end, count)) setPagination(Math.max(start - pageCount, 0), pageCount * 3) } } } tableHeight = () => { const { containerHeight } = this.props return containerHeight - 10 } render () { const { columnWidths, columns, columnsMeta, results, count, offset, containerWidth, filter } = this.props const { setColumnWidth, digDeeper, addFilter, removeFiltersByKey } = this.props.actions const { scrollToRow } = this.state if (columns.length === 0) { return null } let i = 0 return ( <div className='results-explorer-table'> <Table rowsCount={count} rowHeight={30} headerHeight={30} width={containerWidth - 20} height={this.tableHeight()} scrollToRow={scrollToRow} isColumnResizing={false} isColumnReordering={false} onColumnResizeEndCallback={setColumnWidth} onColumnReorderEndCallback={this.handleColumnReorder} onScrollStart={this.handleScrollStart} onScrollEnd={this.handleScrollEnd} > <Column header={<Cell><TableSettings /></Cell>} cell={props => ( <Cell {...props}> <div className='cell-body'> {props.rowIndex + 1}. </div> </Cell> )} fixed width={Math.max(`${count}`.length * 10 + 18, 30)} /> {columns.map(s => [s, columnsMeta[s], i++]).map(([column, meta, i]) => { const columnFilter = filter.find(f => f.key === column) return ( <Column key={column} header={<Cell><TableHeader index={i} column={column} /></Cell>} columnKey={column} isResizable isReorderable cell={props => ( <TableCell results={results} row={props.rowIndex} index={i} offset={offset} meta={meta} column={column} columnFilter={columnFilter} addFilter={addFilter} removeFiltersByKey={removeFiltersByKey} digDeeper={digDeeper} /> )} width={columnWidths[column] || defaultColumnWidth(meta)} flexGrow={typeof columnWidths[column] === 'undefined' ? 1 : null} /> ) })} </Table> </div> ) } } export default logic(Dimensions({ elementResize: true })(ExplorerTable))
JavaScript
0.000002
@@ -525,17 +525,18 @@ return -5 +10 0%0A %7D @@ -607,26 +607,27 @@ return -75 +150 %0A %7D els @@ -649,11 +649,11 @@ urn -175 +350 %0A @@ -715,10 +715,11 @@ urn -75 +150 %0A @@ -733,33 +733,33 @@ %7B%0A return -1 +2 00%0A %7D%0A %7D els @@ -769,25 +769,25 @@ %0A return -1 +2 00%0A %7D%0A%7D%0A%0Aco @@ -4982,62 +4982,13 @@ ow=%7B -typeof columnWidths%5Bcolumn%5D === 'undefined' ? 1 : null +false %7D /%3E
10ff579f93579a63f73132e415b7235fca167e8d
Move to DMs.
server/routes/codeship.js
server/routes/codeship.js
var express = require('express'); var router = express.Router(); var request = require('request'); router.post('/', function(req, res) { if (req.query.secret !== process.env.SECRET) { res.sendStatus(404).end(); } else if (req.body.build.status !== 'testing' && req.body.build.status !== 'success') { var payload = { channel: '#hackers', username: 'Codeship', icon_emoji: ':codeship:', attachments: [{ fallback: 'Alert', color: 'danger', title: 'Build Failed', title_link: req.body.build.build_url, fields: [{ title: 'Branch', value: req.body.build.branch, short: 'true' }, { title: 'Shame upon', value: '<' + req.body.build.commit_url + '|' + req.body.build.committer + '>', short: 'true' }] }] }; request({ url: process.env.URL, method: 'POST', body: JSON.stringify(payload) }, function() { res.sendStatus(201).end(); }); } else { res.sendStatus(201).end(); } }); module.exports = router;
JavaScript
0
@@ -93,16 +93,160 @@ est');%0A%0A +var nameMap = %7B%0A alexmingoia: '@alex',%0A bradfordh: '@bradfordh',%0A jessepedler: '@jessepedler',%0A joebalancio: '@joe',%0A jontewks: '@jon'%0A%7D;%0A%0A router.p @@ -485,18 +485,41 @@ el: -'#hackers' +nameMap%5Breq.body.build.committer%5D ,%0A @@ -872,18 +872,35 @@ e: ' -Shame upon +This is the breaking commit ',%0A @@ -955,40 +955,14 @@ + '%7C -' + req.body.build.committer + ' +Commit %3E',%0A
d4ce40d86d9ca15084ad531a0cd7992f49891c45
Add comments route to examples router
server/routes/examples.js
server/routes/examples.js
'use strict'; /* global __dirname */ var express = require('express'), fs = require('fs'), path = require('path'), pd = require('pretty-data').pd, router = express.Router(); var base = path.resolve(__dirname, '../../examples/data'); function docPath(req, addPath, ending) { return base + '/' + addPath + '/' + req.params.doc + '.' + ending; } var contentTypes = { 'xml' : 'text/xml; charset=utf-8', 'json': 'application/json; charset=utf-8', 'html': 'text/html; charset=utf-8' }; function sendFile(req, res, addPath, ending) { res.header('Content-Type', contentTypes[ending]); res.sendFile(docPath(req, addPath, ending)); } function prettify(str, req) { var type = req.headers['content-type']; if (type.match(/xml/)) return pd.xml(str); if (type.match(/json/)) return pd.json(str); return str; } function writeFile(req, res, addPath, ending) { var doc = ''; req.on('data', function(data) { doc += data; }); req.on('end', function() { var path = docPath(req, addPath, ending); fs.writeFile(path, prettify(doc, req), function() { res.end(); }); }); } function get(route, fileType) { return function(req, res) { sendFile(req, res, route, fileType); }; } function post(route, fileType) { return function(req, res) { writeFile(req, res, route, fileType); }; } var exampleFileRoutes = { 'treebanks': 'xml', 'comments': 'json', 'translations': 'json', 'tei' : 'xml', 'oa' : 'json', 'treebanks/phaidra': 'json', 'translations/phaidra': 'json' }; for (var route in exampleFileRoutes) { var fileType = exampleFileRoutes[route]; router.get( '/' + route + '/:doc', get(route, fileType)); router.post('/' + route + '/:doc', post(route, fileType)); } module.exports = router;
JavaScript
0
@@ -1326,24 +1326,86 @@ ype); %7D;%0A%7D%0A%0A +function docRoute(route) %7B%0A return '/' + route + '/:doc';%0A%7D%0A%0A var exampleF @@ -1444,30 +1444,8 @@ l',%0A - 'comments': 'json',%0A 't @@ -1669,116 +1669,992 @@ et( -'/' + route + '/:doc', get(route, fileType));%0A router.post('/' + route + '/:doc', post(route, fileType) +docRoute(route), get(route, fileType));%0A router.post(docRoute(route), post(route, fileType));%0A%7D%0A%0Arouter.get( docRoute('comments'), get('comments', 'json'));%0Arouter.post(docRoute('comments'), function(req, res) %7B%0A var comment, comments;%0A var path = docPath(req, 'comments', 'json');%0A var now = new Date().toJSON();%0A req.on('data', function(data) %7B comment = JSON.parse(data); %7D);%0A req.on('end', function() %7B%0A fs.readFile(path, function(err, file) %7B%0A if (err) %7B comments = %5B%5D; %7D else %7B comments = JSON.parse(file); %7D%0A var ids = comments.map(function(el) %7B return el.comment_id; %7D).sort();%0A delete comment.ids;%0A delete comment.sentenceId;%0A comment.comment_id = (ids%5Bids.length - 1%5D %7C%7C 0) + 1;%0A comment.reason = 'general';%0A comment.created_at = now;%0A comment.updated_at = now;%0A comment.user = 'you';%0A comments.push(comment);%0A fs.writeFile(path, prettify(comments, req), function() %7B res.json(comment); %7D);%0A %7D);%0A %7D );%0A%7D +); %0A%0Amo
a35c99b1b255bccffb520a4457a7f34baa6dc722
move service name to correct place
ngdoc/services/getPartialNames.js
ngdoc/services/getPartialNames.js
/** * @dgService getPartialNames * @description * Get a list of all the partial code names that can be made from the provided set of parts * @param {Array} codeNameParts A collection of parts for a code name * @return {Array} A collection of partial names */ module.exports = function() { return function getPartialNames(codeNameParts) { var methodName; var partialNames = []; // Add the last part to the list of partials var part = codeNameParts.pop(); // If the name contains a # then it is a member and that should be included in the partial names if ( part.name.indexOf('#') !== -1 ) { methodName = part.name.split('#')[1]; } // Add the part name and modifier, if provided partialNames.push(part.name); if (part.modifier) { partialNames.push(part.modifier + ':' + part.name); } // Continue popping off the parts of the codeName and work forward collecting up each partial partialNames = codeNameParts.reduceRight(function(partialNames, part) { // Add this part to each of the partials we have so far partialNames.forEach(function(name) { // Add the part name and modifier, if provided partialNames.push(part.name + '.' + name); if ( part.modifier ) { partialNames.push(part.modifier + ':' + part.name + '.' + name); } }); return partialNames; }, partialNames); if ( methodName ) { partialNames.push(methodName); } return partialNames; }; };
JavaScript
0.000001
@@ -298,16 +298,32 @@ function + getPartialNames () %7B%0A r @@ -336,32 +336,16 @@ function - getPartialNames (codeNam
fa87791106175cc2c37114609ad66f90ee824291
Fix fast-slow example
examples/fast-slow-progress.js
examples/fast-slow-progress.js
// Fast-low progress emission, copied from <http://jsfiddle.net/cLtNS/1/> with // discussion at <https://github.com/kriskowal/q/pull/114#issuecomment-8739693>. var legendary = require("../"); function fast(){ return new legendary.Promise(function(resolver){ setTimeout(function(){ resolver.progress(1); }, 200); setTimeout(function(){ resolver.progress(2); }, 400); setTimeout(function(){ resolver.progress(3); }, 600); setTimeout(function(){ resolver.progress(4); }, 800); setTimeout(function(){ resolver.progress(5); resolver.fulfill(); }, 1000); }); } function slow(){ return new legendary.Promise(function(resolver){ setTimeout(function(){ resolver.progress(11); }, 500); setTimeout(function(){ resolver.progress(22); }, 1000); setTimeout(function(){ resolver.progress(33); }, 1500); setTimeout(function(){ resolver.progress(44); }, 2000); setTimeout(function(){ resolver.progress(55); resolver.fulfill(); }, 2500); }); } var a = fast(); var b = slow(); a.then(function(){ return b; }).then(console.log);
JavaScript
0.999989
@@ -1155,16 +1155,28 @@ %7D).then( +null, null, console.
d5e8f9cd378952ae3f42d3fa10c48b92732b088e
Update test to make constant naming consistent with other files
node-tests/unit/icon-task-test.js
node-tests/unit/icon-task-test.js
'use strict'; const expect = require('../helpers/expect'); const IconTask = require('../../src/icon-task'); const fs = require('fs'); const sizeOf = require('image-size'); const parseString = require('xml2js').parseString; const _find = require('lodash').find; const DefaultIcons = require('../../src/default-icons'); describe('IconTask', function() { // Hitting the file system is slow this.timeout(0); const configFixtureDir = 'node-tests/fixtures/config.xml'; const tmpConfigPath = 'tmp/config.xml'; const svgPath = 'node-tests/fixtures/icon.svg'; const pngPath = 'icons'; const projectPath = 'tmp'; before((done) => { if (!fs.existsSync('tmp')) fs.mkdirSync('tmp'); const fixturePath = `${configFixtureDir}/no-platform-nodes.xml`; const fixtureStream = fs.createReadStream(fixturePath); const tmpConfigStream = fs.createWriteStream(tmpConfigPath); fixtureStream.pipe(tmpConfigStream); tmpConfigStream.on('finish', () => { done(); }); }); after(() => { fs.unlinkSync(tmpConfigPath); }); context('when platforms', () => { context('when ios', () => { const platform = 'ios'; const platformSizes = DefaultIcons[platform]; let task; before(() => { task = IconTask({ source: svgPath, dest: pngPath, projectPath: projectPath, platforms: [platform] }) }); after(() => { platformSizes.items.forEach((size) => { const path = `${projectPath}/${pngPath}/${platform}/${size.name}.png`; fs.unlinkSync(path); }); fs.rmdirSync(`${projectPath}/${pngPath}/${platform}`); fs.rmdirSync(`${projectPath}/${pngPath}`); }); it('generates the icons', (done) => { task.then(() => { try { platformSizes.items.forEach((size) => { const path = `${projectPath}/${pngPath}/${platform}/${size.name}.png`; expect(fs.existsSync(path)).to.equal(true); expect(sizeOf(path).width).to.equal(size.size); expect(sizeOf(path).height).to.equal(size.size); }); done(); } catch(e) { done(e); } }); }); it('updates config.xml', (done) => { task.then(() => { const configXML = fs.readFileSync(tmpConfigPath, 'utf8'); try { parseString(configXML, (err, config) => { if (err) done(err); const platformNode = _find(config.widget.platform, (node) => { return node.$.name == platform; }); expect(platformNode).to.exist; const iconsAttrs = platformNode.icon.map((iconNode) => { return iconNode.$; }); platformSizes.items.forEach((size) => { const attrs = { src: `${pngPath}/${platform}/${size.name}.png`, height: size.size.toString(), width: size.size.toString() } expect(iconsAttrs).to.include(attrs); }); }); done(); } catch(e) { done(e); } }); }); it('returns a promise', (done) => { expect(task).to.be.fulfilled.notify(done); }); }); }); });
JavaScript
0.000002
@@ -2398,19 +2398,20 @@ t config -XML +File = fs.re @@ -2496,11 +2496,12 @@ nfig -XML +File , (e
b6e927a4ed3ff0c0e959bd1e131276a3a30d7fa2
add 'watch' to allowed component keys (#1787)
src/renderer/services/plugin-manager/component/validate.js
src/renderer/services/plugin-manager/component/validate.js
import { hooks } from './hooks' import { PLUGINS } from '@config' export function validateComponent ({ plugin, component, name, logger }) { const requiredKeys = ['template'] const allowedKeys = [ 'data', 'methods', 'computed', 'components', 'props', ...hooks ] const missingKeys = [] for (const key of requiredKeys) { if (!Object.prototype.hasOwnProperty.call(component, key)) { missingKeys.push(key) } } const componentError = (error, errorType) => { if (logger) { logger.error(`Plugin '${plugin.config.id}' component '${name}' ${errorType}: ${error}`) } } if (missingKeys.length) { componentError(missingKeys.join(', '), 'is missing') return false } const inlineErrors = [] if (/v-html/i.test(component.template)) { inlineErrors.push('uses v-html') } if (/javascript:/i.test(component.template)) { inlineErrors.push('"javascript:"') } if (/<\s*webview/i.test(component.template)) { inlineErrors.push('uses webview tag') } if (/<\s*script/i.test(component.template)) { inlineErrors.push('uses script tag') } else if (/[^\w]+eval\(/i.test(component.template)) { inlineErrors.push('uses eval') } if (/<\s*iframe/i.test(component.template)) { inlineErrors.push('uses iframe tag') } if (/srcdoc/i.test(component.template)) { inlineErrors.push('uses srcdoc property') } const inlineEvents = [] for (const event of PLUGINS.validation.events) { if ((new RegExp(`(^|\\s)+on${event}`, 'i')).test(component.template)) { inlineEvents.push(event) } } if (inlineEvents.length) { inlineErrors.push('events: ' + inlineEvents.join(', ')) } if (inlineErrors.length) { componentError(inlineErrors.join('; '), 'has inline javascript') return false } const bannedKeys = [] for (const key of Object.keys(component)) { if (![...requiredKeys, ...allowedKeys].includes(key)) { bannedKeys.push(key) } } if (bannedKeys.length) { componentError(bannedKeys.join(', '), 'has unpermitted keys') return false } return true }
JavaScript
0
@@ -217,24 +217,37 @@ 'methods',%0A + 'watch',%0A 'compute
5968b8290bc218ab8a1feb366c98879de45ed9fe
Fix test for checking touch-away behaviour
packages/react-accessible-tooltip/src/Tooltip.test.js
packages/react-accessible-tooltip/src/Tooltip.test.js
// @flow import classnames from 'classnames'; import toJson from 'enzyme-to-json'; import { mount } from 'enzyme'; import { Simulate } from 'react-dom/test-utils'; import ReactDOM from 'react-dom'; // $FlowFixMe import React16 from 'react-16'; // $FlowFixMe import React15 from 'react-15'; import { type LabelProps, type OverlayProps } from './'; function testReact(React, Tooltip) { const HIDDEN_CLASS = 'HIDDEN_CLASS'; const LABEL_CLASS = 'LABEL_CLASS'; const OVERLAY_CLASS = 'OVERLAY_CLASS'; const Label = ({ isHidden, labelAttributes }: LabelProps) => ( <div className={classnames(LABEL_CLASS, { [HIDDEN_CLASS]: isHidden, })} {...labelAttributes} /> ); const CloseButton = props => <button {...props} />; const Overlay = ({ isHidden, requestHide, overlayAttributes, }: OverlayProps) => ( <div className={classnames(OVERLAY_CLASS, { [HIDDEN_CLASS]: isHidden, })} {...overlayAttributes} > <CloseButton onClick={requestHide}>close</CloseButton> </div> ); let wrapper; let label; let overlay; let closeButton; beforeEach(() => { wrapper = mount(<Tooltip label={Label} overlay={Overlay} />); label = wrapper.find(Label); overlay = wrapper.find(Overlay); closeButton = wrapper.find(CloseButton); }); describe(`${React.version} -`, () => { it('matches the previous snapshot', () => { expect(toJson(wrapper)).toMatchSnapshot(); }); it("increments the overlay's `id` attribute with each instance.", () => { expect(overlay.find('div').prop('id')).toEqual( 'react-accessible-tooltip-1', // as opposed to `react-accessible-tooltip-0` ); }); it('hides the overlay by default', () => { expect(wrapper.state('isHidden')).toBeTruthy(); }); it('reveals the overlay when the label is focussed, and hides the overlay when the whole tooltip is blurred.', () => { label.simulate('focus'); expect(wrapper.state('isHidden')).toBeFalsy(); overlay.simulate('focus'); expect(wrapper.state('isHidden')).toBeFalsy(); label.simulate('blur'); expect(wrapper.state('isHidden')).toBeTruthy(); }); it('respects a manual close request', () => { label.simulate('focus'); expect(wrapper.state('isHidden')).toBeFalsy(); closeButton.simulate('click'); expect(wrapper.state('isHidden')).toBeTruthy(); }); it('respects the containerRef prop', () => { const containerRef = jest.fn(); wrapper = mount( <Tooltip label={Label} overlay={Overlay} containerRef={containerRef} />, ); wrapper.simulate('touchStart', { type: 'touchstart', x: 0, y: 0, }); expect(containerRef.mock.calls.length).toEqual(1); expect(containerRef.mock.calls[0][0]).toBeInstanceOf( HTMLDivElement, ); }); describe('touch devices -', () => { // let containerRef; let labelRef; let overlayRef; beforeAll(() => { const testRoot = document.createElement('div'); ReactDOM.render( <div // ref={_containerRef => { // containerRef = _containerRef; // }} > <Tooltip label={({ labelAttributes }) => ( <div {...labelAttributes} ref={_labelRef => { labelRef = _labelRef; }} /> )} overlay={({ overlayAttributes }) => ( <div {...overlayAttributes} ref={_overlayRef => { overlayRef = _overlayRef; }} /> )} /> </div>, testRoot, ); }); it('opens on focus', () => { expect(overlayRef.getAttribute('aria-hidden')).toEqual('true'); Simulate.focus(labelRef); expect(overlayRef.getAttribute('aria-hidden')).toEqual('false'); }); it('closes on touch-away', () => { const testEvent = new Event('touchstart', { bubbles: true }); // $FlowFixMe document.body.dispatchEvent(testEvent); expect(overlayRef.getAttribute('aria-hidden')).toEqual('true'); }); it('successfully unmounts without crashing', () => { wrapper.unmount(); }); it('removes touch event listeners on unmount', () => { const removeEventListenerSpy = jest.spyOn( document, 'removeEventListener', ); wrapper.unmount(); expect(removeEventListenerSpy).toHaveBeenCalled(); removeEventListenerSpy.mockReset(); removeEventListenerSpy.mockRestore(); }); }); }); } describe('<Tooltip />', () => { describe('React 16', () => { jest.resetModules(); jest.doMock('react', () => React16); // eslint-disable-next-line global-require const { Tooltip } = require('./'); testReact(React16, Tooltip); }); describe('React 15', () => { jest.resetModules(); jest.doMock('react', () => React15); // eslint-disable-next-line global-require const { Tooltip } = require('./'); testReact(React15, Tooltip); }); });
JavaScript
0
@@ -5021,32 +5021,155 @@ -away', () =%3E %7B%0A + Simulate.focus(labelRef);%0A expect(overlayRef.getAttribute('aria-hidden')).toEqual('false');%0A
7d15f18198446ace82c582cd2289514633969508
Fix example 3
examples/exmaple3.js
examples/exmaple3.js
'use strict' var { ModelManager, Repo } = require('../lib/index'); var data = { person: [ { _id: '63', name: 'Kevin', bestFriendId: '89', workPlaceId: '1', contact: { address: '123 Picton Road', tel: '123 456 789' }, created: new Date() }, { _id: '89', name: 'Tom', bestFriendId: '63', workPlaceId: '2', contact: { address: '5 Marina Tower', tel: '133 436 109' } }, { _id: '97', name: 'Sarah', bestFriendId: '63', workPlaceId: '1', contact: { address: '93 Alderson Road', tel: '093 238 2349' } }, { _id: '165', name: 'Sam', bestFriendId: '63', workPlaceId: '2', contact: { address: '502 Tanjung Bungha', tel: '078 131 1847' } }, { _id: '192', name: 'Paula', bestFriendId: '63', workPlaceId: '1', contact: { address: '101 King Street', tel: '555 555 5555' } }, ], workPlace: [ {_id: '1', name: 'Hotel', managerId: '89'}, {_id: '2', name: 'Bar', managerId: '192'}, ] }; var modelManager = new ModelManager({ dataSources: [{ name: 'db', type: 'mongodb', url: 'mongodb://localhost:27017/domain-model-example' }] }); class Person { getName() { return this.name + ' (' + this._id + ')'; } }; class PersonContact { getAddress() { return this.address + ' (@)'; } }; var personRepo = new Repo({ name: 'person', dataSource: 'db', entityConstructor: Person, embeddedConstructors: { 'contact': PersonContact }, strict: false, schema: { _id: Number, bestFriendId: Number, workPlaceId: Number, created: Date, contact: { address: String, tel: String } }, indexes: { bestFriendId: {spec: {bestFriendId: 1}}, workPlaceId: {spec: {workPlaceId: 1}} }, autoIndex: true, relations: { isConsideredBestFriendBy: { type: 'hasMany', repo: 'person', key: 'bestFriendId', sort: ['name', 'asc'], populate: true, recursion: 0 }, isConsideredBestFriendByCount: { type: 'hasManyCount', repo: 'person', key: 'bestFriendId', sort: ['name', 'asc'], populate: true, recursion: 0 }, bestFriend: { type: 'belongsToOne', repo: 'person', key: 'bestFriendId', populate: true, recursion: 0 }, workPlace: { type: 'belongsToOne', repo: 'workPlace', key: 'workPlaceId', populate: true, recursion: 0 }, } }); modelManager.addRepo(personRepo); var workPlaceRepo = new Repo({ name: 'workPlace', dataSource: 'db', schema: { _id: Number, managerId: Number }, relations: { manager: { type: 'belongsToOne', repo: 'person', key: 'managerId', populate: true } } }); modelManager.addRepo(workPlaceRepo); modelManager .init() .then(function(){ console.log('** Connected **'); }).then(function(){ return personRepo.deleteMany(); }).then(function(){ return workPlaceRepo.deleteMany(); }).then(function(){ return personRepo.insertMany(data.person); }).then(function(savedData){ return workPlaceRepo.insertOne(data.workPlace[0]); }).then(function(savedData){ return personRepo.updateMany({'workPlaceId': 1}, {$set: {'contact.address': '123 Updated Street'}}); }).then(function(savedData){ return personRepo.find({}, {sort: [['name', 'asc']]}); }).then(function(objects){ console.log(JSON.stringify(objects, null, 2)); }).then(function(){ return modelManager.shutdown(); }).then(function(){ console.log('** Disconnected **'); }).catch(function(err) { console.log(err.stack); }); (async () => { try { await modelManager.init(); console.log('** Connected **'); await personRepo.deleteMany(); await workPlaceRepo.deleteMany(); await personRepo.insertMany(data.person); await workPlaceRepo.insertOne(data.workPlace[0]); await personRepo.updateMany({'workPlaceId': 1}, {$set: {'contact.address': '123 Updated Street'}}); var people = await personRepo.find({}, {sort: [['name', 'asc']]}); console.log(JSON.stringify(people, null, 2)); await modelManager.shutdown(); console.log('** Disconnected **'); } catch (e) { console.log(JSON.stringify(e, null, 2)); } })();
JavaScript
0.999992
@@ -3011,800 +3011,8 @@ );%0A%0A -modelManager%0A.init()%0A.then(function()%7B%0A console.log('** Connected **');%0A%7D).then(function()%7B%0A return personRepo.deleteMany();%0A%7D).then(function()%7B%0A return workPlaceRepo.deleteMany();%0A%7D).then(function()%7B%0A return personRepo.insertMany(data.person);%0A%7D).then(function(savedData)%7B%0A return workPlaceRepo.insertOne(data.workPlace%5B0%5D);%0A%7D).then(function(savedData)%7B%0A return personRepo.updateMany(%7B'workPlaceId': 1%7D, %7B$set: %7B'contact.address': '123 Updated Street'%7D%7D);%0A%7D).then(function(savedData)%7B%0A return personRepo.find(%7B%7D, %7Bsort: %5B%5B'name', 'asc'%5D%5D%7D);%0A%7D).then(function(objects)%7B%0A console.log(JSON.stringify(objects, null, 2));%0A%7D).then(function()%7B%0A return modelManager.shutdown();%0A%7D).then(function()%7B%0A console.log('** Disconnected **');%0A%7D).catch(function(err) %7B%0A console.log(err.stack);%0A%7D);%0A%0A %0A(as
ef639a9b0ee0fcdb48b6f0242e7ce6f5ab69cf43
update user info
data/SiteConfig.js
data/SiteConfig.js
const config = { siteTitle: "Thada W.", // Site title. siteTitleShort: "Thada W", // Short site title for homescreen (PWA). Preferably should be under 12 characters to prevent truncation. siteTitleAlt: "Thada W.", // Alternative site title for SEO. siteLogo: "/logos/android-chrome-512x512.png", // Logo used for SEO and manifest. siteUrl: "https://thadaw.com", // Domain of your website without pathPrefix. pathPrefix: "/", // Prefixes all links. For cases when deployed to example.github.io/gatsby-advanced-starter/. nodePrefix: "/b", // Prefixes for only post created by createNodeField from `gastby-node.js` siteDescription: "You can find almost stuff about me: sharing ideas, programming techniques, web technology and others.", // Website description used for RSS feeds/meta description tag. siteRss: "/rss.xml", // Path to the RSS file. siteRssTitle: "Thadaw.com RSS feed", // Title of the RSS feed siteFBAppID: "xxxxx", // FB Application ID for using app insights googleAnalyticsID: "UA-62565035-1", // GA tracking ID. disqusShortname: "https-vagr9k-github-io-gatsby-advanced-starter", // Disqus shortname. dateFromFormat: "YYYY-MM-DD", // Date format used in the frontmatter. dateFormat: "DD/MM/YYYY", // Date format for display. // postsPerPage: 4, // Amount of posts displayed per listing page. userName: "Thada Wangthammang", // Username to display in the author segment. userEmail: "[email protected]", // Email used for RSS feed's author segment userTwitter: "mildronize", // Optionally renders "Follow Me" in the UserInfo segment. userLocation: "Songkhla, Thailand", // User location to display in the author segment. userAvatar: "https://api.adorable.io/avatars/150/test.png", // User avatar to display in the author segment. userDescription: "Yeah, I like animals better than people sometimes... Especially dogs. Dogs are the best. Every time you come home, they act like they haven't seen you in a year. And the good thing about dogs... is they got different dogs for different people.", // User description to display in the author segment. // Links to social profiles/projects you want to display in the author segment/navigation bar. userLinks: [ { label: "GitHub", url: "https://github.com/mildronize", iconClassName: "fab fa-github", }, { label: "Twitter", url: "https://twitter.com/mildronize", iconClassName: "fab fa-twitter", }, { label: "Email", url: "mailto:[email protected]", iconClassName: "fas fa-envelope", }, { label: "Linkedin", url: "https://www.linkedin.com/in/thada-wangthammang-281894a6/", iconClassName: "fab fa-linkedin", }, { label: "Medium", url: "https://medium.com/@mildronize", iconClassName: "fab fa-medium", }, { label: "RSS", url: "/rss.xml", iconClassName: "fas fa-rss", } ], copyright: "Copyright © 2021. Thada W.", // Copyright string for the footer of the website and RSS feed. themeColor: "#c62828", // Used for setting manifest and progress theme colors. backgroundColor: "#e0e0e0", // Used for setting manifest background color. }; // Validate // Make sure pathPrefix is empty if not needed if (config.pathPrefix === "/") { config.pathPrefix = ""; } else { // Make sure pathPrefix only contains the first forward slash config.pathPrefix = `/${config.pathPrefix.replace(/^\/|\/$/g, "")}`; } // Make sure siteUrl doesn't have an ending forward slash if (config.siteUrl.substr(-1) === "/") config.siteUrl = config.siteUrl.slice(0, -1); // Make sure nodePrefix doesn't have an ending forward slash if (config.nodePrefix.substr(-1) === "/") config.nodePrefix = config.nodePrefix.slice(0, -1); // Make sure siteRss has a starting forward slash if (config.siteRss && config.siteRss[0] !== "/") config.siteRss = `/${config.siteRss}`; module.exports = config;
JavaScript
0
@@ -1425,26 +1425,25 @@ Email: %22 -mildronize +thada.wth @gmail.c @@ -2501,26 +2501,25 @@ %22mailto: -mildronize +thada.wth @gmail.c @@ -2768,16 +2768,23 @@ https:// +thadaw. medium.c @@ -2790,19 +2790,8 @@ com/ -@mildronize %22,%0A
19b974942aba017e42caaec6ae1df6b5fe6596bb
Fix size in example
Sources/Rendering/Misc/RenderWindowWithControlBar/example/index.js
Sources/Rendering/Misc/RenderWindowWithControlBar/example/index.js
import vtkRenderWindowWithControlBar from 'vtk.js/Sources/Rendering/Misc/RenderWindowWithControlBar'; import vtkSlider from 'vtk.js/Sources/Interaction/UI/Slider'; import vtkCornerAnnotation from 'vtk.js/Sources/Interaction/UI/CornerAnnotation'; import vtkActor from 'vtk.js/Sources/Rendering/Core/Actor'; import vtkConeSource from 'vtk.js/Sources/Filters/Sources/ConeSource'; import vtkMapper from 'vtk.js/Sources/Rendering/Core/Mapper'; // Define container size/position const body = document.querySelector('body'); const rootContainer = document.createElement('div'); rootContainer.style.position = 'relative'; rootContainer.style.width = '500px'; rootContainer.style.height = '500px'; body.appendChild(rootContainer); // Create render window inside container const renderWindow = vtkRenderWindowWithControlBar.newInstance({ controlSize: 25 }); renderWindow.setContainer(rootContainer); // Add some content to the renderer const coneSource = vtkConeSource.newInstance(); const mapper = vtkMapper.newInstance(); const actor = vtkActor.newInstance(); mapper.setInputConnection(coneSource.getOutputPort()); actor.setMapper(mapper); renderWindow.getRenderer().addActor(actor); renderWindow.getRenderer().resetCamera(); renderWindow.getRenderWindow().render(); // Set control bar to be red so we can see it + layout setup... renderWindow.getControlContainer().style.background = '#eee'; renderWindow.getControlContainer().style.display = 'flex'; renderWindow.getControlContainer().style.alignItems = 'stretch'; renderWindow.getControlContainer().style.justifyContent = 'stretch'; renderWindow.getControlContainer().innerHTML = ` <button alt="Left" title="Left" value="left">L</button> <button alt="Top" title="Top" value="top">T</button> <button alt="Right" title="Right" value="right">R</button> <button alt="Bottom" title="Bottom" value="bottom">B</button> <div class="js-slider"></div> `; // Add corner annotation const cornerAnnotation = vtkCornerAnnotation.newInstance(); cornerAnnotation.setContainer(renderWindow.getRenderWindowContainer()); cornerAnnotation.getAnnotationContainer().style.color = 'white'; cornerAnnotation.updateMetadata(coneSource.get('resolution', 'mtime')); cornerAnnotation.updateTemplates({ nw(meta) { return `<b>Resolution: </b> ${meta.resolution}`; }, se(meta) { return `<span style="font-size: 50%"><i style="color: red;">mtime:</i>${meta.mtime}</span><br/>Annotation Corner`; }, }); // Add slider to the control bar const sliderContainer = renderWindow.getControlContainer().querySelector('.js-slider'); sliderContainer.style.flex = '1'; sliderContainer.style.position = 'relative'; sliderContainer.style.minWidth = '25px'; sliderContainer.style.minHeight = '25px'; const slider = vtkSlider.newInstance(); slider.generateValues(6, 60, 55); slider.setValue(6); slider.setContainer(sliderContainer); slider.onValueChange((resolution) => { coneSource.set({ resolution }); renderWindow.getRenderWindow().render(); cornerAnnotation.updateMetadata(coneSource.get('resolution', 'mtime')); }); function updateSizeAndOrientation() { renderWindow.resize(); slider.resize(); renderWindow.getControlContainer().style.flexFlow = slider.getOrientation() ? 'row' : 'column'; setTimeout(slider.resize, 0); } updateSizeAndOrientation(); // Handle UI to change bar location function onClick(e) { renderWindow.setControlPosition(e.target.value); updateSizeAndOrientation(); } const list = document.querySelectorAll('button'); let count = list.length; while (count--) { list[count].style.width = '25px'; list[count].style.height = '25px'; list[count].style.flex = 'none'; list[count].addEventListener('click', onClick); }
JavaScript
0
@@ -723,16 +723,17 @@ 500px';%0A +%0A body.app @@ -752,24 +752,49 @@ tContainer); +%0Abody.style.margin = '0'; %0A%0A// Create
06ccc096936daf3f597d42428a1c1bb6ad303409
Fix navbar highlighting
src/encoded/static/modules/navbar.js
src/encoded/static/modules/navbar.js
define(['exports', 'jquery', 'underscore', 'navigator', 'app', 'base', 'text!templates/navbar.html'], function navbar(exports, $, _, navigator, app, base, navbar_template) { // The top navbar exports.NavBarView = base.View.extend({ template: _.template(navbar_template), initialize: function () { // TODO: re-renders more than necessary, should split into subviews. console.log("Initializing navbar"); this.listenTo(app.router, 'all', this.on_route); }, // Preprocess the global_sections adding an active class to the current section global_sections: function global_sections() { var view = this; return _(this.model.global_sections).map(function (action) { return _.extend(action, { 'class': view.current_route === action.id ? 'active': '' }); }); }, user_actions: function user_actions() { return this.model.user_actions; }, on_route: function on_route(evt) { this.current_route = evt.substring(evt.indexOf(':')+1); this.render(); if (app.user.email) { $("#signout").text("Log out: "+app.user.email); $("#signout").parent().show(); $("#signin").parent().hide(); } else { $("#signin").parent().show(); $("#signout").parent().hide(); } }, events: { "click #signin": "signin", "click #signout": "signout" }, signout: function(event) { event.preventDefault(); console.log('Loggin out (persona)'); navigator.id.logout(); }, signin:function (event) { event.preventDefault(); // Don't let this button submit the form $('.alert-error').hide(); // Hide any errors on a new submit var request_params = {}; // could be site name console.log('Logging in (persona) '); navigator.id.request(request_params); navigator.id.watch({ loggedInUser: app.user.email, onlogin: function(assertion) { if (assertion) { $.ajax({ url:'/login', type:'POST', dataType:"json", data: JSON.stringify({ "assertion": assertion, "came_from": "/" }), contentType: 'application/json', headers: { "X-Genuine-Request": "Bonafide ENCODE3 Submission"}, success:function (data) { console.log("Login request headers: "+data["headers"]); console.log("Login info:"); console.log(data["info"]); if(data.error) { // If there is an error, show the error messages $('.alert-error').text(data.error.text).show(); } else if (data.status != 'okay') { $('.alert-error').text('This seems impossible, but Persona returned your status as something other than ok').show(); } else { // If not, send them back to the home page app.user.email = data.email; //_each(app.Config.user_actions(), function(action) { // action = action._extend({'class': hide}); //}); app.router.trigger('login'); // possibly this should trigger on navbar view directly //Backbone.history.navigate(location.href, {trigger: true, replace: true}); } }, error: function(xhr, status, err) { $('.alert-error').text("Login failure: "+err+" ("+status+")").show(); } }); } }, onlogout: function() { console.log("Persona thinks we need to log out"); $.ajax({ url: '/logout', type: 'POST', data: JSON.stringify({ came_from: "/" }), success: function () { console.log('reloading after persona logout'); app.user = { email: undefined }; app.router.trigger('logout'); //Backbone.history.navigate(location.href, {trigger: true, replace: true}); //window.location.reload(); }, error: function(xhr, status, err) { alert("Logout failure: "+err+" ("+status+")"); } }); } }); } }, { slot_name: 'navbar' }); return exports; });
JavaScript
0
@@ -1096,62 +1096,209 @@ -this.current_route = evt.substring(evt.indexOf(':')+1) +var route_parts = evt.split(':');%0A // Only render on the main route not the overlay route.%0A if (route_parts%5B0%5D !== 'route') return;%0A this.current_route = route_parts%5B1%5D ;%0A
c72a230b1fd924be9af9f10d2c598ea2c3792e61
fix bug 权限显示不全问题
flask_perm/static/admin.js
flask_perm/static/admin.js
// declare a new module called 'myApp', and make it require the `ng-admin` module as a dependency var PermAdmin = angular.module('PermAdmin', ['ng-admin']); // declare a function to run when the module bootstraps (during the 'config' phase) PermAdmin.config(['NgAdminConfigurationProvider', function (nga) { // create an admin application var applicationName = 'Permission Management Admininistration'; var admin = nga.application( applicationName, window.g.debug ).baseApiUrl(window.g.baseApiUrl); // more configuration here later var permission = nga.entity('permissions'); var user = nga.entity('users').readOnly(); var userGroup = nga.entity('user_groups'); var userPermission = nga.entity('user_permissions'); var userGroupMember = nga.entity('user_group_members'); var userGroupPermission = nga.entity('user_group_permissions'); var fields = { title: nga.field('title').label('Title'), code: nga.field('code').label('Code'), nickname: nga.field('nickname').label('Nickname'), user: nga.field('user_id', 'reference') .targetEntity(user) .targetField(nga.field('nickname')) .label('User'), userGroup: nga.field('user_group_id', 'reference') .targetEntity(userGroup) .targetField(nga.field('title')) .label('User Group'), permission: nga.field('permission_id', 'reference') .targetEntity(permission) .targetField(nga.field('title')) .label('Permission') }; admin.addEntity(permission); admin.addEntity(userGroup); admin.addEntity(user); admin.addEntity(userPermission); admin.addEntity(userGroupPermission); admin.addEntity(userGroupMember); permission.listView().fields([ fields.title.isDetailLink(true), fields.code, ]).filters([ fields.title, fields.code, ]); permission.creationView().fields([ fields.title.validation({ required: true}), fields.code.validation({ required: true}), ]); permission.editionView().fields(permission.creationView().fields()); userGroup.listView().fields([ fields.title.isDetailLink(true), fields.code, ]); userGroup.creationView().fields([ fields.title.validation({ required: true }), fields.code.validation({ required: true }), ]); userGroup.editionView().fields(userGroup.creationView().fields()); user.listView().fields([ fields.nickname, ]); userPermission.listView().fields([ fields.user, fields.permission, ]).filters([ fields.user, fields.permission, ]); userPermission.creationView().fields([ fields.user, fields.permission, ]); userPermission.showView().disable(); userGroupPermission.listView().fields([ fields.userGroup, fields.permission, ]).filters([ fields.userGroup, fields.permission, ]); userGroupPermission.creationView().fields([ fields.userGroup, fields.permission, ]); userGroupPermission.showView().disable(); userGroupMember.listView().fields([ fields.userGroup, fields.user, ]).filters([ fields.userGroup, fields.user, ]); userGroupMember.creationView().fields([ fields.userGroup, fields.user, ]); // ... // attach the admin application to the DOM and execute it var makeIcon = function(cls) { return '<span class="glyphicon '+ cls + '"></span>' }; var menuIcons = { user: makeIcon('glyphicon-user'), userGroup: makeIcon('glyphicon-user'), permission: makeIcon('glyphicon-minus-sign'), userPermission: makeIcon('glyphicon-pencil'), userGroupPermission: makeIcon('glyphicon-pencil'), userGroupMember: makeIcon('glyphicon-pencil'), }; admin.menu( nga.menu() .addChild(nga.menu(user).icon(menuIcons.user)) .addChild(nga.menu(userGroup).icon(menuIcons.userGroup)) .addChild(nga.menu(permission).icon(menuIcons.permission)) .addChild(nga.menu(userPermission).icon(menuIcons.userPermission)) .addChild(nga.menu(userGroupPermission).icon(menuIcons.userGroupPermission)) .addChild(nga.menu(userGroupMember).icon(menuIcons.userGroupMember)) ); var customHeaderTemplate = '<div class="navbar-header">' + '<a class="navbar-brand" href="#" ng-click="appController.displayHome()">' + applicationName + '</a>' + '</div>' + '<p class="navbar-text navbar-right">' + '<a href="' + window.g.baseWebUrl + '/logout">' + 'Logout' + '</a>' + '</p>'; admin.header(customHeaderTemplate); nga.configure(admin); }]); PermAdmin.config(['RestangularProvider', function(RestangularProvider) { RestangularProvider.addFullRequestInterceptor( function(element, operation, what, url, headers, params) { if (operation === "getList") { if (params._page) { params.offset = (params._page - 1) * params._perPage; params.limit = params._perPage; } } return {params: params}; } ); RestangularProvider.addResponseInterceptor( function(data, operation, what, url, response, deferred) { var extractedData; extractedData = data.data; return extractedData; } ); }]);
JavaScript
0
@@ -581,32 +581,93 @@ 'permissions');%0A + var all_permission = nga.entity('permissions?limit=1000');%0A var user = nga @@ -1486,32 +1486,195 @@ field('title'))%0A + .label('Permission'),%0A all_permission: nga.field('permission_id', 'reference')%0A .targetEntity(all_permission)%0A .targetField(nga.field('title'))%0A .label('Pe @@ -2801,32 +2801,36 @@ ser,%0A fields. +all_ permission,%0A %5D) @@ -3097,32 +3097,36 @@ oup,%0A fields. +all_ permission,%0A %5D) @@ -4922,24 +4922,173 @@ , params) %7B%0A + String.prototype.endWith=function(endStr)%7B%0A var d=this.length-endStr.length;%0A return (d%3E=0&&this.lastIndexOf(endStr)==d)%0A %7D%0A if (op @@ -5136,16 +5136,47 @@ ms._page + && !url.endWith(%22?limit=1000%22) ) %7B%0A
0459e12dc45ff9c24b03f92df8bef0d9631a654c
modify rich text link handler to open URLs via the bounce app
www/pad/links.js
www/pad/links.js
define([ 'jquery', '/common/hyperscript.js', '/common/common-ui-elements.js', '/customize/messages.js' ], function ($, h, UIElements, Messages) { var onLinkClicked = function (e, inner, openLinkSetting) { var $target = $(e.target); if (!$target.is('a')) { $target = $target.closest('a'); if (!$target.length) { return; } } var href = $target.attr('href'); if (!href) { return; } var $inner = $(inner); e.preventDefault(); e.stopPropagation(); if (href[0] === '#') { var anchor = $inner.find(href); if (!anchor.length) { return; } anchor[0].scrollIntoView(); return; } if(openLinkSetting) { window.open(href, '_blank', 'noreferrer'); return; } var $iframe = $('html').find('iframe').contents(); var rect = e.target.getBoundingClientRect(); var rect0 = inner.getBoundingClientRect(); var l = (rect.left - rect0.left)+'px'; var t = rect.bottom + $iframe.scrollTop() +'px'; var a = h('a', { href: href}, href); var link = h('div.cp-link-clicked.non-realtime', { contenteditable: false, style: 'top:'+t+';left:'+l }, [ a ]); var $link = $(link); $inner.append(link); if (rect.left + $link.outerWidth() - rect0.left > $inner.width()) { $link.css('left', 'unset'); $link.css('right', 0); } $(a).click(function (ee) { ee.preventDefault(); ee.stopPropagation(); var bounceHref = window.location.origin + '/bounce/#' + encodeURIComponent(href); window.open(bounceHref); $link.remove(); }); $link.on('mouseleave', function () { $link.remove(); }); }; var removeClickedLink = function ($inner) { $inner.find('.cp-link-clicked').remove(); }; return { init : function (Ckeditor, editor, openLinkSetting) { if (!Ckeditor.plugins.link) { return; } var inner = editor.document.$.body; var $inner = $(inner); // Bubble to open the link in a new tab $inner.click(function (e) { removeClickedLink($inner); if (e.target.nodeName.toUpperCase() === 'A' || $(e.target).closest('a').length) { return void onLinkClicked(e, inner, openLinkSetting); } }); // Adds a context menu entry to open the selected link in a new tab. var getActiveLink = function() { var anchor = Ckeditor.plugins.link.getSelectedLink(editor); // We need to do some special checking against widgets availability. var activeWidget = editor.widgets && editor.widgets.focused; // If default way of getting links didn't return anything useful.. if (!anchor && activeWidget && activeWidget.name === 'image' && activeWidget.parts.link) { // Since CKEditor 4.4.0 image widgets may be linked. anchor = activeWidget.parts.link; } return anchor; }; editor.addCommand( 'openLink', { exec: function() { var anchor = getActiveLink(); if (anchor) { var href = anchor.getAttribute('href'); if (href) { var bounceHref = window.location.origin + '/bounce/#' + encodeURIComponent(href); window.open(bounceHref); } } } }); if (typeof editor.addMenuItem === 'function') { editor.addMenuItem('openLink', { label: Messages.openLinkInNewTab, command: 'openLink', group: 'link', order: -1 }); } if (editor.contextMenu) { editor.contextMenu.addListener(function(startElement) { if (startElement) { var anchor = getActiveLink(); if (anchor && anchor.getAttribute('href')) { return {openLink: Ckeditor.TRISTATE_OFF}; } } }); editor.contextMenu._.panelDefinition.css.push('.cke_button__openLink_icon {' + Ckeditor.skin.getIconStyle('link') + '}'); } } }; });
JavaScript
0
@@ -749,80 +749,124 @@ -if(openLinkSetting) %7B%0A window.open(href, '_blank', 'noreferrer' +var open = function () %7B%0A var bounceHref = window.location.origin + '/bounce/#' + encodeURIComponent(href );%0A @@ -870,39 +870,113 @@ ;%0A + -return;%0A +window.open(bounceHref);%0A %7D;%0A%0A if (openLinkSetting) %7B return void open(); %7D%0A%0A @@ -1773,124 +1773,13 @@ -var bounceHref = window.location.origin + '/bounce/#' + encodeURIComponent(href);%0A window.open(bounceHref +open( );%0A
2b13863680378bc4e7908c42efef68b60a80e712
Fix Node version check (#12382)
packages/babel-cli/src/babel/util.js
packages/babel-cli/src/babel/util.js
// @flow import readdirRecursive from "fs-readdir-recursive"; import * as babel from "@babel/core"; import path from "path"; import fs from "fs"; export function chmod(src: string, dest: string): void { fs.chmodSync(dest, fs.statSync(src).mode); } type ReaddirFilter = (filename: string) => boolean; export function readdir( dirname: string, includeDotfiles: boolean, filter?: ReaddirFilter, ): Array<string> { return readdirRecursive(dirname, (filename, _index, currentDirectory) => { const stat = fs.statSync(path.join(currentDirectory, filename)); if (stat.isDirectory()) return true; return ( (includeDotfiles || filename[0] !== ".") && (!filter || filter(filename)) ); }); } export function readdirForCompilable( dirname: string, includeDotfiles: boolean, altExts?: Array<string>, ): Array<string> { return readdir(dirname, includeDotfiles, function (filename) { return isCompilableExtension(filename, altExts); }); } /** * Test if a filename ends with a compilable extension. */ export function isCompilableExtension( filename: string, altExts?: Array<string>, ): boolean { const exts = altExts || babel.DEFAULT_EXTENSIONS; const ext = path.extname(filename); return exts.includes(ext); } export function addSourceMappingUrl(code: string, loc: string): string { return code + "\n//# sourceMappingURL=" + path.basename(loc); } const CALLER = { name: "@babel/cli", }; export function transform( filename: string, code: string, opts: Object, ): Promise<Object> { opts = { ...opts, caller: CALLER, filename, }; return new Promise((resolve, reject) => { babel.transform(code, opts, (err, result) => { if (err) reject(err); else resolve(result); }); }); } export function compile( filename: string, opts: Object | Function, ): Promise<Object> { opts = { ...opts, caller: CALLER, }; return new Promise((resolve, reject) => { babel.transformFile(filename, opts, (err, result) => { if (err) reject(err); else resolve(result); }); }); } export function deleteDir(path: string): void { if (fs.existsSync(path)) { fs.readdirSync(path).forEach(function (file) { const curPath = path + "/" + file; if (fs.lstatSync(curPath).isDirectory()) { // recurse deleteDir(curPath); } else { // delete file fs.unlinkSync(curPath); } }); fs.rmdirSync(path); } } process.on("uncaughtException", function (err) { console.error(err); process.exitCode = 1; }); export function requireChokidar(): Object { try { // todo(babel 8): revert `@nicolo-ribaudo/chokidar-2` hack return parseInt(process.version) >= 8 ? require("chokidar") : require("@nicolo-ribaudo/chokidar-2"); } catch (err) { console.error( "The optional dependency chokidar failed to install and is required for " + "--watch. Chokidar is likely not supported on your platform.", ); throw err; } } export function withExtension(filename: string, ext: string = ".js") { const newBasename = path.basename(filename, path.extname(filename)) + ext; return path.join(path.dirname(filename), newBasename); }
JavaScript
0.000059
@@ -2723,16 +2723,22 @@ .version +s.node ) %3E= 8%0A
ee4803d8744d593df07a7c85b8ddd28860d9aae7
use local time
frontend/src/components/guild_config_edit.js
frontend/src/components/guild_config_edit.js
import React, { Component } from 'react'; import AceEditor, { diff as DiffEditor } from 'react-ace'; import { globalState } from '../state'; import { NavLink } from 'react-router-dom'; import moment from 'moment'; import 'brace/mode/yaml' import 'brace/theme/monokai' class ConfigHistory extends Component { render() { let buttonsList = [] if (this.props.history) { for (let change of this.props.history) { buttonsList.push( <NavLink key={change.created_timestamp} to={`/guilds/${this.props.guild.id}/config/${change.created_timestamp}`} className="list-group-item" activeClassName="active"> <i className="fa fa-history fa-fw"></i> {change.user.username}#{change.user.discriminator} <span className="pull-right text-muted small" title={change.created_at}><em>{moment(change.created_at).fromNow()}</em></span> </NavLink> ) } } return ( <div className="col-lg-3"> <div className="panel panel-default"> <div className="panel-heading"> <i className="fa fa-history fa-fw"></i> History </div> <div className="panel-body"> <div className="list-group"> <NavLink key='config' exact to={`/guilds/${this.props.guild.id}/config`} className="list-group-item" activeClassName="active"> <i className="fa fa-edit fa-fw"></i> Current version </NavLink> {this.props.history && buttonsList} </div> </div> </div> </div> ); } } export default class GuildConfigEdit extends Component { constructor() { super(); this.messageTimer = null; this.initialConfig = null; this.state = { message: null, guild: null, contents: null, hasUnsavedChanges: false, history: null, } } componentWillMount() { globalState.getGuild(this.props.params.gid).then((guild) => { globalState.currentGuild = guild; guild.getConfig(true) .then((config) => { this.initialConfig = config.contents; this.setState({ guild: guild, contents: config.contents, }); return guild.id }) .then(guild.getConfigHistory) .then((history) => { this.setState({ history: history }); }); }).catch((err) => { console.error('Failed to find guild for config edit', this.props.params.gid); }); } componentWillUnmount() { globalState.currentGuild = null; } onEditorChange(newValue) { let newState = {contents: newValue, hasUnsavedChanges: false}; if (this.initialConfig != newValue) { newState.hasUnsavedChanges = true; } this.setState(newState); } onSave() { this.state.guild.putConfig(this.state.contents).then(() => { this.initialConfig = this.state.contents; this.setState({ hasUnsavedChanges: false, }); this.renderMessage('success', 'Saved Configuration!'); }).catch((err) => { this.renderMessage('danger', `Failed to save configuration: ${err}`); }); } renderMessage(type, contents) { this.setState({ message: { type: type, contents: contents, } }) if (this.messageTimer) clearTimeout(this.messageTimer); this.messageTimer = setTimeout(() => { this.setState({ message: null, }); this.messageTimer = null; }, 5000); } render() { let history; if (this.props.params.timestamp) { history = this.state.history ? this.state.history.find(c => c.created_timestamp == this.props.params.timestamp) : null } return (<div> {this.state.message && <div className={"alert alert-" + this.state.message.type}>{this.state.message.contents}</div>} <div className="row"> <div className="col-md-9"> <div className="panel panel-default"> <div className="panel-heading"> <i className="fa fa-gear fa-fw"></i> Configuration Editor </div> <div className="panel-body"> {this.state.history && this.props.params.timestamp && this.state.history.find(c => c.created_timestamp == this.props.params.timestamp) ? ( <DiffEditor mode="yaml" theme="monokai" width="100%" height="1000px" value={[history.before, history.after]} readOnly={true} /> ) : ( <AceEditor mode="yaml" theme="monokai" width="100%" height="1000px" value={this.state.contents == null ? '' : this.state.contents} onChange={(newValue) => this.onEditorChange(newValue)} readOnly={this.state.guild && this.state.guild.role != 'viewer' ? false : true} /> )} </div> <div className="panel-footer"> { this.state.guild && !this.props.params.timestamp && this.state.guild.role != 'viewer' && <button onClick={() => this.onSave()} type="button" className="btn btn-success btn-circle btn-lg"> <i className="fa fa-check"></i> </button> } { this.state.hasUnsavedChanges && <i style={{paddingLeft: '10px'}}>Unsaved Changes!</i>} </div> </div> </div> {this.state.guild && this.state.history && <ConfigHistory guild={this.state.guild} history={this.state.history} timestamp={this.props.params.timestamp} />} </div> </div>); } }
JavaScript
0.000003
@@ -821,16 +821,25 @@ %7Bmoment( +new Date( change.c @@ -845,18 +845,48 @@ created_ -a t +imestamp*1000).toLocaleString() ).fromNo
fba887dc8aa220bbea8737354446eb469b4178ee
Remove on-finished module
rco_design/lib/autoload/hooks/server_bin/static.js
rco_design/lib/autoload/hooks/server_bin/static.js
// Static file handler. Serves all of the files from `public/root` directory // under the main application root path. 'use strict'; const path = require('path'); const send = require('send'); const Promise = require('bluebird'); const onFinished = require('on-finished'); module.exports = function (N) { var root = path.join(__dirname, '../../../../static'); N.validate('server_bin:rcd-nodeca.static', { // DON'T validate unknown params - those can exists, // if someone requests '/myfile.txt?xxxx' instead of '/myfile.txt/ additionalProperties: true, properties: { path: { type: 'string', required: true } } }); N.wire.on('server_bin:rcd-nodeca.static', async function static_file_send(env) { var req = env.origin.req, res = env.origin.res; if (req.method !== 'GET' && req.method !== 'HEAD') throw N.io.BAD_REQUEST; await new Promise((resolve, reject) => { let ss = send(req, env.params.path, { root, index: false, maxAge: '7d' }); // Errors with status are not fatal, // rethrow those up as code, not as Error ss.on('error', err => reject(err.status || err)); onFinished(res, () => { if (res.statusCode) env.status = res.statusCode; resolve(); }); ss.pipe(res); }); }); };
JavaScript
0.000001
@@ -208,23 +208,23 @@ ;%0Aconst -Promise +stream = r @@ -235,60 +235,14 @@ re(' -bluebird');%0Aconst onFinished = require('on-finished +stream ');%0A @@ -1151,11 +1151,16 @@ -onF +stream.f inis
0af5200f7bc5ddd9676ddf1abbaf253e7ce84e69
Update resolve function
lib/plugins/pseudo-levels/builder.js
lib/plugins/pseudo-levels/builder.js
var path = require('path'), SUBLEVEL_NAME = 'blocks', SYMLINK_EXT = '.symlink'; /** * Создаёт resolve-функцию псевдоуровней. * * Используется для построения уровня-сета с бандлами примеров на основе папок-технологий, представляющих собой * simple-уровни с бандлами примеров. * * Пример: * * <block-name>.examples/ * ├── blocks/ # уровень для всех примеров блока <block-name> * ├── 10-simple.blocks/ # уровень для примера 10-simple * ├── 10-simple.bemjson.js * ├── 10-simple.title.txt * ├── 20-complex.bemjson.js * └── 20-complex.title.txt * * В результирующий уровень-сет будут предоставлены только те файлы, суффиксы которых содержатся в `fileSuffixes` опции, * а так же, если файлы находятся внутри папок-технологий, суффиксы которых содержатся в `techSuffixes` опции. * * Если для примера встретится уровень, то он будет предоставлен в бандл этого примера с именем `blocks`. Если же * встретится уровень для всех примеров, то он будет предоставлен в уровень-сет с именем `.blocks`. * * Все файлы в уровне-сете представлены как симлинки с расширением `.symlink`. * * Пример: * * <set-name>.examples * └── <block-name>/ * ├── .blocks/ # уровень для всех примеров блока <block-name> * ├── 10-simple/ * ├── blocks/ # уровень для примера 10-simple * └── 10-simple.bemjson.js.symlink * └── 20-complex/ * └── 20-comples.bemjson.js.symlink * * @param {Object} options * @param {Array<String>} options.techSuffixes Суффиксы папок-технологий с примерами. * @param {Array<String>} options.fileSuffixes Суффиксы файлов внутри папок-технологий с примерами. * @return {Function} */ module.exports = function (options) { return function (dir) { if (dir.isDirectory && options.techSuffixes.indexOf(dir.suffix) !== -1) { var scope = dir.name.split('.')[0], files = dir.files, res = []; files && files.length && files.forEach(function (file) { var basename = file.name, bemname = basename.split('.')[0], suffix = file.suffix, hasSublevel = false; // Уровень для всех примеров if (basename === SUBLEVEL_NAME) { basename = '.blocks'; bemname = ''; hasSublevel = true; } else // Уровень только для текущего примера if (suffix === SUBLEVEL_NAME) { basename = 'blocks'; hasSublevel = true; } if (hasSublevel || options.fileSuffixes.indexOf(suffix) !== -1) { res.push({ targetPath: path.join(scope, bemname, file.isDirectory ? basename : basename + SYMLINK_EXT), sourcePath: file.fullname }); } }); return res; } }; };
JavaScript
0.000001
@@ -2937,16 +2937,71 @@ fullname +,%0A isDirectory: file.isDirectory %0A
6692729103dbcb34b807a6911e2603b11c45f17e
add support for Red vs Blue shortcode
shared/GameTypes.js
shared/GameTypes.js
const GameType = require('./GameType'); const find = require('lodash/find'); const types = { FFA: new GameType({ name: 'FFA', shortCode: 'FFA', requiresTeamSizes: false }), CHOSEN: new GameType({ name: 'Chosen', shortCode: 'c', requiresTeamSizes: true, // Call default but also add the extra check if there is no type string to assume its a chosen teams (fallback) isType: typeString => GameType.defaultChecker.call(types.CHOSEN, typeString) || typeString === '' }), RANDOM: new GameType({ name: 'Random', shortCode: 'r', requiresTeamSizes: true }), CAPTAINS: new GameType({ name: 'Captains', shortCode: 'Cpt', requiresTeamSizes: true }), PICKED: new GameType({ name: 'Picked', shortCode: 'p', requiresTeamSizes: true }), AUCTION: new GameType({ name: 'SlaveMarket', shortCode: 'SlaveMarket', requiresTeamSizes: false }), MYSTERY: new GameType({ name: 'Mystery', shortCode: 'm', requiresTeamSizes: true }), CUSTOM: new GameType({ name: 'Custom', shortCode: 'Not required', requiresTeamSizes: 'CUSTOM', // Never use this type when parsing, it is for the generator only isType: () => false, formatter: size => size }) }; module.exports = { types, parseFromString: typeString => find(types, value => value.isType(typeString)) };
JavaScript
0
@@ -1137,24 +1137,152 @@ rue%0A %7D),%0A + RED_VS_BLUE: new GameType(%7B%0A name: 'Red vs Blue',%0A shortCode: 'RvB',%0A requiresTeamSizes: false%0A %7D),%0A CUSTOM:
4c7f38e03115cf529a90fe509eaa008b06d03c12
Improve list argument validation
ext/html5/_list-construct.js
ext/html5/_list-construct.js
'use strict'; var isFunction = require('es5-ext/function/is-function') , isArrayLike = require('es5-ext/object/is-array-like') , isPlainObject = require('es5-ext/object/is-plain-object') , isIterable = require('es6-iterator/is-iterable') , isObservable = require('observable-value/is-observable') , makeElement = require('dom-ext/document/#/make-element') , castAttributes = require('dom-ext/element/#/cast-attributes') , elExtend = require('dom-ext/element/#/extend') , remove = require('dom-ext/element/#/remove') , replaceContent = require('dom-ext/element/#/replace-content') , isNode = require('dom-ext/node/is-node') , isText = require('dom-ext/text/is-text') , memoize = require('memoizee/plain') , getNormalizer = require('memoizee/normalizers/get-1') , map = Array.prototype.map, call = Function.prototype.call; module.exports = function (childName, isChildNode) { return function (listArg/*, renderItem, thisArg*/) { var attrs, renderItem, render, thisArg, cb, onEmpty, arrayLike , list = listArg; if (isPlainObject(list) && !isFunction(arguments[1])) { attrs = list; list = arguments[1]; renderItem = arguments[2]; thisArg = arguments[3]; } else { renderItem = arguments[1]; thisArg = arguments[2]; } if (isNode(list) || !isFunction(renderItem)) return elExtend.apply(this, arguments); arrayLike = isArrayLike(list); if (!arrayLike && !isIterable(list)) return elExtend.apply(this, arguments); if (attrs) { if (attrs.onEmpty) { onEmpty = attrs.onEmpty; delete attrs.onEmpty; if (isNode(onEmpty)) remove.call(onEmpty); } castAttributes.call(this, attrs); } cb = function (item, index, list) { var result; result = this.safeCollect(renderItem.bind(thisArg, item, index, list)); if (result == null) return null; if (isText(result) && !result.data && result._isDomExtLocation_) return result; if (!isChildNode(result)) result = makeElement.call(this.document, childName, result); return result; }; render = function () { var content; if (arrayLike) { content = map.call(list, cb, this.domjs); } else if (list.forEach) { content = []; list.forEach(function (item, key) { content.push(call.call(cb, this.domjs, item, key, list)); }, this); } if (!content.length && onEmpty) content = onEmpty; replaceContent.call(this, content); }.bind(this); if (isObservable(list)) { cb = memoize(cb, { normalizer: getNormalizer() }); list.on('change', render); } render(); return this; }; };
JavaScript
0.000003
@@ -1485,47 +1485,168 @@ t)) -return elExtend.apply(this, arguments); +%7B%0A%09%09%09if (typeof renderItem.toDOM !== 'function') return elExtend.apply(this, arguments);%0A%09%09%09throw new TypeError(list + %22 is not an array-like or iterable%22);%0A%09%09%7D %0A%09%09i
cdb94f8e49bd36e6aad2e493599e5b2fbd81498b
Set ariaLabel in TextSearchView.
src/foam/u2/search/TextSearchView.js
src/foam/u2/search/TextSearchView.js
/** * @license * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ foam.CLASS({ package: 'foam.u2.search', name: 'TextSearchView', extends: 'foam.u2.View', imports: [ 'memento' ], requires: [ 'foam.parse.QueryParser', 'foam.u2.tag.Input' ], implements: [ 'foam.mlang.Expressions' ], messages: [ { name: 'LABEL_SEARCH', message: 'Search' } ], properties: [ { class: 'Class', name: 'of' }, { class: 'Boolean', name: 'richSearch' }, { class: 'Boolean', name: 'keywordSearch' }, { class: 'Boolean', name: 'checkStrictEquality', documentation: ` Set this flag if you want to match by strict equality instead of checking if the text contains the string. Doing so should improve performance. ` }, { name: 'queryParser', factory: function() { return this.QueryParser.create({ of: this.of }); } }, { class: 'Int', name: 'width', value: 47 }, 'property', { name: 'predicate', factory: function() { return this.TRUE; } }, { class: 'foam.u2.ViewSpec', name: 'viewSpec', value: { class: 'foam.u2.tag.Input' } }, { name: 'view' }, { name: 'label', expression: function(property) { return property && property.label ? property.label : this.LABEL_SEARCH; } }, { // All search views (in the SearchManager) need a name. // This defaults to 'textSearchView'. name: 'name', value: 'textSearchView' }, { class: 'Boolean', name: 'onKey' }, 'searchValue' ], methods: [ function initE() { this .addClass(this.myClass()) .tag(this.viewSpec, { alwaysFloatLabel: true, label$: this.label$, onKey: this.onKey, mode$: this.mode$ }, this.view$); this.view.data$.sub(this.updateValue); this.updateValue(); if ( this.searchValue ) { this.view.data = this.searchValue; } }, function clear() { this.view.data = ''; this.predicate = this.TRUE; } ], listeners: [ { name: 'updateValue', isMerged: true, mergeDelay: 500, code: function() { var value = this.view.data; if ( this.memento ) { if ( value ) { this.memento.paramsObj.s = value; } else { delete this.memento.paramsObj.s; } this.memento.paramsObj = foam.Object.clone(this.memento.paramsObj); } this.predicate = ! value ? this.True.create() : this.richSearch ? this.OR( this.queryParser.parseString(value) || this.FALSE, this.KEYWORD(value) ) : this.checkStrictEquality ? this.EQ(this.property, value) : this.CONTAINS_IC(this.property, value); } } ] });
JavaScript
0
@@ -2452,16 +2452,51 @@ label$,%0A + ariaLabel$: this.label$,%0A @@ -3249,24 +3249,16 @@ %7D%0A - %0A
ab913884bdf434d0e30ae3512d5f113e2c98aea7
Make background images behave like legacy plugin
src/widget/widget.js
src/widget/widget.js
import buildfire from 'buildfire'; const Layouts = { 1: 'WideScreen', 2: 'Cinema' } const defaultData = { content: { text : '<p>The WYSIWYG (which stands for What You See Is What You Get) allows you to do some really cool stuff. You can add images like this</p>\ <p><img src="https://static.pexels.com/photos/12057/pexels-photo-12057-large.jpeg" alt="" width="100%" height="auto" /></p>\ <p>You can even create links like these:<br /> Link to web content like <a href="http://www.google.com">this</a><br /> Link to a phone number like this <a href="tel: 8005551234">8005551234</a><br /> Link to an email like this <a href="mailto:[email protected]">[email protected]</a></p>\ <p>Want to add some super cool videos about this item? You can do that too!</p>\ <p><iframe src="https://www.youtube.com/embed/wTcNtgA6gHs" width="100%" height="auto" frameborder="0" allowfullscreen="allowfullscreen"></iframe></p>\ <p>You can create bulleted and numbered lists like this:</p>\ <ul>\ <li>This is an item in a list</li>\ <li>This is another item in a list</li>\ <li>This is a last item in a list</li>\ </ul>\ <p>Want more info? Check out our tutorial by clicking the help button at the top of this page.</p>', carouselImages : [ {"action":"noAction","iconUrl":"http://imageserver.prod.s3.amazonaws.com/b55ee984-a8e8-11e5-88d3-124798dea82d/5db61d30-0854-11e6-8963-f5d737bc276b.jpg","title":"image 1"},{"action":"noAction","iconUrl":"http://imageserver.prod.s3.amazonaws.com/b55ee984-a8e8-11e5-88d3-124798dea82d/31c88a00-0854-11e6-8963-f5d737bc276b.jpeg","title":"image 2"} ] }, design: { backgroundImage: null, selectedLayout: 1 } }; const state = { height: window.innerHeight, width: window.innerWidth, carouselInstance: null, data: { content: { carouselImages: [], text: '' }, design: { backgroundImage: null, selectedLayout: 1 } } }; function init() { // Get initial data state buildfire.datastore.get((err, result) => { if (err) return console.error(err); state.data = result.data && result.data.content ? result.data : defaultData; render(); }); // Keep state up to date with control changes buildfire.datastore.onUpdate((result) => { state.data = result.data; render(); }); } function render() { const { design, content } = state.data; const textContainer = window.document.getElementById('text'); renderCarousel(); // Set background image if needed if (design && design.backgroundImage) { const DPR = window.devicePixelRatio; const width = Math.ceil(state.width * DPR); const height = Math.ceil(state.height * DPR); const baseUrl = 'https://czi3m2qn.cloudimg.io/s/crop'; const cropUrl = `${baseUrl}/${width}x${height}`; const url = `${cropUrl}/${design.backgroundImage}`; window.document.body.setAttribute('style', ` background-position: center !important; background-size: cover !important; background-attachment: fixed !important; background-image: url(${url}) !important; `); } else { window.document.body.style.backgroundImage = ''; } // Render HTML content textContainer.innerHTML = content.text; try { buildfire.appearance.ready(); } catch (err) { console.log('appearance.ready() failed, is sdk up to date?'); } } function renderCarousel() { const { carouselImages } = state.data.content; const { selectedLayout } = state.data.design; const carouselContainer = window.document.getElementById('carousel'); // Toggle carousel container visibility carouselContainer.style.display = carouselImages.length ? 'block' : 'none'; // Don't do anything if we don't have carousel images if (!carouselImages.length) return; // Set the proper size to the carousel container carouselContainer.style.height = selectedLayout === 1 ? `${Math.ceil(9 * state.width / 16)}px` : `${Math.ceil(1 * state.width / 2.39)}px`; // Destroy the carousel if we already have one if (state.carouselInstance && state.carouselInstance.lorySlider) { state.carouselInstance.lorySlider.destroy(); carouselContainer.innerHTML = ''; delete state.carouselInstance; } // Initialize carousel state.carouselInstance = new buildfire.components.carousel.view({ selector: carouselContainer, layout: Layouts[state.data.design.selectedLayout], items: carouselImages }); } init();
JavaScript
0.000001
@@ -2608,49 +2608,8 @@ ) %7B%0A - const DPR = window.devicePixelRatio;%0A @@ -2643,22 +2643,16 @@ te.width - * DPR );%0A c @@ -2691,14 +2691,8 @@ ight - * DPR );%0A%0A @@ -2745,14 +2745,15 @@ .io/ -s/crop +cdn/n/n ';%0A @@ -2761,21 +2761,17 @@ const -cropU +u rl = %60$%7B @@ -2785,254 +2785,135 @@ %7D/$%7B -width%7Dx$%7Bheight%7D%60;%0A const url = %60$%7BcropUrl%7D/$%7Bdesign.backgroundImage%7D%60;%0A%0A window.document.body.setAttribute('style', %60%0A background-position: center !important;%0A background-size: cover !important;%0A background-attachment: fixed +design.backgroundImage%7D?h=$%7Bheight%7D&w=$%7Bwidth%7D%60;%0A%0A window.document.body.setAttribute('style', %60%0A background-size: cover !im
bf87ee3daf0b5533803a2b712059db452244962a
correct unread color class
pkg/interface/link/src/js/components/lib/link-item.js
pkg/interface/link/src/js/components/lib/link-item.js
import React, { Component } from 'react' import moment from 'moment'; import { Sigil } from '/components/lib/icons/sigil'; import { Route, Link } from 'react-router-dom'; import { base64urlEncode } from '../../lib/util'; export class LinkItem extends Component { constructor(props) { super(props); this.state = { timeSinceLinkPost: this.getTimeSinceLinkPost() }; this.markPostAsSeen = this.markPostAsSeen.bind(this); } componentDidMount() { this.updateTimeSinceNewestMessageInterval = setInterval( () => { this.setState({timeSinceLinkPost: this.getTimeSinceLinkPost()}); }, 60000); } componentWillUnmount() { if (this.updateTimeSinceNewestMessageInterval) { clearInterval(this.updateTimeSinceNewestMessageInterval); this.updateTimeSinceNewestMessageInterval = null; } } getTimeSinceLinkPost() { return !!this.props.timestamp ? moment.unix(this.props.timestamp / 1000).from(moment.utc()) : ''; } markPostAsSeen() { api.seenLink(this.props.groupPath, this.props.url); } render() { let props = this.props; let mono = (props.nickname) ? "inter white-d" : "mono white-d"; let URLparser = new RegExp(/((?:([\w\d\.-]+)\:\/\/?){1}(?:(www)\.?){0,1}(((?:[\w\d-]+\.)*)([\w\d-]+\.[\w\d]+))){1}(?:\:(\d+)){0,1}((\/(?:(?:[^\/\s\?]+\/)*))(?:([^\?\/\s#]+?(?:.[^\?\s]+){0,1}){0,1}(?:\?([^\s#]+)){0,1})){0,1}(?:#([^#\s]+)){0,1}/); let hostname = URLparser.exec(props.url); const seenState = props.seen ? "grey2" : "green2 pointer"; const seenAction = props.seen ? ()=>{} : this.markPostAsSeen if (hostname) { hostname = hostname[4]; } let encodedUrl = base64urlEncode(props.url); let comments = props.comments + " comment" + ((props.comments === 1) ? "" : "s"); return ( <div className="w-100 pv3 flex"> <Sigil ship={"~" + props.ship} size={36} color={"#" + props.color} /> <div className="flex flex-column ml2"> <a href={props.url} className="w-100 flex" target="_blank" onClick={this.markPostAsSeen}> <p className="f8 truncate">{props.title} <span className="gray2 dib truncate-m mw4-m v-btm ml2">{hostname} ↗</span> </p> </a> <div className="w-100 pt1"> <span className={"f9 pr2 v-mid " + mono}>{(props.nickname) ? props.nickname : "~" + props.ship}</span> <span className={seenState + " f9 inter pr3 v-mid"} onClick={this.markPostAsSeen}> {this.state.timeSinceLinkPost} </span> <Link to= {"/~link" + props.popout + props.groupPath + "/" + props.page + "/" + props.linkIndex + "/" + encodedUrl} className="v-top" onClick={this.markPostAsSeen}> <span className="f9 inter gray2"> {comments} </span> </Link> </div> </div> </div> ) } } export default LinkItem
JavaScript
0.000001
@@ -1518,17 +1518,17 @@ ? %22gr -e +a y2%22%0A
f77853a865b6acb372f2a317683f3c073ccf0c1e
rename AttributeSelector.operator -> matcher
lib/syntax/node/AttributeSelector.js
lib/syntax/node/AttributeSelector.js
var TYPE = require('../../tokenizer').TYPE; var IDENTIFIER = TYPE.Identifier; var STRING = TYPE.String; var DOLLARSIGN = TYPE.DollarSign; var ASTERISK = TYPE.Asterisk; var COLON = TYPE.Colon; var EQUALSSIGN = TYPE.EqualsSign; var LEFTSQUAREBRACKET = TYPE.LeftSquareBracket; var RIGHTSQUAREBRACKET = TYPE.RightSquareBracket; var CIRCUMFLEXACCENT = TYPE.CircumflexAccent; var VERTICALLINE = TYPE.VerticalLine; var TILDE = TYPE.Tilde; function getAttributeName() { if (this.scanner.eof) { this.scanner.error('Unexpected end of input'); } var start = this.scanner.tokenStart; var expectIdentifier = false; var checkColon = true; if (this.scanner.tokenType === ASTERISK) { expectIdentifier = true; checkColon = false; this.scanner.next(); } else if (this.scanner.tokenType !== VERTICALLINE) { this.scanner.eat(IDENTIFIER); } if (this.scanner.tokenType === VERTICALLINE) { if (this.scanner.lookupType(1) !== EQUALSSIGN) { this.scanner.next(); this.scanner.eat(IDENTIFIER); } else if (expectIdentifier) { this.scanner.error('Identifier is expected', this.scanner.tokenEnd); } } else if (expectIdentifier) { this.scanner.error('Vertical line is expected'); } if (checkColon && this.scanner.tokenType === COLON) { this.scanner.next(); this.scanner.eat(IDENTIFIER); } return { type: 'Identifier', loc: this.getLocation(start, this.scanner.tokenStart), name: this.scanner.substrToCursor(start) }; } function getOperator() { var start = this.scanner.tokenStart; var tokenType = this.scanner.tokenType; if (tokenType !== EQUALSSIGN && // = tokenType !== TILDE && // ~= tokenType !== CIRCUMFLEXACCENT && // ^= tokenType !== DOLLARSIGN && // $= tokenType !== ASTERISK && // *= tokenType !== VERTICALLINE // |= ) { this.scanner.error('Attribute selector (=, ~=, ^=, $=, *=, |=) is expected'); } if (tokenType === EQUALSSIGN) { this.scanner.next(); } else { this.scanner.next(); this.scanner.eat(EQUALSSIGN); } return this.scanner.substrToCursor(start); } // '[' S* attrib_name ']' // '[' S* attrib_name S* attrib_match S* [ IDENT | STRING ] S* attrib_flags? S* ']' module.exports = { name: 'AttributeSelector', structure: { name: 'Identifier', operator: [String, null], value: ['String', 'Identifier', null], flags: [String, null] }, parse: function() { var start = this.scanner.tokenStart; var name; var operator = null; var value = null; var flags = null; this.scanner.eat(LEFTSQUAREBRACKET); this.scanner.skipSC(); name = getAttributeName.call(this); this.scanner.skipSC(); if (this.scanner.tokenType !== RIGHTSQUAREBRACKET) { // avoid case `[name i]` if (this.scanner.tokenType !== IDENTIFIER) { operator = getOperator.call(this); this.scanner.skipSC(); value = this.scanner.tokenType === STRING ? this.String() : this.Identifier(); this.scanner.skipSC(); } // attribute flags if (this.scanner.tokenType === IDENTIFIER) { flags = this.scanner.getTokenValue(); this.scanner.next(); this.scanner.skipSC(); } } this.scanner.eat(RIGHTSQUAREBRACKET); return { type: 'AttributeSelector', loc: this.getLocation(start, this.scanner.tokenStart), name: name, operator: operator, value: value, flags: flags }; }, generate: function(processChunk, node) { var flagsPrefix = ' '; processChunk('['); this.generate(processChunk, node.name); if (node.operator !== null) { processChunk(node.operator); if (node.value !== null) { this.generate(processChunk, node.value); // space between string and flags is not required if (node.value.type === 'String') { flagsPrefix = ''; } } } if (node.flags !== null) { processChunk(flagsPrefix); processChunk(node.flags); } processChunk(']'); } };
JavaScript
0
@@ -2367,16 +2367,18 @@ ib_match +er S* %5B ID @@ -2416,16 +2416,16 @@ S* '%5D'%0A - module.e @@ -2519,23 +2519,22 @@ -operato +matche r: %5BStri @@ -2727,23 +2727,22 @@ var -operato +matche r = null @@ -3120,23 +3120,22 @@ -operato +matche r = getO @@ -3839,25 +3839,23 @@ -operator: operato +matcher: matche r,%0A @@ -4092,23 +4092,22 @@ f (node. -operato +matche r !== nu @@ -4146,15 +4146,14 @@ ode. -operato +matche r);%0A
87ea202c4d1c9a32e2b449b4bcb5213c3f2507e7
use limit
workers/restore_all.js
workers/restore_all.js
const massive = require("massive"); const log = require('log-colors'); const spawn = require('lib/spawn'); const itunes_restorer = require('lib/restorers/itunes'); const s_digital_restorer = require('lib/restorers/7digital'); const DB_HOST = process.env['DB_HOST']; const DB_PORT = process.env['DB_PORT']; const DB_USER = process.env['DB_USER']; const DB_PASSWD = process.env['DB_PASSWD']; const DB_NAME = process.env['DB_NAME']; const TABLE = 'items'; var connect = () => { return new Promise((resolve, reject) => { massive.connect({ connectionString: `postgres://${DB_USER}:${DB_PASSWD}@${DB_HOST}/${DB_NAME}` }, (err, data) => resolve(data)); }); }; spawn(function*(){ log.info('connecting to db'); var db = yield connect(); log.info('connected to db'); var query = (q) => { return new Promise((resolve, reject) => { db.run(q, (err, stat) => { if(err){ reject(err); return; } resolve(stat, err); }); }).catch((e) => { log.error(`${e}, QUERY: ${q}`); }) } var result = yield query(`select id from ${TABLE} where s_digital is null and itunes is null`); log.info(`processing ${result.length} items`); for(var item of result){ try { var item_data = yield query(`select * from ${TABLE} where id = ${item.id}`); var restored_data = yield [ yield itunes_restorer(item_data[0]), yield s_digital_restorer(item_data[0]) ]; var itunes_data = restored_data[0]; var s_digital_data = restored_data[1]; var values = [ `itunes = '${JSON.stringify(itunes_data).replace(/'/ig, "''")}'`, `s_digital = '${JSON.stringify(s_digital_data).replace(/'/ig, "''")}'` ].join(', '); var query_text = `UPDATE ${TABLE} set ${values} WHERE id = ${item.id}`; var query_result = yield query(query_text); query_result && log.info(`item #${item.id} updated`); } catch(e) { log.info(`could not process item #${item.id}, ERROR: ${e.stack}`); } } process.exit(0); });
JavaScript
0.000003
@@ -449,16 +449,36 @@ items';%0A +const LIMIT = 4000;%0A %0A%0Avar co @@ -1175,16 +1175,31 @@ is null + limit $%7BLIMIT%7D %60);%0A lo
ad9a2db80ebcce36f2d0111bb985ececaa96e2cf
Fix deprecated url/name options
lib/ui/src/core/init-provider-api.js
lib/ui/src/core/init-provider-api.js
import pick from 'lodash.pick'; import deprecate from 'util-deprecate'; import { create } from '@storybook/theming'; const deprecatedUiOptions = ['name', 'url']; const applyDeprecatedUiOptions = deprecate(({ name, url, theme }) => { const vars = { brandTitle: name, brandUrl: url, }; return { theme: create(vars, theme) }; }, 'The `name` and `url` options are deprecated -- instead use the `theme.brandTitle` or `theme.brandUrl`'); const checkDeprecatedUiOptions = options => { if (deprecatedUiOptions.find(key => !!options[key])) { return applyDeprecatedUiOptions(options); } return {}; }; export default ({ provider, api, store }) => { const providerAPI = { ...api, setOptions: options => { const { layout, ui, selectedPanel } = store.getState(); if (options) { store.setState({ layout: { ...layout, ...pick(options, Object.keys(layout)), }, ui: { ...ui, ...pick(options, Object.keys(ui)), ...checkDeprecatedUiOptions(options), }, selectedPanel: options.panel || options.selectedPanel || selectedPanel, }); } }, }; provider.handleAPI(providerAPI); return providerAPI; };
JavaScript
0.000066
@@ -286,16 +286,38 @@ l: url,%0A + brandImage: null,%0A %7D;%0A%0A
64bbf66bb4e3a558a93b12dc6cc59dbf697a3856
fix reset filter
app/assets/javascripts/scripts/core/lib/modules/renderer/filter.js
app/assets/javascripts/scripts/core/lib/modules/renderer/filter.js
/** * Created with RubyMine. * User: teamco * Date: 2/24/15 * Time: 7:31 PM */ /** * Created by i061485 on 7/10/14. */ define([], function defineFilterRenderer() { /** * Define FilterRenderer * @class FilterRenderer * @extends LabelRenderer * @constructor */ var FilterRenderer = function FilterRenderer() { }; return FilterRenderer.extend('FilterRenderer', { /** * Render iframe * @member FilterRenderer * @param {{ * text: string, * name: string, * placeholder: string, * visible: boolean, * callback: function, * [items] * }} opts * @returns {*|jQuery} */ renderFilter: function renderFilter(opts) { // Get scope var scope = this.view.scope, filterEvent = 'keyup.' + scope.name.toLowerCase() + '-search'; // Define items setter this.items = opts.items; /** * Define $search * @type {TextFieldRenderer} */ var $search = this.renderTextField({ text: opts.text, name: opts.name, placeholder: opts.placeholder, monitor: { events: [filterEvent], callback: this.filterResults.bind({ callback: opts.callback, $element: this }) }, visible: opts.visible }); scope.logger.debug('Search field params', opts); /** * Define $reset * @type {*|jQuery} */ var $reset = $('<div />').addClass('reset-filter'). attr({ title: 'Reset filter' }). on('click.reset', function reset() { /** * Get $node * @type {*|jQuery|HTMLElement} */ var $node = $(this); $node.prev().val('').trigger(filterEvent); $node.parent().removeClass('reset'); } ); $search.push($reset); return $search; }, /** * Update items * @member FilterRenderer * @param {{items, [focusOn]}} opts */ updateData: function updateData(opts) { this.items = opts.items; this.focusOn(opts.focusOn); }, /** * Filter search results * @member FilterRenderer * @param e */ filterResults: function filterResults(e) { e.preventDefault(); if (e.which === 13) { return false; } var input = e.target, $parent = $(input).parent(); if (e.which === 27) { input.value = ''; $parent.removeClass('reset'); } $parent.addClass('reset'); /** * Get item elements * @type {{}} */ var items = this.$element.items, index, $item, value = e.target.value, regex; for (index in items) { if (items.hasOwnProperty(index)) { /** * Define item * @type {{ * name: string, * description:string, * [type]: string * }} */ $item = items[index]; if (value.length === 0) { $item.$.removeClass('hide'); } else { /** * Define regex * @type {RegExp} */ regex = new RegExp(value, 'ig'); if (typeof($item.data) === 'undefined') { this.$element.view.scope.logger.warn( 'Item has no data', $item ); return false; } // Define matchers var nameMatch = ($item.data.name || '').match(regex), typeMatch = ($item.data.type || '').match(regex), descriptionMatch = ($item.data.description || '').match(regex); $item.$[( (nameMatch || typeMatch || descriptionMatch) ? 'remove' : 'add' ) + 'Class']('hide'); } } } if (typeof(this.callback) === 'function') { // Execute callback this.callback(); } } }); });
JavaScript
0.000001
@@ -3016,24 +3016,64 @@ .parent();%0A%0A + $parent.addClass('reset');%0A%0A @@ -3193,48 +3193,8 @@ %7D%0A%0A - $parent.addClass('reset');%0A%0A
4e4fdfe9eada8fbd65caabe88377d6f502d42e28
fix potential miscalculation of growth duration
addon/growable.js
addon/growable.js
import Ember from "ember"; import Promise from "liquid-fire/promise"; var capitalize = Ember.String.capitalize; export default Ember.Mixin.create({ growDuration: 250, growPixelsPerSecond: 200, growEasing: 'slide', transitionMap: Ember.inject.service('liquid-fire-transitions'), animateGrowth: function(elt, have, want) { this.get('transitionMap').incrementRunningTransitions(); return Promise.all([ this._adaptDimension(elt, 'width', have, want), this._adaptDimension(elt, 'height', have, want) ]).then(()=>{ this.get('transitionMap').decrementRunningTransitions(); }); }, _adaptDimension: function(elt, dimension, have, want) { var target = {}; target['outer'+capitalize(dimension)] = [ want[dimension], have[dimension], ]; return Ember.$.Velocity(elt[0], target, { duration: this._durationFor(have[dimension], want[dimension]), queue: false, easing: this.get('growEasing') || this.constructor.prototype.growEasing }); }, _durationFor: function(before, after) { return Math.min(this.get('growDuration') || this.constructor.prototype.growDuration, 1000*Math.abs(before - after)/(this.get('growPixelsPerSecond')) || this.constructor.prototype.growPixelsPerSecond); } });
JavaScript
0.000241
@@ -1214,17 +1214,16 @@ Second') -) %7C%7C this @@ -1265,16 +1265,17 @@ rSecond) +) ;%0A %7D%0A%0A%7D
d0fba7b81cba53a24658d53b6ec13aa5e2d19e06
test for abc2
simple-bot-slack.js
simple-bot-slack.js
/** * Copyright 2016 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ require('dotenv').load(); var Botkit = require('botkit'); var express = require('express'); var middleware = require('botkit-middleware-watson')({ username: process.env.CONVERSATION_USERNAME, password: process.env.CONVERSATION_PASSWORD, workspace_id: process.env.WORKSPACE_ID, version_date: '2016-09-20' }); // Configure your bot. var slackController = Botkit.slackbot(); var slackBot = slackController.spawn({ token: process.env.SLACK_TOKEN }); var abc = "guilherme"; slackController.hears(['.*'], ['direct_message', 'direct_mention', 'mention'], function(bot, message) { slackController.log('Slack message received'); middleware.interpret(bot, message, function(err) { if (!err) bot.reply(abc, message.watsonData.output.text.join('\n')); }); }); slackBot.startRTM(); // Create an Express app var app = express(); var port = process.env.PORT || 5000; app.set('port', port); app.listen(port, function() { console.log('Client server listening on port ' + port); });
JavaScript
0.999999
@@ -1075,16 +1075,17 @@ %0Avar abc +2 = %22guil @@ -1329,16 +1329,126 @@ eply(abc +2var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');%0A , messag
f3cc37f0dfd500107a94b13c43fe72e93f851f12
Fix jsdoc.
error-handler.js
error-handler.js
/** * express-error-handler * * A graceful error handler for Express * applications. * * Copyright (C) 2013 Eric Elliott * * Written for * "Programming JavaScript Applications" * (O'Reilly) * * MIT License **/ 'use strict'; var mixIn = require('mout/object/mixIn'), path = require('path'), fs = require('fs'), /** * Return true if the error status represents * a client error that should not trigger a * restart. * * @param {number} status * @return {boolean} */ clientError = function clientError(status) { return (status >= 400 && status <= 499); }, /** * Attempt a graceful shutdown, and then time * out if the connections fail to drain in time. * * @param {object} o options * @param {object} o.server server object * @param {object} o.timeout timeout in ms * @param {function} exit - force kill function */ close = function close(o, exit) { // We need to kill the server process so // the app can repair itself. Your process // should be monitored in production and // restarted when it shuts down. // // That can be accomplished with modules // like forever, forky, etc... // // First, try a graceful shutdown: if (o.server && typeof o.server.close === 'function') { o.server.close(function () { process.exit(o.exitStatus); }); } // Just in case the server.close() callback // never fires, this will wait for a timeout // and then terminate. Users can override // this function by passing options.shutdown: exit(o); }, sendFile = function sendFile (staticFile, res) { var filePath = path.resolve(staticFile), stream = fs.createReadStream(filePath); stream.pipe(res); }, defaults = { handlers: {}, views: {}, static: {}, timeout: 3 * 1000, exitStatus: 1, server: undefined, shutdown: undefined }, createHandler; /** * A graceful error handler for Express * applications. * * @param {object} [options] * * @param {object} [options.handlers] Custom * handlers for specific status codes. * * @param {object} [options.views] View files to * render in response to specific status * codes. Specify a default with * options.views.default. * * @param {object} [options.static] Static files * to send in response to specific status * codes. Specify a default with * options.static.default. * * @param {number} [options.timeout] Delay * between the graceful shutdown * attempt and the forced shutdown * timeout. * * @param {number} [options.exitStatus] Custom * process exit status code. * * @param {object} [options.server] The app server * object for graceful shutdowns. * * @param {function} [options.shutdown] An * alternative shutdown function if the * graceful shutdown fails. * * @return {function} errorHandler Express error * handling middleware. */ createHandler = function createHandler(options) { var o = mixIn({}, defaults, options), /** * In case of an error, wait for a timer to * elapse, and then terminate. * @param {Number} status Exit status code. */ exit = o.shutdown || function exit(o){ // Give the app time for graceful shutdown. setTimeout(function () { process.exit(o.exitStatus); }, o.timeout); }; /** * Express error handler to handle any * uncaught express errors. For error logging, * see bunyan-request-logger. * * @param {object} err * @param {object} req * @param {object} res * @param {function} next */ return function errorHandler(err, req, res, next) { var defaultView = o.views['default'], defaultStatic = o.static['default'], status = err.status, handler = o.handlers[status], view = o.views[status], staticFile = o.static[status], renderDefault = function renderDefault(status) { if (defaultView) { return res.render(defaultView, err); } if (defaultStatic) { return sendFile(defaultStatic, res); } return res.send(status); }, resumeOrClose = function resumeOrClose(status) { if (!clientError(status)) { return close(o, exit); } }; // If there's a custom handler defined, // use it and return. if (typeof handler === 'function') { handler(err, req, res, next); return resumeOrClose(status); } // If there's a custom view defined, // render it. if (view) { res.render(view, err); return resumeOrClose(status); } // If there's a custom static file defined, // render it. if (staticFile) { sendFile(staticFile, res); return resumeOrClose(status); } // If the error is user generated, send // a helpful error message, and don't shut // down. // // If we shutdown on user errors, // attackers can send malformed requests // for the purpose of creating a Denial // Of Service (DOS) attack. if (clientError(status)) { return renderDefault(status); } // For all other errors, deliver a 500 // error and shut down. renderDefault(500); close(o, exit); }; }; createHandler.clientError = clientError; module.exports = createHandler;
JavaScript
0
@@ -3241,42 +3241,93 @@ ram +%7Bobject%7D options%0A * @param %7B -N +n umber%7D -status Exit status code. +o.exitStatus%0A * @param %7Bnumber%7D o.timeout %0A
dc09f4b15208b7cd495566730fd0f54e93fc16f7
use express-favicon-short-circuit
examples/index.js
examples/index.js
/* eslint no-console: "off" */ const express = require('express'); const app = express(); app.use(require('../index')({ path: '/' })); app.listen(3000, () => { console.log('listening on http://0.0.0.0:3000'); });
JavaScript
0.000213
@@ -130,16 +130,67 @@ '/' %7D)); +%0Aapp.use(require('express-favicon-short-circuit')); %0A%0Aapp.li
dd3b5cdf1c42144d4971711a3d49978b6348c707
update paints chainer announcement
app/javascript/mastodon/features/compose/components/announcements.js
app/javascript/mastodon/features/compose/components/announcements.js
import React from 'react'; import Immutable from 'immutable'; import Link from 'react-router-dom/Link'; import IconButton from '../../../components/icon_button'; const storageKey = 'announcements_dismissed'; class Announcements extends React.PureComponent { componentDidUpdate (prevProps, prevState) { if (prevState.dismissed !== this.state.dismissed) { try { localStorage.setItem(storageKey, JSON.stringify(this.state.dismissed)); } catch (e) {} } } componentWillMount () { try { const dismissed = JSON.parse(localStorage.getItem(storageKey)); this.state = { dismissed: Array.isArray(dismissed) ? dismissed : [] }; } catch (e) { this.state = { dismissed: [] }; } const announcements = []; announcements.push( { id: 13, icon: '/announcements/icon_2x_360.png', body: `【企画予告】 PaintsChainer × Pawoo AI三姉妹イラスト企画開催決定!`, link: [ { reactRouter: true, inline: false, href: '/statuses/51259014', body: '企画詳細はこちら!', }, ], }, { id: 1, icon: '/announcements/icon_2x_360.png', body: 'PawooのiOS・Android版アプリをリリースしました!!', link: [ { reactRouter: false, inline: true, href: 'https://itunes.apple.com/us/app/%E3%83%9E%E3%82%B9%E3%83%88%E3%83%89%E3%83%B3%E3%82%A2%E3%83%97%E3%83%AA-pawoo/id1229070679?l=ja&ls=1&mt=8', body: 'Appストア', }, { reactRouter: false, inline: true, href: 'https://play.google.com/store/apps/details?id=jp.pxv.pawoo&hl=ja', body: 'Google Playストア', }, ], }, { id: 7, icon: '/announcements/icon_2x_360.png', body: 'Pawooにどんなユーザーさんがいるのか見てみよう!', link: [ { reactRouter: true, inline: false, href: '/suggested_accounts', body: 'おすすめユーザー(実験中)', }, ], }, { id: 9, icon: '/announcements/icon_2x_360.png', body: '音楽版Pawooリリース!楽曲投稿や共有プレイリストで盛り上がろう!', link: [ { reactRouter: false, inline: false, href: 'https://music.pawoo.net/?ref=pawoo-announcements', body: 'Pawoo Music', }, ], } // NOTE: id: 13 まで使用した ); this.announcements = Immutable.fromJS(announcements); } handleDismiss = (event) => { const id = +event.currentTarget.getAttribute('title'); if (Number.isInteger(id)) { this.setState({ dismissed: [].concat(this.state.dismissed, id) }); } } render () { return ( <ul className='announcements'> {this.announcements.map(announcement => this.state.dismissed.indexOf(announcement.get('id')) === -1 && ( <li key={announcement.get('id')}> <div className='announcements__icon'> <img src={announcement.get('icon')} alt='' /> </div> <div className='announcements__body'> <div className='announcements__body__dismiss'> <IconButton icon='close' title={`${announcement.get('id')}`} onClick={this.handleDismiss} /> </div> <p>{announcement.get('body')}</p> <p> {announcement.get('link').map((link) => { const classNames = ['announcements__link']; const action = link.get('action'); if (link.get('inline')) { classNames.push('announcements__link-inline'); } if (link.get('reactRouter')) { return ( <Link key={link.get('href')} className={classNames.join(' ')} to={link.get('href')} onClick={action ? action : null}> {link.get('body')} </Link> ); } else { return ( <a className={classNames.join(' ')} key={link.get('href')} href={link.get('href')} target='_blank' onClick={action ? action : null}> {link.get('body')} </a> ); } })} </p> </div> </li> ))} </ul> ); } }; export default Announcements;
JavaScript
0
@@ -802,17 +802,17 @@ id: 1 -3 +4 ,%0A @@ -872,15 +872,8 @@ y: %60 -%E3%80%90%E4%BC%81%E7%94%BB%E4%BA%88%E5%91%8A%E3%80%91%0A Pain @@ -907,10 +907,9 @@ %E4%BC%81%E7%94%BB%E9%96%8B%E5%82%AC -%E6%B1%BA%E5%AE%9A +%E4%B8%AD %EF%BC%81%60,%0A @@ -1028,15 +1028,15 @@ es/5 -1259014 +2025880 ',%0A @@ -2378,17 +2378,17 @@ E: id: 1 -3 +4 %E3%81%BE%E3%81%A7%E4%BD%BF%E7%94%A8%E3%81%97%E3%81%9F%0A
3bccc8dab5f20e671697ed5499846aa49a258673
teste frontend
frontend/app/app.config.js
frontend/app/app.config.js
angular. module('MatWeb'). config(['$locationProvider', '$routeProvider', '$http', function config($locationProvider, $routeProvider, $http) { $locationProvider.html5Mode(true).hashPrefix('!'); $http.defaults.headers.common.Authorization = "" $http.defaults.headers.post = { 'Content-Type' : 'application/json; charset=UTF-8' } $routeProvider.otherwise('/'); } ]);
JavaScript
0.000001
@@ -77,16 +77,24 @@ , '$http +Provider ',%0A f @@ -148,16 +148,24 @@ r, $http +Provider ) %7B%0A @@ -227,32 +227,40 @@ %0A $http +Provider .defaults.header @@ -298,16 +298,24 @@ $http +Provider .default
758f6c5d0ab2fce3800968841d3c6ec01341ea89
Make longlist close when another select2 is clicked on.
www/client/longlist.js
www/client/longlist.js
// layerLists.js // Manage the layer lists. var app = app || {}; (function (hex) { // How many layer results should we display at once? var SEARCH_PAGE_SIZE = 10, $search; function make_browse_ui(layer_name) { // Returns a jQuery element to represent the layer with the given name in // the browse panel. // This holds a jQuery element that's the root of the structure we're // building. var root = $("<div/>").addClass("layer-entry"); root.data("layer-name", layer_name); // Put in the layer name in a div that makes it wrap. root.append($("<div/>").addClass("layer-name").text(layer_name)); // Put in a layer metadata container div var metadata_container = $("<div/>"); Layer.fill_metadata(metadata_container, layer_name); root.append(metadata_container); return root; } updateLonglist = function() { // Make the layer browse UI reflect the current list of layers in sorted // order. // Re-sort the sorted list that we maintain sort_layers(); // Close the select if it was open, forcing the data to refresh when it // opens again. $("#search").select2("close"); } initLayerLists = function () { $search = $("#search"); // Set up the layer search $search.select2({ placeholder: "Search Attributes...", //closeOnSelect: false, doesn't work, maybe because of old version of select2? query: function(query) { // Given a select2 query object, call query.callback with an object // with a "results" array. // This is the array of result objects we will be sending back. var results = []; // Get where we should start in the layer list, from select2's // infinite scrolling. var start_position = 0; if(query.context != undefined) { start_position = query.context; } var displayLayers = Session.get('displayLayers'), sortedLayers = Session.get('sortedLayers'); for (var i = start_position; i < sortedLayers.length; i++) { // Check for the sort layer being in the display layers // and the sort term in the layer name if (displayLayers.indexOf(sortedLayers[i]) > -1 && sortedLayers[i].toLowerCase().indexOf( query.term.toLowerCase()) > -1) { // Query search term is in this layer's name. Add a select2 // record to our results. Don't specify text: our custom // formatter looks up by ID and makes UI elements // dynamically. results.push({ id: sortedLayers[i] }); if(results.length >= SEARCH_PAGE_SIZE) { // Page is full. Send it on. break; } } } // Give the results back to select2 as the results parameter. query.callback({ results: results, // Say there's more if we broke out of the loop. more: i < Session.get('sortedLayers').length, // If there are more results, start after where we left off. context: i + 1 }); }, formatResult: function(result, container, query) { // Given a select2 result record, the element that our results go // in, and the query used to get the result, return a jQuery element // that goes in the container to represent the result. // Get the layer name, and make the browse UI for it. return make_browse_ui(result.id); }, }); // Make the bottom of the list within the main window $search.parent().on('select2-open', function () { var results = $('#select2-drop .select2-results'); results.css('max-height', $(window).height() - results.offset().top - 15); // Allow the rest of the UI to remain active $('#select2-drop-mask').css('display', 'none'); }); // Handle result selection $search.on("select2-selecting", function(event) { // The select2 id of the thing clicked (the layer's name) is event.val var layer_name = event.val; // User chose this layer. Add it to the global shortlist. Shortlist.ui_and_list_add(layer_name); // Don't actually change the selection. // This keeps the dropdown open when we click. event.preventDefault(); }); // Make the dropdown close if there is a click anywhere on the screen // other than the dropdown and search box $(window).on('mousedown', function (ev) { $("#search").select2("close"); }); }; })(app);
JavaScript
0
@@ -4603,138 +4603,8 @@ 5);%0A - %0A // Allow the rest of the UI to remain active%0A $('#select2-drop-mask').css('display', 'none');%0A
2becfd026bbbf8eaa09c0c662d922ea1f89bc434
add proptypes shim for popup
react/features/device-selection/popup.js
react/features/device-selection/popup.js
/* global JitsiMeetJS */ import 'aui-css'; import 'aui-experimental-css'; import DeviceSelectionPopup from './DeviceSelectionPopup'; let deviceSelectionPopup; window.init = i18next => { JitsiMeetJS.init({}).then(() => { deviceSelectionPopup = new DeviceSelectionPopup(i18next); }); }; window.addEventListener('beforeunload', () => deviceSelectionPopup.close());
JavaScript
0
@@ -69,16 +69,115 @@ -css';%0A%0A +// FIXME: remove once atlaskit work with React 16.%0Aimport '../base/react/prop-types-polyfill.js';%0A%0A import D
f60c71f790a68f21fd41a04c7e8238693c962d26
Print all summaries
agolo-slackbot.js
agolo-slackbot.js
var validUrl = require('valid-url'); var RtmClient = require('@slack/client').RtmClient; var RestClient = require('node-rest-client').Client; var CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS; var RTM_EVENTS = require('@slack/client').RTM_EVENTS; var TOKEN, AGOLO_URL; var HEROKU = false; // Determine which environment we're running in if (process.env.SLACK_TOKEN && process.env.AGOLO_URL) { // For Heroku TOKEN = process.env.SLACK_TOKEN; AGOLO_URL = process.env.AGOLO_URL; HEROKU = true; console.log("Slack token: " + TOKEN); } else { // For local var SlackSecret = require('./slack-secrets.js'); TOKEN = SlackSecret.slackToken(); AGOLO_URL = SlackSecret.agoloURL(); } var LOG_LEVEL = 'debug'; var slackClient = new RtmClient(TOKEN, {logLevel: LOG_LEVEL}); var restClient = new RestClient(); var bot; // Track bot user .. for detecting messages by yourself // Summarize a given URL and call the given callback with the result var summarize = function(url, typingInterval, callback) { var result = "Here's Agolo's summary of " + url + "\n"; var args = { data: { "coref":"false", "summary_length":"3", "articles":[      { "type":"article", "url": url, "metadata":{} } ]}, headers: { "Content-Type": "application/json" } }; console.log("Sending Agolo request!"); console.log(args); restClient.post(AGOLO_URL, args, function (data, rawResponse) { console.log("Agolo response: "); console.log(data); clearInterval(typingInterval); if (data && data.summary && data.summary[0].sentences) { var sentences = data.summary[0].sentences; console.log("sentences: \n", sentences); // Quote each line for (var i = 0; i < sentences.length; i++) { sentences[i] = ">" + sentences[i]; } result = result + sentences.join("\n-\n"); callback(result); } }); } slackClient.on(CLIENT_EVENTS.RTM.AUTHENTICATED, function (rtmStartData) { bot = rtmStartData.self.id; }); slackClient.on('open', function() { console.log('Connected'); }); slackClient.on("message", function(message) { if (message.user == bot) return; // Ignore bot's own messages var text = message.text; var channel = message.channel; var attachments = message.attachments; if (text) { var urlRegex = /<([^\s]+)>/; var matches = text.match(urlRegex); if (matches) { // Start at index 1 because 0 has the entire match, not just the group for (var i = 0; i < matches.length; i++) { var candidate = matches[i]; if (validUrl.isWebUri(candidate)) { // Show typing indicator as we summarize var sendTypingMessage = function() { slackClient._send({ id: 1, type: "typing", channel: channel }); } var TYPING_MESSAGE_SECS = 3; var typingInterval = setInterval(function() { sendTypingMessage() }, TYPING_MESSAGE_SECS * 1000); summarize(candidate, typingInterval, function(result) { slackClient.sendMessage(result, channel); }); } } } } }); slackClient.start(); if (HEROKU) { // To prevent Heroku from crashing us. https://github.com/slackhq/node-slack-client/issues/39 http = require('http'); handle = function(req, res) {return res.end("hit"); }; server = http.createServer(handle); server.listen(process.env.PORT || 5000); if (process.env.HEROKU_APP_URL) { var URL = process.env.HEROKU_APP_URL; if (URL.indexOf("http") != 0) { URL = "http://" + URL; } console.log("Heroku app URL: " + URL); var heartbeat = function() { restClient.get(URL, function(){ console.log("heartbeat!"); }); }; heartbeat(); var HEARTBEAT_INTERVAL_MINS = 5; setInterval(heartbeat, HEARTBEAT_INTERVAL_MINS * 60 * 1000); } }
JavaScript
0.999998
@@ -1532,26 +1532,109 @@ mary - && data.summary%5B0 +) %7B%0A%09%09%09for (var summIdx = 0; summIdx %3C data.summary.length; summIdx++) %7B%0A%09%09%09%09if (data.summary%5BsummIdx %5D.se @@ -1644,16 +1644,18 @@ nces) %7B%0A +%09%09 %09%09%09var s @@ -1678,17 +1678,23 @@ summary%5B -0 +summIdx %5D.senten @@ -1699,16 +1699,18 @@ ences;%0A%0A +%09%09 %09%09%09conso @@ -1726,16 +1726,44 @@ entences + for summary %22 + summIdx + %22 : %5Cn%22, s @@ -1777,16 +1777,18 @@ s);%0A%0A%09%09%09 +%09%09 // Quote @@ -1798,16 +1798,18 @@ ch line%0A +%09%09 %09%09%09for ( @@ -1852,16 +1852,18 @@ ) %7B%0A%09%09%09%09 +%09%09 sentence @@ -1896,14 +1896,18 @@ %0A%09%09%09 +%09%09 %7D%0A%0A%09%09%09 +%09 +%09 resu @@ -1949,16 +1949,18 @@ %22);%0A%0A%09%09%09 +%09%09 callback @@ -1969,16 +1969,27 @@ esult);%0A +%09%09%09%09%7D%0A%09%09%09%7D%0A %09%09%7D%0A%09%7D);
cda29a3515586eec7128e9441a289c472e73de78
comment removal
event_handler.js
event_handler.js
const config = require('./userconfig/config.json'); // Import configuration const moment = require('moment'); // Part of log writing var timestamp = moment().format('DD/MM/YYYY HH:mm:ss'); module.exports = { // Export event functions "ready": function ready(selfbot, chalk) { // Once the selfbot is ready (fully booted) ... console.log(`[${timestamp}]${chalk.green("[POWER]")} motiful ready!`); // ...console log a ready message. selfbot.user.setStatus('invisible'); /* Set motiful's status to invisible, so you won't appear as online if you actually aren't but have motiful running. If you ARE online, the online/idle/dnd status of your discord client will overweigh motiful's invisible status, meaning that this won't make you permanently display as invisible. */ }, "error": function error(selfbot, error, chalk) { // If a "serious connection error" occurs... timestamp = moment().format('DD/MM/YYYY HH:mm:ss'); console.log(`[${timestamp}]${chalk.red("[CONNECTION]")} motiful encountered a "serious connection error! | ${error.code}`); // ...console log a notifcation. }, "disconnect": function disconnect(selfbot, error, chalk) { // If the selfbot gets disconnected... timestamp = moment().format('DD/MM/YYYY HH:mm:ss'); console.log(`[${timestamp}]${chalk.red("[CONNECTION]")} motiful was disconnected! | ${error.code}`); // ...console log a notifcation. if(error.code == 1000) { console.log(`[${timestamp}]${chalk.green("[POWER]")} Automatically restarting...`); selfbot.destroy().then(() => selfbot.login(config.token)); // Restart selfbot if disconnect code is 1000 (gracefully exited) because it won't reconnect automatically }; }, };
JavaScript
0
@@ -48,32 +48,8 @@ n'); - // Import configuration %0Acon @@ -82,31 +82,8 @@ t'); - // Part of log writing %0Avar @@ -158,34 +158,8 @@ = %7B - // Export event functions %0A%09%22r @@ -201,56 +201,8 @@ k) %7B - // Once the selfbot is ready (fully booted) ... %0A%09%09c @@ -274,43 +274,8 @@ !%60); - // ...console log a ready message. %0A%09%09s @@ -317,313 +317,55 @@ %0A%09%09/ -*%0A%09%09Set motiful's status to invisible, so you won't appear as online if you actually aren't but have motiful running.%0A%09%09If you ARE online, the online/idle/dnd status of your discord client will overweigh motiful's invisible status, meaning%0A%09%09that this won't make you permanently display as invisible.%0A%09%09*/ +/ appear offline when not online as actual user %0A%09%7D, @@ -418,53 +418,8 @@ k) %7B - // If a %22serious connection error%22 occurs... %0A%09%09t @@ -598,41 +598,8 @@ %7D%60); - // ...console log a notifcation. %0A%09%7D, @@ -662,47 +662,8 @@ k) %7B - // If the selfbot gets disconnected... %0A%09%09t @@ -819,41 +819,8 @@ %7D%60); - // ...console log a notifcation. %0A%09%09i
c502d5ad22a621c4f44fb2c2ce44ad13cc6c5235
refactor `addTab` function (tab id now is the same as patch id) and add same reaction for PATCH_DELETE as for TAB_CLOSE. So now when patch is deleted — tab is closed and switched to another one.
packages/xod-client/src/editor/reducer.js
packages/xod-client/src/editor/reducer.js
import R from 'ramda'; import { ENTITY, generateId } from 'xod-core'; import { EDITOR_DESELECT_ALL, EDITOR_SELECT_NODE, EDITOR_SELECT_PIN, EDITOR_SELECT_LINK, EDITOR_SET_MODE, EDITOR_SET_SELECTED_NODETYPE, EDITOR_SWITCH_PATCH, TAB_CLOSE, TAB_SORT, } from './actionTypes'; import { PROJECT_CREATE, PROJECT_LOAD_DATA, PROJECT_ONLY_LOAD_DATA, NODE_DELETE, LINK_DELETE, } from '../project/actionTypes'; const addSelection = (entityName, action, state) => { const select = { entity: entityName, id: action.payload.id, }; const newSelection = R.append(select, state.selection); return R.set(R.lensProp('selection'), newSelection, state); }; const addTab = (state, action) => { if (!(action.payload && action.payload.id)) { return state; } const tabs = R.prop('tabs')(state); const lastIndex = R.reduce( (acc, tab) => R.pipe( R.prop('index'), R.max(acc) )(tab), -Infinity, R.values(tabs) ); const newIndex = R.inc(lastIndex); const newId = generateId(); return R.assocPath(['tabs', newId], { id: newId, patchId: action.payload.id, index: newIndex, }, state); }; const applyTabSort = (tab, payload) => { if (R.not(R.has(tab.id, payload))) { return tab; } return R.assoc('index', payload[tab.id].index, tab); }; const tabHasPatch = (state, patchId) => R.find(R.propEq('patchId', patchId))(R.values(state.tabs)); const resetCurrentPatchId = (reducer, state, payload) => { const newState = R.assoc('tabs', [], state); const firstPatchId = R.pipe( JSON.parse, R.prop('patches'), R.values, R.head, R.propOr(null, 'id') )(payload); return reducer(newState, { type: EDITOR_SWITCH_PATCH, payload: { id: firstPatchId, }, }); }; const editorReducer = (state = {}, action) => { switch (action.type) { case NODE_DELETE: case LINK_DELETE: case EDITOR_DESELECT_ALL: return R.merge(state, { selection: [], linkingPin: null, }); case EDITOR_SELECT_NODE: return addSelection(ENTITY.NODE, action, state); case EDITOR_SELECT_LINK: return addSelection(ENTITY.LINK, action, state); case EDITOR_SELECT_PIN: return R.assoc('linkingPin', action.payload, state); case EDITOR_SET_MODE: return R.assoc('mode', action.payload.mode, state); case EDITOR_SET_SELECTED_NODETYPE: return R.assoc('selectedNodeType', action.payload.id, state); case PROJECT_CREATE: { const newState = R.assoc('tabs', [], state); return editorReducer(newState, { type: EDITOR_SWITCH_PATCH, payload: { id: action.payload.mainPatchId, }, }); } case PROJECT_LOAD_DATA: return resetCurrentPatchId(editorReducer, state, action.payload); case PROJECT_ONLY_LOAD_DATA: return resetCurrentPatchId(editorReducer, state, action.payload); case EDITOR_SWITCH_PATCH: { let newState = state; if (!tabHasPatch(state, action.payload.id)) { newState = addTab(newState, action); } return R.assoc('currentPatchId', action.payload.id, newState); } case TAB_CLOSE: return R.compose( R.converge( R.assoc('currentPatchId'), [ R.compose( // get patch id from last of remaining tabs R.propOr(null, 'patchId'), R.last, R.values, R.prop('tabs') ), R.identity, ] ), R.dissocPath(['tabs', action.payload.id.toString()]) )(state); case TAB_SORT: return R.assoc( 'tabs', R.reduce( (p, cur) => R.assoc(cur.id, applyTabSort(cur, action.payload), p), {}, R.values(state.tabs) ), state ); default: return state; } }; export default editorReducer;
JavaScript
0
@@ -35,20 +35,8 @@ TITY -, generateId %7D f @@ -346,16 +346,32 @@ D_DATA,%0A + PATCH_DELETE,%0A NODE_D @@ -1020,28 +1020,35 @@ nst -newId = generateId() +patchId = action.payload.id ;%0A%0A @@ -1076,19 +1076,21 @@ 'tabs', -new +patch Id%5D, %7B%0A @@ -1096,19 +1096,21 @@ id: -new +patch Id,%0A @@ -1116,35 +1116,16 @@ patchId -: action.payload.id ,%0A in @@ -3129,32 +3129,55 @@ ewState);%0A %7D%0A + case PATCH_DELETE:%0A case TAB_CLO
752907c6acacb304b89c6c4dd0d04c89a7d2b910
add minLayoutPosition option
src/validate.js
src/validate.js
var Joi = require('joi'); var Promise = require('bluebird'); var stepsSchema = require('screener-runner/src/validate').stepsSchema; var resolutionSchema = require('screener-runner/src/validate').resolutionSchema; var browsersSchema = require('screener-runner/src/validate').browsersSchema; var sauceSchema = require('screener-runner/src/validate').sauceSchema; exports.storybookConfig = function(value) { var schema = Joi.object().keys({ apiKey: Joi.string().required(), projectRepo: Joi.string().max(100).required(), storybookConfigDir: Joi.string().required(), storybookStaticDir: Joi.string(), storybookPort: Joi.number().required(), storybook: Joi.array().min(0).items( Joi.object().keys({ kind: Joi.string().required(), stories: Joi.array().min(1).items( Joi.object().keys({ name: Joi.string().required(), steps: stepsSchema }) ).required() }) ).required(), build: Joi.string().max(40), branch: Joi.string().max(100), resolution: resolutionSchema, resolutions: Joi.array().min(1).items( resolutionSchema ), browsers: browsersSchema, cssAnimations: Joi.boolean(), ignore: Joi.string(), includeRules: Joi.array().min(0).items( Joi.string(), Joi.object().type(RegExp) ), excludeRules: Joi.array().min(0).items( Joi.string(), Joi.object().type(RegExp) ), initialBaselineBranch: Joi.string().max(100), diffOptions: Joi.object().keys({ structure: Joi.boolean(), layout: Joi.boolean(), style: Joi.boolean(), content: Joi.boolean() }), sauce: sauceSchema, failureExitCode: Joi.number().integer().min(0).max(255).default(1) }).without('resolutions', ['resolution']).with('browsers', ['sauce']).required(); var validator = Promise.promisify(Joi.validate); return validator(value, schema); };
JavaScript
0.000001
@@ -1642,16 +1642,72 @@ oolean() +,%0A minLayoutPosition: Joi.number().integer().min(0) %0A %7D),
f420d61c2f120643c6a9831ccf054ae2104bdbfe
rework the listeners seeking an abstraction that provides GC
findAnything/findAnything.js
findAnything/findAnything.js
// See license.txt, BSD // Copyright 2011 Google, Inc. author: [email protected] define(['../lib/domplate/lib/domplate'], function findAnythingFactory(DOMPLATE) { var anyThingBar = new thePurple.PurplePart('findAnything'); anyThingBar.initialize = function() { this.buildDomplate(); this.renderDomplate(); this.addListeners(); }; anyThingBar.buildDomplate = function() { with (DOMPLATE.tags) { this.template = DOMPLATE.domplate({ tag: DIV({'id': 'findAnythingToolbar','class':'purpleToolbar'}, FOR('preButton', '$preButtons', TAG("$buttonTag", {button: "$button"}) ), DIV({'id': 'findAnything', 'class':'omniboxLikeLeft omniboxLike omniboxLikeRight'}, IMG({'id': 'findAnythingIcon', 'class':'findAnythingIcon omniboxLikeLeft', 'src':'../ui/icons/o2_http_query.png'} ), DIV({'id':'findAnythingBackground'}, INPUT({'id':'findAnythingCompletion', 'value':'.js'}), DIV({'id':'findAnythingNotify'}, 'Resource and event counts here'), INPUT({'id':'findAnythingInput', 'value':'.js'}) ) ) ), }); } }; anyThingBar.renderDomplate = function() { var html = this.template.tag.render({ preButtons: [], }); var body = document.getElementsByTagName('body')[0]; body.innerHTML = html; this.resize(); }; anyThingBar.addListeners = function () { window.addEventListener('resize', this.resize, true); }; // ------------------------------------------------------------------------ // Output anyThingBar.resize = function () { var toolbar = document.getElementById('findAnythingToolbar'); var availableWidth = toolbar.offsetWidth; // remove the width of childern TODO availableWidth -= 24*4; this.setWidth('findAnythingBackground', availableWidth); this.setWidth('findAnythingCompletion', availableWidth); this.setWidth('findAnythingInput', availableWidth); }; anyThingBar.setWidth = function(id, availableWidth) { var elt = document.getElementById(id); elt.style.width = availableWidth +"px"; }; // ------------------------------------------------------------------------- // Input anyThingBar.eventsToElements = { keypress: makeListener('#findAnythingInput', function(event) { console.log("findAnything.keypress ", event.charCode); }.bind(anyThingBar)), }; thePurple.registerPart(anyThingBar); anyThingBar.onUnload = (function() { window.removeEventListener('unload', anyThingBar.onUnload, false); anyThingBar.removeListeners(); }).bind(anyThingBar); window.addEventListener('unload', anyThingBar.onLoad, false); anyThingBar.initialize(); anyThingBar.removeListeners = addListeners(anyThingBar.eventsToElements); function makeListener(selector, handler) { handler.selector = selector; return handler; } function addListeners(eventHandlers) { Object.keys(eventHandlers).forEach(function on(prop) { var handler = eventHandlers[prop]; var selector = handler.selector; var elt = document.querySelector(selector); elt.addEventListener(prop, handler, false); handler.element = elt; }); return makeRemoveListeners(eventHandlers); } function makeRemoveListeners(eventHandlers) { return function removeListeners() { Object.keys(eventHandlers).forEach(function off(prop) { var handler = eventHandlers[prop]; var elt = handler.element; elt.removeEventListener(prop, handler, false); }); } } return anyThingBar; });
JavaScript
0.000008
@@ -332,35 +332,8 @@ ();%0A - this.addListeners();%0A @@ -1487,121 +1487,8 @@ %0A - anyThingBar.addListeners = function () %7B%0A window.addEventListener('resize', this.resize, true);%0A %7D;%0A%0A @@ -2150,32 +2150,34 @@ h +%22px%22;%0A %7D;%0A +%0A%0A %0A // ---- @@ -2255,24 +2255,205 @@ // Input%0A +%0A anyThingBar.makeListener = function(selector, handler) %7B%0A var boundHandler = handler.bind(this);%0A boundHandler.selector = selector;%0A return boundHandler;%0A %7D%0A%0A anyThing @@ -2493,16 +2493,28 @@ ypress: +anyThingBar. makeList @@ -2628,22 +2628,66 @@ %0A %7D -.bind( +),%0A resize: anyThingBar.makeListener(window, anyThing @@ -2689,17 +2689,23 @@ ThingBar -) +.resize ),%0A %7D @@ -3100,113 +3100,8 @@ %0A %0A - function makeListener(selector, handler) %7B%0A handler.selector = selector;%0A return handler;%0A %7D%0A %0A fu @@ -3272,24 +3272,68 @@ r.selector;%0A + if (typeof selector === 'string') %7B%0A var el @@ -3370,16 +3370,18 @@ ector);%0A + el @@ -3418,24 +3418,26 @@ er, false);%0A + handle @@ -3453,16 +3453,133 @@ = elt;%0A + %7D else %7B%0A selector.addEventListener(prop, handler, false);%0A handler.element = selector;%0A %7D%0A%0A %7D);%0A
80934ea23253227d37d7e9b978c79733508258a8
Fix build.
build/post-compile.js
build/post-compile.js
#!/usr/bin/env node ;(function() { 'use strict'; /** The Node.js filesystem module */ var fs = require('fs'); /** The minimal license/copyright template */ var licenseTemplate = [ '/**', ' * @license', ' * Lo-Dash <%= VERSION %> lodash.com/license', ' * Underscore.js 1.4.4 underscorejs.org/LICENSE', ' */' ].join('\n'); /*--------------------------------------------------------------------------*/ /** * Post-process a given minified Lo-Dash `source`, preparing it for * deployment. * * @param {String} source The source to process. * @returns {String} Returns the processed source. */ function postprocess(source) { // remove copyright header source = source.replace(/^\/\**[\s\S]+?\*\/\n/, ''); // correct overly aggressive Closure Compiler advanced optimization source = source .replace(/(document[^&]+&&)\s*(?:\w+|!\d)/, '$1!({toString:0}+"")') .replace(/"\t"/g, '"\\t"') .replace(/"[^"]*?\\u180e[^"]*?"/g, '" \\t\\x0B\\f\\xa0\\ufeff' + '\\n\\r\\u2028\\u2029' + '\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000"' ); // flip `typeof` expressions to help optimize Safari and // correct the AMD module definition for AMD build optimizers // (e.g. from `"number" == typeof x` to `typeof x == "number") source = source.replace(/(\w)?("[^"]+")\s*([!=]=)\s*(typeof(?:\s*\([^)]+\)|\s+[.\w]+(?!\[)))/g, function(match, other, type, equality, expression) { return (other ? other + ' ' : '') + expression + equality + type; }); // add a space so `define` is detected by the Dojo builder source = source.replace(/.define\(/, function(match) { return (/^\S/.test(match) ? ' ' : '') + match; }); // add trailing semicolon if (source) { source = source.replace(/[\s;]*?(\s*\/\/.*\s*|\s*\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/\s*)*$/, ';$1'); } // exit early if version snippet isn't found var snippet = /VERSION\s*[=:]\s*([\'"])(.*?)\1/.exec(source); if (!snippet) { return source; } // add new copyright header var version = snippet[2]; source = licenseTemplate.replace('<%= VERSION %>', version) + '\n;' + source; return source; } /*--------------------------------------------------------------------------*/ // expose `postprocess` if (module != require.main) { module.exports = postprocess; } else { // read the Lo-Dash source file from the first argument if the script // was invoked directly (e.g. `node post-compile.js source.js`) and write to // the same file (function() { var options = process.argv; if (options.length < 3) { return; } var filePath = options[options.length - 1], source = fs.readFileSync(filePath, 'utf8'); fs.writeFileSync(filePath, postprocess(source), 'utf8'); }()); } }());
JavaScript
0.00016
@@ -1730,17 +1730,20 @@ ce(/ -. +(.)( define%5C( /, f @@ -1738,16 +1738,17 @@ define%5C( +) /, funct @@ -1756,16 +1756,33 @@ on(match +, prelude, define ) %7B%0A @@ -1789,16 +1789,26 @@ return + prelude + (/%5E%5CS/. @@ -1812,21 +1812,23 @@ S/.test( -match +prelude ) ? ' ' @@ -1835,21 +1835,23 @@ : '') + -match + define ;%0A %7D)
0b8d192e64d8d3f7343655901d668b7f3f852557
Fix unknown .getDOMNode() call
fields/types/html/HtmlField.js
fields/types/html/HtmlField.js
import _ from 'lodash'; import Field from '../Field'; import React from 'react'; import tinymce from 'tinymce'; import { FormInput } from 'elemental'; /** * TODO: * - Remove dependency on underscore */ var lastId = 0; function getId () { return 'keystone-html-' + lastId++; } // Workaround for #2834 found here https://github.com/tinymce/tinymce/issues/794#issuecomment-203701329 function removeTinyMCEInstance (editor) { var oldLength = tinymce.editors.length; tinymce.remove(editor); if (oldLength === tinymce.editors.length) { tinymce.editors.remove(editor); } } module.exports = Field.create({ displayName: 'HtmlField', statics: { type: 'Html', }, getInitialState () { return { id: getId(), isFocused: false, }; }, initWysiwyg () { if (!this.props.wysiwyg) return; var self = this; var opts = this.getOptions(); opts.setup = function (editor) { self.editor = editor; editor.on('change', self.valueChanged); editor.on('focus', self.focusChanged.bind(self, true)); editor.on('blur', self.focusChanged.bind(self, false)); }; this._currentValue = this.props.value; tinymce.init(opts); }, componentDidUpdate (prevProps, prevState) { if (prevState.isCollapsed && !this.state.isCollapsed) { this.initWysiwyg(); } if (!_.isEqual(this.props.currentDependencies, prevProps.currentDependencies)) { if (_.isEqual(prevProps.dependsOn, prevProps.currentDependencies)) { var instance = tinymce.get(prevState.id); if (instance) { removeTinyMCEInstance(instance); } } if (_.isEqual(this.props.dependsOn, this.props.currentDependencies)) { this.initWysiwyg(); } } }, componentDidMount () { this.initWysiwyg(); }, componentWillReceiveProps (nextProps) { if (this.editor && this._currentValue !== nextProps.value) { this.editor.setContent(nextProps.value); } }, focusChanged (focused) { this.setState({ isFocused: focused, }); }, valueChanged () { var content; if (this.editor) { content = this.editor.getContent(); } else if (this.refs.editor) { content = this.refs.editor.getDOMNode().value; } else { return; } this._currentValue = content; this.props.onChange({ path: this.props.path, value: content, }); }, getOptions () { var plugins = ['code', 'link']; var options = Object.assign( {}, Keystone.wysiwyg.options, this.props.wysiwyg ); var toolbar = options.overrideToolbar ? '' : 'bold italic | alignleft aligncenter alignright | bullist numlist | outdent indent | removeformat | link '; var i; if (options.enableImages) { plugins.push('image'); toolbar += ' | image'; } if (options.enableCloudinaryUploads || options.enableS3Uploads) { plugins.push('uploadimage'); toolbar += options.enableImages ? ' uploadimage' : ' | uploadimage'; } if (options.additionalButtons) { var additionalButtons = options.additionalButtons.split(','); for (i = 0; i < additionalButtons.length; i++) { toolbar += (' | ' + additionalButtons[i]); } } if (options.additionalPlugins) { var additionalPlugins = options.additionalPlugins.split(','); for (i = 0; i < additionalPlugins.length; i++) { plugins.push(additionalPlugins[i]); } } if (options.importcss) { plugins.push('importcss'); var importcssOptions = { content_css: options.importcss, importcss_append: true, importcss_merge_classes: true, }; Object.assign(options.additionalOptions, importcssOptions); } if (!options.overrideToolbar) { toolbar += ' | code'; } var opts = { selector: '#' + this.state.id, toolbar: toolbar, plugins: plugins, menubar: options.menubar || false, skin: options.skin || 'keystone', }; if (this.shouldRenderField()) { opts.uploadimage_form_url = options.enableS3Uploads ? Keystone.adminPath + '/api/s3/upload' : Keystone.adminPath + '/api/cloudinary/upload'; } else { Object.assign(opts, { mode: 'textareas', readonly: true, menubar: false, toolbar: 'code', statusbar: false, }); } if (options.additionalOptions) { Object.assign(opts, options.additionalOptions); } return opts; }, getFieldClassName () { var className = this.props.wysiwyg ? 'wysiwyg' : 'code'; return className; }, renderField () { var className = this.state.isFocused ? 'is-focused' : ''; var style = { height: this.props.height, }; return ( <div className={className}> <FormInput multiline ref="editor" style={style} onChange={this.valueChanged} id={this.state.id} className={this.getFieldClassName()} name={this.props.path} value={this.props.value} /> </div> ); }, renderValue () { return <FormInput multiline noedit value={this.props.value} />; }, });
JavaScript
0.000004
@@ -1964,16 +1964,21 @@ anged ( +event ) %7B%0A%09%09va @@ -2061,102 +2061,41 @@ lse -if (this.refs.editor) %7B%0A%09%09%09content = this.refs.editor.getDOMNode().value;%0A%09%09%7D else %7B%0A%09%09%09return +%7B%0A%09%09%09content = event.target.value ;%0A%09%09 @@ -4441,21 +4441,8 @@ line - ref=%22editor%22 sty
5993e26d58c3bc099bdc01b71166fe8814289667
Delete references field to fix userId and groupId bugs
server/migrations/20170625133452-create-message.js
server/migrations/20170625133452-create-message.js
module.exports = { up: (queryInterface, Sequelize) => queryInterface.createTable('Messages', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, content: { type: Sequelize.STRING }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE }, userId: { type: Sequelize.INTEGER, onDelete: 'CASCADE', references: { model: 'Users', key: 'id', as: 'userId', }, }, groupId: { type: Sequelize.INTEGER, onDelete: 'CASCADE', references: { model: 'Groups', key: 'id', as: 'groupId', }, }, }), down(queryInterface /* , Sequelize */) { queryInterface.dropTable('Messages'); } };
JavaScript
0
@@ -487,279 +487,87 @@ ADE' -,%0A references: %7B%0A model: 'Users',%0A key: 'id',%0A as: 'userId',%0A %7D,%0A %7D,%0A groupId: %7B%0A type: Sequelize.INTEGER,%0A onDelete: 'CASCADE',%0A references: %7B%0A model: 'Groups',%0A key: 'id',%0A as: 'groupId',%0A %7D, +%0A %7D,%0A groupId: %7B%0A type: Sequelize.INTEGER,%0A onDelete: 'CASCADE' %0A
1adbb91db663c28a9c2c8eb49fe6e39b68aaf1f6
Add google+ sdk library
angular-auth.js
angular-auth.js
/** * ngAuth 0.0.1 * (c) 2014 Sahat Yalkabov <[email protected]> * License: MIT */ // TODO: Enable CORS, separate server from client, Gulp server runner // TODO: Provider return object, underscore private functions < 10loc angular.module('ngAuth', []) .provider('Auth', function() { var config = this.config = { logoutRedirect: '/', loginRedirect: '/', loginUrl: '/auth/login', signupUrl: '/auth/signup', signupRedirect: '/login', providers: { facebook: { url: '/auth/facebook', appId: null, scope: null, responseType: 'token', locale: 'en_US', version: 'v2.0' }, google: { clientId: null, scope: null, redirectUri: null, responseType: 'token', authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth', verificationEndpoint: 'https://accounts.google.com/o/oauth2/token' } } }; this.setProvider = function(provider, params) { angular.extend(config.providers[provider], params); }; this.$get = function($http, $location, $rootScope, $alert, $q, $injector, $window, $document) { // Local var token = $window.localStorage.token; if (token) { var payload = JSON.parse($window.atob(token.split('.')[1])); if (Date.now() > payload.exp) { $window.alert('Token has expired'); delete $window.localStorage.token; } else { $rootScope.currentUser = payload.user; console.log($rootScope.currentUser) } } // Initialzie Facebook if (config.providers.facebook.appId) { $window.fbAsyncInit = function() { FB.init(config.providers.facebook); }; (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/" + config.providers.facebook.locale + "/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); } // Google if (config.providers.google.clientId) { } return { loginOauth: function(provider) { provider = provider.trim().toLowerCase(); // if (provider === 'facebook') { // // } else if (provider === 'google') { // // } else if (provider === 'twitter') { // // } else { // throw Error('Invalid Provider') // } // switch (provider) { case 'facebook': var scope = config.providers.facebook.scope.join(','); FB.login(function(response) { FB.api('/me', function(profile) { var info = { signedRequest: response.authResponse.signedRequest, profile: profile }; $http.post(config.providers.facebook.url, info).success(function(token) { var payload = JSON.parse($window.atob(token.split('.')[1])); $window.localStorage.token = token; $rootScope.currentUser = payload.user; $location.path(config.loginRedirect); }); }); }, { scope: scope }); break; case 'google': console.log('google signin'); break; default: break; } }, login: function(user) { return $http.post(config.loginUrl, user).success(function(data) { $window.localStorage.token = data.token; var token = $window.localStorage.token; var payload = JSON.parse($window.atob(token.split('.')[1])); $rootScope.currentUser = payload.user; $location.path(config.loginRedirect); }); }, signup: function(user) { return $http.post(config.signupUrl, user).success(function() { $location.path(config.signupRedirect); }); }, logout: function() { delete $window.localStorage.token; $rootScope.currentUser = null; $location.path(config.logoutRedirect); } }; }; }) .factory('authInterceptor', function($q, $window, $location) { return { request: function(config) { if ($window.localStorage.token) { config.headers.Authorization = 'Bearer ' + $window.localStorage.token; } return config; }, responseError: function(response) { if (response.status === 401 || response.status === 403) { $location.path('/login'); } return $q.reject(response); } } }) .config(function($httpProvider) { $httpProvider.interceptors.push('authInterceptor'); }) .run(function($rootScope, $location) { $rootScope.$on('$routeChangeStart', function(event, current, previous) { if($rootScope.currentUser && (current.originalPath === '/login' || current.originalPath === '/signup')) { $location.path('/'); } if (current.authenticated && !$rootScope.currentUser) { $location.path('/login'); } }); });
JavaScript
0
@@ -2217,16 +2217,27 @@ // + Initialize Google%0A @@ -2232,16 +2232,16 @@ Google%0A - if @@ -2274,25 +2274,322 @@ clientId) %7B%0A + (function() %7B%0A var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;%0A po.src = 'https://apis.google.com/js/client:plusone.js';%0A var s = document.getElementsByTagName('script')%5B0%5D; s.parentNode.insertBefore(po, s);%0A %7D)(); %0A - %7D%0A%0A%0A @@ -2585,17 +2585,16 @@ %7D%0A%0A -%0A re @@ -2986,17 +2986,16 @@ ebook':%0A -%0A @@ -3055,17 +3055,16 @@ n(',');%0A -%0A @@ -3145,25 +3145,24 @@ (profile) %7B%0A -%0A @@ -3171,20 +3171,20 @@ var -info +data = %7B%0A @@ -3302,33 +3302,32 @@ %7D;%0A -%0A @@ -3374,12 +3374,12 @@ rl, -info +data ).su @@ -3678,17 +3678,16 @@ %7D);%0A -%0A @@ -3747,32 +3747,32 @@ break;%0A - case @@ -3782,16 +3782,300 @@ oogle':%0A + gapi.auth.authorize(%7B%0A client_id: config.providers.google.clientId,%0A scope: config.providers.google.scope,%0A immediate: false%0A %7D, function() %7B%0A console.log(gapi.auth.getToken());%0A %7D);%0A%0A
8dbd1a78bb163d99b61914979568c11561cc3a84
support multiple classes
addon/modifiers/css-transition.js
addon/modifiers/css-transition.js
import Modifier from 'ember-modifier'; import { dasherize } from '@ember/string'; import { nextTick, sleep, computeTimeout } from 'ember-css-transitions/utils/transition-utils'; /** Modifier that applies classes. Usage: ```hbs <div {{css-transition name="example"}}> <p>Hello world</p> </div> ``` @class CssTransitionModifier @argument {Function} [didTransitionIn] @argument {Function} [didTransitionOut] @public */ export default class CssTransitionModifier extends Modifier { clone = null; parentElement = null; nextElementSibling = null; installed = false; prevState = null; /** * @type {(HTMLElement|undefined)} * @private * @readonly */ get el() { return this.clone || this.element; } /** * @type {(String|undefined)} * @private * @readonly */ get transitionName() { return this.args.positional[0] || this.args.named.name; } /** * @type {(String|undefined)} * @private * @readonly */ get enterClass() { return this.args.named.enterClass || this.transitionName && `${this.transitionName}-enter`; } /** * @type {(String|undefined)} * @private * @readonly */ get enterActiveClass() { return this.args.named.enterActiveClass || this.transitionName && `${this.transitionName}-enter-active`; } /** * @type {(String|undefined)} * @private * @readonly */ get enterToClass() { return this.args.named.enterToClass || this.transitionName && `${this.transitionName}-enter-to`; } /** * @type {(String|undefined)} * @private * @readonly */ get leaveClass() { return this.args.named.leaveClass || this.transitionName && `${this.transitionName}-leave`; } /** * @type {(String|undefined)} * @private * @readonly */ get leaveActiveClass() { return this.args.named.leaveActiveClass || this.transitionName && `${this.transitionName}-leave-active`; } /** * @type {(String|undefined)} * @private * @readonly */ get leaveToClass() { return this.args.named.leaveToClass || this.transitionName && `${this.transitionName}-leave-to`; } didInstall() { if (this.args.named.isEnabled === false) { return; } this.parentElement = this.element.parentElement; this.nextElementSibling = this.element.nextElementSibling; this.guardedRun(this.transitionIn); } willRemove() { if (this.args.named.isEnabled === false || !this.installed) { return; } this.guardedRun(this.transitionOut); } didUpdateArguments() { if (this.args.named.isEnabled === false) { return; } this.guardedRun(this.transitionClassChange); } applyClasses() { if (Object.prototype.hasOwnProperty.call(this.args.named, 'state')) { this.prevState = this.args.named['state']; if (this.prevState) { this.addClass(dasherize(this.prevState)); } } } /** * Adds a clone to the parentElement so it can be transitioned out * * @private * @method addClone */ addClone() { let original = this.element; let parentElement = original.parentElement || this.parentElement; let nextElementSibling = original.nextElementSibling || this.nextElementSibling; if (nextElementSibling && (nextElementSibling.parentElement !== parentElement)) { nextElementSibling = null; } let clone = original.cloneNode(true); clone.setAttribute('id', `${original.id}_clone`); parentElement.insertBefore(clone, nextElementSibling); this.clone = clone; } /** * Removes the clone from the parentElement * * @private * @method removeClone */ removeClone() { if (this.clone.isConnected && this.clone.parentNode !== null) { this.clone.parentNode.removeChild(this.clone); } } *transitionIn() { this.applyClasses(); if (this.enterClass) { yield* this.transition({ className: this.enterClass, activeClassName: this.enterActiveClass, toClassName: this.enterToClass }); if (this.args.named.didTransitionIn) { this.args.named.didTransitionIn(); } } this.installed = true; } *transitionOut() { if (this.leaveClass) { // We can't stop ember from removing the element // so we clone the element to animate it out this.addClone(); yield nextTick(); yield* this.transition({ className: this.leaveClass, activeClassName: this.leaveActiveClass, toClassName: this.leaveToClass }); this.removeClone(); if (this.args.named.didTransitionOut) { this.args.named.didTransitionOut(); } this.clone = null; } } *transitionClassChange() { let prevState = this.prevState; let state = this.args.named['state']; this.prevState = state; // update previous state if (prevState !== state) { if (state) { let className = dasherize(state); this.addClass(className); yield* this.transition({ className: `${className}-add`, activeClassName: `${className}-add-active`, toClassName: `${className}-add-to` }); if (this.args.named.didTransitionIn) { this.args.named.didTransitionIn(className); } } else { let className = dasherize(prevState); this.removeClass(className); yield* this.transition({ className: `${className}-remove`, activeClassName: `${className}-remove-active`, toClassName: `${className}-remove-to` }); if (this.args.named.didTransitionOut) { this.args.named.didTransitionOut(className); } } } } /** * Transitions the element. * * @private * @method transition * @param {Object} args * @param {String} args.className the class representing the starting state * @param {String} args.activeClassName the class applied during the entire transition. This class can be used to define the duration, delay and easing curve. * @param {String} args.toClassName the class representing the finished state * @return {Generator} */ *transition({ className, activeClassName, toClassName }) { let element = this.el; // add first class right away this.addClass(className); this.addClass(activeClassName); yield nextTick(); // This is for to force a repaint, // which is necessary in order to transition styles when adding a class name. element.scrollTop; // after repaint this.addClass(toClassName); this.removeClass(className); // wait for ember to apply classes // set timeout for animation end yield sleep(computeTimeout(element) || 0); this.removeClass(toClassName); this.removeClass(activeClassName); } /** * Add classNames to el. * * @private * @method addClass * @param {String} classNames */ addClass(className) { this.el.classList.add(...className.split(' ')); } /** * Remove classNames from el. * * @private * @method removeClass * @param {String} classNames */ removeClass(className) { this.el.classList.remove(...className.split(' ')); } async guardedRun(f, ...args) { let gen = f.call(this, ...args); let isDone = false; // stop if the function doesn't have anything else to yield // or if the element is no longer present while (!isDone && this.el) { let { value, done } = gen.next(); isDone = done; await value; } } }
JavaScript
0.000001
@@ -6992,33 +6992,42 @@ ..className. +trim(). split( -' ' +/%5Cs+/ ));%0A %7D%0A%0A / @@ -7216,17 +7216,26 @@ ame. +trim(). split( -' ' +/%5Cs+/ ));%0A
4bf69722dd337f172af87bb4d344df84f9af0188
Add the relation names as a property of the repository
foxx_generator/json_api.js
foxx_generator/json_api.js
/*jslint indent: 2, nomen: true, maxlen: 120 */ /*global require */ (function () { 'use strict'; var Foxx = require('org/arangodb/foxx'), _ = require('underscore'), ArangoError = require('internal').ArangoError, JsonApiModel, JsonApiRepository, ContainsTransition, ReplaceOperation, transitions = []; var addLinks = function (model, graph, relationNames) { var links = {}; _.each(relationNames, function (relation) { var neighbors = graph._neighbors(model.id, { edgeCollectionRestriction: [relation.edgeCollectionName] }); if (relation.type === 'one') { links[relation.relationName] = neighbors[0]._key; } else if (relation.type === 'many') { links[relation.relationName] = _.pluck(neighbors, '_key'); } }); model.set('links', links); }; JsonApiRepository = Foxx.Repository.extend({ updateByIdWithOperations: function (id, operations) { var model = this.byId(id); _.each(operations, function (operation) { operation.execute(model); }); return this.replace(model); }, allWithNeighbors: function (options, relationNames) { var results = this.all(options); _.each(results, function (result) { addLinks(result, this.graph, relationNames); }, this); return results; }, byIdWithNeighbors: function (key, relationNames) { var result = this.byId(key); addLinks(result, this.graph, relationNames); return result; } }); JsonApiModel = Foxx.Model.extend({ forClient: function () { var attributes = Foxx.Model.prototype.forClient.call(this); return _.extend({ id: this.get('_key') }, attributes); } }); ReplaceOperation = Foxx.Model.extend({ isValid: function () { return (this.get('op') === 'replace'); }, execute: function (model) { model.set(this.getAttributeName(), this.get('value')); }, // Fake implementation getAttributeName: function () { return this.get('path').split('/').pop(); } }, { op: { type: 'string', required: true }, path: { type: 'string', required: true }, value: { type: 'string', required: true } }); // This should later inherit from Transition ContainsTransition = function (appContext, graph, controller, states) { this.appContext = appContext; this.graph = graph; this.controller = controller; this.states = states; }; _.extend(ContainsTransition.prototype, { apply: function (from, to) { var entryPath = '/' + from.name + '/:id', collectionPath = '/' + from.name, perPage = 10, repository = from.repository, nameOfRootElement = from.name, Model = to.model, attributes = Model.attributes, relationNames = to.relationNames, BodyParam = Foxx.Model.extend({}, { attributes: attributes }); this.controller.get(collectionPath, function (req, res) { var data = {}, page = req.params('page') || 0, skip = page * perPage, options = { skip: skip, limit: perPage }; data[nameOfRootElement] = _.map(repository.allWithNeighbors(options, relationNames), function (datum) { return datum.forClient(); }); res.json(data); }).queryParam('page', { description: 'Page of the results', type: 'int' }).summary('Get all entries') .notes('Some fancy documentation'); this.controller.post(collectionPath, function (req, res) { var data = {}; data[nameOfRootElement] = _.map(req.params(nameOfRootElement), function (model) { return repository.save(model).forClient(); }); res.status(201); res.json(data); }).bodyParam(nameOfRootElement, 'TODO', [BodyParam]) .summary('Post new entries') .notes('Some fancy documentation'); this.controller.get(entryPath, function (req, res) { var id = req.params('id'), entry = repository.byIdWithNeighbors(id, relationNames), data = {}; data[nameOfRootElement] = [entry.forClient()]; res.json(data); }).pathParam('id', { description: 'ID of the document', type: 'string' }).summary('Get a specific entry') .notes('Some fancy documentation'); // This works a little different from the standard: // It expects a root element, the standard does not this.controller.patch(entryPath, function (req, res) { var operations = req.params('operations'), id = req.params('id'), data = {}; if (_.all(operations, function (x) { return x.isValid(); })) { data[nameOfRootElement] = repository.updateByIdWithOperations(id, operations).forClient(); res.json(data); } else { res.json({ error: 'Only replace is supported right now' }); res.status(405); } }).pathParam('id', { description: 'ID of the document', type: 'string' }).bodyParam('operations', 'The operations to be executed on the document', [ReplaceOperation]) .summary('Update an entry') .notes('Some fancy documentation'); this.controller.del(entryPath, function (req, res) { var id = req.params('id'); repository.removeById(id); res.status(204); }).pathParam('id', { description: 'ID of the document', type: 'string' }).errorResponse(ArangoError, 404, 'An entry with this ID could not be found') .summary('Remove an entry') .notes('Some fancy documentation'); } }); transitions.push({ name: 'element', Transition: ContainsTransition }); exports.mediaType = { Model: JsonApiModel, Repository: JsonApiRepository, transitions: transitions }; }());
JavaScript
0.000008
@@ -1154,31 +1154,16 @@ (options -, relationNames ) %7B%0A @@ -1269,32 +1269,37 @@ lt, this.graph, +this. relationNames);%0A @@ -1381,31 +1381,16 @@ ion (key -, relationNames ) %7B%0A @@ -1451,24 +1451,29 @@ this.graph, +this. relationName @@ -2784,50 +2784,8 @@ es,%0A - relationNames = to.relationNames,%0A @@ -2848,24 +2848,76 @@ ibutes %7D);%0A%0A + repository.relationNames = to.relationNames;%0A%0A this.c @@ -3194,31 +3194,16 @@ (options -, relationNames ), funct @@ -4039,31 +4039,16 @@ hbors(id -, relationNames ),%0A
511e90071a8aa10d674e41d717a9390c1a6aa445
comment / idea
node/provider.notification-mongo.js
node/provider.notification-mongo.js
/* * Lunchpad Notification provider * * @author Markus Riegel <[email protected]> */ var db = require('./module.dbase.js').dBase, quando = require('./module.quando.js').quando, cn = 'notification'; var NotificationProvider = function(){}; /* * find all */ NotificationProvider.prototype.findAll = function(onSuccess, onError){ db.gc(cn, function(collection){ collection.find({},{ sort:[['date','desc']] }).toArray(function(error,results){ if(error) onError(error); else onSuccess(results); }); },onError); } /* * Count older then 15min */ NotificationProvider.prototype.countLt15min = function(type, onSuccess, onError){ db.gc(cn, function(collection){ collection.count({ type: type, date: {$lte: quando.min15()} }, function(error,count){ if(error) onError(error); else onSuccess(count); }); },onError); } /* * Count older then 5min */ NotificationProvider.prototype.countLt5min = function(type, onSuccess, onError){ db.gc(cn, function(collection){ collection.count({ type: type, date: {$lte: quando.min5()} }, function(error,count){ if(error) onError(error); else onSuccess(count); }); },onError); } /* * Delete for uid */ /* NotificationProvider.prototype.delWithUid = function(uid, onSuccess, onError){ db.gc(cn, function(collection){ collection.remove({ uid: uid },{ safe: true },function(error,numRemoved){ if(error) onError(error); else{ console.log('Notis removed: '+numRemoved); onSuccess(numRemoved); } }); },onError); } */ NotificationProvider.prototype.delWithTypeAndUser = function(type, userId, onSuccess, onError){ db.gc(cn, function(collection){ collection.remove({ 'user.id': userId, type: type },{ safe: true },function(error,numRemoved){ if(error) onError(error); else{ console.log('Notis removed: '+numRemoved); onSuccess(numRemoved); } }); },onError); } /* * Delete all */ NotificationProvider.prototype.delAll = function(type, onSuccess, onError){ db.gc(cn, function(collection){ collection.remove({ type: type },{ safe: true },function(error,numRemoved){ if(error) onError(error); else{ console.log('Notis removed: '+numRemoved); onSuccess(numRemoved); } }); },onError); } /* * Aggregate all comments */ NotificationProvider.prototype.aggrTargets = function(type, onSuccess, onError){ db.gc(cn, function(collection){ // ???? collection.aggregate([ {$match:{ type: type }}, {$group:{ _id: { target: '$target', venue: '$venue' }, users: { '$addToSet': user } }}, {$group:{ _id: { target: '$target' }, venues: { '$push': { venue: '$venue', users: '$users' } } }} ], function(error, results){ if(error) onError(error); else onSuccess(results); }); },onError); } /* * Save one or more new notifications */ NotificationProvider.prototype.save = function(notis, onSuccess, onError){ db.gc(cn, function(collection){ var i, noti; if(notis.length === undefined) notis = [notis]; // expected values for(i=0;i<notis.length;i++){ noti = notis[i]; if( !noti.target || // that's a user !noti.target._id || !noti.target.nick || !noti.type || //either comment or checkin !noti.venue || !noti.venue._id || !noti.venue.name || !noti.user || !noti.user._id || !noti.user.nick || !noti.user.ava){ // there is no parameter for commets. // place additional data as attributes of existing objects. // this way they wont get lost in the pipeline // noti.user.comment callback('data incomplete'); return; } // fill auto values noti.date = new Date(); } collection.insert(notis, function(error,results) { if(error) onError(error); else{ console.log('Checkins created: '+notis.length); onSuccess(results); } }); },onError); } /* * Save one checkin and delete others from the same user from today */ /* NotificationProvider.prototype.saveAndDel = function(noti, onSuccess, onError){ NotificationProvider.prototype.delWithUid(noti.uid,function(numRemoved){ NotificationProvider.prototype.save(noti,onSuccess,onError); },onError); } */ exports.notificationProvider = new NotificationProvider();
JavaScript
0
@@ -2914,32 +2914,286 @@ %09%7D,onError);%0A%7D%0A%0A +// So.%0A// Zum Eintragen sollten wir eine shortcut fn schreiben,%0A// die uns eine noti f%C3%BCr einen array von usern erstellen l%C3%A4sst.%0A%0A// Der UserProvider muss uns noch die Infos holen, welche User denn%0A// jeweils f%C3%BCr Eintragen der Notification relvant sind.%0A%0A %0A%0A%0A/*%0A * Save on
30013715ab8c00e6a678cb78591e2666e388c9d6
Add bgeraymovich to emailsMap
getSlackUser.js
getSlackUser.js
// Usage // author=$(node ./getSlackUser.js) // or // author=$(curl –silent -L 'https://raw.githubusercontent.com/debitoor/teamcity-merge/master/getSlackUser.js' | node) const { execSync } = require('child_process'); const assert = require('assert'); assert(process.env.SLACK_TOKEN, 'process.env.SLACK_TOKEN should be specified'); //Map of emails -> slack user name const emailsMap = { '[email protected]': 'eagleeye', '[email protected]': 'bogdan', '[email protected]': 'mamant', '[email protected]': 'mpushkin', '[email protected]': 'jonatanpedersen', '[email protected]': 'kollner', '[email protected]': 'hilleer', '[email protected]': 'lex', '[email protected]': 'mpushkin', '[email protected]': 'niklas', '[email protected]': 'dima', '[email protected]': 'zygi', '[email protected]': 'stepan', '[email protected]': 'cd', '[email protected]' : 'rasmus', '[email protected]' : 'katsanva', }; const email = execSync('git log --pretty=format:\'%ae\' -n 1', {encoding: 'utf-8'}); if (email === '[email protected]') { console.log('TeamCity'); process.exit(0); } const usersJSON = execSync(`curl -X POST "https://slack.com/api/users.list?token=${process.env.SLACK_TOKEN}" -s`); const users = JSON.parse(usersJSON); const slackUser = emailsMap[email]; const user = users.members.find((m) => m.name === slackUser || m.profile.email === email ); if(!user) { console.log(`${slackUser}|${email} (could not find this slack-username or email in slack?! Fix it here: https://github.com/debitoor/teamcity-merge/blob/master/getSlackUser.js)`); process.exit(0); } console.log(`<@${user.id}|${slackUser}>`);
JavaScript
0.000001
@@ -954,16 +954,60 @@ sanva',%0A +%09'[email protected]' : 'bgeraymovich',%0A %7D;%0A%0Acons
4d2cb83796b6e42902bf56ee4b270446000ba729
use JSON parse hack to clone defaults perfectly
extra/gulpfile.js
extra/gulpfile.js
var gulp = require('gulp'), gutil = require('gulp-util'), jshint = require('gulp-jshint'), coverage = require('gulp-jsx-coverage'), fs = require('fs'), React = require('react-tools'), through = require('through2'), buffer = require('vinyl-buffer'), source = require('vinyl-source-stream'), aliasify = require('aliasify'), browserify = require('browserify'), uglify = require('gulp-uglify'), nodemon = require('nodemon'), browserSync = require('browser-sync'), serverStarted = false, // If you use vim and watch tasks be triggered 2 times when saving // You can :set nowritebackup in vim to prevent this // Reference: https://github.com/joyent/node/issues/3172 configs = { static_dir: 'static/', mainjs: require(process.cwd() + '/package.json').main, appjs: process.cwd() + '/fluxexapp.js', nodemon_restart_delay: 200, nodemon_delay: 2000, gulp_watch: {debounceDelay: 500}, watchify: {debug: true, delay: 500}, jshint_jsx: {quotmark: false}, jslint_fail: false, aliasify: { aliases: { request: 'browser-request' } }, test_coverage: { default: { src: ['test/**/*.js', 'test/components/*.js*'], istanbul: { coverageVariable: '__FLUXEX_COVERAGE__', skip: /node_modules\/|test\// }, coverage: { directory: 'coverage' }, mocha: {}, react: { sourceMap: true }, coffee: { sourceMap: true } }, console: { coverage: { reporters: ['text-summary'] }, mocha: { reporter: 'spec' } }, report: { coverage: { reporters: ['lcov', 'json'] }, mocha: { reporter: 'tap' } } } }, build_files = { js: ['actions/*.js', 'stores/*.js'], jsx: ['components/*.jsx'] }, restart_nodemon = function () { setTimeout(function () { nodemon.emit('restart'); }, configs.nodemon_restart_delay); }, lint_chain = function (task) { task = task.pipe(jshint.reporter('jshint-stylish')); if (configs.jslint_fail) { task = task.pipe(jshint.reporter('fail')); } return task; }, // Stop using gulp-react because it do not keep original file name react_compiler = function (options) { return through.obj(function (file, enc, callback) { try { file.contents = new Buffer(React.transform(file.contents.toString(), options)); this.push(file); } catch (E) { gutil.log('[jsx ERROR]', gutil.colors.red(file.path)); gutil.log('[jsx ERROR]', gutil.colors.red(E.message)); } callback(); }); }, // Do testing tasks get_testing_task = function (options) { var cfg = Object.assign({}, configs.test_coverage.default); cfg.coverage.reporters = options.coverage.reporters; cfg.mocha = options.mocha; return coverage.createTask(cfg); }, bundleAll = function (b, noSave) { var B = b.bundle() .on('error', function (E) { gutil.log('[browserify ERROR]', gutil.colors.red(E)); }); if (!noSave) { B.pipe(source('main.js')) .pipe(gulp.dest(configs.static_dir + 'js/')) .on('end', restart_nodemon); } return B; }, buildApp = function (watch, fullpath, nosave, disc) { var b = browserify(configs.appjs, { cache: {}, packageCache: {}, require: (disc ? process.cwd() : '.') + '/components/Html.jsx', standalone: 'Fluxex', fullPaths: fullpath ? true: false, debug: watch }); b.transform('reactify'); b.transform(aliasify.configure(configs.aliasify), {global: true}); if (watch) { b = require('watchify')(b, configs.watchify); b.on('update', function (F) { gutil.log('[browserify] ' + F[0] + ' updated'); bundleAll(b); }); } return bundleAll(b, nosave); }; gulp.task('build_app', function () { return buildApp(false, false, true) .pipe(source('main.js')) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest(configs.static_dir + 'js/')); }); gulp.task('disc_app', function () { return buildApp(false, true, true, true) .pipe(require('disc')()) .pipe(fs.createWriteStream(configs.static_dir + 'disc.html')); }); gulp.task('watch_app', function () { return buildApp(true, true); }); gulp.task('watch_flux_js', ['lint_flux_js'], function () { gulp.watch(build_files.js, configs.gulp_watch, ['lint_flux_js']); }); gulp.task('lint_flux_js', function () { return lint_chain( gulp.src(build_files.js) .pipe(jshint()) ); }); gulp.task('watch_jsx', ['lint_jsx'], function () { gulp.watch(build_files.jsx, configs.gulp_watch, ['lint_jsx']); }); gulp.task('lint_jsx', function () { return lint_chain( gulp.src(build_files.jsx) .pipe(react_compiler({sourceMap: true})) .pipe(jshint(configs.jshint_jsx)) ); }); gulp.task('watch_server', ['lint_server'], function () { gulp.watch(configs.mainjs, configs.gulp_watch, ['lint_server']) .on('change', function () { nodemon.emit('restart'); }); }); gulp.task('lint_server', function () { return gulp.src(configs.mainjs) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('nodemon_server', ['watch_flux_js', 'watch_jsx', 'watch_app', 'watch_server'], function () { nodemon({ ignore: '*', script: configs.mainjs, ext: 'do_not_watch' }) .on('log', function (log) { gutil.log(log.colour); }) .on('start', function () { if (serverStarted) { setTimeout(browserSync.reload, configs.nodemon_delay); } else { browserSync.init(null, { proxy: 'http://localhost:3000', files: [configs.static_dir + 'css/*.css'], port: 3001, online: false, open: false }); serverStarted = true; } }); }); gulp.task('test_app', get_testing_task(configs.test_coverage.console)); gulp.task('save_test_app', get_testing_task(configs.test_coverage.report)); gulp.task('develop', ['nodemon_server']); gulp.task('lint_all', ['lint_server', 'lint_flux_js', 'lint_jsx']); gulp.task('buildall', ['lint_all', 'build_app']); gulp.task('default',['buildall']); module.exports = configs;
JavaScript
0
@@ -1339,12 +1339,15 @@ -skip +exclude : /n @@ -2998,26 +2998,34 @@ g = -Object.assign(%7B%7D, +JSON.parse(JSON.stringify( conf @@ -3050,16 +3050,17 @@ default) +) ;%0A%0A c
469efc848ad3e052add955c8e0910b40307d7cb2
Fix last commit.
app/scripts/services/dimEngramFarmingService.factory.js
app/scripts/services/dimEngramFarmingService.factory.js
(function() { 'use strict'; angular.module('dimApp') .factory('dimEngramFarmingService', EngramFarmingService); EngramFarmingService.$inject = ['$rootScope', '$q', 'dimBungieService', 'dimItemService', 'dimStoreService', '$interval', 'toaster']; /** * A service for "farming" engrams by moving them continuously off a character, * so that they don't go to the Postmaster. */ function EngramFarmingService($rootScope, $q, dimBungieService, dimItemService, dimStoreService, $interval, toaster) { var intervalId; var cancelReloadListener; return { active: false, store: null, engramsMoved: 0, movingEngrams: false, makingRoom: false, // Move all engrams on the selected character to the vault. moveItemsToVault: function(items, incrementCounter) { var self = this; return _.reduce(items, function(promise, item) { return promise .then(function() { var vault = dimStoreService.getVault(); if (vault.spaceLeftForItem(item) <= 1) { // If we're down to one space, try putting it on other characters var otherStores = _.select(dimStoreService.getStores(), function(store) { return !store.isVault && store.id !== self.store.id && store.spaceLeftForItem > 0; }); if (otherStores.length) { return dimItemService.moveTo(item, store, false, item.amount, items); } } return dimItemService.moveTo(item, vault, false, item.amount, items); }) .then(function() { if (incrementCounter) { // TODO: whoops self.engramsMoved++; } }) .catch(function(e) { toaster.pop('error', item.name, e.message); }); }, $q.resolve()); }, moveEngramsToVault: function() { var self = this; var store = dimStoreService.getStore(self.store.id); var engrams = _.select(store.items, function(i) { return i.isEngram() && i.sort !== 'Postmaster'; }); if (engrams.length === 0) { return $q.resolve(); } self.movingEngrams = true; return self.moveItemsToVault(engrams, true) .finally(function() { self.movingEngrams = false; }); }, // Ensure that there's one open space in each category that could // hold an engram, so they don't go to the postmaster. makeRoomForEngrams: function() { var self = this; var store = dimStoreService.getStore(self.store.id); // TODO: this'll be easier with buckets // These types can have engrams var engramTypes = ['Primary', 'Special', 'Heavy', 'Helmet', 'Gauntlets', 'Chest', 'Leg', 'ClassItem']; var applicableItems = _.select(store.items, function(i) { return !i.equipped && i.sort !== 'Postmaster' && _.contains(engramTypes, i.type); }); var itemsByType = _.groupBy(applicableItems, 'type'); // If any category is full, we'll move one aside var itemsToMove = []; _.each(itemsByType, function(items, type) { // subtract 1 from capacity because we excluded the equipped item if (items.length > 0 && items.length >= (store.capacityForItem(items[0]) - 1)) { // We'll move the lowest-value item to the vault. itemsToMove.push(_.min(_.select(items, { notransfer: false}), function(i) { var value = { Common: 0, Uncommon: 1, Rare: 2, Legendary: 3, Exotic: 4 }[i.tier]; // And low-stat if (i.primStat) { value += i.primStat.value / 1000.0; } return value; })); } }); if (itemsToMove.length === 0) { return $q.resolve(); } self.makingRoom = true; return self.moveItemsToVault(itemsToMove, false) .finally(function() { self.makingRoom = false; }); }, start: function(store) { if (!this.active) { this.active = true; this.store = store; this.engramsMoved = 0; this.movingEngrams = false; this.makingRoom = false; var self = this; function farm() { self.moveEngramsToVault().then(function() { self.makeRoomForEngrams(); }); } // Whenever the store is reloaded, run the farming algo // That way folks can reload manually too cancelReloadListener = $rootScope.$on('dim-stores-updated', function() { // prevent some recursion... if (self.active && !self.movingEngrams && !self.makingRoom) { farm(); } }); intervalId = $interval(function() { // just start reloading stores more often dimStoreService.reloadStores(); }, 60000); farm(); } }, stop: function() { if (intervalId) { $interval.cancel(intervalId); } if (cancelReloadListener) { cancelReloadListener(); } this.active = false; } }; } })();
JavaScript
0
@@ -1372,16 +1372,22 @@ tForItem +(item) %3E 0;%0A @@ -1499,21 +1499,30 @@ o(item, -store +otherStores%5B0%5D , false, @@ -1749,40 +1749,8 @@ ) %7B%0A - // TODO: whoops%0A
dee13c9f0f094b883a39bf69bec05c8b38fc3307
fix build error
extra/gulpfile.js
extra/gulpfile.js
var gulp = require('gulp'), gutil = require('gulp-util'), react = require('gulp-react'), jshint = require('gulp-jshint'), buffer = require('vinyl-buffer'), source = require('vinyl-source-stream'), aliasify = require('aliasify'), browserify = require('browserify'), uglify = require('gulp-uglify'), nodemon = require('nodemon'), browserSync = require('browser-sync'), serverStarted = false, // If you use vim and watch tasks be triggered 2 times when saving // You can :set nowritebackup in vim to prevent this // Reference: https://github.com/joyent/node/issues/3172 configs = { static_dir: 'static/', mainjs: require(process.cwd() + '/package.json').main, appjs: process.cwd() + '/fluxexapp.js', nodemon_restart_delay: 200, nodemon_delay: 2000, gulp_watch: {debounceDelay: 500}, watchify: {debug: true, delay: 500}, jshint_jsx: {quotmark: false}, aliasify: { aliases: { request: 'browser-request' } } }, build_files = { js: ['actions/*.js', 'stores/*.js'], jsx: ['components/*.jsx'] }, restart_nodemon = function () { setTimeout(function () { nodemon.emit('restart'); }, configs.nodemon_restart_delay); }, bundleAll = function (b, noSave) { var B = b.bundle() .on('error', function (E) { gutil.log('[browserify ERROR]', gutil.colors.red(E)); }); if (!noSave) { B.pipe(source('main.js')) .pipe(gulp.dest(configs.static_dir + 'js/')) .on('end', restart_nodemon); } return B; }, buildApp = function (watch, fullpath, nosave) { var b = browserify(configs.appjs, { cache: {}, packageCache: {}, require: (fullpath ? process.cwd() : '.') + '/components/Html.jsx', standalone: 'Fluxex', insertGlobals: false, detectGlobals: false, fullPaths: fullpath ? true: false, debug: watch }); b.transform('reactify'); b.transform(aliasify.configure(configs.aliasify), {global: true}); if (watch) { b = require('watchify')(b, configs.watchify); b.on('update', function (F) { gutil.log('[browserify] ' + F[0] + ' updated'); bundleAll(b); }); } return bundleAll(b, nosave); }; gulp.task('build_app', function () { return buildApp(false) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest(configs.static_dir + 'js/')); }); gulp.task('disc_app', function () { return buildApp(false, true, true) .pipe(require('disc')()) .pipe(require('fs').createWriteStream(configs.static_dir + 'disc.html')); }); gulp.task('watch_app', function () { return buildApp(true, true); }); gulp.task('watch_flux_js', ['lint_flux_js'], function () { gulp.watch(build_files.js, configs.gulp_watch, ['lint_flux_js']); }); gulp.task('lint_flux_js', function () { return gulp.src(build_files.js) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('watch_jsx', ['lint_jsx'], function () { gulp.watch(build_files.jsx, configs.gulp_watch, ['lint_jsx']); }); gulp.task('lint_jsx', function () { return gulp.src(build_files.jsx) .pipe(react()) .on('error', function (E) { gutil.log('[jsx ERROR]', gutil.colors.red(E.fileName)); gutil.log('[jsx ERROR]', gutil.colors.red(E.message)); }) .pipe(jshint(configs.jshint_jsx)) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('watch_server', ['lint_server'], function () { gulp.watch(configs.mainjs, configs.gulp_watch, ['lint_server']) .on('change', function () { nodemon.emit('restart'); }); }); gulp.task('lint_server', function () { return gulp.src(configs.mainjs) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) }); gulp.task('nodemon_server', ['watch_flux_js', 'watch_jsx', 'watch_app', 'watch_server'], function() { nodemon({ ignore: '*', script: configs.mainjs, ext: 'do_not_watch' }) .on('log', function (log) { gutil.log(log.colour); }) .on('start', function () { if (serverStarted) { setTimeout(browserSync.reload, configs.nodemon_delay); } else { browserSync.init(null, { proxy: 'http://localhost:3000', files: [configs.static_dir + 'css/*.css'], port: 3001, online: false, open: false }); serverStarted = true; } }); }); gulp.task('develop', ['nodemon_server']); gulp.task('lint_all', ['lint_server', 'lint_flux_js', 'lint_jsx']); gulp.task('buildall', ['lint_all', 'build_app']); gulp.task('default',['buildall']);
JavaScript
0.000001
@@ -2356,16 +2356,62 @@ pp(false +, false, true)%0A .pipe(source('main.js') )%0A
118f90f0c2e087acd2392abeb3af0d74051b794e
Fix other links on small devices
interfaces/default/js/default.js
interfaces/default/js/default.js
$.ajaxSetup({timeout: 30000}) $(document).ready(function () { path = window.location.pathname.split('/') $('#nav-'+path[1]).addClass('active') $('.carousel').carousel() $(".table-sortable").tablesorter() $('.tabs').tab() $(window).on('hashchange', function() { if (location.hash) { $('a[href='+location.hash+']').tab('show'); } else { $('a[data-toggle="tab"]:first').tab('show') } }) $('a[data-toggle="tab"]').on('click', function(e) { var yScroll = $(window).scrollTop() location.hash = $(e.target).attr('href') $(window).scrollTop(yScroll) }) $('form.disabled').submit(function(e) { e.preventDefault() }) $('a.ajax-link').click(function (e) { e.preventDefault() var link = $(this) $.getJSON(link.attr('href'), function(data) { notify(link.text(), data, 'success') }) }) $('a.ajax-confirm').click(function (e) { e.preventDefault() var link = $(this) if (confirm(link.attr('title') + '?')) { $.getJSON(link.attr('href'), function(data){ notify(link.attr('title'), data, 'info') }) } }) $('a.confirm').click(function (e) { return(confirm($(this).attr('title') + '?')) }) $('.btn-check-update').click(function (e) { e.preventDefault() notify('Update','Checking for update.','info') $.ajax({ dataType: "json", timeout: 10000, url: WEBDIR + 'update/', success: function(data) { if ($.isNumeric(data.versionsBehind) && data.versionsBehind == 0) { notify('Update', 'Already running latest version.', 'success') } else if (data.updateNeeded) { if (confirm('Your are '+data.versionsBehind+' versions behind. Update need. Update to latest version?')) { $.post(WEBDIR + 'update/', function (data) { if (data == 1) { showModal('Installing update', '<div class="progress progress-striped active"><div class="bar" style="width:100%"></div></div>','') } else { notify('Update', 'An error occured while updating!', 'error') } }, 'json').always(function() { checkUpdate() }) } } else { notify('Update', 'Failed. Check errorlog.', 'error') } } }); }) $('#modal_dialog').on('hidden', function () { $('#modal_dialog .modal-body').empty() $('#modal_dialog .trans').removeClass('trans') $('#modal_dialog .modal-fanart').css('background', '#fff') }) }) function makeIcon(iconClass, title) { return $('<i>') .addClass(iconClass) .attr('title', title) .css('cursor', 'pointer') .tooltip({placement: 'right'}) } function shortenText(string, length) { return string.substr(0,length)+(string.length>length?'&hellip;':'') } function pad(str, max) { return str.toString().length < max ? pad("0"+str, max) : str } function bytesToSize(bytes, precision) { var sizes = ['B', 'KB', 'MB', 'GB', 'TB'] var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))) return (bytes / Math.pow(1024, i)).toFixed(precision) + ' ' + sizes[i] } function parseDate(sec) { var date = new Date(sec*1000) var year = pad(date.getFullYear(), 2) var month = pad(date.getMonth(), 2) var day = pad(date.getDate(), 2) var hour = pad(date.getHours(), 2) var min = pad(date.getMinutes(), 2) return year+'-'+month+'-'+day+' '+hour+':'+min } function parseSec(sec) { if (sec==undefined) return '0.00' var h = Math.floor(sec / 3600) var m = Math.floor(sec % 3600 / 60) var s = pad(Math.floor(sec % 60), 2) return ((h>0) ? h+':'+pad(m, 2) : m) + ':' + s } function notify(title, text, type, time) { $.pnotify({ title: title, text: text, type: type, history: false, sticker: false, closer_hover: false, addclass: "stack-bottomright", stack: {"dir1": "up", "dir2": "left", push: 'top'} }) } function showModal(title, content, buttons) { $('#modal_dialog .modal-h3').html(title) $('#modal_dialog .modal-body').html(content) var footer = $('#modal_dialog .modal-footer').empty() $.each(buttons, function (name, action) { footer.append( $('<button>').html(name).addClass('btn btn-primary').click(function() { $(action) }) ) }) footer.append( $('<button>').html('Close').addClass('btn').click(function() { $(hideModal) }) ) $('#modal_dialog').modal({show: true, backdrop: true}) } function hideModal() { $('#modal_dialog').modal('hide') } function checkUpdate() { $.getJSON(WEBDIR + 'update/status', function (data) { if (data != 0) { setTimeout(checkUpdate, 1000) } else { location.reload() } }).error(function() { setTimeout(checkUpdate, 1000) }) }
JavaScript
0
@@ -5497,20 +5497,389 @@ , 1000)%0D%0A %7D)%0D%0A%7D%0D%0A +%0D%0A// Fix for dropdown menu on small devices. Credits https://github.com/twbs/bootstrap/issues/4550#issuecomment-21361314%0D%0A$('.dropdown-toggle').click(function(e) %7B%0D%0A e.preventDefault();%0D%0A setTimeout($.proxy(function() %7B%0D%0A if ('ontouchstart' in document.documentElement) %7B%0D%0A $(this).siblings('.dropdown-backdrop').off().remove();%0D%0A %7D%0D%0A %7D, this), 0);%0D%0A%7D);%0D%0A
b7422e3cd757e08c06ab5447b8f33348ed5e152b
Fix #155 Making attribute "TEXT" showing in the response.
src/main/javascript/form/SearchES.js
src/main/javascript/form/SearchES.js
/* Copyright (C) 2014 Härnösands kommun This program 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/>. */ /** * Combobox that uses ES for generic search */ Ext.define('OpenEMap.form.SearchES', { extend : 'Ext.form.field.ComboBox', alias: 'widget.searches', require: ['Ext.data.*', 'Ext.form.*'], initComponent : function() { var map = this.mapPanel.map; var layer = this.mapPanel.searchLayer; this.store = Ext.create('Ext.data.Store', { proxy: { type: 'ajax', url: OpenEMap.basePathES + '_search', reader: { type: 'json', root: 'hits.hits', totalProperty: 'hits.total', idProperty: '_id' } }, fields: [ { name: 'type', mapping: '_type' }, { name: 'hit', mapping: '_source.properties.PLANNUMMER' }, { name: 'geometry', mapping: '_source.geometry' } ] }); this.displayField = 'hit'; this.valueField = 'id'; this.queryParam ='q'; this.typeAhead = true; this.forceSelection = true; this.allowBlank = false; this.allowOnlyWhitespace = false; this.minChars = 4; this.minLength = 4; this.preventMark = true; this.hideTrigger = true; this.listeners = { 'select': function(combo, records) { var geojson = records[0].data.geometry; var format = new OpenLayers.Format.GeoJSON({ ignoreExtraDims: true }); var geometry = format.read(geojson, 'Geometry'); var feature = new OpenLayers.Feature.Vector(geometry); layer.destroyFeatures(); layer.addFeatures([feature]); map.zoomToExtent(feature.geometry.getBounds()); }, 'beforequery': function(queryPlan) { queryPlan.query = '"' + queryPlan.query + '"' + '*'; }, scope: this }; this.callParent(arguments); } });
JavaScript
0
@@ -1566,16 +1566,60 @@ perties. +TEXT' %7D, // Could be AKT=%222281K-NJU-268%22 or PLANNUMM @@ -1620,20 +1620,24 @@ ANNUMMER -' %7D, +=%22S5086%22 %0A
52c546fa95fce78a82173cccbef083bc2a5de40f
Update index.js
example/index.js
example/index.js
import React from 'react'; import Raspi from 'raspi-io'; import { AppRegistry, Board, Led, Button, Container } from 'react-iot'; class App extends React.Component { state = { isOn: false } takeOff(){ this.setState({ isOn: true }) this.socket.emit('takeoff'); } land(){ this.setState({ isOn: false }) this.socket.emit('land'); } componentWillMount(){ this.socket = require('socket.io-client')('http://localhost:3005'); this.socket.on('connect', () => { console.log('connected'); }); } render(){ return ( <Container> <Led pin="P1-13" isOn={this.state.isOn} /> <Button pin="P1-15" isPullup onPress={() => this.takeOff() } onRelease={() => this.land() } /> </Container> ) } } class IoTApplication extends React.Component { render(){ return ( <Board config={{ io: new Raspi() }}> <App /> </Board> ) } } AppRegistry.registerComponent('IoTApplication', IoTApplication);
JavaScript
0.000002
@@ -374,12 +374,11 @@ nent -Will +Did Moun
f305fcc8c3fefa9725b7c3cd29cfff794aeef726
use enum syntax for model parameters
node_modules/oae-search/lib/rest.js
node_modules/oae-search/lib/rest.js
/*! * Copyright 2014 Apereo Foundation (AF) Licensed under the * Educational Community 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://opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ var _ = require('underscore'); var util = require('util'); var OAE = require('oae-util/lib/oae'); var SearchAPI = require('oae-search'); var SearchUtil = require('oae-search/lib/util'); var REGEX_SEARCH_ENDPOINT = /\/api\/search\/([^\/]+)(\/.*)?/; /** * A REST endpoint handler for handling any search type * * @param {Request} req The express request object of the request * @param {Response} res The express response object for the request * @api private */ var _handleSearchRequest = function(req, res) { var searchType = req.params[0]; if (searchType) { req.telemetryUrl = util.format('/api/search/%s', searchType); } var pathParams = req.params[1] ? _.compact(req.params[1].split('/')) : []; var opts = _.extend({}, req.query, SearchUtil.getSearchParams(req), {'pathParams': pathParams}); SearchAPI.search(req.ctx, searchType, opts, function(err, result) { if (err) { return res.send(err.code, err); } res.send(200, result); }); }; /** * @REST postSearchReindexAll * * Administration function to reindex all data in storage * * @Server admin * @Method POST * @Path /search/reindexAll * @Return {void} */ OAE.globalAdminRouter.on('post', '/api/search/reindexAll', function(req, res) { SearchAPI.postReindexAllTask(req.ctx, function(err) { if (err) { return res.send(err.code, err.msg); } res.send(200); }); }); /** * @REST getSearch * * Perform a search * * @Server admin,tenant * @Method GET * @Path /search/{searchType} * @PathParam {string} searchType The type of search to execute [general] * @QueryParam {number} [limit] Maximum number of documents to return (defaults to 10) * @QueryParam {string} [q] Search phrase * @QueryParam {string[]} [resourceTypes] Resources to search [all,user,group,content,discussion] * @QueryParam {string} scope Scope of the search [_all,_interact,_network,_tenant] * @QueryParam {string} [sort] Sort direction (defaults to asc) [asc,desc] * @QueryParam {number} [start] Document at which to start (defaults to 0) * @Return {SearchResponse} Returns an object containing search results */ OAE.tenantRouter.on('get', REGEX_SEARCH_ENDPOINT, _handleSearchRequest, '/api/search'); OAE.globalAdminRouter.on('get', REGEX_SEARCH_ENDPOINT, _handleSearchRequest, '/api/search'); // Add the REST models for Search /** * @RESTModel SearchResponse * * @Required [total, SearchResults] * @Property {string} total Total number of matches * @Property {SearchResult[]} results Results from current query */ /** * @RESTModel SearchResult * * @Required [id,lastModified,resourceType,tenant,tenantAlias,visibility] * @Property {string} description Description of result * @Property {string} displayName Displayable name for result * @Property {string} id Unique identifier for result * @Property {string} joinable Can current user join the group (no,yes) * @Property {string} lastModified Time result was last modified (epoch format) * @Property {string} mime MIME type for result * @Property {string} profilePath URL for result * @Property {string} resourceSubType Subtype of resource (collabdoc,file,link) * @Property {string} resourceType Type of resource (content,discussion,group) * @Property {TenantInfo} tenant Tenant associated with result * @Property {string} tenantAlias Unique identifier for tenant * @Property {string} thumbnailUrl URL for thumbnail image of result * @Property {string} visibility Visibility of result (loggedin,private,public) */
JavaScript
0
@@ -3985,16 +3985,28 @@ oup -( + %5B no,yes -) +%5D %0A * @@ -4327,17 +4327,41 @@ esource -( + %5B collabdo @@ -4371,17 +4371,17 @@ ile,link -) +%5D %0A * @Pro @@ -4446,17 +4446,44 @@ esource -( + %5B content, @@ -4498,17 +4498,17 @@ on,group -) +%5D %0A * @Pro @@ -4838,17 +4838,40 @@ result -( + %5B loggedin @@ -4885,14 +4885,14 @@ e,public -) +%5D %0A */%0A
90256556cc1ef052359cff5040731e93d7819e7a
Migrate AdvisingCourse to function. Add hooks for redux and styling
src/components/AdvisingCourses.js
src/components/AdvisingCourses.js
import React from 'react' import AdvisingGrade from './AdvisingGrade' import AdvisingInstructors from './AdvisingInstructors' import AdvisingMeetings from './AdvisingMeetings' import Card from '@material-ui/core/Card' import CardContent from '@material-ui/core/CardContent' import CardHeader from '@material-ui/core/CardHeader' import PropTypes from 'prop-types' import Typography from '@material-ui/core/Typography' import { connect } from 'react-redux' import { withStyles } from '@material-ui/core/styles' const styles = theme => ({ header: { backgroundColor: theme.palette.primary.light }, body2: { fontWeight: 'bolder' }, empty: { textAlign: 'center' } }) class AdvisingCourses extends React.Component { getCourses() { let advisorCourses = [] const { classes, courses, regs } = this.props for (let i = 0; i < courses.length; i++) { if (Object.is(regs[courses[i].registrationStatusDescription], true)) { advisorCourses.push( <Card key={courses[i].crn + i + Math.random()} style={{ marginBottom: '1em' }} > <CardHeader className={classes.header} title={ <Typography tabIndex="0" variant="h1" style={{ fontSize: '20px' }} > {courses[i].subjectCode + '-' + courses[i].subjectNumber + ': ' + courses[i].courseTitle + ' [CRN: ' + courses[i].crn + ']'} </Typography> } key={courses[i].crn + i + Math.random()} subheader={ <Typography tabIndex="0"> {'Credits: ' + courses[i].credit} </Typography> } /> <CardContent key={courses[i].crn + i + Math.random()}> <div style={{ display: 'flex', justifyContent: 'space-around' }}> <div> <Typography variant="body1" classes={{ body2: classes.body2 }} > Instructors </Typography> <AdvisingInstructors instructors={courses[i].instructors} /> </div> <div> <Typography variant="body1" classes={{ body2: classes.body2 }} > Grade </Typography> <AdvisingGrade grade={courses[i].grade} /> </div> </div> <Typography variant="body1" classes={{ body2: classes.body2 }}> Meetings </Typography> <AdvisingMeetings meetings={courses[i].meetings} /> </CardContent> </Card> ) } } return advisorCourses } render() { const { courses_error, courses_fetched, classes, updating } = this.props if (courses_fetched !== true || updating === true) { return <div /> } else if (courses_error) { return ( <div> <Typography variant="h3" className={classes.empty} tabIndex="0"> No Courses. </Typography> </div> ) } else { return <div>{this.getCourses()}</div> } } } AdvisingCourses.propTypes = { classes: PropTypes.object.isRequired } const mapStateToProps = state => ({ courses: state.courses.courses, courses_error: state.courses.error, courses_fetched: state.courses.fetched, current_term: state.terms.current_term, regs: state.courses.regs, updating: state.courses.updating }) export default withStyles(styles, { name: 'AdvisingCourses' })( connect(mapStateToProps)(AdvisingCourses) )
JavaScript
0
@@ -326,43 +326,8 @@ er'%0A -import PropTypes from 'prop-types'%0A impo @@ -385,23 +385,27 @@ mport %7B -conn +useSel ect +or %7D from @@ -427,20 +427,20 @@ mport %7B -with +make Styles %7D @@ -459,21 +459,16 @@ rial-ui/ -core/ styles'%0A @@ -478,17 +478,20 @@ nst -s +useS tyles = them @@ -486,16 +486,27 @@ tyles = +makeStyles( theme =%3E @@ -661,152 +661,460 @@ %7D%0A%7D) +) %0A%0A -class AdvisingCourses extends React.Component %7B%0A getCourses() %7B%0A let advisorCourses = %5B%5D%0A const %7B classes, courses, regs %7D = this.props +export default function AdvisingCourses() %7B%0A const classes = useStyles()%0A const courses = useSelector(state =%3E state.courses.courses)%0A const courses_error = useSelector(state =%3E state.courses.error)%0A const courses_fetched = useSelector(state =%3E state.courses.fetched)%0A const regs = useSelector(state =%3E state.courses.regs)%0A const updating = useSelector(state =%3E state.courses.updating)%0A%0A const getCourses = () =%3E %7B%0A let advisorCourses = %5B%5D %0A @@ -3295,103 +3295,16 @@ s%0A -%7D%0A%0A render() %7B%0A const %7B courses_error, courses_fetched, classes, updating %7D = this.props%0A + %0A %7D%0A%0A if @@ -3354,26 +3354,24 @@ true) %7B%0A - return %3Cdiv @@ -3373,18 +3373,16 @@ %3Cdiv /%3E%0A - %7D else @@ -3403,26 +3403,24 @@ rror) %7B%0A - - return (%0A @@ -3418,26 +3418,24 @@ urn (%0A - %3Cdiv%3E%0A @@ -3428,34 +3428,32 @@ %3Cdiv%3E%0A - - %3CTypography vari @@ -3511,18 +3511,16 @@ - No Cours @@ -3523,18 +3523,16 @@ ourses.%0A - @@ -3547,26 +3547,24 @@ aphy%3E%0A - %3C/div%3E%0A @@ -3562,22 +3562,18 @@ iv%3E%0A - - )%0A - %7D else @@ -3575,18 +3575,16 @@ else %7B%0A - retu @@ -3596,13 +3596,8 @@ iv%3E%7B -this. getC @@ -3618,456 +3618,8 @@ %3E%0A - %7D%0A %7D%0A%7D%0A%0AAdvisingCourses.propTypes = %7B%0A classes: PropTypes.object.isRequired%0A%7D%0A%0Aconst mapStateToProps = state =%3E (%7B%0A courses: state.courses.courses,%0A courses_error: state.courses.error,%0A courses_fetched: state.courses.fetched,%0A current_term: state.terms.current_term,%0A regs: state.courses.regs,%0A updating: state.courses.updating%0A%7D)%0A%0Aexport default withStyles(styles, %7B name: 'AdvisingCourses' %7D)(%0A connect(mapStateToProps)(AdvisingCourses)%0A)%0A +%7D %0A%7D
e08ac3119824d681fdbd4fc493f67984ee4ceb5d
fix golden_file_test accept
internal/golden_file_test/bin.js
internal/golden_file_test/bin.js
const fs = require('fs'); const path = require('path'); const unidiff = require('unidiff'); function main(args) { const [mode, golden_no_debug, golden_debug, actual] = args; const debug = !!process.env['DEBUG']; const golden = debug ? golden_debug : golden_no_debug; const actualContents = fs.readFileSync(require.resolve(actual), 'utf-8').replace(/\r\n/g, '\n'); const goldenContents = fs.readFileSync(require.resolve(golden), 'utf-8').replace(/\r\n/g, '\n'); if (actualContents !== goldenContents) { if (mode === '--out') { // Write to golden file fs.writeFileSync(require.resolve(golden), actualContents); console.error(`Replaced ${path.join(process.cwd(), golden)}`); } else if (mode === '--verify') { // Generated does not match golden const diff = unidiff.diffLines(goldenContents, actualContents); const prettyDiff = unidiff.formatLines(diff, {aname: golden, bname: actual}); throw new Error(`Actual output doesn't match golden file: ${prettyDiff} Update the golden file: bazel run ${debug ? '--define=DEBUG=1 ' : ''}${ process.env['BAZEL_TARGET'].replace(/_bin$/, '')}.accept `); } else { throw new Error('unknown mode', mode); } } } if (require.main === module) { main(process.argv.slice(2)); }
JavaScript
0.000015
@@ -52,44 +52,8 @@ h'); -%0Aconst unidiff = require('unidiff'); %0A%0Afu @@ -699,24 +699,66 @@ -verify') %7B%0A + const unidiff = require('unidiff');%0A // Gen @@ -862,20 +862,18 @@ ;%0A -cons +le t pretty @@ -938,16 +938,130 @@ tual%7D);%0A + if (prettyDiff.length %3E 5000) %7B%0A prettyDiff = prettyDiff.substr(0, 5000) + '/n...elided...';%0A %7D%0A th
870f8435ec27444b86571fe159c82d9e0e780606
Update comments slightly in UndoStack and add empty fallback options object for when none are supplied.
resources/assets/js/classes/UndoStack.js
resources/assets/js/classes/UndoStack.js
/* global clearTimeout, setTimeout */ export default class UndoStack { defaultOptions = { maxSize: 30, lock: false, undoGroupingInterval: 400, onUndoRedo: () => {}, callback: () => {} }; constructor(opts) { opts = { ...this.defaultOptions, ...opts }; this.stack = []; this.index = -1; this.timer = null; this.maxSize = opts.maxSize; this.undoGroupingInterval = opts.undoGroupingInterval; this.isLocked = opts.lock; this.onUndoRedo = opts.onUndoRedo; this.callback = opts.callback; } runCallback(type) { this.callback({ type, index: this.index, length: this.stack.length, canUndo: this.canUndo(), canRedo: this.canRedo() }); return this; } lock(lock = true) { this.isLocked = lock; return this; } unlock() { return this.lock(false); } setUndoRedo(func) { this.onUndoRedo = func; return this; } setCallback(func) { this.callback = func; return this; } init(data) { return this.add(data).unlock(); } add(data) { if(this.timer) { clearTimeout(this.timer); } this.timer = setTimeout(() => { // if called after undoing remove upper this.stack.splice(this.index + 1, this.stack.length - this.index); if(this.stack.length === this.maxSize) { this.stack.shift(); } this.stack.push(JSON.stringify(data)); this.index = this.stack.length - 1; this.runCallback('add'); }, this.undoGroupingInterval); return this; } undoOrRedo(type) { const isUndo = type === 'undo', index = this.index + (isUndo ? -1 : 1), data = this.stack[index]; if(!data) { return this; } this.onUndoRedo(data); isUndo ? this.index-- : this.index++; this.runCallback(type); return this; } undo() { return this.undoOrRedo('undo'); } redo() { return this.undoOrRedo('redo'); } clear() { this.stack = []; this.index = -1; return this; } canUndo() { return !this.isLocked && this.index > 0; } canRedo() { return !this.isLocked && this.index < this.stack.length - 1; } }
JavaScript
0
@@ -212,16 +212,21 @@ tor(opts + = %7B%7D ) %7B%0A%09%09op @@ -1120,16 +1120,17 @@ oing +, remove uppe @@ -1129,13 +1129,30 @@ ove -upper +stack above this index %0A%09%09%09 @@ -1219,16 +1219,63 @@ ndex);%0A%0A +%09%09%09// remove oldest item if we surpass maxSize%0A %09%09%09if(th
f70531697976cfe5143be3fce43a4e61118c6969
Fix search not working
frontend/src/actions/search.js
frontend/src/actions/search.js
import { SEARCH_URL, AUTOCOMPLETE_URL } from 'constants'; import { SHOW_TOOLTIP, HIDE_TOOLTIP, TOGGLE_FOCUS, SEARCH_REQUEST, SEARCH_SUCCESS, SEARCH_FAILURE, UPDATE_SEARCH_INPUT, SEARCH_APPEND, AUTOCOMPLETE_REQUEST, AUTOCOMPLETE_SUCCESS, AUTOCOMPLETE_FAILURE } from './actionTypes'; import makeActionCreator from './makeActionCreator'; import mockAutocomplete from '../utils/mockAutocomplete'; export const showSearchTooltip = makeActionCreator(SHOW_TOOLTIP); export const hideSearchTooltip = makeActionCreator(HIDE_TOOLTIP); export const toggleFocus = makeActionCreator(TOGGLE_FOCUS); const searchRequest = makeActionCreator(SEARCH_REQUEST); const searchSuccess = makeActionCreator(SEARCH_SUCCESS, 'data'); const searchFailure = makeActionCreator(SEARCH_FAILURE, 'error'); const searchAppend = makeActionCreator(SEARCH_APPEND); export const updateSearchInput = makeActionCreator(UPDATE_SEARCH_INPUT, 'input'); let pageIndex = 1; const getResults = serializedQuery => new Promise((resolve, reject) => { const baseSearchURL = SEARCH_URL[window.catalogue]; const searchUrl = `${baseSearchURL}?${serializedQuery}`; fetch(searchUrl) .then(response => response.json()) .then(parsedResponse => resolve(parsedResponse)) .catch(error => reject(error)); }); const serializeQuery = (query, selectedData) => { const encode = encodeURIComponent; // short-hand let serializedQuery = (query) ? `recording=${encode(query)}` : ''; Object.keys(selectedData).forEach((category) => { if (selectedData[category].length) { const categoryEntries = selectedData[category].reduce((curStr, entry, index) => { if (index === selectedData[category].length - 1) { return curStr + encode(entry); } return `${curStr}${encode(entry)}+`; }, ''); serializedQuery += `&${encode(category)}=${categoryEntries}`; } }); if (pageIndex - 1 !== 0) { serializedQuery += `&page=${pageIndex}`; } return serializedQuery; }; const getQuery = (getStore) => { const state = getStore(); const query = state.search.input; const { selectedData } = state.filtersData; const serializedQuery = serializeQuery(query, selectedData); return serializedQuery; }; const getQueryResults = () => (dispatch, getStore) => { const query = getQuery(getStore); getResults(query).then( data => dispatch(searchSuccess(data)), error => { console.log(error); dispatch(searchFailure(error)); }); }; export const getSearchResults = () => (dispatch) => { pageIndex = 1; dispatch(searchRequest()); dispatch(getQueryResults()); }; export const getMoreResults = () => (dispatch) => { pageIndex += 1; dispatch(searchAppend()); dispatch(getQueryResults()); }; export const getAutocompleteList = input => (dispatch) => { const autocompleteURL = AUTOCOMPLETE_URL[window.catalogue]; if (!autocompleteURL) { return; } dispatch({ type: AUTOCOMPLETE_REQUEST }); mockAutocomplete(input).then(datalist => dispatch({ type: AUTOCOMPLETE_SUCCESS, datalist })); };
JavaScript
0.000004
@@ -43,16 +43,15 @@ om ' -constant +setting s';%0A @@ -2389,30 +2389,8 @@ r =%3E - %7B console.log(error); dis @@ -2420,11 +2420,8 @@ or)) -; %7D );%0A%7D
77375f54944490373f66b9c1a0f51f4bfc947693
Update differenceEnginev2.js
javascript/differenceEnginev2.js
javascript/differenceEnginev2.js
// Create the array var x = new Array(7); for (var i = 0; i < 7; i++) { x[i] = new Array(8); } // Initalize the Array for (var i = 0; i < 7; i++) { for (var j = 0; j < 8; j++) { x[i][j] = 0; } } // Update the values from the start function initalUpdateNumbers() { for (var i = 0; i < 7; i++) { for (var j = 0; j < 8; j++) { document.getElementById("num" + i + j).value = x[i][j]; } } } // Update the values on the screen function updateNumbers() { for (var i = 7; i > -1; i--) { for (var j = 6; j > 0; j--) { x[j][i] = parseInt(document.getElementById("num" + j + i).value); if (x[j][i] >= 10) { x[j - 1][i] = parseInt(document.getElementById("num" + (j - 1) + i).value); x[j][i] = x[j][i] % 10; document.getElementById("num" + (j - 1) + i).value = x[j - 1][i] + 1; } document.getElementById("num" + j + i).value = x[j][i]; } x[0][i] = parseInt(document.getElementById("num0" + i).value); document.getElementById("num0" + i).value = x[0][i]; } } // Add one to the last row $('#add1').click(function() { x[6][0] = parseInt(document.getElementById("num60").value) + 1; document.getElementById("num60").value = x[6][0]; updateNumbers(); }); $('#add2').click(function() { document.getElementById("num61").value = parseInt(document.getElementById("num61").value) + 1; updateNumbers(); }); $('#add3').click(function() { document.getElementById("num62").value = parseInt(document.getElementById("num62").value) + 1; updateNumbers(); }); $('#add4').click(function() { document.getElementById("num63").value = parseInt(document.getElementById("num63").value) + 1; updateNumbers(); }); $('#add5').click(function() { document.getElementById("num64").value = parseInt(document.getElementById("num64").value) + 1; updateNumbers(); }); $('#add6').click(function() { document.getElementById("num65").value = parseInt(document.getElementById("num65").value) + 1; updateNumbers(); }); $('#add7').click(function() { document.getElementById("num66").value = parseInt(document.getElementById("num66").value) + 1; updateNumbers(); }); $('#add8').click(function() { document.getElementById("num67").value = parseInt(document.getElementById("num67").value) + 1; updateNumbers(); }); // Add row to row $('#clear').click(function() { for (var i = 0; i < 6; i++) { $("#num" + 6 + i).value = $("#num" + 6 + (i + 1)).value; } /* for (i = 6; i > -1; i--) { for (var j = 6; j > -1; j--) { document.getElementById("num" + j + (i + 1)).value = parseInt(document.getElementById("num" + j + (i + 1)).value) + parseInt(document.getElementById("num" + j + i).value); updateNumbers(); } } */ }); // Start of the page $(document).ready(function() { initalUpdateNumbers(); }); // Allows only Number Keys function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; } return true; }
JavaScript
0
@@ -2408,16 +2408,21 @@ value = +5; // $(%22#num%22
0f24291b5be1383d4cf8d106d3aea50e1e70ba8d
Remove obsolete require gl-shader
aoshader.js
aoshader.js
var glslify = require("glslify") var fs = require("fs") var createShader = require("gl-shader") var mat4 = require('gl-matrix').mat4 module.exports = function(game, opts) { return new ShaderPlugin(game, opts); }; module.exports.pluginInfo = { clientOnly: true, loadAfter: ['voxel-stitch', 'game-shell-fps-camera'], }; function ShaderPlugin(game, opts) { this.shell = game.shell; this.stitcher = game.plugins.get('voxel-stitch'); if (!this.stitcher) throw new Error('voxel-shader requires voxel-stitch plugin'); // for tileCount uniform and updateTexture event this.meshes = opts.meshes || game.voxels.meshes if (!this.meshes) throw new Error('voxel-shader requires "meshes" option or game.voxels.meshes set to array of voxel-mesher meshes') this.camera = game.plugins.get('game-shell-fps-camera'); if (!this.camera) throw new Error('voxel-shader requires game-shell-fps-camera plugin'); // for camera view matrix this.perspectiveResize = opts.perspectiveResize !== undefined ? opts.perspectiveResize : true; this.cameraNear = opts.cameraNear !== undefined ? opts.cameraNear : 0.1; this.cameraFar = opts.cameraFar !== undefined ? opts.cameraFar : 200.0; this.cameraFOV = opts.cameraFOV !== undefined ? opts.cameraFOV : 45.0; this.projectionMatrix = mat4.create(); this.enable(); } ShaderPlugin.prototype.enable = function() { this.shell.on('gl-init', this.onInit = this.ginit.bind(this)); this.shell.on('gl-render', this.onRender = this.render.bind(this)); if (this.perspectiveResize) this.shell.on('gl-resize', this.onResize = this.updateProjectionMatrix.bind(this)); this.stitcher.on('updateTexture', this.onUpdateTexture = this.updateTexture.bind(this)); }; ShaderPlugin.prototype.disable = function() { this.shell.removeListener('gl-init', this.onInit); this.shell.removeListener('gl-render', this.onRender); if (this.onResize) this.shell.removeListener('gl-resize', this.onResize); this.stitcher.removeListener('updateTexture', this.onUpdateTexture); }; ShaderPlugin.prototype.updateTexture = function(texture) { this.texture = texture; // used in tileMap uniform } ShaderPlugin.prototype.ginit = function() { this.shader = this.createAOShader(); this.updateProjectionMatrix(); this.viewMatrix = mat4.create(); }; ShaderPlugin.prototype.updateProjectionMatrix = function() { mat4.perspective(this.projectionMatrix, this.cameraFOV*Math.PI/180, this.shell.width/this.shell.height, this.cameraNear, this.cameraFar) }; ShaderPlugin.prototype.render = function() { var gl = this.shell.gl this.camera.view(this.viewMatrix) gl.enable(gl.CULL_FACE) gl.enable(gl.DEPTH_TEST) // TODO: is this right? see https://github.com/mikolalysenko/ao-shader/issues/2 //gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) //gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.enable(gl.BLEND) // premultiply alpha when loading textures, so can use gl.ONE blending, see http://stackoverflow.com/questions/11521035/blending-with-html-background-in-webgl // TODO: move to gl-texture2d? gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true) //Bind the shader var shader = this.shader if (!shader) throw new Error('voxel-shader render() called before gl-init, shader=', this.shader) shader.bind() shader.attributes.attrib0.location = 0 shader.attributes.attrib1.location = 1 shader.uniforms.projection = this.projectionMatrix shader.uniforms.view = this.viewMatrix shader.uniforms.tileCount = this.stitcher.tileCount if (this.texture) shader.uniforms.tileMap = this.texture.bind() // if a texture is loaded for (var chunkIndex in this.meshes) { var mesh = this.meshes[chunkIndex] var triangleVAO = mesh.vertexArrayObjects.surface if (triangleVAO) { // if there are triangles to render shader.uniforms.model = mesh.modelMatrix triangleVAO.bind() gl.drawArrays(gl.TRIANGLES, 0, triangleVAO.length) triangleVAO.unbind() } } }; ShaderPlugin.prototype.createAOShader = function() { return glslify({ vertex: './lib/ao.vsh', fragment: './lib/ao.fsh' })(this.shell.gl) }
JavaScript
0.000129
@@ -52,48 +52,8 @@ fs%22) -%0Avar createShader = require(%22gl-shader%22) %0A%0Ava
23d7bce1eab8f6b770ab2c527c23c3c0908ce907
Return same function if length doesn't differ
function/_define-length.js
function/_define-length.js
'use strict'; var test = function (a, b) {}, desc, defineProperty , generate, mixin; try { Object.defineProperty(test, 'length', { configurable: true, writable: false, enumerable: false, value: 1 }); } catch (ignore) {} if (test.length === 1) { // ES6 desc = { configurable: true, writable: false, enumerable: false }; defineProperty = Object.defineProperty; module.exports = function (fn, length) { desc.value = length; return defineProperty(fn, 'length', desc); }; } else { mixin = require('../object/mixin'); generate = (function () { var cache = []; return function (l) { var args, i = 0; if (cache[l]) return cache[l]; args = []; while (l--) args.push('a' + (++i).toString(36)); return new Function('fn', 'return function (' + args.join(', ') + ') { return fn.apply(this, arguments); };'); }; }()); module.exports = function (src, length) { var target = generate(length)(src); try { mixin(target, src); } catch (ignore) {} return target; }; }
JavaScript
0.999998
@@ -11,16 +11,58 @@ t';%0A%0Avar + toUint = require('../number/to-uint')%0A , test = @@ -102,16 +102,16 @@ roperty%0A - , gene @@ -447,16 +447,82 @@ ngth) %7B%0A +%09%09length = toUint(length);%0A%09%09if (fn.length === length) return fn;%0A %09%09desc.v @@ -993,22 +993,100 @@ ngth) %7B%0A - %09%09var +target;%0A%09%09length = toUint(length);%0A%09%09if (src.length === length) return src;%0A%09%09 target =
90368be1022f40636546f742362a8f6cb83744d1
Remove old pages from docs build
docs/src/Root.js
docs/src/Root.js
/** @jsx React.DOM */ 'use strict'; var React = require('react'); var Router = require('react-router-component'); var HomePage = require('./HomePage'); var GettingStartedPage = require('./GettingStartedPage'); var ComponentsPage = require('./ComponentsPage'); var NotFoundPage = require('./NotFoundPage'); var Locations = Router.Locations; var Location = Router.Location; var NotFound = Router.NotFound; var PagesHolder = React.createClass({ render: function () { return ( <Locations contextual> <Location path="/" handler={HomePage} /> <Location path="/index.html" handler={HomePage} /> <Location path="/getting-started.html" handler={GettingStartedPage} /> <Location path="/components.html" handler={ComponentsPage} /> <NotFound handler={NotFoundPage} /> </Locations> ); } }); var Root = React.createClass({ statics: { /** * Get the doctype the page expects to be rendered with * * @returns {string} */ getDoctype: function () { return '<!doctype html>'; }, /** * Get the list of pages that are renderable * * @returns {Array} */ getPages: function () { return [ 'index.html', 'getting-started.html', 'css.html', 'components.html', 'javascript.html' ]; }, renderToString: function (props) { return Root.getDoctype() + React.renderComponentToString(Root(props)); }, /** * Get the Base url this app sits at * This url is appended to all app urls to make absolute url's within the app. * * @returns {string} */ getBaseUrl: function () { return '/'; } }, render: function () { // Dump out our current props to a global object via a script tag so // when initialising the browser environment we can bootstrap from the // same props as what each page was rendered with. var browserInitScriptObj = { __html: "window.INITIAL_PROPS = " + JSON.stringify(this.props) + ";\n" + // console noop shim for IE8/9 "(function (w) {\n" + " var noop = function () {};\n" + " if (!w.console) {\n" + " w.console = {};\n" + " ['log', 'info', 'warn', 'error'].forEach(function (method) {\n" + " w.console[method] = noop;\n" + " });\n" + " }\n" + "}(window));\n" }; var head = { __html: '<title>React Bootstrap</title>' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />' + '<meta name="viewport" content="width=device-width, initial-scale=1.0" />' + '<link href="vendor/bootstrap/bootstrap.css" rel="stylesheet" />' + '<link href="vendor/bootstrap/docs.css" rel="stylesheet" />' + '<link href="vendor/codemirror/codemirror.css" rel="stylesheet" />' + '<link href="vendor/codemirror/solarized.css" rel="stylesheet" />' + '<link href="vendor/codemirror/syntax.css" rel="stylesheet" />' + '<link href="assets/style.css" rel="stylesheet" />' + '<!--[if lt IE 9]>' + '<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>' + '<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>' + '<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>' + '<script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-shim.js"></script>' + '<script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-sham.js"></script>' + '<![endif]-->' }; return ( <html> <head dangerouslySetInnerHTML={head} /> <body> <Locations path={Root.getBaseUrl() + this.props.initialPath}> <Location path={Root.getBaseUrl() + '*'} handler={PagesHolder} /> </Locations> <script dangerouslySetInnerHTML={browserInitScriptObj} /> <script src="vendor/codemirror/codemirror.js" /> <script src="vendor/codemirror/javascript.js" /> <script src="vendor/JSXTransformer.js" /> <script src="assets/bundle.js" /> </body> </html> ); } }); module.exports = Root;
JavaScript
0
@@ -1288,64 +1288,17 @@ 'c -ss.html',%0A 'components.html',%0A 'javascript +omponents .htm
bba2cfe90230b4b4d8120c61b90ede8cc8febb0a
Use let instead of var
frontend/reducers/index.js
frontend/reducers/index.js
import Shogi from '../src/shogi'; import * as CONST from '../constants/actionTypes'; const InitialState = { board: Shogi.Board, isHoldingPiece: undefined }; const ShogiReducer = (state = InitialState, action) => { switch (action.type) { case CONST.HOLD_PIECE: if (action.piece.type == '*') { return state; } else { let newBoard = state.board.enhanceMovablePoint(action.piece); return Object.assign({}, { board: newBoard, isHoldingPiece: action.piece }); } case CONST.MOVE_PIECE: // if same piece click, release piece. if (state.isHoldingPiece) { var newBoard = state.board.movePiece(state.isHoldingPiece, action.piece); return Object.assign({}, { board: newBoard }, { isHoldingPiece: undefined }); } else { return Object.assign({}, state, { isHoldingPiece: action.piece }); } default: return state; } }; export default ShogiReducer;
JavaScript
0.000001
@@ -599,11 +599,11 @@ -var +let new
03285add2a2362d37bf89dbf9951c8274c4fd665
remove test url
src/components/CropImg/CropImg.js
src/components/CropImg/CropImg.js
import React, {Component} from 'react'; import AvatarCropper from 'react-avatar-cropper'; import FileUpload from './FileUpload'; const styles = require('./CropImg.scss'); export default class CropImg extends Component { state = { cropperOpen: false, img: null, croppedImg: 'http://www.fillmurray.com/400/400' }; handleFileChange = (dataURI) => { this.setState({ img: dataURI, croppedImg: this.state.croppedImg, cropperOpen: true }); } handleCrop = (dataURI) => { this.setState({ cropperOpen: false, img: null, croppedImg: dataURI }); } handleRequestHide = () => { this.setState({ cropperOpen: false }); } render() { return ( <div> <div className="avatar-photo"> <FileUpload handleFileChange={this.handleFileChange} /> <div className="avatar-edit"> <span>Click to Pick Avatar</span> <i className="fa fa-camera"></i> </div> <img src={this.state.croppedImg} /> </div> {this.state.cropperOpen && <AvatarCropper onRequestHide={this.handleRequestHide} cropperOpen={this.state.cropperOpen} onCrop={this.handleCrop} image={this.state.img} width={400} height={400} /> } </div> ); } }
JavaScript
0.000002
@@ -289,41 +289,8 @@ g: ' -http://www.fillmurray.com/400/400 '%0A
685f34ee21c46ced2625657b6425329ae9512e2b
Remove js.js from jsScripts concat task
grunt/concat.js
grunt/concat.js
module.exports = { options: { separator: ' ', }, jsScripts: { src: [ '<%= globalConfig.source.js %>/scripts/js.js', '<%= globalConfig.source.js %>/scripts/**/*.js', '<%= globalConfig.source.js %>/*.js' ], dest: '<%= globalConfig.cms.js %>/scripts.js' }, jsVendor: { src: [ '<%= globalConfig.source.js %>/vendor/libs/**/*.js', '<%= globalConfig.source.js %>/vendor/plugins/**/*.js' ], dest: '<%= globalConfig.cms.js %>/vendor.js' }, jsAll: { src: [ '<%= globalConfig.source.js %>/vendor/libs/**/*.js', '<%= globalConfig.source.js %>/vendor/plugins/**/*.js', '<%= globalConfig.source.js %>/scripts/**/*.js', '<%= globalConfig.source.js %>/*.js' ], dest: '<%= globalConfig.cms.js %>/app.js' } };
JavaScript
0.000011
@@ -94,67 +94,8 @@ : %5B%0A - '%3C%25= globalConfig.source.js %25%3E/scripts/js.js',%0A
10f98a721cf9ac592ee9ad469f0d0fcca47e3610
Use current tenant for invoking SSO login
src/components/Login/LoginCtrl.js
src/components/Login/LoginCtrl.js
import React, { Component, PropTypes } from 'react'; // eslint-disable-line import { connect as reduxConnect } from 'react-redux'; // eslint-disable-line import { requestLogin, checkUser } from '../../loginServices'; import Login from './Login'; import SSOLogin from '../SSOLogin'; import css from './Login.css'; class LoginCtrl extends Component { static contextTypes = { store: PropTypes.object, router: PropTypes.object, authFail: PropTypes.bool, } static propTypes = { authFail: PropTypes.bool, autoLogin: PropTypes.shape({ username: PropTypes.string.isRequired, password: PropTypes.string.isRequired, }), } constructor(props, context) { super(props); this.store = context.store; this.router = context.router; this.handleSubmit = this.handleSubmit.bind(this); this.sys = require('stripes-loader'); // eslint-disable-line this.okapiUrl = this.sys.okapi.url; this.tenant = this.sys.okapi.tenant; this.initialValues = { username: '', password: '' }; this.ssoUrl = `${this.okapiUrl}/saml/login`; this.state = {}; this.handleSSOLogin = this.handleSSOLogin.bind(this); if (props.autoLogin && props.autoLogin.username) { this.handleSubmit(props.autoLogin); } } componentDidMount() { fetch(`${this.okapiUrl}/saml/check`, { headers: Object.assign({}, { 'X-Okapi-Tenant': this.tenant }) }) .then((response) => { if (response.status < 400) { this.setState({ssoActive: true }); } else { this.setState({ssoActive: false }); } }); } componentWillMount() { checkUser(this.okapiUrl, this.store, this.tenant); } handleSubmit(data) { requestLogin(this.okapiUrl, this.store, this.tenant, data).then((response) => { if (response.status >= 400) { // eslint-disable-next-line no-param-reassign this.initialValues.username = data.username; } }); } handleSSOLogin(e) { window.open(`${this.okapiUrl}/_/invoke/tenant/diku/saml/login`, '_self'); } render() { const authFail = this.props.authFail; return ( <div className={css.loginOverlay}> <Login onSubmit={this.handleSubmit} authFail={authFail} initialValues={this.initialValues} /> { this.state.ssoActive ? <SSOLogin handleSSOLogin={this.handleSSOLogin} /> : null } </div> ); } } function mapStateToProps(state) { return { authFail: state.okapi.authFailure }; } export default reduxConnect(mapStateToProps)(LoginCtrl);
JavaScript
0
@@ -2034,12 +2034,22 @@ ant/ -diku +$%7Bthis.tenant%7D /sam
3371d13b76b0ac513418dfe30c35bd2c7e09d3e4
Add releasePiece case for release holding piece.
frontend/reducers/shogi.js
frontend/reducers/shogi.js
import * as CONST from '../constants/actionTypes'; import Shogi from '../src/shogi'; const initialState = { holdingPiece: undefined, board: Shogi.Board, blackPieceStand: [], whitePieceStand: [] }; export default function shogi(state = initialState, action) { switch (action.type) { case CONST.HOLD_PIECE: if (action.piece.isEmpty()) return state; return Object.assign( {}, state, { holdingPiece: action.piece } ); case CONST.ENHANCE_MOVABLE_POINT: if (action.piece.isEmpty()) return state; return Object.assign( {}, state, { board: state.board.enhanceMovablePoint(action.piece) } ); case CONST.MOVE_PIECE: // if same piece click, release piece. if (state.holdingPiece) { let newBoard = state.board.movePiece(state.holdingPiece, action.piece); if (newBoard.takedPiece) { const takedPiece = newBoard.takedPiece; // TODO: Use constants. Refactor. switch (newBoard.takedPiece.team()) { case 'white': return Object.assign( {}, state, { board: newBoard, holdingPiece: undefined, blackPieceStand: state.blackPieceStand.concat([takedPiece.toOpponentPiece()]) } ); case 'black': return Object.assign( {}, state, { board: newBoard, holdingPiece: undefined, whitePieceStand: state.whitePieceStand.concat([takedPiece.toOpponentPiece()]) } ); } } else { return Object.assign( {}, state, { board: newBoard, holdingPiece: undefined } ); } } else { return Object.assign({}, state, { holdingPiece: action.piece }); } default: return state; } }
JavaScript
0
@@ -444,32 +444,243 @@ .piece %7D%0A );%0A + case CONST.RELEASE_PIECE:%0A if (action.piece.isEmpty()) return state;%0A%0A return Object.assign(%0A %7B%7D,%0A state,%0A %7B board: state.board.cloneBoard().clearAttrs(), holdingPiece: undefined %7D%0A );%0A case CONST.ENH
7fe00d6926114c3614059558a872b3b26e5846eb
fix add scheme function
arches/app/media/js/views/rdm/modals/add-scheme-form.js
arches/app/media/js/views/rdm/modals/add-scheme-form.js
define(['jquery', 'backbone', 'models/concept', 'models/value'], function ($, Backbone, ConceptModel, ValueModel) { return Backbone.View.extend({ initialize: function(e){ var self = this; this.modal = this.$el.find('.modal'); this.modal.on('hidden.bs.modal', function () { self.$el.find("input[type=text], textarea").val(""); }); // test to see if select2 has already been applied to the dom if (! this.modal.find('.select2').attr('id')){ this.select2 = this.modal.find('.select2').select2(); } this.modal.validate({ ignore: null, rules: { label: "required", language_dd: "required" }, submitHandler: function(form) { var model = new ConceptModel({ id: '00000000-0000-0000-0000-000000000003' }) var label = new ValueModel({ value: $(form).find("[name=label]").val(), language: $(form).find("[name=language_dd]").val(), category: 'label', datatype: 'text', type: 'prefLabel' }); var subconcept = new ConceptModel({ values: [label], relationshiptype: 'narrower' }); model.set('subconcepts', [subconcept]); model.save(function() { var modal = self.$el.find('#add-scheme-form'); this.modal.modal('hide'); $('.modal-backdrop.fade.in').remove(); // a hack for now self.trigger('conceptSchemeAdded'); }, self); } }); } }); });
JavaScript
0.000004
@@ -876,149 +876,8 @@ ) %7B%0A - var model = new ConceptModel(%7B%0A id: '00000000-0000-0000-0000-000000000003'%0A %7D)%0A @@ -1239,26 +1239,21 @@ var -subconcept +model = new C @@ -1359,16 +1359,17 @@ arrower' +, %0A @@ -1385,69 +1385,64 @@ -%7D);%0A model.set('subconcepts', %5Bsubconcept%5D + nodetype: 'ConceptSchemeGroup'%0A %7D );%0A
393d6029df393b095301a12eba38dfd9ef500696
Remove precision from axis numbering format specifier.
final/js/index.js
final/js/index.js
var data; function main() { wordCountChart("#wc"); percentEnglish('#eng_fw', 0); percentEnglish('#eng_ul', 1); percentEnglish('#eng_ofk', 2); $('#novelty').load('data/novelty.html'); } function wordCountChart(id) { var margin = {top: 20, right: 20, bottom: 30, left: 40}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var x0 = d3.scale.ordinal() .rangeRoundBands([0, width], .1); var x1 = d3.scale.ordinal(); var y = d3.scale.linear() .range([height, 0]); var color = d3.scale.ordinal() .range(["#98abc5", "#8a89a6"]); var xAxis = d3.svg.axis() .scale(x0) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left") .tickFormat(d3.format(".2s")); var svg = d3.select(id).append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.csv("data/wc.csv", function(error, data) { var countNames = d3.keys(data[0]).filter(function(key) { return key !== "Title"; }); data.forEach(function(d) { d.counts = countNames.map(function(name) { return {name: name, value: +d[name]}; }); }); x0.domain(data.map(function(d) { return d.Title; })); x1.domain(countNames).rangeRoundBands([0, x0.rangeBand()]); y.domain([0, d3.max(data, function(d) { return d3.max(d.counts, function(d) { return d.value; }); })]); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text("Number of words"); var state = svg.selectAll(".state") .data(data) .enter().append("g") .attr("class", "g") .attr("transform", function(d) { return "translate(" + x0(d.Title) + ",0)"; }); state.selectAll("rect") .data(function(d) { return d.counts; }) .enter().append("rect") .attr("width", x1.rangeBand()) .attr("x", function(d) { return x1(d.name); }) .attr("y", function(d) { return y(d.value); }) .attr("height", function(d) { return height - y(d.value); }) .style("fill", function(d) { return color(d.name); }); var legend = svg.selectAll(".legend") .data(countNames.slice()) .enter().append("g") .attr("class", "legend") .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; }); legend.append("rect") .attr("x", width - 18) .attr("width", 18) .attr("height", 18) .style("fill", color); legend.append("text") .attr("x", width - 24) .attr("y", 9) .attr("dy", ".35em") .style("text-anchor", "end") .text(function(d) { return d; }); }); } function percentEnglish(id, idx) { var width = 250, height = 250, radius = Math.min(width, height) / 2; var color = d3.scale.ordinal() .range(["#d0743c", "#a05d56"]); var arc = d3.svg.arc() .outerRadius(radius - 10) .innerRadius(0); var pie = d3.layout.pie() .sort(null) .value(function(d) { return d.percent; }); var svg = d3.select(id).append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); d3.json("data/english.json", function(error, data) { data[idx].sects.forEach(function(d) { d.name = d.name; d.percent = +d.percent; }); var g = svg.selectAll(".arc") .data(pie(data[idx].sects)) .enter().append("g") .attr("class", "arc"); g.append("path") .attr("d", arc) .style("fill", function(d) { return color(d.data.name); }); }); } main();
JavaScript
0
@@ -822,10 +822,8 @@ at(%22 -.2 s%22))
108f30db895d00bbe1e901af1c63649a880a76f0
add paging parameters to api getCollections call
static/js/lib/api.js
static/js/lib/api.js
// @flow import { fetchJSONWithCSRF, fetchWithCSRF } from "redux-hammock/django_csrf_fetch" import type { Collection } from "../flow/collectionTypes" export type VideoUpdatePayload = { description?: string } export function getCollections() { return fetchJSONWithCSRF(`/api/v0/collections/`) } export function getCollection(collectionKey: string) { return fetchJSONWithCSRF(`/api/v0/collections/${encodeURI(collectionKey)}/`) } export function updateCollection(collectionKey: string, payload: Object) { return fetchJSONWithCSRF(`/api/v0/collections/${encodeURI(collectionKey)}/`, { method: "PATCH", body: JSON.stringify(payload) }) } export function createCollection(payload: Collection) { return fetchJSONWithCSRF(`/api/v0/collections/`, { method: "POST", body: JSON.stringify(payload) }) } export function getVideo(videoKey: string) { return fetchJSONWithCSRF(`/api/v0/videos/${encodeURI(videoKey)}/`) } export function updateVideo(videoKey: string, payload: VideoUpdatePayload) { return fetchJSONWithCSRF(`/api/v0/videos/${encodeURI(videoKey)}/`, { method: "PATCH", body: JSON.stringify(payload) }) } export function deleteVideo(videoKey: string) { return fetchJSONWithCSRF(`/api/v0/videos/${videoKey}/`, { method: "DELETE" }) } export function uploadVideo(collectionKey: string, files: Array<Object>) { return fetchJSONWithCSRF(`/api/v0/upload_videos/`, { method: "POST", body: JSON.stringify({ collection: collectionKey, files: files }) }) } export function createSubtitle(payload: FormData) { return fetchWithCSRF(`/api/v0/upload_subtitles/`, { headers: { Accept: "application/json" }, method: "POST", body: payload }) } export function deleteSubtitle(videoSubtitleKey: number) { return fetchJSONWithCSRF(`/api/v0/subtitles/${videoSubtitleKey}/`, { method: "DELETE" }) } export async function getVideoAnalytics(videoKey: string) { if (window && window.ovsMockAnalyticsData) { return Promise.resolve({ key: videoKey, data: window.ovsMockAnalyticsData }) } let url = `/api/v0/videos/${videoKey}/analytics/` if (window && window.ovsMockAnalyticsError) { url += `?throw=1` } else if (window && window.ovsMockAnalytics) { url += `?mock=1&seed=${videoKey}` } const response = await fetchJSONWithCSRF(url) return { key: videoKey, data: response.data } }
JavaScript
0
@@ -2,16 +2,39 @@ / @flow%0A +import _ from 'lodash'%0A import %7B @@ -34,16 +34,16 @@ mport %7B%0A - fetchJ @@ -267,61 +267,334 @@ ons( -) %7B%0A return fetchJSONWithCSRF(%60/api/v0/collections/%60 +opts = %7B%7D) %7B%0A const %7B pagination %7D = opts%0A console.log(%22pp: %22, pagination)%0A let url = %22/api/v0/collections/%22%0A if (pagination) %7B%0A const queryParamsStr = _.map(pagination, (v, k) =%3E %7B%0A return %5Bk, v%5D.map(encodeURIComponent).join('=')%0A %7D).join('&')%0A url += %60?$%7BqueryParamsStr%7D%60%0A %7D%0A return fetchJSONWithCSRF(url )%0A%7D%0A
f382eec983c1db7405e191a2a67ec70aceed0d02
Update story.
assets/js/components/MediaErrorHandler/index.stories.js
assets/js/components/MediaErrorHandler/index.stories.js
/** * MediaErrorHandler Component Stories. * * Site Kit by Google, Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import MediaErrorHandler from './'; const ErrorComponent = () => { throw new Error( 'Something bad happened. 💣 (On purpose; ErrorComponent was used to simulate an error.)' ); }; const Template = () => ( <MediaErrorHandler> <ErrorComponent /> </MediaErrorHandler> ); export const Default = Template.bind( {} ); Default.storyName = 'Default'; Default.scenario = { label: 'Global/MediaErrorHandler', }; export default { title: 'Components/MediaErrorHandler', component: MediaErrorHandler, };
JavaScript
0
@@ -775,100 +775,8 @@ ror( -%0A%09%09'Something bad happened. %F0%9F%92%A3 (On purpose; ErrorComponent was used to simulate an error.)'%0A%09 );%0A%7D
30788ae2a10469f6c1c032241a45d12bbe121048
Rewrite a few lines in notes
src/components/admin/NotesForm.js
src/components/admin/NotesForm.js
import React, { Component, Fragment } from 'react' import { Formik } from 'formik' import api from 'api' import { AutoSaver, Field } from 'components/Forms' import { Box, Flex, IconButton } from '@hackclub/design-system' Box.form = Box.withComponent('form') class SingleNote extends Component { constructor(props) { super(props) this.state = { id: props.note.id, note: props.note } this.handleSubmit = this.handleSubmit.bind(this) } componentWillReceiveProps(nextProps) { if (this.state.id != nextProps.note.id) { this.setState({ id: nextProps.note.id, note: nextProps.note }) } } deleteNote(id) { const { authToken } = this.props console.log('making delete request') api.delete(`v1/notes/${id}`, { authToken }).then(json => { console.log('finished delete request') this.setState({ deleted: true }) }) } handleSubmit(values, { setSubmitting }) { const { authToken, applicationId } = this.props const { note, id } = this.state if (id) { api .patch(`v1/notes/${id}`, { authToken, data: values }) .then(json => { setSubmitting(false) }) .catch(e => { setSubmitting(false) }) } else { api .post(`v1/new_club_applications/${applicationId}/notes`, { authToken, data: values }) .then(json => { this.setState({ id: json.id }) setSubmitting(false) }) .catch(e => { setSubmitting(false) }) } } render() { const { id, note, deleted } = this.state if (deleted) { return null } else { return ( <Formik initialValues={note} enableReinitialize={true} onSubmit={this.handleSubmit} > {props => { const { handleChange, handleBlur, handleSubmit, isSubmitting, deleted, values } = props return ( <Box.form w={1} onSubmit={handleSubmit}> <Field name="body" label={`Note from user #${values.user_id}`} onBlur={e => { if (id && values.body === '') { this.deleteNote(id) } handleBlur(e) }} onChange={handleChange} value={values.body} type="textarea" bg="rgba(250,247,133,0.5)" renderMarkdown /> <AutoSaver handleSubmit={handleSubmit} isSubmitting={isSubmitting} values={values} /> </Box.form> ) }} </Formik> ) } } } export default class NotesForm extends Component { constructor(props) { super(props) this.state = { notes: [], status: 'loading' } this.loadNotes = this.loadNotes.bind(this) this.addNote = this.addNote.bind(this) } componentDidMount() { this.loadNotes(this.props.application.id) } componentWillReceiveProps(nextProps) { if (this.props.application.id !== nextProps.application.id) { this.loadNotes(nextProps.application.id) } } loadNotes(id) { const { authToken } = this.props api .get(`v1/new_club_applications/${id}/notes`, { authToken }) .then(json => { this.setState({ notes: json }) }) } addNote() { this.setState({ notes: [...this.state.notes, { created_at: new Date() }] }) } render() { const { authToken, application, updateApplicationList } = this.props const { status, notes } = this.state return ( <Fragment> <IconButton name="add" bg="success" circle onClick={this.addNote} /> {notes .sort((a, b) => new Date(b.created_at) - new Date(a.created_at)) .map((note, index) => ( <SingleNote key={index} note={note} applicationId={application.id} authToken={authToken} /> ))} </Fragment> ) } }
JavaScript
0.002718
@@ -710,49 +710,8 @@ ops%0A - console.log('making delete request')%0A @@ -773,53 +773,8 @@ %3E %7B%0A - console.log('finished delete request')%0A @@ -3050,51 +3050,8 @@ is)%0A - this.addNote = this.addNote.bind(this)%0A %7D%0A @@ -3421,36 +3421,37 @@ %7D)%0A .then( -json +notes =%3E %7B%0A th @@ -3467,38 +3467,14 @@ te(%7B -%0A notes: json%0A + notes %7D)%0A
998a594fac4603a5364682ec65548adaea15cbae
add Kahinah name to persona request
static/js/persona.js
static/js/persona.js
$("document").ready(function(){ $("#logout").hide(); function loggedIn(email){ $("#login").hide(); $("#logout").show(); $("#logout").text("Logout [" + email + "]"); } function loggedOut(){ $("#logout").hide(); $("#login").show(); } $("#login").on("click", function(e) { e.preventDefault(); navigator.id.get(mailVerified); }); $("#logout").on("click", function(e) { e.preventDefault(); $.get('/auth/logout', onlogout); }); function onlogout() { location.reload(true); } function mailVerified(assertion){ $.ajax({ type: 'POST', url: '/auth/login', data: {assertion: assertion}, success: function(res, status, xhr) { location.reload(true); }, //error: function(xhr, status, err) { alert("Didn't login: " + err); } }); } $.get('/auth/check', function (res) { if (res === "") loggedOut(); else loggedIn(res); }); });
JavaScript
0
@@ -356,16 +356,39 @@ Verified +, %7BsiteName: %22Kahinah%22%7D );%0A %7D);
b4a545b0aa8d916cafc288f0816c9a2dd975cac5
Fix validation plugin being loaded prior to jQuery
public/js/validate.js
public/js/validate.js
/** public/js/validate.js * * @author Victor Petrov <[email protected]> * @copyright (c) 2012, The Neuroinformatics Research Group at Harvard University. * @copyright (c) 2012, The President and Fellows of Harvard College. * @license New BSD License (see LICENSE file for details). */ define([ 'jquery', 'validation' //jquery plugin ], function ($) { "use strict"; var cache = {}, errors = {}, all_rules = {}; function register(id, rules) { all_rules[id] = rules; console.log('form ', id, rules); } function check(form) { console.log("validating form"); if ($(form).valid()) { console.log('form is valid!'); return true; } console.log('form is not valid'); return false; } function checkField(form_id, f) { var validator; if (cache[form_id] === undefined) { console.error('Form ' + form_id + ' has not been registered with the validator'); return false; } validator = cache[form_id]; if (!validator) { return false; } return validator.element(f); } function onSkipClick(e) { var btn = e.currentTarget, element = $(btn.ignoreEl); element.rules("remove", "required"); element.addClass('s-error-ignore s-skipped'); //hide the message (and the warning button). //todo: this is not working properly for Skip buttons on Firefox (it seems there is a different parent that //should be selected instead) $(btn).parent().addClass('s-hidden'); } function onTooltipClick(e) { var wrapper = $(e.currentTarget), label = wrapper.children('label'), buttons = wrapper.children('a.s-error-button'); //show label.toggleClass('s-hidden'); //more than 1 button? assume the hidden/visible classes are set up for toggling if (buttons.length > 1) { buttons.toggleClass('s-hidden'); } } /* must be used with the {'wrapper':'div'} config option for jQuery Validation plugin */ function errorPlacement(error, el) { //todo: figure out a way to get these values from a config var theme = { error: 'e', 'btn': 'e', 'skip': 'c' }, rules = el.rules(), //per-element option to allow user to ignore errors controls = el.closest('.s-input-container'), btn = $('<a class="s-button-mini s-error s-error-button" href="#" data-role="button" data-mini="true"' + ' data-inline="true" data-icon="alert" data-iconpos="notext" data-theme="' + theme.btn + '"></a>'), label = error.children('label').first(), btnSkip; label.addClass('ui-content ui-body ui-btn-up-' + theme.error + ' s-tooltip s-error s-error-label ui-overlay-shadow ui-corner-all'); error.css('display', 'inline'); //keeps inline inputs from being pushed down one row error.append(btn); //allow user to ignore errors for this field? if (rules.skip) { //ignore button is larger than the warning button, so the label needs more padding on the right label.addClass('s-error-label-far'); //the warning button should be hidden by default (will be displayed again when the label is hidden) btn.addClass('s-hidden'); //create a Skip button btnSkip = $('<a class="s-error s-error-button s-skip" href="#" data-role="button" data-mini="true" ' + 'data-inline="true" data-icon="check" data-iconpos="right" data-theme="' + theme.skip + '">Skip</a>'); //append button to the error container error.append(btnSkip); //create jqm button object btnSkip.button(); //half-hack: store the element in the button's DOM object btnSkip.get(0).ignoreEl = el; //register the click handler btnSkip.click(onSkipClick); } else { //if not, then just set enough padding on the label to make room for the warning button label.addClass('s-error-label-near'); } //errors are positioned absolutely, but they tend to be the first item (visually) in their container controls.prepend(error); //create the jqm object for the warning button btn.button(); //register click handler error.click(onTooltipClick); } function init(id, el) { console.log('validate.init', id, el, all_rules[id]); cache[id] = $(el).validate({ "rules": all_rules[id] }); } function clean() { errors = {}; } //set default validation options $.validator.setDefaults({ "ignore": ".s-error-ignore", "ignoreTitle": true, "onsubmit": false, "onfocusout": false, "onkeyup": false, "onclick": false, "focusInvalid": false, "errorClass": "s-error", "wrapper": 'div', "errorPlacement": errorPlacement }); //override default message jQuery.extend(jQuery.validator.messages, { required: 'This field is missing.', min: 'This value is too low.', max: 'This value is too high.' }); // callback takes 'value' and 'element' params $.validator.addMethod('skip', function () { return true; }, 'N/A'); //public API return { 'register': register, 'check': check, 'checkField': checkField, 'init': init, 'clean': clean }; });
JavaScript
0
@@ -2765,15 +2765,15 @@ el. -closest +parents ('.s @@ -2790,16 +2790,23 @@ tainer') +.last() ,%0A
ae5edd5a3af9e4d1786aec1ebf022206f3680a3c
update func call
src/components/settings/Tandem.js
src/components/settings/Tandem.js
/* * == BSD2 LICENSE == * Copyright (c) 2016, Tidepool Project * * This program is free software; you can redistribute it and/or modify it under * the terms of the associated License, which is identical to the BSD 2-Clause * License as published by the Open Source Initiative at opensource.org. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the License for more details. * * You should have received a copy of the License along with this program; if * not, you can obtain one from Tidepool Project at tidepool.org. * == BSD2 LICENSE == */ import React, { PropTypes } from 'react'; import _ from 'lodash'; import ClipboardButton from 'react-clipboard.js'; import styles from './Tandem.css'; import Header from './common/Header'; import Table from './common/Table'; import CollapsibleContainer from './common/CollapsibleContainer'; import { MGDL_UNITS, MMOLL_UNITS } from '../../utils/constants'; import * as tandemData from '../../utils/settings/tandemData'; import { tandemText } from '../../utils/settings/textData'; import { DISPLAY_VIEW, PRINT_VIEW } from './constants'; const Tandem = (props) => { const { bgUnits, copySettingsClicked, openedSections, pumpSettings, timePrefs, toggleProfileExpansion, user, view, } = props; function renderBreathingSpace() { if (view === PRINT_VIEW) { return ( <div className={styles.printNotes}> <hr /> <hr /> </div> ); } return null; } function openSection(sectionName) { if (view === PRINT_VIEW) { return true; } return _.get(openedSections, sectionName, false); } const tables = _.map(tandemData.basalSchedules(pumpSettings), (schedule) => { const basal = tandemData.basal(schedule, pumpSettings, bgUnits, styles); return ( <div className="settings-table-container" key={basal.scheduleName}> <CollapsibleContainer label={basal.title} labelClass={styles.collapsibleLabel} opened={openSection(basal.scheduleName)} toggleExpansion={_.partial(toggleProfileExpansion, basal.scheduleName)} twoLineLabel={false} > <Table rows={basal.rows} columns={basal.columns} tableStyle={styles.profileTable} /> </CollapsibleContainer> {renderBreathingSpace()} </div> ); }); return ( <div> <ClipboardButton className={styles.copyButton} button-title="For email or notes" data-clipboard-target="#copySettingsText" onSuccess={copySettingsClicked()} > <p>Copy as text</p> </ClipboardButton> <Header deviceDisplayName="Tandem" deviceMeta={tandemData.deviceMeta(pumpSettings, timePrefs)} printView={view === PRINT_VIEW} /> <div> <span className={styles.title}>Profile Settings</span> {tables} </div> <pre className={styles.copyText} id="copySettingsText"> {tandemText(user, pumpSettings, bgUnits)} </pre> </div> ); }; Tandem.propTypes = { bgUnits: PropTypes.oneOf([MMOLL_UNITS, MGDL_UNITS]).isRequired, copySettingsClicked: PropTypes.func.isRequired, deviceKey: PropTypes.oneOf(['tandem']).isRequired, openedSections: PropTypes.object.isRequired, pumpSettings: PropTypes.shape({ activeSchedule: PropTypes.string.isRequired, units: PropTypes.object.isRequired, deviceId: PropTypes.string.isRequired, basalSchedules: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string.isRequired, value: PropTypes.arrayOf( PropTypes.shape({ start: PropTypes.number.isRequired, rate: PropTypes.number.isRequired, }), ), }).isRequired, ).isRequired, bgTargets: PropTypes.objectOf( PropTypes.arrayOf( PropTypes.shape({ start: PropTypes.number.isRequired, target: PropTypes.number.isRequired, }) ).isRequired, ).isRequired, carbRatios: PropTypes.objectOf( PropTypes.arrayOf( PropTypes.shape({ start: PropTypes.number.isRequired, amount: PropTypes.number.isRequired, }) ).isRequired, ).isRequired, insulinSensitivities: PropTypes.objectOf( PropTypes.arrayOf( PropTypes.shape({ start: PropTypes.number.isRequired, amount: PropTypes.number.isRequired, }) ).isRequired, ).isRequired, }).isRequired, timePrefs: PropTypes.shape({ timezoneAware: PropTypes.bool.isRequired, timezoneName: PropTypes.oneOfType([PropTypes.string, null]), }).isRequired, toggleProfileExpansion: PropTypes.func.isRequired, user: PropTypes.object.isRequired, view: PropTypes.oneOf([DISPLAY_VIEW, PRINT_VIEW]).isRequired, }; Tandem.defaultProps = { deviceDisplayName: 'Tandem', deviceKey: 'tandem', view: DISPLAY_VIEW, }; export default Tandem;
JavaScript
0.000001
@@ -2760,18 +2760,16 @@ sClicked -() %7D%0A
fc0f4f69f56e2c7e05e5fa1391e44dbaaa202e77
Remove paragraph tag that adds extra spacing.
api/resolver.js
api/resolver.js
var key = require('../utils/key'); var sync = require('synchronize'); var request = require('request'); var _ = require('underscore'); // The API that returns the in-email representation. module.exports = function(req, res) { var term = req.query.text.trim(); if (/^http:\/\/giphy\.com\/\S+/.test(term)) { // Special-case: handle strings in the special URL form that are suggested by the commandHint // API. This is how the command hint menu suggests an exact Giphy image. handleIdString(term.replace(/^http:\/\/giphy\.com\//, ''), req, res); } else { // Else, assume it was a search string. handleSearchString(term, req, res); } }; function handleIdString(id, req, res) { var response; try { response = sync.await(request({ url: 'http://api.giphy.com/v1/gifs/' + encodeURIComponent(id), qs: { api_key: key }, gzip: true, json: true, timeout: 15 * 1000 }, sync.defer())); } catch (e) { res.status(500).send('Error'); return; } var image = response.body.data.images.original; var width = image.width > 600 ? 600 : image.width; var html = '<p><img style="max-width:100%;" src="' + image.url + '" width="' + width + '"/></p>'; res.json({ body: html }); } function handleSearchString(term, req, res) { var response; try { response = sync.await(request({ url: 'http://api.giphy.com/v1/gifs/random', qs: { tag: term, api_key: key }, gzip: true, json: true, timeout: 15 * 1000 }, sync.defer())); } catch (e) { res.status(500).send('Error'); return; } var data = response.body.data; // Cap at 600px wide var width = data.image_width > 600 ? 600 : data.image_width; var html = '<p><img style="max-width:100%;" src="' + data.image_url + '" width="' + width + '"/></p>'; res.json({ body: html }); }
JavaScript
0.000001
@@ -1131,35 +1131,32 @@ %0A var html = '%3C -p%3E%3C img style=%22max-w @@ -1206,36 +1206,32 @@ ' + width + '%22/%3E -%3C/p%3E ';%0A res.json(%7B%0A @@ -1237,32 +1237,122 @@ %0A body: html%0A + // Add raw:true if you're returning content that you want the user to be able to edit%0A %7D);%0A%7D%0A%0Afunctio @@ -1852,11 +1852,8 @@ = '%3C -p%3E%3C img @@ -1932,12 +1932,8 @@ '%22/%3E -%3C/p%3E ';%0A @@ -1959,16 +1959,105 @@ y: html%0A + // Add raw:true if you're returning content that you want the user to be able to edit%0A %7D);%0A%7D -%0A
97c8414b1a61a9993c98035fea3ed386cf7246e1
Fix error when uri.pathname is not set.
app/atom.js
app/atom.js
// Stopgap atom.js file for handling normal browser things that atom // does not yet have stable from the browser-side API. // - Opening external links in default web browser // - Saving files/downloads to disk $(document).ready(function() { if (typeof process === 'undefined') return; if (typeof process.versions['atom-shell'] === undefined) return; var remote = require('remote'); var shell = require('shell'); var http = require('http'); var url = require('url'); var fs = require('fs'); $('body').on('click', 'a', function(ev) { var uri = url.parse(ev.currentTarget.href); // Opening external URLs. if (uri.hostname && uri.hostname !== 'localhost') { shell.openExternal(ev.currentTarget.href); return false; } // File saving. var fileTypes = { tm2z: 'Package', mbtiles: 'Tiles', png: 'Image', jpg: 'Image', jpeg: 'Image' } var typeExtension = uri.pathname.split('.').pop().toLowerCase(); var typeLabel = fileTypes[typeExtension]; if (typeLabel) { var filePath = remote.require('dialog').showSaveDialog({ title: 'Save ' + typeLabel, defaultPath: '~/Untitled ' + typeLabel + '.' + typeExtension, filters: [{ name: typeExtension.toUpperCase(), extensions: [typeExtension]}] }); if (filePath) { window.Modal.show('atomexporting'); uri.method = 'GET'; var writeStream = fs.createWriteStream(filePath); var req = http.request(uri, function(res) { if (res.statusCode !== 200) return; res.pipe(writeStream); writeStream.on('finish', function() { window.Modal.close(); }); }); req.end(); } return false; } // Passthrough everything else. }); if (window.Modal) { window.Modal.options.templates.modalatomexporting = function() { return "\ <div id='atom-loading' class='modal round col6 margin3 pin-top top2 dark fill-dark'>\ <h3 class='center pad1y pad2x keyline-bottom'>Exporting</h3>\ <div class='row2 loading contain'></div>\ </div>"; }; } });
JavaScript
0
@@ -1024,16 +1024,17 @@ nsion = +( uri.path @@ -1037,16 +1037,23 @@ pathname + %7C%7C '') .split('
b3061857900cf1bb7748bc6204f2d8bf8acabb0e
Update RepeatedStringMatch
algorithms/RepeatedStringMatch.js
algorithms/RepeatedStringMatch.js
// Source : https://leetcode.com/problems/repeated-string-match/discuss/ // Author : Dean Shi // Date : 2017-10-09 /*************************************************************************************** * * Given two strings A and B, find the minimum number of times A has to be * repeated such that B is a substring of it. If no such solution, return -1. * * For example, with A = "abcd" and B = "cdabcdab". * * Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of * it; and B is not a substring of A repeated two times ("abcdabcd"). * * Note: * The length of A and B will be between 1 and 10000. * ***************************************************************************************/ /** * @param {string} A * @param {string} B * @return {number} */ var repeatedStringMatch = function(A, B) { let result = Math.ceil(B.length / A.length) const [str1, str2] = [A.repeat(result), A.repeat(result + 1)] if (str1.includes(B)) return result if (str2.includes(B)) return result + 1 return -1 };
JavaScript
0.000001
@@ -60,17 +60,8 @@ atch -/discuss/ %0A//
6b091f2a7f3c529bfa6d454d8fd6c68a5aac877d
Clarify arguments to seal.
app/main.js
app/main.js
exports = module.exports = function(IoC, negotiator, interpreter, translator, unsealer, sealer, logger) { var Tokens = require('tokens').Tokens; var tokens = new Tokens(); return Promise.resolve(tokens) .then(function(tokens) { var components = IoC.components('http://i.bixbyjs.org/tokens/Token'); return Promise.all(components.map(function(comp) { return comp.create(); } )) .then(function(formats) { formats.forEach(function(format, i) { var type = components[i].a['@type']; logger.info('Loaded token type: ' + type); tokens.format(type, format) }); }) .then(function() { return tokens; }); }) .then(function(tokens) { var api = {}; api.seal = function(msg, to, from, cb) { console.log('SEAL THIS MESSAGE!'); console.log(msg) var sealer; try { sealer = tokens.createSealer('application/jwt'); } catch (ex) { return cb(ex); } sealer.seal(msg, to, from, function(err, token) { console.log('SEALED IT!'); console.log(err) console.log(token) if (err) { return cb(err); } return cb(null, token); }); }; api.unseal = function(token, cb) { console.log('UNSEAL THIS') console.log(token) var unsealer; try { unsealer = tokens.createUnsealer(); } catch (ex) { return cb(ex); } unsealer.unseal(token, function(err, msg, extra) { if (err) { return cb(err); } console.log('MESSAG!'); console.log(msg); console.log(extra); return cb(null, msg.claims); }); }; api.negotiate = function(formats) { return negotiator.negotiate(formats); } api.cipher = function(ctx, options, cb) { if (typeof options == 'function') { cb = options; options = undefined; } options = options || {}; translator.translate(ctx, options, function(err, claims) { if (err) { return cb(err); } // Marshal context necessary for sealing the token. This includes this // that are conceptually "header" information, such as the audience, time // of issuance, expiration, etc. options.audience = ctx.audience; sealer.seal(claims, options, function(err, token) { if (err) { return cb(err); } return cb(null, token); }); }); } api.decipher = function(token, options, cb) { if (typeof options == 'function') { cb = options; options = undefined; } options = options || {}; unsealer.unseal(token, options, function(err, tok) { if (err) { return cb(err); } interpreter.interpret(tok, options, function(err, sctx) { if (err) { return cb(err); } return cb(null, sctx, tok); }); }); } return api; }); }; exports['@implements'] = 'http://i.bixbyjs.org/tokens'; exports['@singleton'] = true; exports['@require'] = [ '!container', 'http://i.bixbyjs.org/tokens/Negotiator', './interpreter', './translator', './unsealer', './sealer', 'http://i.bixbyjs.org/Logger' ];
JavaScript
0.000002
@@ -800,29 +800,43 @@ unction( +clai ms -g , -to, from +recipients, options , cb) %7B%0A @@ -898,19 +898,22 @@ ole.log( +clai ms -g )%0A @@ -1108,21 +1108,35 @@ eal( +clai ms -g , -to, from +recipients, options , fu
473d6beb428f32ebc2923191d9d46a4fda863e72
Update main.js
app/main.js
app/main.js
requirejs.config({ paths: { 'text': '../lib/require/text', 'durandal':'../lib/durandal/js', 'plugins' : '../lib/durandal/js/plugins', 'transitions' : '../lib/durandal/js/transitions', 'knockout': '../lib/knockout/knockout-3.1.0', 'bootstrap': '../lib/bootstrap/js/bootstrap', 'jquery': '../lib/jquery/jquery-1.9.1', 'react': '../lib/react/react', 'jsx': "../lib/react/jsx", 'JSXTransformer':'../lib/react/JSXTransformer' }, shim: { 'bootstrap': { deps: ['jquery'], exports: 'jQuery' } , 'react': { exports: 'react' }, 'JSXTransformer': { exports: "JSXTransformer" } } }); define(['durandal/system', 'durandal/app', 'durandal/viewLocator'], function (system, app, viewLocator) { //>>excludeStart("build", true); system.debug(true); //>>excludeEnd("build"); app.title = 'Durandal Starter Kit'; app.configurePlugins({ router:true, dialog: true }); app.start().then(function() { //Replace 'viewmodels' in the moduleId with 'views' to locate the view. //Look for partial views in a 'views' folder in the root. viewLocator.useConvention(); //Show the app by setting the root view model for our application with a transition. app.setRoot('viewmodels/shell', 'entrance'); }); });
JavaScript
0.000001
@@ -1513,12 +1513,14 @@ %7D);%0D%0A%7D); +%0D%0A
bc241e99347ff3054784a9a7e6e91c061faab9cb
Refactor snapshot loop with getInterval
app/main.js
app/main.js
import { TANK_PADDING, UI_WIDTH, settings, updateSetting, addUpdateListener, getSetting, getSavedSettings, loadSettings, restoreDefaultSettings, } from './settings.js'; import { simulateFrame, } from './simulation.js'; import { getRandomBody, } from './meebas/bodies.js'; import { range, } from './utils/arrays.js'; import { getSnapshot, toCsv, } from './utils/diagnostics.js'; import { createLoop, } from './utils/loop.js'; import { seedPrng, } from './utils/math.js'; import { getFrameRenderer, } from './view/animation.js'; import { canvas, } from './view/components.js'; import { e, appendById, } from './view/dom.js'; import { getInterface, } from './view/interface.js'; /** * @typedef {import('./simulation.js').Body} Body */ /** * @typedef {import('./utils/diagnostics.js').Snapshot} Snapshot */ const APP_ID = 'app'; const VIEW_ID = 'view'; const { core } = settings; const view = canvas(VIEW_ID, core.width, core.height); const renderFrame = getFrameRenderer(view); let oldWidth = core.width; let oldHeight = core.height; addUpdateListener(() => { const { width, height } = core; if (width !== oldWidth || height !== oldHeight) { view.width = width; view.height = height; oldWidth = width; oldHeight = height; } }); /** @type {Object<string, any>} */ const anyWindow = window; const MeebaFarm = {}; anyWindow.MeebaFarm = MeebaFarm; /** @type {Body[]} */ MeebaFarm.bodies = []; // ------ Setup Loop ------ /** @type {Snapshot[]} */ let snapshots = []; let nextSnapshot = Infinity; let snapshotFrequency = 0; const { start, stop, reset } = createLoop((tick, delay) => { MeebaFarm.bodies = simulateFrame(MeebaFarm.bodies, tick, delay); renderFrame(MeebaFarm.bodies); if (tick > nextSnapshot) { nextSnapshot = tick + snapshotFrequency; snapshots.push(getSnapshot(tick, MeebaFarm.bodies)); } }); // ------ Setup Debug API ------ MeebaFarm.pause = stop; MeebaFarm.resume = start; MeebaFarm.reset = () => { // eslint-disable-next-line no-console console.log('Starting simulation with seed:', core.seed); seedPrng(core.seed); MeebaFarm.bodies = range(core.startingMeebaCount).map(getRandomBody); reset(); }; MeebaFarm.updateSetting = updateSetting; MeebaFarm.getSetting = getSetting; MeebaFarm.getSavedSettings = getSavedSettings; MeebaFarm.loadSettings = loadSettings; MeebaFarm.restoreDefaultSettings = restoreDefaultSettings; MeebaFarm.snapshots = { start(frequency = 5000) { nextSnapshot = 0; snapshotFrequency = frequency; }, stop() { nextSnapshot = Infinity; }, clear() { snapshots = []; }, getCsv() { return toCsv(snapshots); }, getRaw() { return snapshots; }, now() { return getSnapshot(performance.now(), MeebaFarm.bodies); }, }; // ------ Setup UI ------ const frameElement = e( 'div', { style: { width: `${UI_WIDTH + 2 * TANK_PADDING}px` } }, e('div', { style: { float: 'left', width: `${UI_WIDTH}px`, }, }, getInterface(MeebaFarm)), e('div', { style: { float: 'right', padding: `${TANK_PADDING}px`, width: '0px', }, }, view), ); appendById(APP_ID, frameElement); // ------ Run ------ MeebaFarm.reset(); MeebaFarm.resume();
JavaScript
0
@@ -500,24 +500,76 @@ ';%0Aimport %7B%0A + getInterval,%0A%7D from './utils/tweens.js';%0Aimport %7B%0A getFrameRe @@ -897,16 +897,83 @@ ot%0A */%0A%0A +/**%0A * @typedef %7Bimport('./utils/tweens.js').Tweener%7D Tweener%0A */%0A%0A const AP @@ -1652,62 +1652,66 @@ %5B%5D;%0A -let nextSnapshot = Infinity;%0Alet snapshotFrequency = 0 +%0A/** @type %7BTweener%7Cnull%7D */%0Alet snapshotAtInterval = null ;%0A%0Ac @@ -1881,130 +1881,57 @@ if ( -tick %3E nextSnapshot) %7B%0A nextSnapshot = tick + snapshotFrequency;%0A snapshots.push(getSnapshot(tick, MeebaFarm.bodies) +snapshotAtInterval) %7B%0A snapshotAtInterval(tick );%0A @@ -2540,49 +2540,118 @@ -nextS +s napshot - = 0;%0A snapshotFrequency = +AtInterval = getInterval((tick) =%3E %7B%0A snapshots.push(getSnapshot(tick, MeebaFarm.bodies));%0A %7D, fre @@ -2656,16 +2656,17 @@ requency +) ;%0A %7D,%0A%0A @@ -2684,31 +2684,33 @@ -nextS +s napshot - = Infinity +AtInterval = null ;%0A
348cd19be1990882b65ef290bfe92e13a8450cf7
FIx cache
app/main.js
app/main.js
angular.module('onibusgv', [ 'ionic', 'filters', 'home', 'search', 'horario', 'itinerario', 'linha', 'services.sql' ]) .run([ '$ionicPlatform', 'sqlService', function($ionicPlatform, sqlService) { $ionicPlatform.ready(function() { if (window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleDefault(); } sqlService.init(); }); } ]) .config([ '$stateProvider', '$urlRouterProvider', '$ionicConfigProvider', function($stateProvider, $urlRouterProvider, $ionicConfigProvider) { $ionicConfigProvider.backButton.text('Voltar'); $stateProvider .state('home', { url: '/home', cache: true, templateUrl: 'views/pages/home/home.html', controller: 'HomeCtrl' }) .state('search', { url: '/search/:searchQuery', cache: true, templateUrl: 'views/pages/search/search.html', controller: 'SearchCtrl' }) .state('tabs', { url: '/tab', abstract: true, cache: true, templateUrl: 'views/pages/linha/linha.html', controller: 'LinhaCtrl' }) .state('tabs.horarios', { url: '/horarios/:linha/:dia', cache: true, views: { 'horario-tab': { templateUrl: 'views/pages/horario/horario.html', controller: 'HorarioCtrl' } } }) .state('tabs.itinerario', { url: '/itinerarios/:linha', cache: true, views: { 'itinerario-tab': { templateUrl: 'views/pages/itinerario/itinerario.html', controller: 'ItinerarioCtrl' } } }); $urlRouterProvider.otherwise('/home'); } ]);
JavaScript
0.000001
@@ -1048,35 +1048,36 @@ %0A cache: -tru +fals e,%0A templ
f86e0dfa283239b1ffd64215559573395c2956c2
disable devTools
app/main.js
app/main.js
const {app, BrowserWindow} = require('electron') const path = require('path') const url = require('url') let winMain = null // create main window let version = app.getVersion() //const nameLog = process.env.USERNAME const name = process.env.USER console.log(name) console.log(version) function createWindow () { // Create browser window winMain = new BrowserWindow({ width: 1024, height: 728, minWidth: 720, minHeight: 400, backgroundColor: '#c3c3c3', show: false }) // Load index.html winMain.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })) // wait all DOM are ready to show but not access winMain.webContents.on('did-finish-load', () => { winMain.show() winMain.focus() }) // Open devtools winMain.webContents.openDevTools() winMain.on('closed', () => { winMain = null }) } // Run create windows function app.on('ready', () => { createWindow() // spawnSync('sudo erwb') //electron-settings }) // Quit when all windows are closed app.on('window-all-closed', () => { app.quit() })
JavaScript
0.000001
@@ -813,16 +813,19 @@ vtools%0A + // winMain
c29f99386b4fe19ab0136a2c0c70dadcc1ce9c47
fix #59 修复登陆页不能复制粘贴
app/main.js
app/main.js
/** * Main Process - bos client entry * * @file main.js * @author mudio([email protected]) */ import {app, ipcMain} from 'electron'; import {isDev} from './utils/helper'; import AutoUpdater from './main/AutoUpdater'; import MenuManager from './main/MenuManager'; import Development from './main/Development'; import WindowManager from './main/WindowManager'; let _window = null; const shouldQuit = app.makeSingleInstance(() => { if (_window) { if (_window.isMinimized()) { _window.restore(); } _window.focus(); } }); if (shouldQuit) { app.quit(); } app.on('ready', () => { // 开启登陆 _window = WindowManager.fromLogin(`file://${__dirname}/login.html`); // 监听通知 ipcMain.on('notify', (evt, msg) => { if (msg.type === 'login_success') { const win = WindowManager.fromApp(`file://${__dirname}/app.html#/region`); _window.close(); _window = win; // 初始化菜单 MenuManager.initMenu(); // 初始化自动更新 AutoUpdater.from(win); } else if (msg.type === 'logout') { const win = WindowManager.fromLogin(`file://${__dirname}/login.html`); _window.close(); _window = win; } }); // 启动开发者模式 if (isDev) { const developer = new Development(); developer.supportInspect(); developer.installExtensions(); _window.openDevTools(); } }); app.on('window-all-closed', () => app.quit());
JavaScript
0
@@ -957,65 +957,8 @@ in;%0A - // %E5%88%9D%E5%A7%8B%E5%8C%96%E8%8F%9C%E5%8D%95%0A MenuManager.initMenu();%0A @@ -1399,24 +1399,66 @@ ols();%0A %7D +%0A%0A // %E5%88%9D%E5%A7%8B%E5%8C%96%E8%8F%9C%E5%8D%95%0A MenuManager.initMenu(); %0A%7D);%0A%0Aapp.on
92f37554fd78ccd617538565cc36fb05858441de
Add minify json function
gulpfile.dev.js
gulpfile.dev.js
/** * This <server-gardu-reporter> project created by : * Name : syafiq * Date / Time : 20 June 2017, 10:58 AM. * Email : [email protected] * Github : syafiqq */ var gulp = require('gulp'); var watch = require('gulp-watch'); var cleanCSS = require('gulp-clean-css'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var htmlmin = require('gulp-htmlmin'); var pump = require('pump'); var imagemin = require('gulp-imagemin'); gulp.task('move-application-assets', function () { return gulp.src('./raw/application/**', {base: './raw/application/'}) .pipe(gulp.dest('./application/')); }); gulp.task('move-assets', function () { return gulp.src('./raw/assets/**', {base: './raw/assets/'}) .pipe(gulp.dest('./public/assets/')); }); gulp.task('minify-img', function () { return gulp.src('./raw/assets/**/{*.png,*.jpg,*.jpeg}', {base: './raw/assets/'}) .pipe(gulp.dest('./public/assets/')); }); gulp.task('minify-js', function (cb) { pump([ gulp.src(['./raw/assets/**/*.js', '!./raw/assets/**/*.min.js'], {base: './raw/assets/'}) .pipe(rename({ suffix: ".min", extname: ".js" })), gulp.dest('./public/assets/') ], cb ); }); gulp.task('minify-css', function () { return gulp.src(['./raw/assets/**/*.css', '!./raw/assets/**/*.min.css'], {base: './raw/assets/'}) .pipe(rename({ suffix: ".min", extname: ".css" })) .pipe(gulp.dest('./public/assets/')); }); gulp.task('minify-html', function () { return gulp.src('./raw/application/**/{*.php,*.html}', {base: './raw/application/'}) .pipe(gulp.dest('./application/')); }); gulp.task('watch-move-application-assets', function () { // Callback mode, useful if any plugin in the pipeline depends on the `end`/`flush` event return watch('./raw/application/**', function () { return gulp.src('./raw/application/**', {base: './raw/application/'}) .pipe(gulp.dest('./application/')); }); }); gulp.task('watch-move-assets', function () { // Callback mode, useful if any plugin in the pipeline depends on the `end`/`flush` event return watch('./raw/assets/**', function () { return gulp.src('./raw/assets/**', {base: './raw/assets/'}) .pipe(gulp.dest('./public/assets/')); }); }); gulp.task('watch-minify-img', function () { // Callback mode, useful if any plugin in the pipeline depends on the `end`/`flush` event return watch('./raw/assets/**/{*.png,*.jpg,*.jpeg}', function () { return gulp.src('./raw/assets/**/{*.png,*.jpg,*.jpeg}', {base: './raw/assets/'}) .pipe(gulp.dest('./public/assets/')); }); }); gulp.task('watch-minify-js', function () { // Callback mode, useful if any plugin in the pipeline depends on the `end`/`flush` event return watch(['./raw/assets/**/*.js', '!./raw/assets/**/*.min.js'], function (cb) { pump([ gulp.src(['./raw/assets/**/*.js', '!./raw/assets/**/*.min.js'], {base: './raw/assets/'}) .pipe(rename({ suffix: ".min", extname: ".js" })), gulp.dest('./public/assets/') ], cb ); }); }); gulp.task('watch-minify-css', function () { // Callback mode, useful if any plugin in the pipeline depends on the `end`/`flush` event return watch(['./raw/assets/**/*.css', '!./raw/assets/**/*.min.css'], function () { return gulp.src(['./raw/assets/**/*.css', '!./raw/assets/**/*.min.css'], {base: './raw/assets/'}) .pipe(rename({ suffix: ".min", extname: ".css" })) .pipe(gulp.dest('./public/assets/')); }); }); gulp.task('watch-minify-html', function () { // Callback mode, useful if any plugin in the pipeline depends on the `end`/`flush` event return watch('./raw/application/**/{*.php,*.html}', function () { return gulp.src('./raw/application/**/{*.php,*.html}', {base: './raw/application/'}) .pipe(gulp.dest('./application/')); }); });
JavaScript
0.000453
@@ -252,24 +252,57 @@ lp-watch');%0A +var util = require('gulp-util');%0A var cleanCSS @@ -512,16 +512,62 @@ gemin'); +%0Avar jsonMinify = require('gulp-json-minify'); %0A%0Agulp.t @@ -1871,16 +1871,301 @@ );%0A%7D);%0A%0A +gulp.task('minify-json', function ()%0A%7B%0A return gulp.src(%5B'./raw/assets/**/*.json', '!./raw/assets/**/*.min.json'%5D, %7Bbase: './raw/assets/'%7D)%0A .pipe(rename(%7B%0A suffix: %22.min%22,%0A extname: %22.json%22%0A %7D))%0A .pipe(gulp.dest('./public/assets/'));%0A%7D);%0A %0Agulp.ta @@ -4631,28 +4631,540 @@ pplication/'));%0A %7D);%0A%7D);%0A +%0Agulp.task('watch-minify-json', function ()%0A%7B%0A // Callback mode, useful if any plugin in the pipeline depends on the %60end%60/%60flush%60 event%0A return watch(%5B'./raw/assets/**/*.json', '!./raw/assets/**/*.min.json'%5D, function ()%0A %7B%0A return gulp.src(%5B'./raw/assets/**/*.json', '!./raw/assets/**/*.min.json'%5D, %7Bbase: './raw/assets/'%7D)%0A .pipe(rename(%7B%0A suffix: %22.min%22,%0A extname: %22.json%22%0A %7D))%0A .pipe(gulp.dest('./public/assets/'));%0A %7D);%0A%7D);%0A
6a71a03e3736a462bcf77545eb46782979eb1ad0
add ability to update student rating, close #125
src/containers/student/ratings.js
src/containers/student/ratings.js
import React from 'react'; import StarRating from 'react-star-rating'; import './style.scss'; export default (props) => { const updateRating = () => { props.updateStudent(props.data); }; return ( <div className="card"> {console.log(props.data.ratings.logic, 'STARS')} <div className="card-content black-text"> <span className="card-title">Ratings</span> <hr /> <div className="stars"> <span>Logic</span> <StarRating className="star" size={30} name="airbnb-rating" totalStars={7} rating={props.data.ratings.logic} onRatingClick={updateRating} /> </div> <div className="stars"> <span>Motivation</span> <StarRating className="star" size={30} name="airbnb-rating" totalStars={7} /> </div> <div className="stars"> <span>Effort</span> <StarRating className="star" size={30} name="airbnb-rating" totalStars={7} /> </div> <div className="stars"> <span>Likebility</span> <StarRating className="star" size={30} name="airbnb-rating" totalStars={7} /> </div> <div className="stars"> <span>Explanation</span> <StarRating className="star" size={30} name="airbnb-rating" totalStars={7} /> </div> <div className="stars"> <span>Confidence</span> <StarRating className="star" size={30} name="airbnb-rating" totalStars={7} /> </div> </div> </div> ); };
JavaScript
0
@@ -140,16 +140,24 @@ ting = ( +_, stars ) =%3E %7B%0A @@ -163,28 +163,57 @@ -props.updateS +console.log('updateRating');%0A const s tudent -( + = prop @@ -222,108 +222,134 @@ data -);%0A %7D;%0A return (%0A %3Cdiv className=%22card%22%3E%0A %7Bconsole.log(props.data.ratings.logic, 'STARS')%7D +;%0A student.ratings%5Bstars.name%5D = stars.rating;%0A props.updateStudent(student);%0A %7D;%0A return (%0A %3Cdiv className=%22card%22%3E %0A @@ -593,36 +593,40 @@ ize=%7B30%7D - name=%22airbnb-rating +%0A name=%22logic %22%0A @@ -733,16 +733,43 @@ Rating%7D%0A + editing=%7Btrue%7D%0A @@ -867,32 +867,44 @@ %3CStarRating +%0A className=%22star @@ -908,54 +908,206 @@ tar%22 - size=%7B30%7D name=%22airbnb-rating%22 totalStars=%7B7%7D +%0A size=%7B30%7D%0A totalStars=%7B7%7D%0A name=%22motiv%22%0A rating=%7Bprops.data.ratings.motiv%7D%0A onRatingClick=%7BupdateRating%7D%0A editing=%7Btrue%7D%0A /%3E%0A @@ -1196,32 +1196,44 @@ %3CStarRating +%0A className=%22star @@ -1237,54 +1237,208 @@ tar%22 - size=%7B30%7D name=%22airbnb-rating%22 totalStars=%7B7%7D +%0A size=%7B30%7D%0A totalStars=%7B7%7D%0A name=%22effort%22%0A rating=%7Bprops.data.ratings.effort%7D%0A onRatingClick=%7BupdateRating%7D%0A editing=%7Btrue%7D%0A /%3E%0A @@ -1531,32 +1531,44 @@ %3CStarRating +%0A className=%22star @@ -1572,54 +1572,206 @@ tar%22 - size=%7B30%7D name=%22airbnb-rating%22 totalStars=%7B7%7D +%0A size=%7B30%7D%0A totalStars=%7B7%7D%0A name=%22ethic%22%0A rating=%7Bprops.data.ratings.ethic%7D%0A onRatingClick=%7BupdateRating%7D%0A editing=%7Btrue%7D%0A /%3E%0A @@ -1865,32 +1865,44 @@ %3CStarRating +%0A className=%22star @@ -1906,54 +1906,210 @@ tar%22 - size=%7B30%7D name=%22airbnb-rating%22 totalStars=%7B7%7D +%0A size=%7B30%7D%0A totalStars=%7B7%7D%0A name=%22explain%22%0A rating=%7Bprops.data.ratings.explain%7D%0A onRatingClick=%7BupdateRating%7D%0A editing=%7Btrue%7D%0A /%3E%0A @@ -2210,16 +2210,28 @@ arRating +%0A classNa @@ -2243,54 +2243,208 @@ tar%22 - size=%7B30%7D name=%22airbnb-rating%22 totalStars=%7B7%7D +%0A size=%7B30%7D%0A totalStars=%7B7%7D%0A name=%22confid%22%0A rating=%7Bprops.data.ratings.confid%7D%0A onRatingClick=%7BupdateRating%7D%0A editing=%7Btrue%7D%0A /%3E%0A
9efb161d405226438d27a73c628f49b445e01aa6
Convert to either pure CommonJS or pure ES6 (ES6, in this case)
gatsby-browser.js
gatsby-browser.js
import React from 'react' import ComponentRenderer from './src/templates/component-renderer-with-pagination' exports.replaceComponentRenderer = ({ props, loader }) => { if (props.layout) { return null } return <ComponentRenderer {...props} loader={loader} /> }
JavaScript
0.999125
@@ -110,18 +110,29 @@ %0A%0Aexport -s. + default %7B%0A replaceC @@ -147,18 +147,17 @@ Renderer - = +: (%7B prop @@ -176,16 +176,18 @@ =%3E %7B%0A + + if (prop @@ -202,16 +202,18 @@ ) %7B%0A + return n @@ -222,11 +222,15 @@ l%0A + + %7D%0A%0A + re @@ -283,10 +283,14 @@ der%7D /%3E%0A + %7D%0A %7D%0A
ff7a84e822e68c4effc45e0e6135d924e6604fc4
Fix /members permission for listing members.
generate-rules.js
generate-rules.js
const {forEach, split} = require('lodash') const ADMIN = 'zedeck' const ID_STRING_LENGTH = 20 const USER_ID_STRING_LENGTH = 28 const PROFILES_NODE = 'members' const ROLES_NODE = 'memberRoles' const ROLES = [ 'clerk', 'church_elder', 'elder', 'department_director', 'department_secretary', 'department_assistant' ] function root(path) { let r = 'root' const path_components = split(path, '/') forEach(path_components, c => { if (c) { // component isn't empty if (c === 'auth.uid') r += `.child(${c})` else r += `.child('${c}')` } }) return { matchUserID() { return `(${r}.val() === auth.uid)` }, exists() { return `(${r}.exists())` } } } function requiresAuth() { return '(auth !== null)' } function hasProfile() { return `(${requiresAuth()} && ${root(PROFILES_NODE + '/auth.uid').exists()})` } function hasAnyRoles(roles) { if (Array.isArray(roles)) { let r = '' forEach(roles, role => { r += `root.child('${ROLES_NODE}').child(auth.uid).child('${role}').exists() || ` }) return `(${requiresAuth()} && (${r.substr(0, r.length - 4)}))` } return '' } function location(name) { return { matchUserID() { return `(${requiresAuth()} && (auth.uid === ${name}))` }, inStringEnum(list) { let r = '' forEach(list, e => { r += `${name} === '${e}' || ` }) return `(${r.substr(0, r.length - 4)})` } } } function child(name, newData) { let source = 'data' if (newData) source = 'newData' return { matchUserID() { return `(${requiresAuth()} && auth.uid === ${source}.child('${name}').val())` }, equalToString(value) { return `(${source}.child('${name}').val() === '${value}')` }, equalTo(value) { return `(${source}.child('${name}').val() === ${value})` }, exists() { return `(${source}.child('${name}').exists())` } } } function fields(definitions) { let r = '' let fields = [] let fieldChecks = '' forEach(definitions, (def, key) => { let field = '' if ('type' in def) { if (def.type === 'bool' || def.type === 'boolean') { field += `newData.child('${key}').isBoolean()` } else if (def.type === 'string') { field += `newData.child('${key}').isString()` if ('min' in def) field += ` && newData.child('${key}').val().length >= ${def.min}` if ('max' in def) field += ` && newData.child('${key}').val().length <= ${def.max}` } else if (def.type === 'uid') { field += `${requiresAuth()} && newData.child('${key}').isString() && newData.child('${key}').val().length === ${USER_ID_STRING_LENGTH}` } else if (def.type === 'user.uid') { field += `${requiresAuth()} && newData.child('${key}').isString() && newData.child('${key}').val() === auth.uid` } else if (def.type === 'id') { field += `newData.child('${key}').isString() && newData.child('${key}').val().length === ${ID_STRING_LENGTH}` } else if (def.type === 'timestamp' || def.type === 'number') { field += `newData.child('${key}').isNumber()` } if (def.optional) field = `(newData.hasChild('${key}') && ${field}) || !newData.hasChild('${key}')` else fields.push(key) fieldChecks += `(${field}) && ` } }) r += `newData.hasChildren(['${fields.join("', '")}'])` if (fieldChecks) r += ` && ${fieldChecks.substr(0, fieldChecks.length - 4)}` return `(${r})` } function operations(rules) { let r = '' // Create if (rules.create) r += `(newData.exists() && !data.exists() && ${rules.create}) || ` // Edit/modify if (rules.edit) r += `(newData.exists() && data.exists() && ${rules.edit}) || ` // Delete if (rules.delete) r += `(!newData.exists() && data.exists() && ${rules.delete}) || ` return r.substr(0, r.length - 4) } const rules = { memberRoles: { $uid: { '.read': `${hasAnyRoles([ADMIN])} || ${location('$uid').matchUserID()}`, $role: { '.validate': `newData.isBoolean() && ${location('$role').inStringEnum(ROLES)}`, '.write': `${hasAnyRoles([ADMIN])}` } } }, members: { $uid: { '.read': hasProfile(), '.write': `${location('$uid').matchUserID()} || ${hasAnyRoles(['clerk', ADMIN])}` } }, prayers: { '.read': hasProfile(), $prayer_id: { '.validate': fields({ poster: {type: 'user.uid', optional: true}, content: {type: 'string', min: 7, max: 4096}, anonymous: {type: 'bool'}, createdAt: {type: 'timestamp'} }) + ` && ((${child('anonymous', true).equalTo('false')} && ${child('poster', true).exists()}) || ${child('anonymous', true).equalTo('true')})`, '.write': operations({ 'create': `${hasProfile()} && ${child('poster', true).matchUserID()}`, 'edit': `${child('poster').matchUserID()} || ${hasAnyRoles(['clerk', 'zedeck'])}`, 'delete': `${child('poster').matchUserID()} || ${hasAnyRoles(['clerk', 'zedeck'])}` }) } }, prayerViews: { // Listing '.read': hasProfile(), $prayer_id: { '.validate': `newData.isNumber()`, '.write': operations({ 'create': `${hasProfile()} && newData.val() === 1`, 'edit': `${hasProfile()}`, 'delete': `false` }) } }, prayerComments: { '.read': hasProfile(), $prayer_id: { '.validate': fields({ prayerId: {type: 'id'}, content: {type: 'string', min: 3, max: 4096}, createdBy: {type: 'uid'}, createdAt: {type: 'timestamp'} }), '.write': operations({ 'create': `${hasProfile()} && ${child('createdBy', true).matchUserID()}`, 'edit': `false`, 'delete': `${hasProfile()} || ${child('createdBy', false).matchUserID()} || ${hasAnyRoles(['clerk', ADMIN])}` }) } }, membersPrayingForPrayerRequests: { '.read': hasProfile(), $prayer_id: { $uid: { '.validate': 'newData.isBoolean()', '.write': `${hasProfile()} && root.child('prayers').child($prayer_id).exists() && ${location('$uid').matchUserID()}`, } } } } console.log(JSON.stringify({ rules }, null, 2))
JavaScript
0
@@ -4259,38 +4259,24 @@ members: %7B%0A - $uid: %7B%0A '.read': @@ -4268,32 +4268,35 @@ %7B%0A '.read': +%60$%7B hasProfile(),%0A @@ -4291,17 +4291,32 @@ rofile() -, +%7D%60,%0A%0A $uid: %7B %0A '
d41f7ed637d335f000ec850425a421af02529f63
Fix AutoLaunch with appimage
gui/src/main/autolaunch.js
gui/src/main/autolaunch.js
const AutoLaunch = require('auto-launch') const autoLauncher = new AutoLaunch({ name: 'Cozy-Desktop', isHidden: true }) module.exports.isEnabled = () => autoLauncher.isEnabled() module.exports.setEnabled = (enabled) => { autoLauncher.isEnabled().then((was) => { if (was !== enabled) { if (enabled) { autoLauncher.enable() } else { autoLauncher.disable() } } }) }
JavaScript
0
@@ -39,44 +39,22 @@ h')%0A +%0A const -autoLauncher = new AutoLaunch( +opts = %7B%0A @@ -93,16 +93,124 @@ : true%0A%7D +%0A%0Aif (process.env.APPIMAGE) %7B%0A opts.path = process.env.APPIMAGE%0A%7D%0A%0Aconst autoLauncher = new AutoLaunch(opts )%0A%0Amodul
bd822bebcd755b69eac48ee1bc68c128442f81fb
Disable arrows when you have no more results in a direction.
zephyr/static/js/search.js
zephyr/static/js/search.js
var cached_term = ""; var cached_matches = []; var cached_index; var cached_table = $('table.focused_table'); function get_zid_as_int(object) { return parseInt(object.attr("zid"), 10); } function match_on_visible_text(row, search_term) { // You can't select on :visible, since that includes hidden elements that // take up space. return row.find(".message_content, .sender_name, .message_header, .message_time") .text().toLowerCase().indexOf(search_term) !== -1; } function search(term, highlighted_message, reverse) { // term: case-insensitive text to search for // highlighted_message: the current location of the pointer. Ignored // on cached queries // reverse: boolean as to whether the search is forward or backwards // // returns a message object containing the search term. var previous_header_matched = false; var focused_table = $('table.focused_table'); if ((term !== cached_term) || (cached_table[0] !== focused_table[0])) { cached_term = term; cached_matches = []; cached_index = null; cached_table = focused_table; var selected_zid = get_zid_as_int(highlighted_message); focused_table.find('.message_row, .recipient_row').each(function (index, row) { row = $(row); if (previous_header_matched || (match_on_visible_text(row, term))) { previous_header_matched = false; if (row.hasClass("recipient_row")) { previous_header_matched = true; } else { cached_matches.push(row); var zid = get_zid_as_int(row); if ((reverse && (zid <= selected_zid)) || (!reverse && (zid >= selected_zid) && !cached_index)) { // Keep track of the closest match going up or down. cached_index = cached_matches.length - 1; } } } }); return cached_matches[cached_index]; } if (reverse) { if (cached_index > 0) { cached_index--; } } else { if (cached_index < cached_matches.length - 1) { cached_index++; } } return cached_matches[cached_index]; } function highlight_match(row, search_term) { $('table tr').removeHighlight(); row.highlight(search_term); row = row.prev('.recipient_row'); if ((row.length !== 0) && (match_on_visible_text(row, search_term))) { row.highlight(search_term); } } function search_button_handler(reverse) { var query = $('#search').val().toLowerCase(); var res = search(query, selected_message, reverse); if (!res) { return; } select_message_by_id(res.attr("zid")); highlight_match(res, query); scroll_to_selected(); } function clear_search_cache() { cached_term = ""; } function focus_search() { $("#search").width("504px"); $("#search_arrows").addClass("input-append"); $('.search_button').show(); } function initiate_search() { $('#search').val('').focus(); } function clear_search() { $('table tr').removeHighlight(); // Reset the width to that in the stylesheet. If you change it there, change // it here. $('#search').val('').width("610px"); $("#search_arrows").removeClass("input-append"); $('.search_button').hide(); clear_search_cache(); } function something_is_highlighted() { return $(".highlight").length > 0; } function update_highlight_on_narrow() { highlight_match(selected_message, cached_term); clear_search_cache(); }
JavaScript
0
@@ -487,24 +487,365 @@ !== -1;%0A%7D%0A%0A +function disable_search_arrows_if(condition, affected_arrows) %7B%0A var i, button;%0A%0A for (i = 0; i %3C affected_arrows.length; i++) %7B%0A button = $(%22#search_%22 + affected_arrows%5Bi%5D);%0A if (condition) %7B%0A button.attr(%22disabled%22, %22disabled%22);%0A %7D else %7B%0A button.removeAttr(%22disabled%22);%0A %7D%0A %7D%0A%7D%0A%0A function sea @@ -882,24 +882,24 @@ reverse) %7B%0A - // term: @@ -2354,24 +2354,104 @@ %7D);%0A%0A + disable_search_arrows_if(cached_matches.length === 0, %5B%22up%22, %22down%22%5D);%0A%0A retu @@ -2689,24 +2689,242 @@ %7D%0A %7D%0A%0A + disable_search_arrows_if(cached_matches.length === 0, %5B%22up%22, %22down%22%5D);%0A disable_search_arrows_if(cached_index === 0, %5B%22up%22%5D);%0A disable_search_arrows_if(cached_index === cached_matches.length - 1, %5B%22down%22%5D);%0A%0A return c @@ -3714,24 +3714,77 @@ n').show();%0A + disable_search_arrows_if(false, %5B%22up%22, %22down%22%5D);%0A %7D%0A%0Afunction @@ -4037,24 +4037,24 @@ h(%22610px%22);%0A - $(%22#sear @@ -4086,32 +4086,90 @@ input-append%22);%0A + $(%22#search_up, #search_down%22).removeAttr(%22disabled%22);%0A $('.search_b
f711baefab7471d7503afe20438ea26a2d2bc879
Use navigator.languages in preference to navigator.language (Chrome does not set navigator.language based on user preferences).
guacamole/src/main/webapp/app/settings/services/preferenceService.js
guacamole/src/main/webapp/app/settings/services/preferenceService.js
/* * Copyright (C) 2015 Glyptodon LLC * * 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. */ /** * A service for setting and retrieving browser-local preferences. Preferences * may be any JSON-serializable type. */ angular.module('settings').provider('preferenceService', function preferenceServiceProvider() { /** * Reference to the provider itself. * * @type preferenceServiceProvider */ var provider = this; /** * The storage key of Guacamole preferences within local storage. * * @type String */ var GUAC_PREFERENCES_STORAGE_KEY = "GUAC_PREFERENCES"; /** * All valid input method type names. * * @type Object.<String, String> */ var inputMethods = { /** * No input method is used. Keyboard events are generated from a * physical keyboard. * * @constant * @type String */ NONE : 'none', /** * Keyboard events will be generated from the Guacamole on-screen * keyboard. * * @constant * @type String */ OSK : 'osk', /** * Keyboard events will be generated by inferring the keys necessary to * produce typed text from an IME (Input Method Editor) such as the * native on-screen keyboard of a mobile device. * * @constant * @type String */ TEXT : 'text' }; /** * Returns the key of the language currently in use within the browser. * This is not necessarily the user's desired language, but is rather the * language user by the browser's interface. * * @returns {String} * The key of the language currently in use within the browser. */ var getDefaultLanguageKey = function getDefaultLanguageKey() { // Pull browser language, falling back to US English var language = navigator.language || navigator.browserLanguage || 'en_US'; // Convert to format used internally return language.replace(/-/g, '_'); }; /** * All currently-set preferences, as name/value pairs. Each property name * corresponds to the name of a preference. * * @type Object.<String, Object> */ this.preferences = { /** * Whether translation of touch to mouse events should emulate an * absolute pointer device, or a relative pointer device. * * @type Boolean */ emulateAbsoluteMouse : true, /** * The default input method. This may be any of the values defined * within preferenceService.inputMethods. * * @type String */ inputMethod : inputMethods.NONE, /** * The key of the desired display language. * * @type String */ language : getDefaultLanguageKey() }; // Get stored preferences, ignore inability to use localStorage try { if (localStorage) { var preferencesJSON = localStorage.getItem(GUAC_PREFERENCES_STORAGE_KEY); if (preferencesJSON) angular.extend(provider.preferences, JSON.parse(preferencesJSON)); } } catch (ignore) {} // Factory method required by provider this.$get = ['$injector', function preferenceServiceFactory($injector) { // Required services var $rootScope = $injector.get('$rootScope'); var $window = $injector.get('$window'); var service = {}; /** * All valid input method type names. * * @type Object.<String, String> */ service.inputMethods = inputMethods; /** * All currently-set preferences, as name/value pairs. Each property name * corresponds to the name of a preference. * * @type Object.<String, Object> */ service.preferences = provider.preferences; /** * Persists the current values of all preferences, if possible. */ service.save = function save() { // Save updated preferences, ignore inability to use localStorage try { if (localStorage) localStorage.setItem(GUAC_PREFERENCES_STORAGE_KEY, JSON.stringify(service.preferences)); } catch (ignore) {} }; // Persist settings when window is unloaded $window.addEventListener('unload', service.save); // Persist settings upon navigation $rootScope.$on('$routeChangeSuccess', function handleNavigate() { service.save(); }); // Persist settings upon logout $rootScope.$on('guacLogout', function handleLogout() { service.save(); }); return service; }]; });
JavaScript
0
@@ -2967,16 +2967,17 @@ guage = +( navigato @@ -2982,24 +2982,116 @@ tor.language +s && navigator.languages%5B0%5D)%0A %7C%7C navigator.language%0A %7C%7C navigato @@ -3111,18 +3111,36 @@ uage +%0A %7C%7C 'en -_US ';%0A%0A
093114e9308034b16e443dfe270a4b8250d1fa65
Fix parameter annotation
lib/node_modules/@stdlib/math/generics/random/shuffle/lib/factory.js
lib/node_modules/@stdlib/math/generics/random/shuffle/lib/factory.js
'use strict'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); var isArrayLike = require( '@stdlib/utils/is-array-like' ); var isString = require( '@stdlib/utils/is-string' ).isPrimitive; var deepCopy = require( '@stdlib/utils/copy' ); var floor = require( '@stdlib/math/base/special/floor' ); var randu = require( '@stdlib/math/base/random/randu' ).factory; var validate = require( './validate.js' ); // FACTORY // /** * Returns a function to create a random permutation of elements from an array-like object. * * @param {Options} [options] - function options * @param {PositiveInteger} [options.seed] - integer-valued seed * @param {string} [options.copy="shallow"] - default copy option (`deep`, `shallow` or `none`) * @throws {TypeError} `options` must be an object * @returns {Function} shuffle function * * @example * var shuffle = factory( 249 ); * var data = [ 3, 8, 4, 8 ]; * var out = shuffle( data ); * // returns [ 4, 3, 8, 8 ] */ function factory( config ) { var conf; var rand; var err; if ( config ) { if ( config.seed ) { rand = randu({ 'seed': config.seed }); } conf = {}; err = validate( conf, config ); if ( err ) { throw err; } if ( conf.copy === void 0 ) { conf.copy = 'shallow'; } } else { conf = { 'copy': 'shallow' }; rand = randu(); } /** * Generate a random permutation of elements in `arr`. * * @param {ArrayLike} arr - array-like object to shuffle * @param {Options} [options] - function options * @param {string} [options.copy=true] - string indicating whether to return a copy (`deep`,`shallow` or `none`) * @throws {TypeError} first argument must be array-like * @throws {TypeError} `options` must be an object * @throws {TypeError} must provide valid options * @returns {ArrayLike} the shuffled array-like object * * @example * var data = [ 1, 2, 3 ]; * var out = shuffle( data ); * // e.g., returns [ 3, 1, 2 ] * * @example * var data = [ 1, 2, 3 ]; * var out = shuffle( data, false ); * var bool = ( data === out ); * // returns true */ function shuffle( arr, options ) { var strflg; var level; var opts; var err; var out; var tmp; var N; var i; var j; opts = deepCopy( conf ); strflg = isString( arr ); if ( strflg ) { arr = arr.split( '' ); opts.copy = 'none'; } if ( !isArrayLike( arr ) ) { throw new TypeError( 'invalid input argument. First argument must be array-like. Value: `' + arr + '`.' ); } if ( arguments.length > 1 ) { err = validate( opts, options ); if ( err ) { throw err; } } switch ( opts.copy ) { case 'deep': level = 2; break; case 'none': level = 0; break; case 'shallow': level = 1; break; } N = arr.length; out = deepCopy( arr, level ); // Note: we skip the first element, as no further swaps are possible given that all other indices are excluded from swapping... for ( i = N - 1; i > 0; i-- ) { // Generate an integer index on the interval [0,i]: j = floor( rand() * (i+1.0) ); // Swap elements: tmp = out[ i ]; out[ i ] = out[ j ]; out[ j ] = tmp; } if ( strflg ) { out = arr.join( '' ); } return out; } // end FUNCTION shuffle() setReadOnly( shuffle, 'SEED', rand.SEED ); setReadOnly( shuffle, 'PRNG', rand.PRNG ); return shuffle; } // end FUNCTION factory() // EXPORTS // module.exports = factory;
JavaScript
0.000007
@@ -1549,13 +1549,8 @@ copy -=true %5D -
52639dd03968fefce57612772c701d243d7d0276
use reporter
gulpfile.babel.js
gulpfile.babel.js
'use strict'; import babel from 'gulp-babel'; import babelCompiler from 'babel-core'; import del from 'del'; import gulp from 'gulp'; import eslint from 'gulp-eslint'; import istanbul from 'gulp-istanbul'; import jscs from 'gulp-jscs'; import jshint from 'gulp-jshint'; import mocha from 'gulp-mocha'; const configFiles = './gulpfile.babel.js' , srcFiles = 'src/*.js' , testFiles = 'test/*.js' , destDir = './lib/'; gulp.task('clean', () => del(destDir)); gulp.task('lint', ['clean'], () => { return gulp.src([configFiles, srcFiles, testFiles]) .pipe(eslint()) .pipe(eslint.formatEach('./node_modules/eslint-path-formatter')) .pipe(eslint.failOnError()) .pipe(jscs({ esnext: true })) .pipe(jshint()) .pipe(jshint.reporter('default')) .pipe(jshint.reporter('fail')); }); gulp.task('compile', ['lint'], () => { return gulp.src(srcFiles) .pipe(babel({ auxiliaryCommentBefore: 'istanbul ignore next', modules: 'common' })) .pipe(gulp.dest(destDir)); }); gulp.task('build', ['compile']); gulp.task('test', ['build'], cb => { gulp.src([destDir + '*.js']) .pipe(istanbul()) .pipe(istanbul.hookRequire()) .on('finish', () => { gulp.src([testFiles]) .pipe(mocha({ compilers: { js: babelCompiler } })) .pipe(istanbul.writeReports()) .on('end', cb); }); });
JavaScript
0.000004
@@ -707,32 +707,59 @@ t: true%0A %7D))%0A + .pipe(jscs.reporter())%0A .pipe(jshint
abcae06465eefc551775a14b1f3d4b0b329027e0
Handle Dockerflow endpoints
gulpfile.babel.js
gulpfile.babel.js
import gulp from 'gulp'; import fs from 'fs'; import path from 'path'; import autoprefixer from 'gulp-autoprefixer'; import cleanCSS from 'gulp-clean-css'; import concat from 'gulp-concat'; import data from 'gulp-data'; import fse from 'fs-extra'; import gitRev from 'git-rev'; import gutil from 'gulp-util'; import nunjucks from 'gulp-nunjucks'; import sourcemaps from 'gulp-sourcemaps'; import stylus from 'gulp-stylus'; import webserver from 'gulp-webserver'; const buildDirectory = './build'; const stylesheets = [ './media/stylus/main.styl', './media/stylus/home.styl', './media/stylus/tabzilla-customizations.styl', './media/stylus/fonts.styl', ]; const neededModules = [ './node_modules/mozilla-tabzilla/**/*', ]; const images = './media/img/*'; const fonts = './media/fonts/*'; function _log(req, res, next) { gutil.log(req.method, req.url, 'HTTP/' + req.httpVersion); next(); } gulp.task('default', ['build']); gulp.task('build', [ 'build:html', 'build:css', 'build:copy-needed-modules', 'build:copy-images', 'build:copy-fonts', 'build:version.json', ]); gulp.task('build:html', () => { const context = { sites: JSON.parse(fs.readFileSync('./sites.json')), } gulp.src('./templates/index.html') .pipe(data(() => context)) .pipe(nunjucks.compile()) .pipe(gulp.dest(buildDirectory)); }); gulp.task('build:css', () => { gulp.src(stylesheets) .pipe(sourcemaps.init()) .pipe(stylus()) .pipe(autoprefixer()) .pipe(concat('main.css')) .pipe(cleanCSS()) .pipe(sourcemaps.write('.')) .pipe(gulp.dest(path.join(buildDirectory, 'media/css'))) }); gulp.task('build:copy-needed-modules', () => { gulp.src(neededModules, { base: '.' }) .pipe(gulp.dest(buildDirectory)); }); gulp.task('build:copy-images', () => { gulp.src(images) .pipe(gulp.dest(path.join(buildDirectory, path.dirname(images)))); }); gulp.task('build:copy-fonts', () => { gulp.src(fonts) .pipe(gulp.dest(path.join(buildDirectory, path.dirname(fonts)))); }); gulp.task('build:version.json', () => { gitRev.long(commitHash => { const version = { 'source': 'https://github.com/openjck/datacenter', 'version': process.env.NODE_ENV || '', 'commit': commitHash, }; fse.outputJson(path.join(buildDirectory, 'app/version.json'), version); }); }); gulp.task('watch', ['build'], () => { gulp.watch('./templates/*.html', ['build:html']); gulp.watch(stylesheets, ['build:css']); gulp.watch(neededModules, ['build:copy-needed-modules']); gulp.watch(images, ['build:copy-images']); gulp.watch(fonts, ['build:copy-fonts']); }); gulp.task('serve', ['watch'], () => { gulp.src(buildDirectory) .pipe(webserver({ host: '0.0.0.0', port: process.env.PORT || 3000, middleware: _log, })); });
JavaScript
0.000001
@@ -808,16 +808,708 @@ ts/*';%0A%0A +const versionFilename = path.join(buildDirectory, 'app/version.json');%0A%0A%0A// Handle endpoints required by Dockerflow%0A// See https://github.com/mozilla-services/Dockerflow/blob/643b1a26dfef80e9fc0b5a4d356d92d73edd012d/README.md%0Afunction _handleDockerflowEndpoints(req, res, next) %7B%0A switch (req.url) %7B%0A case '/__heartbeat__':%0A case '/__lbheartbeat__':%0A res.writeHead(200);%0A res.end('OK');%0A break;%0A case '/__version__':%0A const versionContents = fs.readFileSync(versionFilename);%0A res.writeHead(200, %7B'Content-Type': 'application/json'%7D);%0A res.end(versionContents);%0A break;%0A %7D%0A%0A next();%0A%7D%0A %0Afunctio @@ -3101,53 +3101,23 @@ son( -path.join(buildDirectory, 'app/version.json') +versionFilename , ve @@ -3622,20 +3622,97 @@ leware: -_log +%5B%0A _handleDockerflowEndpoints,%0A _log,%0A %5D ,%0A
1a92868840c90eff5436c293f3f0325aba3c9c12
Fix production dependencies
gulpfile.babel.js
gulpfile.babel.js
import gulp from 'gulp'; gulp.task('clean', () => { let del = require('del'); return del(['build/']); }); // Build gulp.task('build:lib', ['clean'], () => { let babel = require('gulp-babel'); return gulp.src('lib/*.es6') .pipe(babel()) .pipe(gulp.dest('build/lib')); }); gulp.task('build:docs', ['clean'], () => { let ignore = require('fs').readFileSync('.npmignore').toString() .trim().split(/\n+/) .concat(['.npmignore', 'package.json', 'index.js']) .map( i => '!' + i ); return gulp.src(['*'].concat(ignore)) .pipe(gulp.dest('build')); }); gulp.task('build:package', ['clean'], () => { let editor = require('gulp-json-editor'); let builders = [ 'babel-plugin-add-module-exports', 'babel-preset-es2015-loose', 'babel-preset-stage-0', 'babel-core' ]; gulp.src('./package.json') .pipe(editor( json => { json.main = 'lib/scss-syntax'; for ( let i of builders ) { json.devDependencies[i] = json.dependencies[i]; delete json.dependencies[i]; } return json; })) .pipe(gulp.dest('build')); }); gulp.task('build', ['build:lib', 'build:docs', 'build:package']); // Lint gulp.task('lint', () => { let eslint = require('gulp-eslint'); return gulp.src(['*.js', 'lib/*.es6', 'test/*.es6']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); // Test gulp.task('test', () => { require('babel-core/register')({ extensions: ['.es6'], ignore: false }); let mocha = require('gulp-mocha'); return gulp.src('test/*.es6', { read: false }).pipe(mocha()); }); gulp.task('integration', done => { require('babel-core/register')({ extensions: ['.es6'], ignore: false }); let postcss = require('postcss'); let real = require('postcss-parser-tests/real'); let scss = require('./'); real(done, css => { return postcss().process(css, { parser: scss, map: { annotation: false } }); }); }); // Common gulp.task('default', ['lint', 'test']);
JavaScript
0.000028
@@ -838,16 +838,47 @@ age-0',%0A + 'babel-preset-es2015',%0A
eb4248f4943b1ab1fbaae243811b55ad20b2e970
remove strip comments task
gulpfile.babel.js
gulpfile.babel.js
/** * RMC gulpfile * * @license * Copyright (c) 2017 Rogers Manufacturing Company. All rights reserved. */ 'use strict'; // include gulp & tools import gulp from 'gulp'; import rename from 'gulp-rename'; import replace from 'gulp-replace'; import header from 'gulp-header'; import strip from 'gulp-strip-comments'; import fs from 'fs'; import sass from 'gulp-sass'; import purifyCSS from 'gulp-purifycss'; import cleanCSS from 'gulp-clean-css'; import webp from 'gulp-webp'; import browserSync from 'browser-sync'; import pkg from './package.json'; const banner = ['/**', ' * <%= pkg.name %> - <%= pkg.description %>', ' * @version v<%= pkg.version %>', ' * @license <%= pkg.license %>', ' * @copyright 2017 The Rogers Manufacturing Company', ' * @link <%= pkg.homepage %>', ' */', ''].join('\n'); const reload = browserSync.reload; const FONTS = ['node_modules/components-font-awesome/fonts/*.*']; const IMAGES = [ 'images/**/*', '!images/manifest/**/*', '!images/favicon.ico', '!images/**/*.webp', ]; /** * Defines the list of resources to watch for changes. */ function watch() { gulp.watch(['scss/**/*.scss'], ['css', reload]); gulp.watch(IMAGES, ['webp', reload]); gulp.watch(['node_modules/components-font-awesome/fonts/*.*'], ['fonts:local', reload]); } // Compile Stylesheets gulp.task('sass', function() { return gulp.src('scss/**/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('css/')); }); // Strip Comments gulp.task('strip', ['sass'], function() { return gulp.src('css/rmc-theme.css') .pipe(strip()) .pipe(gulp.dest('css/')); }); // Minify CSS gulp.task('clean-css', ['sass', 'strip'], function() { return gulp.src('css/rmc-theme.css') .pipe(purifyCSS([ 'node_modules/bootstrap/dist/js/bootstrap.min.js', 'src/**/*.html', 'index.html', ])) .pipe(cleanCSS({ level: 2, })) .pipe(rename({suffix: '.min'})) .pipe(header(banner, {pkg : pkg})) .pipe(gulp.dest('css/')); }); // WebP gulp.task('webp', function() { return gulp.src(IMAGES) .pipe(webp()) .pipe(gulp.dest('images/')); }); // Copy fonts gulp.task('fonts', function() { return gulp.src(FONTS) .pipe(gulp.dest('build/es5-bundled/fonts/')); }); // Copy fonts locally gulp.task('fonts:local', function() { return gulp.src(FONTS) .pipe(gulp.dest('fonts/')); }); // Inline CSS gulp.task('inline', function() { return gulp.src('build/es5-bundled/index.html') .pipe(replace('<link rel="stylesheet" href="css/rmc-theme.min.css">', function(s) { var style = fs.readFileSync('css/rmc-theme.min.css', 'utf8'); return '<style>' + style + '</style>'; })) .pipe(gulp.dest('build/es5-bundled/')); }); // Watch resources for changes. gulp.task('watch', function() { watch(); }); /** * Serves local landing page from "./" directory. */ gulp.task('serve:browsersync:local', () => { browserSync({ notify: false, server: '.', browser: 'chrome', }); watch(); }); /** * Serves production landing page from "build/es5-bundled/" directory. */ gulp.task('serve:browsersync:build', () => { browserSync({ notify: false, server: { baseDir: ['build/es5-bundled/'], }, browser: 'chrome', }); watch(); }); // Compile Stylesheets gulp.task('css', ['sass', 'strip', 'clean-css']); // Before polymer build gulp.task('build:before', ['sass', 'strip', 'clean-css', 'webp']); // After polymer build gulp.task('build:after', ['inline', 'fonts']); // Serve local gulp.task('serve:local', ['build:before', 'fonts:local', 'serve:browsersync:local']); gulp.task('serve:build', ['serve:browsersync:build']);
JavaScript
0.000004
@@ -278,49 +278,8 @@ r';%0A -import strip from 'gulp-strip-comments';%0A impo @@ -1437,171 +1437,8 @@ );%0A%0A -// Strip Comments%0Agulp.task('strip', %5B'sass'%5D, function() %7B%0A return gulp.src('css/rmc-theme.css')%0A .pipe(strip())%0A .pipe(gulp.dest('css/'));%0A%7D);%0A%0A // M @@ -1477,25 +1477,16 @@ %5B'sass' -, 'strip' %5D, funct @@ -3166,33 +3166,24 @@ s', %5B'sass', - 'strip', 'clean-css' @@ -3249,17 +3249,8 @@ ss', - 'strip', 'cl
e7258f67639c41dc8f21efd3ff3f32b5cbbb6e30
Update tasks
gulpfile.babel.js
gulpfile.babel.js
import gulp from 'gulp'; import autoprefixer from 'gulp-autoprefixer'; import cleanCSS from 'gulp-clean-css'; import del from 'del'; import imagemin from 'gulp-imagemin'; import pug from 'gulp-pug'; import sass from 'gulp-sass'; import sourcemaps from 'gulp-sourcemaps'; import webpack from 'webpack-stream'; import { create as bsCreate } from 'browser-sync'; const browserSync = bsCreate(); const paths = { styles: { src: 'src/styles/**/*.scss', dest: 'dist/styles/' }, scripts: { src: 'src/scripts/**/*.js', dest: 'dist/scripts/' }, images: { src: 'src/images/**/*.{jpg,jpeg,png}', dest: 'dist/images/' } }; export const clean = () => del(['dist']); export function serve() { return browserSync.init({ server: { baseDir: './dist' }, open: false }); } export function styles() { return gulp .src(paths.styles.src) .pipe(sourcemaps.init()) .pipe(sass().on('error', sass.logError)) .pipe(autoprefixer({ browsers: ['last 2 versions'], cascade: false })) .pipe(cleanCSS()) .pipe(sourcemaps.write('.')) .pipe(gulp.dest(paths.styles.dest)) .pipe(browserSync.stream()); } export function scripts() { return gulp .src(paths.scripts.src) .pipe(webpack(require('./webpack.config.js'))) .pipe(gulp.dest(paths.scripts.dest)) .pipe(browserSync.stream()); } export function images() { return gulp .src(paths.images.src) .pipe(imagemin({ optimizationLevel: 5 })) .pipe(gulp.dest(paths.images.dest)) .pipe(browserSync.stream()); } export function templates() { return gulp .src('src/index.pug') .pipe(pug()) .pipe(gulp.dest('dist')) .pipe(browserSync.stream()); } export function watch() { gulp.watch(paths.styles.src, styles); gulp.watch(paths.scripts.src, scripts); gulp.watch(paths.images.src, images); gulp.watch('src/index.pug', templates); gulp.watch('dist/index.html').on('change', browserSync.reload); } const build = gulp.series(clean, gulp.parallel(styles, scripts, images, templates)); const defaultTask = gulp.parallel(build, serve, watch); gulp.task('build', build); gulp.task('default', defaultTask); export default defaultTask;
JavaScript
0.000002
@@ -107,31 +107,8 @@ s';%0A -import del from 'del';%0A impo @@ -237,24 +237,47 @@ ourcemaps';%0A +import del from 'del';%0A import webpa @@ -313,83 +313,39 @@ ort -%7B create as bsCreate %7D from 'browser-sync';%0A%0Aconst browserSync = bsCreate() +browserSync from 'browser-sync' ;%0A%0Ac @@ -424,24 +424,25 @@ ist/styles/' +, %0A %7D,%0A scri @@ -505,16 +505,17 @@ cripts/' +, %0A %7D,%0A @@ -591,20 +591,22 @@ images/' +, %0A %7D +, %0A%7D;%0A%0Aexp @@ -736,16 +736,17 @@ './dist' +, %0A %7D,%0A @@ -760,16 +760,17 @@ n: false +, %0A %7D);%0A%7D @@ -941,39 +941,8 @@ er(%7B - browsers: %5B'last 2 versions'%5D, cas @@ -1348,24 +1348,57 @@ s.images.src +, %7B since: gulp.lastRun(images) %7D )%0A .pipe( @@ -1525,24 +1525,20 @@ unction -template +view s() %7B%0A @@ -1835,24 +1835,20 @@ x.pug', -template +view s);%0A gu @@ -1988,16 +1988,12 @@ es, -template +view s));
344e5379fc83c112b029ed4bd6ae4cab793936d6
Update buildStatus.js
store/buildStatus.js
store/buildStatus.js
/** * Function to build status data **/ // const config = require('../config'); const queue = require('./queue'); const async = require('async'); const moment = require('moment'); module.exports = function buildStatus(db, redis, cb) { redis.zremrangebyscore('added_match', 0, moment().subtract(1, 'day').format('X')); redis.zremrangebyscore('error_500', 0, moment().subtract(1, 'day').format('X')); redis.zremrangebyscore('api_hits', 0, moment().subtract(1, 'day').format('X')); redis.zremrangebyscore('parser', 0, moment().subtract(1, 'day').format('X')); redis.zremrangebyscore('retriever', 0, moment().subtract(1, 'day').format('X')); redis.zremrangebyscore('visitor_match', 0, moment().subtract(1, 'day').format('X')); redis.zremrangebyscore('requests', 0, moment().subtract(1, 'day').format('X')); async.series({ user_players(cb) { redis.zcard('visitors', cb); }, tracked_players(cb) { redis.zcard('tracked', cb); }, error_500(cb) { redis.zcard('error_500', cb); }, matches_last_day(cb) { redis.zcard('added_match', cb); }, matches_last_hour(cb) { redis.zcount('added_match', moment().subtract(1, 'hour').format('X'), moment().format('X'), cb); }, user_matches_last_day(cb) { redis.zcard('visitor_match', cb); }, retriever_matches_last_day(cb) { redis.zcard('retriever', cb); }, parsed_matches_last_day(cb) { redis.zcard('parser', cb); }, requests_last_day(cb) { redis.zcard('requests', cb); }, fhQueue(cb) { redis.llen('fhQueue', cb); }, gcQueue(cb) { redis.llen('gcQueue', cb); }, mmrQueue(cb) { redis.llen('mmrQueue', cb); }, api_hits(cb) { redis.zcard('api_hits', cb); }, last_added(cb) { redis.lrange('matches_last_added', 0, -1, (err, result) => cb(err, result.map(r => JSON.parse(r) )) ); }, last_parsed(cb) { redis.lrange('matches_last_parsed', 0, -1, (err, result) => cb(err, result.map(r => JSON.parse(r) )) ); }, retriever(cb) { redis.zrangebyscore('retriever', moment().subtract(1, 'hour').format('X'), moment().format('X'), (err, results) => { if (err) { return cb(err); } const counts = {}; results.forEach((e) => { const key = e.split('_')[0]; counts[key] = counts[key] ? counts[key] + 1 : 1; }); const result = Object.keys(counts).map(retriever => ({ hostname: retriever.split('.')[0], count: counts[retriever], })).sort((a, b) => a.hostname.localeCompare(b.hostname)); cb(err, result); }); }, queue(cb) { // generate object with properties as queue types, each mapped to json object mapping state to count queue.getCounts(redis, cb); }, load_times(cb) { redis.lrange('load_times', 0, -1, (err, arr) => { cb(err, generatePercentiles(arr)); }); }, health(cb) { redis.hgetall('health', (err, result) => { if (err) { return cb(err); } for (const key in result) { result[key] = JSON.parse(result[key]); } cb(err, result || {}); }); }, }, (err, results) => { cb(err, results); }); function generatePercentiles(arr) { // sort the list arr.sort((a, b) => Number(a) - Number(b)); // console.log(arr); const percentiles = [50, 75, 95, 99]; const result = {}; arr.forEach((time, i) => { if (i >= arr.length * (percentiles[0] / 100)) { result[percentiles[0]] = Number(time); // Pop the first element percentiles.shift(); } }); return result; } };
JavaScript
0.000001
@@ -3516,16 +3516,20 @@ %5B50, 75, + 90, 95, 99%5D