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
b0f47604687764924f09341bc94eb7fb8b519235
Read file source and save to vyper compilation output
packages/truffle-compile-vyper/index.js
packages/truffle-compile-vyper/index.js
const path = require("path"); const exec = require("child_process").exec; const async = require("async"); const colors = require("colors"); const minimatch = require("minimatch"); const find_contracts = require("truffle-contract-sources"); const Profiler = require("truffle-compile/profiler"); const compiler = { name: "vyper", version: null }; const VYPER_PATTERN = "**/*.{vy,v.py,vyper.py}"; // -------- TODO: Common with truffle-compile -------- const compile = {}; // contracts_directory: String. Directory where .sol files can be found. // quiet: Boolean. Suppress output. Defaults to false. // strict: Boolean. Return compiler warnings as errors. Defaults to false. compile.all = function(options, callback) { find_contracts(options.contracts_directory, function(err, files) { if (err) return callback(err); options.paths = files; compile.with_dependencies(options, callback); }); }; // contracts_directory: String. Directory where .sol files can be found. // build_directory: String. Optional. Directory where .sol.js files can be found. Only required if `all` is false. // all: Boolean. Compile all sources found. Defaults to true. If false, will compare sources against built files // in the build directory to see what needs to be compiled. // quiet: Boolean. Suppress output. Defaults to false. // strict: Boolean. Return compiler warnings as errors. Defaults to false. compile.necessary = function(options, callback) { options.logger = options.logger || console; Profiler.updated(options, function(err, updated) { if (err) return callback(err); if (updated.length === 0 && options.quiet !== true) { return callback(null, [], {}); } options.paths = updated; compile.with_dependencies(options, callback); }); }; compile.display = function(paths, options) { if (options.quiet !== true) { if (!Array.isArray(paths)) { paths = Object.keys(paths); } paths.sort().forEach(contract => { if (path.isAbsolute(contract)) { contract = "." + path.sep + path.relative(options.working_directory, contract); } options.logger.log("> Compiling " + contract); }); } }; // -------- End of common with truffle-compile -------- // Check that vyper is available, save its version function checkVyper(callback) { exec("vyper --version", function(err, stdout, stderr) { if (err) return callback(`${colors.red("Error executing vyper:")}\n${stderr}`); compiler.version = stdout.trim(); callback(null); }); } // Execute vyper for single source file function execVyper(options, source_path, callback) { const formats = ["abi", "bytecode", "bytecode_runtime"]; if ( options.compilers.vyper.settings && options.compilers.vyper.settings.sourceMap ) { formats.push("source_map"); } const command = `vyper -f${formats.join(",")} ${source_path}`; exec(command, { maxBuffer: 600 * 1024 }, function(err, stdout, stderr) { if (err) return callback( `${stderr}\n${colors.red( `Compilation of ${source_path} failed. See above.` )}` ); var outputs = stdout.split(/\r?\n/); const compiled_contract = outputs.reduce(function(contract, output, index) { return Object.assign(contract, { [formats[index]]: output }); }, {}); callback(null, compiled_contract); }); } // compile all options.paths function compileAll(options, callback) { options.logger = options.logger || console; compile.display(options.paths, options); async.map( options.paths, function(source_path, c) { execVyper(options, source_path, function(err, compiled_contract) { if (err) return c(err); // remove first extension from filename const extension = path.extname(source_path); const basename = path.basename(source_path, extension); // if extension is .py, remove second extension from filename const contract_name = extension !== ".py" ? basename : path.basename(basename, path.extname(basename)); const contract_definition = { contract_name: contract_name, sourcePath: source_path, abi: compiled_contract.abi, bytecode: compiled_contract.bytecode, deployedBytecode: compiled_contract.bytecode_runtime, sourceMap: compiled_contract.source_map, compiler: compiler }; c(null, contract_definition); }); }, function(err, contracts) { if (err) return callback(err); const result = contracts.reduce(function(result, contract) { result[contract.contract_name] = contract; return result; }, {}); const compilerInfo = { name: "vyper", version: compiler.version }; callback(null, result, options.paths, compilerInfo); } ); } // Check that vyper is available then forward to internal compile function function compileVyper(options, callback) { // filter out non-vyper paths options.paths = options.paths.filter(function(path) { return minimatch(path, VYPER_PATTERN); }); // no vyper files found, no need to check vyper if (options.paths.length === 0) return callback(null, {}, []); checkVyper(function(err) { if (err) return callback(err); return compileAll(options, callback); }); } // append .vy pattern to contracts_directory in options and return updated options function updateContractsDirectory(options) { return options.with({ contracts_directory: path.join(options.contracts_directory, VYPER_PATTERN) }); } // wrapper for compile.all. only updates contracts_directory to find .vy compileVyper.all = function(options, callback) { return compile.all(updateContractsDirectory(options), callback); }; // wrapper for compile.necessary. only updates contracts_directory to find .vy compileVyper.necessary = function(options, callback) { return compile.necessary(updateContractsDirectory(options), callback); }; compile.with_dependencies = compileVyper; module.exports = compileVyper;
JavaScript
0
@@ -66,16 +66,49 @@ %22).exec; +%0Aconst fse = require(%22fs-extra%22); %0A%0Aconst @@ -3442,16 +3442,22 @@ s.paths%0A +async function @@ -3481,32 +3481,32 @@ ns, callback) %7B%0A - options.logger @@ -3680,16 +3680,22 @@ ce_path, + async functio @@ -4134,24 +4134,146 @@ asename));%0A%0A + const source_buffer = await fse.readFile(source_path);%0A const source_contents = source_buffer.toString();%0A%0A cons @@ -4373,16 +4373,50 @@ e_path,%0A + source: source_contents, %0A
81646b2d5fad5f2cb2a124607292a04183c84ce7
move parent object so that anchor is working
passwordpolicy/js/user.js
passwordpolicy/js/user.js
$(document).ready(function() { $('#passwordform').after($('#password_policy').detach()); });
JavaScript
0.000001
@@ -73,16 +73,25 @@ olicy'). +parent(). detach()
44c1262a4e975941d7fc74c852c03d47390e828e
replace className by class, export a div container instead of a pre container (code block)
src/exporter.js
src/exporter.js
import React from 'react'; import { convertToHTML } from 'draft-convert'; import { Inline, Block, Entity } from './util/constants'; export const styleToHTML = (style) => { switch (style) { case Inline.ITALIC: return <em className={`md-inline-${style.toLowerCase()}`} />; case Inline.BOLD: return <strong className={`md-inline-${style.toLowerCase()}`} />; case Inline.STRIKETHROUGH: return <strike className={`md-inline-${style.toLowerCase()}`} />; case Inline.UNDERLINE: return <u className={`md-inline-${style.toLowerCase()}`} />; case Inline.HIGHLIGHT: return <span className={`md-inline-${style.toLowerCase()}`} />; case Inline.CODE: return <code className={`md-inline-${style.toLowerCase()}`} />; default: return null; } }; export const blockToHTML = (block) => { const blockType = block.type; const blockClass = blockType.toLowerCase(); switch (blockType) { case Block.H1: // eslint-disable-next-line jsx-a11y/heading-has-content return <h1 className={`md-block-${blockClass}`} />; case Block.H2: // eslint-disable-next-line jsx-a11y/heading-has-content return <h2 className={`md-block-${blockClass}`} />; case Block.H3: // eslint-disable-next-line jsx-a11y/heading-has-content return <h3 className={`md-block-${blockClass}`} />; case Block.H4: // eslint-disable-next-line jsx-a11y/heading-has-content return <h4 className={`md-block-${blockClass}`} />; case Block.H5: // eslint-disable-next-line jsx-a11y/heading-has-content return <h5 className={`md-block-${blockClass}`} />; case Block.H6: // eslint-disable-next-line jsx-a11y/heading-has-content return <h6 className={`md-block-${blockClass}`} />; case Block.BLOCKQUOTE_CAPTION: case Block.CAPTION: return { start: `<p class="md-block-${blockClass}"><caption>`, end: '</caption></p>', }; case Block.IMAGE: { const imgData = block.data; const text = block.text; const extraClass = (text.length > 0 ? ' md-block-image-has-caption' : ''); return { start: `<figure class="md-block-image${extraClass}"><img src="${imgData.src}" alt="${block.text}" /><figcaption className="md-block-image-caption">`, end: '</figcaption></figure>', }; } case Block.ATOMIC: return { start: `<figure class="md-block-${blockClass}">`, end: '</figure>', }; case Block.TODO: { const checked = block.data.checked || false; let inp = ''; let containerClass = ''; if (checked) { inp = '<input type=checkbox disabled checked="checked" />'; containerClass = 'md-block-todo-checked'; } else { inp = '<input type=checkbox disabled />'; containerClass = 'md-block-todo-unchecked'; } return { start: `<div class="md-block-${blockType} ${containerClass}">${inp}<p>`, end: '</p></div>', }; } case Block.BREAK: return <hr className={`md-block-${blockType}`} />; case Block.BLOCKQUOTE: return <blockquote className={`md-block-${blockType}`} />; case Block.OL: return { element: <li />, nest: <ol className={`md-block-${blockType}`} />, }; case Block.UL: return { element: <li />, nest: <ul className={`md-block-${blockType}`} />, }; case Block.UNSTYLED: if (block.text.length < 1) { return <p className={`md-block-${blockType}`}><br /></p>; } return <p className={`md-block-${blockType}`} />; case Block.CODE: return { element: <pre className={`md-block-${blockType}`} />, nest: <pre className="md-block-code-container" />, }; default: return null; } }; export const entityToHTML = (entity, originalText) => { if (entity.type === Entity.LINK) { return ( <a className="md-inline-link" href={entity.data.url} target="_blank" rel="noopener noreferrer" > {originalText} </a> ); } return originalText; }; export const options = { styleToHTML, blockToHTML, entityToHTML, }; export const setRenderOptions = (htmlOptions = options) => convertToHTML(htmlOptions); export default (contentState, htmlOptions = options) => convertToHTML(htmlOptions)(contentState);
JavaScript
0
@@ -2262,28 +2262,24 @@ aption class -Name =%22md-block-i @@ -3729,27 +3729,27 @@ nest: %3C -pre +div className=%22
d4220b04da09b5ba4a572a82a515f8265b598602
rewrite app.react
logspace-frontend/src/client/app/app.react.js
logspace-frontend/src/client/app/app.react.js
/* * Logspace * Copyright (c) 2015 Indoqa Software Design und Beratung GmbH. All rights reserved. * This program and the accompanying materials are made available under the terms of * the Eclipse Public License Version 1.0, which accompanies this distribution and * is available at http://www.eclipse.org/legal/epl-v10.html. */ import DocumentTitle from 'react-document-title' import React from 'react' import {Link, RouteHandler} from 'react-router' import {state} from '../state' require('./app.styl'); export default class App extends React.Component { componentDidMount() { state.on('change', () => { this.forceUpdate(); }) } render() { return ( <DocumentTitle title='logspace.io'> <div className="page"> <RouteHandler /> </div> </DocumentTitle> ) } }
JavaScript
0.000012
@@ -454,22 +454,29 @@ er'%0A +%0A import -%7Bs +* as appS tate -%7D fro @@ -493,82 +493,676 @@ e'%0A%0A -require('./app.styl');%0A%0Aexport default class App extends React.Component %7B +import '../intl/store'%0Aimport '../time-window/store'%0Aimport '../time-series/store'%0Aimport '../result/store'%0Aimport '../suggestions/store'%0Aimport '../drawer/store'%0A%0Arequire('./app.styl');%0A%0Aexport default class App extends React.Component %7B%0A%0A constructor(props) %7B%0A super(props)%0A this.state = this.getState()%0A %7D%0A%0A getState() %7B%0A return %7B%0A i18n: appState.i18nCursor(),%0A timeWindow: appState.timeWindowCursor(),%0A timeSeries: appState.timeSeriesCursor(),%0A editedTimeSeries: appState.editedTimeSeriesCursor(),%0A result: appState.resultCursor(),%0A suggestion: appState.suggestionCursor(),%0A drawer: appState.drawerCursor()%0A %7D;%0A %7D %0A%0A @@ -1187,16 +1187,25 @@ ) %7B%0A +appState. state.on @@ -1233,35 +1233,201 @@ -this.forceUpdate();%0A %7D) +console.time('app render') // eslint-disable-line no-console%0A this.setState(this.getState(), () =%3E %7B%0A console.timeEnd('app render') // eslint-disable-line no-console%0A %7D)%0A %7D) %0A %7D @@ -1550,16 +1550,32 @@ eHandler + %7B...this.state%7D /%3E%0A
cc6501a48a8116ea33234300a37af70002071bda
Handle empty or missing user agent responses.
usragent.js
usragent.js
function parse_user_agent(agent) { "use strict"; var fields = []; fields[0] = agent; fields[1] = "Mozilla-compatible"; fields[2] = "Unix-derived"; return (fields); }
JavaScript
0.000002
@@ -160,16 +160,140 @@ erived%22; +%0A%0A if (fields%5B0%5D === %22%22) %7B%0A fields%5B0%5D = %22(no browser identification sent)%22;%0A fields%5B1%5D = %22(unknown)%22;%0A %7D %0A ret
a57f65c8e4ec973921d876ed223b8cd7e45e9c6f
Create login functionality in Ally framework
plugins/gui-core/gui-resources/scripts/js/views/auth.js
plugins/gui-core/gui-resources/scripts/js/views/auth.js
define ([ 'jquery', 'jquery/superdesk', 'dust/core', 'utils/sha512', 'jquery/tmpl', 'jquery/rest', 'bootstrap', 'tmpl!auth', ], function($, superdesk, dust, jsSHA) { <<<<<<< HEAD var AuthLogin = function(username, password, logintoken){ ======= var AuthDetails = function(username){ var authDetails = new $.rest('Superdesk/User'); authDetails.resetData().xfilter('Name,Id,EMail').select({ name: username }).done(function(users){ var user = users.UserList[0]; localStorage.setItem('superdesk.login.id', user.Id); localStorage.setItem('superdesk.login.name', user.Name); localStorage.setItem('superdesk.login.email', user.EMail); }); return $(authDetails); }, AuthLogin = function(username, password, logintoken){ >>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81 var shaObj = new jsSHA(logintoken, "ASCII"),shaPassword = new jsSHA(password, "ASCII"), authLogin = new $.rest('Authentication'); authLogin.resetData().insert({ UserName: username, LoginToken: logintoken, HashedLoginToken: shaObj.getHMAC(username+shaPassword.getHash("SHA-512", "HEX"), "ASCII", "SHA-512", "HEX") }).done(function(user){ localStorage.setItem('superdesk.login.session', user.Session); <<<<<<< HEAD localStorage.setItem('superdesk.login.id', user.Id); localStorage.setItem('superdesk.login.name', user.UserName); localStorage.setItem('superdesk.login.email', user.EMail); $(authLogin).trigger('success'); ======= //localStorage.setItem('superdesk.login.id', user.Id); localStorage.setItem('superdesk.login.name', user.UserName); localStorage.setItem('superdesk.login.email', user.EMail); $(authLogin).trigger('success'); /* authDetails = AuthDetails(username); $(authDetails).on('failed', function(){ $(authLogin).trigger('failed', 'authDetails'); }); */ >>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81 }); return $(authLogin); }, AuthToken = function(username, password) { var authToken = new $.rest('Authentication'); authToken.resetData().select({ userName: username }).done( function(data){ authLogin = AuthLogin(username, password, data.Token); authLogin.on('failed', function(){ $(authToken).trigger('failed', 'authToken'); }).on('success', function(){ $(authToken).trigger('success'); }); } ); return $(authToken); }, AuthApp = { success: $.noop, require: function() { if(this.showed) return; var self = this; // rest self.showed = true; $.tmpl('auth', null, function(e, o) { var dialog = $(o).eq(0).dialog ({ draggable: false, resizable: false, modal: true, width: "40.1709%", buttons: [ { text: "Login", click: function(){ $(form).trigger('submit'); }, class: "btn btn-primary"}, { text: "Close", click: function(){ $(this).dialog('close'); }, class: "btn"} ] }), form = dialog.find('form'); form.off('submit.superdesk')// .on('submit.superdesk', function(event) { var username = $(this).find('#username'), password=$(this).find('#password'); AuthToken(username.val(), password.val()).on('failed',function(evt, type){ username.val(''); password.val('') }).on('success', function(){ AuthApp.success && AuthApp.success.apply(); $(dialog).dialog('close'); self.showed = false; }); event.preventDefault(); }); }); } }; return AuthApp; });
JavaScript
0
@@ -1220,29 +1220,16 @@ ssion);%0A -%3C%3C%3C%3C%3C%3C%3C HEAD%0A %09%09%09local @@ -1445,437 +1445,8 @@ ');%0A -=======%0A%09%09%09//localStorage.setItem('superdesk.login.id', user.Id);%0A%09%09%09localStorage.setItem('superdesk.login.name', user.UserName);%0A%09%09%09localStorage.setItem('superdesk.login.email', user.EMail);%09%09%09%0A%09%09%09$(authLogin).trigger('success');%0A/*%09%09%09authDetails = AuthDetails(username);%0A%09%09%09$(authDetails).on('failed', function()%7B%0A%09%09%09%09$(authLogin).trigger('failed', 'authDetails');%0A%09%09%09%7D);%0A*/%09%09%09%0A%3E%3E%3E%3E%3E%3E%3E 718d8c014dc7f1c47606de731769286a6bcebb81%0A %09%09%7D)
f1b1c153d98440bbde019b452736a8e1bab5fe47
Add TODO comment
packages/uikit-default/src/js/panels.js
packages/uikit-default/src/js/panels.js
/*! * Default Panels for Pattern Lab plus Panel related events * * Copyright (c) 2016 Dave Olsen, http://dmolsen.com * Licensed under the MIT license * * config is coming from the default viewer and is passed through from PL's config * * @requires prism-languages.js */ var Panels = { panels: [], count: function() { return this.panels.length; }, get: function() { return JSON.parse(JSON.stringify(this.panels)); }, add: function(panel) { // if ID already exists in panels array ignore the add() for (i = 0; i < this.panels.length; ++i) { if (panel.id === this.panels[i].id) { return; } } // it wasn't found so push the tab onto the tabs this.panels.push(panel); } }; // add the default panels // Panels.add({ 'id': 'sg-panel-info', 'name': 'info', 'default': true, 'templateID': 'pl-panel-template-info', 'httpRequest': false, 'prismHighlight': false, 'keyCombo': '' }); Panels.add({ 'id': 'sg-panel-pattern', 'name': config.patternExtension.toUpperCase(), 'default': true, 'templateID': 'pl-panel-template-code', 'httpRequest': true, 'httpRequestReplace': '.'+config.patternExtension, 'httpRequestCompleted': false, 'prismHighlight': true, 'language': PrismLanguages.get(config.patternExtension), 'keyCombo': 'ctrl+shift+u' }); Panels.add({ 'id': 'sg-panel-html', 'name': 'HTML', 'default': false, 'templateID': 'pl-panel-template-code', 'httpRequest': true, 'httpRequestReplace': '.markup-only.html', 'httpRequestCompleted': false, 'prismHighlight': true, 'language': 'markup', 'keyCombo': 'ctrl+shift+y' }); // gather panels from plugins Dispatcher.trigger('setupPanels');
JavaScript
0
@@ -964,24 +964,56 @@ bo': '' %7D);%0A +// TODO: sort out sg-panel-html%0A Panels.add(%7B
74b576b2d4f98c1059f48be6c127e9dc0025e16d
test setting inner html
__tests__/src/index-test.js
__tests__/src/index-test.js
/* eslint-env jest */ jest.unmock('../../src'); import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import marked from 'marked'; import MarkdownRenderer from '../../src'; describe('MarkdownRenderer', () => { const markdown = '# This is a H1 \n## This is a H2 \n###### This is a H6'; beforeEach(() => { marked.mockClear(); }); it('renders', () => { const markdownRenderer = TestUtils.renderIntoDocument( <div> <MarkdownRenderer markdown={markdown} /> </div> ); const containerNode = ReactDOM.findDOMNode(markdownRenderer); const markdownRendererNode = containerNode.children[0]; expect(markdownRendererNode).toBeDefined(); expect(markdownRendererNode).not.toBe(null); expect(marked.mock.calls.length).toEqual(1); expect(marked).toBeCalledWith(markdown, { sanitize: true }); }); describe('applies className', () => { it('defaults empty', () => { const markdownRenderer = TestUtils.renderIntoDocument( <div> <MarkdownRenderer markdown={markdown} /> </div> ); const containerNode = ReactDOM.findDOMNode(markdownRenderer); const markdownRendererNode = containerNode.children[0]; expect(markdownRendererNode.className).toBe(''); }); it('applies className', () => { const className = 'one two three'; const markdownRenderer = TestUtils.renderIntoDocument( <div> <MarkdownRenderer markdown={markdown} className={className} /> </div> ); const containerNode = ReactDOM.findDOMNode(markdownRenderer); const markdownRendererNode = containerNode.children[0]; expect(markdownRendererNode.className).toBe(className); }); }); describe('defaults markdown', () => { afterEach(() => { expect(marked.mock.calls.length).toEqual(1); expect(marked).toBeCalledWith('', { sanitize: true }); }); it('nothing passed', () => { TestUtils.renderIntoDocument( <div> <MarkdownRenderer /> </div> ); }); it('undefined passed', () => { TestUtils.renderIntoDocument( <div> <MarkdownRenderer markdown={undefined} /> </div> ); }); it('null passed', () => { TestUtils.renderIntoDocument( <div> <MarkdownRenderer markdown={null} /> </div> ); }); }); });
JavaScript
0
@@ -412,19 +412,736 @@ -it('renders +describe('sets innerHTML', () =%3E %7B%0A let containerNode;%0A let html;%0A%0A afterEach(() =%3E %7B%0A expect(marked.mock.calls.length).toEqual(1);%0A expect(marked).toBeCalledWith(markdown, %7B sanitize: true %7D);%0A%0A const markdownRendererNode = containerNode.children%5B0%5D;%0A%0A expect(markdownRendererNode).toBeDefined();%0A expect(markdownRendererNode).not.toBe(null);%0A expect(markdownRendererNode.innerHTML).toBe(html);%0A %7D);%0A%0A describe('marked returns html', () =%3E %7B%0A beforeEach(() =%3E %7B%0A html = '%3Ch1%3EThis is a H1%3C/h1%3E';%0A marked.mockReturnValueOnce(html);%0A %7D);%0A%0A it('sets innerHTML to html ', ( @@ -1139,32 +1139,40 @@ html', () =%3E %7B%0A + const ma @@ -1222,32 +1222,40 @@ nt(%0A + %3Cdiv%3E%0A @@ -1252,32 +1252,40 @@ + + %3CMarkdownRendere @@ -1321,31 +1321,46 @@ -%3C/div%3E%0A + %3C/div%3E%0A );%0A%0A @@ -1343,32 +1343,33 @@ %0A + );%0A%0A cons @@ -1356,37 +1356,39 @@ );%0A%0A -const + containerNode = @@ -1440,125 +1440,324 @@ -const markdownRendererNode = containerNode.children%5B0%5D;%0A%0A expect(markdownRendererNode).toBeDefined( + %7D);%0A %7D);%0A%0A describe('marked returns empty string', () =%3E %7B%0A beforeEach(() =%3E %7B%0A html = '';%0A marked.mockReturnValueOnce(html);%0A %7D);%0A%0A it('sets innerHTML to empty string', () =%3E %7B%0A marked.mockReturnValueOnce('' );%0A +%0A expe @@ -1744,39 +1744,46 @@ e('');%0A%0A -expect( + const markdownRenderer @@ -1786,148 +1786,274 @@ erer -Node).not.toBe(null);%0A%0A expect(marked.mock.calls.length).toEqual(1);%0A expect(marked).toBeCalledWith(markdown, %7B sanitize: true + = TestUtils.renderIntoDocument(%0A %3Cdiv%3E%0A %3CMarkdownRenderer markdown=%7Bmarkdown%7D /%3E%0A %3C/div%3E%0A );%0A%0A containerNode = ReactDOM.findDOMNode(markdownRenderer);%0A %7D);%0A %7D);
26f4d77e51d9de91b0332f54237edf7f868735a8
fix context of confirm modal
src/app/ui/components/modal/modal-confirm/component.js
src/app/ui/components/modal/modal-confirm/component.js
import { get } from "@ember/object"; import ModalDialogComponent from "../modal-dialog/component"; import layout from "./template.hbs"; function actionFactory( action ) { return function( success, failure ) { get( this, "modal.context" ).send( action, success, failure ); }; } export default ModalDialogComponent.extend({ layout, "class": "modal-confirm", hotkeysNamespace: "modalconfirm", hotkeys: { confirm: "apply" }, actions: { "apply" : actionFactory( "apply" ), "discard": actionFactory( "discard" ), "cancel" : actionFactory( "cancel" ) } });
JavaScript
0.000002
@@ -1,41 +1,4 @@ -import %7B get %7D from %22@ember/object%22;%0A impo @@ -174,36 +174,25 @@ %7B%0A%09%09 -get( this -, %22 +. modal -.c +C ontext -%22 ) .sen
4cdf4227d39304b0c6f7ab9e6e62fa27977617d1
fix directory permission hang
src/service.js
src/service.js
import {createServer as httpServer} from 'http' import {parse as parseURL} from 'url' import {join as joinPath} from 'path' import {exists as existsFile, stat} from 'fs' import {transpile} from './index' export default function service({base, lang, port}) { //var watched = [] httpServer((req, res) => { if (req.method === 'GET') { let f = joinPath(base, parseURL(req.url).pathname) f = f.replace(/^\\\\([A-Z])\|/, '$1:') //if (watched.indexOf(path) >= 0) const send = (status, message) => { res.writeHead(status) res.end(message + ': ' + f + '\n') if (status >= 400) { console.error(message + ': ' + f) console.error() } else { console.info(message + ': ' + f) console.info() } } existsFile(f, exists => { if (!exists) { send(404, 'file not exist') } else { stat(f, (err, stats) => { if (err) throw err // should never happen if (stats.isFile()) { const t0 = Date.now() lang.forEach(function(lang){ transpile(f, f.replace(/\.jedi$/, '.' + lang), lang) }) const t1 = Date.now() send(200, 'transpiled in ' + (t1 - t0) + 'ms') } else { send(404, 'path is not a file') } }) } }) //transpiler.watch(loc.pathname) } else { res.writeHead(405) res.end() } }).listen(port) process.on('uncaughtException', err => { console.error(new Date().toISOString(), 'uncaught exception:', err) console.trace(err) }) }
JavaScript
0.000001
@@ -963,24 +963,38 @@ Date.now()%0A +%09%09%09%09%09%09%09try %7B%0A%09 %09%09%09%09%09%09%09lang. @@ -1017,16 +1017,18 @@ (lang)%7B%0A +%09%09 %09%09%09%09%09%09%09%09 @@ -1083,27 +1083,133 @@ ang)%0A%09%09%09%09%09%09%09 +%09 %7D)%0A +%09%09%09%09%09%09%09%7D catch (e) %7B%0A%09%09%09%09%09%09%09%09send(403, 'jedi probably cannot access directory!')%0A%09%09%09%09%09%09%09%09return%0A%09%09%09%09%09%09%09%7D%0A %09%09%09%09%09%09%09const
7ac2d4067579d8dd943f7764ba19fa50e6360b85
remove overflow use
runners.js
runners.js
export function generator(node, method) { const iter = method(node); return function(nextDelay) { const out = iter.next(); if (out.done) { return true; // stop calling me } if (out.value !== true) { throw new Error('unsupported generator value: ' + value); } } } export function frame(node, frames) { let i = -1; return function(nextDelay) { const frame = frames[++i]; if (!frame) { console.info('animation done'); return true; } console.info('rendering frame', i, frame); if ('class' in frame) { node.className = frame.class; } if ('scene' in frame) { const arg = {detail: frame.scene, bubbles: true, composed: true}; node.dispatchEvent(new CustomEvent('scene', arg)); } // FIXME: incorporate overflow into styling of scene // if ('overflow' in frame) { device.overflow = frame.overflow; } // FIXME: return a delayed Promise for the longer delay // if ('delay' in frame) { nextDelay = Math.max(frame.delay, nextDelay); } if ('value' in frame) { const el = node.querySelector(frame.value.q); el.value = frame.value.value; } if ('attr' in frame) { const attr = frame.attr; const el = node.querySelector(attr.q); if (attr.value !== undefined) { el.setAttribute(attr.name, attr.value); } else { el.removeAttribute(attr.name); } } if ('keyboard' in frame) { const k = frame.keyboard; const el = node.querySelector(k.q); let remaining = k.value || ''; el.focus(); let first = true; const seg = (nextDelay / remaining.length) * 0.75; const interval = window.setInterval(() => { if (first) { el.value = ''; first = false; return; } if (!remaining.length) { window.clearInterval(interval); return; } let i = 0; while (remaining[i] === ' ') { ++i; } el.value = el.value + remaining.substr(0, i + 1); el.focus(); remaining = remaining.substr(i + 1); }, seg); } if ('click' in frame) { const el = node.querySelector(frame.click); el.focus(); window.setTimeout(() => { el.click(); }, nextDelay * 0.25); window.setTimeout(() => { (document.activeElement || el).blur(); }, nextDelay * 0.75); } if ('scroll' in frame) { const el = node.querySelector(frame.scroll.q); const startAt = el.scrollTop; const scrollTo = frame.scroll.to; const start = performance.now(); const update = whenever => { const delta = performance.now() - start; let ratio = (delta / nextDelay); ratio = Math.max(0, ratio); ratio = Math.min(1, ratio); el.scrollTop = (scrollTo - startAt) * ratio + startAt; if (ratio < 1) { window.requestAnimationFrame(update); } }; window.requestAnimationFrame(update); } }; }
JavaScript
0.000001
@@ -770,136 +770,8 @@ %7D%0A%0A - // FIXME: incorporate overflow into styling of scene%0A // if ('overflow' in frame) %7B device.overflow = frame.overflow; %7D%0A%0A
ab5bc27c7cc8ea1e8d6b9e73f0b26bd516b24188
Set base row structure
app/app.module.js
app/app.module.js
var app = angular.module('weather-app', []); app.factory('SearchService', [function() { var queryTerms = []; var updateNotifications = []; function updateTerms(terms) { queryTerms = terms; notifyDidUpdateTerms(terms); return true; } // Notify contexts that the terms were updated function didUpdateTerms(callback) { updateNotifications.push(callback); } function notifyDidUpdateTerms(terms) { for (var i = 0; i < updateNotifications.length; i++) { updateNotifications[i](terms); } } function getTerms() { return queryTerms; } var SearchService = { updateTerms: updateTerms, getTerms: getTerms, didUpdateTerms: didUpdateTerms }; return SearchService; }]); app.controller('SearchBarController', ['$scope', 'SearchService', function($scope, SearchService) { // Init form variable $scope.searchForm = null; $scope.query = 'Lisbon, Paris, Los Angeles'; // Default query value $scope.queryTerms = []; var _splitByCharacter = ','; // Set split character // Extract terms from query function extractQueryTerms(query) { var splittedTerms = query.split(_splitByCharacter); // Split by comma var trimmedTerms = splittedTerms.map(function(value) { return value.trim(); // Remove any whitespace before or after extracted term }); var filteredTerms = trimmedTerms.filter(function(value) { return value.length; }); return filteredTerms; }; // Build query from terms function builQueryFromTerms(terms) { return terms.join(', '); } // Watch for query changes and extract query terms $scope.$watch(function() { return $scope.query; }, function() { $scope.queryTerms = extractQueryTerms($scope.query); }); // Watch for queryTerms changes and update service $scope.$watch(function() { return $scope.queryTerms; }, function() { $scope.updateService(); }); // Remove term from query $scope.removeQueryTerm = function(term) { var termIndex = $scope.queryTerms.indexOf(term); // Term does not exist, return false if ( termIndex < 0 ) { return false; } // Remove term $scope.queryTerms.splice(termIndex, 1); $scope.query = builQueryFromTerms($scope.queryTerms); return true; }; // Notify service that terms were updated $scope.updateService = function() { console.log('updateService'); SearchService.updateTerms($scope.queryTerms); }; // Detect certain special keys and handle accordingly $scope.didKeyUp = function(e) { // Pressed Return if (e.keyCode == 13) { e.target.blur(); } // Pressed ESC if (e.keyCode == 27) { $scope.searchForm.searchQuery.$rollbackViewValue(); e.target.blur(); } }; // Visibility conditions - watch runs on init, sets correct visibility $scope.$watch(function() { return $scope.queryTerms; }, function() { $scope.shouldDisplayQuery = false || !$scope.queryTerms.length; $scope.shouldDisplayTerms = true && $scope.queryTerms.length; }); $scope.didFocusQuery = function() { $scope.shouldDisplayQuery = true; $scope.shouldDisplayTerms = false; }; $scope.didBlurQuery = function() { $scope.shouldDisplayQuery = false || !$scope.queryTerms.length; $scope.shouldDisplayTerms = true && $scope.queryTerms.length; }; }]); app.controller('SearchBarTermsController', ['$scope', 'SearchService', function($scope, SearchService) { $scope.terms = []; // Recieve terms updates SearchService.didUpdateTerms(function(terms) { $scope.terms = terms; }); }]); app.controller('SearchBarSuggestionsController', ['$scope', function($scope) { }]); app.controller('SearchResultsController', ['$scope', 'SearchService', function($scope, SearchService) { $scope.terms = []; // Recieve terms updates SearchService.didUpdateTerms(function(terms) { $scope.terms = terms; }); }]);
JavaScript
0.000001
@@ -3795,32 +3795,95 @@ pe.terms = %5B%5D;%0A%0A + var dataRowBase = %7B%0A label: '',%0A isLoading: true%0A %7D;%0A%0A // Recieve ter
e946e8f5a70091ab8817d4744aff152f651c14dd
fix routing bug
src/core/router/index.js
src/core/router/index.js
import Router from 'vue-router'; import store from '@/core/store'; import langShortCodes from '@/translations/getShortCodes'; import routesDefault from './routes-default'; import routesWallet from './routes-wallet'; import { ROUTES_HOME } from '../configs/configRoutes'; const routes = [routesDefault, routesWallet]; const getLangBasePath = () => { if (ROUTER_MODE === 'hash') return undefined; const locale = window.location.pathname.replace(/^\/([^/]+).*/i, '$1').trim(); if (Object.keys(langShortCodes).includes(locale)) return '/' + locale; return undefined; }; const router = new Router({ base: getLangBasePath(), mode: ROUTER_MODE || 'hash', routes: routes, scrollBehavior(to) { if (to.hash) { return { selector: to.hash }; } window.scrollTo(0, 0); } }); router.beforeResolve((to, from, next) => { // Check if user is coming from a path that needs auth if (!from.meta.noAuth && store.state.wallet.address && to.meta.noAuth) { store.dispatch('wallet/removeWallet'); } if (to.meta.noAuth) { next(); } else { if (store.state.wallet.address === null) { store.dispatch('external/setLastPath', to.path); next({ name: ROUTES_HOME.PAGE_NOT_FOUND.NAME }); } else { if (store.state.external.path !== '') { const localPath = store.state.external.path; store.dispatch('external/setLastPath', ''); router.push({ path: localPath }); } else { next(); } } } }); export default router;
JavaScript
0.000028
@@ -848,16 +848,167 @@ t) =%3E %7B%0A + // If route point doesn't exist, re-route to 404 page%0A if (to.name === null) %7B%0A next(%7B name: ROUTES_HOME.PAGE_NOT_FOUND.NAME %7D);%0A return;%0A %7D%0A // Che @@ -1354,38 +1354,37 @@ ROUTES_HOME. -PAGE_NOT_FOUND +ACCESS_WALLET .NAME %7D);%0A
5be15f2f3e5d45fef4d4c20c34b2b5d3a8f90b7d
Fix JS hints
app/scripts/app.js
app/scripts/app.js
'use strict'; require('scripts/components/*'); require('scripts/compiled/components'); require('scripts/scenes/*'); require('scripts/compiled/scenes'); require('scripts/game'); window.Game.start(); // Handle the fullscreen button $(document).on('click', function () { if (screenfull.enabled) { screenfull.request($('#cr-stage')[0]); $("body").addClass("fullscreen"); document.addEventListener(screenfull.raw.fullscreenchange, function () { if (!screenfull.isFullscreen) { // exit fullscreen code here $("body").removeClass("fullscreen"); } }); } }); function scaleGame() { var stageHeight = $("#cr-stage").height(), viewportHeight = $(window).height() ratio = viewportHeight / stageHeight; console.log(viewportHeight); $("#cr-stage").css("transform", "scale("+ratio+")"); } $(window).on("resize", function() { scaleGame(); }); scaleGame(); Crafty.debugBar.show();
JavaScript
0.000001
@@ -341,22 +341,22 @@ ;%0A $( -%22 +' body -%22 +' ).addCla @@ -354,25 +354,25 @@ ').addClass( -%22 +' fullscreen%22) @@ -365,25 +365,25 @@ ('fullscreen -%22 +' );%0A docum @@ -539,14 +539,14 @@ $( -%22 +' body -%22 +' ).re @@ -555,17 +555,17 @@ veClass( -%22 +' fullscre @@ -566,17 +566,17 @@ llscreen -%22 +' );%0A @@ -641,17 +641,17 @@ ght = $( -%22 +' #cr-stag @@ -651,17 +651,17 @@ cr-stage -%22 +' ).height @@ -664,18 +664,16 @@ ight(),%0A - view @@ -703,19 +703,18 @@ height() +, %0A - rati @@ -752,49 +752,13 @@ t;%0A%0A - console.log(viewportHeight);%0A%0A $( -%22 +' #cr- @@ -766,16 +766,16 @@ tage -%22 +' ).css( -%22 +' tran @@ -783,29 +783,29 @@ form -%22, %22 +', ' scale( -%22 +' +ratio+ -%22)%22 +')' );%0A%7D @@ -822,16 +822,16 @@ .on( -%22 +' resize -%22 +' , fu
9f60f404bbff89d8ad7c4bcb102745ff90e9c713
add reactivity on object3ds (namespace)
src/core/vgl-object3d.js
src/core/vgl-object3d.js
import { Object3D } from 'three'; import { parseVector3, parseEuler, parseQuaternion } from '../parsers'; import { vector3, euler, quaternion, boolean, string, } from '../validators'; /** * This is the base mixin component for most object components in VueGL, * corresponding [THREE.Object3D](https://threejs.org/docs/index.html#api/core/Object3D). * Object3d components inside a object3d component are added * as children via THREE.Object3D.prototype.add() method. * * VglObject3d components inside default slots are added as children. */ export default { props: { /** The object's local position as a 3D vector. */ position: vector3, /** The object's local rotation as a euler angle. */ rotation: euler, /** * The object's local rotation as a quaternion (specified in x, y, z, w order). * Do not use in conjunction with the rotation prop, since they both control the same property * of the underlying THREE.Object3D object. */ rotationQuaternion: quaternion, /** The object's local scale as a 3D vector. */ scale: vector3, /** Whether the object gets rendered into shadow map. */ castShadow: boolean, /** Whether the material receives shadows. */ receiveShadow: boolean, /** Optional name of the object. */ name: string, /** Whether the object is visible. */ visible: { type: boolean, default: true, }, }, computed: { inst: () => new Object3D(), }, inject: { vglObject3d: { default: {} }, vglNamespace: 'vglNamespace', }, provide() { const vm = this; return { vglObject3d: { get inst() { return vm.inst; } } }; }, created() { this.vglNamespace.update(); }, beforeUpdate() { this.vglNamespace.update(); }, beforeDestroy() { const { vglNamespace, inst, name } = this; if (inst.parent) inst.parent.remove(inst); if (vglNamespace.object3ds[name] === inst) delete vglNamespace.object3ds[name]; vglNamespace.update(); }, watch: { inst: { handler(inst, oldInst) { if (oldInst && oldInst.parent) oldInst.parent.remove(oldInst); if (this.vglObject3d.inst) this.vglObject3d.inst.add(inst); if (this.position) inst.position.copy(parseVector3(this.position)); if (this.rotation) inst.rotation.copy(parseEuler(this.rotation)); if (this.rotationQuaternion) inst.quaternion.copy(parseQuaternion(this.rotationQuaternion)); if (this.scale) inst.scale.copy(parseVector3(this.scale)); Object.assign(inst, { castShadow: this.castShadow, receiveShadow: this.receiveShadow, visible: this.visible, }); if (this.name !== undefined) { // eslint-disable-next-line no-param-reassign inst.name = this.name; this.vglNamespace.object3ds[this.name] = inst; } }, immediate: true, }, 'vglObject3d.inst': function parentInst(inst) { inst.add(this.inst); }, position(position) { this.inst.position.copy(parseVector3(position)); }, rotation(rotation) { this.inst.rotation.copy(parseEuler(rotation)); }, rotationQuaternion(rotationQuaternion) { this.inst.quaternion.copy(parseQuaternion(rotationQuaternion)); }, scale(scale) { this.inst.scale.copy(parseVector3(scale)); }, castShadow(castShadow) { this.inst.castShadow = castShadow; }, receiveShadow(receiveShadow) { this.inst.receiveShadow = receiveShadow; }, name(name, oldName) { const { vglNamespace: { object3ds }, inst } = this; if (object3ds[oldName] === inst) delete object3ds[oldName]; this.inst.name = name; object3ds[name] = inst; }, visible(visible) { this.inst.visible = visible; }, }, render(h) { return this.$slots.default ? h('div', this.$slots.default) : undefined; }, };
JavaScript
0
@@ -1920,23 +1920,29 @@ = inst) +this.$ delete - +( vglNames @@ -1955,22 +1955,23 @@ bject3ds -%5B +, name -%5D +) ;%0A vg @@ -2800,24 +2800,34 @@ ;%0A +this.$set( this.vglName @@ -2841,17 +2841,18 @@ bject3ds -%5B +, this.nam @@ -2848,32 +2848,31 @@ s, this.name -%5D = +, inst +) ;%0A %7D%0A @@ -3598,15 +3598,21 @@ st) +this.$ delete - +( obje @@ -3616,25 +3616,26 @@ bject3ds -%5B +, oldName -%5D +) ;%0A @@ -3663,16 +3663,26 @@ ;%0A +this.$set( object3d @@ -3686,21 +3686,21 @@ t3ds -%5B +, name -%5D = +, inst +) ;%0A
1060ee1db3dd5b0b587d6834ed122dffe7ad8990
Set the current document to the first search result
src/sidebar.js
src/sidebar.js
// SidebarView define(function (require) { var _ = require('underscore'), $ = require('jquery'), Backbone = require('backbone'), Handlebars = require('handlebars'), SimpleSearchListItemView = require('./simple_search_list_item'); var SidebarView = Backbone.View.extend({ tagName: 'div', className: 'stfd-sidebar', initialize: function(options) { var t = this; _.bindAll(t, 'render'); t.results_model = options.results_model; t.doc_model = options.doc_model; t.query_model = options.query_model; t.listenTo(t.results_model, 'change', t.render); }, render: function() { var t = this; // Clear existing items. t.$el.html(''); _.each(t.results_model.get_records(), function(record) { var record_view = new SimpleSearchListItemView({ record: record, doc_model: t.doc_model, query_model: t.query_model }); t.$el.append(record_view.render().el); }); return t; } }); return SidebarView; });
JavaScript
0.000002
@@ -727,15 +727,22 @@ -_.each( +var records = t.re @@ -766,16 +766,104 @@ ecords() +;%0A%0A // Create a list item view for each record in the results.%0A _.each(records , functi @@ -1088,16 +1088,16 @@ ().el);%0A - %7D) @@ -1094,24 +1094,307 @@ ;%0A %7D);%0A +%0A // Set the current document to the first result, if any.%0A if (records && records.length %3E 0) %7B%0A var doc_obj = _.extend(%0A %7B%7D,%0A records%5B0%5D,%0A %7Bsearch: t.query_model.get('search')%7D%0A );%0A t.doc_model.set(doc_obj);%0A %7D%0A%0A return
13a56423ec7b22c6e94e0cd0475e1be39e7beb7c
fix name
app/utils/index.js
app/utils/index.js
const mapToFakeStatus = (fakeStatus, fakeResolution) => fakeStatus === 'resolved' ? fakeResolution : fakeStatus; const needToAlter = [ 'successful', 'partially_successful', 'not_held', 'refused', 'user_withdrew_costs', 'user_withdrew', ]; function mapToFakeStatus(realStatus) { if (needToAlter.indexOf(realStatus) !== -1) { return { status: 'resolved', resolution: realStatus, }; } return { status: realStatus, resolution: null, }; } const getItemById = id => x => x.id === id; export { mapToRealStatus, mapToFakeStatus, getItemById };
JavaScript
0.019891
@@ -1,27 +1,27 @@ const mapTo -Fake +Real Status = (fa
52851e9cf6de788ded2e86f64b92fc356ff4a8dd
update content
app/views/index.js
app/views/index.js
define(['app', 'angular', 'authentication'], function() { 'use strict'; return ['$scope', '$rootScope', '$route', '$browser', '$location', '$window', 'authentication', function ($scope, $rootScope, $route, $browser, $location, $window, authentication) { $scope.carouselData= { items :[ { title: "Sustainable Ocean Night at UN Ocean Conference", description: "Sustainable Ocean Night at UN Ocean Conference", imageUrl: "app/images/carousel/soi-oc-group-photo.jpg", targetUrl: "http://enb.iisd.org/oceans/sdg14conference/cbd-partners/6jun.html" }, { title: "Sustainable Ocean Initiative video", description: "", imageUrl: "app/images/carousel/soi-video.jpg", targetUrl: "https://www.youtube.com/watch?v=4q6RiihseQ8" }, { title: "Sustainable Oceans: Marine Biodiversity for the Future We Want", description: "", imageUrl: "app/images/carousel/soi-marine-biodiversity-video.jpg", targetUrl: "https://www.youtube.com/watch?v=73hSF4kC0Lg" }, { title: "Blue Solutions Panorama", description: "", imageUrl: "app/images/carousel/blue-solutions.jpg", targetUrl: "http://panorama.solutions/en/portal/marine-coastal" }, { title: "CBD and Partners at the UN Ocean Conference", description: "", imageUrl: "app/images/carousel/cbd-ocean-conference.jpg", targetUrl: "http://enb.iisd.org/oceans/sdg14conference/cbd-partners/about.html" }, { title: "SOI Global Dialogue with Regional Seas Organizations and Regional Fisheries Bodies", description: "", imageUrl: "app/images/carousel/soiom-2016-01-group-photo.jpg", targetUrl: "https://www.cbd.int/doc/?meeting=SOIOM-2016-01" }, { title: "Perspectives on Marine Biodiversity and Sustainable Development: Interviews at the UN Ocean Conference", imageUrl: "app/images/carousel/soi-interview.jpg", targetUrl: "resources/unoc-interviews" }, ] }; $(document).ready(function(){ $('.carousel').carousel({ interval: 5000 }); }); $rootScope.homePage = true; $rootScope.navigation = []; $rootScope.navigationTree = []; }]; });
JavaScript
0
@@ -1067,16 +1067,42 @@ title: %22 +PANORAMA portal hosted by Blue Sol @@ -1111,17 +1111,8 @@ ions - Panorama %22,%0A%09
e5110938e6ccf52c42d9c5c057ca01435e3a7aa9
Add unique identifier in front of the label
src/getChart.js
src/getChart.js
'use strict'; // convert an experiment, an array of spectra, to a chart var types=require('./types.js'); module.exports=function (experiments, channels, index) { var channels = channels || 'RGBWZE' if (! Array.isArray(experiments)) experiments=[experiments]; var chart = { type: "chart", value: { title: "Open Spectrophotometer results", "axis": [ { "label": "nM" }, { "label": "Y axis" } ], "data": [] } } for (var i = 0; i < experiments.length; i++) { if ((index === undefined) || (index === i)) { var experiment=experiments[i]; for (var key in experiment) { if (channels.indexOf(key)>-1) { var data=experiment[key]; chart.value.data.push({ "x":data.x, "y":data.y, "label":types[key].label+": "+data.name, xAxis: 0, yAxis: 1, lineWidth: 2, color: 'red' }); } } } } return chart; }
JavaScript
0.000031
@@ -595,24 +595,43 @@ %7D%0A %7D%0A + var counter=0;%0A for (var @@ -1050,16 +1050,33 @@ %22label%22: +(++counter)+%22. %22+ types%5Bke
f79ad552152b640a32aa007dfcd9c39dfc875dff
Update TemperatureSensor_MRz_accessory.js
accessories/TemperatureSensor_MRz_accessory.js
accessories/TemperatureSensor_MRz_accessory.js
var Accessory = require('../').Accessory; var Service = require('../').Service; var Characteristic = require('../').Characteristic; var uuid = require('../').uuid; var DS3231ESPTEMP = { currentTemperature: 50, getTemperature: function() { console.log("Getting the current temperature!"); return DS3231ESPTEMP.currentTemperature; }, setTemperature: function(value) { console.log(value); DS3231ESPTEMP.currentTemperature = Math.round(value) } } // Generate a consistent UUID for our Temperature Sensor Accessory that will remain the same // even when restarting our server. We use the `uuid.generate` helper function to create // a deterministic UUID based on an arbitrary "namespace" and the string "temperature-sensor". var sensorUUID = uuid.generate('hap-nodejs:accessories:temperature-sensor'); // This is the Accessory that we'll return to HAP-NodeJS that represents our fake lock. var sensor = exports.accessory = new Accessory('Temperature Sensor', sensorUUID); // Add properties for publishing (in case we're using Core.js and not BridgedCore.js) sensor.username = "A3:99:32:BB:5E:AA"; sensor.pincode = "031-45-154"; // Add the actual TemperatureSensor Service. // We can see the complete list of Services and Characteristics in `lib/gen/HomeKitTypes.js` sensor .addService(Service.TemperatureSensor) .getCharacteristic(Characteristic.CurrentTemperature) .on('get', function(callback) { // return our current value callback(null, DS3231ESPTEMP.getTemperature()); }); var mqtt = require('mqtt'); var client = mqtt.connect('mqtt://localhost');//mqtt server. client.on('connect', function() { client.subscribe('temperature'); client.on('message', function(topic, message) { //subscribe to topic DS3231ESPTEMP.setTemperature(message); console.log("Sensor current temperature from mqtt:" + DS3231ESPTEMP.currentTemperature) // update the characteristic value so interested iOS devices can get notified sensor .getService(Service.TemperatureSensor) .setCharacteristic(Characteristic.CurrentTemperature, DS3231ESPTEMP.currentTemperature) console.log(message.toString()); }); });
JavaScript
0
@@ -1006,16 +1006,20 @@ e Sensor + MRz ', senso
e87e9975541f61872c7bf1fd8e2e2192d805da29
Update standard.spec.js
tests/viewerpreferences/standard.spec.js
tests/viewerpreferences/standard.spec.js
'use strict' /* global describe, it, expect, jsPDF, comparePdf */ /** * Standard spec tests * * These tests return the datauristring so that reference files can be generated. * We compare the exact output. */ describe('viewerpreferences plugin', () => { it('HideToolbar', () => { const doc = new jsPDF() doc.text(10, 10, 'This is a test') doc.viewerPreferences({'HideToolbar': true}) comparePdf(doc.output(), 'HideToolbar.pdf', 'viewerpreferences') }) it('HideMenubar', () => { const doc = new jsPDF() doc.text(10, 10, 'This is a test') doc.viewerPreferences({'HideMenubar': true}) comparePdf(doc.output(), 'HideMenubar.pdf', 'viewerpreferences') }) it('HideWindowUI', () => { const doc = new jsPDF() doc.text(10, 10, 'This is a test') doc.viewerPreferences({'HideWindowUI': true}) comparePdf(doc.output(), 'HideWindowUI.pdf', 'viewerpreferences') }) it('FitWindow', () => { const doc = new jsPDF() doc.text(10, 10, 'This is a test') doc.viewerPreferences({'FitWindow': true}) comparePdf(doc.output(), 'FitWindow.pdf', 'viewerpreferences') }) /** it('check if reset works var. 1', () => { const doc = new jsPDF() doc.text(10, 10, 'This is a test') doc.viewerPreferences({'HideWindowUI': true}) doc.viewerPreferences('reset') doc.viewerPreferences({'FitWindow': true}) comparePdf(doc.output(), 'FitWindow.pdf', 'viewerpreferences') }) it('check if reset works var. 2', () => { const doc = new jsPDF() doc.text(10, 10, 'This is a test') doc.viewerPreferences({'HideWindowUI': true}) doc.viewerPreferences({'FitWindow': true}, true) comparePdf(doc.output(), 'FitWindow.pdf', 'viewerpreferences') }) */ it('ViewArea MediaBox', () => { const doc = new jsPDF() doc.text(10, 10, 'This is a test') doc.viewerPreferences({'ViewArea' : 'MediaBox'}) comparePdf(doc.output(), 'ViewAreaMediaBox.pdf', 'viewerpreferences') }) it('PrintPageRange', () => { const doc = new jsPDF() doc.text(10, 10, 'This is a test') doc.viewerPreferences({'PrintPageRange' : [[1,3],[5,9]]}) comparePdf(doc.output(), 'PrintPageRange.pdf', 'viewerpreferences') }) })
JavaScript
0
@@ -1129,14 +1129,8 @@ %7D)%0A - /**%0A it @@ -1740,13 +1740,8 @@ %7D)%0A - */%0A it
c32812b171ff81f678aebf846d276f1bb1ea8989
Store currentVideo playing data
devServer.js
devServer.js
var webpack = require('webpack'); var webpackDevMiddleware = require('webpack-dev-middleware'); var webpackHotMiddleware = require('webpack-hot-middleware'); var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); var config = require('./webpack.config'); var toId = require('./toId'); var parse = require('./parse'); var Deque = require("double-ended-queue"); var got = require('got'); var moment = require('moment'); var port = process.env.PORT || 3000; var compiler = webpack(config); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(webpackHotMiddleware(compiler)); app.get('/', function(req, res) { res.sendFile(__dirname + '/index.html'); }); var users = {}; var history = []; var currentVideoDuration = 0; var videos = new Deque(); var isPlaying = false; function getDuration(id) { return new Promise((resolve, reject) => { const url = 'https://www.googleapis.com/youtube/v3/videos?id=' + id + '&key=AIzaSyDYwPzLevXauI-kTSVXTLroLyHEONuF9Rw&part=snippet,contentDetails'; got(url) .then(response => { const json = JSON.parse(response.body); if (!json.items.length) return reject(); const time = json.items[0].contentDetails.duration; resolve(moment.duration(time).asMilliseconds()); }) .catch(error => console.log(error.response.body)); }); } function nextVideo(io, socket) { if (isPlaying) return; if (videos.isEmpty()) { isPlaying = false; return; } const videoid = videos.shift(); getDuration(videoid) .then(duration => { isPlaying = true; setTimeout(() => { isPlaying = false; nextVideo(io); }, duration); io.emit('next video', videoid); }) .catch(error => { socket.emit('error video', {message: 'Invalid video url.'}); }); } io.on('connection', function(socket){ console.log('a user connected'); socket.emit('chat history', {users: Object.keys(users).map(userid => users[userid].username), history: history}); socket.on('add video', function(video) { videos.push(video); nextVideo(io, socket); }); socket.on('chat message', function(data) { if (data.message.length > 300) return; if (typeof data === 'object' && data.hasOwnProperty('username')) { const markup = {__html: parse(data.message)}; data = {username: data.username, message: markup}; } history.push(data); io.emit('chat message', data); }); socket.on('add user', function(username) { const userid = toId(username); if (!userid || userid.length > 19) return; if (socket.user && username !== socket.user.username && userid === socket.user.userid) { users[userid] = {userid: userid, username: username, ip: socket.handshake.address}; socket.user = users[userid]; io.emit('update users', Object.keys(users).map(userid => users[userid].username)); return; } if (users[userid]) return; if (socket.user && socket.user.userid) { delete users[socket.user.userid]; } users[userid] = {userid: userid, username: username, ip: socket.handshake.address}; socket.user = users[userid]; io.emit('update users', Object.keys(users).map(userid => users[userid].username)); }); socket.on('disconnect', function() { if (socket.user) delete users[socket.user.userid]; io.emit('update users', Object.keys(users).map(userid => users[userid].username)); console.log('user disconnected'); }); }); server.listen(port, function(error) { if (error) { console.error(error); } else { console.info('==> Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port); } });
JavaScript
0
@@ -799,38 +799,8 @@ %5B%5D;%0A -var currentVideoDuration = 0;%0A var @@ -843,16 +843,60 @@ = false; +%0Avar currentVideo = %7Bvideoid: '', start: 0%7D; %0A%0Afuncti @@ -1666,16 +1666,76 @@ = true;%0A + currentVideo = %7Bvideoid: videoid, start: Date.now()%7D;%0A se
32bf964785b24d0bd45d8b71c6c98d73ed3300ef
Fix misleading sign up success Bert Alert
imports/ui/components/account/AccountAlerts.js
imports/ui/components/account/AccountAlerts.js
/** * Notification functions for displaying accounts-related user feedback, * such as success or failure messages for logging in, logging out, * signing in and forgetting password. */ const MAX_PASSWORD_TRIES = 5; export const successMsgs = { SUCCESS_LOGIN: "Welcome back!", SUCCESS_SIGNUP: "Welcome! Please log in with your new account below!", SUCCESS_SETUP: "Setup is all done. Welcome to NUS Oracle!", SUCCESS_NEW_PASSWORD_SENT: "New password sent to your email!" } export const warningMsgs = { WARNING_CANCEL_SETUP: "Click again to leave this page" } export const errorMsgs = { ERR_INCORRECT_PASSWORD: "Incorrect password entered", ERR_PASSWORDS_NOT_MATCH: "Passwords do not match", ERR_EXCEEDED_LOGIN_ATTEMPTS: "Password reset. Too many login attempts. Please check", ERR_EMAIL_UNRECOGNIZED: "is not recognized. Have you created an account yet?", ERR_EMAIL_UNVERIFIED: "Your email has not been verified. Please check", ERR_EMAIL_ENTERED_INVALID: "Invalid NUS email. Remember to end your email address with '@u.nus.edu'", ERR_SETUP_INCOMPLETE: "Please enter all four fields before continuing", } //===================================================== // CUSTOM SUCCESS MESSAGES //===================================================== /** * SUCCESSFUL Login Message * @param {[String]} username User's username * @return {[String]} Welcome message */ export const successMsgLoginName = function(username) { return successMsgs.SUCCESS_LOGIN + " " + username; } //===================================================== // CUSTOM ERROR MESSAGES //===================================================== /** * ERROR Incorrect Password with Number of Tries Message * @param {[String]} numOfTries Number of times the user has tried * @return {[String]} Error message counting down number of tries left */ export const errorMsgIncorrectPassword = function(numOfTries) { let numTriesMsg = "You've got " + (MAX_PASSWORD_TRIES - numOfTries) + " tries left."; return errorMsgs.ERR_INCORRECT_PASSWORD + ". " + numTriesMsg; } /** * ERROR Warning when user exceeded the max number of login attempts Message * @param {[String]} email User's email address * @return {[String]} Error message */ export const errorMsgExceededLoginAttempts = function(email) { return errorMsgs.ERR_EXCEEDED_LOGIN_ATTEMPTS + " " + email; } /** * ERROR Warning when user hasn't verified email Message * @param {[String]} email User's email address * @return {[String]} Error message */ export const errorMsgUnverifiedEmail = function(email) { return errorMsgs.ERR_EMAIL_UNVERIFIED + " " + email; } /** * ERROR Warning when the email the user entered isn't a recognized in our * database Message * @param {[String]} email User's email address * @return {[String]} Error message */ export const errorMsgUnrecognizedEmail = function(email) { console.log(errorMsgs.ERR_EMAIL_UNRECOGNIZED); return email + " " + errorMsgs.ERR_EMAIL_UNRECOGNIZED; }
JavaScript
0.002296
@@ -299,52 +299,88 @@ P: %22 -Welcome! Please log in with your new +Thanks for signing up! Please check your email to verify your NUS Oracle account bel @@ -379,14 +379,8 @@ ount - below !%22,%0A
ece21e18feb6871c83f02bc4a2516471c61c4bee
Make options argument to ol.style.Text optional
src/ol/style/textstyle.js
src/ol/style/textstyle.js
goog.provide('ol.style.Text'); /** * @constructor * @param {olx.style.TextOptions} options Options. */ ol.style.Text = function(options) { /** * @type {string|undefined} */ this.font = options.font; /** * @type {number|undefined} */ this.rotation = options.rotation; /** * @type {string|undefined} */ this.text = options.text; /** * @type {string|undefined} */ this.textAlign = options.textAlign; /** * @type {string|undefined} */ this.textBaseline = options.textBaseline; /** * @type {ol.style.Fill} */ this.fill = goog.isDef(options.fill) ? options.fill : null; /** * @type {ol.style.Stroke} */ this.stroke = goog.isDef(options.stroke) ? options.stroke : null; }; /** * @param {ol.style.Text} textStyle1 Text style 1. * @param {ol.style.Text} textStyle2 Text style 2. * @return {boolean} Equals. */ ol.style.Text.equals = function(textStyle1, textStyle2) { if (!goog.isNull(textStyle1)) { if (!goog.isNull(textStyle2)) { return textStyle1 === textStyle2 || ( textStyle1.font == textStyle2.font && textStyle1.text == textStyle2.text && textStyle1.textAlign == textStyle2.textAlign && textStyle1.textBaseline == textStyle2.textBaseline); } else { return false; } } else { if (!goog.isNull(textStyle2)) { return false; } else { return true; } } };
JavaScript
0.002239
@@ -79,18 +79,23 @@ tOptions += %7D +opt_ options @@ -132,16 +132,20 @@ unction( +opt_ options) @@ -148,16 +148,77 @@ ons) %7B%0A%0A + var options = goog.isDef(opt_options) ? opt_options : %7B%7D;%0A%0A /**%0A
5ecd31f7971e524db1c0ea9ec8300c17297f97f6
Add updateQueuePosition function to Chatbody
frontend/src/components/chat/body/Chatbody.js
frontend/src/components/chat/body/Chatbody.js
import React, { Component } from 'react'; import ChatMessages from './ChatMessages'; import ChatFooter from './ChatFooter'; import realtimeConnector from '../connection/realtimeConnector'; import presenceConnector from '../connection/presenceConnector'; import * as config from '../../config'; import QueueMessage from './QueueMessage'; import Sound from 'react-sound'; import axios from 'axios'; axios.defaults.withCredentials = true; const INFO_MESSAGES = { queued: 'Είσαι στην ουρά...', alreadyConnected: 'Έχεις ήδη συνδεθεί!' } const GENDERS = { '0': '(Μη-ορισμένο φύλο)', '1': 'γυναίκα', '-1': 'άνδρα' } class Chatbody extends Component { constructor(props) { super(props); this.state = { partner: {}, me: {}, messages: [], isFooterDisabled: true, infoMessage: INFO_MESSAGES.queued, footerInfoMessage: '', playSound: '' }; } disableChat = (disableOption) => { if (disableOption) { this.setState({isFooterDisabled: disableOption, infoMessage: INFO_MESSAGES.queued, footerInfoMessage: ''}); } else { this.setState({isFooterDisabled: disableOption, infoMessage: ''}); } } alreadyConnected = () => { this.setState({infoMessage: INFO_MESSAGES.alreadyConnected}); } handleNext = (origin) => { if (origin === 'me') { this._realtimeConnector.broadcastNext(); } this._realtimeConnector.disconnect(); this._presenceConnector.reconnect(); } handleNewMessage = (message, from) => { if (message !== '') { if (from === undefined) { from = 'me'; } let newMessages = this.state.messages; let newMessage = { content: message, timestamp: new Date(), from: from }; if (from === 'me') { this._realtimeConnector.broadcastMessage(message); newMessage.gender = this.state.me.gender; newMessage.school = this.state.me.school; } else { if (!document.hasFocus()) { this.setState({playSound: Sound.status.PLAYING}); } newMessage.gender = this.state.partner.gender; newMessage.school = this.state.partner.school; } newMessages.push(newMessage); this.setState({messages: newMessages}); } } joinRoom = (realtimeUrl, roomId, partnerInfo) => { if (!document.hasFocus()) { this.setState({playSound: Sound.status.PLAYING}); } let connectedWithMessage = 'Έχεις συνδεθεί με ' + GENDERS[partnerInfo.gender] + ' από ' + partnerInfo.school + ', ' + partnerInfo.university; let newMessages = this.state.messages; let newMessage = { content: connectedWithMessage, gender: '2', timestamp: new Date(), from: 'unimeet' }; newMessages.push(newMessage); this.setState({ partner: { gender: partnerInfo.gender, school: partnerInfo.school + ', ' + partnerInfo.university, }, footerInfoMessage: connectedWithMessage, messages: newMessages }); axios.get(config.backendUrl + '/user_info') .then(res => { this.setState({ me: { gender: res.data.gender, school: res.data.school + ', ' + res.data.university } }); this._realtimeConnector = new realtimeConnector(this.props.token, realtimeUrl, this.handleNewMessage, this.handleNext, this.disableChat); this._realtimeConnector.joinRoom(roomId); this._presenceConnector.disconnect(); }) .catch(error => { console.log(error); }) } componentDidMount() { this._presenceConnector = new presenceConnector(this.props.token, config.presenceUrl, this.joinRoom, this.alreadyConnected); } componentWillReceiveProps(nextProps) { if (this.props.infoUpdate !== nextProps.infoUpdate) { if (this._presenceConnector.isConnected) { this._presenceConnector.disconnect(); this._presenceConnector = new presenceConnector(this.props.token, config.presenceUrl, this.joinRoom, this.alreadyConnected); } } } render() { return ( <div className="Chatbox"> <ChatMessages messages={this.state.messages} partner={this.state.partner} me={this.state.me} /> <ChatFooter handleNext={this.handleNext} handleNewMessage={this.handleNewMessage} footerInfoMessage={this.state.footerInfoMessage} isFooterDisabled={this.state.isFooterDisabled} /> <Sound url="ring.mp3" playStatus={this.state.playSound} /> { this.state.infoMessage !== '' ? <QueueMessage infoMessage={this.state.infoMessage} /> : null } </div> ); } } export default Chatbody;
JavaScript
0.000001
@@ -1373,32 +1373,192 @@ ected%7D);%0A %7D%0A%0A + updateQueuePosition = (queuePosition) =%3E %7B%0A this.setState(%7BinfoMessage: INFO_MESSAGES.queued + ' (%CE%98%CE%AD%CF%83%CE%B7: ' + queuePosition.toString() + ')'%7D);%0A %7D%0A%0A handleNext =
7458eddac266564b7bef0e675fa57c2ac97554f9
Add line chart
host/Chart.js
host/Chart.js
import React, { Component } from 'react' import { connect } from 'react-redux' import ReactHighcharts from 'react-highcharts' import HighchartsMore from 'highcharts-more' HighchartsMore(ReactHighcharts.Highcharts) function computeQuartile(array, length, n, d) { const pos = (length - 1.0) * n / d const divisible = (length - 1) % d == 0 if (divisible) { return array[Math.trunc(pos)] } else { const posInt = Math.trunc(pos) const ratio1 = pos - posInt const ratio2 = 1.0 - ratio1 return array[posInt] * ratio2 + array[posInt + 1] * ratio1 } } const mapStateToProps = ({investmentLog, rounds}) => { const data = Array.from(Array(rounds).keys()).map(() => []) investmentLog.forEach(({round, investments}) => { Array.prototype.push.apply(data[round], investments) }) const finalData = data.map(investments => { investments.sort((a, b) => a - b) length = investments.length const low = investments[0] const q1 = computeQuartile(investments, length, 1, 4) const median = computeQuartile(investments, length, 1, 2) const q2 = computeQuartile(investments, length, 3, 4) const high = investments[length - 1] return [low, q1, median, q2, high] }) const config = { chart: { type: 'boxplot' }, title: { text: 'タイトル' }, legend: { enabled: false }, xAxis: { categories: Array.from(Array(rounds).keys()).map(x => (x + 1).toString()), title: { text: 'Round' } }, yAxis: { title: { text: '投資額' }, }, series: [{ name: '投資額', data: finalData, tooltip: { headerFormat: '<em>{point.key}回目</em><br/>' } }] } console.log(config) return { display: investmentLog.length > 0, config } } const Chart = ({ config, display }) => ( display ? <ReactHighcharts config={config} /> : null ) export default connect(mapStateToProps)(Chart)
JavaScript
0.000003
@@ -1206,24 +1206,74 @@ high%5D%0A %7D)%0A + const lineData = finalData.map(list =%3E list%5B2%5D)%0A const conf @@ -1748,24 +1748,74 @@ /%3E'%0A %7D%0A + %7D, %7B%0A type: %22line%22,%0A data: lineData%0A %7D%5D%0A %7D%0A
a5b8d890d73b49020bb79a49e9a9eb86cc35da80
Update openClosedVines2.user.js
openClosedVines2.user.js
openClosedVines2.user.js
// ==UserScript== // @name Auto open sensitive Vines // @namespace http://nindogo.tumblr.com/ // @version 0.1.0.4 // @description open vines that are hidden due to sensitivity. // @match https://vine.co/* // @downloadURL https://github.com/nindogo/test_repo/raw/master/openClosedVines2.user.js // @include https://mutation-summary.googlecode.com/git/src/mutation-summary.js // @run-at document-end // @copyright 2014+, Nindogo // ==/UserScript== window.onload = openVines; function openVines() { var i, j, x, y, z; x = document.getElementsByClassName("small"); console.log(x.length); for (i = (x.length - 1); i > -1; i--) { console.log(i); console.log(x[i]); try { x[i].click(); } catch (error) { console.log("during " + i + " I caught error: " + error.type + " with message: " + error.message); } } }
JavaScript
0
@@ -115,17 +115,17 @@ 0.1.0. -4 +5 %0A// @des @@ -311,14 +311,14 @@ // @ -includ +requir e ht @@ -462,35 +462,282 @@ ==%0A%0A -%0Awindow.onload = openVines; +var observer = new MutationSummary(%7B%0A callback: openVines,%0A queries: %5B%7B%0A element: 'button.small',%0A elementAttributes: %22button.small%22 // optional%0A %7D%5D%0A%7D);%0A%0Afunction openVines(summay) %7B%0A console.log(summay%5B0%5D.added);%0A openVines2(summay%5B0%5D.added);%0A%7D %0A%0Afu @@ -752,17 +752,19 @@ penVines -( +2(u ) %7B%0A @@ -774,24 +774,17 @@ i, -j, x, y, z +x ;%0A +// x = @@ -825,16 +825,25 @@ mall%22);%0A + x=u;%0A cons
f8341ec90424c2a8a02588ff2f8e4abb6821d734
Tidy up
packages/udaru-hapi-plugin/index.js
packages/udaru-hapi-plugin/index.js
'use strict' const buildUdaru = require('@nearform/udaru-core') const buildConfig = require('./lib/config') const buildAuthorization = require('./lib/authorization') const HapiAuthService = require('./lib/authentication') const pluginName = 'udaru-hapi-plugin' module.exports = { pkg: require('./package'), name: pluginName, async register (server, options) { const config = buildConfig(options.config) const udaru = buildUdaru(options.dbPool, config) // If there are hooks to register if (typeof options.hooks === 'object') { for (const hook of Object.keys(options.hooks)) { // For each hook // Normalize handlers to always be an array and only consider functions let handlers = options.hooks[hook] if (!Array.isArray(handlers)) handlers = [handlers] handlers = handlers.filter(f => typeof f === 'function') // Register each handler for (const handler of handlers) { udaru.hooks.add(hook, handler) } } } server.decorate('server', 'udaru', udaru) server.decorate('server', 'udaruConfig', config) server.decorate('server', 'udaruAuthorization', buildAuthorization(config)) server.decorate('request', 'udaruCore', udaru) await server.register([ require('./lib/routes/users'), require('./lib/routes/policies'), require('./lib/routes/teams'), require('./lib/routes/authorization'), require('./lib/routes/organizations'), require('./lib/routes/monitor'), HapiAuthService ]) server.auth.strategy('udaru', 'udaru') server.auth.default({ mode: 'required', strategy: 'udaru' }) } }
JavaScript
0.000027
@@ -221,48 +221,8 @@ ')%0A%0A -const pluginName = 'udaru-hapi-plugin'%0A%0A modu @@ -277,18 +277,27 @@ me: +'udaru-hapi- plugin -Name +' ,%0A
b7b01e71b1cb06f06e497715db8a97bc814792b3
create file with 'settings.output' option
packages/uglify-es/src/uglify-es.js
packages/uglify-es/src/uglify-es.js
/*! * node-minify * Copyright(c) 2011-2019 Rodolphe Stoclin * MIT Licensed */ /** * Module dependencies. */ import uglifyES from 'uglify-es'; import { utils } from '@node-minify/utils'; /** * Run uglifyES. * * @param {Object} settings * @param {String} content * @param {Function} callback */ const minifyUglifyES = ({ settings, content, callback, index }) => { const contentMinified = uglifyES.minify(content, settings.options); if (contentMinified.error) { if (callback) { return callback(contentMinified.error); } } if (contentMinified.map && settings.options.sourceMap) { utils.writeFile({ file: settings.options.sourceMap.url, content: contentMinified.map, index }); } utils.writeFile({ file: settings.output, content: contentMinified.code, index }); if (callback) { return callback(null, contentMinified.code); } return contentMinified.code; }; /** * Expose `minifyUglifyES()`. */ module.exports = minifyUglifyES;
JavaScript
0.000007
@@ -625,32 +625,35 @@ iteFile(%7B file: +%60$%7B settings.options @@ -650,28 +650,19 @@ gs.o -ptions.sourceMap.url +utput%7D.map%60 , co
8b4ef0eac6ef41228fdc86621dea66d3bd59aa23
add item workflow improvements
src/flows/addItem.js
src/flows/addItem.js
'use strict' module.exports = (app) => { let slapp = app.slapp let kv = app.kv slapp.message('new item', ['direct_mention', 'direct_message'], (msg, text, role) => { slapp.client.users.info({ token: msg.meta.bot_token, user: msg.meta.user_id }, (err, data) => { kv.get("owners", (err, roleList) => { if (err) return handleError(err, msg) if(roleList.indexOf(data.user.name) !== -1) msg.say(`Title?`).route('new-item-title', { greeting: text }) else msg.say("Must be owner!") }) }) }) .route('new-item-title', (msg, state) => { var text = (msg.body.event && msg.body.event.text) || '' if (!text) { return msg .say("Whoops, I'm still waiting to hear our new item.") .say('Title?') .route('new-item-title', state) } state.title = text msg.say(`Sounds good! Little description?`).route('new-item-desc', state) }) .route('new-item-desc', (msg, state) => { var text = (msg.body.event && msg.body.event.text) || '' if (!text) { return msg .say("I'm eagerly awaiting to hear the description.") .route('new-item-desc', state) } state.desc = text kv.get("qa reviewers", (err, roleList) => { if (err) return handleError(err, msg) msg.say('Thanks!').say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``) roleList.forEach(function(element){ msg.say('@'+element + ' Please Review ' + state.title) }) kv.get("dev reviewers", (err, roleList) => { if (err) return handleError(err, msg) roleList.forEach(function(element){ msg.say('@'+element + ' Please Review ' + state.title) }) }) }) }) function handleError (err, msg) { console.error(err) // Only show errors when we can respond with an ephemeral message // So this includes any button actions or slash commands if (!msg.body.response_url) return msg.respond({ text: `:scream: Uh Oh: ${err.message || err}`, response_type: 'ephemeral', replace_original: false }, (err) => { if (err) console.error('Error handling error:', err) }) } }
JavaScript
0
@@ -1525,16 +1525,35 @@ %5C%60%5C%60%60)%0A%0A + msg.say()%0A%0A @@ -1620,32 +1620,159 @@ element + ' -Please R +' + state.title + ' changes do not require QA or have automated test coverage?')%0A msg.say('@'+element + ' Please reply %22qa r eview ' + st @@ -1772,32 +1772,46 @@ ' + state.title + + 'yes/no%22 ?' )%0A %7D)%0A @@ -2012,16 +2012,124 @@ + ' -Please R +' + state.title + ' changes constainted to one system?')%0A msg.say('@'+element + ' Please reply %22dev r evie @@ -2145,16 +2145,30 @@ te.title + + 'yes/no%22 ?' )%0A
679aeefc869eb69b873c5220b9f6104b6b03b6e2
Update FFA.js
src/gamemodes/FFA.js
src/gamemodes/FFA.js
var Mode = require('./Mode'); function FFA() { Mode.apply(this, Array.prototype.slice.call(arguments)); this.ID = 0; this.name = "Free For All"; this.specByLeaderboard = true; } module.exports = FFA; FFA.prototype = new Mode(); // Gamemode Specific Functions FFA.prototype.onPlayerSpawn = function(gameServer, player) { player.setColor(gameServer.getRandomColor()); // Spawn player gameServer.spawnPlayer(player, gameServer.randomPos()); }; FFA.prototype.updateLB = function(gameServer, lb) { gameServer.leaderboardType = this.packetLB; for (var i = 0, pos = 0; i < gameServer.clients.length; i++) { var player = gameServer.clients[i].playerTracker; if (player.isRemoved || !player.cells.length || player.socket.isConnected == false || player.isMi) continue; for (var j = 0; j < pos; j++) if (lb[j]._score < player._score) break; lb.splice(j, 0, player); pos++; } this.rankOne = lb[0]; };
JavaScript
0
@@ -365,17 +365,16 @@ yer. -setC +c olor -( + = game @@ -396,17 +396,16 @@ mColor() -) ;%0D%0A /
5bb07fdc737d974fc2c52647c355053ffb0bdce1
Add host specification
src/githubFactory.js
src/githubFactory.js
var GithubLib = require('github') var queue = require('queue') var rawGithubFactory = function (token) { // Allow to inject a GitHub API instead of a token if (token.repos) { return token } var res = new GithubLib({ version: '3.0.0' }) res.authenticate({ type: 'oauth', token: token }) return res } module.exports = function (token) { var api = rawGithubFactory(token) var q = queue({ concurrency: 1, timeout: 2000 }) // Transform a github function call into a queued function call // to ensure that only one API call runs at a time // https://developer.github.com/guides/best-practices-for-integrators/#dealing-with-abuse-rate-limits var qd = function(call){ if (typeof call !== 'function') throw new Error('call should be a function: ' + call); return function(){ var args = [].slice.apply(arguments) return new Promise(function(resolve, reject){ q.push(function(cb){ var argsCb = args.pop() if (typeof argsCb !== 'function') { args.push(argsCb) argsCb = null } call.apply(null, args).then(function(result){ cb() if (argsCb) argsCb(null, result) resolve(result) }, function(error){ cb() if (argsCb) argsCb(error) reject(error) }) }) q.start() }) } } var makeResponseTransformer = function(transform){ return function(call){ if (typeof call !== 'function') throw new Error('call should be a function: ' + call); return function(){ var args = [].slice.apply(arguments) var argsCb = args.pop() if (typeof argsCb !== 'function') { args.push(argsCb) argsCb = null } return call.apply(null, args).then(function(result){ result = transform(result) if (argsCb) argsCb(null, result) return result }, function (err){ if (argsCb) argsCb(err) }) } } } // Unwrap .data in the response var nd = makeResponseTransformer(function(response){ return response.data; }); return { repos: { compareCommits: nd(qd(api.repos.compareCommits)), delete: nd(qd(api.repos.delete)), get: nd(qd(api.repos.get)), getAll: nd(qd(api.repos.getAll)), getBranches: nd(qd(api.repos.getBranches)) } } }
JavaScript
0
@@ -243,16 +243,44 @@ '3.0.0' +,%0A host: 'api.github.com' %0A %7D)%0A
601894e24d59c2784bfd746346e5fd9b4dd8350f
add back DELETE method context as POST support
src/helpers/fetch.js
src/helpers/fetch.js
import {isObject, isString, startsWith, endsWith} from './util'; import { encodeUriQuery, encodeUriSegment, replaceUrlParamFromUrl, replaceQueryStringParamFromUrl, splitUrlByProtocolAndDomain } from './url'; import {defaultGlobals, defaultHeaders, defaultIdKeys} from '../defaults'; export class HttpError extends Error { constructor(statusCode = 500, {body, message = 'HttpError'}) { super(message); this.name = this.constructor.name; this.message = message; if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } else { this.stack = new Error(message).stack; } // Http this.statusCode = statusCode; this.status = statusCode; this.body = body; } } export const buildFetchUrl = (context, {url, urlParams, stripTrailingSlashes = true}) => { const [protocolAndDomain = '', remainderUrl] = splitUrlByProtocolAndDomain(url); // Replace urlParams with values from context let builtUrl = Object.keys(urlParams).reduce((wipUrl, urlParam) => { const urlParamInfo = urlParams[urlParam]; const contextAsObject = !isObject(context) ? { [defaultIdKeys.singular]: context } : context; const value = contextAsObject[urlParam] || ''; // self.defaults[urlParam]; if (value) { const encodedValue = urlParamInfo.isQueryParamValue ? encodeUriQuery(value, true) : encodeUriSegment(value); return replaceUrlParamFromUrl(wipUrl, urlParam, encodedValue); } return replaceUrlParamFromUrl(wipUrl, urlParam); }, remainderUrl); // Strip trailing slashes and set the url (unless this behavior is specifically disabled) if (stripTrailingSlashes) { builtUrl = builtUrl.replace(/\/+$/, '') || '/'; } return protocolAndDomain + builtUrl; }; export const buildFetchOpts = (context, {method, headers, credentials, query, body}) => { const opts = { headers: defaultHeaders }; if (method) { opts.method = method; } if (headers) { opts.headers = { ...opts.headers, ...headers }; } if (credentials) { opts.credentials = credentials; } if (query) { opts.query = query; } const hasBody = /^(POST|PUT|PATCH)$/i.test(opts.method); if (body) { opts.body = isString(body) ? body : JSON.stringify(body); } else if (hasBody && context) { const contextAsObject = !isObject(context) ? { [defaultIdKeys.singular]: context } : context; opts.body = JSON.stringify(contextAsObject); } return opts; }; export const parseResponse = res => { const contentType = res.headers.get('Content-Type'); // @NOTE parses 'application/problem+json; charset=utf-8' for example // see https://tools.ietf.org/html/rfc6839 const isJson = contentType && (startsWith(contentType, 'application/json') || endsWith(contentType.split(';')[0], '+json')); return res[isJson ? 'json' : 'text'](); }; const fetch = (url, options = {}) => { // Support options.query const builtUrl = Object.keys(options.query || []).reduce((wipUrl, queryParam) => { const queryParamValue = isString(options.query[queryParam]) ? options.query[queryParam] : JSON.stringify(options.query[queryParam]); return replaceQueryStringParamFromUrl(wipUrl, queryParam, queryParamValue); }, url); return (options.Promise || defaultGlobals.Promise) .resolve((defaultGlobals.fetch || fetch)(builtUrl, options)) .then(res => { if (!res.ok) { return parseResponse(res).then(body => { throw new HttpError(res.status, { body }); }); } return res; }); }; export default fetch;
JavaScript
0.000002
@@ -2220,16 +2220,23 @@ UT%7CPATCH +%7CDELETE )$/i.tes
ac377996cd5b970d1765641fc13eabfe7558ca59
Change GroupStateModel to not be storable on the contact
go/base/static/js/src/apps/dialogue/models.js
go/base/static/js/src/apps/dialogue/models.js
// go.apps.dialogue.models // ======================= // Models for dialogue screen. (function(exports) { var Model = go.components.models.Model; var stateMachine = go.components.stateMachine, EndpointModel = stateMachine.EndpointModel, ConnectionModel = stateMachine.ConnectionModel, StateModel = stateMachine.StateModel; var contacts = go.contacts.models, GroupModel = contacts.GroupModel, GroupCollection = contacts.GroupCollection; var DialogueEndpointModel = EndpointModel.extend({ defaults: function() { return {uuid: uuid.v4()}; } }); var ChoiceEndpointModel = DialogueEndpointModel.extend({ defaults: {user_defined_value: false}, initialize: function() { this.on('change:label', function(m, v) { if (!this.get('user_defined_value')) { this.setValue(v); } }, this); }, setValue: function(v) { return this.set('value', go.utils.slugify(v)); } }); var DialogueStateModel = StateModel.extend({ storableOnContact: true, relations: [], subModelTypes: { dummy: 'go.apps.dialogue.models.DummyStateModel', choice: 'go.apps.dialogue.models.ChoiceStateModel', freetext: 'go.apps.dialogue.models.FreeTextStateModel', end: 'go.apps.dialogue.models.EndStateModel', group: 'go.apps.dialogue.models.GroupStateModel' }, defaults: function() { return { uuid: uuid.v4(), user_defined_store_as: false, store_on_contact: false, }; }, initialize: function() { this.on('change:name', function(m, v) { if (!this.get('user_defined_store_as')) { this.setStoreAs(v); } }, this); }, setStoreAs: function(v) { return this.set('store_as', go.utils.slugify(v)); } }); var DialogueStateModelCollection = Backbone.Collection.extend({ model: DialogueStateModel, comparator: function(state) { return state.get('ordinal'); } }); var DummyStateModel = DialogueStateModel.extend({ relations: [{ type: Backbone.HasOne, key: 'entry_endpoint', relatedModel: DialogueEndpointModel }, { type: Backbone.HasOne, key: 'exit_endpoint', relatedModel: DialogueEndpointModel }], defaults: function() { return _({ entry_endpoint: {}, exit_endpoint: {} }).defaults(DummyStateModel.__super__.defaults.call(this)); } }); var ChoiceStateModel = DialogueStateModel.extend({ relations: [{ type: Backbone.HasOne, key: 'entry_endpoint', relatedModel: DialogueEndpointModel }, { type: Backbone.HasMany, key: 'choice_endpoints', relatedModel: ChoiceEndpointModel }], defaults: function() { return _({ text: '', entry_endpoint: {} }).defaults(ChoiceStateModel.__super__.defaults.call(this)); } }); var FreeTextStateModel = DialogueStateModel.extend({ relations: [{ type: Backbone.HasOne, key: 'entry_endpoint', relatedModel: DialogueEndpointModel }, { type: Backbone.HasOne, key: 'exit_endpoint', relatedModel: DialogueEndpointModel }], defaults: function() { return _({ text: '', entry_endpoint: {}, exit_endpoint: {} }).defaults(FreeTextStateModel.__super__.defaults.call(this)); } }); var GroupStateModel = DialogueStateModel.extend({ relations: [{ type: Backbone.HasOne, key: 'entry_endpoint', relatedModel: DialogueEndpointModel }, { type: Backbone.HasOne, key: 'exit_endpoint', relatedModel: DialogueEndpointModel }], defaults: function() { return _({ group: null, entry_endpoint: {}, exit_endpoint: {} }).defaults(GroupStateModel.__super__.defaults.call(this)); } }); var EndStateModel = DialogueStateModel.extend({ storableOnContact: false, relations: [{ type: Backbone.HasOne, key: 'entry_endpoint', relatedModel: DialogueEndpointModel }], defaults: function() { return _({ text: '', entry_endpoint: {} }).defaults(EndStateModel.__super__.defaults.call(this)); } }); var DialogueConnectionModel = ConnectionModel.extend({ relations: [{ type: Backbone.HasOne, key: 'source', includeInJSON: ['uuid'], relatedModel: DialogueEndpointModel }, { type: Backbone.HasOne, key: 'target', includeInJSON: ['uuid'], relatedModel: DialogueEndpointModel }] }); var DialogueMetadataModel = Model.extend({ defaults: {repeatable: false} }); var DialogueModel = Model.extend({ methods: { read: { method: 'conversation.dialogue.get_poll', params: ['campaign_id', 'conversation_key'], parse: function(resp) { return resp.poll; } }, update: { method: 'conversation.dialogue.save_poll', params: function() { return [ this.get('campaign_id'), this.get('conversation_key'), {poll: this}]; } } }, idAttribute: 'conversation_key', relations: [{ type: Backbone.HasOne, key: 'urls', relatedModel: Model }, { type: Backbone.HasMany, key: 'groups', relatedModel: GroupModel, collectionType: GroupCollection }, { type: Backbone.HasOne, key: 'poll_metadata', relatedModel: DialogueMetadataModel }, { type: Backbone.HasMany, key: 'states', relatedModel: DialogueStateModel, collectionType: DialogueStateModelCollection }, { type: Backbone.HasOne, key: 'start_state', includeInJSON: ['uuid'], relatedModel: DialogueStateModel }, { type: Backbone.HasMany, key: 'connections', parse: true, relatedModel: DialogueConnectionModel }], defaults: { states: [], urls: {}, groups: [], connections: [], poll_metadata: {} } }); _(exports).extend({ DialogueModel: DialogueModel, DialogueConnectionModel: DialogueConnectionModel, DialogueEndpointModel: DialogueEndpointModel, ChoiceEndpointModel: ChoiceEndpointModel, DialogueStateModel: DialogueStateModel, DummyStateModel: DummyStateModel, ChoiceStateModel: ChoiceStateModel, FreeTextStateModel: FreeTextStateModel, EndStateModel: EndStateModel, GroupStateModel: GroupStateModel }); })(go.apps.dialogue.models = {});
JavaScript
0
@@ -3386,32 +3386,63 @@ eModel.extend(%7B%0A + storableOnContact: false,%0A%0A relations: %5B
18ca3a216ef05bc8647d1a25b7fae66ddd9ea104
Fix typos
packages/ratings/lib/ratings.js
packages/ratings/lib/ratings.js
Rating = {}; function K(rating) { return 32; } function Q(rating) { return Math.exp(rating / 400); } /** * Returns initial player rating. * @returns {number} */ Rating.initial = function () { return 500; }; /** * Calculate new ratings. * @param {number} blue - Rating of red player. * @param {number} red - Rating of red player. * @param {number} score - Score of blue player -- 1 for win, 0 for lose, 0.5 for draw. * @returns {{blue: number, red: number}} - Expected scores for players. */ Rating.calc = function (blue, red, score) { var expected = Rating.expected(blue, red); return { blue: blue + K(blue) * (score - expected.blue), red: red + K(red) * ((1 - score) - expected.red) } }; /** * Calculate expected scores for players. * @param {number} blue - Rating of red player. * @param {number} red - Rating of red player. * @returns {{blue: number, red: number}} - New ratings for players. */ Rating.expected = function (blue, red) { var qBlue = Q(blue); var qRed = Q(red); var denominator = qBlue + qRed; return { blue: qBlue / denominator, red: qRed / denominator } };
JavaScript
0.999999
@@ -271,35 +271,36 @@ lue - Rating of -red +blue player.%0A * @par @@ -475,22 +475,18 @@ %7D - -Expected score +New rating s fo @@ -787,35 +787,36 @@ lue - Rating of -red +blue player.%0A * @par @@ -895,34 +895,38 @@ number%7D%7D - -New rating +Expected score s for player
18f29494d789febec73100b6987747a01110184d
Validate URL
scholar.js
scholar.js
window.onload = initialize; var DATAFILE = "research.json"; var DONE_READYSTATE = 4; var DONE_STATUS = 200; var references = {}; function initialize() { validateHost(); loadExternalData(); } function validateHost() { if( window.location.hostname != "www.ecst.csuchico.edu" ) { window.location.href = "https://www.ecst.csuchico.edu/~kbuffardi/"; } } function loadExternalData() { var json = new XMLHttpRequest(); json.overrideMimeType("application/json"); //event listener: when json file load is "done" json.onreadystatechange = function() { if (this.readyState == DONE_READYSTATE && this.status == DONE_STATUS) { references=JSON.parse(this.responseText); console.log(references); } } json.open("GET", DATAFILE); json.send(); }
JavaScript
0.000026
@@ -101,16 +101,80 @@ S = 200; +%0Avar OFFICIAL_URL = %22https://www.ecst.csuchico.edu/~kbuffardi/%22; %0A%0Avar re @@ -377,51 +377,20 @@ f = -%22https://www.ecst.csuchico.edu/~kbuffardi/%22 +OFFICIAL_URL ;%0A
92b51edcfe1d1be3f7e5c5b0ce3b6bad51363edd
Remove model argument from View altogether
web/src/js/base/view.js
web/src/js/base/view.js
import domify from 'domify'; export default class View { constructor({app, model}) { this.app = app; this.model = model; } render() { const html = this.getHTML(); const element = domify(html); this.mount(element); return element; } renderInto(target) { target.innerHTML = this.getHTML(); const element = target.children[0]; this.mount(element); return element; } getHTML() { return '<div></div>'; } mount(element, sync=false) { this.element = element; } }
JavaScript
0
@@ -74,15 +74,8 @@ %7Bapp -, model %7D) %7B @@ -99,32 +99,8 @@ pp;%0A - this.model = model;%0A %7D%0A
4dda6bc2c80e02e7284c349abd96fff6d0809f9a
fix service to return values
packages/tyranid/src/service.js
packages/tyranid/src/service.js
import { handleException } from './express'; import { submitJob } from './job'; import Tyr from './tyr'; export function instrumentServerServices(col) { // col.def.service = service metadata // col.service = implementation of services const { def: cdef } = col; const { service } = cdef; if (service) { for (const methodName in service) { const method = service[methodName]; if (!method.route && method.client !== false) { method.route = `/api/${col.def.name}/${methodName}`; } col[methodName] = method.job ? (...args) => { submitJob( col, methodName, args, undefined // TODO: user ); } : (...args) => col.service[methodName].apply( { source: 'server', user: undefined, // TODO: figure out some way to pass in the user ? req: undefined, collection: col, }, args ); } } } export function instrumentExpressServices(col, app, auth) { const { service } = col.def; for (const methodName in service) { const method = service[methodName]; if (method.client === false) continue; const { params, return: returns, route } = method; app .route(route) .all(auth) .post(async (req, res) => { try { const { body } = req; const opts = { req }; const args = []; if (params) { let i = 0; for (const paramName in params) { const v = body[i++]; if (paramName === 'collectionId' && v) { // TODO: this is sort of a hack ... a parameter named "collectionId" has special meaning. // The need for this originated with TyrExport needing to take a FindOpts object that // had a query relative to the collection that was being *exported* NOT *TyrExport*. // There probably is a cleaner way to solve this... const collection = Tyr.byId[v]; if (!collection) throw new Tyr.AppError( `Export: Could not find a collection with ID "${v}` ); opts.collection = collection; } args.push(await params[paramName].fromClient(v, opts)); } } const result = await col.service[methodName].apply( { source: 'client', auth: req.user, user: req.user, req, res, collection: col, }, args ); if (returns) { res.json(returns.toClient(result)); } else { res.sendStatus(200); } } catch (err) { handleException(res, err); } }); } } export const serviceClientCode = () => ` for (const col of Tyr.collections) { const { def: cdef } = col; const { service } = cdef; if (service) { for (const methodName in service) { const method = service[methodName]; col[methodName] = function() { return Tyr.fetch(method.route, { method: 'POST', body: JSON.stringify(arguments), headers: { 'Content-Type': 'application/json' } }).then(result => { // res.json('string') seems to return a {'message':'string'} ??? if (method.return?.type.name === 'string' && result.message) { return result.message; } // TODO: iterate through data and wrap results ? return result; }); }; } } } `;
JavaScript
0.000005
@@ -2791,24 +2791,31 @@ +return res.json(ret @@ -2853,15 +2853,9 @@ %7D - else %7B +%0A %0A @@ -2857,25 +2857,30 @@ %0A%0A - +return res.sendSta @@ -2889,28 +2889,16 @@ s(200);%0A - %7D%0A
0fce1f86b4d8efcdb422ad1a9ce98203912e5601
Clean -> CleanPlugin
webpack.config.babel.js
webpack.config.babel.js
import * as path from 'path'; import webpack from 'webpack'; import HtmlWebpackPlugin from 'html-webpack-plugin'; import ExtractTextPlugin from 'extract-text-webpack-plugin'; import SystemBellPlugin from 'system-bell-webpack-plugin'; import Clean from 'clean-webpack-plugin'; import merge from 'webpack-merge'; import React from 'react'; import ReactDOM from 'react-dom/server'; import renderJSX from './lib/render.jsx'; import App from './demo/App.jsx'; import pkg from './package.json'; const RENDER_UNIVERSAL = true; const TARGET = process.env.npm_lifecycle_event; const ROOT_PATH = __dirname; const config = { paths: { dist: path.join(ROOT_PATH, 'dist'), src: path.join(ROOT_PATH, 'src'), demo: path.join(ROOT_PATH, 'demo'), tests: path.join(ROOT_PATH, 'tests') }, filename: 'boilerplate', library: 'Boilerplate' }; const CSS_PATHS = [ config.paths.demo, path.join(ROOT_PATH, 'style.css'), path.join(ROOT_PATH, 'node_modules/purecss'), path.join(ROOT_PATH, 'node_modules/highlight.js/styles/github.css'), path.join(ROOT_PATH, 'node_modules/react-ghfork/gh-fork-ribbon.ie.css'), path.join(ROOT_PATH, 'node_modules/react-ghfork/gh-fork-ribbon.css') ]; const STYLE_ENTRIES = [ 'purecss', 'highlight.js/styles/github.css', 'react-ghfork/gh-fork-ribbon.ie.css', 'react-ghfork/gh-fork-ribbon.css', './demo/main.css', './style.css' ]; process.env.BABEL_ENV = TARGET; const demoCommon = { resolve: { extensions: ['', '.js', '.jsx', '.css', '.png', '.jpg'] }, module: { preLoaders: [ { test: /\.jsx?$/, loaders: ['eslint'], include: [ config.paths.demo, config.paths.src ] } ], loaders: [ { test: /\.png$/, loader: 'url?limit=100000&mimetype=image/png', include: config.paths.demo }, { test: /\.jpg$/, loader: 'file', include: config.paths.demo }, { test: /\.json$/, loader: 'json', include: path.join(ROOT_PATH, 'package.json') } ] }, plugins: [ new SystemBellPlugin() ] }; if (TARGET === 'start') { module.exports = merge(demoCommon, { devtool: 'eval-source-map', entry: { demo: [config.paths.demo].concat(STYLE_ENTRIES) }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"development"' }), new HtmlWebpackPlugin(Object.assign({}, { title: pkg.name + ' - ' + pkg.description, template: 'lib/index_template.ejs', inject: false }, renderJSX(__dirname, pkg))), new webpack.HotModuleReplacementPlugin() ], module: { loaders: [ { test: /\.css$/, loaders: ['style', 'css'], include: CSS_PATHS }, { test: /\.jsx?$/, loaders: ['babel?cacheDirectory'], include: [ config.paths.demo, config.paths.src ] } ] }, devServer: { historyApiFallback: true, hot: true, inline: true, progress: true, host: process.env.HOST, port: process.env.PORT, stats: 'errors-only' } }); } function NamedModulesPlugin(options) { this.options = options || {}; } NamedModulesPlugin.prototype.apply = function(compiler) { compiler.plugin('compilation', function(compilation) { compilation.plugin('before-module-ids', function(modules) { modules.forEach(function(module) { if(module.id === null && module.libIdent) { var id = module.libIdent({ context: this.options.context || compiler.options.context }); // Skip CSS files since those go through ExtractTextPlugin if(!id.endsWith('.css')) { module.id = id; } } }, this); }.bind(this)); }.bind(this)); }; if (TARGET === 'gh-pages' || TARGET === 'gh-pages:stats') { module.exports = merge(demoCommon, { entry: { app: config.paths.demo, vendors: [ 'react' ], style: STYLE_ENTRIES }, output: { path: './gh-pages', filename: '[name].[chunkhash].js', chunkFilename: '[chunkhash].js' }, plugins: [ new Clean(['gh-pages'], { verbose: false }), new ExtractTextPlugin('[name].[chunkhash].css'), new webpack.DefinePlugin({ // This affects the react lib size 'process.env.NODE_ENV': '"production"' }), new HtmlWebpackPlugin(Object.assign({}, { title: pkg.name + ' - ' + pkg.description, template: 'lib/index_template.ejs', inject: false }, renderJSX( __dirname, pkg, RENDER_UNIVERSAL ? ReactDOM.renderToString(<App />) : '') )), new NamedModulesPlugin(), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new webpack.optimize.CommonsChunkPlugin({ names: ['vendors', 'manifest'] }) ], module: { loaders: [ { test: /\.css$/, loader: ExtractTextPlugin.extract('style', 'css'), include: CSS_PATHS }, { test: /\.jsx?$/, loaders: ['babel'], include: [ config.paths.demo, config.paths.src ] } ] } }); } // !TARGET === prepush hook for test if (TARGET === 'test' || TARGET === 'test:tdd' || !TARGET) { module.exports = merge(demoCommon, { module: { preLoaders: [ { test: /\.jsx?$/, loaders: ['eslint'], include: [ config.paths.tests ] } ], loaders: [ { test: /\.jsx?$/, loaders: ['babel?cacheDirectory'], include: [ config.paths.src, config.paths.tests ] } ] } }) } const distCommon = { devtool: 'source-map', output: { path: config.paths.dist, libraryTarget: 'umd', library: config.library }, entry: config.paths.src, externals: { 'react': { commonjs: 'react', commonjs2: 'react', amd: 'React', root: 'React' } }, module: { loaders: [ { test: /\.jsx?$/, loaders: ['babel'], include: config.paths.src } ] }, plugins: [ new SystemBellPlugin() ] }; if (TARGET === 'dist') { module.exports = merge(distCommon, { output: { filename: config.filename + '.js' } }); } if (TARGET === 'dist:min') { module.exports = merge(distCommon, { output: { filename: config.filename + '.min.js' }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ] }); }
JavaScript
0
@@ -240,16 +240,22 @@ rt Clean +Plugin from 'c @@ -4273,16 +4273,22 @@ ew Clean +Plugin (%5B'gh-pa
9b1a6eaee0f58016b1c820f383ac76197af0ea03
Move html generation into start script
webpack.config.babel.js
webpack.config.babel.js
import * as path from 'path'; import webpack from 'webpack'; import HtmlWebpackPlugin from 'html-webpack-plugin'; import ExtractTextPlugin from 'extract-text-webpack-plugin'; import SystemBellPlugin from 'system-bell-webpack-plugin'; import CleanWebpackPlugin from 'clean-webpack-plugin'; import merge from 'webpack-merge'; import pkg from './package.json'; const TARGET = process.env.npm_lifecycle_event || ''; const ROOT_PATH = __dirname; const config = { paths: { dist: path.join(ROOT_PATH, 'dist'), src: path.join(ROOT_PATH, 'src'), demo: path.join(ROOT_PATH, 'demo'), }, filename: 'AdminLTE', library: 'React-AdminLTE', }; const extractCSS = new ExtractTextPlugin('bundle.css'); process.env.BABEL_ENV = TARGET; const common = { resolve: { extensions: ['', '.js', '.jsx', '.css', '.png', '.jpg'], }, module: { preLoaders: [ { test: /\.jsx?$/, loaders: ['eslint'], include: [ config.paths.demo, config.paths.src, ], }, ], loaders: [ { test: /\.png$/, loader: 'url?limit=100000&mimetype=image/png', }, { test: /\.jpg$/, loader: 'file', }, { test: /\.json$/, loader: 'json', }, { test: /\.(ttf|eot|svg|gif)(\?[\s\S]+)?$/, loader: 'file', }, { test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff', }, { test: /\.md$/, loader: 'raw', }, ], }, plugins: [ new SystemBellPlugin(), ], }; const siteCommon = { plugins: [ new HtmlWebpackPlugin({ template: require('html-webpack-template'), // eslint-disable-line global-require inject: false, mobile: true, title: pkg.name, appMountId: 'app', }), new webpack.DefinePlugin({ NAME: JSON.stringify(pkg.name), USER: JSON.stringify(pkg.user), VERSION: JSON.stringify(pkg.version), }), ], }; if (TARGET === 'start') { module.exports = merge(common, siteCommon, { devtool: 'eval-source-map', entry: { demo: config.paths.demo, }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"development"', }), new webpack.HotModuleReplacementPlugin(), ], module: { loaders: [ { test: /\.css$/, loaders: ['style', 'css'], }, { test: /\.jsx?$/, loaders: ['babel?cacheDirectory'], include: [ config.paths.demo, config.paths.src, ], }, ], }, devServer: { historyApiFallback: true, hot: true, inline: true, progress: true, host: process.env.HOST, port: process.env.PORT, stats: 'errors-only', }, }); } if (TARGET === 'gh-pages' || TARGET === 'gh-pages:stats') { module.exports = merge(common, siteCommon, { entry: { app: config.paths.demo, vendors: [ 'react', 'react-dom', ], }, output: { path: './gh-pages', filename: '[name].[chunkhash].js', chunkFilename: '[chunkhash].js', }, plugins: [ new CleanWebpackPlugin(['gh-pages'], { verbose: false, }), extractCSS, new HtmlWebpackPlugin({ template: 'lib/index_template.ejs', filename: 'index.html', // Context for the template title: pkg.name, description: pkg.description, }), new HtmlWebpackPlugin({ template: 'lib/404_template.ejs', filename: '404.html', inject: false, // Context for the template title: pkg.name, remote: true, }), new webpack.DefinePlugin({ // This affects the react lib size 'process.env.NODE_ENV': '"production"', }), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, }, }), new webpack.optimize.CommonsChunkPlugin( 'vendor', '[name].[chunkhash].js', ), ], module: { loaders: [ { test: /\.css$/, loader: extractCSS.extract('style', 'css?sourceMap'), }, { test: /\.jsx?$/, loaders: ['babel'], include: [ config.paths.demo, config.paths.src, ], }, ], }, }); } const distCommon = { devtool: 'source-map', resolve: { extensions: ['', '.js', '.jsx'], }, output: { path: config.paths.dist, libraryTarget: 'umd', library: config.library, }, entry: { app: config.paths.src, vendors: [ 'react', ], }, externals: { react: { commonjs: 'react', commonjs2: 'react', amd: 'React', root: 'React', }, }, module: { loaders: [ { test: /\.jsx?$/, loaders: ['babel'], include: config.paths.src, }, ], }, plugins: [ new SystemBellPlugin(), ], }; if (TARGET === 'dist') { module.exports = merge(distCommon, { output: { filename: `${config.filename}.js`, }, }); } if (TARGET === 'dist:min') { module.exports = merge(distCommon, { output: { filename: `${config.filename}.min.js`, }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, }, }), ], }); } if (!TARGET) { module.exports = common; }
JavaScript
0.000002
@@ -1664,221 +1664,8 @@ : %5B%0A - new HtmlWebpackPlugin(%7B%0A template: require('html-webpack-template'), // eslint-disable-line global-require%0A inject: false,%0A mobile: true,%0A title: pkg.name,%0A appMountId: 'app',%0A %7D),%0A @@ -1991,32 +1991,259 @@ %0A plugins: %5B%0A + new HtmlWebpackPlugin(%7B%0A template: require('html-webpack-template'), // eslint-disable-line global-require%0A inject: false,%0A mobile: true,%0A title: pkg.name,%0A appMountId: 'app',%0A %7D),%0A new webpac
e7fb1622ee3ec1bb4fa068d741c493b9a827c9d2
Fix bug that delete key still works when dialog is showing
src/js/keyHandler.js
src/js/keyHandler.js
/* * Rapid Interface Builder (RIB) - A simple WYSIWYG HTML5 app creator * Copyright (c) 2011, Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 * */ "use strict"; /** * Global object for key handler. * */ $(function() { var navUtils = { enableKeys: function (element) { $(element).keyup(navUtils.shortCut); $(element).keydown(navUtils.tabHandler); $(element).keyup(navUtils.deleteHandler); }, shortCut: function(e) { var charItem, shortKeys; shortKeys = { // "ctrl+z" for "undo" 'z': 'undo', // "ctrl+y" for "redo" 'y':'redo', // "ctrl+x" for "cut" 'x':'cut', // "ctrl+c" for "copy" 'c':'copy', // "ctrl+v" for "past" 'v':'paste' }; if (e.ctrlKey && !navUtils.ignoreText()) { charItem = String.fromCharCode(e.which).toLowerCase(); if (shortKeys[charItem]) { $('#btn' + shortKeys[charItem] + ':visible').trigger("click"); return false; } } return true; }, // for "tab" tabHandler: function (e) { var navItems = navUtils.enableFocus(); if (e.which !== 9) { return true; } if (navItems.last().is(":focus")) { if (!e.shiftKey) { e.preventDefault(); navItems.first().focus(); return false; } } else if (navItems.first().is(":focus")) { if (e.shiftKey) { e.preventDefault(); navItems.last().focus(); return false; } } }, // for "delete" deleteHandler: function (e) { if (e.which !== 46 || navUtils.ignoreText()) { return true; } else { $('#deleteElement:visible').trigger("click"); return false; } }, /** * Enable items that wants to be focused by tab key. * * This is hard-coding, if all the views or elements can mark themself if it want key navigation, * such as add a class "navItem" to the elements, case will be better. */ enableFocus: function () { var navItems, items, navPanes; navPanes = ['.navbar', '.pageView', '.propertyView', ".tools"]; items = "a, button, input, select, textarea, area"; navPanes.forEach(function (pane, index) { navItems = $(navItems).add($(":visible", pane).find(items)); }); navItems = $(navItems).add($(".treeView:visible")); navItems = $(navItems).add($(".pageIcon:visible")); navItems.attr("tabindex", 1); return navItems; }, ignoreText: function () { var i = Boolean($('input[type="text"]:focus, textarea:focus', '.property_content').length), f = Boolean($('.adm-editing:focus',$(':rib-layoutView') .layoutView('option','contentDocument')).length); return i||f; } }; /******************* export pageUtils to $.rib **********************/ $.rib = $.rib || {}; $.rib.enableKeys = navUtils.enableKeys; });
JavaScript
0
@@ -548,62 +548,8 @@ r);%0A - $(element).keyup(navUtils.deleteHandler);%0A @@ -547,32 +547,32 @@ er);%0A %7D,%0A + shortCut @@ -1015,47 +1015,456 @@ -if (e.ctrlKey && !navUtils.ignoreText() +// If there is modal dialog or need to ignore text elements, do nothing.%0A if ($('.ui-widget-overlay:visible').length %3E 0 %7C%7C navUtils.ignoreText()) %7B%0A return true;%0A %7D%0A // for %22delete%22%0A // fn + delete in Mac to delete element%0A if (e.which === 46) %7B%0A $('#deleteElement:visible').trigger(%22click%22);%0A return false;%0A %7D%0A if (e.ctrlKey ) %7B%0A @@ -1810,32 +1810,136 @@ function (e) %7B%0A + if ($('.ui-wiget-overlay:visible').length %3E 0) %7B%0A return true;%0A %7D%0A var @@ -2471,32 +2471,32 @@ return false;%0A + @@ -2526,296 +2526,8 @@ %7D,%0A - // for %22delete%22%0A deleteHandler: function (e) %7B%0A if (e.which !== 46 %7C%7C navUtils.ignoreText()) %7B%0A return true;%0A %7D else %7B%0A $('#deleteElement:visible').trigger(%22click%22);%0A return false;%0A %7D%0A %7D,%0A
7bcdad4a64c8289b7cc750fca42b83e308536c2f
Correct App
src/js/mainAssist.js
src/js/mainAssist.js
import {run} from '@cycle/core' import drivers from './drivers/drivers.js' import addGlobalErrorHandler from './utilities/globalError' import runHot from './utilities/runHot' import AssistApp from './components/AssistApp' const PRODUCTION = (process.env.NODE_ENV === 'production') // note while this is usefull it breaks the source mapping in console error messages if (!PRODUCTION) { // addGlobalErrorHandler() } if (!PRODUCTION && module.hot && false) { // hot loading enabled in config console.log('Hot reloading enabled') runHot('./components/App', AssistApp, drivers) } else { run(App, drivers) }
JavaScript
0.000064
@@ -592,16 +592,22 @@ %7B%0A run( +Assist App, dri @@ -610,13 +610,12 @@ drivers)%0A%7D%0A -%0A
b071eabe4b2942544d773767c9574f0128090334
disable shortcuts if inspector closed
src/lib/shortcuts.js
src/lib/shortcuts.js
/* globals AFRAME */ var Events = require('./Events'); import { removeSelectedEntity, cloneSelectedEntity, cloneEntity } from '../lib/entity'; import { os } from '../lib/utils.js'; function shouldCaptureKeyEvent(event) { if (event.metaKey) { return false; } return ( event.target.closest('#cameraToolbar') || (event.target.tagName !== 'INPUT' && event.target.tagName !== 'TEXTAREA') ); } var Shortcuts = { enabled: false, shortcuts: { default: {}, modules: {} }, onKeyUp: function(event) { if (!shouldCaptureKeyEvent(event)) { return; } var keyCode = event.keyCode; // h: help if (keyCode === 72) { Events.emit('openhelpmodal'); } // esc: close inspector if (keyCode === 27) { if (this.inspector.selectedEntity) { this.inspector.selectEntity(null); } } // w: translate if (keyCode === 87) { Events.emit('transformmodechange', 'translate'); } // e: rotate if (keyCode === 69) { Events.emit('transformmodechange', 'rotate'); } // r: scale if (keyCode === 82) { Events.emit('transformmodechange', 'scale'); } // o: transform space if (keyCode === 79) { Events.emit('transformspacechange'); } // g: toggle grid if (keyCode === 71) { Events.emit('togglegrid'); } // m: motion capture if (keyCode === 77) { Events.emit('togglemotioncapture'); } // n: new entity if (keyCode === 78) { Events.emit('entitycreate', { element: 'a-entity', components: {} }); } // backspace & supr: remove selected entity if (keyCode === 8 || keyCode === 46) { removeSelectedEntity(); } // d: clone selected entity if (keyCode === 68) { cloneSelectedEntity(); } // f: Focus on selected entity. if (keyCode === 70) { const selectedEntity = AFRAME.INSPECTOR.selectedEntity; if (selectedEntity !== undefined && selectedEntity !== null) { Events.emit('objectfocus', selectedEntity.object3D); } } if (keyCode === 49) { Events.emit('cameraperspectivetoggle'); } else if (keyCode === 50) { Events.emit('cameraorthographictoggle', 'left'); } else if (keyCode === 51) { Events.emit('cameraorthographictoggle', 'right'); } else if (keyCode === 52) { Events.emit('cameraorthographictoggle', 'top'); } else if (keyCode === 53) { Events.emit('cameraorthographictoggle', 'bottom'); } else if (keyCode === 54) { Events.emit('cameraorthographictoggle', 'back'); } else if (keyCode === 55) { Events.emit('cameraorthographictoggle', 'front'); } for (var moduleName in this.shortcuts.modules) { var shortcutsModule = this.shortcuts.modules[moduleName]; if ( shortcutsModule[keyCode] && (!shortcutsModule[keyCode].mustBeActive || (shortcutsModule[keyCode].mustBeActive && AFRAME.INSPECTOR.modules[moduleName].active)) ) { this.shortcuts.modules[moduleName][keyCode].callback(); } } }, onKeyDown: function(event) { if (!shouldCaptureKeyEvent(event)) { return; } if ( (event.ctrlKey && os === 'windows') || (event.metaKey && os === 'macos') ) { if ( AFRAME.INSPECTOR.selectedEntity && document.activeElement.tagName !== 'INPUT' ) { // x: cut selected entity if (event.keyCode === 88) { AFRAME.INSPECTOR.entityToCopy = AFRAME.INSPECTOR.selectedEntity; removeSelectedEntity(true); } // c: copy selected entity if (event.keyCode === 67) { AFRAME.INSPECTOR.entityToCopy = AFRAME.INSPECTOR.selectedEntity; } // v: paste copied entity if (event.keyCode === 86) { cloneEntity(AFRAME.INSPECTOR.entityToCopy); } } // s: focus search input if (event.keyCode === 83) { event.preventDefault(); event.stopPropagation(); document.getElementById('filter').focus(); } } // º: toggle sidebars visibility if (event.keyCode === 48) { Events.emit('togglesidebar', { which: 'all' }); event.preventDefault(); event.stopPropagation(); } }, enable: function() { if (this.enabled) { this.disable(); } window.addEventListener('keydown', this.onKeyDown.bind(this), false); window.addEventListener('keyup', this.onKeyUp.bind(this), false); this.enabled = true; }, disable: function() { window.removeEventListener('keydown', this.onKeyDown); window.removeEventListener('keyup', this.onKeyUp); this.enabled = false; }, checkModuleShortcutCollision: function(keyCode, moduleName, mustBeActive) { if ( this.shortcuts.modules[moduleName] && this.shortcuts.modules[moduleName][keyCode] ) { console.warn( 'Keycode <%s> already registered as shorcut within the same module', keyCode ); } }, registerModuleShortcut: function( keyCode, callback, moduleName, mustBeActive ) { if (this.checkModuleShortcutCollision(keyCode, moduleName, mustBeActive)) { return; } if (!this.shortcuts.modules[moduleName]) { this.shortcuts.modules[moduleName] = {}; } if (mustBeActive !== false) { mustBeActive = true; } this.shortcuts.modules[moduleName][keyCode] = { callback, mustBeActive }; }, init: function(inspector) { this.inspector = inspector; this.onKeyDown = this.onKeyDown.bind(this); this.onKeyUp = this.onKeyUp.bind(this); } }; module.exports = Shortcuts;
JavaScript
0.000002
@@ -556,32 +556,60 @@ eKeyEvent(event) + %7C%7C !AFRAME.INSPECTOR.opened ) %7B%0A return @@ -3207,16 +3207,44 @@ t(event) + %7C%7C !AFRAME.INSPECTOR.opened ) %7B%0A
bbf26a3f382529a7e81b2c9ca7993934d37f9877
Update fontstacks URL according to https://github.com/klokantech/tileserver-gl/pull/104#issuecomment-274444087
src/libs/metadata.js
src/libs/metadata.js
import request from 'request' function loadJSON(url, defaultValue, cb) { request({ url: url, withCredentials: false, }, (error, response, body) => { if (!error && body && response.statusCode == 200) { try { cb(JSON.parse(body)) } catch(err) { console.error(err) cb(defaultValue) } } else { console.warn('Can not metadata for ' + url) cb(defaultValue) } }) } export function downloadGlyphsMetadata(urlTemplate, cb) { if(!urlTemplate) return cb([]) // Special handling because Tileserver GL serves the fontstacks metadata differently // https://github.com/klokantech/tileserver-gl/pull/104 let url = urlTemplate.replace('/fonts/{fontstack}/{range}.pbf', '/fontstacks.json') url = url.replace('{fontstack}/{range}.pbf', 'fontstacks.json') loadJSON(url, [], cb) } export function downloadSpriteMetadata(baseUrl, cb) { if(!baseUrl) return cb([]) const url = baseUrl + '.json' loadJSON(url, {}, glyphs => cb(Object.keys(glyphs))) }
JavaScript
0
@@ -22,16 +22,41 @@ request' +%0Aimport npmurl from 'url' %0A%0Afuncti @@ -698,50 +698,102 @@ /104 -%0A let url = urlTemplate.replace('/fonts/%7B +#issuecomment-274444087%0A let urlObj = npmurl.parse(urlTemplate);%0A const normPathPart = '/%257B font @@ -801,109 +801,232 @@ tack -%7D/%7B +%257D/%257B range -%7D +%257D .pbf' -, '/fontstacks.json')%0A url = url.replace('%7Bfontstack%7D/%7Brange%7D.pbf', 'fontstacks.json') +;%0A if(urlObj.pathname === normPathPart) %7B%0A urlObj.pathname = '/fontstacks.json';%0A %7D else %7B%0A urlObj.pathname = urlObj.pathname.replace(normPathPart, '.json');%0A %7D%0A let url = npmurl.format(urlObj); %0A%0A
9028f49d7608ef3c488b69482b0ec1ad8aa9c399
make attach chainable when using livequery
src/lowpro.jquery.js
src/lowpro.jquery.js
(function($) { var addMethods = function(source) { var ancestor = this.superclass && this.superclass.prototype; var properties = $.keys(source); if (!$.keys({ toString: true }).length) properties.push("toString", "valueOf"); for (var i = 0, length = properties.length; i < length; i++) { var property = properties[i], value = source[property]; if (ancestor && $.isFunction(value) && $.argumentNames(value)[0] == "$super") { var method = value, value = $.extend($.wrap((function(m) { return function() { return ancestor[m].apply(this, arguments) }; })(property), method), { valueOf: function() { return method }, toString: function() { return method.toString() } }); } this.prototype[property] = value; } return this; } $.extend({ keys: function(obj) { var keys = []; for (var key in obj) keys.push(key); return keys; }, argumentNames: function(func) { var names = func.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(/, ?/); return names.length == 1 && !names[0] ? [] : names; }, bind: function(func, scope) { return function() { return func.apply(scope, $.makeArray(arguments)); } }, wrap: function(func, wrapper) { var __method = func; return function() { return wrapper.apply(this, [$.bind(__method, this)].concat($.makeArray(arguments))); } }, klass: function() { var parent = null, properties = $.makeArray(arguments); if ($.isFunction(properties[0])) parent = properties.shift(); var klass = function() { this.initialize.apply(this, arguments); }; klass.superclass = parent; klass.subclasses = []; klass.addMethods = addMethods; if (parent) { var subclass = function() { }; subclass.prototype = parent.prototype; klass.prototype = new subclass; parent.subclasses.push(klass); } for (var i = 0; i < properties.length; i++) klass.addMethods(properties[i]); if (!klass.prototype.initialize) klass.prototype.initialize = function() {}; klass.prototype.constructor = klass; return klass; } }); var bindEvents = function(instance) { for (var member in instance) { if (member.match(/^on(.+)/) && typeof instance[member] == 'function') { instance.element.bind(RegExp.$1, $.bind(instance[member], instance)); } } } var behaviorWrapper = function(behavior) { return $.klass(behavior, { initialize: function($super, element, args) { this.element = $(element); if ($super) $super.apply(this, args); } }); } var attachBehavior = function(el, behavior, args) { var wrapper = behaviorWrapper(behavior); instance = new wrapper(el, args); bindEvents(instance); if (!behavior.instances) behavior.instances = []; behavior.instances.push(instance); return instance; }; $.fn.extend({ attach: function() { var args = $.makeArray(arguments), behavior = args.shift(); if ($.livequery && this.selector) { this.livequery(function() { attachBehavior(this, behavior, args); }) } else { return this.each(function() { attachBehavior(this, behavior, args); }); } }, attachAndReturn: function() { var args = $.makeArray(arguments), behavior = args.shift(); return $.map(this, function(el) { return attachBehavior(el, behavior, args); }); } }); Remote = $.klass({ initialize: function(options) { if (this.element.attr('nodeName') == 'FORM') this.element.attach(Remote.Form, options); else this.element.attach(Remote.Link, options); } }); Remote.Base = $.klass({ initialize : function(options) { this.options = $.extend({ }, options || {}); }, _makeRequest : function(options) { $.ajax(options); return false; } }); Remote.Link = $.klass(Remote.Base, { onclick: function() { var options = $.extend({ url: this.element.attr('href'), type: 'GET' }, this.options); return this._makeRequest(options); } }); Remote.Form = $.klass(Remote.Base, { onclick: function(e) { var target = e.target; if ($.inArray(target.nodeName.toLowerCase(), ['input', 'button']) >= 0 && target.type.match(/submit|image/)) this._submitButton = target; }, onsubmit: function() { var data = this.element.serializeArray(); if (this._submitButton) data.push({ name: this._submitButton.name, value: this._submitButton.value }); var options = $.extend({ url : this.element.attr('action'), type : this.element.attr('method') || 'GET', data : data }, this.options); this._makeRequest(options); return false; } }); $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader("Accept", "text/javascript, text/html, application/xml, text/xml, */*"); } }); })(jQuery);
JavaScript
0
@@ -3254,24 +3254,31 @@ ) %7B%0A +return this.liveque @@ -3351,16 +3351,17 @@ %7D) +; %0A %7D
6ca3efecd2d57bb1019495eb612a9e10efd14768
add comment
src/main/gulpfile.js
src/main/gulpfile.js
var gulp = require("gulp"); var print = require("gulp-print"); var console = require("console"); var server = require("browser-sync").create("sabbat.notes static server"); var glob = require('glob'); var srcDirsUi = ['sabbat.notes.ui/**/*.html', 'sabbat.notes.ui/**/*.css', 'sabbat.notes.ui/**/*.js']; gulp.task('reload', function () { gulp.src(srcDirsUi) .pipe(print()) .pipe(server.stream({once:true})); /*.pipe(server.notify('Hello this is a notification'));*/ }); gulp.task('notify', function() { server.notify('test notification'); }) gulp.task('typescript', function() { console.info("compile changes"); }); gulp.task('watch', function() { gulp.watch(srcDirsUi, ['reload']); }); gulp.task('serve', function() { console.info('serve started...') //server.getSingletonEmitter().on("init", function() { // console.info("Servicer initialized"); //}); server.init( { port: 8000, server: { baseDir: "./sabbat.notes.ui", index: "index.html" }, // Change the default weinre port ui: { port: 8001, weinre: { port: 8002 } } }); }); gulp.task('default', ['serve', 'watch']);
JavaScript
0
@@ -1,12 +1,26 @@ +// gulp file%0A%0A var gulp = r
1d276e06bce5981e98629530adc193b832c97015
remove attribute disabled
widget/loader/loader.js
widget/loader/loader.js
Editor.registerWidget( 'editor-loader', { is: 'editor-loader', properties: { text: { type: String, notify: true, value: '', } }, ready: function () { this.stopUpdate = false; this.originPosition = ''; this.node = null; }, initLoader: function (node) { this.disabled = false; this.stopUpdate = false; this.node = node; this.node.style.pointerEvents = 'none'; this.stopLoading = false; this.originPosition = window.getComputedStyle(node)['position']; if (this.originPosition !== 'absolute') { this.node.style.position = 'relative'; } this.style.background = 'rgba(0,0,0,.5)'; this.style.position = 'absolute'; this.style.left = 0; this.style.top = 0; this.style.right = 0; this.style.bottom = 0; this.$.animate.style.position = 'absolute'; this.$.animate.style.left = '50%'; this.$.animate.style.marginLeft = -this.$.animate.getBoundingClientRect().width / 2 - 5; this.$.animate.style.marginTop = this.getBoundingClientRect().height / 2 - this.$.animate.getBoundingClientRect().height / 2; node.appendChild(this); this._update(); }, _update: function () { window.requestAnimationFrame(function () { if (this.stopUpdate) { return; } this.$.animate.style.marginTop = this.getBoundingClientRect().height / 2 - this.$.animate.getBoundingClientRect().height / 2; this._update(); }.bind(this)); }, clear: function () { this.stopUpdate = true; this.node.style.pointerEvents = 'auto'; this.node.style.position = this.originPosition; this.disabled = true; this.remove(); }, });
JavaScript
0.000001
@@ -352,39 +352,8 @@ ) %7B%0A - this.disabled = false;%0A @@ -1788,38 +1788,8 @@ on;%0A - this.disabled = true;%0A
e16a7bfd6456b49910fc8c4728fc0a9dcf1a8c57
fix text field: fix dependency injection
modules/text-field/js/text-field_directive.js
modules/text-field/js/text-field_directive.js
(function() { 'use strict'; angular .module('lumx.text-field') .directive('lxTextField', lxTextField); LxTextFieldController.$inject = ['$timeout']; function lxTextField($timeout) { return { restrict: 'E', templateUrl: 'text-field.html', scope: { allowClear: '=?lxAllowClear', error: '=?lxError', fixedLabel: '=?lxFixedLabel', icon: '@?lxIcon', label: '@lxLabel', ngDisabled: '=?', theme: '@?lxTheme', valid: '=?lxValid' }, link: link, controller: LxTextFieldController, controllerAs: 'lxTextField', bindToController: true, replace: true, transclude: true }; function link(scope, element, attrs, ctrl, transclude) { var backwardOneWay = ['icon', 'label', 'theme']; var backwardTwoWay = ['error', 'fixedLabel', 'valid']; angular.forEach(backwardOneWay, function(attribute) { if (angular.isDefined(attrs[attribute])) { attrs.$observe(attribute, function(newValue) { scope.lxTextField[attribute] = newValue; }); } }); angular.forEach(backwardTwoWay, function(attribute) { if (angular.isDefined(attrs[attribute])) { scope.$watch(function() { return scope.$parent.$eval(attrs[attribute]); }, function(newValue) { scope.lxTextField[attribute] = newValue; }); } }); transclude(function() { var input = element.find('textarea'); if (input[0]) { input.bind('cut paste drop keydown', function() { $timeout(ctrl.updateTextareaHeight); }); } else { input = element.find('input'); } input.addClass('text-field__input'); ctrl.setInput(input); ctrl.setModel(input.data('$ngModelController')); input.bind('focus', ctrl.focusInput); input.bind('blur', ctrl.blurInput); }); } } LxTextFieldController.$inject = ['$scope', '$timeout']; function LxTextFieldController($scope, $timeout) { var lxTextField = this; var input; var modelController; lxTextField.blurInput = blurInput; lxTextField.clearInput = clearInput; lxTextField.focusInput = focusInput; lxTextField.hasValue = hasValue; lxTextField.setInput = setInput; lxTextField.setModel = setModel; lxTextField.updateTextareaHeight = updateTextareaHeight; $scope.$watch(function() { return modelController.$viewValue; }, function(newValue, oldValue) { if (angular.isDefined(newValue) && newValue) { lxTextField.isActive = true; } else { lxTextField.isActive = false; } }); //////////// function blurInput() { if (!hasValue()) { $scope.$apply(function() { lxTextField.isActive = false; }); } $scope.$apply(function() { lxTextField.isFocus = false; }); } function clearInput() { modelController.$setViewValue(undefined); modelController.$render(); $timeout(function() { input.focus(); }); } function focusInput() { $scope.$apply(function() { lxTextField.isActive = true; lxTextField.isFocus = true; }); } function hasValue() { return input.val(); } function init() { lxTextField.isActive = hasValue(); lxTextField.isFocus = false; } function setInput(_input) { input = _input; $timeout(init); if (input.selector === 'textarea') { $timeout(updateTextareaHeight); } } function setModel(_modelControler) { modelController = _modelControler; } function updateTextareaHeight() { var tmpTextArea = angular.element('<textarea class="text-field__input" style="width: ' + input.width() + 'px;">' + input.val() + '</textarea>'); tmpTextArea.appendTo('body'); input.css( { height: tmpTextArea[0].scrollHeight + 'px' }); tmpTextArea.remove(); } } })();
JavaScript
0.000241
@@ -122,25 +122,25 @@ ield);%0A%0A -L +l xTextFieldCo @@ -133,34 +133,24 @@ lxTextField -Controller .$inject = %5B
43e7955e154cffb1765a5d58c1f96b6d728e1384
fix grouped bar example (#1014)
site/src/components/series/grouped-example.js
site/src/components/series/grouped-example.js
var width = 500, height = 250; var container = d3.select('#grouped') .append('svg') .attr({'width': width, 'height': height}); var data = [{ 'State': 'AL', 'Under 5 Years': '310', '5 to 13 Years': '552', '14 to 17 Years': '259', '18 to 24 Years': '450', '25 to 44 Years': '1215', '45 to 64 Years': '641' }, { 'State': 'AK', 'Under 5 Years': '52', '5 to 13 Years': '85', '14 to 17 Years': '42', '18 to 24 Years': '74', '25 to 44 Years': '183', '45 to 64 Years': '50' }, { 'State': 'AZ', 'Under 5 Years': '515', '5 to 13 Years': '828', '14 to 17 Years': '362', '18 to 24 Years': '601', '25 to 44 Years': '1804', '45 to 64 Years': '1523' }, { 'State': 'AR', 'Under 5 Years': '202', '5 to 13 Years': '343', '14 to 17 Years': '157', '18 to 24 Years': '264', '25 to 44 Years': '754', '45 to 64 Years': '727' }]; // manipulate the data into stacked series var spread = fc.data.spread() .xValueKey('State'); var series = spread(data); // create scales var x = d3.scale.ordinal() .domain(data.map(function(d) { return d.State; })) .rangePoints([0, width], 1); var yExtent = fc.util.extent() .fields(['y']) .include(0); var y = d3.scale.linear() .domain(yExtent(series.map(function(d) { return d.values; }))) .range([height, 0]); var groupedSeries = fc.series.bar(); // create the grouped series var groupedBar = fc.series.grouped(groupedSeries) .xScale(x) .yScale(y) .xValue(function(d) { return d.x; }) .yValue(function(d) { return d.y; }); // render container.append('g') .datum(series) .call(groupedBar);
JavaScript
0
@@ -1229,11 +1229,100 @@ ds(%5B -'y' +%0A function(a) %7B%0A return a.map(function(d) %7B return d.y; %7D);%0A %7D%0A %5D)%0A
95cfc674508fe9934998b46bce412c12ec7cb381
Remove redundant expectations
addons/knobs/src/components/__tests__/Array.js
addons/knobs/src/components/__tests__/Array.js
import React from 'react'; import { shallow } from 'enzyme'; // eslint-disable-line import ArrayType from '../types/Array'; describe('Array', () => { it('should subscribe to setKnobs event of channel', () => { const onChange = jest.fn(); const wrapper = shallow( <ArrayType onChange={onChange} knob={{ name: 'passions', value: ['Fishing', 'Skiing'], separator: ',' }} /> ); wrapper.simulate('change', { target: { value: 'Fhishing,Skiing,Dancing' } }); expect(onChange).toHaveBeenCalledWith(['Fhishing', 'Skiing', 'Dancing']); }); it('deserializes an Array to an Array', () => { const array = ['a', 'b', 'c']; const deserialized = ArrayType.deserialize(array); expect(Array.isArray(deserialized)).toEqual(true); expect(deserialized).toEqual(['a', 'b', 'c']); }); it('deserializes an Object to an Array', () => { const object = { 1: 'one', 0: 'zero', 2: 'two' }; const deserialized = ArrayType.deserialize(object); expect(Array.isArray(deserialized)).toEqual(true); expect(deserialized).toEqual(['zero', 'one', 'two']); }); });
JavaScript
0.000009
@@ -723,63 +723,8 @@ );%0A%0A - expect(Array.isArray(deserialized)).toEqual(true);%0A @@ -944,63 +944,8 @@ );%0A%0A - expect(Array.isArray(deserialized)).toEqual(true);%0A
73503de802e186ff86cabc8c276bf6fea38364b4
Make readByte private.
binary_reader.js
binary_reader.js
/** * @fileoverview Reads binary data. */ /** * @param {!ArrayBuffer} arraybuffer The binary data to read. * @param {number=} opt_length The length of the data, uses the ArrayBuffers * byte length if this isn't specified. * @constructor */ keepasschrome.BinaryReader = function(arraybuffer, opt_length) { /** * @private */ this.data_ = new Uint8Array(arraybuffer); /** * @private */ this.length_ = opt_length || arraybuffer.byteLength; /** * @private */ this.pos_ = 0; }; /** * Creates a BinaryReader from a WordArray. * @param {!CryptoJS.lib.WordArray} wordArray The WordArray. * @return {!keepasschrome.BinaryReader} A new BinaryReader. */ keepasschrome.BinaryReader.fromWordArray = function(wordArray) { var length = Math.ceil(wordArray.sigBytes / Uint32Array.BYTES_PER_ELEMENT) * Uint32Array.BYTES_PER_ELEMENT; var buf = new ArrayBuffer(length); var words = new Uint32Array(buf); // swap endianness, from // http://stackoverflow.com/questions/5320439/#answer-5320624 words.set(wordArray.words.map(function(val) { return ((val & 0xFF) << 24) | ((val & 0xFF00) << 8) | ((val >> 8) & 0xFF00) | ((val >> 24) & 0xFF); })); return new keepasschrome.BinaryReader(buf, wordArray.sigBytes); }; /** * @return {!boolean} True if there's at least one more byte. */ keepasschrome.BinaryReader.prototype.hasNextByte = function() { return this.pos_ < this.length_; }; /** * @return {!boolean} True if there's at least one more int. */ keepasschrome.BinaryReader.prototype.hasNextInt = function() { return this.pos_ < this.length_ - 3; }; /** * @return {!number} The next byte. */ keepasschrome.BinaryReader.prototype.readByte = function() { if (!this.hasNextByte()) { throw new RangeError(); } return this.data_[this.pos_++]; }; /** * @param {!number} num The number of bytes to read. * @return {!Array.<!number>} The bytes. */ keepasschrome.BinaryReader.prototype.readBytes = function(num) { var bytes = []; for (var i = 0; i < num; i++) { bytes.push(this.readByte()); } return bytes; }; /** * @param {!number} numBytes The numbers of bytes to read. * @return {!number} The number. * @private */ keepasschrome.BinaryReader.prototype.readNumber_ = function(numBytes) { var bytes = this.readBytes(numBytes); var result = 0; for (var i = bytes.length - 1; i >= 0; i--) { result = (result * 256) + bytes[i]; } return result; }; /** * @return {!number} The short. */ keepasschrome.BinaryReader.prototype.readShort = function() { return this.readNumber_(2); }; /** * @return {!number} The int. */ keepasschrome.BinaryReader.prototype.readInt = function() { return this.readNumber_(4); }; /** * @return {!number} The word. * @private */ keepasschrome.BinaryReader.prototype.readWord_ = function() { var bytes = this.readBytes(4); var result = 0; for (var i = 0; i < bytes.length; i++) { result = (result * 256) + bytes[i]; } return result; }; /** * @param {!number} num The number of bytes to read. * @return {!CryptoJS.lib.WordArray} The bytes. */ keepasschrome.BinaryReader.prototype.readWordArray = function(num) { var words = []; while (num > 0) { words.push(this.readWord_()); num -= 4; } return CryptoJS.lib.WordArray.create(words); }; /** * @return {!CryptoJS.lib.WordArray} The bytes. */ keepasschrome.BinaryReader.prototype.readRestToWordArray = function() { var restOfFile = []; var numBytes = 0; while (this.hasNextInt()) { restOfFile.push(this.readWord_()); numBytes += 4; } return CryptoJS.lib.WordArray.create(restOfFile, numBytes); }; /** * Reads in a null-terminated string. * @return {!string} The string; */ keepasschrome.BinaryReader.prototype.readString = function() { var result = ''; var b = this.readByte(); while (b != 0) { result += String.fromCharCode(b); b = this.readByte(); } return result; }; /** * @return {!Date} The date. */ keepasschrome.BinaryReader.prototype.readDate = function() { var bytes = this.readBytes(5); var year = (bytes[0] << 6) | (bytes[1] >> 2); var month = ((bytes[1] & 3) << 2) | (bytes[2] >> 6); var day = (bytes[2] >> 1) & 31; var hour = ((bytes[2] & 1) << 4) | (bytes[3] >> 4); var min = ((bytes[3] & 15) << 2) | (bytes[4] >> 6); var sec = bytes[4] & 63; return new Date(year, month - 1, day, hour, min, sec); };
JavaScript
0
@@ -1684,24 +1684,36 @@ next byte.%0A + * @private%0A */%0Akeepassc @@ -1745,24 +1745,25 @@ ype.readByte +_ = function( @@ -2113,16 +2113,17 @@ readByte +_ ());%0A %7D @@ -3873,24 +3873,25 @@ his.readByte +_ ();%0A while @@ -3960,16 +3960,17 @@ readByte +_ ();%0A %7D%0A
68f515e2e6839624490b4fa7c97441f08d6b516b
Fix bug related to URL handling.
src/js/index.js
src/js/index.js
// @flow import * as React from 'react'; import * as ReactDOM from 'react-dom'; import DocumentTitle from 'react-document-title'; import IconSettings from '@salesforce/design-system-react/components/icon-settings'; import logger from 'redux-logger'; import settings from '@salesforce/design-system-react/components/settings'; import thunk from 'redux-thunk'; import { withRouter } from 'react-router'; import { BrowserRouter, Route, Switch } from 'react-router-dom'; import { Provider } from 'react-redux'; import { applyMiddleware, createStore } from 'redux'; import { composeWithDevTools } from 'redux-devtools-extension'; import { t } from 'i18next'; import actionSprite from '@salesforce-ux/design-system/assets/icons/action-sprite/svg/symbols.svg'; import customSprite from '@salesforce-ux/design-system/assets/icons/custom-sprite/svg/symbols.svg'; import doctypeSprite from '@salesforce-ux/design-system/assets/icons/doctype-sprite/svg/symbols.svg'; import standardSprite from '@salesforce-ux/design-system/assets/icons/standard-sprite/svg/symbols.svg'; import utilitySprite from '@salesforce-ux/design-system/assets/icons/utility-sprite/svg/symbols.svg'; import init_i18n from './i18n'; import AuthError from 'components/authError'; import ErrorBoundary from 'components/error'; import Footer from 'components/footer'; import FourOhFour from 'components/404'; import Header from 'components/header'; import PerfTable, { changeUrl } from 'components/perfTable'; import getApiFetch from 'utils/api'; import reducer from 'store'; import { logError } from 'utils/logging'; import { login } from 'store/user/actions'; import { routePatterns } from 'utils/routes'; const SF_logo = require('images/salesforce-logo.png'); const App = () => ( <DocumentTitle title={t('Meta CI')}> <div className="slds-grid slds-grid_vertical" > <ErrorBoundary> <div className="slds-p-around_x-large slds-grow slds-shrink-none" > <ErrorBoundary> <PerfTable/> </ErrorBoundary> </div> </ErrorBoundary> </div> </DocumentTitle> ); init_i18n(() => { const el = document.getElementById('app'); if (el) { // Create store const appStore = createStore( reducer, {}, composeWithDevTools( applyMiddleware( thunk.withExtraArgument({ apiFetch: getApiFetch(), }), logger, ), ), ); // Get JS globals let GLOBALS = {}; try { const globalsEl = document.getElementById('js-globals'); if (globalsEl) { GLOBALS = JSON.parse(globalsEl.textContent); } } catch (err) { logError(err); } window.GLOBALS = GLOBALS; // Get logged-in/out status const userString = el.getAttribute('data-user'); if (userString) { let user; try { user = JSON.parse(userString); } catch (err) { // swallow error } if (user) { // Login appStore.dispatch(login(user)); } } el.removeAttribute('data-user'); // Set App element (used for react-SLDS modals) settings.setAppElement(el); /* Special case for getting repo name from URL path into query params with other filters */ if( window.location.pathname.indexOf("/repos/")>=0){ let pathParts = window.location.pathname.split("/"); changeUrl({repo: pathParts[pathParts-2]}) } ReactDOM.render( <Provider store={appStore}> <BrowserRouter> <IconSettings actionSprite={actionSprite} customSprite={customSprite} doctypeSprite={doctypeSprite} standardSprite={standardSprite} utilitySprite={utilitySprite} > <App /> </IconSettings> </BrowserRouter> </Provider>, el, ); } });
JavaScript
0
@@ -3440,16 +3440,23 @@ athParts +.length -2%5D%7D)%0A
2368117705c5afdd6865cd9ec697e0a2aaaca600
Implement min and max for grow shrink effect
src/js/index.js
src/js/index.js
// Creates the main splash scene (if you can even call it a scene) // // times: [Array<SplashTime>] All of the timing objects of your splash // // If you assign an onEnd property to the object and it's a function, it'll fire // once the splash is completed. class Splash { constructor(times) { this._times = times; } run() { this._previousTime = window.performance.now(); for (let time of this._times) { time.start(); } this._update(); } _update() { let now = window.performance.now(), delta = now - this._previousTime; this._previousTime = now; for (let time of this._times) { time.update(delta); } requestAnimationFrame(this._update.bind(this)); } } // Creates a splash timer object. Used for timing all the effects. // // delay: How much should this timer be delayed after the splash was started (seconds) // effects: [Array<SplashEffect>] What effects to use // parts: { // open: [Float] How long opening does this timer have (seconds) // stay: [Float] How long does it stay (the middle part) (seconds) // out: [Float] How long does it take it to end (seconds) // } // // If one of the parts isn't present, a value of 0 seconds will be assumed. class SplashTimer { constructor(delay, effects, parts) { this.delay = delay; this.effects = effects; this.parts = { open: parts.open || 0, stay: parts.stay || 0, out: parts.out || 0 } } update(delta) { this.seconds += delta / 1000; let partTime = [ this.parts.open, this.parts.open + this.parts.stay, this.parts.open + this.parts.stay + this.parts.out ]; if (this.seconds <= partTime[0]) { let value = this.seconds / this.parts.open; for (let effect of this.effects) { if (typeof effect.in == "function") effect.in(value); } } else if (this.seconds <= partTime[1]) { let value = (this.seconds - partTime[0]) / this.parts.stay; for (let effect of this.effects) { if (typeof effect.stay == "function") effect.stay(value); } } else if (this.seconds <= partTime[2]) { let value = (this.seconds - partTime[1]) / this.parts.out; for (let effect of this.effects) { if (typeof effect.out == "function") effect.out(value); } } } start() { this.seconds = 0; } } // ### Splash effect base class ### // Splash effects are created as follows: // Create a new class and extend it with this class. Then add a constructor // which calls super with the element you want to modify. Add functions in, out // and stay respectively as needed. If you don't want to use one of them, skip it. // // When implementing the in, out and stay functions, you most likely want to use // css styles, which you do with `this.setStyle(style, value)`. Keep in mind that // if you want to use transforms, you should use `this.setTransform(key, valye)`. class SplashEffect { constructor(element) { this.element = element; this.transforms = {}; } setStyle(style, value) { this.element.style[style] = value; } setTransform(key, value) { this.transforms[key] = value; this.applyTransforms(); } applyTransforms() { this.element.style.transform = ""; for (let transformName in this.transforms) { let transformValue = this.transforms[transformName]; this.element.style.transform += transformName + "(" + transformValue + ")"; } } } // ### Some basic effects ### class GrowAndShrink extends SplashEffect { constructor(element, min, max) { super(element); this.min = min; if (typeof max == "undefined") max = 1; } in(value) { this.setTransform("scale", value); } out(value) { this.setTransform("scale", value * -1 + 1); } } class FadeIn extends SplashEffect { }
JavaScript
0
@@ -3467,48 +3467,34 @@ min -;%0A%09%09if (typeof max == %22undefined%22) + %7C%7C 0;%0A%09%09this.max = max -= +%7C%7C 1;%0A @@ -3539,21 +3539,56 @@ scale%22, -value +(this.max - this.min) * value + this.min );%0A%09%7D%0A%0A%09 @@ -3629,16 +3629,41 @@ scale%22, +(this.max - this.min) * ( value * @@ -3669,16 +3669,28 @@ -1 + 1) + + this.min) ;%0A%09%7D%0A%7D%0A%0A
7eebe1b0d49235b9a5dc668602d055d0b883754b
Increase e2e test analysis timeout
nightwatchSpec/cribbageAnalystEndToEndTest.js
nightwatchSpec/cribbageAnalystEndToEndTest.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* globals module */ (function() { 'use strict'; const siteUrl = 'http://localhost:8080', bodySelector = 'body', initialRenderTimeoutMilliseconds = 151, analysesSelector = '#analyses', firstAnalysisSelector = '.analysis:first-of-type', analysisTimeoutMilliseconds = 850; /* Create at least one e2e test verifying entry point + HTML with Vue.js * markup works as expected - at least for a happy path. */ module.exports = { // jscs:disable jsDoc 'hand with fifteens and pairs points': function(browser) { // jscs:enable jsDoc browser .url(siteUrl) .waitForElementVisible(bodySelector, initialRenderTimeoutMilliseconds) .setValue('input[type=text]', 'Q7742A') .waitForElementPresent(firstAnalysisSelector, analysisTimeoutMilliseconds) .assert.containsText('#analyses', 'Keep Q77A, discard 42 = 4 points.') .end(); }, // jscs:disable jsDoc 'unknown card index': function(browser) { // jscs:enable jsDoc browser .url(siteUrl) .waitForElementVisible(bodySelector, initialRenderTimeoutMilliseconds) .setValue('input[type=text]', 'A233XY') .waitForElementPresent(firstAnalysisSelector, analysisTimeoutMilliseconds) .assert.containsText(analysesSelector, 'Keep A33X, discard 2Y = 2 points.') .end(); }, // jscs:disable jsDoc 'analyses sorted in descending points order': function(browser) { // jscs:enable jsDoc browser .url(siteUrl) .waitForElementVisible(bodySelector, initialRenderTimeoutMilliseconds) .setValue('input[type=text]', 'Q77772') .waitForElementPresent(firstAnalysisSelector, analysisTimeoutMilliseconds) .assert.containsText(firstAnalysisSelector, 'Keep 7777, discard Q2 = 12 points.') .end(); }, // jscs:disable jsDoc 'no cards to discard': function(browser) { // jscs:enable jsDoc browser .url(siteUrl) .waitForElementVisible(bodySelector, initialRenderTimeoutMilliseconds) .setValue('input[type=text]', 'K774') .waitForElementPresent(firstAnalysisSelector, analysisTimeoutMilliseconds) .assert.containsText(analysesSelector, 'Keep K774, discard nothing = 2 points.') .end(); }, // jscs:disable jsDoc 'hand with just a 4-run': function(browser) { // jscs:enable jsDoc browser .url(siteUrl) .waitForElementVisible(bodySelector, initialRenderTimeoutMilliseconds) .setValue('input[type=text]', 'A289TJ') .waitForElementPresent(firstAnalysisSelector, analysisTimeoutMilliseconds) .assert.containsText(analysesSelector, 'Keep 89TJ, discard A2 = 4 points.') .end(); }, // jscs:disable jsDoc 'hand with pairs, fifteens and runs points': function(browser) { // jscs:enable jsDoc browser .url(siteUrl) .waitForElementVisible(bodySelector, initialRenderTimeoutMilliseconds) .setValue('input[type=text]', '8876KQ') .waitForElementPresent(firstAnalysisSelector, analysisTimeoutMilliseconds) .assert.containsText(analysesSelector, 'Keep 8876, discard KQ = 12 points.') .end(); } }; }());
JavaScript
0
@@ -519,10 +519,11 @@ s = -85 +120 0;%0A%0A
ab2b4ed242de1f9e6de6ab3618d00d52a364679c
Fix bug in overall feedback view for students.
js/components/activity-feedback-for-student.js
js/components/activity-feedback-for-student.js
import React, { PureComponent } from 'react' import '../../css/activity-feedback.less' export default class ActivityFeedbackForStudent extends PureComponent { render() { const student = this.props.student const feedback = this.props.feedbacks .find( (f) => f.get('studentId') == student.get('id')) .get('feedbacks') .first() .toJS() const showFeedback = (feedback && feedback.hasBeenReviewed) const feedbackDiv = <div className="feedback"> <div className="feedback-section written-feedback"> <h1>Overall Feedback:</h1> <span>{feedback.feedback}</span> </div> <div className="feedback-section score"> <h1>Overall Score:</h1> <span className="score">{feedback.score}</span> </div> </div> const noFeedbackDiv = <div className="feedback noFeedback"> No overall feedback yet. </div> const displayDiv = showFeedback ? feedbackDiv : noFeedbackDiv return( <div className="activity-feedback"> { displayDiv } </div> ) } }
JavaScript
0
@@ -208,16 +208,106 @@ student%0A + let feedback = %7B%0A hasBeenReviewed: false,%0A score:0,%0A feedback:%22%22%0A %7D%0A cons @@ -308,24 +308,25 @@ const +_ feedback = this. @@ -317,16 +317,17 @@ feedback +s = this. @@ -407,60 +407,170 @@ '))%0A +%0A - .get('feedbacks')%0A .first()%0A .toJS() +if(_feedbacks)%7B%0A const fblist = _feedbacks.get('feedbacks')%0A if(fblist && fblist.size %3E 0) %7B%0A feedback = fblist.first().toJS()%0A %7D%0A %7D %0A%0A
4f3c62d3c58dbe55647b414bd4a89c5996204d3b
Make View spec skeleton
spec/filesize-view-spec.js
spec/filesize-view-spec.js
'use babel'; import filesizeView from '../lib/filesize-view'; const workspaceView = atom.views.getView(atom.workspace); beforeEach(() => { waitsForPromise(() => atom.packages.activate('status-bar') .then(() => atom.workspace.open('../fixtures/test.txt')) .then(() => atom.packages.activate('filesize'))); }); describe('when refreshing the view', () => { it('should display the human readable size', () => { const filesizeElement = workspaceView.querySelector('.file-size'); expect(filesizeElement.text).toEqual('5 bytes'); }); });
JavaScript
0
@@ -61,266 +61,835 @@ ';%0A%0A -const workspaceView = atom.views.getView(atom.workspace);%0A%0AbeforeEach(() =%3E %7B%0A waitsForPromise(() =%3E atom.packages.activate('status-bar')%0A .then(() =%3E atom.workspace.open('../fixtures/test.txt'))%0A .then(() =%3E atom.packages.activate('filesize')) +describe('View', () =%3E %7B%0A // Disable tooltip for these tests%0A atom.config.set('filesize.EnablePopupAppearance', false);%0A const workspaceView = atom.views.getView(atom.workspace);%0A const view = filesizeView(workspaceView);%0A%0A describe('when refreshing the view', () =%3E %7B%0A it('should display the human readable size', () =%3E %7B%0A workspaceView.appendChild(view.container);%0A const filesizeElement = workspaceView.querySelector('.current-size');%0A view.refresh(%7B size: 5 %7D);%0A expect(filesizeElement.innerHTML).toEqual('5 bytes');%0A %7D);%0A %7D);%0A%0A describe('when cleaning the view', () =%3E %7B%0A it('should wipe the filesize contents', () =%3E %7B%0A view.clean();%0A const filesizeElement = workspaceView.querySelector('.current-size');%0A expect(filesizeElement.innerHTML).toEqual('');%0A %7D );%0A + %7D);%0A +%0A desc @@ -891,39 +891,39 @@ describe('when -refresh +destroy ing the view', ( @@ -929,16 +929,18 @@ () =%3E %7B%0A + it('sh @@ -948,39 +948,36 @@ uld -display the human readable +remove the file- size + element ', ( @@ -979,24 +979,48 @@ t', () =%3E %7B%0A + view.destroy();%0A const fi @@ -1074,24 +1074,26 @@ ile-size');%0A + expect(f @@ -1110,13 +1110,8 @@ ment -.text ).to @@ -1112,33 +1112,36 @@ nt).toEqual( -'5 bytes' +null);%0A %7D );%0A %7D);%0A%7D); @@ -1137,12 +1137,13 @@ ;%0A %7D);%0A%7D);%0A +%0A
4ce2559fe7d0a2a967ba37b53c7132b9f21db9f6
Add css custom class
src/js/shade.js
src/js/shade.js
(function(factory) { if (typeof define === 'function' && define.amd) { define([ '$', 'plugin', 'velocity' ], factory); } else { var framework = window.Zepto || window.jQuery; factory(framework, window.Plugin, framework.Velocity); } }(function($, Plugin, Velocity) { function Shade(element, options) { Shade.__super__.call(this, element, options, Shade.DEFAULTS); } Shade.VERSION = '0'; Shade.DEFAULTS = { cover: document.body, color: 'black', opacity: '0.25', duration: 150, easing: 'swing', padding: 0, zIndex: 1, click: function() { this.close(); }, open: $.noop, opened: $.noop, close: $.noop, closed: $.noop }; Plugin.create('shade', Shade, { _init: function(element) { var plugin = this; this.$element = $(element); this.isBody = $(this.options.cover).is('body'); this.$shade = $('<div />') .addClass('shade') .css({ background: this.options.color ? this.options.color : '', opacity: 0 }) .hide() .on('click', function() { plugin.options.click && plugin.options.click.call(plugin); }) .insertAfter(this.$element); $(window) .on('resize:shade', function() { plugin.$shade.hasClass('shade--is-open') && plugin.setPosition.call(plugin); }); }, open: function() { var plugin = this; this._trigger('open'); this.setPosition(); Velocity.animate( this.$shade, { opacity: this.options.opacity }, { display: 'block', duration: this.options.duration, easing: this.options.easing, complete: function() { plugin.$shade .addClass('shade--is-open') .on('touchmove', function() { return false; }); plugin._trigger('opened'); } } ); }, close: function() { var plugin = this; this._trigger('close'); Velocity.animate( this.$shade, 'reverse', { display: 'none', duration: this.options.duration, easing: this.options.easing, complete: function() { plugin.$shade .removeClass('shade--is-open') .off('touchmove'); plugin._trigger('closed'); } } ); }, setPosition: function() { var $element = this.$element; var width = this.isBody ? 'auto' : $element.width(); var height = this.isBody ? 'auto' : $element.height(); var position = this.isBody ? 'fixed' : 'absolute'; this.$shade .css({ left: this.options.padding ? -this.options.padding : 0, top: this.options.padding ? -this.options.padding : 0, bottom: this.options.padding ? -this.options.padding : 0, right: this.options.padding ? -this.options.padding : 0, width: this.options.padding ? width - this.options.padding : width, height: this.options.padding ? height - this.options.padding : height, position: position, padding: this.options.padding, zIndex: this.options.zIndex || $element.css('zIndex') + 1 }); } }); return $; }));
JavaScript
0.000001
@@ -670,16 +670,38 @@ dex: 1,%0A + cssClass: '',%0A @@ -1136,16 +1136,65 @@ shade')%0A + .addClass(this.options.cssClass)%0A
7d1bd7d81c89ebdb27b4bb118ea55e78f7c08c86
Update Date
contentScript.js
contentScript.js
var woman=[]; var graceHopper = {name:"Grace Hopper", field:"Computer Science/Math", description:"Born in New York City in 1906, Grace Hopper joined the U.S. Navy during World War II and was assigned to program the Mark I computer. She continued to work in computing after the war, leading the team that created the first computer language compiler, which led to the popular COBOL language."}; var saumyRay = {name:"Saumya Ray", field:"Computer Science", description: "Saumya really loves nail art!" } woman.push(graceHopper); woman.push(saumyRay); document.write(woman[0].name + "\n"); document.write(woman[0].field);
JavaScript
0.000024
@@ -559,46 +559,146 @@ y);%0A -%09document.write( +%0Avar d = new Date(); %0Avar t = d.getTime(); %0Avar days = Math.floor(t / (1000));%0A%0Avar i = days %25 woman.length; %0A%0Avar today = woman%5B -0 +i %5D.name - + %22%5Cn%22) ; +%0A %0A%09do @@ -714,20 +714,11 @@ ite( -woman%5B0%5D.field +today );
7116034b345a1cb56481eb15ab9bef6a8d9011a1
Update new renderer for StatusList
app/assets/javascripts/repositories/renderers/new_renderers.js
app/assets/javascripts/repositories/renderers/new_renderers.js
/* global ListColumnHelper ChecklistColumnHelper Status SmartAnnotation I18n GLOBAL_CONSTANTS DateTimeHelper */ $.fn.dataTable.render.newRowName = function(formId, $cell) { $cell.html(` <div class="form-group"> <input class="form-control editing" form="${formId}" type="text" name="repository_row[name]" value="" data-type="RowName"> </div> `); }; $.fn.dataTable.render.newRepositoryAssetValue = function(formId, columnId, $cell) { $cell.html(` <div class="file-editing"> <div class="file-hidden-field-container hidden"></div> <input class="" id="repository_file_${columnId}" form="${formId}" type="file" data-col-id="${columnId}" data-is-empty="true" value="" data-type="RepositoryAssetValue"> <div class="file-upload-button new-file"> <label for="repository_file_${columnId}">${I18n.t('repositories.table.assets.select_file_btn', { max_size: GLOBAL_CONSTANTS.FILE_MAX_SIZE_MB })}</label> <span class="icon"><i class="fas fa-paperclip"></i></span><span class="label-asset"></span> <span class="delete-action fas fa-trash"> </span> </div> </div>`); }; $.fn.dataTable.render.newRepositoryTextValue = function(formId, columnId, $cell) { $cell.html(` <div class="form-group"> <input class="form-control editing" form="${formId}" type="text" name="repository_cells[${columnId}]" value="" data-type="RepositoryTextValue"> </div>`); SmartAnnotation.init($cell.find('input')); }; $.fn.dataTable.render.newRepositoryListValue = function(formId, columnId, $cell) { ListColumnHelper.initialListEditMode(formId, columnId, $cell); }; $.fn.dataTable.render.newRepositoryStatusValue = function(formId, columnId, $cell) { let url = $cell.closest('table').data('status-items-path'); let hiddenField = ` <input form="${formId}" type="hidden" name="repository_cells[${columnId}]" value="" data-type="RepositoryStatusValue">`; $cell.html(hiddenField + Status.initialStatusItemsRequest(columnId, '', formId, url)); Status.initStatusSelectPicker($cell.find('select'), $cell.find(`[name='repository_cells[${columnId}]']`)); }; $.fn.dataTable.render.newRepositoryChecklistValue = function(formId, columnId, $cell) { ChecklistColumnHelper.initialChecklistEditMode(formId, columnId, $cell); }; $.fn.dataTable.render.newRepositoryNumberValue = function(formId, columnId, $cell, $header) { let decimals = Number($header.data('metadata-decimals')); $cell.html(` <div class="form-group"> <input class="form-control editing" form="${formId}" type="number" name="repository_cells[${columnId}]" value="" onchange="if (this.value !== '') { this.value = parseFloat(Number(this.value).toFixed(${decimals})); }" data-type="RepositoryNumberValue"> </div>`); SmartAnnotation.init($cell.find('input')); }; $.fn.dataTable.render.newRepositoryDateTimeValue = function(formId, columnId, $cell) { DateTimeHelper.initDateTimeEditMode(formId, columnId, $cell, '', 'RepositoryDateTimeValue'); }; $.fn.dataTable.render.newRepositoryTimeValue = function(formId, columnId, $cell) { DateTimeHelper.initDateTimeEditMode(formId, columnId, $cell, 'timeonly', 'RepositoryTimeValue'); }; $.fn.dataTable.render.newRepositoryDateValue = function(formId, columnId, $cell) { DateTimeHelper.initDateTimeEditMode(formId, columnId, $cell, 'dateonly', 'RepositoryDateValue'); }; $.fn.dataTable.render.newRepositoryDateTimeRangeValue = function(formId, columnId, $cell) { DateTimeHelper.initDateTimeRangeEditMode(formId, columnId, $cell, '', 'RepositoryDateTimeRangeValue'); }; $.fn.dataTable.render.newRepositoryDateRangeValue = function(formId, columnId, $cell) { DateTimeHelper.initDateTimeRangeEditMode(formId, columnId, $cell, 'dateonly', 'RepositoryDateRangeValue'); }; $.fn.dataTable.render.newRepositoryTimeRangeValue = function(formId, columnId, $cell) { DateTimeHelper.initDateTimeRangeEditMode(formId, columnId, $cell, 'timeonly', 'RepositoryTimeRangeValue'); }; $.fn.dataTable.render.newRepositoryCheckboxValue = function(formId, columnId) { return ''; };
JavaScript
0
@@ -48,16 +48,28 @@ r Status +ColumnHelper SmartAn @@ -1941,456 +1941,72 @@ %7B%0A -let url = $cell.closest('table').data('status-items-path');%0A let hiddenField = %60%0A %3Cinput form=%22$%7BformId%7D%22%0A type=%22hidden%22%0A name=%22repository_cells%5B$%7BcolumnId%7D%5D%22%0A value=%22%22%0A data-type=%22RepositoryStatusValue%22%3E%60;%0A%0A $cell.html(hiddenField + Status.initialStatusItemsRequest(columnId, '', formId, url));%0A%0A Status.initStatusSelectPicker($cell.find('select'), $cell.find(%60%5Bname='repository_cells%5B$%7BcolumnId%7D%5D'%5D%60) +StatusColumnHelper.initialStatusEditMode(formId, columnId, $cell );%0A%7D
86e11f3bbae8fee1accf1774b5847503c988c675
raise timeout duration for sessions xhr requests
app/assets/javascripts/admin/views/sessions.js
app/assets/javascripts/admin/views/sessions.js
var SessionView = Backbone.View.extend({ el: "#session-form", readyToSubmit: false, initialize: function () { this.$submitButton = this.$("#session-form-submit"); this.$emailInput = this.$("#session-form-email"); this.$passcodeInput = this.$("#session-form-passcode"); this.$spinner = this.$("#session-spinner"); this.$feedbackMessage = this.$("#session-form-feedback"); this.$resendButton = this.$("#session-form-resend"); this.$rememberGroup = this.$("#session-form-remember-group"); }, requestAuthenticationCode: function(event) { var self = this; self.$passcodeInput.fadeOut(300); self.$submitButton.fadeOut(300); self.$resendButton.fadeOut(300); self.$feedbackMessage.fadeOut(300); self.$emailInput.fadeOut(300); self.$rememberGroup.fadeOut(300); window.setTimeout(function() { self.$spinner.fadeIn(400); $.ajax({ type: "POST", url: "/admin/signin/code", data: { "administrator": { "email": self.$emailInput.val() } }, beforeSend: function(xhr) { xhr.setRequestHeader("X-CSRF-Token", RailsMeta.csrfToken); }, statusCode: { 204: function(data, xstatus, xhr) { self.presentPasscodeInput(); }, 404: function(xhr, status, error) { self.presentErrorMessage(xhr.responseJSON.error) }, 423: function(xhr, status, error) { self.presentErrorMessage(xhr.responseJSON.error) }, 500: function(xhr, status, error) { self.presentErrorMessage("An unexpected server error occurred. Developers have been notified. Please try again\xA0later.") } }, timeout: 5000, error: function(xhr, status, error) { self.presentErrorMessage("Could not connect to the server. Check your network connection and try\xA0again.") } }); }, 300); }, presentErrorMessage: function(message) { var self = this; self.readyToSubmit = false; self.$spinner.fadeOut(400, function() { self.$feedbackMessage.html(message).fadeIn(300); self.$emailInput.fadeIn(300); self.$submitButton.html("Request a passcode").fadeIn(300); }); }, presentPasscodeInput: function() { var self = this; self.readyToSubmit = true; self.$spinner.fadeOut(400, function() { self.$passcodeInput.fadeIn(300).val("").focus(); self.$feedbackMessage.html("A passcode was just emailed to you.<br> Enter it here to sign in.").fadeIn(300); self.$submitButton.html("Sign In").fadeIn(300); self.$rememberGroup.fadeIn(300); self.$resendButton.fadeIn(300); }); }, handleSubmit: function(event) { if (!this.readyToSubmit) { event.preventDefault(); event.stopPropagation(); this.requestAuthenticationCode(); } }, events: { "submit": "handleSubmit", "click button": "handleSubmit", "click #session-form-resend": "requestAuthenticationCode" } }); var SessionView = new SessionView;
JavaScript
0
@@ -1774,17 +1774,18 @@ imeout: -5 +29 000,%0A
e0cf6c755e7f3fbdff5a63d1ce233146da2d67a7
Clean up semantics of ConditionalPromises.
kolibri/core/assets/src/conditionalPromise.js
kolibri/core/assets/src/conditionalPromise.js
class ConditionalPromise { /** * Create a conditional promise - like a promise, but cancelable! */ constructor(...args) { if ([...args].length) { this._promise = new Promise(...args); } } catch(...args) { this._promise.catch(...args); return this; } then(...args) { this._promise.then(...args); return this; } only(cancelCheck, resolve, reject) { /* * When the promise resolves, call the resolve function, only if cancelCheck evaluates to true. * @param {cancelCheck} Function - Function that returns a Boolean. * @param {resolve} Function - Function to call if the Promise succeeds. * @param {reject} Function - Function to call if the Promise fails. */ this._promise.then((success) => { if (cancelCheck() && resolve) { resolve(success); } }, (error) => { if (cancelCheck() && reject) { reject(error); } }); return this; } static all(promises) { /* * Equivalent of Promise.all, but return a ConditionalPromise instead. * @param {promises} [Promise|ConditionalPromise] - an array of Promises */ const conditionalPromise = new ConditionalPromise(); conditionalPromise._promise = Promise.all(promises); return conditionalPromise; } } module.exports = ConditionalPromise;
JavaScript
0.015832
@@ -86,19 +86,157 @@ but -cancelable! +with an additional method 'only'%0A * that allows for chaining resolve/reject handlers that will only be called if a%0A * certain condition pertains. %0A @@ -502,21 +502,23 @@ only(c -ancel +ontinue Check, r @@ -581,20 +581,16 @@ s, call -the resolve @@ -608,21 +608,23 @@ nly if c -ancel +ontinue Check ev @@ -656,21 +656,23 @@ param %7Bc -ancel +ontinue Check%7D F @@ -712,17 +712,17 @@ Boolean -. +, %0A * @@ -913,37 +913,39 @@ =%3E %7B%0A if (c -ancel +ontinue Check() && resol @@ -1019,13 +1019,15 @@ f (c -ancel +ontinue Chec
2e901b358beb0121f37bf37f9dbc3c7b6d62e6e8
Introduce StandingOrderListContainer
src/OutgoingOrderListContainer.js
src/OutgoingOrderListContainer.js
import React, {Component} from 'react'; import {Table} from 'react-bootstrap'; import OutgoingOrderList from './OutgoingOrderList' class OutgoingOrderListContainer extends Component { constructor(props){ console.log("OutgoingOrderListContainer props: ") console.log(props) super(props) this.state = { outgoingOrders: [], account: props.account } this.isWatching = false } tryStartWatching() { var self = this if (self.props.factoryInstance) { console.log("Factory still undefined...") return } // Okay, I'm watching self.isWatching = true // Get all existing contracts var allEvents = this.props.factoryInstance.allEvents({fromBlock: 0, toBlock: 'latest'}) allEvents.get(function (error, logs) { if (error === null) { console.log("Got " + logs.length + " Past events") var entry for (entry of logs) { console.log(entry) self.props.orderContract.at(entry.args.orderAddress).then(function (order_instance) { console.log("Adding order:") console.log(order_instance) self.setState({ // use concat to create a new array extended with the new order outgoingOrders: self.state.outgoingOrders.concat([order_instance]) }) }) } } else { console.log("Error while fetching past events:") console.log(error) } }) // Start watching for new contracts this.createdOrders = this.props.factoryInstance.LogOrderCreated({fromBlock: 'pending', toBlock: 'latest'}) this.createdOrders.watch(function (error, result) { // This will catch all createdOrder events, regardless of how they originated. if (error === null) { console.log('LogOrderCreated event:') console.log(result.args) self.props.orderContract.at(result.args.orderAddress).then(function (order_instance) { console.log("Got contract at " + result.args.orderAddress + ":") console.log(order_instance) self.setState({ // use concat to create a new array extended with the new order outgoingOrders: self.state.outgoingOrders.concat([order_instance]) }) }) } else { console.log('Error while watching events:') console.log(error) } }) } tryStopWatching() { if (this.isWatching) { this.isWatching = false this.createdOrders.stopWatching() } } componentWillUnmount() { // Stop watching for new contracts this.tryStopWatching() } render() { console.log("Rendering OutgoingOrderListContainer!") console.log("Props: ") console.log(this.props) if (!this.isWatching){ this.tryStartWatching() } return <OutgoingOrderList outgoingOrders={this.state.outgoingOrders} /> } } export default OutgoingOrderListContainer
JavaScript
0
@@ -532,26 +532,35 @@ toryInstance + === null )%0A - %7B%0A @@ -631,32 +631,115 @@ return%0A %7D + else %7B%0A console.log(%22Factory: %22 + self.props.factoryInstance)%0A %7D %0A%0A // Oka @@ -844,28 +844,28 @@ allEvents = -this +self .props.facto @@ -1909,20 +1909,20 @@ rders = -this +self .props.f
ab70dd753efa6801e4328cc45956c3741efff431
remove prelude references
src/lib/game.js
src/lib/game.js
import compact from 'prelude-es6/lib/List/compact'; import curry from 'prelude-es6/lib/Func/curry'; function newKey(key, offset, size) { let $key = key + offset; if ($key < 0) { $key = size - 1; } if ($key >= size) { $key = 0; } return $key; } export function getNeighbours(grid, { y, x }) { const size = grid.length - 1; let aliveNeighours = 0; for (let xOffset = -1; xOffset <= 1; ++xOffset) { for (let yOffset = -1; yOffset <= 1; ++yOffset) { if (!xOffset && !yOffset) continue; const $x = newKey(x, xOffset, size); const $y = newKey(y, yOffset, size); aliveNeighours += +!!grid[$y][$x]; } } return aliveNeighours; } export function willLive(isAlive, neighbours) { return isAlive ? neighbours >= 2 && neighbours <= 3 : neighbours === 3 } export function nextState(grid) { return grid.map((row, y) => row.map((column, x) => +willLive(column, getNeighbours(grid, { x, y })))); } export function toggle({ y, x }, current, grid) { grid[y][x] = +!current; return grid; }
JavaScript
0.000001
@@ -1,105 +1,4 @@ -import compact from 'prelude-es6/lib/List/compact';%0Aimport curry from 'prelude-es6/lib/Func/curry';%0A%0A func
d955093d6340f79023330047cebc7646834e1292
fix for empty count bug
src/lib/main.js
src/lib/main.js
//Todo: option to count all unread mail var request = require("sdk/request").Request; var tabs = require("sdk/tabs"); var tmr = require('sdk/timers'); var self = require("sdk/self"); var preferences = require("sdk/simple-prefs").prefs; var notifications = require("sdk/notifications"); var { ActionButton } = require("sdk/ui/button/action"); // Global variables var oldcount = 0; var outlookbutton = ActionButton({ id: "outlookbutton", label: "Not logged in", icon: { "16": "./outlook-16.png", "32": "./outlook-32.png", "64": "./outlook-64.png" }, onClick: newOutlook, badge: "", badgeColor: "#FF4444", label: "Loading" }); tmr.setTimeout(checkOutlook, 420); //preferences.checktime * 1000 function checkOutlook() { request({ url: "https://dub110.mail.live.com/default.aspx", content: { var: Date.now() }, onComplete: function(response) { //Test if logged in: if(response.text.indexOf("Login_Core.js") > 0) { //not logged in outlookbutton.label = "Not logged in"; outlookbutton.badge = "!"; } else { var count = /containerListRoot.+?title="\w+?[&#\d;]*?(\d*?)"/.exec(response.text); if(count !== null && count[1] !== undefined) { //fail test //count > 999? -> 999+ if (!(parseInt(oldcount) >= parseInt(count[1]))) { oldcount = count[1]; if (parseInt(count[1]) >= 1000) { count[1] = "999+"; } if (parseInt(count[1]) == 0) { count[1] = ""; } else { notifications.notify({ title: count[1] + " new " + (count[1]==1 ? "E-Mail" : "E-Mails") + " on Outlook", text: "Click here to open outlook", iconURL: self.data.url("outlook-64.png"), onClick: function () { newOutlook(); } }); } } outlookbutton.label = "Visit outlook.com"; outlookbutton.badge = count[1]; } else { outlookbutton.label = "Check login"; outlookbutton.badge = "@!"; } } } }).get(); tmr.setTimeout(function(){ checkOutlook(); }, preferences.checktime * 1000); } function newOutlook() { switch (preferences.newtab) { case "N": tabs.open("https://mail.live.com/"); break; case "R": var reused = false; for (let tab of tabs) { if (/mail\.live\.com/.test(tab.url)) { tab.activate(); reused = true; } if ((/about:newtab/.test(tab.url)) && !reused) { tab.activate(); tab.url = "https://mail.live.com/"; reused = true; } } if (!reused) { tabs.open("https://mail.live.com/"); } break; } }
JavaScript
0
@@ -1266,34 +1266,14 @@ %09%09%09%09 -if (!(parseInt(old count -) %3E + = pa @@ -1288,17 +1288,48 @@ ount%5B1%5D) -) + %7C%7C 0;%0A%09%09%09%09%09if (count %3E oldcount ) %7B%0A%09%09%09%09 @@ -1342,27 +1342,24 @@ ount = count -%5B1%5D ;%0A%09%09%09%09%09%09if ( @@ -1357,35 +1357,22 @@ %09%09%09%09%09if -(parseInt (count -%5B1%5D) %3E= 1000 @@ -1376,27 +1376,24 @@ 000) %7B count -%5B1%5D = %22999+%22; %7D @@ -1406,27 +1406,14 @@ %09if -(parseInt (count -%5B1%5D) == @@ -1429,19 +1429,16 @@ %09%09%09count -%5B1%5D = %22%22;%0A%09 @@ -1501,19 +1501,16 @@ e: count -%5B1%5D + %22 new @@ -1520,19 +1520,16 @@ + (count -%5B1%5D ==1 ? %22E @@ -1812,19 +1812,16 @@ = count -%5B1%5D ;%0A%09%09%09%09%7D
a51107bcea9d4ce711b73ab5fdd6cc703590f865
Update 2017.09.24
assets/js/index.js
assets/js/index.js
/** * Main JS file for kaldorei behaviours */ /* globals jQuery, document */ (function($, undefined) { "use strict"; var $document = $(document); $document.ready(function() { var $postContent = $(".post-content"); $postContent.fitVids(); $(".scroll-down").arctic_scroll(); $(".menu-button, .nav-cover, .nav-close").on("click", function(e) { e.preventDefault(); $("body").toggleClass("nav-opened nav-closed"); }); $(window).scroll(function() { var scrollerToTop = $('.backTop'); var scrollerTOC = $('.widget-toc'); document.documentElement.scrollTop + document.body.scrollTop > 200 ? scrollerToTop.fadeIn() : scrollerToTop.fadeOut(); document.documentElement.scrollTop + document.body.scrollTop > 250 ? scrollerTOC.addClass("widget-toc-fixed") : scrollerTOC.removeClass("widget-toc-fixed"); }); // #backTop Button Event $("#backTop").on("click", function() { scrollToTop(); }); // highlight config hljs.initHighlightingOnLoad(); // numbering for pre>code blocks $(function() { $('pre code').each(function() { var lines = $(this).text().split('\n').length - 1; var $numbering = $('<ul/>').addClass('pre-numbering'); $(this).addClass('has-numbering').parent().append($numbering); for (var i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); } }); }); var toc = $('.toc'); // toc config toc.toc({ content: ".post-content", headings: "h2,h3,h4,h5" }); if (toc.children().length == 0) $(".widget-toc").hide(); var tocHieght = toc.height(); var tocFixedHeight = $(window).height() - 192; tocHieght > tocFixedHeight ? toc.css('height', tocFixedHeight) : toc.css('height', tocHieght) $(window).resize(function() { var tocFixedHeight = $(this).height() - 192; tocHieght > tocFixedHeight ? toc.css('height', tocFixedHeight) : toc.css('height', tocHieght) }) // toc animate effect // bind click event to all internal page anchors $('a.data-scroll').on('click', function(e) { // prevent default action and bubbling e.preventDefault(); e.stopPropagation(); // set target to anchor's "href" attribute var target = $(this).attr('href'); // scroll to each target $(target).velocity('scroll', { duration: 500, easing: 'ease-in-out' //easing: 'spring' }); }); // tooltip config $('[data-rel=tooltip]').tooltip(); // fancybox config $('.post-content a:has(img)').addClass('fancybox'); $(".fancybox").attr('rel', 'gallery-group').fancybox({ helpers: { overlay: { css: { 'background': 'rgba(0, 154, 97, 0.33)' }, locked: false } }, beforeShow: function() { var alt = this.element.find('img').attr('alt'); this.inner.find('img').attr('alt', alt); this.title = alt; } }); // add archives year var yearArray = new Array(); $(".archives-item").each(function() { var archivesYear = $(this).attr("date"); yearArray.push(archivesYear); }); var uniqueYear = $.unique(yearArray); for (var i = 0; i < uniqueYear.length; i++) { var html = "<div class='archives-item fadeInDown animated'>" + "<div class='archives-year'>" + "<h3><time datetime='" + uniqueYear[i] + "'>" + uniqueYear[i] + "</time></h3>" + "</div></div>"; $("[date='" + uniqueYear[i] + "']:first").before(html); } }); // Arctic Scroll by Paul Adam Davis // https://github.com/PaulAdamDavis/Arctic-Scroll $.fn.arctic_scroll = function(options) { var defaults = { elem: $(this), speed: 500 }, allOptions = $.extend(defaults, options); allOptions.elem.click(function(event) { event.preventDefault(); var $this = $(this), $htmlBody = $('html, body'), offset = ($this.attr('data-offset')) ? $this.attr('data-offset') : false, position = ($this.attr('data-position')) ? $this.attr('data-position') : false, toMove; if (offset) { toMove = parseInt(offset); $htmlBody.stop(true, false).animate({ scrollTop: ($(this.hash).offset().top + toMove) }, allOptions.speed); } else if (position) { toMove = parseInt(position); $htmlBody.stop(true, false).animate({ scrollTop: toMove }, allOptions.speed); } else { $htmlBody.stop(true, false).animate({ scrollTop: ($(this.hash).offset().top) }, allOptions.speed); } }); }; })(jQuery); function scrollToTop(name, speed) { if (!speed) speed = 300 if (!name) { $('html,body').animate({ scrollTop: 0 }, speed) } else { if ($(name).length > 0) { $('html,body').animate({ scrollTop: $(name).offset().top }, speed) } } }
JavaScript
0
@@ -2684,40 +2684,188 @@ -var target = $(this).attr('href' +// Thanks to @https://github.com/xiongchengqing fixed this bug.%0A var target = document.getElementById($(this).attr('href').split('#')%5B1%5D);%0A console.log(target );%0A
a7719b5a30ad6024afa31c082c6fd57f46f0f065
Add util functions
src/lib/util.js
src/lib/util.js
export const focusNextInput = $el => { setTimeout(() => { const $nextEl = $el.nextElementSibling if ($nextEl && $nextEl instanceof HTMLInputElement) { $nextEl && $nextEl.focus && $nextEl.focus() } }) } export const focusPrevInput = $el => { const $nextEl = $el.nextElementSibling const $prevEl = $el.previousElementSibling if (!$nextEl || !($nextEl instanceof HTMLInputElement)) { $prevEl && $prevEl.focus && $prevEl.focus() } } export const week = date => { date = date instanceof Date ? date : new Date() var first = new Date(date.getFullYear(), 0, 1) var diff = ((date - first) / 86400000) var days = (diff + first.getDay()) return Math.floor(days / 7).toString() }
JavaScript
0.000039
@@ -704,12 +704,817 @@ oString()%0A%7D%0A +%0Aexport const transDate = date =%3E %7B%0A const year = date.getFullYear()%0A const month = (month =%3E %7B%0A let ret = (month + 1).toString()%0A return ret.length === 1 ? '0' + ret : ret%0A %7D)(date.getMonth())%0A const day = (date =%3E %7B%0A let ret = date.toString()%0A return ret.length === 1 ? '0' + ret : ret%0A %7D)(date.getDate())%0A return %60$%7Byear%7D-$%7Bmonth%7D-$%7Bday%7D%60%0A%7D%0A%0Aexport const getDateRange = date =%3E %7B%0A const startDate = new Date(date)%0A const endDate = new Date(date)%0A const day = (new Date(date)).getDay()%0A startDate.setDate(startDate.getDate() - day)%0A endDate.setDate(endDate.getDate() + 7 - day - 1)%0A return %7B%0A start: transDate(startDate),%0A end: transDate(endDate)%0A %7D%0A%7D%0A%0Aexport const hasReport = props =%3E !(%0A !props.thisWeek.length%0A && !props.nextWeek.length%0A && !props.projects.length%0A)
3a928beeb209ca67b38324011d4aca46fd2b82e7
Update mohan.js
assets/js/mohan.js
assets/js/mohan.js
<script type="text/javascript"> $(document).ready(function() { var date = Date.today().second().thursday(); $('nextmeetingdate').html = date; }); </script>
JavaScript
0
@@ -108,16 +108,17 @@ );%0A $(' +# nextmeet
6fc441ec20666fc7803fdc325452f2349a61fa1a
Set margin instead of padding for body
assets/js/table.js
assets/js/table.js
function TeiTable() { var XSLTProc; var hiddenCols = []; /** Populate the hide and show menus. */ function _populateMenus() { var headings = [] $('table th').each(function(i) { var h = {'label': $(this).html(), 'visible': hiddenCols.indexOf(i) == -1, 'index': i} headings.push(h); }); function renderPlaceholder(id) { var template = $("#table-menu-ph-template").html(); rendered = Mustache.render(template, {label: "Nothing to " + id}); $("#" + id + "-menu").html(rendered); } function renderMenu(id, cls) { var template = $("#table-menu-template").html(); rendered = Mustache.render(template, {cls: cls, headings: headings}); $("#" + id + "-menu").html(rendered); } function getHideCls() { return (this.visible) ? "hide-column" : "hide-column hidden"; } function getShowCls() { return (!this.visible) ? "show-column" : "show-column hidden"; } if (hiddenCols.length !== $('table th').length) { renderMenu('hide', getHideCls) } else { renderPlaceholder('hide'); } if (hiddenCols.length > 0) { renderMenu('show', getShowCls) } else { renderPlaceholder('show'); } } /** Hide a table column. */ this.hideColumn = function(columnIndex) { $('table tr > *:nth-child(' + (columnIndex + 1) + ')').hide(); hiddenCols.push(columnIndex); _populateMenus(); } /** Show a table column. */ this.showColumn = function(columnIndex) { $('table tr > *:nth-child(' + (columnIndex + 1) + ')').show(); hiddenCols = $.grep(hiddenCols, function(value) { return value != columnIndex; }); _populateMenus(); } /** Fixes for frozen table header. */ this.fixFrozenTable = function() { // Resize header cells $('#table-scroll.fixed tbody tr:first-child td').each(function(i) { var colWidth = $(this).width(); $('table thead tr th:nth-child(' + (i + 1) + ')').width(colWidth); }); // Resize tbody to always show vertical scroll bar var offset = $('#table-scroll').scrollLeft(); width = $('#table-scroll').width(); $('#table-scroll.fixed tbody').css('width', offset + width); // Add padding var headerHeight = $('thead').height(); $('#table-scroll.fixed tbody').css('padding-top', headerHeight); } /** Load TEI data into the table view. */ this.populate = function(xml) { teiTable = this; html = XSLTProc.transformToFragment(xml, document); $('#table-scroll').html(html); this.fixFrozenTable(); $(hiddenCols).each(function(k, v) { teiTable.hideColumn(v); }); _populateMenus(); } /** Update the XSLT processor. */ this.updateXSLTProc = function(obj) { XSLTProc = obj; } /** Check if the XSLT processor has been loaded. */ this.XSLTProcLoaded = function() { return typeof(XSLTProc) !== 'undefined'; } /** Show table borders. */ this.showBorders = function() { $('table').addClass('table-bordered'); this.fixFrozenTable(); } /** Hide table borders. */ this.hideBorders = function() { $('table').removeClass('table-bordered'); this.fixFrozenTable(); } }
JavaScript
0
@@ -2624,23 +2624,22 @@ ').css(' -padd +marg in -g -top', h
3d6a9424f054bfeebe05fc00c4bf4bd538bc8efb
Use exact equals in video.js
assets/js/video.js
assets/js/video.js
angular .module('video', []) .factory('$video', ['$http', '$log', function($http, $log) { var videos = []; const YOUTUBE_URL = 'https://www.youtube.com/watch?v='; function push(video) { videos.push(video); } function update(v) { let video = findById(v.id); if (video) { videos[videos.indexOf(video)] = v; } } function getVideos() { return videos.filter(function(video) { return !video.played || new Date(video.startTime) >= new Date(Date.now() - 24 * 3600 * 1000); }); } function findById(id) { return videos.find((v) => v.id.toString() == id); } function findByKey(key) { return videos.find((v) => v.key == key); } function current() { return videos.find((v) => v.playing); } function subscribe() { io.socket.get('/api/subscribeVideos'); } function getAll() { return $http.get('/api/start').then(({ data }) => { videos = data.videos; return data; }); } function skip(username) { return $http.post('/api/skip', { username }); } function add(link, user) { return $http.post('/api/add', { link, user }); } function addByKey(user, key) { return $http.post('/api/add', { link: YOUTUBE_URL + key, user }); } function addPlaylistById(user, playlistId) { return $http.post('/api/addPlaylist', { playlistId, user }); } function remove(id) { let removedVideo = findById(id); if (removedVideo) { videos.splice(videos.indexOf(removedVideo), 1); } } function removePermanently(id) { return $http.delete(`/api/remove/${id}`); } function upcoming() { return videos.filter((video) => !video.played && !video.playing); } function recent() { return videos.filter((video) => video.played && !video.playing); } function videoInUpcoming(key) { return upcoming().filter((video) => video.key === key).length === 1; } function formatDuration(duration) { return moment.duration(duration).format('H:mm:ss'); } function expectedPlayTime(video) { if (video.played || video.playing) { return ''; } let currentVideo = current(); let currentStartTime = moment(currentVideo.startTime); let upcomingVideos = upcoming(); upcomingVideos.unshift(currentVideo); let betweenVideos = upcomingVideos.slice(0, upcomingVideos.indexOf(video)); let expectedTime = betweenVideos.reduce(function(time, video) { time.add(moment.duration(video.duration)); return time; }, currentStartTime); return expectedTime.format('LT'); } return { push, add, addByKey, addPlaylistById, update, getVideos, findById, findByKey, current, subscribe, getAll, skip, remove, removePermanently, upcoming, recent, videoInUpcoming, formatDuration, expectedPlayTime }; }]);
JavaScript
0.000017
@@ -585,16 +585,17 @@ ing() == += id);%0A @@ -663,16 +663,17 @@ v.key == += key);%0A
79d86493529ebe02f1041da95565b19125cebb88
Update tests.
assets/src/edit-story/components/fontPicker/test/fontPicker.js
assets/src/edit-story/components/fontPicker/test/fontPicker.js
/* * Copyright 2020 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. */ /** * External dependencies */ import { act, fireEvent, waitFor } from '@testing-library/react'; /** * Internal dependencies */ import FontPicker from '../'; import { FontProvider } from '../../../app/font'; import APIContext from '../../../app/api/context'; import { renderWithTheme } from '../../../testUtils'; import fontsListResponse from './fontsResponse'; async function getFontPicker(options) { const getAllFontsPromise = Promise.resolve(fontsListResponse); const apiContextValue = { actions: { getAllFonts: () => getAllFontsPromise, }, }; const props = { onChange: jest.fn(), value: 'Roboto', ...options, }; const accessors = renderWithTheme( <APIContext.Provider value={apiContextValue}> <FontProvider> <FontPicker {...props} /> </FontProvider> </APIContext.Provider> ); await act(() => getAllFontsPromise); return accessors; } describe('Font Picker', () => { // Mock scrollTo const scrollTo = jest.fn(); Object.defineProperty(window.Element.prototype, 'scrollTo', { writable: true, value: scrollTo, }); it('should render font picker title and clicking the button should open the font picker', async () => { const { getByRole, getAllByRole } = await getFontPicker(); // Fire a click event. const selectButton = getByRole('button'); fireEvent.click(selectButton); // Listbox should be showing after click const fontsList = getByRole('listbox'); expect(fontsList).toBeInTheDocument(); // Should render all options const allOptionItems = getAllByRole('option'); expect(allOptionItems).toHaveLength(fontsListResponse.length); }); it('should mark the currently selected font and scroll to it', async () => { scrollTo.mockReset(); const { getByRole } = await getFontPicker(); // Fire a click event. const selectButton = getByRole('button'); fireEvent.click(selectButton); // Listbox should be showing after click const fontsList = getByRole('listbox'); expect(fontsList).toBeInTheDocument(); // Roboto option should be visible and have a selected checkmark const selectedRobotoOption = getByRole('option', { // The "accessible name" is derived by concatenating the accessible names // of all children, which in this case is an SVG with aria-label="Selected" // and a plain text node with the font name. Thus this works! name: 'Selected Roboto', }); expect(selectedRobotoOption).toBeInTheDocument(); // We can't really validate this number anyway in JSDom (no actual // layout is happening), so just expect it to be called expect(scrollTo).toHaveBeenCalledWith(0, expect.any(Number)); }); it('should select the next font in the list when using the down arrow plus enter key', async () => { const onChangeFn = jest.fn(); const { getByRole } = await getFontPicker({ onChange: onChangeFn }); const selectButton = getByRole('button'); fireEvent.click(selectButton); const fontsList = getByRole('listbox'); expect(fontsList).toBeInTheDocument(); act(() => { fireEvent.keyDown(fontsList, { key: 'ArrowDown', }); }); act(() => { fireEvent.keyDown(fontsList, { key: 'Enter' }); }); expect(onChangeFn).toHaveBeenCalledWith('Roboto Condensed'); }); it('should close the menu when the Esc key is pressed.', async () => { const onChangeFn = jest.fn(); const { getByRole } = await getFontPicker({ onChange: onChangeFn }); const selectButton = getByRole('button'); fireEvent.click(selectButton); const fontsList = getByRole('listbox'); expect(fontsList).toBeInTheDocument(); act(() => { fireEvent.keyDown(fontsList, { key: 'Escape', }); }); await waitFor(() => expect(fontsList).not.toBeInTheDocument()); }); it('should select the previous font in the list when using the up arrow plus enter key', async () => { const onChangeFn = jest.fn(); const { getByRole } = await getFontPicker({ onChange: onChangeFn }); const selectButton = getByRole('button'); fireEvent.click(selectButton); const fontsList = getByRole('listbox'); expect(fontsList).toBeInTheDocument(); act(() => { fireEvent.keyDown(fontsList, { key: 'ArrowUp', }); }); act(() => { fireEvent.keyDown(fontsList, { key: 'Enter' }); }); expect(onChangeFn).toHaveBeenCalledWith('Handlee'); }); it('should search and filter the list to match the results.', async () => { const { getByRole, queryAllByRole } = await getFontPicker(); const selectButton = getByRole('button'); fireEvent.click(selectButton); expect(queryAllByRole('option')).toHaveLength(fontsListResponse.length); act(() => { fireEvent.change(getByRole('combobox'), { target: { value: 'Yrsa' }, }); }); await waitFor(() => expect(queryAllByRole('option')).toHaveLength(1), { timeout: 500, }); }); it('should show an empty list when the search keyword has no results.', async () => { const { getByRole, queryAllByRole } = await getFontPicker(); const selectButton = getByRole('button'); fireEvent.click(selectButton); expect(queryAllByRole('option')).toHaveLength(fontsListResponse.length); act(() => { fireEvent.change(getByRole('combobox'), { target: { value: 'Not a font!' }, }); }); await waitFor(() => expect(queryAllByRole('option')).toHaveLength(0), { timeout: 500, }); }); });
JavaScript
0
@@ -3871,32 +3871,68 @@ r' %7D);%0A %7D);%0A%0A + // The second font in the list.%0A expect(onCha @@ -3964,24 +3964,12 @@ th(' -Roboto Condensed +Abel ');%0A @@ -4871,32 +4871,249 @@ TheDocument();%0A%0A + // Move down by 2%0A act(() =%3E %7B%0A fireEvent.keyDown(fontsList, %7B%0A key: 'ArrowDown',%0A %7D);%0A %7D);%0A act(() =%3E %7B%0A fireEvent.keyDown(fontsList, %7B%0A key: 'ArrowDown',%0A %7D);%0A %7D);%0A%0A act(() =%3E %7B%0A @@ -5104,32 +5104,32 @@ act(() =%3E %7B%0A - fireEvent. @@ -5267,24 +5267,104 @@ );%0A %7D);%0A%0A + // Moving down by 2 and back 1 up should end up with the second font: Abel.%0A expect(o @@ -5400,15 +5400,12 @@ th(' -Handlee +Abel ');%0A
9f0a08ae356a7491eec2fe3f384a9252e82b0453
Update `listView` to match type resolver
src/listView.js
src/listView.js
import { OrderedMap } from 'immutable' import { memoize, rawValue, createType } from './lowlevel/common' import initFactory from './lowlevel/initFactory' import { hash } from './crypto' const LIST_VIEW_NODE_DEF = { name: 'ListViewNode', union: [ { name: 'branch', type: { struct: [ { name: 'left', type: 'ListViewNode' }, { name: 'right', type: 'ListViewNode' } ] } }, { name: 'stub', type: 'ListViewNode' }, { name: 'hash', type: 'Hash' }, { name: 'val', type: 'T' } ] } /** * Creates a `ListViewNode<ValType>` for a specific type of values. */ function listViewNode (ValType, resolver) { // XXX: works only with "native" type definitions return resolver.addNativeType('T', ValType) .addTypes([ LIST_VIEW_NODE_DEF ]).resolve('ListViewNode') } function parseTreeStructure (tree) { const nodes = [] const leaves = [] /** * Recursively walks the tree from root to leaves. * * @param {number} level 0-based tree level, counting from the root * @param {number} pos 0-based position of the current node on the current level */ function walkTree (node, level = 0, pos = 0) { node.level = level node.pos = pos nodes.push(node) switch (node.type) { case 'val': case 'hash': leaves.push(node) break case 'branch': const { left, right } = node.branch walkTree(left, level + 1, 2 * pos) walkTree(right, level + 1, 2 * pos + 1) break case 'stub': walkTree(node.stub, level + 1, 2 * pos) break } } walkTree(tree) const levels = leaves.map(node => node.level) const depth = Math.max.apply(null, levels) const values = leaves.filter(node => node.type === 'val') // All values must be on the same level // All hashes must not exceed this level if ( !values.every(node => node.level === depth) ) { throw new Error('Invalid value / hash height') } // All `stub`s must be right children of their parents if ( nodes.filter(node => node.type === 'branch') .some(({ branch }) => branch.left.type === 'stub') ) { throw new TypeError('Stub node being the left child of parent') } return { depth, nodes, leaves, values } } /** * Recursively calculates the hash of the entire `ListView`. * * @param {ListViewNode<any>} node * @returns {Hash} */ function treeHash (node) { switch (node.type) { case 'hash': return node.hash case 'val': return hash(node.val) case 'branch': return hash(treeHash(node.branch.left), treeHash(node.branch.right)) case 'stub': return hash(treeHash(node.stub)) } } // Methods proxied from `OrderedMap` to `ListView` const PROXIED_METHODS = [ 'get', 'count', 'keys', 'values', 'entries', 'keySeq', 'valueSeq', 'entrySeq' ] function listView (ValType, resolver) { ValType = resolver.resolve(ValType) const Node = listViewNode(ValType, resolver) class ListView extends createType({ name: `ListView<${ValType.inspect()}>` }) { constructor (obj) { const root = Node.from(obj) const { depth, values } = parseTreeStructure(root) // Guaranteed to be sorted by ascending `node.pos` // XXX: This loses original Exonum-typed values. Suppose this is OK? const map = OrderedMap(values.map(node => [node.pos, node.val])) super({ map, root, depth }) } rootHash () { return treeHash(rawValue(this).root) } depth () { return rawValue(this).depth } } ListView.prototype.rootHash = memoize(ListView.prototype.rootHash) PROXIED_METHODS.forEach(methodName => { ListView.prototype[methodName] = function () { const map = rawValue(this).map return map[methodName].apply(map, arguments) } }) return ListView } export default initFactory(listView, { name: 'listView' })
JavaScript
0
@@ -672,60 +672,8 @@ ) %7B%0A - // XXX: works only with %22native%22 type definitions%0A re @@ -2870,46 +2870,8 @@ ) %7B%0A - ValType = resolver.resolve(ValType)%0A co @@ -3813,16 +3813,18 @@ tView, %7B +%0A name: ' @@ -3832,12 +3832,81 @@ istView' - +,%0A%0A prepare (Type, resolver) %7B%0A return resolver.resolve(Type)%0A %7D%0A %7D)%0A
c59b53ffa3d47f2cbbd3763d55aa473112cba250
Fix invalid source map for imported files in transformer-less
packages/pundle-transformer-less/src/index.js
packages/pundle-transformer-less/src/index.js
// @flow import path from 'path' import { createFileTransformer, loadLocalFromContext } from 'pundle-api' import manifest from '../package.json' function createComponent({ extensions = ['.less'], options = {} }: { extensions?: Array<string>, options?: Object } = {}) { return createFileTransformer({ name: 'pundle-transformer-less', version: manifest.version, priority: 2000, async callback({ file, context }) { const extName = path.extname(file.filePath) if (!extensions.includes(extName)) return null const { name, exported } = loadLocalFromContext(context, ['less']) if (!name) { throw new Error(`'less' not found in '${context.config.rootDirectory}'`) } const processed = await exported.render(typeof file.contents === 'string' ? file.contents : file.contents.toString(), { sourceMap: {}, paths: [path.dirname(file.filePath)], ...options, }) return { contents: processed.css, sourceMap: JSON.parse(processed.map), } }, }) } module.exports = createComponent
JavaScript
0
@@ -850,67 +850,54 @@ -sourceMap: %7B%7D,%0A paths: %5Bpath.dirname(file.filePath)%5D +filename: file.filePath,%0A sourceMap: %7B%7D ,%0A
2d25b1d0f23b9b55f1e3369f6e6250339eca71bc
Update index.js
packages/strapi/lib/middlewares/cron/index.js
packages/strapi/lib/middlewares/cron/index.js
'use strict'; /** * Module dependencies */ // Public node modules. const _ = require('lodash'); const cron = require('node-schedule'); /** * CRON hook */ module.exports = strapi => { return { /** * Initialize the hook */ initialize() { if (strapi.config.get('server.cron.enabled', false) === true) { _.forEach(_.keys(strapi.config.get('functions.cron', {})), taskExpression => { const taskValue = strapi.config.functions.cron[taskExpression]; const isFunctionValue = _.isFunction(taskValue); if (isFunctionValue) { cron.scheduleJob(taskExpression, strapi.config.functions.cron[taskExpression]); return; } const options = _.get(strapi.config.functions.cron[taskExpression], 'options', {}); cron.scheduleJob( { rule: taskExpression, ...options, }, strapi.config.functions.cron[taskExpression]['task'] ); }); } }, }; };
JavaScript
0.000002
@@ -489,16 +489,17 @@ ssion%5D;%0A +%0A @@ -504,87 +504,35 @@ -const isFunctionValue = _.isFunction(taskValue);%0A%0A if (isFunctionValue +if (_.isFunction(taskValue) ) %7B%0A @@ -535,32 +535,39 @@ ) %7B%0A +return cron.scheduleJob @@ -587,74 +587,18 @@ on, -strapi.config.functions.cron%5BtaskExpression%5D);%0A%0A return +taskValue) ;%0A @@ -644,52 +644,17 @@ get( -strapi.config.functions.cron%5BtaskExpression%5D +taskValue , 'o @@ -803,60 +803,22 @@ -strapi.config.functions.cron%5BtaskExpression%5D%5B' +taskValue. task -'%5D %0A
96e33f7179bcc9f651633da0321cad2679f390dc
fix display when last_delete is null
assets/settings.js
assets/settings.js
import Banner from '../components/Banner.html'; (function(){ if(!('fetch' in window)){ return; } let status_timeout = null; let settings_section = document.querySelector('#settings-section'); let form = document.forms.settings; let backoff_level = 0; let banner_el = document.querySelector('.main-banner'); banner_el.innerHTML = ''; let banner = new Banner({ target: banner_el, }); function hide_status(){ status_display.classList.remove('error', 'success', 'saving'); status_display.classList.add('hidden'); status_display.innerHTML=''; } function show_error(){ hide_status(); status_display.textContent='Could not save. Retrying...'; status_display.classList.add('error'); status_display.classList.remove('hidden'); } function show_success(){ hide_status(); status_display.textContent='Saved!'; status_display.classList.add('success'); status_display.classList.remove('hidden'); } function show_still_saving(){ status_display.textContent='Still saving...'; } function show_saving(){ hide_status(); status_display.textContent='Saving...'; status_display.classList.add('saving'); status_display.classList.remove('hidden'); status_timeout = setTimeout(show_still_saving, 5000); } function save(){ hide_status(); clearTimeout(status_timeout); status_timeout = setTimeout(show_saving, 70); let promise = send_settings(get_all_inputs()) .then(() => { show_success(); clearTimeout(status_timeout); status_timeout = setTimeout(hide_status, 3000); backoff_level = 0; }); promise.catch(() => { show_error(); clearTimeout(status_timeout); status_timeout = setTimeout(save, Math.pow(2, backoff_level)*1000); backoff_level += 1; backoff_level = Math.min(backoff_level, 5); }); promise.then(fetch_viewer).then(update_viewer); // remove server-rendered banner let banner = settings_section.querySelector('.banner'); if(banner){ settings_section.removeChild(banner); } } function get_all_inputs(){ let o = Object(); for(let input of form.elements){ if(input.type != 'radio' || input.checked){ o[input.name] = input.value; } } return o; } function send_settings(body){ return fetch('/api/settings', { method:'PUT', credentials:'same-origin', headers: { 'content-type': 'application/json', }, body: JSON.stringify(body) }) .then(resp => { if(!resp.ok){ return Promise.reject(resp); } return resp; }) .then(resp => resp.json()) .then(data => { if(data.status == 'error'){ return Promise.reject(data); } return data; }); } for(let input of form.elements){ input.addEventListener('change', save); } // remove submit button since we're doing live updates let submit = form.querySelector('input[type=submit]'); form.removeChild(submit); let status_display = document.createElement('span'); status_display.classList.add('status-display', 'hidden'); settings_section.insertBefore(status_display, settings_section.childNodes[0]); // silently send_settings in case the user changed settings while the page was loading send_settings(get_all_inputs()); let viewer_update_interval = 500; function fetch_viewer(){ viewer_update_interval *= 2; viewer_update_interval = Math.min(30000, viewer_update_interval); return fetch('/api/viewer', { credentials: 'same-origin', }) .then(resp => { if(!resp.ok){ return Promise.reject(resp); } return resp; }) .then(resp => resp.json()); } let last_viewer = {}; function update_viewer(viewer){ if(last_viewer == JSON.stringify(viewer)){ return; } last_viewer = JSON.stringify(viewer); document.querySelector('#post-count').textContent = viewer.post_count; document.querySelector('#eligible-estimate').textContent = viewer.eligible_for_delete_estimate; document.querySelector('#display-name').textContent = viewer.display_name || viewer.screen_name; document.querySelector('#display-name').title = '@' + viewer.screen_name; document.querySelector('#avatar').src = viewer.avatar_url; viewer_update_interval = 500; viewer.next_delete = new Date(viewer.next_delete); viewer.last_delete = new Date(viewer.last_delete); banner.set(viewer); } update_viewer(JSON.parse(document.querySelector('script[data-viewer]').textContent)) function set_viewer_timeout(){ setTimeout(() => fetch_viewer().then(update_viewer).then(set_viewer_timeout, set_viewer_timeout), viewer_update_interval); } set_viewer_timeout(); banner.on('toggle', enabled => { send_settings({policy_enabled: enabled}).then(fetch_viewer).then(update_viewer); // TODO show error or spinner if it takes over a second }) })();
JavaScript
0.000004
@@ -4796,24 +4796,60 @@ val = 500;%0A%0A + if(viewer.next_delete)%7B%0A view @@ -4887,32 +4887,78 @@ r.next_delete);%0A + %7D%0A if(viewer.last_delete)%7B%0A viewer.l @@ -4992,32 +4992,42 @@ r.last_delete);%0A + %7D%0A banner.s
c2013197f946f1a65b42a30f66645aae3b216d25
update viewer immediately after enabling/disabling
assets/settings.js
assets/settings.js
import Banner from '../components/Banner.html'; (function(){ if(!('fetch' in window)){ return; } let status_timeout = null; let settings_section = document.querySelector('#settings-section'); let form = document.forms.settings; let backoff_level = 0; let banner_el = document.querySelector('.main-banner'); banner_el.innerHTML = ''; let banner = new Banner({ target: banner_el, }); function hide_status(){ status_display.classList.remove('error', 'success', 'saving'); status_display.classList.add('hidden'); status_display.innerHTML=''; } function show_error(){ hide_status(); status_display.textContent='Could not save. Retrying...'; status_display.classList.add('error'); status_display.classList.remove('hidden'); } function show_success(){ hide_status(); status_display.textContent='Saved!'; status_display.classList.add('success'); status_display.classList.remove('hidden'); } function show_still_saving(){ status_display.textContent='Still saving...'; } function show_saving(){ hide_status(); status_display.textContent='Saving...'; status_display.classList.add('saving'); status_display.classList.remove('hidden'); status_timeout = setTimeout(show_still_saving, 5000); } function save(){ hide_status(); clearTimeout(status_timeout); status_timeout = setTimeout(show_saving, 70); let promise = send_settings(get_all_inputs()) .then(() => { show_success(); clearTimeout(status_timeout); status_timeout = setTimeout(hide_status, 3000); backoff_level = 0; }); promise.catch(() => { show_error(); clearTimeout(status_timeout); status_timeout = setTimeout(save, Math.pow(2, backoff_level)*1000); backoff_level += 1; backoff_level = Math.min(backoff_level, 5); }); promise.then(fetch_viewer).then(update_viewer); // remove server-rendered banner let banner = settings_section.querySelector('.banner'); if(banner){ settings_section.removeChild(banner); } } function get_all_inputs(){ let o = Object(); for(let input of form.elements){ if(input.type != 'radio' || input.checked){ o[input.name] = input.value; } } return o; } function send_settings(body){ return fetch('/api/settings', { method:'PUT', credentials:'same-origin', headers: { 'content-type': 'application/json', }, body: JSON.stringify(body) }) .then(resp => { if(!resp.ok){ return Promise.reject(resp); } return resp; }) .then(resp => resp.json()) .then(data => { if(data.status == 'error'){ return Promise.reject(data); } return data; }); } for(let input of form.elements){ input.addEventListener('change', save); } // remove submit button since we're doing live updates let submit = form.querySelector('input[type=submit]'); form.removeChild(submit); let status_display = document.createElement('span'); status_display.classList.add('status-display', 'hidden'); settings_section.insertBefore(status_display, settings_section.childNodes[0]); // silently send_settings in case the user changed settings while the page was loading send_settings(get_all_inputs()); let viewer_update_interval = 500; function fetch_viewer(){ viewer_update_interval *= 2; viewer_update_interval = Math.min(30000, viewer_update_interval); return fetch('/api/viewer', { credentials: 'same-origin', }) .then(resp => { if(!resp.ok){ return Promise.reject(resp); } return resp; }) .then(resp => resp.json()); } let last_viewer = {}; function update_viewer(viewer){ if(last_viewer == JSON.stringify(viewer)){ return; } last_viewer = JSON.stringify(viewer); document.querySelector('#post-count').textContent = viewer.post_count; document.querySelector('#eligible-estimate').textContent = viewer.eligible_for_delete_estimate; document.querySelector('#display-name').textContent = viewer.display_name || viewer.screen_name; document.querySelector('#display-name').title = '@' + viewer.screen_name; document.querySelector('#avatar').src = viewer.avatar_url; viewer_update_interval = 500; viewer.next_delete = new Date(viewer.next_delete); viewer.last_delete = new Date(viewer.last_delete); banner.set(viewer); } update_viewer(JSON.parse(document.querySelector('script[data-viewer]').textContent)) function set_viewer_timeout(){ setTimeout(() => fetch_viewer().then(update_viewer).then(set_viewer_timeout, set_viewer_timeout), viewer_update_interval); } set_viewer_timeout(); banner.on('toggle', enabled => { send_settings({policy_enabled: enabled}); // TODO show error or spinner if it takes over a second }) })();
JavaScript
0
@@ -5340,16 +5340,55 @@ nabled%7D) +.then(fetch_viewer).then(update_viewer) ;%0A
17570bc3907d47f4b653ea695da85e0492d9bec3
Fix how we assert mappPagesToSelect results
src/app/global/PreviewNav.test.js
src/app/global/PreviewNav.test.js
import React from 'react'; import { shallow } from 'enzyme'; import { PreviewNav } from './PreviewNav'; let dispatchedActions = []; const defaultProps = { preview: {}, dispatch: action => dispatchedActions.push(action), workingOn: { id: "test-collection", }, rootPath: "/florence" } const pages = [ { "uri": "/test-uri", "type": "bulletin", "description": { "title": "Test title", "edition": "Edition", "language": "English" } }, { "uri": "/test-uri2", "type": "bulletin", "description": { "title": "Test title 2", "edition": "", } }, { "uri": "/test-uri3", "type": "bulletin", "description": { "title": "", "edition": "Edition 3", } } ] const component = shallow( <PreviewNav {...defaultProps} /> ); test("Map pages to select component", () => { const pagesResult = component.instance().mapPagesToSelect(pages); expect(pagesResult).toContainEqual( {id: "/test-uri", name: "Test title: Edition"}, {id: "/test-uri2", name: "Test title 2"}, {id: "/test-uri3", name: "Test title 3"} ) }) describe("Creating page title", () => { it("with title and edition", () => { const pageTitle = component.instance().createPageTitle(pages[0]); expect(pageTitle).toBe("Test title: Edition") }); it("with title but not an edition", () => { const pageTitle = component.instance().createPageTitle(pages[1]); expect(pageTitle).toBe("Test title 2") }); it("with edition but no title", () => { const pageTitle = component.instance().createPageTitle(pages[2]); expect(pageTitle).toBe("[no title available]: Edition 3") }); }); describe("Handle select", () => { it("does nothing when default option selected", () => { component.instance().handleSelectChange({target: {value: "default-option"}}) expect(dispatchedActions.length).toBe(0) }) it("routes to selected page on page selection", () => { component.instance().handleSelectChange({target: {value: "/test-uri"}}) expect(dispatchedActions[1].type).toBe("@@router/CALL_HISTORY_METHOD"); expect(dispatchedActions[1].payload.method).toBe("push"); expect(dispatchedActions[1].payload.args[0]).toBe("/florence/collections/test-collection/preview?url=/test-uri"); }) })
JavaScript
0
@@ -1082,34 +1082,27 @@ sult +%5B0%5D ).to -ContainEqual(%0A +MatchObject( %7Bid: @@ -1143,26 +1143,59 @@ dition%22%7D -, +) %0A - +expect(pagesResult%5B1%5D).toMatchObject( %7Bid: %22/t @@ -1230,19 +1230,51 @@ 2%22%7D -, +) %0A - +expect(pagesResult%5B2%5D).toMatchObject( %7Bid: @@ -1299,31 +1299,41 @@ e: %22 -Test +%5Bno title -3%22%7D%0A +available%5D: Edition 3%22%7D )%0A%7D)
a7d351a760ba3915e4341bdfc114f5e6ea32e259
fix genotype index filter, closes #289
src/webcomponents/commons/forms/select-field-filter.js
src/webcomponents/commons/forms/select-field-filter.js
/** * Copyright 2015-2019 OpenCB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {LitElement, html} from "lit"; import UtilsNew from "../../../core/utilsNew.js"; import LitUtils from "../utils/lit-utils.js"; // TODO reorganize props multiple/forceSelection /** NOTE - Design choice: to allow deselection, the single mode (this.multiple=false), has been implemented with the multiple flag in bootstrap-select, but forcing 1 selection with data-max-options=1 * (this has no consequences for the developer point of view). This behaviour can be over overridden using "forceSelection" prop. * * NOTE putting names in data-content attr instead of as <option> content itself allows HTML entities to be correctly decoded. * * Usage: * <select-field-filter .data="${["A","B","C"]}" .value=${"A"} @filterChange="${e => console.log(e)}"></select-field-filter> * <select-field-filter .data="${[{id: "a", name: "A"}, {id:"b", name: "B"}, {id: "c", name: "C"}]}" .value=${"a"} @filterChange="${e => console.log(e)}"></select-field-filter> */ export default class SelectFieldFilter extends LitElement { constructor() { super(); // Set status and init private properties this._init(); } createRenderRoot() { return this; } static get properties() { return { // NOTE value (default Values) can be either a single value as string or a comma separated list (in case of multiple=true we support array of strings) value: { type: String }, placeholder: { type: String }, multiple: { type: Boolean }, disabled: { type: Boolean }, required: { type: Boolean }, maxOptions: { type: Number }, liveSearch: { type: Boolean }, forceSelection: { type: Boolean }, classes: { type: String }, size: { type: Number, }, // the expected format is either an array of string or an array of objects {id, name} data: { type: Object } }; } _init() { this._prefix = UtilsNew.randomString(8); this.multiple = false; this.data = []; this.classes = ""; this.elm = this._prefix + "selectpicker"; this.size = 20; // Default size } firstUpdated() { this.selectPicker = $("#" + this.elm, this); this.selectPicker.selectpicker("val", ""); } updated(changedProperties) { if (changedProperties.has("data")) { // TODO check why lit-element execute this for all existing select-field-filter instances..wtf this.data = this.data ?? []; this.selectPicker.selectpicker("refresh"); } if (changedProperties.has("value")) { let val = ""; if (this.value) { if (this.multiple) { if (Array.isArray(this.value)) { val = this.value; } else { val = this.value.split(","); } } else { val = this.value; } } this.selectPicker.selectpicker("val", val); } if (changedProperties.has("disabled")) { this.selectPicker.selectpicker("refresh"); } if (changedProperties.has("classes")) { if (this.classes) { this.selectPicker.selectpicker("setStyle", this.classes, "add"); } else { // if classes os removed then we need to removed the old assigned classes this.selectPicker.selectpicker("setStyle", changedProperties.get("classes"), "remove"); this.selectPicker.selectpicker("setStyle", "btn-default", "add"); } } } filterChange(e) { const selection = this.selectPicker.selectpicker("val"); let val; if (selection && selection.length) { if (this.multiple) { val = selection.join(","); } else { if (this.forceSelection) { // single mode that DOESN'T allow deselection // forceSelection means multiple flag in selectpicker is false, this is the only case `selection` is not an array val = selection; } else { // single mode that allows deselection val = selection[0]; } } } LitUtils.dispatchEventCustom(this, "filterChange", val || null, null, { data: this.data, }); } render() { return html` <div id="${this._prefix}-select-field-filter-wrapper" class="select-field-filter"> <select id="${this.elm}" class="${this.elm}" ?multiple="${!this.forceSelection}" ?disabled="${this.disabled}" ?required="${this.required}" data-live-search="${this.liveSearch ? "true" : "false"}" data-size="${this.size}" title="${this.placeholder ?? (this.multiple ? "Select option(s)" : "Select an option")}" data-max-options="${!this.multiple ? 1 : this.maxOptions ? this.maxOptions : false}" @change="${this.filterChange}" data-width="100%" data-style="btn-default ${this.classes}"> ${this.data?.map(opt => html` ${opt?.separator ? html` <option data-divider="true"></option> ` : html` ${opt?.fields ? html` <optgroup label="${opt.id ?? opt.name}"> ${opt.fields.map(subopt => html` ${UtilsNew.isObject(subopt) ? html` <option ?disabled="${subopt.disabled}" ?selected="${subopt.selected}" .value="${subopt.id ?? subopt.name}" data-content="${subopt.name}"> </option> ` : html` <option>${subopt}</option> `} `)} </optgroup> ` : html` ${UtilsNew.isObject(opt) ? html` <option ?disabled="${opt.disabled}" ?selected="${opt.selected}" .value="${opt.id ?? opt.name}" data-content="${opt.name ?? opt.id}"> </option> ` : html` <option data-content="${opt}">${opt}</option> `} `} `} `)} </select> </div> `; } } customElements.define("select-field-filter", SelectFieldFilter);
JavaScript
0
@@ -5449,16 +5449,51 @@ +%7D, %7Bbubbles: false, composed: false %7D);%0A @@ -6858,33 +6858,32 @@ %3Coption - %0A @@ -7637,17 +7637,16 @@ %3Coption - %0A
d10ccceae7a3985cd2b591a20e19603fe04e3d02
use a per Trait Timer
lib/behaviour/traits/showcase/jumpingcrate.js
lib/behaviour/traits/showcase/jumpingcrate.js
(function () { // Jump all 5 seconds. var jumpTimer = new Bloob.Timer(5); Bloob.Trait.Repository.add("showcase/jumpingcrate", function jump(entity) { if(jumpTimer.get() > 0) { jumpTimer.reset(); var body = entity.getBody(); body.addGlobalForce(body.getDerivedPosition().add(new Jello.Vector2(0.1, 0)), new Jello.Vector2(0, 1000)); } // add additional force, if clicked on crate if(entity.isClicked()) { var body = entity.getBody(); body.addGlobalForce(body.getDerivedPosition().add(new Jello.Vector2(0.1, 0)), new Jello.Vector2(1000, 0)); } else if(entity.isHovered()) { // add additional force, if hovered over crate var body = entity.getBody(); body.addGlobalForce(body.getDerivedPosition().add(new Jello.Vector2(0.1, 0)), new Jello.Vector2(0, 100)); } }); })();
JavaScript
0
@@ -13,73 +13,8 @@ %7B%0D%0A -%09// Jump all 5 seconds.%0D%0A%09var jumpTimer = new Bloob.Timer(5);%0D%0A%0D%0A %09Blo @@ -89,19 +89,166 @@ y) %7B%0D%0A%09%09 -if( +// lazy initialization%0D%0A%09%09if(typeof this.jumpTimer === %22undefined%22)%0D%0A%09%09%09// Jump all 5 seconds.%0D%0A%09%09%09this.jumpTimer = new Bloob.Timer(5);%0D%0A%0D%0A%09%09if(this. jumpTime @@ -266,16 +266,21 @@ ) %7B%0D%0A%09%09%09 +this. jumpTime @@ -440,16 +440,20 @@ ;%0D%0A%09%09%7D%0D%0A +%09%09%0D%0A %09%09// add
4fc7d0b7a0560b39a57341aafa299886f01b5829
Fix error notifications
src/browser/extension/background/messaging.js
src/browser/extension/background/messaging.js
import { onConnect, onMessage, sendToTab } from 'crossmessaging'; import updateState from 'remotedev-app/lib/store/updateState'; import syncOptions from '../options/syncOptions'; import openDevToolsWindow from './openWindow'; let panelConnections = {}; let tabConnections = {}; let catchedErrors = {}; let monitors = 0; let isMonitored = false; window.syncOptions = syncOptions(toAllTabs); // Used in the options page const naMessage = { type: 'NA' }; function initPanel(msg, port) { monitorInstances(true); panelConnections[msg.tabId] = port; if (msg.tabId !== store.id) return naMessage; } function getId(port) { return port.sender.tab ? port.sender.tab.id : port.sender.id; } function initInstance(msg, port) { const id = getId(port); tabConnections[id] = port; store.liftedStore.instances[id] = msg.instance; store.id = id; if (typeof id === 'number') chrome.pageAction.show(id); if (isMonitored) return { type: 'START' }; } function disconnect(port) { if (!port.sender.tab && !port.sender.id) { monitorInstances(false); return; } const id = getId(port); delete tabConnections[id]; if (panelConnections[id]) panelConnections[id].postMessage(naMessage); if (window.store.liftedStore.instances[id]) { delete window.store.liftedStore.instances[id]; window.store.liftedStore.deleteInstance(id); } } onConnect(undefined, { INIT_PANEL: initPanel, INIT_INSTANCE: initInstance, RELAY: (msg, port) => { messaging(msg.message, port.sender); } }, panelConnections, disconnect); function handleInstancesChanged(instance, name) { window.store.liftedStore.instances[instance] = name || instance; } // Receive message from content script function messaging(request, sender, sendResponse) { const tabId = sender.tab ? sender.tab.id : sender.id; if (tabId) { if (request.type === 'GET_OPTIONS') { window.syncOptions.get(options => { sendResponse({options: options}); }); return true; } if (request.type === 'OPEN') { let position = 'devtools-left'; if (['remote', 'panel', 'left', 'right', 'bottom'].indexOf(request.position) !== -1) position = 'devtools-' + request.position; openDevToolsWindow(position); return true; } if (request.type === 'ERROR') { chrome.notifications.create('app-error', { type: 'basic', title: 'An error occurred in the app', message: request.message, iconUrl: 'img/logo/48x48.png', isClickable: false }); return true; } request.id = tabId; const payload = updateState(store, request, handleInstancesChanged, store.liftedStore.instance); if (!payload) return true; // Relay the message to the devTools panel if (tabId in panelConnections) { panelConnections[tabId].postMessage(request); } // Notify when errors occur in the app window.syncOptions.get(options => { if (!options.notifyErrors) return; const error = payload.computedStates[payload.currentStateIndex].error; if (error === 'Interrupted by an error up the chain') return; if (error) { chrome.notifications.create('redux-error', { type: 'basic', title: 'An error occurred in the reducer', message: error, iconUrl: 'img/logo/48x48.png', isClickable: true }); if (typeof store.id === 'number') { chrome.pageAction.setIcon({tabId: store.id, path: 'img/logo/error.png'}); catchedErrors.tab = store.id; } } else if (catchedErrors.last && typeof store.id === 'number' && catchedErrors.tab === store.id) { chrome.pageAction.setIcon({tabId: store.id, path: 'img/logo/38x38.png'}); } catchedErrors.last = error; }); } return true; } onMessage(messaging); chrome.notifications.onClicked.addListener(id => { chrome.notifications.clear(id); if (id === 'redux-error') openDevToolsWindow('devtools-right'); }); export function toContentScript(action) { const message = { type: 'DISPATCH', action: action }; let id = store.liftedStore.instance; if (!id || id === 'auto') id = store.id; if (id in panelConnections) { panelConnections[id].postMessage(message); } else { tabConnections[id].postMessage(message); } } function toAllTabs(msg) { Object.keys(tabConnections).forEach(id => { tabConnections[id].postMessage(msg); }); } function monitorInstances(shouldMonitor) { if ( !shouldMonitor && monitors !== 0 || isMonitored === shouldMonitor ) return; toAllTabs({ type: shouldMonitor ? 'START' : 'STOP' }); isMonitored = shouldMonitor; } const unsubscribeMonitor = (unsubscribeList) => () => { monitors--; unsubscribeList.forEach(unsubscribe => { unsubscribe(); }); if (Object.getOwnPropertyNames(panelConnections).length === 0) { monitorInstances(false); } }; // Expose store to extension's windows (monitors) window.getStore = () => { monitors++; monitorInstances(true); let unsubscribeList = []; return { store: { ...store, liftedStore: { ...store.liftedStore, subscribe(...args) { const unsubscribe = store.liftedStore.subscribe(...args); unsubscribeList.push(unsubscribe); return unsubscribe; } } }, unsubscribe: unsubscribeMonitor(unsubscribeList) }; };
JavaScript
0.000004
@@ -2966,21 +2966,29 @@ const -error +computedState = paylo @@ -3031,16 +3031,85 @@ teIndex%5D +;%0A if (!computedState) return;%0A const error = computedState .error;%0A
09e97ddb319bb99fc099f197743e0d9606379402
Put the type extraction route in place but only if the command line is right
lib/modules/apostrophe-documentation/index.js
lib/modules/apostrophe-documentation/index.js
var _ = require('lodash'); var fs = require('fs'); // Assists in generating documentation for A2 module.exports = { enabled: false, construct: function(self, options) { if (!options.enabled) { return; } self.route('get', 'scripts', function(req, res) { req.scene = 'user'; return self.sendPage(req, 'scripts', {}); }); self.apos.tasks.add('apostrophe-documentation', 'extract-moog-types', function(callback) { console.log('Fetching server side definitions'); fs.writeFileSync(self.apos.rootDir + '/data/server-types.json', JSON.stringify(self.apos.synth.definitions)); console.log('Fetching browser side definitions'); self.apos.options.afterListen = function() { console.log('in afterListen'); return require('child_process').exec('phantomjs ' + __dirname + '/phantomjs-print-definitions.js', function(err, stdout, stderr) { if (err) { throw err; } fs.writeFileSync(self.apos.rootDir + '/data/browser-types.json', stdout); process.exit(0); }); }; self.apos.listen(); }); } };
JavaScript
0
@@ -176,56 +176,226 @@ -if (!options.enabled) %7B%0A return;%0A %7D%0A +// Routes have to be added before tasks get executed, but we don't%0A // want this route in place when we're not running the task%0A if (self.apos.argv._%5B0%5D === 'apostrophe-documentation:extract-moog-types') %7B%0A + self @@ -446,16 +446,18 @@ %7B%0A + req.scen @@ -470,24 +470,26 @@ ser';%0A + + return self. @@ -518,24 +518,26 @@ ', %7B%7D);%0A + %7D);%0A self @@ -524,24 +524,30 @@ ;%0A %7D);%0A + %7D%0A self.apo
8bff0e876faaa259c8ba0194e3c8186c6b3de887
Remove the need for getRootModelClass()
lib/queryBuilder/graphUpserter/UpsertGraph.js
lib/queryBuilder/graphUpserter/UpsertGraph.js
'use strict'; const keyBy = require('lodash/keyBy'); const difference = require('lodash/difference'); const RelationExpression = require('../RelationExpression'); const UpsertNode = require('./UpsertNode'); const isSqlite = require('../../utils/knexUtils').isSqlite; const asArray = require('../../utils/objectUtils').asArray; // Given an upsert model graph, creates a set of nodes that describe what to do // to each individual model in the graph. node.types returns the needed actions // (any of insert, relate, update, delete and unrelate). This class determines // the needed actions by fetching the current state of the graph from the // database. Only ids and foreign keys needed by the relations are fetched. class UpsertGraph { constructor(upsert, opt) { this.upsert = asArray(upsert); this.rootModelClass = getRootModelClass(upsert); this.relExpr = RelationExpression.fromGraph(upsert); this.nodes = []; // Keys are upsert models and values are corresponding nodes. this.nodesByUpsert = new Map(); this.opt = opt || {}; } build(builder) { return this.fetchCurrentState(builder).then(currentState => this.buildGraph(currentState)); } // Fetches the current state of the graph from the database. This method // only fetches ids and all foreign keys needed by the relations. fetchCurrentState(builder) { const rootIds = getRootIds(this.upsert); const rootIdCols = builder.fullIdColumnFor(this.rootModelClass); const allowedExpr = builder.allowedUpsertExpression(); const oldContext = builder.context(); if (allowedExpr && !allowedExpr.isSubExpression(this.relExpr)) { throw builder .modelClass() .createValidationError({allowedRelations: 'trying to upsert an unallowed relation'}); } if (rootIds.length === 0) { return Promise.resolve([]); } return builder .modelClass() .query() .childQueryOf(builder, true) .whereInComposite(rootIdCols, rootIds) .eager(this.relExpr) .internalOptions({ keepImplicitJoinProps: true }) .mergeContext({ onBuild(builder) { // There may be an onBuild hook in the old context. if (oldContext.onBuild) { oldContext.onBuild(builder); } const idColumn = builder.fullIdColumnFor(builder.modelClass()); builder.select(idColumn); } }); } buildGraph(current) { this.doBuildGraph(this.rootModelClass, this.upsert, current, null, this.relExpr); } doBuildGraph(modelClass, upsert, current, parentNode, relExpr) { this.buildGraphArray( modelClass, ensureArray(upsert), ensureArray(current), parentNode, relExpr ); } buildGraphArray(modelClass, upsert, current, parentNode, relExpr) { const idProp = modelClass.getIdPropertyArray(); const upsertById = keyBy(upsert, model => model.$propKey(idProp)); const currentById = keyBy(current, model => model.$propKey(idProp)); upsert.forEach(upsert => { const key = upsert.$propKey(idProp); const current = currentById[key]; this.buildGraphSingle(modelClass, upsert, current, parentNode, relExpr); }); current.forEach(current => { const key = current.$propKey(idProp); const upsert = upsertById[key]; if (!upsert) { this.buildGraphSingle(modelClass, upsert, current, parentNode, relExpr); } }); } buildGraphSingle(modelClass, upsert, current, parentNode, relExpr) { if (!upsert && !current) { return; } const node = new UpsertNode(parentNode, relExpr, upsert, current, this.opt); this.nodes.push(node); if (upsert) { this.nodesByUpsert.set(upsert, node); } if (parentNode) { parentNode.relations[relExpr.name] = parentNode.relations[relExpr.name] || []; parentNode.relations[relExpr.name].push(node); } // No need to build the graph down from a deleted node. if (node.upsertModel === null) { return; } relExpr.forEachChildExpression(modelClass.getRelations(), (expr, relation) => { const relUpsert = upsert && upsert[relation.name]; const relCurrent = current && current[relation.name]; this.doBuildGraph(relation.relatedModelClass, relUpsert, relCurrent, node, expr); }); } } function getRootModelClass(graph) { if (Array.isArray(graph)) { return graph[0].constructor; } else { return graph.constructor; } } function getRootIds(graph) { return asArray(graph) .filter(it => it.$hasId()) .map(root => root.$id()); } function ensureArray(item) { if (item && !Array.isArray(item)) { return [item]; } else if (!item) { return []; } else { return item; } } module.exports = UpsertGraph;
JavaScript
0.000002
@@ -825,33 +825,34 @@ s = -getRootModelClass(upsert) +this.upsert%5B0%5D.constructor ;%0A @@ -4352,155 +4352,8 @@ %0A%7D%0A%0A -function getRootModelClass(graph) %7B%0A if (Array.isArray(graph)) %7B%0A return graph%5B0%5D.constructor;%0A %7D else %7B%0A return graph.constructor;%0A %7D%0A%7D%0A%0A func
7fbd16b29573ed16c274da82fa3d23e38a7fb1d4
use context
src/commands/Worldstate/ConclaveChallenges.js
src/commands/Worldstate/ConclaveChallenges.js
'use strict'; const Command = require('../../models/Command.js'); const ConclaveChallengeEmbed = require('../../embeds/ConclaveChallengeEmbed.js'); const values = ['all', 'day', 'week']; /** * Displays the currently active Invasions */ class ConclaveChallenges extends Command { /** * Constructs a callable command * @param {Genesis} bot The bot object */ constructor(bot) { super(bot, 'warframe.worldstate.conclaveChallenges', 'conclave', 'Gets the current conclave challenges for a category of challenge, or all.'); this.regex = new RegExp(`^${this.call}(?:\\s+(${values.join('|')}))?(?:\\s+on\\s+([pcsxb14]{2,3}))?$`, 'i'); this.usages = [ { description: 'Display conclave challenges for a challenge type.', parameters: ['conclave category'], }, ]; } async run(message) { const matches = message.strippedContent.match(this.regex); const param1 = (matches[1] || '').toLowerCase(); const param2 = (matches[2] || '').toLowerCase(); const category = values.indexOf(param1) > -1 ? param1 : 'all'; let platformParam; if (this.platforms.indexOf(param2) > -1) { platformParam = param2; } else if (this.platforms.indexOf(param1) > -1) { platformParam = param1; } const platform = platformParam || await this.settings.getChannelSetting(message.channel, 'platform'); const ws = await this.bot.worldStates[platform.toLowerCase()].getData(); const { conclaveChallenges } = ws; const embed = new ConclaveChallengeEmbed(this.bot, conclaveChallenges, category, platform); await this.messageManager.embed(message, embed, true, false); return this.messageManager.statuses.SUCCESS; } } module.exports = ConclaveChallenges;
JavaScript
0.99865
@@ -834,16 +834,21 @@ (message +, ctx ) %7B%0A @@ -1311,74 +1311,19 @@ %7C%7C -await this.settings.getChannelSetting(message.channel, 'platform') +ctx.context ;%0A
723a6fb603c36258411d2149a0be4ab8c4eb27f4
Fix bad Autocomplete component import
src/common/field/mixin/built-in-components.js
src/common/field/mixin/built-in-components.js
// Dependencies import React, {PropTypes} from 'react'; import find from 'lodash/collection/find'; import result from 'lodash/object/result'; import assign from 'object-assign'; import {addRefToPropsIfNotPure, INPUT, DISPLAY} from '../../../utils/is-react-class-component'; // Components import AutocompleteSelectComponent from '../../../components/input/autocomplete-select/field'; import AutocompleteTextComponent from '../../../components/input/autocomplete-text/field'; import InputText from '../../../components/input/text'; import {component as DisplayText} from '../../display/text'; import SelectClassic from '../../../components/input/select'; import {component as Label} from '../../label'; import Autocomplete from '../../autocomplete/field'; // Mixins import fieldGridBehaviourMixin from '../../mixin/field-grid-behaviour'; const fieldBuiltInComponentsMixin = { mixins: [fieldGridBehaviourMixin], getDefaultProps() { return { /** * Does the component has a Label. * @type {Boolean} */ hasLabel: true, /** * Redefine complety the component. * @type {Object} */ FieldComponent: undefined, /** * Redefine only the input and label component. * @type {Object} */ InputLabelComponent: undefined, /** * Component for the input. * @type {Object} */ InputComponent: InputText, /** * Autocomplete component * @type {Object} */ AutocompleteComponent: Autocomplete, AutocompleteSelectComponent, AutocompleteTextComponent, /** * Component for the select. * @type {Object} */ SelectComponent: SelectClassic, /** * Component for the display. * @type {Object} */ DisplayComponent: DisplayText, /** * Component for the label. * @type {Object} */ LabelComponent: Label }; }, /** @inheriteDoc */ propTypes: { AutocompleteComponent: PropTypes.func, AutocompleteSelectComponent: PropTypes.func, DisplayComponent: PropTypes.func, FieldComponent: PropTypes.func, InputComponent: PropTypes.func, InputLabelComponent: PropTypes.func, LabelComponent: PropTypes.func, SelectComponent: PropTypes.func, hasLabel: PropTypes.bool, labelSize: PropTypes.number }, _buildStyle() { let {style} = this.props; style = style || {}; style.className = style && style.className ? style.className : ''; return style; }, /** * Render the label part of the component. * @returns {Component} - The builded label component. */ label() { const {name, label, LabelComponent, domain} = this.props; return ( <div className ={`${this._getLabelGridClassName()}`} data-focus='field-label-container' > <LabelComponent domain={domain} name={name} text={label} /> </div> ); }, /** * Rendet the input part of the component. * @return {Component} - The constructed input component. */ input() { const {name: id, placeholder} = this.props; const {value, error} = this.state; const {onInputChange: onChange} = this; const inputBuildedProps = { ...this.props, id, onChange, value, error, placeholder }; const finalInputProps = addRefToPropsIfNotPure(this.props.InputComponent, inputBuildedProps, INPUT) return <this.props.InputComponent {...finalInputProps}/>; }, /** * Autocomplete render * @return {JSX} rendered component */ autocomplete() { const {name: id, placeholder} = this.props; const {value, error} = this.state; const {onInputChange: onChange} = this; const inputBuildedProps = { ...this.props, id, onChange, value, error, placeholder }; const finalInputProps = addRefToPropsIfNotPure(this.props.AutocompleteComponent.component, inputBuildedProps, INPUT); return <this.props.AutocompleteComponent {...finalInputProps}/>; }, autocompleteSelect() { const {name: id, label: placeHolder} = this.props; const {value} = this.state; const {onInputChange: onChange} = this; const inputBuildedProps = { ...this.props, id, onChange, value, placeHolder }; const finalInputProps = addRefToPropsIfNotPure(this.props.AutocompleteSelectComponent, inputBuildedProps, INPUT) return <this.props.AutocompleteSelectComponent {...finalInputProps}/>; }, autocompleteText() { const {name: id, label: placeHolder} = this.props; const {value} = this.state; const {onInputChange: onChange} = this; const inputBuildedProps = { ...this.props, id, onChange, value, placeHolder }; const finalInputProps = addRefToPropsIfNotPure(this.props.AutocompleteTextComponent, inputBuildedProps, INPUT) return <this.props.AutocompleteTextComponent {...finalInputProps}/>; }, /** * Build a select component depending on the domain, definition and props. * @return {Component} - The builded select component. */ select() { const {error, value} = this.state; const buildedSelectProps = { ...this.props, value, style: this._buildStyle(), onChange: this.onInputChange, error }; const finalSelectProps = addRefToPropsIfNotPure(this.props.SelectComponent, buildedSelectProps, INPUT); return <this.props.SelectComponent {...finalSelectProps} />; }, /** * Render the display part of the component. * @return {object} - The display part of the compoennt if the mode is not edit. */ display() { const {value} = this.state; const {name, valueKey, labelKey, values} = this.props; const _processValue = values ? result(find(values, {[valueKey || 'code']: value}), labelKey || 'label') : value; const buildedDislplayProps = { ...this.props, id: name, style: this._buildStyle(), value: _processValue }; const finalDisplayProps = addRefToPropsIfNotPure(this.props.DisplayComponent, buildedDislplayProps, DISPLAY); return <this.props.DisplayComponent {...finalDisplayProps}/>; }, /** * Render the error part of the component. * @return {object} - The error part of the component. */ error() { let {error} = this.state; if (error) { return ( <span className='mdl-textfield__error'> {error} </span> ); } }, /** * Render the help component. * @return {object} - The help part of the component. */ help() { let {help, name} = this.props; if (help) { return ( <label className='mdl-textfield__label' htmFor={`${name}`} > {help} </label> ); } }, /** * Render the field component if it is overriden in the component definition. * @return {Component} - The builded field component. */ _renderFieldComponent() { const FieldComponent = this.props.FieldComponent || this.props.InputLabelComponent; const {value, error} = this.state; const buildedProps = { ...this.props, id: this.props.name, value: value, error: error, onChange: this.onInputChange }; const finalBuildedProps = addRefToPropsIfNotPure(this.props.FieldComponent, buildedProps, INPUT); return <FieldComponent {...finalBuildedProps} />; } }; export default fieldBuiltInComponentsMixin;
JavaScript
0.000003
@@ -695,32 +695,46 @@ /label';%0Aimport +%7Bcomponent as Autocomplete fro @@ -729,16 +729,17 @@ complete +%7D from '.
80117210001318240d2795bbadedd745f7f86299
deploy sign tx form styling
src/components/tx/SendTx/SignTx/SignTxForm.js
src/components/tx/SendTx/SignTx/SignTxForm.js
import React from 'react'; import { trimEnd } from 'lodash'; import { Button, ButtonGroup, IdentityIcon, Input } from 'emerald-js-ui'; import { ArrowRight } from 'emerald-js-ui/lib/icons3'; import { required } from 'lib/validators'; import { Divider } from 'material-ui'; import { List, ListItem } from 'material-ui/List'; import muiThemeable from 'material-ui/styles/muiThemeable'; import { Form, Row, styles } from '../../../../elements/Form'; import { Currency } from '../../../../lib/currency'; const HorizontalAddressWithIdentity = (props) => { return ( <div style={{display: 'flex', alignItems: 'center', flexDirection: 'column', justifyContent: 'center'}}> <IdentityIcon size={60} id={props.accountId} /> <div style={{paddingTop: '10px'}}>{props.accountId}</div> </div> ); }; const passwordFields = (props) => { if (props.useLedger) { return null; } return ( <Row> <div style={styles.left}> <div style={styles.fieldName}> Password </div> </div> <div style={styles.right}> <Input name="password" type="password" onChange={props.onChange} style={{ minWidth: '600px' }} hintText="Enter your Password" underlineShow={false} fullWidth={true} /> </div> </Row> ); }; const displayFlexCenter = { display: 'flex', justifyContent: 'center', alignItems: 'center', }; const TypedData = (props) => { const { typedData } = props; if (!typedData) { return null; } const listStyle = { cursor: 'default', }; const listProps = { disableTouchRipple: true, hoverColor: 'transparent', autoGenerateNestedIndicator: false, initiallyOpen: true, }; const getNestedItems = () => { return typedData.get('argsDefaults').toJS().map((item, i) => { return ( <ListItem key={i} {...listProps} style={listStyle} primaryText={item.name} secondaryText={item.value} /> ); }); }; return ( <div> <List> <ListItem {...listProps} style={listStyle} primaryText="Method to be called" secondaryText={typedData.get('name')} /> <ListItem {...listProps} style={listStyle} primaryText="Params" nestedItems={getNestedItems()}/> </List> </div> ); }; const getTypedDataOrDeploy = (props) => { if (props.mode === 'contract_function') { return ( <React.Fragment> <Divider style={{ marginTop: '35px' }} />, <TypedData typedData={props.typedData} />, <Divider style={{ marginTop: '35px' }} />, </React.Fragment> ); } if (props.mode === 'contract_constructor') { return ( <React.Fragment> <h3>Contract Deploy</h3>, <Divider style={{ marginTop: '35px' }} />, </React.Fragment> ); } }; const SignTx = muiThemeable()((props) => { const { value, fiatRate, fiatCurrency, txFee, tx } = props; const { onCancel, onChangePassword, onSubmit, useLedger, typedData } = props; const onChange = (event, val) => { onChangePassword(val); }; // const USDValue = Currency.format(Currency.convert(tx.amount, fiatRate, 2), fiatCurrency); return ( <div> <div style={{ display: 'flex', justifyContent: 'center', paddingTop: '50px' }}> <HorizontalAddressWithIdentity accountId={tx.from} /> <div style={{ display: 'flex', alignItems: 'center', flexDirection: 'column', justifyContent: 'space-between' }}> <div style={{ ...displayFlexCenter, flexDirection: 'column' }}> {/* <div>{USDValue} USD</div> */} <div style={{fontSize: '28px'}}>{tx.amount} {tx.token}</div> </div> <div style={{display: 'flex'}}> <ArrowRight /> </div> </div> <HorizontalAddressWithIdentity accountId={tx.to} /> </div> <div style={{ paddingTop: '35px', display: 'flex', justifyContent: 'center' }}> <span style={{ color: props.muiTheme.palette.secondaryTextColor }}> Plus {txFee} ETC for {tx.gasLimit} GAS. </span> </div> { getTypedDataOrDeploy(props) } <Form style={{ marginTop: '0' }}> {passwordFields({...props, onChange})} <Row> <div style={styles.left} /> <div style={{ paddingTop: '10px', ...styles.right }}> <ButtonGroup> <Button label="Cancel" onClick={onCancel} /> <Button primary label="Sign & Send Transaction" onClick={onSubmit} /> </ButtonGroup> </div> </Row> </Form> </div> ); }); export default SignTx;
JavaScript
0.000001
@@ -544,16 +544,56 @@ s) =%3E %7B%0A + if (props.hide) %7B%0A return null%0A %7D%0A return @@ -2506,25 +2506,24 @@ '35px' %7D%7D /%3E -, %0A %3CTy @@ -2556,25 +2556,24 @@ ypedData%7D /%3E -, %0A %3CDi @@ -2602,33 +2602,32 @@ op: '35px' %7D%7D /%3E -, %0A %3C/React.F @@ -2743,32 +2743,33 @@ %3C -h3%3EContract Deploy%3C/h3%3E, +div%3ECONTRACT DEPLOY%3C/div%3E %0A @@ -2814,17 +2814,16 @@ x' %7D%7D /%3E -, %0A %3C @@ -3204,16 +3204,54 @@ rrency); +%0A const hideAccounts = tx.to === '0'; %0A%0A retu @@ -3410,16 +3410,35 @@ x.from%7D +hide=%7BhideAccounts%7D /%3E%0A @@ -3791,24 +3791,48 @@ e=%7B%7Bdisplay: + hideAccounts ? 'none' : 'flex'%7D%7D%3E%0A @@ -3946,16 +3946,35 @@ %7Btx.to%7D +hide=%7BhideAccounts%7D /%3E%0A
890183cc91b7c1bb426413071ffc00cb82f76b73
Change port from 8443 to 443
src/config/zoomdata-connections/production.js
src/config/zoomdata-connections/production.js
import { map } from 'mobx'; export const server = { credentials: map(), application: { secure: true, host: 'live.zoomdata.com', path: '/zoomdata', port: 8443 }, oauthOptions: { client_id: 'bmh0c2FfY2xpZW50MTQ1ODA2NzM4MTE3NDdkNzAxZGIzLTA3MDMtNDk4Mi1iNThiLTQ4NzU2OTZkOTYwNw==', redirect_uri: 'http://demos.zoomdata.com/nhtsa-dashboard-2.2/index.html', auth_uri: 'https://live.zoomdata.com/zoomdata/oauth/authorize', scope: ['read'] } }; server.credentials = map({ key: '58cbe712e4b0336a00f938d7' });
JavaScript
0.000011
@@ -187,17 +187,16 @@ port: -8 443%0A
970b60841a05762d471ff7ead5867385a7c8312e
Add new action
system_user/system_user_manager/system_user_manager.js
system_user/system_user_manager/system_user_manager.js
"use strict"; //load the application configuration var app_config = require ('./public/javascript/application_config.js'); // Loading and initializing the library: var pgp = require('pg-promise')({ // Initialization Options }); // Preparing the connection details: // Need to change var cn = 'postgres://' + app_config.db_login + ':' + app_config.db_password + '@' + app_config.db_host + ':' + app_config.db_port + '/' + app_config.database_name; // Creating a new database instance from the connection details: var db = pgp(cn); module.exports = function system_user_manager( options ) { var seneca = this; var promise = require('bluebird'); var role_name = 'system_user_manager' // Set top-level options for API var options = seneca.util.deepextend({ promiseLib: promise, prefix: '/system_user_manager/' }); // Here are the system_user_manager API definitions this.add({role:'system_user_manager', cmd:'test'}, test); this.add({role:'system_user_manager', cmd:'get_one_row'}, get_one_row); this.add({role:'system_user_manager', cmd:'add_one_user'}, function (msg, respond) { db.func('system_user_schema.action_add_new_user', msg._in_data) .then(function (data) { respond (null, data); }) .catch(function (error) { console.log("ERROR:", error.message || error); // print the error; }); }); this.add({role:'system_user_manager', cmd:'user_login'}, function (msg, respond) { //console.log ('In user_login'); //console.log (msg._in_data); db.func('system_user_schema.action_user_login', msg._in_data) .then(function (data) { //console.log("DATA:", data); // print data; respond (null, data); }) .catch(function (error) { console.log("ERROR:", error.message || error); // print the error; }); }); //user_logout this.add({role:'system_user_manager', cmd:'user_logout'}, function (msg, respond) { db.func('system_user_schema.action_user_logout', msg._in_data) .then(function (data) { //console.log("DATA:", data); // print data; respond (null, data); }) .catch(function (error) { console.log("ERROR:", error.message || error); // print the error; }); }); //change_password this.add({role:'system_user_manager', cmd:'change_password'}, function (msg, respond) { db.func('system_user_schema.action_change_password', msg._in_data) .then(function (data) { //console.log("DATA:", data); // print data; respond (null, data); }) .catch(function (error) { console.log("ERROR:", error.message || error); // print the error; }); }); //change_user_allowed_actions this.add({role:'system_user_manager', cmd:'change_user_allowed_actions'}, function (msg, respond) { db.func('system_user_schema.action_change_user_allowed_actions', msg._in_data) .then(function (data) { //console.log("DATA:", data); // print data; respond (null, data); }) .catch(function (error) { console.log("ERROR:", error.message || error); // print the error; }); }); // list_users this.add({role:'system_user_manager', cmd:'list_users'}, function (msg, respond) { db.func('system_user_schema.action_list_users', msg._in_data) .then(function (data) { //console.log("DATA:", data); // print data; respond (null, data); }) .catch(function (error) { console.log("ERROR:", error.message || error); // print the error; }); }); this.add( {init:'system_user_manager'}, function init( args, done ) { setTimeout( function() { done(); }, 10000 ); }); // END ( {init:'system_user_manager'} function test(args, done) { done(null, {working:true}); }; function get_one_row (args, done) { var result = db.any("SELECT * FROM system_users", [true]) .then (function (data) { done(null, data); }) .catch (function (error) { console.log("ERROR:", error); // print the error; }); }; /* function add_one_user (args, done) { console.log ('In add_one_user'); console.log (_in_data); db.func('action_add_new_user', [_in_data]) .then(function (data) { console.log("DATA:", data); // print data; }) .catch(function (error) { console.log("ERROR:", error.message || error); // print the error; }); };*/ }; // END module.exports = function system_user_manager( options )
JavaScript
0.000003
@@ -3457,24 +3457,445 @@ %09%7D);%0D%0A%09%7D);%0D%0A +%0D%0A// list_user_actions%0D%0A%09this.add(%7Brole:'system_user_manager', cmd:'list_user_actions'%7D, function (msg, respond) %7B%0D%0A %09%09db.func('system_user_schema.action_list_actions_for_a_user', msg._in_data)%0D%0A%09%09.then(function (data) %7B%0D%0A%09%09%09//console.log(%22DATA:%22, data); // print data;%0D%0A%09%09%09respond (null, data);%0D%0A%09%09%7D)%0D%0A%09%09.catch(function (error) %7B%0D%0A%09%09%09console.log(%22ERROR:%22, error.message %7C%7C error); // print the error;%0D%0A%09%09%7D);%0D%0A%09%7D);%0D%0A%09%0D%0A%0D%0A %09%0D%0A%09this.add
90a7356e8fa00e2378980a25247bdc7f7d4d5ef8
fix data not set in interceptedview's cardview
src/foam/u2/crunch/CapabilityInterceptView.js
src/foam/u2/crunch/CapabilityInterceptView.js
/** * @license * Copyright 2020 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.u2.crunch', name: 'CapabilityInterceptView', extends: 'foam.u2.View', implements: [ 'foam.mlang.Expressions' ], requires: [ 'foam.log.LogLevel', 'foam.nanos.crunch.AgentCapabilityJunction', 'foam.nanos.crunch.Capability', 'foam.nanos.crunch.CapabilityJunctionStatus', 'foam.nanos.crunch.UserCapabilityJunction', 'foam.u2.crunch.CapabilityCardView', 'foam.u2.layout.Rows' ], imports: [ 'capabilityCache', 'capabilityDAO', 'crunchController', 'notify', 'stack', 'subject', 'userCapabilityJunctionDAO' ], properties: [ { name: 'capabilityView', class: 'foam.u2.ViewSpec', factory: function () { return 'foam.u2.crunch.CapabilityCardView'; } }, { name: 'onClose', class: 'Function', factory: () => (x) => { x.closeDialog(); } } ], messages: [ { name: 'REJECTED_MSG', message: 'Your choice to bypass this was stored, please refresh page to revert cancel selection.' } ], css: ` ^detail-container { overflow-y: scroll; } ^ > *:not(:last-child) { margin-bottom: 24px !important; } `, methods: [ function initE() { this.data.capabilityOptions.forEach((c) => { if ( this.capabilityCache.has(c) && this.capabilityCache.get(c) ) { this.aquire(); } }); var self = this; this .addClass(this.myClass()) .start(this.Rows) .addClass(this.myClass('detail-container')) .add(this.slot(function (data$capabilityOptions) { return this.E().select(this.capabilityDAO.where( self.IN(self.Capability.ID, data$capabilityOptions) ), (cap) => { return this.E().tag(self.capabilityView, { data: cap }) .on('click', () => { var p = self.crunchController.launchWizard(cap); p.then(() => { this.checkStatus(cap); }) }) }) })) .end() .startContext({ data: this }) .tag(this.CANCEL, { buttonStyle: 'SECONDARY' }) .endContext(); }, function checkStatus(cap) { // Query UCJ status var associatedEntity = cap.associatedEntity === foam.nanos.crunch.AssociatedEntity.USER ? this.subject.user : this.subject.realUser; this.userCapabilityJunctionDAO.where( this.AND( this.OR( this.AND( this.NOT(this.INSTANCE_OF(this.AgentCapabilityJunction)), this.EQ(this.UserCapabilityJunction.SOURCE_ID, associatedEntity.id) ), this.AND( this.INSTANCE_OF(this.AgentCapabilityJunction), this.EQ(this.UserCapabilityJunction.SOURCE_ID, associatedEntity.id), this.EQ(this.AgentCapabilityJunction.EFFECTIVE_USER, this.subject.user.id) ) ), this.EQ(this.UserCapabilityJunction.TARGET_ID, cap.id) ) ).limit(1).select(this.PROJECTION( this.UserCapabilityJunction.STATUS )).then(results => { if ( results.array.length < 1 ) { this.reject(); return; } var entry = results.array[0]; // limit 1 var status = entry[0]; // first field (status) switch ( status ) { case this.CapabilityJunctionStatus.GRANTED: this.aquire(); break; default: this.reject(); break; } }); }, function aquire(x) { x = x || this.__subSubContext__; this.data.aquired = true; this.data.capabilityOptions.forEach((c) => { this.capabilityCache.set(c, true); }); this.onClose(x); }, function reject(x) { x = x || this.__subSubContext__; this.data.cancelled = true; this.data.capabilityOptions.forEach((c) => { this.capabilityCache.set(c, true); }); this.notify(this.REJECTED_MSG, '', this.LogLevel.INFO, true); this.onClose(x); } ], actions: [ { name: 'cancel', label: 'Not interested in adding this functionality', code: function(x) { this.reject(x); } } ] });
JavaScript
0
@@ -749,173 +749,8 @@ %7B%0A - name: 'capabilityView',%0A class: 'foam.u2.ViewSpec',%0A factory: function () %7B%0A return 'foam.u2.crunch.CapabilityCardView';%0A %7D%0A %7D,%0A %7B%0A @@ -1770,17 +1770,17 @@ ag(self. -c +C apabilit @@ -1780,16 +1780,20 @@ pability +Card View, %7B%0A
34580932cb5e18b4e8df4aec85d8470e3114a1b2
Fix for creating paygroup without tax rule
main/app/lib/collections/schemas/paygroups.js
main/app/lib/collections/schemas/paygroups.js
/** * Order Types Schema */ Core.Schemas.PayGroup = new SimpleSchema({ _id: { type: String, optional: true }, code: { type: String }, name: { type: String }, businessId: { type: String }, tax: { type: String }, pension: { type: String, optional: true }, status: { type: String, defaultValue: "Active" }, createdAt: { type: Date, autoValue: function () { if (this.isInsert) { return new Date; } else if (this.isUpsert) { return { $setOnInsert: new Date }; } }, denyUpdate: true, optional: true } });
JavaScript
0
@@ -279,32 +279,56 @@ type: String +,%0A optional: true %0A %7D,%0A pens
68629ee5a11a0fe505e0864009226c6e1e5d22ae
Fix offset for jumpToElement module
assets/src/javascript/modules/jumpToElement.js
assets/src/javascript/modules/jumpToElement.js
/* eslint-disable */ import jump from 'jump.js'; /* eslint-enable */ // Listen for clicks on this trigger class name const JUMP_TRIGGER_CLASS = '.js-jump'; // Enabling A11Y will add tabindex and focus on the target. We disable it by default, because // it could cause scroll jumping const ENABLE_A11Y = false; // Get all triggers const jumpElements = document.querySelectorAll(JUMP_TRIGGER_CLASS); const jumpElementsArr = Array.prototype.slice.call(jumpElements); export default { /** * Loop through elements, and create event listeners for every element * @return {Void} */ initialize() { jumpElementsArr.forEach(this.createEvent.bind(this)); }, /** * Create event listener for the given element * @param {Node} el Element to listen for clicks * @return {Void} */ createEvent(el) { el.addEventListener('click', (e) => { e.preventDefault(); const target = el.dataset.jumpTarget; const offset = this.verifyOffset(el.dataset.jumpOffset); // Ensure that element exists if (!document.querySelector(target)) { return; } this.handleJump(target, offset); }); }, /** * Jump to the target element with a optional offset * @param {String} target Target selector * @param {Number} offset Offset for the scroll (for fixed navigation bars etc.) * @return {Void} */ handleJump(target, offset) { jump(target, { offset, a11y: ENABLE_A11Y, }); }, /** * Verify that the offset is correct, and if it's a string we are going to use that * as a selector and get the height * @param {Number/String} offset Offset in pixels or a selector * @return {Number} Offset in pixels */ verifyOffset(offset) { if (typeof offset === 'undefined') { return 0; } else if (isNaN(parseInt(offset, 10))) { return this.getOffsetFromElement(offset); } return parseInt(offset, 10); }, /** * Get the offset by measuring the given element * @param {String} selector Selector to measure the height of * @return {Number} Height of the element in pixels */ getOffsetFromElement(selector) { const targetEl = document.querySelector(selector); if (!targetEl) { return 0; } return targetEl.clientHeight; }, };
JavaScript
0
@@ -2312,16 +2312,21 @@ ntHeight + * -1 ;%0A %7D,%0A%7D
19c71e5e10957520845c940ede630343699637fa
Migrate leaflet.mesure
mapentity/static/mapentity/leaflet-measure.js
mapentity/static/mapentity/leaflet-measure.js
L.Polyline.Measure = L.Draw.Polyline.extend({ addHooks: function() { L.Handler.Draw.prototype.addHooks.call(this); if (this._map) { this._markerGroup = new L.LayerGroup(); this._map.addLayer(this._markerGroup); this._markers = []; this._map.on('click', this._onClick, this); this._startShape(); } }, removeHooks: function () { L.Handler.Draw.prototype.removeHooks.call(this); this._clearHideErrorTimeout(); //!\ Still useful when control is disabled before any drawing (refactor needed?) this._map.off('mousemove', this._onMouseMove); this._clearGuides(); this._container.style.cursor = ''; this._removeShape(); this._map.removeLayer(this._markerGroup); delete this._markerGroup; delete this._markers; this._map.off('click', this._onClick); }, _startShape: function() { this._drawing = true; this._poly = new L.Polyline([], this.options.shapeOptions); this._container.style.cursor = 'crosshair'; this._updateTooltip(); this._map.on('mousemove', this._onMouseMove, this); }, _finishShape: function () { this._drawing = false; this._cleanUpShape(); this._updateTooltip(); this._map.off('mousemove', this._onMouseMove); this._clearGuides(); this._container.style.cursor = ''; }, _removeShape: function() { this._map.removeLayer(this._poly); delete this._poly; this._markers.splice(0); this._markerGroup.clearLayers(); }, _onClick: function(e) { if (!this._drawing) { this._removeShape(); this._startShape(); return; } L.Draw.Polyline.prototype._onClick.call(this, e); }, _getTooltipText: function() { var labelText = L.Draw.Polyline.prototype._getTooltipText.call(this); if (!this._drawing) { labelText.text = ''; } return labelText; } }); L.Control.Measurement = L.Control.extend({ static: { TITLE: 'Measure distances' }, options: { position: 'topleft', handler: {} }, initialize: function(options) { L.Util.extend(this.options, options); }, toggle: function() { if (this.handler.enabled()) { this.handler.disable.call(this.handler); L.DomUtil.removeClass(this._container, 'enabled'); } else { this.handler.enable.call(this.handler); L.DomUtil.addClass(this._container, 'enabled'); } }, onAdd: function(map) { var className = 'leaflet-control-draw'; this._container = L.DomUtil.create('div', 'leaflet-bar'); this.handler = new L.Polyline.Measure(map, this.options.handler); var link = L.DomUtil.create('a', className+'-measure', this._container); link.href = '#'; link.title = L.Control.Measurement.TITLE; L.DomEvent .addListener(link, 'click', L.DomEvent.stopPropagation) .addListener(link, 'click', L.DomEvent.preventDefault) .addListener(link, 'click', this.toggle, this); return this._container; } });
JavaScript
0.000001
@@ -72,36 +72,37 @@ %7B%0A L. -Handler.Draw +Draw.Polyline .prototype.a @@ -433,20 +433,21 @@ L. -Handler.Draw +Draw.Polyline .pro @@ -1301,32 +1301,61 @@ _cleanUpShape(); +%0A this._clearGuides(); %0A%0A this._ @@ -1428,37 +1428,14 @@ Move -);%0A this._clearGuides( +, this );%0A @@ -1507,32 +1507,77 @@ e: function() %7B%0A + if (!this._poly)%0A return;%0A this._ma
ae0e0ebcbee10fa883685c92ac1aba7f332a9dee
enable mux test cases
benchmark/cases/transports/transports.bench.js
benchmark/cases/transports/transports.bench.js
const path = require('path'); const clonedeep = require('lodash.clonedeep'); const json = { "service": "tcp://127.0.0.1:1081?forward=127.0.0.1:1083", "server": { "service": "", "key": "secret", "presets": [ { "name": "ss-base" }, ], "tls_cert": path.join(__dirname, "cert.pem"), "tls_key": path.join(__dirname, "key.pem"), "tls_cert_self_signed": true, "mux": false } }; function compile(transport, mux = false) { const _json = clonedeep(json); _json.server.service = transport + '://localhost:1082'; _json.server.mux = mux; return _json; } module.exports = function main() { return { 'tcp': compile('tcp'), // 'tcp + mux': compile('tcp', true), 'tls': compile('tls'), // 'tls + mux': compile('tls', true), 'ws': compile('ws'), // 'ws + mux': compile('ws', true), 'wss': compile('wss'), // 'wss + mux': compile('wss', true), 'h2': compile('h2'), // 'h2 + mux': compile('h2', true), }; };
JavaScript
0.000001
@@ -665,19 +665,16 @@ p'),%0A - // 'tcp + @@ -731,19 +731,16 @@ s'),%0A - // 'tls + @@ -791,27 +791,24 @@ e('ws'),%0A - // 'ws + mux': @@ -859,19 +859,16 @@ s'),%0A - // 'wss +
bdf5f93368f0b4fa018270e245592c6c90c832c5
update blueprint server config
blueprints/ember-eureka/files/config/server.js
blueprints/ember-eureka/files/config/server.js
/* jshint node: true */ var pkg = require('../package.json'); var requireDir = require('require-dir'); var dockerLinks = require('docker-links'); var links = dockerLinks.parseLinks(process.env); var internals = { port: 8888, uploadDirectory: './uploads', endpoint: 'http://<path/to/sparqlendpoint>' // TODO }; if (process.env.NODE_ENV === 'production') { var dbUri = 'http://'+links.db.host + ':' + links.db.port; var virtuosoEndpoint = dbUri + '/sparql'; var blazegraphEndpoint = dbUri + '/bigdata/sparql'; internals.endpoint = virtuosoEndpoint internals.port = 80 internals.uploadDirectory = '/app/uploads'; } var secretInfos = require('./secret.json'); module.exports = { name: pkg.name, host: '0.0.0.0', port: internals.port, app: { secret: secretInfos.secret, email: secretInfos.email, clientRootUrl: 'http://', // TODO apiRootPrefix: '/api/1' }, resources: requireDir('../backend/resources'), publicDirectory: 'dist', fileUploads: { uploadDirectory: internals.uploadDirectory, maxBytes: 50 // 50 MB }, log: ['warn'], database: { config: { graphUri: 'http://<%= dasherizedPackageName %>.com', endpoint: internals.endpoint }, schemas: requireDir('./schemas') }, misc: { // custom config } };
JavaScript
0
@@ -217,109 +217,454 @@ -port: 8888,%0A uploadDirectory: './uploads +database: %7B%0A config: %7B%0A engine: 'virtuoso ',%0A + -endpoint: 'http://%3Cpath/to/sparqlendpoint%3E' // TODO + graphUri: 'http://%3C%25= dasherizedPackageName %25%3E.com',%0A port: 8890,%0A host: 'localhost', // TODO check this%0A auth: %7B%0A user: 'dba',%0A password: 'dba'%0A %7D%0A %7D%0A %7D,%0A redis: %7B%0A port: 6379,%0A host: 'localhost' // TODO check this%0A %7D,%0A port: 8888,%0A uploadDirectory: './uploads' %0A%7D;%0A @@ -714,56 +714,44 @@ ) %7B%0A -%0A -var dbUri = 'http://'+links.db.host + ':' + +internals.database.config.host = lin @@ -760,158 +760,157 @@ .db. -por +hos t;%0A -var virtuosoEndpoint = dbUri + '/sparql';%0A var blazegraphEndpoint = dbUri + '/bigdata/sparql';%0A%0A internals.endpoint = virtuosoEndpoint +internals.database.config.port = links.db.port;%0A%0A internals.redis.port = links.redis.port;%0A internals.redis.host = links.redis.host;%0A %0A @@ -1112,16 +1112,35 @@ s.port,%0A + log: %5B'warn'%5D,%0A app: @@ -1344,16 +1344,59 @@ rces'),%0A + tasks: requireDir('../backend/tasks'),%0A publ @@ -1532,134 +1532,156 @@ -log: %5B'warn'%5D,%0A database: %7B%0A config: %7B%0A graphUri: 'http://%3C%25= dasherizedPackageName %25%3E.com',%0A +database: %7B%0A adapter: 'rdf',%0A config: internals.database.config,%0A schemas: requireDir('./schemas')%0A %7D,%0A redis: %7B%0A endp @@ -1676,23 +1676,19 @@ -endpoin +por t: inter @@ -1696,68 +1696,54 @@ als. -endpoint%0A %7D,%0A schemas: requireDir('./schemas') +redis.port,%0A host: internals.redis.host %0A
082d1a712e3bddb02c226b6ddf947d53764e7105
Refactor to resolve promise
addon/components/course/objective-list.js
addon/components/course/objective-list.js
import Component from '@glimmer/component'; import { tracked } from '@glimmer/tracking'; import { restartableTask } from 'ember-concurrency-decorators'; import { map } from 'rsvp'; import { inject as service } from '@ember/service'; import { use } from 'ember-could-get-used-to-this'; import AsyncProcess from '../../classes/async-process'; import ResolveAsyncValue from '../../classes/resolve-async-value'; import sortableByPosition from 'ilios-common/utils/sortable-by-position'; export default class CourseObjectiveListComponent extends Component { @service store; @service intl; @service dataLoader; @tracked isSorting = false; @use courseObjectivesAsync = new ResolveAsyncValue(() => [ this.args.course.courseObjectives, ]); get courseObjectives() { if (this.load.lastSuccessful && this.courseObjectivesAsync) { return this.courseObjectivesAsync.toArray().sort(sortableByPosition); } return undefined; } @use cohortObjectiveAsync = new AsyncProcess(() => [ this.getCohortObjectives, this.args.course.cohorts, this.intl, ]); get cohortObjectives() { if (!this.load.lastSuccessful) { return null; } return this?.cohortObjectiveAsync; } get courseObjectiveCount() { if (this.courseObjectives) { return this.courseObjectives.length; } return this.args.course.hasMany('courseObjectives').ids().length; } @restartableTask *load() { //pre-load all session data as well to get access to child objectives yield this.dataLoader.loadCourseSessions(this.args.course.id); } async getCohortObjectives(cohorts, intl) { return await map(cohorts.toArray(), async cohort => { const programYear = await cohort.programYear; const program = await programYear.program; const school = await program.school; const allowMultipleCourseObjectiveParents = await school.getConfigValue('allowMultipleCourseObjectiveParents'); const objectives = await programYear.programYearObjectives; const objectiveObjects = await map(objectives.toArray(), async objective => { let competencyId = 0; let competencyTitle = intl.t('general.noAssociatedCompetency'); const competency = await objective.competency; if (competency) { competencyId = competency.id; competencyTitle = competency.title; } return { id: objective.id, title: objective.textTitle, active: objective.active, competencyId, competencyTitle, cohortId: cohort.id, }; }); const competencies = objectiveObjects.reduce((set, obj) => { let existing = set.findBy('id', obj.competencyId); if (!existing) { existing = { id: obj.competencyId, title: obj.competencyTitle, objectives: [] }; set.push(existing); } existing.objectives.push(obj); return set; }, []); return { title: `${program.title} ${cohort.title}`, id: cohort.id, allowMultipleParents: allowMultipleCourseObjectiveParents, competencies, }; }); } }
JavaScript
0
@@ -955,34 +955,287 @@ @use co -hortObjectiveAsync +urseCohortsAsync = new ResolveAsyncValue(() =%3E %5B%0A this.args.course.cohorts,%0A %5D);%0A%0A get courseCohorts() %7B%0A if (this.load.lastSuccessful && this.courseCohortsAsync) %7B%0A return this.courseCohortsAsync.toArray();%0A %7D%0A%0A return %5B%5D;%0A %7D%0A%0A @use cohortObjectives = new A @@ -1289,37 +1289,31 @@ s,%0A this. -args. course -.c +C ohorts,%0A @@ -1902,26 +1902,16 @@ (cohorts -.toArray() , async
f5ca0d98f734215a6258793cbdc991cec515b2f7
add data-title and stroke to arcs
addon/components/plaid-donut/component.js
addon/components/plaid-donut/component.js
import { arc, pie } from 'd3-shape'; import Ember from 'ember'; import layout from './template'; import GroupElement from '../../mixins/group-element'; import { interpolateCool } from 'd3-scale'; const { Component, computed, get, getProperties, run, run: { scheduleOnce } } = Ember; const DonutComponent = Component.extend(GroupElement, { layout, radius: computed('width', 'height', function() { let { width, height } = getProperties(this, 'width', 'height'); return Math.min(width, height) / 2; }), transform: computed('width', 'height', function() { let { width, height } = getProperties(this, 'width', 'height'); return `translate(${width / 2},${height / 2})`; }), innerRadius: computed('radius', function() { return get(this, 'radius') - 32; }), outerRadius: computed('radius', function() { return get(this, 'radius'); }), cornerRadius: 8, colorScale: interpolateCool, padDegrees: 5, onArcClick: null, onArcEnter: null, onArcLeave: null, drawnValues: [], didReceiveAttrs() { this._super(...arguments); scheduleOnce('afterRender', this, this.draw); }, pie: computed('padDegrees', function() { return pie() .padAngle(get(this, 'padDegrees') / 360) .value((d) => d[1]); }), piedValues: computed('pie', 'values.[]', function() { let { values, pie } = getProperties(this, 'values', 'pie'); return pie(values); }), arc: computed('cornerRadius', 'innerRadius', 'outerRadius', function() { let { cornerRadius, innerRadius, outerRadius } = getProperties(this, 'cornerRadius', 'innerRadius', 'outerRadius'); return arc() .cornerRadius(cornerRadius) .innerRadius(innerRadius) .outerRadius(outerRadius); }), draw() { let { piedValues, arc, colorScale } = getProperties(this, 'piedValues', 'arc', 'colorScale'); let arcs = this.selection.selectAll('.arc path'); if (piedValues !== this.drawnValues || piedValues.length !== this.drawnValues.length) { arcs = arcs.data(piedValues).enter() .append('g') .attr('class', 'arc') .append('path') .on('click', (d) => run(this, this.sendAction, 'onArcClick', d.data[0])) .on('mouseenter', (d) => run(this, this.sendAction, 'onArcEnter', d.data[0])) .on('mouseleave', (d) => run(this, this.sendAction, 'onArcLeave', d.data[0])); } arcs .attr('fill', (d) => colorScale(d.data[0])) .attr('d', arc); } }); DonutComponent.reopenClass({ positionalParams: [ 'values' ] }); export default DonutComponent;
JavaScript
0.000001
@@ -2113,16 +2113,64 @@ 'arc')%0A + .attr('data-title', (d) =%3E d.data%5B0%5D)%0A @@ -2509,24 +2509,76 @@ d.data%5B0%5D))%0A + .attr('stroke', (d) =%3E colorScale(d.data%5B0%5D))%0A .attr(
a826651b7d1e0258e7e67f167f6deadc91ec318c
Fix a typo in code documentation
addon/mixins/flexberry-file-controller.js
addon/mixins/flexberry-file-controller.js
/** * @module ember-flexberry */ import Ember from 'ember'; /** * Mixin for {{#crossLink "DS.Controller"}}Controller{{/crossLink}} to support * opening current selected image at flexberry-file at modal window. * * @class Controller * @extends Ember.Mixin * @public */ export default Ember.Mixin.create({ /** * Controller for modal window content. * * @property flexberryFileModalController * @type DS.Controller * @default flexberry-file-view-dialog */ flexberryFileModalController: Ember.inject.controller('flexberry-file-view-dialog'), /** * Name of template for modal window content. * * @property flexberryFileModalTemplateName * @type String * @default `flexberry-file-view-dialog` */ flexberryFileModalTemplateName: 'flexberry-file-view-dialog', /** * Width of modal window. * * @property flexberryFileModalWindowWidth * @type Number * @default 750 */ flexberryFileModalWindowWidth: 750, /** * Height of modal window. * * @property flexberryFileModalWindowHeight * @type Number * @default 600 */ flexberryFileModalWindowHeight: 600, actions: { /** * This method creates modal window to view image preview. * * @method flexberryFileViewImageAction * @public * * @param {Object} selectedFileOptions Information about selected file. * @param {String} [selectedFileOptions.fileSrc] File content to set as source for image tag. * @param {String} [selectedFileOptions.fileName] File name to set as title of modal window. */ flexberryFileViewImageAction: function(selectedFileOptions) { let options = Ember.merge({ fileSrc: undefined, fileName: undefined }, selectedFileOptions); let fileSrc = options.fileSrc; let fileName = options.fileName; let flexberryFileModalTemplateName = this.get('flexberryFileModalTemplateName'); if (!fileSrc || !fileName) { throw new Error('File data are not defined.'); } if (!flexberryFileModalTemplateName) { throw new Error('Template for file modal dialog is not defined'); } let controller = this.get('flexberryFileModalController'); controller.setProperties({ title: fileName, modalWindowHeight: this.get('flexberryFileModalWindowWidth'), modalWindowWidth: this.get('flexberryFileModalWindowHeight'), imageSrc: fileSrc }); this.send('showModalDialog', flexberryFileModalTemplateName, { controller: controller }); }, // TODO: try remove this lookup's logic. /** * Handles correcponding route's willTransition action. * It sends message about transition to showing lookup modal window controller. * * @method routeWillTransition */ routeWillTransition: function() { this.get('flexberryFileModalController').send('routeWillTransition'); } } });
JavaScript
0.999887
@@ -222,16 +222,29 @@ @class +FlexberryFile Controll
734cb50c1997fe3e461a0bd325cf5503a4431ee1
Fix paths for CKEditor config
view/src/main/resources/static/js/configureCkEditor.js
view/src/main/resources/static/js/configureCkEditor.js
// CKEditor incompatibility with jquery and bootstrap $.fn.modal.Constructor.prototype.enforceFocus = function() { modal_this = this; $(document).on('focusin.modal', function (e) { if (modal_this.$element[0] !== e.target && !modal_this.$element.has(e.target).length && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_select') && $(e.target.parentNode).hasClass('cke_contents cke_reset') && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_text')) { modal_this.$element.focus() } }) }; function markEditorDirty(editor) { editor.addClass('editorDirty'); } function countCharacters(input, editor) { if (editor) { if (editor == null || editor.document == null) return 0; if (editor.document['$'].body.textContent) { return jQuery.trim(editor.document['$'].body.textContent).length; } if (editor.document['$'].body.innerText) { return jQuery.trim(editor.document['$'].body.innerText).length; } } return jQuery.trim(input.val().replace(/&lt;[^&gt;]*&gt;/g, "").replace(/\s+/g, " ").length); } function updateCharacterCounter(input, editor) { var max = input.attr('data-characterLimit'); if (input && input.limitCharacterCounter) { var count = countCharacters(input, editor); if (count > 1 * max) { input.limitCharacterCounter.parent().addClass('overflow'); input.addClass('invalid'); } else { input.limitCharacterCounter.parent().removeClass('overflow'); input.removeClass('invalid'); } input.limitCharacterCounter.text(count); // needed for copy from base proposal - hides button when there is content var parent = input.parents('.addpropbox'); if (count > 0) { parent.removeClass('empty').addClass('notempty'); } else { parent.removeClass('notempty').addClass('empty'); } } } function initializeTextEditors() { jQuery("input[type='text'], textarea").each(function() { var element = this; var $element = jQuery(this); if ($element.hasClass('rte-editorInitialized')) { return; } if($element.attr("data-section-placeholder")){ console.log("...." + $element.attr("data-section-placeholder") + "....") if($element.val()== "") { $element.val($element.attr("data-section-placeholder")); } } var limitCharactersMax = $element.parent().find(".limit_charactersMax"); var limitCharacterCount = $element.parent().find(".limit_characterCount"); var countCharacters = limitCharactersMax.length > 0; if (countCharacters) { $element.attr({'data-characterLimit': limitCharactersMax.text(), 'data-validateLength': true}); $element.limitCharacterCounter = limitCharacterCount; updateCharacterCounter($element); } else { $element.attr({'data-validateLength': false}); } if ($element.hasClass("rte-editorPlaceholder")) { var editor = CKEDITOR.replace($element.attr("id"), { customConfig: '${_libJsFolder}/newckeditorplugins/configProposal.js'}); $element.get(0)["ckeditor"] = editor; editor.updatedCharCount = false; function updateEditorCharCount() { try { if (editor == null) return; if (editor && editor.document && editor.document['$'] && (editor.checkDirty() || editor.updatedCharCount)) { markEditorDirty($element); updateCharacterCounter($element, editor); editor.updatedCharCount = true; editor.resetDirty(); } setTimeout(updateEditorCharCount, 1000); } catch (e) { if (typeof(console) != 'undefined' && typeof(console.log) != 'undefined') { console.log(e); } } } // if (! jQuery.browser.ie || jQuery.browser.version.number >= 9) { updateEditorCharCount(); // } editor.on("blur", function() { updateCharacterCounter($element, editor); }); // initiate char counters setTimeout(function() { updateCharacterCounter($element, editor); }, 2000); } else { eventsToBind = { keypress: function(event) { if ($element.attr('data-validateLength') && $element.limitCharacterCounter) { updateCharacterCounter($element); } }, keyup: function(event) { console.log("keypup"); if ($element.attr('data-validateLength') && $element.limitCharacterCounter) { updateCharacterCounter($element); } }, change: function(event) { markEditorDirty($element); } }; $element.bind(eventsToBind); } jQuery(this).addClass('rte-editorInitialized'); }); } jQuery(function() { CKEDITOR.plugins.addExternal( 'proposalLink', '${_libJsFolder}/newckeditorplugins/proposalLink/plugin.js' ); initializeTextEditors(); });
JavaScript
0
@@ -3261,31 +3261,23 @@ onfig: ' -$%7B_libJsFolder%7D +/js/lib /newcked @@ -5450,23 +5450,15 @@ ' -$%7B_libJsFolder%7D +/js/lib /new
bef6ef251a08ba27cfdf99b732901c460ccee72f
call AirTable Post HelperService test
Septa/Controllers/MainController.js
Septa/Controllers/MainController.js
(function () { "use strict"; var MainController = function ($scope, HelperService, TrainViewFactory, $http, $timeout) { var trainno = '1111'; //temp value $scope.ThisTrain = null; var TrainIsLate = false; //default value $scope.isLoading = true; //default value var lightOn = false; $scope.nowHour = moment().hour(); $scope.today_dayOftheWeek = moment().day(); $scope.IsWeekDay = (($scope.today_dayOftheWeek === 0) || ($scope.today_dayOftheWeek === 6)) ? false : true ; $scope.checkTimeSlot = moment($scope.nowHour).isBetween(7, 11) ? 'morning' : 'evening'; // //NOTE : doesn't need to be in init() // function init() { // $scope.ThisTrain = TrainViewFactory.getThisTrain(trainno); // } // init(); if($scope.IsWeekDay){ var myTrains_PromiseReturn = HelperService.getMyTrains(); myTrains_PromiseReturn.then(function (data){ $scope.myTrains = data; // console.log($scope.myTrains.data); // console.log($scope.myTrains.data.records[1].fields.timeSlot); // console.log($scope.myTrains.data.records.length); $scope.TrainForNow = []; //Trains for THIS timeSlot accordingly for(var a=0, len=$scope.myTrains.data.records.length; a<len; a++){ if($scope.myTrains.data.records[a].fields.timeSlot === $scope.checkTimeSlot){ $scope.TrainForNow.push($scope.myTrains.data.records[a].fields.trainno); } }; console.log($scope.TrainForNow); var Trains_PromiseReturn = HelperService.getSeptaTrains(); Trains_PromiseReturn.then(function(data){ var Trains_data = data; var Trains = Trains_data.data; //console.log(Trains); for(var b=0, l=$scope.TrainForNow.length; b<l; b++){ // console.log(Trains); trainno = $scope.TrainForNow[b]; $scope.ThisTrain = TrainViewFactory.getThisTrain(Trains, trainno); // console.log(trainno); // console.log($scope.ThisTrain); if($scope.ThisTrain){ //avoid nulls if($scope.ThisTrain.late > 2){ //train late threshold (in minutes) lightOn = true; TrainIsLate = true; break; }; }; }; //AirTable Update var XX = HelperService.updateAirTable($scope.ThisTrain); console.log(XX); // //Temp - GOOD // $http({ // url : 'https://api.airtable.com/v0/app6bRhZ46dwM5aJJ/LateTrainsLog', // method : 'POST', // headers : { // 'Authorization' : 'Bearer keyDH7kBvN03bIM3o', // 'Content-Type' : 'application/json' // }, // data : { // "fields" : { // "trainno" : $scope.ThisTrain.trainno, // "timeSlot" : $scope.checkTimeSlot, // "howLate" : $scope.ThisTrain.late+' mins.' // } // } // }).then(function SuccesFunc(response) { //handle success // console.log('This is a success '); // }, function ErrorFunc(response) { //handle error // console.log('This is an error '); // }); // // //THIS IS GOOD // if(lightOn){ // //Trigger LittleBits CloudBits // $http({ // url : 'https://api-http.littlebitscloud.cc/devices/00e04c0340b5/output?percent=50&duration_ms=5000', // method : 'POST', // headers : { // 'Authorization' : 'Bearer 75480d214b46ed685b139dc49ddaf7d1cbd0af94f585e31cd5f76ef5d7d908a4', // 'Accept' : 'application/vnd.littlebits.v2+json', // 'Content-Type' : 'application/json' // } // }).then(function SuccesFunc(response) { //handle success // console.log('This is a success '); // }, function ErrorFunc(response) { //handle error // console.log('This is an error '); // }); // // //Trigger IFTTT and Maker to send notification // $http({ // url : 'https://maker.ifttt.com/trigger/TrainCheck/with/key/GJElXrQFbvHcF1OLmCK_S?value1='+$scope.ThisTrain.trainno+'&value2='+$scope.ThisTrain.late, // method : 'POST', // headers : { // 'Content-Type' : 'application/json' // } // }).then(function SuccesFunc(response) { //handle success // console.log('This is a success '); // }, function ErrorFunc(response) { //handle error // console.log('This is an error '); // }); // }; //THIS IS GOOD $timeout(function() { $scope.isLoading = false; $scope.isLate = TrainIsLate; }, 3500); }); }); }; // console.log($scope.nowHour); // console.log($scope.checkTimeSlot); // console.log($scope.IsWeekDay); // console.log($scope.ThisTrain); }; MainController.$inject = ['$scope', 'HelperService', 'TrainViewFactory', '$http', '$timeout']; angular.module('appSepta') .controller('MainController', MainController); }());
JavaScript
0
@@ -2942,17 +2942,8 @@ - var XX = Hel @@ -3011,24 +3011,8 @@ -console.log(XX); %0A
0051fdb77b92d88bff9ab2b40895e2878a22479e
Fix URLs in video specs
Specs/Core/VideoSynchronizerSpec.js
Specs/Core/VideoSynchronizerSpec.js
defineSuite([ 'Core/VideoSynchronizer', 'Core/Clock', 'Core/FeatureDetection', 'Core/Iso8601', 'Core/JulianDate', 'Core/Math', 'Specs/pollToPromise' ], function( VideoSynchronizer, Clock, FeatureDetection, Iso8601, JulianDate, CesiumMath, pollToPromise) { 'use strict'; //Video textures do not work on Internet Explorer if (FeatureDetection.isInternetExplorer()) { return; } function loadVideo() { var element = document.createElement('video'); var source = document.createElement('source'); source.setAttribute('src', './Data/Videos/big-buck-bunny-trailer-small.webm'); source.setAttribute('type', 'video/webm'); element.appendChild(source); source = document.createElement('source'); source.setAttribute('src', './Data/Videos/big-buck-bunny-trailer-small.mp4'); source.setAttribute('type', 'video/mp4'); element.appendChild(source); source = document.createElement('source'); source.setAttribute('src', './Data/Videos/big-buck-bunny-trailer-small.mov'); source.setAttribute('type', 'video/quicktime'); element.appendChild(source); return element; } it('Can default construct', function() { var videoSynchronizer = new VideoSynchronizer(); expect(videoSynchronizer.clock).not.toBeDefined(); expect(videoSynchronizer.element).not.toBeDefined(); expect(videoSynchronizer.epoch).toBe(Iso8601.MINIMUM_VALUE); expect(videoSynchronizer.tolerance).toBe(1.0); expect(videoSynchronizer.isDestroyed()).toBe(false); expect(videoSynchronizer.destroy()).not.toBeDefined(); expect(videoSynchronizer.isDestroyed()).toBe(true); }); it('Can construct with options', function() { var clock = new Clock(); var element = document.createElement('video'); var epoch = new JulianDate(); var tolerance = 0.15; var videoSynchronizer = new VideoSynchronizer({ clock : clock, element : element, epoch : epoch, tolerance: tolerance }); expect(videoSynchronizer.clock).toBe(clock); expect(videoSynchronizer.element).toBe(element); expect(videoSynchronizer.epoch).toBe(epoch); expect(videoSynchronizer.tolerance).toBe(tolerance); expect(videoSynchronizer.isDestroyed()).toBe(false); expect(videoSynchronizer.destroy()).not.toBeDefined(); expect(videoSynchronizer.isDestroyed()).toBe(true); }); it('Syncs time when looping', function() { var epoch = JulianDate.fromIso8601('2015-11-01T00:00:00Z'); var clock = new Clock(); clock.shouldAnimate = false; clock.currentTime = epoch.clone(); var element = loadVideo(); element.loop = true; var videoSynchronizer = new VideoSynchronizer({ clock : clock, element : element, epoch : epoch }); return pollToPromise(function() { clock.tick(); return element.currentTime === 0; }).then(function() { clock.currentTime = JulianDate.addSeconds(epoch, 10, clock.currentTime); return pollToPromise(function() { clock.tick(); return element.currentTime === 10; }); }).then(function() { clock.currentTime = JulianDate.addSeconds(epoch, 60, clock.currentTime); return pollToPromise(function() { clock.tick(); return CesiumMath.equalsEpsilon(element.currentTime, 60 - element.duration, CesiumMath.EPSILON3); }); }).then(function() { clock.currentTime = JulianDate.addSeconds(epoch, -1, clock.currentTime); return pollToPromise(function() { clock.tick(); return CesiumMath.equalsEpsilon(element.currentTime, element.duration - 1, CesiumMath.EPSILON1); }); }).then(function() { videoSynchronizer.destroy(); }); }); it('Syncs time when not looping', function() { var epoch = JulianDate.fromIso8601('2015-11-01T00:00:00Z'); var clock = new Clock(); clock.shouldAnimate = false; clock.currentTime = epoch.clone(); var element = loadVideo(); var videoSynchronizer = new VideoSynchronizer({ clock : clock, element : element, epoch : epoch }); return pollToPromise(function() { clock.tick(); return element.currentTime === 0; }).then(function() { clock.currentTime = JulianDate.addSeconds(epoch, 10, clock.currentTime); return pollToPromise(function() { clock.tick(); return element.currentTime === 10; }); }).then(function() { clock.currentTime = JulianDate.addSeconds(epoch, 60, clock.currentTime); return pollToPromise(function() { clock.tick(); return CesiumMath.equalsEpsilon(element.currentTime, element.duration, CesiumMath.EPSILON3); }); }).then(function() { clock.currentTime = JulianDate.addSeconds(epoch, -1, clock.currentTime); return pollToPromise(function() { clock.tick(); return element.currentTime === 0; }); }).then(function() { videoSynchronizer.destroy(); }); }); it('Plays/pauses video based on clock', function() { var epoch = JulianDate.fromIso8601('2015-11-01T00:00:00Z'); var clock = new Clock(); // Since Chrome doesn't allow video playback without user // interaction, we use a mock element. var element = jasmine.createSpyObj('MockVideoElement', ['addEventListener', 'removeEventListener', 'play', 'pause']); element.paused = false; element.play.and.callFake(function() { this.paused = false; }); element.pause.and.callFake(function() { this.paused = true; }); var videoSynchronizer = new VideoSynchronizer({ clock : clock, element : element, epoch : epoch }); clock.shouldAnimate = false; clock.tick(); expect(element.pause.calls.count()).toEqual(1); clock.shouldAnimate = true; clock.tick(); expect(element.play.calls.count()).toEqual(1); clock.shouldAnimate = false; clock.tick(); expect(element.pause.calls.count()).toEqual(2); videoSynchronizer.destroy(); }); });
JavaScript
0.999596
@@ -675,33 +675,32 @@ tribute('src', ' -. /Data/Videos/big @@ -725,32 +725,32 @@ r-small.webm');%0A + source.s @@ -901,33 +901,32 @@ tribute('src', ' -. /Data/Videos/big @@ -1089,32 +1089,32 @@ ment('source');%0A + source.s @@ -1133,17 +1133,16 @@ 'src', ' -. /Data/Vi
4a3645b3710755967f0797a37c9bbacc20c63763
Add API to unfollow blogs.
api/blogs/follow_blog_by_mail_resource.js
api/blogs/follow_blog_by_mail_resource.js
var resources = require('jest'), util = require('util'), models = require('../../models'), common = require('./../common'), async = require('async'), _ = require('underscore'); var follow_blog_by_mail_resource = module.exports = common.GamificationMongooseResource.extend({ init: function(){ this._super(models.User, null, 0); this.allowed_methods = ['get', 'put']; this.authentication = new common.SessionAuthentication(); this.update_fields = { blog_id: null, mail: null }, this.fields = { is_follower: null } }, update_obj: function (req, object, callback) { var blog_id = req.body.blog_id; var mail = req.body.mail; var blog = _.find(object.blogs_email, function(blog){return blog.mail == mail}); if(blog){ // The blog is already followed. Nothing to do here. } else { //add blog var new_blog = { blog_id: blog_id, mail: mail, join_date: Date.now() } object.blogs_email.push(new_blog); object.save(function(err, obj){ obj.is_follower = true; callback(err, obj); }) } } })
JavaScript
0
@@ -853,38 +853,260 @@ );%0A%0A - +%09%09if (req.body.unfollow) %7B%0A%09%09%09// Unfollow request%0A%09%09%09 if + (blog) + %7B%0A - +%09%09%09%09blog.remove(function(err, res)%7B%0A%09%09%09%09%09if(!err)%7B%0A%09%09%09%09%09%09object.save(function(err, obj)%7B%0A%09%09%09%09%09%09%09obj.is_follower = false;%0A%09%09%09%09%09%09%09callback(err, obj);%0A%09%09%09%09%09%09%7D)%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D)%0A%09%09%09%7D else %7B%0A%09%09%09%09 // T @@ -1124,16 +1124,20 @@ already +not followed @@ -1158,24 +1158,23 @@ o here.%0A - +%09%09%09%7D%0A%09%09 %7D else %7B @@ -1178,43 +1178,130 @@ e %7B%0A - //add blog%0A +%09%09%09// Follow request%0A%09%09%09if(blog)%7B%0A%09%09%09%09// The blog is already followed. Nothing to do here.%0A%09%09%09%7D else %7B%0A%09%09%09%09//add blog%0A%09%09%09%09 var @@ -1313,32 +1313,21 @@ log = %7B%0A - +%09%09%09%09%09 blog_id: @@ -1340,101 +1340,63 @@ id,%0A - mail: mail,%0A join_date: Date.now()%0A %7D%0A%0A +%09%09%09%09%09mail: mail,%0A%09%09%09%09%09join_date: Date.now()%0A%09%09%09%09%7D%0A%0A%09%09%09%09 obje @@ -1426,28 +1426,20 @@ _blog);%0A - +%09%09%09%09 object.s @@ -1462,32 +1462,21 @@ , obj)%7B%0A - +%09%09%09%09%09 obj.is_f @@ -1495,24 +1495,13 @@ ue;%0A - +%09%09%09%09%09 call @@ -1520,31 +1520,22 @@ j);%0A - %7D)%0A +%09%09%09%09%7D)%0A%09%09%09%7D%0A%09%09 %7D%0A
fff8b6b567038580627189e7d35d69d14dfdff56
Add example of custom command query
modules/phenyl-api-explorer/examples/index.js
modules/phenyl-api-explorer/examples/index.js
// @flow import http from 'http' import PhenylRestApi from 'phenyl-rest-api' import { createEntityClient } from 'phenyl-memory-db' import { StandardUserDefinition, StandardEntityDefinition } from 'phenyl-standards' import PhenylHttpServer from 'phenyl-http-server' import PhenylApiExplorer from '../src/PhenylApiExplorer' import type { Session, RequestData } from 'phenyl-interfaces' const PORT = 8000 const memoryClient = createEntityClient() class HospitalDefinition extends StandardEntityDefinition { async authorization(reqData: RequestData, session: ?Session): Promise<boolean> { // eslint-disable-line no-unused-vars return true } } class PatientDefinition extends StandardUserDefinition { constructor() { super({ entityClient: memoryClient, accountPropName: 'email', passwordPropName: 'password', ttl: 24 * 3600 }) } async authorization(reqData, session): Promise<boolean> { switch (reqData.method) { case 'insertOne': case 'insertAndGet': case 'insertAndGetMulti': case 'login': return true default: return session != null } } } const functionalGroup = { customQueries: { }, customCommands: { }, users: { patient: new PatientDefinition(), }, nonUsers: { hospital: new HospitalDefinition({}), }, } const server = new PhenylHttpServer(http.createServer(), { restApiHandler: PhenylRestApi.createFromFunctionalGroup(functionalGroup, { client: memoryClient, }), customRequestHandler: new PhenylApiExplorer(functionalGroup, { path: '/explorer' }).handler, }) server.listen(PORT) console.log(`server is listening on :${PORT}`)
JavaScript
0.000007
@@ -328,16 +328,18 @@ t type %7B +%0A Session @@ -339,16 +339,18 @@ Session, +%0A Request @@ -353,17 +353,146 @@ uestData - +,%0A CustomCommand,%0A CustomCommandDefinition,%0A CustomCommandResult,%0A CustomQuery,%0A CustomQueryDefinition,%0A CustomQueryResult,%0A %7D from ' @@ -1274,79 +1274,1485 @@ %0A%7D%0A%0A -const functionalGroup = %7B%0A customQueries: %7B%0A%0A %7D,%0A customCommands: %7B%0A +type CustomCommandParams = %7B%7C%0A echo: string,%0A%7C%7D%0Atype CustomCommandResponse = %7B%7C%0A echo: string,%0A session: ?Session,%0A%7C%7D%0Aclass TestCustomCommand implements CustomCommandDefinition%3C*, CustomCommandParams, CustomCommandResponse%3E %7B%0A async authorization(command: CustomCommand%3C*, CustomCommandParams%3E, session: ?Session): Promise%3Cboolean%3E %7B%0A return !!session%0A %7D%0A%0A async validation(): Promise%3Cvoid%3E %7B%0A // Does nothing%0A %7D%0A%0A async execution(command: CustomCommand%3C*, CustomCommandParams%3E, session: ?Session): Promise%3CCustomCommandResult%3CCustomCommandResponse%3E%3E %7B%0A return %7B%0A ok: 1,%0A result: %7B%0A echo: command.params.echo,%0A session,%0A %7D%0A %7D%0A %7D%0A%7D%0A%0Atype CustomQueryParams = %7B%7C%0A echo: string,%0A%7C%7D%0Atype CustomQueryResponse = %7B%7C%0A echo: string,%0A session: ?Session,%0A%7C%7D%0Aclass TestCustomQuery implements CustomQueryDefinition%3C*, CustomQueryParams, CustomQueryResponse%3E %7B%0A async authorization(command: CustomQuery%3C*, CustomQueryParams%3E, session: ?Session): Promise%3Cboolean%3E %7B%0A return !!session%0A %7D%0A%0A async validation(): Promise%3Cvoid%3E %7B%0A // Does nothing%0A %7D%0A%0A async execution(command: CustomQuery%3C*, CustomQueryParams%3E, session: ?Session): Promise%3CCustomQueryResult%3CCustomQueryResponse%3E%3E %7B%0A return %7B%0A ok: 1,%0A result: %7B%0A echo: command.params.echo,%0A session,%0A %7D%0A %7D%0A %7D%0A%7D%0A%0Aconst functionalGroup = %7B%0A customQueries: %7B%0A test: new TestCustomCommand(),%0A %7D,%0A customCommands: %7B%0A test: new TestCustomQuery(), %0A %7D