content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
PHP
PHP
fix cs error
323401cf68bb59e046aafbb499e1020c73cc025d
<ide><path>tests/TestCase/Error/DebuggerTest.php <ide> <?php <ide> /** <del>* CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <del>* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del>* <del>* Licensed under The MIT License <del>* For full copyright and license information, please see the LICENSE.txt <del>* Redistributions of files must retain the above copyright notice. <del>* <del>* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del>* @link http://cakephp.org CakePHP Project <del>* @since 1.2.0 <del>* @license http://www.opensource.org/licenses/mit-license.php MIT License <del>*/ <add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * @link http://cakephp.org CakePHP Project <add> * @since 1.2.0 <add> * @license http://www.opensource.org/licenses/mit-license.php MIT License <add> */ <ide> namespace Cake\Test\TestCase\Error; <ide> <ide> use Cake\Controller\Controller; <ide> use Cake\TestSuite\TestCase; <ide> <ide> /** <del>* DebuggerTestCaseDebugger class <del>*/ <add> * DebuggerTestCaseDebugger class <add> */ <ide> class DebuggerTestCaseDebugger extends Debugger <ide> { <ide> }
1
Text
Text
add missing patch
d4b4a7e324058d2a50d51197ddd65338d34e477f
<ide><path>guides/source/getting_started.md <ide> REST convention, so to create a new `Post` object it will look for a <ide> route named `posts_path`, and to update a `Post` object it will look for <ide> a route named `post_path` and pass the current object. Similarly, rails <ide> knows that it should create new objects via POST and update them via <del>PUT. <add>PATCH. <ide> <ide> If you run `rake routes` from the console you'll see that we already <ide> have a `posts_path` route, which was created automatically by Rails when we <ide> received an error before. With your server running you can view your routes by v <ide> ```bash <ide> $ rake routes <ide> <del> posts GET /posts(.:format) posts#index <del>posts_new GET /posts/new(.:format) posts#new <del> POST /posts(.:format) posts#create <del> GET /posts/:id(.:format) posts#show <del> GET /posts/:id/edit(.:format) posts#edit <del> PUT /posts/:id(.:format) posts#update <del> root / welcome#index <add> posts GET /posts(.:format) posts#index <add>posts_new GET /posts/new(.:format) posts#new <add> POST /posts(.:format) posts#create <add> GET /posts/:id(.:format) posts#show <add> GET /posts/:id/edit(.:format) posts#edit <add> PATCH /posts/:id(.:format) posts#update <add> root / welcome#index <ide> ``` <ide> <ide> To fix this, open `config/routes.rb` and modify the `get "posts/:id"` <ide> $ rake routes <ide> new_post GET /posts/new(.:format) posts#new <ide> edit_post GET /posts/:id/edit(.:format) posts#edit <ide> post GET /posts/:id(.:format) posts#show <add> PATCH /posts/:id(.:format) posts#update <ide> PUT /posts/:id(.:format) posts#update <ide> DELETE /posts/:id(.:format) posts#destroy <ide> root / welcome#index
1
Text
Text
fix documentation for joins across clusters
9d4a025be2bb335de7ae2e12a6132d284cb97e21
<ide><path>guides/source/active_record_multiple_databases.md <ide> handles outside of Rails. <ide> <ide> ### Joining Across Databases <ide> <del>Applications cannot join across databases. Rails 6.1 will support using `has_many` <del>relationships and creating 2 queries instead of joining, but Rails 6.0 will require <del>you to split the joins into 2 selects manually. <add>Applications cannot join across databases. At the moment applications will need to <add>manually write two selects and split the joins themselves. In a future version Rails <add>will split the joins for you. <ide> <ide> ### Schema Cache <ide>
1
Text
Text
add setup + tweaks
3b48806f753b41b8d0540e001d4217cdc054b602
<ide><path>examples/pplm/README.md <ide> This folder contains the original code used to run the Plug and Play Language Mo <ide> ![header image](./imgs/headfigure.png) <ide> <ide> ## Plug and Play Language Models: a Simple Approach to Steerable Text Generation <del>Authors: [Sumanth Dathathri](https://dathath.github.io/), Andrea Madotto, Janice Lan, Jane Hung, Eric Frank, [Piero Molino](), [Jason Yosinski](http://yosinski.com/), and [Rosanne Liu](http://www.rosanneliu.com/) <add>Authors: [Sumanth Dathathri](https://dathath.github.io/), Andrea Madotto, Janice Lan, Jane Hung, Eric Frank, [Piero Molino](https://w4nderlu.st/), [Jason Yosinski](http://yosinski.com/), and [Rosanne Liu](http://www.rosanneliu.com/) <ide> <ide> PPLM allows a user to flexibly plug in one or more tiny attribute models representing the desired steering objective into a large, unconditional LM. The method has the key property that it uses the LM _as is_---no training or fine-tuning is required---which enables researchers to leverage best-in-class LMs even if they do not have the extensive hardware required to train them. <ide> <ide> Blog link: https://eng.uber.com/pplm <ide> <ide> <ide> ## Setup <del>TODO <add> <add>```bash <add>git clone https://github.com/huggingface/transformers && cd transformers <add>pip install [--editable] . <add>pip install nltk torchtext # additional requirements. <add>cd examples/pplm <add>``` <ide> <ide> ## PPLM-BoW <ide> <ide> ### Example command for bag-of-words control <del>``` <add> <add>```bash <ide> python run_pplm.py -B space --cond_text "The president" --length 100 --gamma 1.5 --num_iterations 3 --num_samples 1 --stepsize 0.01 --window_length 5 --kl_scale 0.01 --gm_scale 0.95 <ide> ``` <ide> <ide> ### Tuning hyperparameters for bag-of-words control <add> <ide> 1. Increase `--stepsize` to intensify topic control, and decrease its value to soften the control. `--stepsize 0` recovers the original uncontrolled GPT-2 model. <ide> <ide> 2. If the language being generated is repetitive (For e.g. "science science experiment experiment"), there are several options to consider: </br> <ide> python run_pplm.py -B space --cond_text "The president" --length 100 --gamma 1.5 <ide> <ide> <ide> ## PPLM-Discrim <add> <ide> ### Example command for discriminator based sentiment control <del>``` <add> <add>```bash <ide> python run_pplm.py -D sentiment --class_label 3 --cond_text "The lake" --length 10 --gamma 1.0 --num_iterations 10 --num_samples 1 --stepsize 0.03 --kl_scale 0.01 --gm_scale 0.95 <ide> ``` <ide> <ide> ### Tuning hyperparameters for discriminator control <add> <ide> 1. Increase `--stepsize` to intensify topic control, and decrease its value to soften the control. `--stepsize 0` recovers the original uncontrolled GPT-2 model. <ide> <ide> 2. Use `--class_label 3` for negative, and `--class_label 2` for positive <ide> <ide> ### Example command for detoxificiation: <del>python run_pplm.py -D toxicity --length 100 --num_iterations 10 --cond-text 'TH PEOPLEMan goddreams Blacks' --gamma 1.0 --num_samples 10 --stepsize 0.02 <ide> <add>```bash <add>python run_pplm.py -D toxicity --length 100 --num_iterations 10 --cond-text 'TH PEOPLEMan goddreams Blacks' --gamma 1.0 --num_samples 10 --stepsize 0.02 <add>```
1
Javascript
Javascript
remove dormant createbatch experiment
71d012ecd07baef6f53d02bebd720794f75266ca
<ide><path>packages/react-dom/src/__tests__/ReactDOMRoot-test.js <ide> describe('ReactDOMRoot', () => { <ide> expect(container.textContent).toEqual(''); <ide> }); <ide> <del> it('`root.render` returns a thenable work object', () => { <del> const root = ReactDOM.unstable_createRoot(container); <del> const work = root.render('Hi'); <del> let ops = []; <del> work.then(() => { <del> ops.push('inside callback: ' + container.textContent); <del> }); <del> ops.push('before committing: ' + container.textContent); <del> Scheduler.unstable_flushAll(); <del> ops.push('after committing: ' + container.textContent); <del> expect(ops).toEqual([ <del> 'before committing: ', <del> // `then` callback should fire during commit phase <del> 'inside callback: Hi', <del> 'after committing: Hi', <del> ]); <del> }); <del> <del> it('resolves `work.then` callback synchronously if the work already committed', () => { <del> const root = ReactDOM.unstable_createRoot(container); <del> const work = root.render('Hi'); <del> Scheduler.unstable_flushAll(); <del> let ops = []; <del> work.then(() => { <del> ops.push('inside callback'); <del> }); <del> expect(ops).toEqual(['inside callback']); <del> }); <del> <ide> it('supports hydration', async () => { <ide> const markup = await new Promise(resolve => <ide> resolve( <ide> describe('ReactDOMRoot', () => { <ide> expect(container.textContent).toEqual('abdc'); <ide> }); <ide> <del> it('can defer a commit by batching it', () => { <del> const root = ReactDOM.unstable_createRoot(container); <del> const batch = root.createBatch(); <del> batch.render(<div>Hi</div>); <del> // Hasn't committed yet <del> expect(container.textContent).toEqual(''); <del> // Commit <del> batch.commit(); <del> expect(container.textContent).toEqual('Hi'); <del> }); <del> <del> it('applies setState in componentDidMount synchronously in a batch', done => { <del> class App extends React.Component { <del> state = {mounted: false}; <del> componentDidMount() { <del> this.setState({ <del> mounted: true, <del> }); <del> } <del> render() { <del> return this.state.mounted ? 'Hi' : 'Bye'; <del> } <del> } <del> <del> const root = ReactDOM.unstable_createRoot(container); <del> const batch = root.createBatch(); <del> batch.render(<App />); <del> <del> Scheduler.unstable_flushAll(); <del> <del> // Hasn't updated yet <del> expect(container.textContent).toEqual(''); <del> <del> let ops = []; <del> batch.then(() => { <del> // Still hasn't updated <del> ops.push(container.textContent); <del> <del> // Should synchronously commit <del> batch.commit(); <del> ops.push(container.textContent); <del> <del> expect(ops).toEqual(['', 'Hi']); <del> done(); <del> }); <del> }); <del> <del> it('does not restart a completed batch when committing if there were no intervening updates', () => { <del> let ops = []; <del> function Foo(props) { <del> ops.push('Foo'); <del> return props.children; <del> } <del> const root = ReactDOM.unstable_createRoot(container); <del> const batch = root.createBatch(); <del> batch.render(<Foo>Hi</Foo>); <del> // Flush all async work. <del> Scheduler.unstable_flushAll(); <del> // Root should complete without committing. <del> expect(ops).toEqual(['Foo']); <del> expect(container.textContent).toEqual(''); <del> <del> ops = []; <del> <del> // Commit. Shouldn't re-render Foo. <del> batch.commit(); <del> expect(ops).toEqual([]); <del> expect(container.textContent).toEqual('Hi'); <del> }); <del> <del> it('can wait for a batch to finish', () => { <del> const root = ReactDOM.unstable_createRoot(container); <del> const batch = root.createBatch(); <del> batch.render('Foo'); <del> <del> Scheduler.unstable_flushAll(); <del> <del> // Hasn't updated yet <del> expect(container.textContent).toEqual(''); <del> <del> let ops = []; <del> batch.then(() => { <del> // Still hasn't updated <del> ops.push(container.textContent); <del> // Should synchronously commit <del> batch.commit(); <del> ops.push(container.textContent); <del> }); <del> <del> expect(ops).toEqual(['', 'Foo']); <del> }); <del> <del> it('`batch.render` returns a thenable work object', () => { <del> const root = ReactDOM.unstable_createRoot(container); <del> const batch = root.createBatch(); <del> const work = batch.render('Hi'); <del> let ops = []; <del> work.then(() => { <del> ops.push('inside callback: ' + container.textContent); <del> }); <del> ops.push('before committing: ' + container.textContent); <del> batch.commit(); <del> ops.push('after committing: ' + container.textContent); <del> expect(ops).toEqual([ <del> 'before committing: ', <del> // `then` callback should fire during commit phase <del> 'inside callback: Hi', <del> 'after committing: Hi', <del> ]); <del> }); <del> <del> it('can commit an empty batch', () => { <del> const root = ReactDOM.unstable_createRoot(container); <del> root.render(1); <del> <del> Scheduler.unstable_advanceTime(2000); <del> // This batch has a later expiration time than the earlier update. <del> const batch = root.createBatch(); <del> <del> // This should not flush the earlier update. <del> batch.commit(); <del> expect(container.textContent).toEqual(''); <del> <del> Scheduler.unstable_flushAll(); <del> expect(container.textContent).toEqual('1'); <del> }); <del> <del> it('two batches created simultaneously are committed separately', () => { <del> // (In other words, they have distinct expiration times) <del> const root = ReactDOM.unstable_createRoot(container); <del> const batch1 = root.createBatch(); <del> batch1.render(1); <del> const batch2 = root.createBatch(); <del> batch2.render(2); <del> <del> expect(container.textContent).toEqual(''); <del> <del> batch1.commit(); <del> expect(container.textContent).toEqual('1'); <del> <del> batch2.commit(); <del> expect(container.textContent).toEqual('2'); <del> }); <del> <del> it('commits an earlier batch without committing a later batch', () => { <del> const root = ReactDOM.unstable_createRoot(container); <del> const batch1 = root.createBatch(); <del> batch1.render(1); <del> <del> // This batch has a later expiration time <del> Scheduler.unstable_advanceTime(2000); <del> const batch2 = root.createBatch(); <del> batch2.render(2); <del> <del> expect(container.textContent).toEqual(''); <del> <del> batch1.commit(); <del> expect(container.textContent).toEqual('1'); <del> <del> batch2.commit(); <del> expect(container.textContent).toEqual('2'); <del> }); <del> <del> it('commits a later batch without committing an earlier batch', () => { <del> const root = ReactDOM.unstable_createRoot(container); <del> const batch1 = root.createBatch(); <del> batch1.render(1); <del> <del> // This batch has a later expiration time <del> Scheduler.unstable_advanceTime(2000); <del> const batch2 = root.createBatch(); <del> batch2.render(2); <del> <del> expect(container.textContent).toEqual(''); <del> <del> batch2.commit(); <del> expect(container.textContent).toEqual('2'); <del> <del> batch1.commit(); <del> Scheduler.unstable_flushAll(); <del> expect(container.textContent).toEqual('1'); <del> }); <del> <del> it('handles fatal errors triggered by batch.commit()', () => { <del> const root = ReactDOM.unstable_createRoot(container); <del> const batch = root.createBatch(); <del> const InvalidType = undefined; <del> expect(() => batch.render(<InvalidType />)).toWarnDev( <del> ['React.createElement: type is invalid'], <del> {withoutStack: true}, <del> ); <del> expect(() => batch.commit()).toThrow('Element type is invalid'); <del> }); <del> <ide> it('throws a good message on invalid containers', () => { <ide> expect(() => { <ide> ReactDOM.unstable_createRoot(<div>Hi</div>); <ide><path>packages/react-dom/src/client/ReactDOM.js <ide> import type {ReactNodeList} from 'shared/ReactTypes'; <ide> import type {RootTag} from 'shared/ReactRootTags'; <ide> // TODO: This type is shared between the reconciler and ReactDOM, but will <ide> // eventually be lifted out to the renderer. <del>import type { <del> FiberRoot, <del> Batch as FiberRootBatch, <del>} from 'react-reconciler/src/ReactFiberRoot'; <add>import type {FiberRoot} from 'react-reconciler/src/ReactFiberRoot'; <ide> <ide> import '../shared/checkReact'; <ide> import './ReactDOMClientInjection'; <ide> <ide> import { <del> computeUniqueAsyncExpiration, <ide> findHostInstanceWithNoPortals, <del> updateContainerAtExpirationTime, <del> flushRoot, <ide> createContainer, <ide> updateContainer, <ide> batchedEventUpdates, <ide> setRestoreImplementation(restoreControlledState); <ide> <ide> export type DOMContainer = <ide> | (Element & { <del> _reactRootContainer: ?(_ReactRoot | _ReactSyncRoot), <add> _reactRootContainer: ?_ReactRoot, <ide> _reactHasBeenPassedToCreateRootDEV: ?boolean, <ide> }) <ide> | (Document & { <del> _reactRootContainer: ?(_ReactRoot | _ReactSyncRoot), <add> _reactRootContainer: ?_ReactRoot, <ide> _reactHasBeenPassedToCreateRootDEV: ?boolean, <ide> }); <ide> <del>type Batch = FiberRootBatch & { <del> render(children: ReactNodeList): Work, <del> then(onComplete: () => mixed): void, <del> commit(): void, <del> <del> // The ReactRoot constructor is hoisted but the prototype methods are not. If <del> // we move ReactRoot to be above ReactBatch, the inverse error occurs. <del> // $FlowFixMe Hoisting issue. <del> _root: _ReactRoot | _ReactSyncRoot, <del> _hasChildren: boolean, <del> _children: ReactNodeList, <del> <del> _callbacks: Array<() => mixed> | null, <del> _didComplete: boolean, <del>}; <del> <del>type _ReactSyncRoot = { <del> render(children: ReactNodeList, callback: ?() => mixed): Work, <del> unmount(callback: ?() => mixed): Work, <add>type _ReactRoot = { <add> render(children: ReactNodeList, callback: ?() => mixed): void, <add> unmount(callback: ?() => mixed): void, <ide> <ide> _internalRoot: FiberRoot, <ide> }; <ide> <del>type _ReactRoot = _ReactSyncRoot & { <del> createBatch(): Batch, <del>}; <del> <del>function ReactBatch(root: _ReactRoot | _ReactSyncRoot) { <del> const expirationTime = computeUniqueAsyncExpiration(); <del> this._expirationTime = expirationTime; <del> this._root = root; <del> this._next = null; <del> this._callbacks = null; <del> this._didComplete = false; <del> this._hasChildren = false; <del> this._children = null; <del> this._defer = true; <del>} <del>ReactBatch.prototype.render = function(children: ReactNodeList) { <del> invariant( <del> this._defer, <del> 'batch.render: Cannot render a batch that already committed.', <del> ); <del> this._hasChildren = true; <del> this._children = children; <del> const internalRoot = this._root._internalRoot; <del> const expirationTime = this._expirationTime; <del> const work = new ReactWork(); <del> updateContainerAtExpirationTime( <del> children, <del> internalRoot, <del> null, <del> expirationTime, <del> null, <del> work._onCommit, <del> ); <del> return work; <del>}; <del>ReactBatch.prototype.then = function(onComplete: () => mixed) { <del> if (this._didComplete) { <del> onComplete(); <del> return; <del> } <del> let callbacks = this._callbacks; <del> if (callbacks === null) { <del> callbacks = this._callbacks = []; <del> } <del> callbacks.push(onComplete); <del>}; <del>ReactBatch.prototype.commit = function() { <del> const internalRoot = this._root._internalRoot; <del> let firstBatch = internalRoot.firstBatch; <del> invariant( <del> this._defer && firstBatch !== null, <del> 'batch.commit: Cannot commit a batch multiple times.', <del> ); <del> <del> if (!this._hasChildren) { <del> // This batch is empty. Return. <del> this._next = null; <del> this._defer = false; <del> return; <del> } <del> <del> let expirationTime = this._expirationTime; <del> <del> // Ensure this is the first batch in the list. <del> if (firstBatch !== this) { <del> // This batch is not the earliest batch. We need to move it to the front. <del> // Update its expiration time to be the expiration time of the earliest <del> // batch, so that we can flush it without flushing the other batches. <del> if (this._hasChildren) { <del> expirationTime = this._expirationTime = firstBatch._expirationTime; <del> // Rendering this batch again ensures its children will be the final state <del> // when we flush (updates are processed in insertion order: last <del> // update wins). <del> // TODO: This forces a restart. Should we print a warning? <del> this.render(this._children); <del> } <del> <del> // Remove the batch from the list. <del> let previous = null; <del> let batch = firstBatch; <del> while (batch !== this) { <del> previous = batch; <del> batch = batch._next; <del> } <del> invariant( <del> previous !== null, <del> 'batch.commit: Cannot commit a batch multiple times.', <del> ); <del> previous._next = batch._next; <del> <del> // Add it to the front. <del> this._next = firstBatch; <del> firstBatch = internalRoot.firstBatch = this; <del> } <del> <del> // Synchronously flush all the work up to this batch's expiration time. <del> this._defer = false; <del> flushRoot(internalRoot, expirationTime); <del> <del> // Pop the batch from the list. <del> const next = this._next; <del> this._next = null; <del> firstBatch = internalRoot.firstBatch = next; <del> <del> // Append the next earliest batch's children to the update queue. <del> if (firstBatch !== null && firstBatch._hasChildren) { <del> firstBatch.render(firstBatch._children); <del> } <del>}; <del>ReactBatch.prototype._onComplete = function() { <del> if (this._didComplete) { <del> return; <del> } <del> this._didComplete = true; <del> const callbacks = this._callbacks; <del> if (callbacks === null) { <del> return; <del> } <del> // TODO: Error handling. <del> for (let i = 0; i < callbacks.length; i++) { <del> const callback = callbacks[i]; <del> callback(); <del> } <del>}; <del> <del>type Work = { <del> then(onCommit: () => mixed): void, <del> _onCommit: () => void, <del> _callbacks: Array<() => mixed> | null, <del> _didCommit: boolean, <del>}; <del> <del>function ReactWork() { <del> this._callbacks = null; <del> this._didCommit = false; <del> // TODO: Avoid need to bind by replacing callbacks in the update queue with <del> // list of Work objects. <del> this._onCommit = this._onCommit.bind(this); <del>} <del>ReactWork.prototype.then = function(onCommit: () => mixed): void { <del> if (this._didCommit) { <del> onCommit(); <del> return; <del> } <del> let callbacks = this._callbacks; <del> if (callbacks === null) { <del> callbacks = this._callbacks = []; <del> } <del> callbacks.push(onCommit); <del>}; <del>ReactWork.prototype._onCommit = function(): void { <del> if (this._didCommit) { <del> return; <del> } <del> this._didCommit = true; <del> const callbacks = this._callbacks; <del> if (callbacks === null) { <del> return; <del> } <del> // TODO: Error handling. <del> for (let i = 0; i < callbacks.length; i++) { <del> const callback = callbacks[i]; <del> invariant( <del> typeof callback === 'function', <del> 'Invalid argument passed as callback. Expected a function. Instead ' + <del> 'received: %s', <del> callback, <del> ); <del> callback(); <del> } <del>}; <del> <ide> function createRootImpl( <ide> container: DOMContainer, <ide> tag: RootTag, <ide> function ReactRoot(container: DOMContainer, options: void | RootOptions) { <ide> ReactRoot.prototype.render = ReactSyncRoot.prototype.render = function( <ide> children: ReactNodeList, <ide> callback: ?() => mixed, <del>): Work { <add>): void { <ide> const root = this._internalRoot; <del> const work = new ReactWork(); <ide> callback = callback === undefined ? null : callback; <ide> if (__DEV__) { <ide> warnOnInvalidCallback(callback, 'render'); <ide> } <del> if (callback !== null) { <del> work.then(callback); <del> } <del> updateContainer(children, root, null, work._onCommit); <del> return work; <add> updateContainer(children, root, null, callback); <ide> }; <ide> <ide> ReactRoot.prototype.unmount = ReactSyncRoot.prototype.unmount = function( <ide> callback: ?() => mixed, <del>): Work { <add>): void { <ide> const root = this._internalRoot; <del> const work = new ReactWork(); <ide> callback = callback === undefined ? null : callback; <ide> if (__DEV__) { <ide> warnOnInvalidCallback(callback, 'render'); <ide> } <del> if (callback !== null) { <del> work.then(callback); <del> } <del> updateContainer(null, root, null, work._onCommit); <del> return work; <del>}; <del> <del>// Sync roots cannot create batches. Only concurrent ones. <del>ReactRoot.prototype.createBatch = function(): Batch { <del> const batch = new ReactBatch(this); <del> const expirationTime = batch._expirationTime; <del> <del> const internalRoot = this._internalRoot; <del> const firstBatch = internalRoot.firstBatch; <del> if (firstBatch === null) { <del> internalRoot.firstBatch = batch; <del> batch._next = null; <del> } else { <del> // Insert sorted by expiration time then insertion order <del> let insertAfter = null; <del> let insertBefore = firstBatch; <del> while ( <del> insertBefore !== null && <del> insertBefore._expirationTime >= expirationTime <del> ) { <del> insertAfter = insertBefore; <del> insertBefore = insertBefore._next; <del> } <del> batch._next = insertBefore; <del> if (insertAfter !== null) { <del> insertAfter._next = batch; <del> } <del> } <del> <del> return batch; <add> updateContainer(null, root, null, callback); <ide> }; <ide> <ide> /** <ide> let warnedAboutHydrateAPI = false; <ide> function legacyCreateRootFromDOMContainer( <ide> container: DOMContainer, <ide> forceHydrate: boolean, <del>): _ReactSyncRoot { <add>): _ReactRoot { <ide> const shouldHydrate = <ide> forceHydrate || shouldHydrateDueToLegacyHeuristic(container); <ide> // First clear any existing content. <ide> function legacyRenderSubtreeIntoContainer( <ide> <ide> // TODO: Without `any` type, Flow says "Property cannot be accessed on any <ide> // member of intersection type." Whyyyyyy. <del> let root: _ReactSyncRoot = (container._reactRootContainer: any); <add> let root: _ReactRoot = (container._reactRootContainer: any); <ide> let fiberRoot; <ide> if (!root) { <ide> // Initial mount <ide> function createRoot( <ide> function createSyncRoot( <ide> container: DOMContainer, <ide> options?: RootOptions, <del>): _ReactSyncRoot { <add>): _ReactRoot { <ide> const functionName = enableStableConcurrentModeAPIs <ide> ? 'createRoot' <ide> : 'unstable_createRoot'; <ide><path>packages/react-dom/src/events/__tests__/DOMEventResponderSystem-test.internal.js <ide> describe('DOMEventResponderSystem', () => { <ide> <ide> function Test({counter}) { <ide> const listener = React.unstable_useResponder(TestResponder, {counter}); <del> <add> Scheduler.unstable_yieldValue('Test'); <ide> return ( <ide> <button listeners={listener} ref={ref}> <ide> Press me <ide> describe('DOMEventResponderSystem', () => { <ide> } <ide> <ide> let root = ReactDOM.unstable_createRoot(container); <del> let batch = root.createBatch(); <del> batch.render(<Test counter={0} />); <del> Scheduler.unstable_flushAll(); <del> jest.runAllTimers(); <del> batch.commit(); <add> root.render(<Test counter={0} />); <add> expect(Scheduler).toFlushAndYield(['Test']); <ide> <ide> // Click the button <ide> dispatchClickEvent(ref.current); <ide> describe('DOMEventResponderSystem', () => { <ide> log.length = 0; <ide> <ide> // Increase counter <del> batch = root.createBatch(); <del> batch.render(<Test counter={1} />); <del> Scheduler.unstable_flushAll(); <del> jest.runAllTimers(); <add> root.render(<Test counter={1} />); <add> // Yield before committing <add> expect(Scheduler).toFlushAndYieldThrough(['Test']); <ide> <ide> // Click the button again <ide> dispatchClickEvent(ref.current); <ide> describe('DOMEventResponderSystem', () => { <ide> log.length = 0; <ide> <ide> // Commit <del> batch.commit(); <add> expect(Scheduler).toFlushAndYield([]); <ide> dispatchClickEvent(ref.current); <ide> expect(log).toEqual([{counter: 1}]); <ide> }); <ide><path>packages/react-noop-renderer/src/createReactNoop.js <ide> import type {RootTag} from 'shared/ReactRootTags'; <ide> <ide> import * as Scheduler from 'scheduler/unstable_mock'; <ide> import {createPortal} from 'shared/ReactPortal'; <del>import expect from 'expect'; <ide> import {REACT_FRAGMENT_TYPE, REACT_ELEMENT_TYPE} from 'shared/ReactSymbols'; <ide> import enqueueTask from 'shared/enqueueTask'; <ide> import ReactSharedInternals from 'shared/ReactSharedInternals'; <ide> function createReactNoop(reconciler: Function, useMutation: boolean) { <ide> console.log(...bufferedLog); <ide> }, <ide> <del> flushWithoutCommitting( <del> expectedFlush: Array<mixed>, <del> rootID: string = DEFAULT_ROOT_ID, <del> ) { <del> const root: any = roots.get(rootID); <del> const expiration = NoopRenderer.computeUniqueAsyncExpiration(); <del> const batch = { <del> _defer: true, <del> _expirationTime: expiration, <del> _onComplete: () => { <del> root.firstBatch = null; <del> }, <del> _next: null, <del> }; <del> root.firstBatch = batch; <del> Scheduler.unstable_flushAllWithoutAsserting(); <del> const actual = Scheduler.unstable_clearYields(); <del> expect(actual).toEqual(expectedFlush); <del> return (expectedCommit: Array<mixed>) => { <del> batch._defer = false; <del> NoopRenderer.flushRoot(root, expiration); <del> expect(Scheduler.unstable_clearYields()).toEqual(expectedCommit); <del> }; <del> }, <del> <ide> getRoot(rootID: string = DEFAULT_ROOT_ID) { <ide> return roots.get(rootID); <ide> }, <ide><path>packages/react-reconciler/src/ReactFiberHotReloading.js <ide> import { <ide> scheduleWork, <ide> flushPassiveEffects, <ide> } from './ReactFiberWorkLoop'; <del>import {updateContainerAtExpirationTime} from './ReactFiberReconciler'; <add>import {updateContainer, syncUpdates} from './ReactFiberReconciler'; <ide> import {emptyContextObject} from './ReactFiberContext'; <ide> import {Sync} from './ReactFiberExpirationTime'; <ide> import { <ide> export let scheduleRoot: ScheduleRoot = ( <ide> return; <ide> } <ide> flushPassiveEffects(); <del> updateContainerAtExpirationTime(element, root, null, Sync, null); <add> syncUpdates(() => { <add> updateContainer(element, root, null, null); <add> }); <ide> } <ide> }; <ide> <ide><path>packages/react-reconciler/src/ReactFiberReconciler.js <ide> import type { <ide> import {FundamentalComponent} from 'shared/ReactWorkTags'; <ide> import type {ReactNodeList} from 'shared/ReactTypes'; <ide> import type {ExpirationTime} from './ReactFiberExpirationTime'; <del>import type {SuspenseConfig} from './ReactFiberSuspenseConfig'; <ide> import type { <ide> SuspenseHydrationCallbacks, <ide> SuspenseState, <ide> import { <ide> import {createFiberRoot} from './ReactFiberRoot'; <ide> import {injectInternals} from './ReactFiberDevToolsHook'; <ide> import { <del> computeUniqueAsyncExpiration, <ide> requestCurrentTime, <ide> computeExpirationForFiber, <ide> scheduleWork, <ide> function getContextForSubtree( <ide> return parentContext; <ide> } <ide> <del>function scheduleRootUpdate( <del> current: Fiber, <del> element: ReactNodeList, <del> expirationTime: ExpirationTime, <del> suspenseConfig: null | SuspenseConfig, <del> callback: ?Function, <del>) { <del> if (__DEV__) { <del> if ( <del> ReactCurrentFiberPhase === 'render' && <del> ReactCurrentFiberCurrent !== null && <del> !didWarnAboutNestedUpdates <del> ) { <del> didWarnAboutNestedUpdates = true; <del> warningWithoutStack( <del> false, <del> 'Render methods should be a pure function of props and state; ' + <del> 'triggering nested component updates from render is not allowed. ' + <del> 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + <del> 'Check the render method of %s.', <del> getComponentName(ReactCurrentFiberCurrent.type) || 'Unknown', <del> ); <del> } <del> } <del> <del> const update = createUpdate(expirationTime, suspenseConfig); <del> // Caution: React DevTools currently depends on this property <del> // being called "element". <del> update.payload = {element}; <del> <del> callback = callback === undefined ? null : callback; <del> if (callback !== null) { <del> warningWithoutStack( <del> typeof callback === 'function', <del> 'render(...): Expected the last optional `callback` argument to be a ' + <del> 'function. Instead received: %s.', <del> callback, <del> ); <del> update.callback = callback; <del> } <del> <del> enqueueUpdate(current, update); <del> scheduleWork(current, expirationTime); <del> <del> return expirationTime; <del>} <del> <del>export function updateContainerAtExpirationTime( <del> element: ReactNodeList, <del> container: OpaqueRoot, <del> parentComponent: ?React$Component<any, any>, <del> expirationTime: ExpirationTime, <del> suspenseConfig: null | SuspenseConfig, <del> callback: ?Function, <del>) { <del> // TODO: If this is a nested container, this won't be the root. <del> const current = container.current; <del> <del> if (__DEV__) { <del> if (ReactFiberInstrumentation.debugTool) { <del> if (current.alternate === null) { <del> ReactFiberInstrumentation.debugTool.onMountContainer(container); <del> } else if (element === null) { <del> ReactFiberInstrumentation.debugTool.onUnmountContainer(container); <del> } else { <del> ReactFiberInstrumentation.debugTool.onUpdateContainer(container); <del> } <del> } <del> } <del> <del> const context = getContextForSubtree(parentComponent); <del> if (container.context === null) { <del> container.context = context; <del> } else { <del> container.pendingContext = context; <del> } <del> <del> return scheduleRootUpdate( <del> current, <del> element, <del> expirationTime, <del> suspenseConfig, <del> callback, <del> ); <del>} <del> <ide> function findHostInstance(component: Object): PublicInstance | null { <ide> const fiber = getInstance(component); <ide> if (fiber === undefined) { <ide> export function updateContainer( <ide> current, <ide> suspenseConfig, <ide> ); <del> return updateContainerAtExpirationTime( <del> element, <del> container, <del> parentComponent, <del> expirationTime, <del> suspenseConfig, <del> callback, <del> ); <add> <add> if (__DEV__) { <add> if (ReactFiberInstrumentation.debugTool) { <add> if (current.alternate === null) { <add> ReactFiberInstrumentation.debugTool.onMountContainer(container); <add> } else if (element === null) { <add> ReactFiberInstrumentation.debugTool.onUnmountContainer(container); <add> } else { <add> ReactFiberInstrumentation.debugTool.onUpdateContainer(container); <add> } <add> } <add> } <add> <add> const context = getContextForSubtree(parentComponent); <add> if (container.context === null) { <add> container.context = context; <add> } else { <add> container.pendingContext = context; <add> } <add> <add> if (__DEV__) { <add> if ( <add> ReactCurrentFiberPhase === 'render' && <add> ReactCurrentFiberCurrent !== null && <add> !didWarnAboutNestedUpdates <add> ) { <add> didWarnAboutNestedUpdates = true; <add> warningWithoutStack( <add> false, <add> 'Render methods should be a pure function of props and state; ' + <add> 'triggering nested component updates from render is not allowed. ' + <add> 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + <add> 'Check the render method of %s.', <add> getComponentName(ReactCurrentFiberCurrent.type) || 'Unknown', <add> ); <add> } <add> } <add> <add> const update = createUpdate(expirationTime, suspenseConfig); <add> // Caution: React DevTools currently depends on this property <add> // being called "element". <add> update.payload = {element}; <add> <add> callback = callback === undefined ? null : callback; <add> if (callback !== null) { <add> warningWithoutStack( <add> typeof callback === 'function', <add> 'render(...): Expected the last optional `callback` argument to be a ' + <add> 'function. Instead received: %s.', <add> callback, <add> ); <add> update.callback = callback; <add> } <add> <add> enqueueUpdate(current, update); <add> scheduleWork(current, expirationTime); <add> <add> return expirationTime; <ide> } <ide> <ide> export { <ide> flushRoot, <del> computeUniqueAsyncExpiration, <ide> batchedEventUpdates, <ide> batchedUpdates, <ide> unbatchedUpdates, <ide><path>packages/react-reconciler/src/ReactFiberRoot.js <ide> import { <ide> import {unstable_getThreadID} from 'scheduler/tracing'; <ide> import {NoPriority} from './SchedulerWithReactIntegration'; <ide> <del>// TODO: This should be lifted into the renderer. <del>export type Batch = { <del> _defer: boolean, <del> _expirationTime: ExpirationTime, <del> _onComplete: () => mixed, <del> _next: Batch | null, <del>}; <del> <ide> export type PendingInteractionMap = Map<ExpirationTime, Set<Interaction>>; <ide> <ide> type BaseFiberRootProperties = {| <ide> type BaseFiberRootProperties = {| <ide> pendingContext: Object | null, <ide> // Determines if we should attempt to hydrate on the initial mount <ide> +hydrate: boolean, <del> // List of top-level batches. This list indicates whether a commit should be <del> // deferred. Also contains completion callbacks. <del> // TODO: Lift this into the renderer <del> firstBatch: Batch | null, <ide> // Node returned by Scheduler.scheduleCallback <ide> callbackNode: *, <ide> // Expiration of the callback associated with this root <ide> function FiberRootNode(containerInfo, tag, hydrate) { <ide> this.context = null; <ide> this.pendingContext = null; <ide> this.hydrate = hydrate; <del> this.firstBatch = null; <ide> this.callbackNode = null; <ide> this.callbackPriority = NoPriority; <ide> this.firstPendingTime = NoWork; <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.js <ide> const LegacyUnbatchedContext = /* */ 0b001000; <ide> const RenderContext = /* */ 0b010000; <ide> const CommitContext = /* */ 0b100000; <ide> <del>type RootExitStatus = 0 | 1 | 2 | 3 | 4 | 5 | 6; <add>type RootExitStatus = 0 | 1 | 2 | 3 | 4 | 5; <ide> const RootIncomplete = 0; <ide> const RootFatalErrored = 1; <ide> const RootErrored = 2; <ide> const RootSuspended = 3; <ide> const RootSuspendedWithDelay = 4; <ide> const RootCompleted = 5; <del>const RootLocked = 6; <ide> <ide> export type Thenable = { <ide> then(resolve: () => mixed, reject?: () => mixed): Thenable | void, <ide> function performConcurrentWorkOnRoot(root, didTimeout) { <ide> const finishedWork: Fiber = ((root.finishedWork = <ide> root.current.alternate): any); <ide> root.finishedExpirationTime = expirationTime; <del> resolveLocksOnRoot(root, expirationTime); <ide> finishConcurrentRender( <ide> root, <ide> finishedWork, <ide> function finishConcurrentRender( <ide> commitRoot(root); <ide> break; <ide> } <del> case RootLocked: { <del> // This root has a lock that prevents it from committing. Exit. If <del> // we begin work on the root again, without any intervening updates, <del> // it will finish without doing additional work. <del> markRootSuspendedAtTime(root, expirationTime); <del> break; <del> } <ide> default: { <ide> invariant(false, 'Unknown root exit status.'); <ide> } <ide> function performSyncWorkOnRoot(root) { <ide> ); <ide> } else { <ide> // We now have a consistent tree. Because this is a sync render, we <del> // will commit it even if something suspended. The only exception is <del> // if the root is locked (using the unstable_createBatch API). <add> // will commit it even if something suspended. <ide> stopFinishedWorkLoopTimer(); <ide> root.finishedWork = (root.current.alternate: any); <ide> root.finishedExpirationTime = expirationTime; <del> resolveLocksOnRoot(root, expirationTime); <ide> finishSyncRender(root, workInProgressRootExitStatus, expirationTime); <ide> } <ide> <ide> function performSyncWorkOnRoot(root) { <ide> } <ide> <ide> function finishSyncRender(root, exitStatus, expirationTime) { <del> if (exitStatus === RootLocked) { <del> // This root has a lock that prevents it from committing. Exit. If we <del> // begin work on the root again, without any intervening updates, it <del> // will finish without doing additional work. <del> markRootSuspendedAtTime(root, expirationTime); <del> } else { <del> // Set this to null to indicate there's no in-progress render. <del> workInProgressRoot = null; <add> // Set this to null to indicate there's no in-progress render. <add> workInProgressRoot = null; <ide> <del> if (__DEV__) { <del> if ( <del> exitStatus === RootSuspended || <del> exitStatus === RootSuspendedWithDelay <del> ) { <del> flushSuspensePriorityWarningInDEV(); <del> } <add> if (__DEV__) { <add> if (exitStatus === RootSuspended || exitStatus === RootSuspendedWithDelay) { <add> flushSuspensePriorityWarningInDEV(); <ide> } <del> commitRoot(root); <ide> } <add> commitRoot(root); <ide> } <ide> <ide> export function flushRoot(root: FiberRoot, expirationTime: ExpirationTime) { <ide> export function flushDiscreteUpdates() { <ide> flushPassiveEffects(); <ide> } <ide> <del>function resolveLocksOnRoot(root: FiberRoot, expirationTime: ExpirationTime) { <del> const firstBatch = root.firstBatch; <del> if ( <del> firstBatch !== null && <del> firstBatch._defer && <del> firstBatch._expirationTime >= expirationTime <del> ) { <del> scheduleCallback(NormalPriority, () => { <del> firstBatch._onComplete(); <del> return null; <del> }); <del> workInProgressRootExitStatus = RootLocked; <del> } <del>} <del> <ide> export function deferredUpdates<A>(fn: () => A): A { <ide> // TODO: Remove in favor of Scheduler.next <ide> return runWithPriority(NormalPriority, fn); <ide><path>packages/react/src/__tests__/ReactProfiler-test.internal.js <ide> function loadModules({ <ide> }; <ide> } <ide> <del>const mockDevToolsForTest = () => { <del> jest.mock('react-reconciler/src/ReactFiberDevToolsHook', () => ({ <del> injectInternals: () => {}, <del> onCommitRoot: () => {}, <del> onCommitUnmount: () => {}, <del> isDevToolsPresent: true, <del> })); <del>}; <del> <ide> describe('Profiler', () => { <ide> describe('works in profiling and non-profiling bundles', () => { <ide> [true, false].forEach(enableSchedulerTracing => { <ide> describe('Profiler', () => { <ide> }); <ide> }); <ide> <del> it('should handle interleaved async yields and batched commits', () => { <del> jest.resetModules(); <del> mockDevToolsForTest(); <del> loadModules({useNoopRenderer: true}); <del> <del> const Child = ({duration, id}) => { <del> Scheduler.unstable_advanceTime(duration); <del> Scheduler.unstable_yieldValue(`Child:render:${id}`); <del> return null; <del> }; <del> <del> class Parent extends React.Component { <del> componentDidMount() { <del> Scheduler.unstable_yieldValue( <del> `Parent:componentDidMount:${this.props.id}`, <del> ); <del> } <del> render() { <del> const {duration, id} = this.props; <del> return ( <del> <> <del> <Child duration={duration} id={id} /> <del> <Child duration={duration} id={id} /> <del> </> <del> ); <del> } <del> } <del> <del> Scheduler.unstable_advanceTime(50); <del> <del> ReactNoop.renderToRootWithID(<Parent duration={3} id="one" />, 'one'); <del> <del> // Process up to the <Parent> component, but yield before committing. <del> // This ensures that the profiler timer still has paused fibers. <del> const commitFirstRender = ReactNoop.flushWithoutCommitting( <del> ['Child:render:one', 'Child:render:one'], <del> 'one', <del> ); <del> <del> expect(ReactNoop.getRoot('one').current.actualDuration).toBe(0); <del> <del> Scheduler.unstable_advanceTime(100); <del> <del> // Process some async work, but yield before committing it. <del> ReactNoop.renderToRootWithID(<Parent duration={7} id="two" />, 'two'); <del> expect(Scheduler).toFlushAndYieldThrough(['Child:render:two']); <del> <del> Scheduler.unstable_advanceTime(150); <del> <del> // Commit the previously paused, batched work. <del> commitFirstRender(['Parent:componentDidMount:one']); <del> <del> expect(ReactNoop.getRoot('one').current.actualDuration).toBe(6); <del> expect(ReactNoop.getRoot('two').current.actualDuration).toBe(0); <del> <del> Scheduler.unstable_advanceTime(200); <del> <del> expect(Scheduler).toFlushAndYield([ <del> 'Child:render:two', <del> 'Parent:componentDidMount:two', <del> ]); <del> <del> expect(ReactNoop.getRoot('two').current.actualDuration).toBe(14); <del> }); <del> <ide> describe('interaction tracing', () => { <ide> let onInteractionScheduledWorkCompleted; <ide> let onInteractionTraced; <ide><path>packages/react/src/__tests__/ReactProfilerDOM-test.internal.js <ide> let ReactFeatureFlags; <ide> let ReactDOM; <ide> let SchedulerTracing; <ide> let Scheduler; <del>let ReactCache; <ide> <ide> function loadModules() { <ide> ReactFeatureFlags = require('shared/ReactFeatureFlags'); <ide> function loadModules() { <ide> SchedulerTracing = require('scheduler/tracing'); <ide> ReactDOM = require('react-dom'); <ide> Scheduler = require('scheduler'); <del> ReactCache = require('react-cache'); <ide> } <ide> <ide> describe('ProfilerDOM', () => { <del> let TextResource; <del> let resourcePromise; <ide> let onInteractionScheduledWorkCompleted; <ide> let onInteractionTraced; <ide> <ide> describe('ProfilerDOM', () => { <ide> onWorkStarted: () => {}, <ide> onWorkStopped: () => {}, <ide> }); <del> <del> resourcePromise = null; <del> <del> TextResource = ReactCache.unstable_createResource(([text, ms = 0]) => { <del> resourcePromise = new Promise( <del> SchedulerTracing.unstable_wrap((resolve, reject) => { <del> setTimeout( <del> SchedulerTracing.unstable_wrap(() => { <del> resolve(text); <del> }), <del> ms, <del> ); <del> }), <del> ); <del> return resourcePromise; <del> }, ([text, ms]) => text); <ide> }); <ide> <del> const AsyncText = ({ms, text}) => { <del> TextResource.read([text, ms]); <del> return text; <del> }; <del> <del> const Text = ({text}) => text; <del> <del> it('should correctly trace interactions for async roots', async done => { <del> let batch, element, interaction; <del> <add> function Text(props) { <add> Scheduler.unstable_yieldValue(props.text); <add> return props.text; <add> } <add> <add> it('should correctly trace interactions for async roots', async () => { <add> let resolve; <add> let thenable = { <add> then(res) { <add> resolve = () => { <add> thenable = null; <add> res(); <add> }; <add> }, <add> }; <add> <add> function Async() { <add> if (thenable !== null) { <add> Scheduler.unstable_yieldValue('Suspend! [Async]'); <add> throw thenable; <add> } <add> Scheduler.unstable_yieldValue('Async'); <add> return 'Async'; <add> } <add> <add> const element = document.createElement('div'); <add> const root = ReactDOM.unstable_createRoot(element); <add> <add> let interaction; <add> let wrappedResolve; <ide> SchedulerTracing.unstable_trace('initial_event', performance.now(), () => { <ide> const interactions = SchedulerTracing.unstable_getCurrent(); <ide> expect(interactions.size).toBe(1); <ide> interaction = Array.from(interactions)[0]; <ide> <del> element = document.createElement('div'); <del> const root = ReactDOM.unstable_createRoot(element); <del> batch = root.createBatch(); <del> batch.render( <add> root.render( <ide> <React.Suspense fallback={<Text text="Loading..." />}> <del> <AsyncText text="Text" ms={2000} /> <add> <Async /> <ide> </React.Suspense>, <ide> ); <del> batch.then( <del> SchedulerTracing.unstable_wrap(() => { <del> batch.commit(); <del> <del> expect(element.textContent).toBe('Loading...'); <del> expect(onInteractionTraced).toHaveBeenCalledTimes(1); <del> expect(onInteractionScheduledWorkCompleted).not.toHaveBeenCalled(); <del> <del> jest.runAllTimers(); <del> <del> resourcePromise.then( <del> SchedulerTracing.unstable_wrap(() => { <del> jest.runAllTimers(); <del> Scheduler.unstable_flushAll(); <del> <del> expect(element.textContent).toBe('Text'); <del> expect(onInteractionTraced).toHaveBeenCalledTimes(1); <del> expect( <del> onInteractionScheduledWorkCompleted, <del> ).not.toHaveBeenCalled(); <del> <del> // Evaluate in an unwrapped callback, <del> // Because trace/wrap won't decrement the count within the wrapped callback. <del> Promise.resolve().then(() => { <del> expect(onInteractionTraced).toHaveBeenCalledTimes(1); <del> expect( <del> onInteractionScheduledWorkCompleted, <del> ).toHaveBeenCalledTimes(1); <del> expect( <del> onInteractionScheduledWorkCompleted, <del> ).toHaveBeenLastNotifiedOfInteraction(interaction); <del> <del> expect(interaction.__count).toBe(0); <del> <del> done(); <del> }); <del> }), <del> ); <del> }), <del> ); <ide> <del> Scheduler.unstable_flushAll(); <add> wrappedResolve = SchedulerTracing.unstable_wrap(() => resolve()); <ide> }); <ide> <add> // Render, suspend, and commit fallback <add> expect(Scheduler).toFlushAndYield(['Suspend! [Async]', 'Loading...']); <add> expect(element.textContent).toEqual('Loading...'); <add> <ide> expect(onInteractionTraced).toHaveBeenCalledTimes(1); <ide> expect(onInteractionTraced).toHaveBeenLastNotifiedOfInteraction( <ide> interaction, <ide> ); <ide> expect(onInteractionScheduledWorkCompleted).not.toHaveBeenCalled(); <del> Scheduler.unstable_flushAll(); <del> jest.advanceTimersByTime(500); <add> <add> // Ping React to try rendering again <add> wrappedResolve(); <add> <add> // Complete the tree without committing it <add> expect(Scheduler).toFlushAndYieldThrough(['Async']); <add> // Still showing the fallback <add> expect(element.textContent).toEqual('Loading...'); <add> <add> expect(onInteractionTraced).toHaveBeenCalledTimes(1); <add> expect(onInteractionTraced).toHaveBeenLastNotifiedOfInteraction( <add> interaction, <add> ); <add> expect(onInteractionScheduledWorkCompleted).not.toHaveBeenCalled(); <add> <add> expect(Scheduler).toFlushAndYield([]); <add> expect(element.textContent).toEqual('Async'); <add> <add> expect(onInteractionTraced).toHaveBeenCalledTimes(1); <add> expect(onInteractionTraced).toHaveBeenLastNotifiedOfInteraction( <add> interaction, <add> ); <add> expect(onInteractionScheduledWorkCompleted).toHaveBeenCalledTimes(1); <ide> }); <ide> });
10
Text
Text
update basic formatting
865ccd6673fc8a29ac48b7ef06afd98d917ebb3d
<ide><path>README.md <del># CakePHP framework <add># CakePHP Framework <ide> <ide> [![Bake Status](https://secure.travis-ci.org/cakephp/cakephp.png?branch=3.0)](http://travis-ci.org/cakephp/cakephp) <ide> [![Latest Stable Version](https://poser.pugx.org/cakephp/cakephp/v/stable.svg)](https://packagist.org/packages/cakephp/cakephp) <ide> and MVC. Our primary goal is to provide a structured framework that enables <ide> PHP users at all levels to rapidly develop robust web applications, without any <ide> loss to flexibility. <ide> <del>## Installing CakePHP via composer <add>## Installing CakePHP via Composer <ide> <ide> You can install CakePHP into your project using <ide> [composer](http://getcomposer.org). If you're starting a new project, we <ide> a starting point. For existing applications you can add the following to your <ide> <ide> And run `php composer.phar update` <ide> <del>## Running tests <add>## Running Tests <ide> <ide> Assuming you have PHPUnit installed system wide using one of the methods stated <ide> [here](http://phpunit.de/manual/current/en/installation.html), you can run the <ide> See CONTRIBUTING.md for more information. <ide> <ide> ## Some Handy Links <ide> <del>[CakePHP](http://www.cakephp.org) - The rapid development PHP framework <add>[CakePHP](http://www.cakephp.org) - The rapid development PHP framework. <ide> <ide> [CookBook](http://book.cakephp.org) - THE CakePHP user documentation; start learning here! <ide> <del>[API](http://api.cakephp.org) - A reference to CakePHP's classes <add>[API](http://api.cakephp.org) - A reference to CakePHP's classes. <ide> <del>[Plugins](http://plugins.cakephp.org) - A repository of extensions to the framework <add>[Plugins](http://plugins.cakephp.org) - A repository of extensions to the framework. <ide> <del>[The Bakery](http://bakery.cakephp.org) - Tips, tutorials and articles <add>[The Bakery](http://bakery.cakephp.org) - Tips, tutorials and articles. <ide> <del>[Community Center](http://community.cakephp.org) - A source for everything community related <add>[Community Center](http://community.cakephp.org) - A source for everything community related. <ide> <del>[Training](http://training.cakephp.org) - Join a live session and get skilled with the framework <add>[Training](http://training.cakephp.org) - Join a live session and get skilled with the framework. <ide> <del>[CakeFest](http://cakefest.org) - Don't miss our annual CakePHP conference <add>[CakeFest](http://cakefest.org) - Don't miss our annual CakePHP conference. <ide> <del>[Cake Software Foundation](http://cakefoundation.org) - Promoting development related to CakePHP <add>[Cake Software Foundation](http://cakefoundation.org) - Promoting development related to CakePHP. <ide> <ide> <ide> ## Get Support! <ide> <del>[#cakephp](http://webchat.freenode.net/?channels=#cakephp) on irc.freenode.net - Come chat with us, we have cake <add>[#cakephp](http://webchat.freenode.net/?channels=#cakephp) on irc.freenode.net - Come chat with us, we have cake. <ide> <del>[Google Group](https://groups.google.com/group/cake-php) - Community mailing list and forum <add>[Google Group](https://groups.google.com/group/cake-php) - Community mailing list and forum. <ide> <ide> [GitHub Issues](https://github.com/cakephp/cakephp/issues) - Got issues? Please tell us! <ide> <ide> [Roadmaps](https://github.com/cakephp/cakephp/wiki#roadmaps) - Want to contribute? Get involved! <ide> <ide> ## Contributing <ide> <del>[CONTRIBUTING.md](CONTRIBUTING.md) - Quick pointers for contributing to the CakePHP project <add>[CONTRIBUTING.md](CONTRIBUTING.md) - Quick pointers for contributing to the CakePHP project. <ide> <del>[CookBook "Contributing" Section (2.x)](http://book.cakephp.org/2.0/en/contributing.html) [(3.0)](http://book.cakephp.org/3.0/en/contributing.html) - Version-specific details about contributing to the project <add>[CookBook "Contributing" Section (2.x)](http://book.cakephp.org/2.0/en/contributing.html) [(3.0)](http://book.cakephp.org/3.0/en/contributing.html) - Version-specific details about contributing to the project.
1
Ruby
Ruby
fix rollback of frozen records
8313797810eefb7e00d0b5a8e91ac02907fa5e8f
<ide><path>activerecord/lib/active_record/transactions.rb <ide> def restore_transaction_record_state(force = false) #:nodoc: <ide> transaction_level = (@_start_transaction_state[:level] || 0) - 1 <ide> if transaction_level < 1 || force <ide> restore_state = @_start_transaction_state <del> thaw unless restore_state[:frozen?] <add> thaw <ide> @new_record = restore_state[:new_record] <ide> @destroyed = restore_state[:destroyed] <ide> pk = self.class.primary_key <ide> if pk && read_attribute(pk) != restore_state[:id] <ide> write_attribute(pk, restore_state[:id]) <ide> end <add> freeze if restore_state[:frozen?] <ide> end <ide> end <ide> end <ide><path>activerecord/test/cases/transactions_test.rb <ide> def test_restore_frozen_state_after_double_destroy <ide> assert_not topic.frozen? <ide> end <ide> <add> def test_rollback_of_frozen_records <add> topic = Topic.create.freeze <add> Topic.transaction do <add> topic.destroy <add> raise ActiveRecord::Rollback <add> end <add> assert topic.frozen?, 'frozen' <add> end <add> <ide> def test_sqlite_add_column_in_transaction <ide> return true unless current_adapter?(:SQLite3Adapter) <ide>
2
Ruby
Ruby
return argv from more methods
22dafbb65800615e8a3f3a499091b8e33c3d39f7
<ide><path>railties/lib/rails/generators/rails/app/app_generator.rb <ide> def handle_invalid_command!(argument, argv) <ide> end <ide> <ide> def handle_rails_rc!(argv) <del> unless argv.delete("--no-rc") <add> if argv.find { |arg| arg == '--no-rc' } <add> argv.reject { |arg| arg == '--no-rc' } <add> else <ide> insert_railsrc_into_argv!(argv, railsrc(argv)) <add> argv <ide> end <del> argv <ide> end <ide> <ide> def railsrc(argv)
1
Text
Text
add changelog for v3.12.4 [ci skip]
68d216b1db1688b41cf8895d7b1bbf84f25864ba
<ide><path>CHANGELOG.md <ide> - [#18688](https://github.com/emberjs/ember.js/pull/18688) / [#18621](https://github.com/emberjs/ember.js/pull/18621) / [#18714](https://github.com/emberjs/ember.js/pull/18714) / [#18743](https://github.com/emberjs/ember.js/pull/18743) / [#18762](https://github.com/emberjs/ember.js/pull/18762) Upgrades Glimmer VM to 0.47.9, fixes ignored `checked` attribute on `input`, fixes using `array` and `hash` helper together <ide> - [#18741](https://github.com/emberjs/ember.js/pull/18741) [BUGFIX] Don't setup mandatory setters on array indexes <ide> - [#18767](https://github.com/emberjs/ember.js/pull/18767) [BUGFIX] Fix observer leaks <del>- [#18770](https://github.com/emberjs/ember.js/pull/18770) [BUGFIX] Make ArrayProxy Lazy <add>- [#18770](https://github.com/emberjs/ember.js/pull/18770) [BUGFIX] Make ArrayProxy Lazy <ide> - [#18780](https://github.com/emberjs/ember.js/pull/18780) [BUGFIX] Fix ownerInjection when used to create services directly <ide> - [#18742](https://github.com/emberjs/ember.js/pull/18742) [BUGFIX] Fix setDiff computed macro used within glimmer component <ide> - [#18727](https://github.com/emberjs/ember.js/pull/18727) [BUGFIX] Avoid breaking {{-in-element}} usage <ide> - [#18728](https://github.com/emberjs/ember.js/pull/18728) [BUGFIX] Fix `{{#-in-element}}` double-clearing issue <ide> - [#18703](https://github.com/emberjs/ember.js/pull/18703) [BUGFIX] Correctly links ArrayProxy tags to `arrangedContent` <ide> - [#18707](https://github.com/emberjs/ember.js/pull/18707) [BUGFIX] Fixes tag chaining on Proxy mixins <ide> - [#18708](https://github.com/emberjs/ember.js/pull/18708) [BUGFIX] Ensures the arg proxy works with `get` <del>- [#18694](https://github.com/emberjs/ember.js/pull/18694) [BUGFIX] Ensure tag updates are buffered, remove error message <add>- [#18694](https://github.com/emberjs/ember.js/pull/18694) [BUGFIX] Ensure tag updates are buffered, remove error message <ide> - [#18709](https://github.com/emberjs/ember.js/pull/18709) [BUGFIX] Fix `this` in `@tracked` initializer <ide> <ide> ### v3.16.8 (April 24, 2020) <ide> - [#18217](https://github.com/emberjs/ember.js/pull/18217) [BUGFIX] Adds ability for computed props to depend on args <ide> - [#18222](https://github.com/emberjs/ember.js/pull/18222) [BUGFIX] Matches assertion behavior for CPs computing after destroy <ide> <add>### v3.12.4 (May 21, 2020) <add> <add>- [#18879](https://github.com/emberjs/ember.js/pull/18879) Ensure errors thrown during component construction do not cause (unrelated) errors during application teardown (fixes a common issue when using `setupOnerror` with components asserting during `constructor`/`init`/`didInssertElement`). <add>- [#18273](https://github.com/emberjs/ember.js/pull/18273) [BUGFIX] Fix issues with SSR rehydration of <title>. <add> <ide> ### v3.12.3 (March 12, 2020) <ide> <ide> - [#18809](https://github.com/emberjs/ember.js/pull/18809) [BUGFIX] Do not error (RE: `elementId` changing) if `elementId` is not changed
1
Ruby
Ruby
pull request allocation up one frame
f1175448ec60d359ede10bc63c3d83a1c2515142
<ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def url_for(options) <ide> end <ide> <ide> def call(env) <del> @router.call(env) <add> req = request_class.new(env) <add> req.path_info = Journey::Router::Utils.normalize_path(req.path_info) <add> @router.serve(req) <ide> end <ide> <ide> def recognize_path(path, environment = {})
1
Javascript
Javascript
run jshint task on travis
06557aab44860baf3f121f3db424c5ede0764bf4
<ide><path>Gruntfile.js <ide> module.exports = function(grunt) { <ide> grunt.registerTask('webserver', ['connect:devserver']); <ide> grunt.registerTask('package', ['bower','clean', 'buildall', 'minall', 'collect-errors', 'docs', 'copy', 'write', 'compress']); <ide> grunt.registerTask('package-without-bower', ['clean', 'buildall', 'minall', 'collect-errors', 'docs', 'copy', 'write', 'compress']); <del> grunt.registerTask('ci-checks', ['ddescribe-iit', 'merge-conflict']); <add> grunt.registerTask('ci-checks', ['ddescribe-iit', 'merge-conflict', 'jshint']); <ide> grunt.registerTask('default', ['package']); <ide> };
1
Go
Go
set default exec driver to windows
041ba90dbb713656440fb5eadbd5aba892645350
<ide><path>daemon/config.go <ide> func (config *Config) InstallCommonFlags() { <ide> flag.StringVar(&config.Bridge.DefaultGatewayIPv6, []string{"-default-gateway-v6"}, "", "Container default gateway IPv6 address") <ide> flag.BoolVar(&config.Bridge.InterContainerCommunication, []string{"#icc", "-icc"}, true, "Enable inter-container communication") <ide> flag.StringVar(&config.GraphDriver, []string{"s", "-storage-driver"}, "", "Storage driver to use") <del> flag.StringVar(&config.ExecDriver, []string{"e", "-exec-driver"}, "native", "Exec driver to use") <add> flag.StringVar(&config.ExecDriver, []string{"e", "-exec-driver"}, defaultExec, "Exec driver to use") <ide> flag.IntVar(&config.Mtu, []string{"#mtu", "-mtu"}, 0, "Set the containers network MTU") <ide> flag.BoolVar(&config.EnableCors, []string{"#api-enable-cors", "#-api-enable-cors"}, false, "Enable CORS headers in the remote API, this is deprecated by --api-cors-header") <ide> flag.StringVar(&config.CorsHeaders, []string{"-api-cors-header"}, "", "Set CORS headers in the remote API") <ide><path>daemon/config_linux.go <ide> import ( <ide> var ( <ide> defaultPidFile = "/var/run/docker.pid" <ide> defaultGraph = "/var/lib/docker" <add> defaultExec = "native" <ide> ) <ide> <ide> // Config defines the configuration of a docker daemon. <ide><path>daemon/config_windows.go <ide> import ( <ide> var ( <ide> defaultPidFile = os.Getenv("programdata") + string(os.PathSeparator) + "docker.pid" <ide> defaultGraph = os.Getenv("programdata") + string(os.PathSeparator) + "docker" <add> defaultExec = "windows" <ide> ) <ide> <ide> // Config defines the configuration of a docker daemon.
3
Javascript
Javascript
add loaddocs to showcase
ec6d41414d3608ebd146c495573429de02a68e52
<ide><path>website/src/react-native/showcase.js <ide> var apps = [ <ide> link: 'https://itunes.apple.com/us/app/leanpub/id913517110?ls=1&mt=8', <ide> author: 'Leanpub', <ide> }, <add> { <add> name: 'LoadDocs', <add> icon: 'http://a2.mzstatic.com/us/r30/Purple3/v4/b5/ca/78/b5ca78ca-392d-6874-48bf-762293482d42/icon350x350.jpeg', <add> link: 'https://itunes.apple.com/us/app/loaddocs/id1041596066', <add> author: 'LoadDocs', <add> }, <ide> { <ide> name: 'Lrn', <ide> icon: 'http://is4.mzstatic.com/image/pf/us/r30/Purple1/v4/41/a9/e9/41a9e9b6-7801-aef7-2400-2eca14923321/mzl.adyswxad.png',
1
PHP
PHP
add ld-json and fix mime type for json
4944427809c2c3437870b4a1cf6b102e94e4433e
<ide><path>src/Illuminate/Http/Concerns/InteractsWithContentTypes.php <ide> public function isJson() <ide> */ <ide> public function expectsJson() <ide> { <del> return ($this->ajax() && ! $this->pjax() && $this->acceptsAnyContentType()) || ($this->prefers(['text/html', 'text/json']) === 'text/json'); <add> return ($this->ajax() && ! $this->pjax() && $this->acceptsAnyContentType()) || Str::contains($this->prefers(['text/html', 'application/json', 'application/ld+json']) ?? '', 'json')); <ide> } <ide> <ide> /**
1
PHP
PHP
add type hints and strict types to auth
aa0e24a7adc7a4fd4658afabf94003a7b4fc9be0
<ide><path>src/Auth/AbstractPasswordHasher.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> abstract class AbstractPasswordHasher <ide> * Constructor <ide> * <ide> * @param array $config Array of config. <add> * @return void <ide> */ <ide> public function __construct(array $config = []) <ide> { <ide> public function __construct(array $config = []) <ide> /** <ide> * Generates password hash. <ide> * <del> * @param string|array $password Plain text password to hash or array of data <add> * @param string $password Plain text password to hash <ide> * required to generate password hash. <del> * @return string Password hash <add> * @return mixed Either the password hash string or bool <ide> */ <del> abstract public function hash($password); <add> abstract public function hash(string $password); <ide> <ide> /** <ide> * Check hash. Generate hash from user provided password string or data array <ide> * and check against existing hash. <ide> * <del> * @param string|array $password Plain text password to hash or data array. <add> * @param string $password Plain text password to hash or data array. <ide> * @param string $hashedPassword Existing hashed password. <ide> * @return bool True if hashes match else false. <ide> */ <del> abstract public function check($password, $hashedPassword); <add> abstract public function check(string $password, string $hashedPassword): bool; <ide> <ide> /** <ide> * Returns true if the password need to be rehashed, due to the password being <ide> abstract public function check($password, $hashedPassword); <ide> * @param string $password The password to verify <ide> * @return bool <ide> */ <del> public function needsRehash($password) <add> public function needsRehash(string $password): bool <ide> { <ide> return password_needs_rehash($password, PASSWORD_DEFAULT); <ide> } <ide><path>src/Auth/BaseAuthenticate.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> */ <ide> namespace Cake\Auth; <ide> <add>use Cake\Auth\AbstractPasswordHasher; <ide> use Cake\Controller\ComponentRegistry; <ide> use Cake\Core\InstanceConfigTrait; <ide> use Cake\Event\EventListenerInterface; <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\ORM\Locator\LocatorAwareTrait; <add>use Cake\ORM\Query; <ide> <ide> /** <ide> * Base Authentication class with common methods and properties. <ide> public function __construct(ComponentRegistry $registry, array $config = []) <ide> * and result of find is returned. <ide> * @return bool|array Either false on failure, or an array of user data. <ide> */ <del> protected function _findUser($username, $password = null) <add> protected function _findUser(string $username, ?string $password = null) <ide> { <ide> $result = $this->_query($username)->first(); <ide> <ide> protected function _findUser($username, $password = null) <ide> * @param string $username The username/identifier. <ide> * @return \Cake\ORM\Query <ide> */ <del> protected function _query($username) <add> protected function _query(string $username): Query <ide> { <ide> $config = $this->_config; <ide> $table = $this->getTableLocator()->get($config['userModel']); <ide> protected function _query($username) <ide> * @throws \RuntimeException If password hasher class not found or <ide> * it does not extend AbstractPasswordHasher <ide> */ <del> public function passwordHasher() <add> public function passwordHasher(): AbstractPasswordHasher <ide> { <ide> if ($this->_passwordHasher) { <ide> return $this->_passwordHasher; <ide> public function passwordHasher() <ide> * <ide> * @return bool <ide> */ <del> public function needsPasswordRehash() <add> public function needsPasswordRehash(): bool <ide> { <ide> return $this->_needsPasswordRehash; <ide> } <ide> public function getUser(ServerRequest $request) <ide> * @param \Cake\Http\Response $response A response object. <ide> * @return void <ide> */ <del> public function unauthenticated(ServerRequest $request, Response $response) <add> public function unauthenticated(ServerRequest $request, Response $response): void <ide> { <ide> } <ide> <ide> public function unauthenticated(ServerRequest $request, Response $response) <ide> * <ide> * @return array List of events this class listens to. Defaults to `[]`. <ide> */ <del> public function implementedEvents() <add> public function implementedEvents(): array <ide> { <ide> return []; <ide> } <ide><path>src/Auth/BaseAuthorize.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function __construct(ComponentRegistry $registry, array $config = []) <ide> * @param \Cake\Http\ServerRequest $request Request instance. <ide> * @return bool <ide> */ <del> abstract public function authorize($user, ServerRequest $request); <add> abstract public function authorize($user, ServerRequest $request): bool; <ide> } <ide><path>src/Auth/BasicAuthenticate.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function getUser(ServerRequest $request) <ide> * @return void <ide> * @throws \Cake\Http\Exception\UnauthorizedException <ide> */ <del> public function unauthenticated(ServerRequest $request, Response $response) <add> public function unauthenticated(ServerRequest $request, Response $response): void <ide> { <ide> $Exception = new UnauthorizedException(); <ide> $Exception->responseHeader($this->loginHeaders($request)); <ide> public function unauthenticated(ServerRequest $request, Response $response) <ide> * @param \Cake\Http\ServerRequest $request Request object. <ide> * @return array Headers for logging in. <ide> */ <del> public function loginHeaders(ServerRequest $request) <add> public function loginHeaders(ServerRequest $request): array <ide> { <ide> $realm = $this->getConfig('realm') ?: $request->getEnv('SERVER_NAME'); <ide> <ide><path>src/Auth/ControllerAuthorize.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function __construct(ComponentRegistry $registry, array $config = []) <ide> * @return \Cake\Controller\Controller <ide> * @throws \Cake\Core\Exception\Exception If controller does not have method `isAuthorized()`. <ide> */ <del> public function controller(Controller $controller = null) <add> public function controller(Controller $controller = null): Controller <ide> { <ide> if ($controller) { <ide> if (!method_exists($controller, 'isAuthorized')) { <ide> public function controller(Controller $controller = null) <ide> * @param \Cake\Http\ServerRequest $request Request instance. <ide> * @return bool <ide> */ <del> public function authorize($user, ServerRequest $request) <add> public function authorize($user, ServerRequest $request): bool <ide> { <ide> return (bool)$this->_Controller->isAuthorized($user); <ide> } <ide><path>src/Auth/DefaultPasswordHasher.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class DefaultPasswordHasher extends AbstractPasswordHasher <ide> * @return bool|string Password hash or false on failure <ide> * @link https://book.cakephp.org/3.0/en/controllers/components/authentication.html#hashing-passwords <ide> */ <del> public function hash($password) <add> public function hash(string $password) <ide> { <ide> return password_hash( <ide> $password, <ide> public function hash($password) <ide> * @param string $hashedPassword Existing hashed password. <ide> * @return bool True if hashes match else false. <ide> */ <del> public function check($password, $hashedPassword) <add> public function check(string $password, string $hashedPassword): bool <ide> { <ide> return password_verify($password, $hashedPassword); <ide> } <ide> public function check($password, $hashedPassword) <ide> * @param string $password The password to verify <ide> * @return bool <ide> */ <del> public function needsRehash($password) <add> public function needsRehash(string $password): bool <ide> { <ide> return password_needs_rehash($password, $this->_config['hashType'], $this->_config['hashOptions']); <ide> } <ide><path>src/Auth/DigestAuthenticate.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> <ide> use Cake\Controller\ComponentRegistry; <ide> use Cake\Http\ServerRequest; <del>use Cake\Utility\Security; <ide> <ide> /** <ide> * Digest Authentication adapter for AuthComponent. <ide> public function __construct(ComponentRegistry $registry, array $config = []) <ide> { <ide> $this->setConfig([ <ide> 'nonceLifetime' => 300, <del> 'secret' => Security::getSalt(), <add> 'secret' => 'foo.bar', <ide> 'realm' => null, <ide> 'qop' => 'auth', <ide> 'opaque' => null, <ide> protected function _getDigest(ServerRequest $request) <ide> * @param string $digest The raw digest authentication headers. <ide> * @return array|null An array of digest authentication headers <ide> */ <del> public function parseAuthData($digest) <add> public function parseAuthData(string $digest): ?array <ide> { <ide> if (substr($digest, 0, 7) === 'Digest ') { <ide> $digest = substr($digest, 7); <ide> public function parseAuthData($digest) <ide> * @param string $method Request method <ide> * @return string Response hash <ide> */ <del> public function generateResponseHash($digest, $password, $method) <add> public function generateResponseHash(array $digest, string $password, string $method): string <ide> { <ide> return md5( <ide> $password . <ide> public function generateResponseHash($digest, $password, $method) <ide> * @param string $realm The realm the password is for. <ide> * @return string the hashed password that can later be used with Digest authentication. <ide> */ <del> public static function password($username, $password, $realm) <add> public static function password(string $username, string $password, string $realm): string <ide> { <ide> return md5($username . ':' . $realm . ':' . $password); <ide> } <ide> public static function password($username, $password, $realm) <ide> * @param \Cake\Http\ServerRequest $request Request object. <ide> * @return array Headers for logging in. <ide> */ <del> public function loginHeaders(ServerRequest $request) <add> public function loginHeaders(ServerRequest $request): array <ide> { <ide> $realm = $this->_config['realm'] ?: $request->getEnv('SERVER_NAME'); <ide> <ide> public function loginHeaders(ServerRequest $request) <ide> * <ide> * @return string <ide> */ <del> protected function generateNonce() <add> protected function generateNonce(): string <ide> { <ide> $expiryTime = microtime(true) + $this->getConfig('nonceLifetime'); <ide> $secret = $this->getConfig('secret'); <ide> protected function generateNonce() <ide> * @param string $nonce The nonce value to check. <ide> * @return bool <ide> */ <del> protected function validNonce($nonce) <add> protected function validNonce(string $nonce): bool <ide> { <ide> $value = base64_decode($nonce); <ide> if ($value === false) { <ide><path>src/Auth/FallbackPasswordHasher.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class FallbackPasswordHasher extends AbstractPasswordHasher <ide> * @param array $config configuration options for this object. Requires the <ide> * `hashers` key to be present in the array with a list of other hashers to be <ide> * used <add> * @return void <ide> */ <ide> public function __construct(array $config = []) <ide> { <ide> public function __construct(array $config = []) <ide> * @param string $password Plain text password to hash. <ide> * @return string Password hash <ide> */ <del> public function hash($password) <add> public function hash(string $password): string <ide> { <ide> return $this->_hashers[0]->hash($password); <ide> } <ide> public function hash($password) <ide> * @param string $hashedPassword Existing hashed password. <ide> * @return bool True if hashes match else false. <ide> */ <del> public function check($password, $hashedPassword) <add> public function check(string $password, string $hashedPassword): bool <ide> { <ide> foreach ($this->_hashers as $hasher) { <ide> if ($hasher->check($password, $hashedPassword)) { <ide> public function check($password, $hashedPassword) <ide> * @param string $password The password to verify <ide> * @return bool <ide> */ <del> public function needsRehash($password) <add> public function needsRehash(string $password): bool <ide> { <ide> return $this->_hashers[0]->needsRehash($password); <ide> } <ide><path>src/Auth/FormAuthenticate.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> class FormAuthenticate extends BaseAuthenticate <ide> * @param array $fields The fields to be checked. <ide> * @return bool False if the fields have not been supplied. True if they exist. <ide> */ <del> protected function _checkFields(ServerRequest $request, array $fields) <add> protected function _checkFields(ServerRequest $request, array $fields): bool <ide> { <ide> foreach ([$fields['username'], $fields['password']] as $field) { <ide> $value = $request->getData($field); <ide><path>src/Auth/PasswordHasherFactory.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> */ <ide> namespace Cake\Auth; <ide> <add>use Cake\Auth\AbstractPasswordHasher; <ide> use Cake\Core\App; <ide> use RuntimeException; <ide> <ide> class PasswordHasherFactory <ide> * @throws \RuntimeException If password hasher class not found or <ide> * it does not extend Cake\Auth\AbstractPasswordHasher <ide> */ <del> public static function build($passwordHasher) <add> public static function build($passwordHasher): AbstractPasswordHasher <ide> { <ide> $config = []; <ide> if (is_string($passwordHasher)) { <ide><path>src/Auth/Storage/MemoryStorage.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> */ <ide> namespace Cake\Auth\Storage; <ide> <add>use Cake\Auth\Storage\StorageInterface; <add> <ide> /** <ide> * Memory based non-persistent storage for authenticated user record. <ide> */ <ide> public function read() <ide> /** <ide> * {@inheritDoc} <ide> */ <del> public function write($user) <add> public function write($user): void <ide> { <ide> $this->_user = $user; <ide> } <ide> <ide> /** <ide> * {@inheritDoc} <ide> */ <del> public function delete() <add> public function delete(): void <ide> { <ide> $this->_user = null; <ide> } <ide><path>src/Auth/Storage/SessionStorage.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function read() <ide> * @param array|\ArrayAccess $user User record. <ide> * @return void <ide> */ <del> public function write($user) <add> public function write($user): void <ide> { <ide> $this->_user = $user; <ide> <ide> public function write($user) <ide> * <ide> * @return void <ide> */ <del> public function delete() <add> public function delete(): void <ide> { <ide> $this->_user = false; <ide> <ide><path>src/Auth/Storage/StorageInterface.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> interface StorageInterface <ide> /** <ide> * Read user record. <ide> * <del> * @return \ArrayAccess|array|null <add> * @return mixed \ArrayAccess, array or null <ide> */ <ide> public function read(); <ide> <ide> /** <ide> * Write user record. <ide> * <del> * @param array|\ArrayAccess $user User record. <add> * @param mixed $user array or \ArrayAccess User record. <ide> * @return void <ide> */ <del> public function write($user); <add> public function write($user): void; <ide> <ide> /** <ide> * Delete user record. <ide> * <ide> * @return void <ide> */ <del> public function delete(); <add> public function delete(): void; <ide> <ide> /** <ide> * Get/set redirect URL. <ide><path>src/Auth/WeakPasswordHasher.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function __construct(array $config = []) <ide> * @param string $password Plain text password to hash. <ide> * @return string Password hash <ide> */ <del> public function hash($password) <add> public function hash(string $password): string <ide> { <ide> return Security::hash($password, $this->_config['hashType'], true); <ide> } <ide> public function hash($password) <ide> * @param string $hashedPassword Existing hashed password. <ide> * @return bool True if hashes match else false. <ide> */ <del> public function check($password, $hashedPassword) <add> public function check(string $password, string $hashedPassword): bool <ide> { <ide> return $hashedPassword === $this->hash($password); <ide> } <ide><path>tests/TestCase/Auth/BasicAuthenticateTest.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class BasicAuthenticateTest extends TestCase <ide> * <ide> * @return void <ide> */ <del> public function setUp() <add> public function setUp(): void <ide> { <ide> parent::setUp(); <ide> <ide> public function setUp() <ide> * <ide> * @return void <ide> */ <del> public function testConstructor() <add> public function testConstructor(): void <ide> { <ide> $object = new BasicAuthenticate($this->Collection, [ <ide> 'userModel' => 'AuthUser', <ide> public function testConstructor() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateNoData() <add> public function testAuthenticateNoData(): void <ide> { <ide> $request = new ServerRequest(['url' => 'posts/index']); <ide> <ide> public function testAuthenticateNoData() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateNoUsername() <add> public function testAuthenticateNoUsername(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticateNoUsername() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateNoPassword() <add> public function testAuthenticateNoPassword(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticateNoPassword() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateInjection() <add> public function testAuthenticateInjection(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticateInjection() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateUsernameZero() <add> public function testAuthenticateUsernameZero(): void <ide> { <ide> $User = $this->getTableLocator()->get('Users'); <ide> $User->updateAll(['username' => '0'], ['username' => 'mariano']); <ide> public function testAuthenticateUsernameZero() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateChallenge() <add> public function testAuthenticateChallenge(): void <ide> { <ide> $request = new ServerRequest(['url' => 'posts/index']); <ide> <ide> public function testAuthenticateChallenge() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateSuccess() <add> public function testAuthenticateSuccess(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide><path>tests/TestCase/Auth/ControllerAuthorizeTest.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * ControllerAuthorizeTest file <ide> * <ide> class ControllerAuthorizeTest extends TestCase <ide> * <ide> * @return void <ide> */ <del> public function setUp() <add> public function setUp(): void <ide> { <ide> parent::setUp(); <ide> $this->controller = $this->getMockBuilder(Controller::class) <ide> public function setUp() <ide> /** <ide> * @return void <ide> */ <del> public function testControllerErrorOnMissingMethod() <add> public function testControllerErrorOnMissingMethod(): void <ide> { <ide> $this->expectException(\Cake\Core\Exception\Exception::class); <ide> $this->auth->controller(new Controller()); <ide> public function testControllerErrorOnMissingMethod() <ide> * <ide> * @return void <ide> */ <del> public function testAuthorizeFailure() <add> public function testAuthorizeFailure(): void <ide> { <ide> $user = []; <ide> $request = new ServerRequest(['url' => '/posts/index']); <ide> public function testAuthorizeFailure() <ide> * <ide> * @return void <ide> */ <del> public function testAuthorizeSuccess() <add> public function testAuthorizeSuccess(): void <ide> { <ide> $user = ['User' => ['username' => 'mark']]; <ide> $request = new ServerRequest(['url' => '/posts/index']); <ide><path>tests/TestCase/Auth/DefaultPasswordHasherTest.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class DefaultPasswordHasherTest extends TestCase <ide> * <ide> * @return void <ide> */ <del> public function testNeedsRehash() <add> public function testNeedsRehash(): void <ide> { <ide> $hasher = new DefaultPasswordHasher(); <ide> $this->assertTrue($hasher->needsRehash(md5('foo'))); <ide> public function testNeedsRehash() <ide> * <ide> * @return void <ide> */ <del> public function testNeedsRehashWithDifferentOptions() <add> public function testNeedsRehashWithDifferentOptions(): void <ide> { <ide> $defaultHasher = new DefaultPasswordHasher(['hashType' => PASSWORD_BCRYPT, 'hashOptions' => ['cost' => 10]]); <ide> $updatedHasher = new DefaultPasswordHasher(['hashType' => PASSWORD_BCRYPT, 'hashOptions' => ['cost' => 12]]); <ide><path>tests/TestCase/Auth/DigestAuthenticateTest.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * DigestAuthenticateTest file <ide> * <ide> class DigestAuthenticateTest extends TestCase <ide> * <ide> * @return void <ide> */ <del> public function setUp() <add> public function setUp(): void <ide> { <ide> parent::setUp(); <ide> <ide> $this->Collection = $this->getMockBuilder(ComponentRegistry::class)->getMock(); <ide> $this->auth = new DigestAuthenticate($this->Collection, [ <ide> 'realm' => 'localhost', <ide> 'nonce' => 123, <del> 'opaque' => '123abc' <add> 'opaque' => '123abc', <add> 'secret' => 'foo.bar' <ide> ]); <add> Configure::write('Security.salt', 'foo.bar'); <ide> <ide> $password = DigestAuthenticate::password('mariano', 'cake', 'localhost'); <ide> $User = $this->getTableLocator()->get('Users'); <ide> public function setUp() <ide> * <ide> * @return void <ide> */ <del> public function testConstructor() <add> public function testConstructor(): void <ide> { <ide> $object = new DigestAuthenticate($this->Collection, [ <ide> 'userModel' => 'AuthUser', <ide> public function testConstructor() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateNoData() <add> public function testAuthenticateNoData(): void <ide> { <ide> $request = new ServerRequest(['url' => 'posts/index']); <ide> <ide> public function testAuthenticateNoData() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateWrongUsername() <add> public function testAuthenticateWrongUsername(): void <ide> { <ide> $this->expectException(\Cake\Http\Exception\UnauthorizedException::class); <ide> $this->expectExceptionCode(401); <ide> public function testAuthenticateWrongUsername() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateChallenge() <add> public function testAuthenticateChallenge(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticateChallenge() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateChallengeIncludesStaleAttributeOnStaleNonce() <add> public function testAuthenticateChallengeIncludesStaleAttributeOnStaleNonce(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticateChallengeIncludesStaleAttributeOnStaleNonce() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateFailsOnStaleNonce() <add> public function testAuthenticateFailsOnStaleNonce(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticateFailsOnStaleNonce() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateValidUsernamePasswordNoNonce() <add> public function testAuthenticateValidUsernamePasswordNoNonce(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticateValidUsernamePasswordNoNonce() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateSuccess() <add> public function testAuthenticateSuccess(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticateSuccess() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateSuccessHiddenPasswordField() <add> public function testAuthenticateSuccessHiddenPasswordField(): void <ide> { <ide> $User = $this->getTableLocator()->get('Users'); <ide> $User->setEntityClass(ProtectedUser::class); <ide> public function testAuthenticateSuccessHiddenPasswordField() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateSuccessSimulatedRequestMethod() <add> public function testAuthenticateSuccessSimulatedRequestMethod(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticateSuccessSimulatedRequestMethod() <ide> * <ide> * @return void <ide> */ <del> public function testLoginHeaders() <add> public function testLoginHeaders(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'environment' => ['SERVER_NAME' => 'localhost'] <ide> public function testLoginHeaders() <ide> * <ide> * @return void <ide> */ <del> public function testParseAuthData() <add> public function testParseAuthData(): void <ide> { <ide> $digest = <<<DIGEST <ide> Digest username="Mufasa", <ide> public function testParseAuthData() <ide> * <ide> * @return void <ide> */ <del> public function testParseAuthDataFullUri() <add> public function testParseAuthDataFullUri(): void <ide> { <ide> $digest = <<<DIGEST <ide> Digest username="admin", <ide> public function testParseAuthDataFullUri() <ide> * <ide> * @return void <ide> */ <del> public function testParseAuthEmailAddress() <add> public function testParseAuthEmailAddress(): void <ide> { <ide> $digest = <<<DIGEST <ide> Digest username="mark@example.com", <ide> public function testParseAuthEmailAddress() <ide> * <ide> * @return void <ide> */ <del> public function testPassword() <add> public function testPassword(): void <ide> { <ide> $result = DigestAuthenticate::password('mark', 'password', 'localhost'); <ide> $expected = md5('mark:localhost:password'); <ide> public function testPassword() <ide> * <ide> * @param string $secret The secret to use. <ide> * @param int $expires Time to live <add> * @param int $time Current time in microseconds <ide> * @return string <ide> */ <del> protected function generateNonce($secret = null, $expires = 300, $time = null) <add> protected function generateNonce(string $secret = null, int $expires = 300, int $time = null): string <ide> { <ide> $secret = $secret ?: Configure::read('Security.salt'); <ide> $time = $time ?: microtime(true); <ide> protected function generateNonce($secret = null, $expires = 300, $time = null) <ide> * @param array $data the data to convert into a header. <ide> * @return string <ide> */ <del> protected function digestHeader($data) <add> protected function digestHeader(array $data): string <ide> { <ide> $data += [ <ide> 'username' => 'mariano', <ide><path>tests/TestCase/Auth/FallbackPasswordHasherTest.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class FallbackPasswordHasherTest extends TestCase <ide> * <ide> * @return void <ide> */ <del> public function testHash() <add> public function testHash(): void <ide> { <ide> $hasher = new FallbackPasswordHasher(['hashers' => ['Weak', 'Default']]); <ide> $weak = new WeakPasswordHasher(); <ide> public function testHash() <ide> * <ide> * @return void <ide> */ <del> public function testCheck() <add> public function testCheck(): void <ide> { <ide> $hasher = new FallbackPasswordHasher(['hashers' => ['Weak', 'Default']]); <ide> $weak = new WeakPasswordHasher(); <ide> public function testCheck() <ide> * <ide> * @return void <ide> */ <del> public function testCheckWithConfigs() <add> public function testCheckWithConfigs(): void <ide> { <ide> $hasher = new FallbackPasswordHasher(['hashers' => ['Default', 'Weak' => ['hashType' => 'md5']]]); <ide> $legacy = new WeakPasswordHasher(['hashType' => 'md5']); <ide> public function testCheckWithConfigs() <ide> * <ide> * @return void <ide> */ <del> public function testNeedsRehash() <add> public function testNeedsRehash(): void <ide> { <ide> $hasher = new FallbackPasswordHasher(['hashers' => ['Default', 'Weak']]); <ide> $weak = new WeakPasswordHasher(); <ide><path>tests/TestCase/Auth/FormAuthenticateTest.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class FormAuthenticateTest extends TestCase <ide> * <ide> * @return void <ide> */ <del> public function setUp() <add> public function setUp(): void <ide> { <ide> parent::setUp(); <ide> $this->Collection = $this->getMockBuilder(ComponentRegistry::class)->getMock(); <ide> public function setUp() <ide> * <ide> * @return void <ide> */ <del> public function testConstructor() <add> public function testConstructor(): void <ide> { <ide> $object = new FormAuthenticate($this->Collection, [ <ide> 'userModel' => 'AuthUsers', <ide> public function testAuthenticateNoData() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateNoUsername() <add> public function testAuthenticateNoUsername(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticateNoUsername() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateNoPassword() <add> public function testAuthenticateNoPassword(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticateNoPassword() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticatePasswordIsFalse() <add> public function testAuthenticatePasswordIsFalse(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticatePasswordIsFalse() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticatePasswordIsEmptyString() <add> public function testAuthenticatePasswordIsEmptyString(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticatePasswordIsEmptyString() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateFieldsAreNotString() <add> public function testAuthenticateFieldsAreNotString(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticateFieldsAreNotString() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateInjection() <add> public function testAuthenticateInjection(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticateInjection() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateSuccess() <add> public function testAuthenticateSuccess(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticateSuccess() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateIncludesVirtualFields() <add> public function testAuthenticateIncludesVirtualFields(): void <ide> { <ide> $users = $this->getTableLocator()->get('Users'); <ide> $users->setEntityClass('TestApp\Model\Entity\VirtualUser'); <ide> public function testAuthenticateIncludesVirtualFields() <ide> * <ide> * @return void <ide> */ <del> public function testPluginModel() <add> public function testPluginModel(): void <ide> { <ide> Plugin::load('TestPlugin'); <ide> <ide> public function testPluginModel() <ide> * <ide> * @return void <ide> */ <del> public function testFinder() <add> public function testFinder(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testFinder() <ide> * <ide> * @return void <ide> */ <del> public function testFinderOptions() <add> public function testFinderOptions(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testFinderOptions() <ide> * <ide> * @return void <ide> */ <del> public function testPasswordHasherSettings() <add> public function testPasswordHasherSettings(): void <ide> { <ide> $this->auth->setConfig('passwordHasher', [ <ide> 'className' => 'Default', <ide> public function testPasswordHasherSettings() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateNoRehash() <add> public function testAuthenticateNoRehash(): void <ide> { <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> public function testAuthenticateNoRehash() <ide> * <ide> * @return void <ide> */ <del> public function testAuthenticateRehash() <add> public function testAuthenticateRehash(): void <ide> { <ide> $this->auth = new FormAuthenticate($this->Collection, [ <ide> 'userModel' => 'Users', <ide><path>tests/TestCase/Auth/PasswordHasherFactoryTest.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class PasswordHasherFactoryTest extends TestCase <ide> * <ide> * @return void <ide> */ <del> public function testBuild() <add> public function testBuild(): void <ide> { <ide> $hasher = PasswordHasherFactory::build('Default'); <ide> $this->assertInstanceof('Cake\Auth\DefaultPasswordHasher', $hasher); <ide> public function testBuild() <ide> * <ide> * @return void <ide> */ <del> public function testBuildException() <add> public function testBuildException(): void <ide> { <ide> $this->expectException(\RuntimeException::class); <ide> $this->expectExceptionMessage('Password hasher class "FooBar" was not found.'); <ide><path>tests/TestCase/Auth/Storage/MemoryStorageTest.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class MemoryStorageTest extends TestCase <ide> * <ide> * @return void <ide> */ <del> public function setUp() <add> public function setUp(): void <ide> { <ide> parent::setUp(); <ide> <ide> public function setUp() <ide> * <ide> * @return void <ide> */ <del> public function testWrite() <add> public function testWrite(): void <ide> { <ide> $this->storage->write($this->user); <ide> $this->assertSame($this->user, $this->storage->read()); <ide> public function testWrite() <ide> * <ide> * @return void <ide> */ <del> public function testRead() <add> public function testRead(): void <ide> { <ide> $this->assertNull($this->storage->read()); <ide> } <ide> public function testRead() <ide> * <ide> * @return void <ide> */ <del> public function testDelete() <add> public function testDelete(): void <ide> { <ide> $this->storage->write($this->user); <ide> $this->storage->delete(); <ide> public function testDelete() <ide> * <ide> * @return void <ide> */ <del> public function testRedirectUrl() <add> public function testRedirectUrl(): void <ide> { <ide> $this->assertNull($this->storage->redirectUrl()); <ide> <ide><path>tests/TestCase/Auth/Storage/SessionStorageTest.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class SessionStorageTest extends TestCase <ide> * <ide> * @return void <ide> */ <del> public function setUp() <add> public function setUp(): void <ide> { <ide> parent::setUp(); <ide> <ide> public function setUp() <ide> * <ide> * @return void <ide> */ <del> public function testWrite() <add> public function testWrite(): void <ide> { <ide> $this->session->expects($this->once()) <ide> ->method('write') <ide> public function testWrite() <ide> * <ide> * @return void <ide> */ <del> public function testRead() <add> public function testRead(): void <ide> { <ide> $this->session->expects($this->once()) <ide> ->method('read') <ide> public function testRead() <ide> * <ide> * @return void <ide> */ <del> public function testGetFromLocalVar() <add> public function testGetFromLocalVar(): void <ide> { <ide> $this->storage->write($this->user); <ide> <ide> public function testGetFromLocalVar() <ide> * <ide> * @return void <ide> */ <del> public function testDelete() <add> public function testDelete(): void <ide> { <ide> $this->session->expects($this->once()) <ide> ->method('delete') <ide> public function testDelete() <ide> * <ide> * @return void <ide> */ <del> public function redirectUrl() <add> public function redirectUrl(): void <ide> { <ide> $url = '/url'; <ide> <ide><path>tests/TestCase/Auth/WeakPasswordHasherTest.php <ide> <?php <add>declare(strict_types = 1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class WeakPasswordHasherTest extends TestCase <ide> * <ide> * @return void <ide> */ <del> public function setUp() <add> public function setUp(): void <ide> { <ide> parent::setUp(); <ide> <ide> public function setUp() <ide> * <ide> * @return void <ide> */ <del> public function testNeedsRehash() <add> public function testNeedsRehash(): void <ide> { <ide> $hasher = new WeakPasswordHasher(); <ide> $this->assertTrue($hasher->needsRehash(md5('foo'))); <ide> public function testNeedsRehash() <ide> * <ide> * @return void <ide> */ <del> public function testHashAndCheck() <add> public function testHashAndCheck(): void <ide> { <ide> $hasher = new WeakPasswordHasher(); <ide> $hasher->setConfig('hashType', 'md5');
24
Python
Python
document the version string
2264c395c4c799ca3dbcf5d31a83f6747a6c6b1f
<ide><path>libcloud/__init__.py <ide> <ide> """ <ide> libcloud provides a unified interface to the cloud computing resources. <add> <add>@var __version__: Current version of libcloud <ide> """ <ide> <ide> __version__ = "0.1.1-dev" <ide>\ No newline at end of file
1
PHP
PHP
ensure loading of deprecated classes
8f851206c44d40ed5bce4ad0f0d9b087ead0fd09
<ide><path>src/Command/Command.php <ide> public function execute(Arguments $args, ConsoleIo $io) <ide> { <ide> } <ide> } <add> <add>// phpcs:disable <add>class_alias( <add> 'Cake\Command\Command', <add> 'Cake\Console\Command' <add>); <add>// phpcs:enable <ide><path>src/Console/Command.php <ide> /** <ide> * @deprecated 4.0.0 Use {@link \Cake\Command\Command} instead. <ide> */ <del> <del>class_alias( <del> 'Cake\Command\Command', <del> 'Cake\Console\Command' <del>); <add>class_exists('Cake\Command\Command'); <ide><path>src/Console/ConsoleErrorHandler.php <ide> <?php <ide> declare(strict_types=1); <ide> <del>class_alias( <del> 'Cake\Error\ConsoleErrorHandler', <del> 'Cake\Console\ConsoleErrorHandler' <del>); <add>class_exists('Cake\Error\ConsoleErrorHandler'); <ide> deprecationWarning( <ide> 'Use Cake\Error\ConsoleErrorHandler instead of Cake\Console\ConsoleErrorHandler.' <ide> ); <ide><path>src/Datasource/Paginator.php <ide> <?php <ide> declare(strict_types=1); <ide> <del>class_alias( <del> 'Cake\Datasource\Paging\NumericPaginator', <del> 'Cake\Datasource\Paginator' <del>); <add>class_exists('Cake\Paging\NumericPaginator'); <ide> deprecationWarning( <ide> 'Use Cake\Datasource\Paging\NumericPaginator instead of Cake\Datasource\Paginator.' <ide> ); <ide><path>src/Datasource/PaginatorInterface.php <ide> <?php <ide> declare(strict_types=1); <ide> <del>class_alias( <del> 'Cake\Datasource\Paging\PaginatorInterface', <del> 'Cake\Datasource\PaginatorInterface' <del>); <add>class_exists('Cake\Datasource\Paging\PaginatorInterface'); <ide> deprecationWarning( <ide> 'Use Cake\Datasource\Paging\PaginatorInterface instead of Cake\Datasource\PaginatorInterface.' <ide> ); <ide><path>src/Datasource/Paging/NumericPaginator.php <ide> public function checkLimit(array $options): array <ide> return $options; <ide> } <ide> } <add> <add>// phpcs:disable <add>class_alias( <add> 'Cake\Datasource\Paging\NumericPaginator', <add> 'Cake\Datasource\Paginator' <add>); <add>// phpcs:enable <ide><path>src/Datasource/Paging/PaginatorInterface.php <ide> public function getPagingParams(): array; <ide> } <ide> <ide> // phpcs:disable <del>// The old interface Cake\Datasource\PaginatorInterface will not get loaded during <del>// instanceof / type checks so ensure it's loaded here. <del>class_exists('Cake\Datasource\PaginatorInterface'); <add>class_alias( <add> 'Cake\Datasource\Paging\PaginatorInterface', <add> 'Cake\Datasource\PaginatorInterface' <add>); <ide> // phpcs:enable <ide><path>src/Datasource/Paging/SimplePaginator.php <ide> protected function getCount(QueryInterface $query, array $data): ?int <ide> return null; <ide> } <ide> } <add> <add>// phpcs:disable <add>class_alias( <add> 'Cake\Datasource\Paging\SimplePaginator', <add> 'Cake\Datasource\SimplePaginator' <add>); <add>// phpcs:enable <ide><path>src/Datasource/SimplePaginator.php <ide> <?php <ide> declare(strict_types=1); <ide> <del>class_alias( <del> 'Cake\Datasource\Paging\SimplePaginator', <del> 'Cake\Datasource\SimplePaginator' <del>); <add>class_exists('Cake\Datasource\Paging\SimplePaginator'); <ide> deprecationWarning( <ide> 'Use Cake\Datasource\Paging\SimplePaginator instead of Cake\Datasource\SimplePaginator.' <ide> ); <ide><path>src/Error/ConsoleErrorHandler.php <ide> protected function _stop(int $code): void <ide> exit($code); <ide> } <ide> } <add> <add>// phpcs:disable <add>class_alias( <add> 'Cake\Error\ConsoleErrorHandler', <add> 'Cake\Console\ConsoleErrorHandler' <add>); <add>// phpcs:enable <ide><path>src/Http/Exception/MissingControllerException.php <ide> class MissingControllerException extends CakeException <ide> */ <ide> protected $_messageTemplate = 'Controller class %s could not be found.'; <ide> } <add> <add>// phpcs:disable <add>class_alias( <add> 'Cake\Http\Exception\MissingControllerException', <add> 'Cake\Routing\Exception\MissingControllerException' <add>); <add>// phpcs:enable <ide><path>src/Routing/Exception/MissingControllerException.php <ide> <?php <ide> declare(strict_types=1); <ide> <del>class_alias( <del> 'Cake\Http\Exception\MissingControllerException', <del> 'Cake\Routing\Exception\MissingControllerException' <del>); <add>class_exists('Cake\Http\Exception\MissingControllerException'); <ide> deprecationWarning( <ide> 'Use Cake\Http\Exception\MissingControllerException instead of Cake\Routing\Exception\MissingControllerException.', <ide> 0
12
Ruby
Ruby
fix the application.rb generator
02c3c9dfbcec05e3b0cecc062da8acd0cf7c53e0
<ide><path>railties/lib/rails/generators/actions.rb <ide> def add_source(source, options={}) <ide> # file in config/environments. <ide> # <ide> def environment(data=nil, options={}, &block) <del> sentinel = "Rails::Initializer.run do |config|" <add> sentinel = /class [a-z_:]+ < Rails::Application/i <ide> data = block.call if !data && block_given? <ide> <ide> in_root do
1
PHP
PHP
add tests for array access implementation
cee00096f03e223967a689fdebeca657d5a9c675
<ide><path>tests/Support/SupportCollectionTest.php <ide> public function testOffsetAccess() <ide> $this->assertEquals('jason', $c[0]); <ide> } <ide> <add> public function testArrayAccessOffsetExists() <add> { <add> $c = new Collection(['foo', 'bar']); <add> $this->assertTrue($c->offsetExists(0)); <add> $this->assertTrue($c->offsetExists(1)); <add> $this->assertFalse($c->offsetExists(1000)); <add> } <add> <add> public function testArrayAccessOffsetGet() <add> { <add> $c = new Collection(['foo', 'bar']); <add> $this->assertEquals('foo', $c->offsetGet(0)); <add> $this->assertEquals('bar', $c->offsetGet(1)); <add> } <add> <add> /** <add> * @expectedException PHPUnit_Framework_Error_Notice <add> */ <add> public function testArrayAccessOffsetGetOnNonExist() <add> { <add> $c = new Collection(['foo', 'bar']); <add> $c->offsetGet(1000); <add> } <add> <add> public function testArrayAccessOffsetSet() <add> { <add> $c = new Collection(['foo', 'foo']); <add> <add> $c->offsetSet(1, 'bar'); <add> $this->assertEquals('bar', $c[1]); <add> <add> $c->offsetSet(null, 'qux'); <add> $this->assertEquals('qux', $c[2]); <add> } <add> <add> /** <add> * @expectedException PHPUnit_Framework_Error_Notice <add> */ <add> public function testArrayAccessOffsetUnset() <add> { <add> $c = new Collection(['foo', 'bar']); <add> <add> $c->offsetUnset(1); <add> $c[1]; <add> } <add> <ide> public function testForgetSingleKey() <ide> { <ide> $c = new Collection(['foo', 'bar']);
1
Ruby
Ruby
fix typo `delegte` => `delegate`
edf0c2914cbc980af67472bed69e072e624d0956
<ide><path>lib/arel/visitors/bind_substitute.rb <ide> module Arel <ide> module Visitors <ide> class BindSubstitute <del> def initialize delegte <add> def initialize delegate <ide> @delegate = delegate <ide> end <ide> end
1
Text
Text
add first 4 articles
cf6b82e0925e2795193a4e001b1cc947d26aea7b
<ide><path>threejs/lessons/threejs-fundamentals.md <add>Title: Three.js Fundamentals <add>Description: Your first Three.js lesson starting with the fundamentals <add> <add>This is the first article in a series of articles about three.js. <add>[Three.js](http://threejs.org) is a 3D library that tries to make <add>it as easy as possible to get 3D content on a webpage. <add> <add>Three.js is often confused with WebGL since more often than <add>not, but not always, three.js uses WebGL to draw 3D. <add>WebGL is a very low-level <add>system that only draws points, lines, and triangles. To do <add>anything useful with WebGL generally requires quite a bit of <add>code and that is where three.js comes in. It handlings things <add>like scenes, lights, shadows, materials, textures, all things that you'd <add>have to write yourself if you were to use WebGL directly. <add> <add>These tutorials assume you already know JavaScript and, for the <add>most part they will use ES6 style JavaScript. Most browsers <add>that support three.js are auto-updated so most users should <add>be able to run this code. If you'd like to make this code run <add>on older browsers look into a transpiler like [Babel](http://babel.io). <add> <add>When learning most programming languages the first thing people <add>do is make the computer print `"Hello World!"`. For 3D one <add>of the most common first things to do is to make a 3D cube. <add>so let's start with "Hello Cube!" <add> <add>The first thing we need is a `<canvas>` tag so <add> <add>``` <add><body> <add> <canvas id="c"></canvas> <add></body> <add>``` <add> <add>Three.js will draw into that canvas so we need to look it up <add>and pass it to three.js. <add> <add>``` <add><script> <add>'use strict'; <add> <add>function main() { <add> const canvas = document.querySelector('#c'); <add> const renderer = new THREE.WebGLRenderer({canvas: canvas}); <add> ... <add></script> <add>``` <add> <add>Note there are some esoteric details here. If you don't pass a canvas <add>into three.js it will create one for you but then you have to add it <add>to your document. Where to add it may change depending on your use case <add>and you'll have to change your code so I find that passing a canvas <add>to three.js feels a little more flexible. I can put the canvas anywhere <add>and the code will find it where as if I had code to insert the canvas <add>into to the document I'd likely have to change that code if my use case <add>changed. <add> <add>After we look up the canvas we create a `WebGLRenderer`. The renderer <add>is the thing responsible for actually taking all the data you provide <add>and rendering it to the canvas. In the past there have been other renderers <add>like `CSSRenderer`, a `CanvasRenderer` and in the future there may be a <add>`WebGL2Renderer` or `WebGPURenderer`. For now there's the `WebGLRenderer` <add>that uses WebGL to render 3D to the canvas. <add> <add>Next up we need a camera. <add> <add>``` <add>const fov = 75; <add>const aspect = 2; // the canvas default <add>const zNear = 0.1; <add>const zFar = 5; <add>const camera = new THREE.PerspectiveCamera(fov, aspect, zNear, zFar); <add>``` <add> <add>`fov` is short for `field of view`. In this case 75 degrees in the vertical <add>dimension. Note that most angles in three.js are in radians but for some <add>reason the perspective camera takes degrees. <add> <add>`aspect` is the display aspect of the canvas. We'll go over the details <add>in another article but by default a canvas is 300x150 pixels which makes <add>the aspect 300/150 or 2. <add> <add>`zNear` and `zFar` represent the space in front of the camera <add>that will be rendered. Anything before that range or after that range <add>will be clipped (not drawn). <add> <add>Those 4 settings define a *"frustum"*. A *frustum* is the name of <add>a 3d shape that is like a pyramid with the tip sliced off. In other <add>words think of the word "frustum" as another 3D shape like sphere, <add>cube, prism, frustum. <add> <add><img src="resources/frustum-3d.svg" width="500" class="threejs_center"/> <add> <add>The height of the zNear and zFar planes are determined by the field of view. <add>The width of both planes is determined by the field of view and the aspect. <add> <add>Anything inside the defined frustum will be be drawn. Anything outside <add>will not. <add> <add>The camera defaults to looking down the -Z axis with +Y up. We'll put our cube <add>at the origin so we need to move the camera back a litte from the origin <add>in order to see anything. <add> <add>``` <add>camera.position.z = 2; <add>``` <add> <add>Here's what we're aiming for. <add> <add><img src="resources/scene-down.svg" width="500" class="threejs_center"/> <add> <add>In the diagram above we can see our camera is at `z = 2`. It's looking <add>down the -Z axis. Our frustum starts 0.1 units from the front of the camera <add>and goes to 5 units in front of the camera. Because in this diagram we are looking down, <add>the field of view is affected by the aspect. Our canvas is twice as wide <add>as it is tall so across view the field of view will be much wider than <add>our specified 75 degrees which is the vertical field of view. <add> <add>Next we make a `Scene`. A `Scene` in three.js is a form of scene graph. <add>Anything you want three.js to draw needs to be added to the scene. We'll <add>cover more details of how scenes work in a future article. <add> <add>``` <add>const scene = new THREE.Scene(); <add>``` <add> <add>Next up we create a `BoxGeometry` which contains the data for a box. <add>Almost anything we want to display in Three.js needs geometry which defines <add>the vertices that make up our 3D object. <add> <add>``` <add>const boxWidth = 1; <add>const boxHeight = 1; <add>const boxDepth = 1; <add>const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth); <add>``` <add> <add>We then create a basic material and set its color. Colors can <add>be specified using standard CSS style 6 digit hex color values. <add> <add>``` <add>const material = new THREE.MeshBasicMaterial({color: 0x44aa88}); <add>``` <add> <add>We then create a `Mesh`. A `Mesh` in three represents the combination <add>of a `Geometry` (the shape of the object) and a `Material` (how to draw <add>the object, shiny or flat, what color, what texture(s) to apply. Etc.) <add>as well as the position, orientation, and scale of that <add>object in the scene. <add> <add>``` <add>const cube = new THREE.Mesh(geometry, material); <add>``` <add> <add>And finally we add that mesh to the scene <add> <add>``` <add>scene.add(cube); <add>``` <add> <add>We can then render the scene by calling the renderer's render function <add>and passing it the scene and the camera <add> <add>``` <add>renderer.render(scene, camera); <add>``` <add> <add>Here's a working exmaple <add> <add>{{{example url="../threejs-fundamentals.html" }}} <add> <add>It's kind of hard to tell that is a 3D cube since we're viewing <add>it directly down the -Z axis and the cube itself is axis aligned <add>so we're only seeing a single face. <add> <add>Let's animate it spinning and hopefully that will make <add>it clear it's being drawn in 3D. To animate it we'll render inside a render loop using <add>[`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame). <add> <add>Here's our loop <add> <add>``` <add>function render(time) { <add> time *= 0.001; // convert time to seconds <add> <add> cube.rotation.x = time; <add> cube.rotation.y = time; <add> <add> renderer.render(scene, camera); <add> <add> requestAnimationFrame(render); <add>} <add>requestAnimationFrame(render); <add>``` <add> <add>`requestAnimationFrame` is a request to the browser that you want to animate something. <add>You pass it a function to be called. In our case that function is `render`. The browser <add>will call your function and if you update anything related to the display of the <add>page the browser will re-render the page. In our case we are calling three's <add>`renderer.render` function which will draw our scene. <add> <add>`requestAnimationFrame` passes the time since the page started rendering to <add>the our function. That time is passed in milliseconds. I find it's much <add>easier to work with seconds so here we're converting that to seconds. <add> <add>We then set the cube's X and Y rotation to the current time. These rotations <add>are in [radians](https://en.wikipedia.org/wiki/Radian). There are 2 pi radians <add>in a circle so our cube should turn around once on each axis in about 6.28 <add>seconds. <add> <add>We then render the scene and request another animation frame to continue <add>our loop. <add> <add>Outside the loop we call `requestAnimationFrame` one time to start the loop. <add> <add>{{{example url="../threejs-fundamentals-with-animation.html" }}} <add> <add>It's a little better but it's still hard to see the 3d. What would help is to add some lighting <add>so let's add a light. There are many kinds of lights in three.js which <add>we'll go over in a future article. For now let's create a directional <add>light. <add> <add>``` <add>{ <add> const color = 0xFFFFFF; <add> const intensity = 1; <add> const light = new THREE.DirectionalLight(color, intensity); <add> light.position.set(-1, 2, 4); <add> scene.add(light); <add>} <add>``` <add> <add>Directional lights have a position and a target. Both default to 0, 0, 0. In our <add>case we're setting the light's position to -1, 2, 4 so it's slightly on the left, <add>above, and behind our camera. The target is still 0, 0, 0 so it will shine <add>toward the origin. <add> <add>We also need to change the material. The `MeshBasicMaterial` is not affected by <add>lights. Let's change it to a `MeshPhongMaterial` which is affected by lights. <add> <add>``` <add>-const material = new THREE.MeshBasicMaterial({color: 0x44aa88}); // greenish blue <add>+const material = new THREE.MeshPhongMaterial({color: 0x44aa88}); // greenish blue <add>``` <add> <add>And here it is working. <add> <add>{{{example url="../threejs-fundamentals-with-light.html" }}} <add> <add>It should now be pretty clearly 3D. <add> <add>Just for the fun of it let's add 2 more cubes. <add> <add>We'll use the same geometry for each cube but make a different <add>material so each cube can be a different color. <add> <add>First we'll make a function that creates a new material <add>with the specified color. Then it creates a mesh using <add>the specified geometry and adds it to the scene and <add>sets its X position. <add> <add>``` <add>function makeInstance(geometry, color, x) { <add> const material = new THREE.MeshPhongMaterial({color}); <add> <add> const cube = new THREE.Mesh(geometry, material); <add> scene.add(cube); <add> <add> cube.position.x = x; <add> <add> return cube; <add>} <add>``` <add> <add>Then we'll call it 3 times with 3 different colors and X positions <add>saving the `Mesh` instances in an array. <add> <add>``` <add>const cubes = [ <add> makeInstance(geometry, 0x44aa88, 0), <add> makeInstance(geometry, 0x8844aa, -2), <add> makeInstance(geometry, 0xaa8844, 2), <add>]; <add>``` <add> <add>Finally we'll spin all 3 cubes in our render function. We <add>compute a slightly different rotation for each one. <add> <add>``` <add>function render(time) { <add> time *= 0.001; // convert time to seconds <add> <add> cubes.forEach((cube, ndx) => { <add> const speed = 1 + ndx * .1; <add> const rot = time * speed; <add> cube.rotation.x = rot; <add> cube.rotation.y = rot; <add> }); <add> <add> ... <add>``` <add> <add>and here's that. <add> <add>{{{example url="../threejs-fundamentals-3-cubes.html" }}} <add> <add>If you compare it to the top down diagram above you can see <add>it matches our expectections. With cubes at X = -2 and X = +2 <add>they are partially outside our frustum. They are also <add>somewhat exaggeratedly warped since the field of view <add>across the canvas is so extreme. <add> <add>I hope this short intro helps to get things started. [Next up we'll cover <add>making our code responsive so it is adaptable to multiple situations](threejs-responsive.html). <add> <ide><path>threejs/lessons/threejs-materials-and-lights.md <add>Title: Three.js Materials and Lights <add>Description: Materials and Lights <add> <add>This article is part of a series of articles about three.js. The <add>first article is [three.js fundamentals](three-fundamentals.html). If <add>you haven't read yet you might want to consider starting there. <add> <add>TBD <ide><path>threejs/lessons/threejs-primitives.md <add>Title: Three.js Primitives <add>Description: A tour of three.js primitives. <add> <add>This article one in a series of articles about three.js. <add>The first article was [about fundamentals](threejs-fundamentals.html). <add>If you haven't read that yet you might want to start there. <add> <add>Three.js has a large number of primitives. Primitives <add>are generally 3D shapes that are generated at runtime <add>with a bunch of parameters. <add> <add>It's common to use primitives for things like a sphere <add>for globe or a bunch of boxes to draw a 3D graph. It's <add>especially common to use primitives to experiment <add>and get started with 3D. For the majority if 3D apps <add>it's more common to have an artist make 3D models <add>in a 3D modeling program. Later in this series we'll <add>cover making and loading data from several 3D modeling <add>programs. For now let's go over some of the available <add>primitives. <add> <add><div class="primitives"> <add><div data-primitive="BoxBufferGeometry">A Box</div> <add><div data-primitive="CircleBufferGeometry">A flat circle</div> <add><div data-primitive="ConeBufferGeometry">A Cone</div> <add><div data-primitive="CylinderBufferGeometry">A Cylinder</div> <add><div data-primitive="DodecahedronBufferGeometry">A dodecahedron (12 sides)</div> <add><div data-primitive="ExtrudeBufferGeometry">An extruded 2d shape with optional bevelling. <add>Here we are extruding a heart shape. Note this is the basis <add>for <code>TextBufferGeometry</code> and <code>TextGeometry</code> respectively.</div> <add><div data-primitive="IcosahedronBufferGeometry">An icosahedron (20 sides)</div> <add><div data-primitive="LatheBufferGeometry">A shape generated by spinning a line. Examples would lamps, bowling pins, candles, candle holders, wine glasses, drinking glasses, etc... You provide the 2d silhouette as series of points and then tell three.js how many subdivisions to make as it spins the silhouette around an axis.</div> <add><div data-primitive="OctahedronBufferGeometry">An Octahedron (8 sides)</div> <add><div data-primitive="ParametricBufferGeometry">A surface generated by providing a function that takes a 2d point from a grid and returns the corresponding 3d point.</div> <add><div data-primitive="PlaneBufferGeometry">A 2D plane</div> <add><div data-primitive="PolyhedronBufferGeometry">Takes a set of triangles centered around a point and projects them onto a sphere</div> <add><div data-primitive="RingBufferGeometry">A 2D disc with a hole in the center</div> <add><div data-primitive="ShapeBufferGeometry">A 2d outline that gets trianglulated</div> <add><div data-primitive="SphereBufferGeometry">A sphere</div> <add><div data-primitive="TetrahedronBufferGeometry">A terahedron (4 sides)</div> <add><div data-primitive="TextBufferGeometry">3D Text generated from a 3D font and a string</div> <add><div data-primitive="TorusBufferGeometry">A torus (donut)</div> <add><div data-primitive="TorusKnotBufferGeometry">A torus knot</div> <add><div data-primitive="TubeBufferGeometry">A circle traced down a path</div> <add><div data-primitive="EdgesGeometry">A helper object that takes another geometry as input and generates edges only if the angle between faces is greater than some threshold. For example if you look at the box at the top it shows a line going through each face showing every triangle that makes the box. Using an EdgesGeometry instead the middle lines are removed.</div> <add><div data-primitive="WireframeGeometry">Generates geometry that contains one line segment (2 points) per edge in the given geometry. With out this you'd often be missing edges or get extra edges since WebGL generally requires 2 points per line segment. For example if all you had was a single triangle there would only be 3 points. If you tried to draw it using a material with <code>wireframe: true</code> you would only get a single line. Passing that triangle geometry to a <code>WireframeGeometry</code> will generate a new Geometry that has 3 lines segments using 6 points..</div> <add></div> <add> <add>You might notice of most of them come in pairs of `Geometry` <add>or `BufferGeometry`. The difference between the 2 types is effectively flexibility <add>vs performance. <add> <add>`BufferGeometry` based primitves are the performance oriented <add>types. The vertices for the geometry are generated directly <add>into an efficient typed array format ready to be uploaded to the GPU <add>for rendering. This means they are faster to start up <add>and take less memory but if you want to modify their <add>data they take what is often considered more complex <add>programming to manipulate. <add> <add>`Geometry` based primitives are the more flexible, easier to manipulate <add>type. They are built from JavaScript based classes like `Vector3` for <add>3D points, `Face3` for triangles. <add>They take quite a bit of memory and before they can be rendered three.js will need to <add>convert them to something similar to the corresponding `BufferGeometry` representation. <add> <add>If you know you are not going to manipulate a primitive or <add>if you're comfortable doing the math to manipulate their <add>internals then it's best to go with the `BufferGeometry` <add>based primitives. If on the other hand you want to change <add>a few things before rendering you might find the `Geometry` <add>based primitives easier to deal with. <add> <add>As an simple example a `BufferGeometry` <add>can not have new vertices easily added. The number of vertices used is <add>decided at creation time, storage is created, and then data for vertices <add>are filled in. Where as for `Geometry` you can add vertices as you go. <add> <add>We'll go over creating custom geometry in another article. For now <add>let's make an example creating each type of primitive. We'll start <add>with the [examples from the previous article](threejs-responsive.html). <add> <add>Near the top let's set a background color <add> <add>``` <add>const canvas = document.querySelector('#c'); <add>const renderer = new THREE.WebGLRenderer({canvas: canvas}); <add>+renderer.setClearColor(0xAAAAAA); <add>``` <add> <add>This tells three.js to clear to lightish gray. <add> <add>The camera needs to change position so that we can see all the <add>objects. <add> <add>``` <add>-const fov = 75; <add>+const fov = 40; <add>const aspect = 2; // the canvas default <add>const zNear = 0.1; <add>-const zFar = 5; <add>+const zFar = 1000; <add>const camera = new THREE.PerspectiveCamera(fov, aspect, zNear, zFar); <add>-camera.position.z = 2; <add>+camera.position.z = 120; <add>``` <add> <add>Let's add a function, `addObject`, that takes an x, y position and an `Object3D` and adds <add>the object to the scene. <add> <add>``` <add>const objects = []; <add>const spread = 15; <add> <add>function addObject(x, y, obj) { <add> obj.position.x = x * spread; <add> obj.position.y = y * spread; <add> <add> scene.add(obj); <add> objects.push(obj); <add>} <add>``` <add> <add>Let's also make a function to create a random colored material. <add>We'll use a feature of `Color` that lets you set a color <add>based on hue, saturation, and luminance. <add> <add>`hue` goes from 0 to 1 around the color wheel with <add>red at 0, green at .33 and blue at .66. `saturation` <add>goes from 0 to 1 with 0 having no color and 1 being <add>most saturated. `luminance` goes from 0 to 1 <add>with 0 being black, 1 being white and 0.5 being <add>the maximum amount of color. In other words <add>as `luminance` goes from 0.0 to 0.5 the color <add>will go from black to `hue`. From 0.5 to 1.0 <add>the color will go from `hue` to white. <add> <add>``` <add>function createMaterial() { <add> const material = new THREE.MeshPhongMaterial({ <add> side: THREE.DoubleSide, <add> }); <add> <add> const hue = Math.random(); <add> const saturation = 1; <add> const luminance = .5; <add> material.color.setHSL(hue, saturation, luminance); <add> <add> return material; <add>} <add>``` <add> <add>We also passed `side: THREE.DoubleSide` to the material. <add>This tells three to draw both sides of the triangles <add>that make up a shape. For a solid shape like a sphere <add>or a cube there's usually no reason to draw the <add>back sides of triangles as they all face inside the <add>shape. In our case though we are drawing a few things <add>like the `PlaneBufferGeometry` and the `ShapeBufferGeometry` <add>which are 2 dimensional and so have no inside. Without <add>setting `side: THREE.DoubleSide` they would disappear <add>when looking at their back sides. <add> <add>I should note that it's faster to draw when **not** setting <add>`side: THREE.DoubleSide` so ideally we'd set it only on <add>the materials that really need it but in this case we <add>are not drawing too much so there isn't much reason to <add>worry about it. <add> <add>Let's make a function, `addSolidGeometry`, that <add>we pass a geometry and it creates a random colored <add>material via `createMaterial` and adds it to the scene <add>via `addObject`. <add> <add>``` <add>function addSolidGeometry(x, y, geometry) { <add> const mesh = new THREE.Mesh(geometry, createMaterial()); <add> addObject(x, y, mesh); <add>} <add>``` <add> <add>Now we can use this for the majority of the primitves we create. <add>For example creating a box <add> <add>``` <add>{ <add> const width = 8; <add> const height = 8; <add> const depth = 8; <add> addSolidGeometry(-2, -2, new THREE.BoxBufferGeometry(width, height, depth)); <add>} <add>``` <add> <add>If you look in the code below you'll see a similar section for each type of geometry. <add> <add>Here's the result: <add> <add>{{{example url="../threejs-primitives.html" }}} <add> <add>There are a couple of notable exceptions to the pattern above. <add>The biggest is probably the `TextBufferGeometry`. It needs to load <add>3D font data before it can generate a mesh for the text. <add>That data loads asynchronously so we need to wait for it <add>to load before trying to create the geometry. You can see below <add>we create a `FontLoader` and pass it the url to our font <add>and a callback. The callback is called after the font loads. <add>In the callback we create the geometry <add>and call `addObject` to add it the scene. <add> <add>``` <add>{ <add> const loader = new THREE.FontLoader(); <add> loader.load('resources/threejs/fonts/helvetiker_regular.typeface.json', (font) => { <add> const geometry = new THREE.TextBufferGeometry('three.js', { <add> font: font, <add> size: 3.0, <add> height: .2, <add> curveSegments: 12, <add> bevelEnabled: true, <add> bevelThickness: 0.15, <add> bevelSize: .3, <add> bevelSegments: 5, <add> }); <add> const mesh = new THREE.Mesh(geometry, createMaterial()); <add> geometry.computeBoundingBox(); <add> geometry.boundingBox.getCenter(mesh.position).multiplyScalar(-1); <add> <add> const parent = new THREE.Object3D(); <add> parent.add(mesh); <add> <add> addObject(-1, 1, parent); <add> }); <add>} <add>``` <add> <add>There's one other difference. We want to spin the text around its <add>center but by default three.js creates the text such that its center of rotation <add>is on the left edge. To work around this we can ask three.js to compute the bounding <add>box of the geometry. We can then call the `getCenter` method <add>of the bounding box and pass it our mesh's position object. <add>`getCenter` copies the center of the box into the position. <add>It also returns the position object so we can call `multiplyScaler(-1)` <add>to position the entire object such that its center of rotation <add>is at the center of the object. <add> <add>If we then just called `addSolidGeometry` like with previous <add>examples it would set the position again which is <add>no good. So, in this case we create an `Object3D` which <add>is the standard node for the three.js scene graph. `Mesh` <add>is inherited from `Object3D` as well. We'll cover [how the scene graph <add>works in another article](threejs-scenegraph.html). <add>For now it's enough to know that <add>like DOM nodes, children are drawn relative to their parent. <add>By making an `Object3D` and making our mesh a child of that <add>we can position the `Object3D` where ever we want and still <add>keep the center offset we set earilier. <add> <add>If we didn't do this the text would spin off center. <add> <add>{{{example url="../threejs-primitives-text.html" }}} <add> <add>Notice the one on the left is not spinning around its center <add>where as the one on the right is. <add> <add>The other exceptions are the 2 line based examples for `EdgesGeometry` <add>and `WireframeGeometry`. Instead of calling `addSolidGeometry` they call <add>`addLineGeomtry` which looks like this <add> <add>``` <add>function addLineGeometry(x, y, geometry) { <add> const material = new THREE.LineBasicMaterial({color: 0x000000}); <add> const mesh = new THREE.LineSegments(geometry, material); <add> addObject(x, y, mesh); <add>} <add>``` <add> <add>It creates a black `LineBasicMaterial` and then creates a `LineSegments` <add>object which is a wrapper for `Mesh` that helps three know you're rendering <add>line segments (2 points per segment). <add> <add>Each of the primitives has several parameters you can pass on creation <add>and it's best to [look in the documentation](https://threejs.org/docs/) for all of them rather than <add>repeat them here. You can also click the links above next to each shape <add>to take you directly to the docs for that shape. <add> <add>One other thing that's important to cover is that almost all shapes <add>have various settings for how much to subdivde them. A good example <add>might be the sphere geometries. Spheres take parameters for <add>how many divisions to make around and how many top to bottom. For example <add> <add><div class="spread"> <add><div data-primitive-diagram="SphereBufferGeometryLow"></div> <add><div data-primitive-diagram="SphereBufferGeometryMedium"></div> <add><div data-primitive-diagram="SphereBufferGeometryHigh"></div> <add></div> <add> <add>The first sphere has 5 segments around and 3 high which is 15 segments <add>or 30 triangles. The second sphere has 24 segments by 10. That's 240 segments <add>or 480 triangles. The last one has 50 by 50 which is 2500 segments or 5000 triangles. <add> <add>It's up to you to decide how many subdivisions you need. It might <add>look like you need a high number of segments but remove the lines <add>and the flat shading and we get this <add> <add><div class="spread"> <add><div data-primitive-diagram="SphereBufferGeometryLowSmooth"></div> <add><div data-primitive-diagram="SphereBufferGeometryMediumSmooth"></div> <add><div data-primitive-diagram="SphereBufferGeometryHighSmooth"></div> <add></div> <add> <add>It's now not so clear that the one on the right with 5000 triangles <add>is entirely better than the one in the middle with only 480. <add>If you're only drawing a few spheres, like say a single globe for <add>a map of the earth, then a single 10000 triangle sphere is not a bad <add>choice. If on the otherhand you're trying to draw 1000 spheres <add>then 1000 spheres times 10000 triangles each is 10 million triangles. <add>To animate smoothly you need the browser to draw at 60 frames a <add>second so you'd be asking the browser to draw 600 million triangles <add>per second. That's a lot of computing. <add> <add>Sometimes it's easy to choose. For example you can also choose <add>to subdivide a plane. <add> <add><div class="spread"> <add><div data-primitive-diagram="PlaneBufferGeometryLow"></div> <add><div data-primitive-diagram="PlaneBufferGeometryHigh"></div> <add></div> <add> <add>The plane on the left is 2 triangles. The plane on the right <add>is 200 triangles. Unlike the sphere there is really no trade off in quality for most <add>use cases of a plane. You'd most likely only subdivide a plane <add>if you expected to want to modify or warp it in some way. A box <add>is similar. <add> <add>So, choose whatever is appropriate for your situation. The less <add>subdivisions you choose the more likely things will run smoothly and the less <add>memory they'll take. You'll have to decide for yourself what the correct <add>tradeoff is for your particular siutation. <add> <add>Next up let's go over [how three's scene graph works and how <add>to use it](threejs-scenegraph.html). <add> <add><canvas id="c"></canvas> <add><script src="../resources/threejs/r94/three.min.js"></script> <add><script src="../resources/threejs/r94/js/controls/TrackballControls.js"></script> <add><script src="resources/threejs-primitives.js"></script> <add><style> <add>.spread { <add> display: flex; <add>} <add>.spread>div { <add> flex: 1 1 auto; <add> height: 150px; <add>} <add>.primitives { <add>} <add>.primitives>div { <add> display: flex; <add> align-items: center; <add> margin-bottom: 1em; <add>} <add>.primitives .shape { <add> flex: 0 0 auto; <add> width: 200px; <add> height: 200px; <add>} <add>.primitives .desc { <add> word-wrap: break-word; <add> padding: 1em; <add> min-width: 0; <add>} <add>.primitives .desc code { <add> white-space: normal; <add>} <add>@media (max-width: 550px) { <add> .primitives .shape { <add> width: 120px; <add> height: 120px; <add> } <add>} <add>.primitives .desc { <add> flex: 1 1 auto; <add>} <add>#c { <add> position: absolute; <add> top: 0; <add> left: 0; <add> width: 100vw; <add> height: 100vh; <add> z-index: -100; <add>} <add></style> <add> <add> <ide><path>threejs/lessons/threejs-responsive.md <add>Title: Three.js Responsive Design <add>Description: How to make your three.js fit different sized displays. <add> <add>This is the second article in a series of articles about three.js. <add>The first article was [about fundamentals](threejs-fundamentals.html). <add>If you haven't read that yet you might want to start there. <add> <add>This article is about how to make your three.js app be responsive <add>to any situation. Making a webpage responsive generally refers <add>to the page displaying well on different sized displays from <add>desktops to tablets to phones. <add> <add>For three.js there are even more situations to consider. For <add>example a 3D editor with controls on the left, right, top, or <add>bottom is something we might want to handle. A live diagram <add>in the middle of a document is another example. <add> <add>The last sample we had used a plain canvas with no css and <add>no size <add> <add>``` <add><canvas id="c"></canvas> <add>``` <add> <add>That canvas defaults to 300x150 css pixels in size. <add> <add>In the web platform the recommended way to set the size <add>of something is to use CSS. <add> <add>Let's make the canvas fill the page by adding CSS <add> <add>``` <add><style> <add>html, body { <add> margin: 0; <add> height: 100%; <add>} <add>#c { <add> width: 100%; <add> height: 100%; <add> display: block; <add>} <add></style> <add>``` <add> <add>In HTML the body has a margin of 5px pixels by default so setting the <add>margin to 0 removes the margin. Setting the html and body height to 100% <add>makes them fill the window. Otherwise they are only as large <add>as the content that fills them. <add> <add>Next we tell the `id=c` element to be <add>100% the size of its container which in this case is the body of <add>the document. <add> <add>Finally we set its `display` mode to `block`. A canvas's <add>default display mode is `inline`. Inline <add>elements can end up adding whitespace to what is displayed. By <add>setting the canvas to `block` that issue goes away. <add> <add>Here's the result <add> <add>{{{example url="../threejs-responsive-no-resize.html" }}} <add> <add>You can see the canvas is now filling the page but there are 2 <add>problems. One our cubes are stretched. They are not cubes they <add>are more like boxes. Too tall or too wide. Open the <add>example in its own window and resize it. You'll see how <add>the cubes get stretched wide and tall. <add> <add><img src="resources/images/resize-incorrect-aspect.png" width="407" class="threejs_center"> <add> <add>The second problem is they look low resolution or blocky and <add>blurry. Stretch the window really large and you'll really see <add>the issue. <add> <add><img src="resources/images/resize-low-res.png" class="threejs_center"> <add> <add>Let's fix the stretchy problem first. To do that we need <add>to set the aspect of the camera to the aspect of the canvas's <add>display size. We can do that by looking at the canvas's <add>`clientWidth` and `clientHeight` properties. <add> <add>We'll update our render loop like this <add> <add>``` <add>function render(time) { <add> time *= 0.001; <add> <add>+ const canvas = renderer.domElement; <add>+ camera.aspect = client.clientWidth / client.clientHeight; <add>+ camera.updateProjectionMatrix(); <add> <add> ... <add>``` <add> <add>Now the cubes should stop being distorted. <add> <add>{{{example url="../threejs-responsive-update-camera.html" }}} <add> <add>Open the example in a separate window and resize the window <add>and you should see the cubes are no longer stretched tall or wide. <add>They stay the correct aspect regardless of window size. <add> <add><img src="resources/images/resize-correct-aspect.png" width="407" class="threejs_center"> <add> <add>Now let's fix the blockiness. <add> <add>Canvas elements have 2 sizes. One size is the size the canvas is displayed <add>on the page. That's what we set with CSS. The other size is the <add>number of pixels in the canvas itself. This is no different than an image. <add>For example we might have a 128x64 pixel image and using <add>css we might display as 400x200 pixels. <add> <add>``` <add><img src="some128x64image.jpg" style="width:400px; height:200px"> <add>``` <add> <add>A canvas's internal size, its resolution, is often called its drawingbuffer size. <add>In three.js we can set the canvas's drawingbuffer size by calling `renderer.setSize`. <add>What size should we pick? The most obvious answer is "the same size the canvas is displayed". <add>Again, to do that we can look at the canvas's `clientWidth` and `clientHeight` <add>attributes. <add> <add>Let's write a function that checks if the renderer's canvas is not <add>already the size it is being displayed as and if so set its size. <add> <add>``` <add>function resizeRendererToDisplaySize(renderer) { <add> const canvas = renderer.domElement; <add> const width = canvas.clientWidth; <add> const height = canvas.clientHeight; <add> const needResize = canvas.width !== width || canvas.height !== height; <add> if (needResize) { <add> renderer.setSize(width, height, false); <add> } <add> return needResize; <add>} <add>``` <add> <add>Notice we check if the canvas actually needs to be resized. Resizing the canvas <add>is an interesting part of the canvas spec and it's best not to set the same <add>size if it's already the size we want. <add> <add>Once we know if we need to resize or not we then call `renderer.setSize` and <add>pass in the new width and height. It's important to pass `false` at the end. <add>`render.setSize` by default sets the canvas's CSS size but doing so is not <add>what we want. We want the browser to continue to work how it does for all other <add>elements which is to use CSS to determine the display size of the element. We don't <add>want canvases used by three to be different than other elements. <add> <add>Note that our function returns true if the canvas was resized. We can use <add>this to check if there are other things we should update. Let's modify <add>our render loop to use the new function <add> <add>``` <add>function render(time) { <add> time *= 0.001; <add> <add>+ if (resizeRendererToDisplaySize(renderer)) { <add>+ const canvas = renderer.domElement; <add>+ camera.aspect = client.clientWidth / client.clientHeight; <add>+ camera.updateProjectionMatrix(); <add>+ } <add> <add> ... <add>``` <add> <add>Since the apsect is only going to change if the canvas's display size <add>changed we only set the camera's aspect if `resizeRendererToDisplaySize` <add>returns `true`. <add> <add>{{{example url="../threejs-responsive.html" }}} <add> <add>It should now render with a resolution that matches the display <add>size of the canvas. <add> <add>To make the point about letting CSS handle the resizing let's take <add>our code and put it in a [separate `.js` file](../resources/threejs-responsive.js). <add>Here then are a few more examples where we let CSS choose the size and notice we had <add>to change zero code for them to work. <add> <add>Let's put our cubes in the middle of a paragraph of text. <add> <add>{{{example url="../threejs-responsive-paragraph.html" startPane="html" }}} <add> <add>and here's our same code used in an editor style layout <add>where the control area on the right can be resized. <add> <add>{{{example url="../threejs-responsive-editor.html" startPane="html" }}} <add> <add>The important part to notice is no code changed. Only our HTML and CSS <add>changed. <add> <add>## Handling HD-DPI displays <add> <add>HD-DPI stands for high-density dot per inch displays. <add>That's most Mac's now a days and many windows machines <add>as well as pretty much all smartphones. <add> <add>The way this works in the browser is they use <add>CSS pixels to set the sizes which are suppose to be the same <add>regardless of how high res the display is. The browser <add>will the just render text with more detail but the <add>same physical size. <add> <add>There are various ways to handle HD-DPI with three.js. <add> <add>The first one is just not to do anything special. This <add>is arguably the most common. Rendering 3D graphics <add>takes a lot of GPU processing power. Mobile GPUs have <add>less power than desktops, at least as of 2018, and yet <add>mobile phones often have very high resolution displays. <add>The current top of the line phones have a HD-DPI ratio <add>of 3x meaning for every one pixel from a non-HD-DPI display <add>those phones have 9 pixels. That means they have to do 9x <add>the rendering. <add> <add>Computing 9x the pixels is a lot of work so if we just <add>leave the code as it is we'll compute 1x the pixels and the <add>browser will just draw it at 3x the size (3x by 3x = 9x pixels). <add> <add>For any heavy three.js app that's probably what you want <add>otherwise you're likely to get a slow framerate. <add> <add>That said if you actually do want to render at the resolution <add>of the device there are a couple of ways to do this in three.js. <add> <add>One is to tell three.js a resolution multiplier using `renderer.setPixelRatio`. <add>You ask the browser what the multiplier is from CSS pixels to device pixels <add>and pass that to three.js <add> <add> renderer.setPixelRatio(window.devicePixelRatio); <add> <add>After that any calls to `renderer.setSize` will magicially <add>use the size you request multiplied by whatever pixel ratio <add>you passed in. <add> <add>The other way is to do it yourself when you resize the canvas. <add> <add>``` <add> function resizeRendererToDisplaySize(renderer) { <add> const canvas = renderer.domElement; <add> const pixelRatio = window.devicePixelRatio; <add> const width = canvas.clientWidth * pixelRatio; <add> const height = canvas.clientHeight * pixelRatio; <add> const needResize = canvas.width !== width || canvas.height !== height; <add> if (needResize) { <add> renderer.setSize(width, height, false); <add> } <add> return needResize; <add> } <add>``` <add> <add>I prefer this second way. Why? Because it means I get what I ask for. <add>There are many cases when using three.js where we need to know the actual <add>size of the canvas's drawingBuffer. For example when making a post processing filter, <add>or if we are making a shader that accesses `gl_FragCoord`, etc... <add>By doing it oursevles we always know the size being used is the size we requested. <add>There is no special case where magic is happening behind the scenes. <add> <add>Here's an example using the code above. <add> <add>{{{example url="../threejs-responsive-hd-dpi.html" }}} <add> <add>It might be hard to see the difference but if you have an HD-DPI <add>display and you compare this sample to those above you should <add>notice the edges are more crisp. <add> <add>This article covered a very basic but fundamental topic. Next up lets quickly <add>[go over the basic primitives that three.js provides](threejs-primitives.html). <add> <ide><path>threejs/lessons/threejs-scenegraph.md <add>Title: Three.js Scenegraph <add>Description: What's a scene graph? <add> <add>This article is part of a series of articles about three.js. The <add>first article is [three.js fundamentals](three-fundamentals.html). If <add>you haven't read yet you might want to consider starting there. <add> <add>Three.js's core is arguably its scene graph. A scene graph in a 3D <add>engine is a hierarchy of nodes in a graph where each node represents <add>a local space. <add> <add><img src="resources/images/scenegraph-generic.svg" align="center"> <add> <add>That's kind of abstract so let's try to give some examples. <add> <add>One example might be solar system, sun, earth, moon. <add> <add><img src="resources/images/scenegraph-solarsystem.svg" align="center"> <add> <add>The Earth orbits the Sun. The Moon orbits the Earth. The Moon <add>moves in a circle around the Earth. From the Moon's point of <add>view it's rotating in the "local space" of the Earth. Even though <add>its motion relative to the Sun is some crazy spirograph like <add>curve from the Moon's point of view it just has to concern itself with rotating <add>around the Earth's local space. <add> <add>{{{diagram url="resources/moon-orbit.html" }}} <add> <add>To think of it another way, you living on the Earth do not have to think <add>about the Earth's rotation on its axis nor its rotation around the <add>Sun. You just walk or drive or swim or run as though the Earth is <add>not moving or rotating at all. You walk, drive, swim, run, and live <add>in the Earth's "local space" even though relative to the sun you are <add>spinning around the earth at around 1000 miles per hour and around <add>the sun at around 67,000 miles per hour. Your position in the solar <add>system is similar to that of the moon above but you don't have to concern <add>yourself. You just worry about your position relative to the earth its <add>"local space". <add> <add>Let's take it one step at a time. Imagine we want to make <add>a diagram of the sun, earth, and moon. We'll start with the sun by <add>just making a sphere and putting it at the origin. Note: We're using <add>sun, earth, moon as a demonstration of how to use a scenegraph. Of course <add>the real sun, earth, and moon use physics but for our purposes we'll <add>fake it with a scenegraph. <add> <add>``` <add>// an array of objects who's rotation to update <add>const objects = []; <add> <add>// use just one sphere for everything <add>const radius = 1; <add>const widthSegments = 6; <add>const heightSegments = 6; <add>const sphereGeometry = new THREE.SphereBufferGeometry( <add> radius, widthSegments, heightSegments); <add> <add>const sunMaterial = new THREE.MeshPhongMaterial({emissive: 0xFFFF00}); <add>const sunMesh = new THREE.Mesh(sphereGeometry, sunMaterial); <add>sunMesh.scale.set(5, 5, 5); // make the sun large <add>scene.add(sunMesh); <add>objects.push(sunMesh); <add>``` <add> <add>We're using a really low-polygon sphere. Only 6 subdivisions around its equator. <add>This is so it's easy to see the rotation. <add> <add>We're going to reuse the same sphere for everything so we'll set a scale <add>for the sun mesh of 5x. <add> <add>We also set the phong material's `emissive` property to yellow. A phong material's <add>emissive property is basically the color that will be drawn with no light hitting <add>the surface. Light is added to that color. <add> <add>Let's also put a single point light in the center of the scene. We'll go into more <add>details about point lights later but for now the simple version is a point light <add>represents light that eminates from a single point. <add> <add>``` <add>{ <add> const color = 0xFFFFFF; <add> const intensity = 3; <add> const light = new THREE.PointLight(color, intensity); <add> scene.add(light); <add>} <add>``` <add> <add>To make it easy to see we're going to put the camera directly above the origin <add>looking down. The easist way to do that us to use the `lookAt` function. The `lookAt` <add>function will orient the camera from its position to "lookAt the position <add>we pass to `lookAt`. Before we do that though we need to tell the camera <add>which way the top of the camera is facing or rather which way is "up" for the <add>camera. For most situations positive Y being up is good enough but since <add>we are looking straight down we need to tell the camera that positive Z is up. <add> <add>``` <add>const camera = new THREE.PerspectiveCamera(fov, aspect, zNear, zFar); <add>camera.position.set(0, 50, 0); <add>camera.up.set(0, 0, 1); <add>camera.lookAt(0, 0, 0); <add>``` <add> <add>In the render loop, adapted from previous examples, we're rotating all <add>objects in our `objects` array with this code. <add> <add>``` <add>objects.forEach((obj) => { <add> obj.rotation.y = time; <add>}); <add>``` <add> <add>Since we added the `sunMesh` to the `objects` array it will rotate. <add> <add>{{{example url="../threejs-scenegraph-sun.html" }}} <add> <add>Now let's add an the earth. <add> <add>``` <add>const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244}); <add>const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial); <add>earthMesh.position.x = 10; <add>scene.add(earthMesh); <add>objects.push(earthMesh); <add>``` <add> <add>We make a material that is blue but we gave it a small amount of *emissive* blue <add>so that it will show up against our black background. <add> <add>We use the same `sphereGeometry` with our new blue `earthMaterial` to make <add>an `earthMesh`. We position that 10 units to the left of the sun <add>and add it to the scene. Since we added it to our `objects` array it will <add>rotate too. <add> <add>{{{example url="../threejs-scenegraph-sun-earth.html" }}} <add> <add>You can see both the sun and the earth are rotating but the earth is not <add>going around the sun. Let's make the earth a child of the sun <add> <add>``` <add>-scene.add(earthMesh); <add>+sunMesh.add(earthMesh); <add>``` <add> <add>and... <add> <add>{{{example url="../threejs-scenegraph-sun-earth-orbit.html" }}} <add> <add>What happened? Why is the earth the same size as the sun and why is it so far away? <add>I actually had to move the camera from 50 units above to 150 units above to see the earth. <add> <add>We made the `earthMesh` a child of the `sunMesh`. The `sunMesh` has <add>its scale set to 5x with `sunMesh.scale.set(5, 5, 5)`. That means the <add>`sunMesh`s local space is 5 times as big. Anything put in that space <add> will be multiplied by 5. That means the earth is now 5x larger and <add> it's distance from the sun (`earthMesh.position.x = 10`) is also <add> 5x as well. <add> <add> Our scene graph currently looks like this <add> <add><img src="resources/images/scenegraph-sun-earth.svg" align="center"> <add> <add>To fix it let's add an empty scene graph node. We'll parent both the sun and the earth <add>to that node. <add> <add>``` <add>+const solarSystem = new THREE.Object3D(); <add>+scene.add(solarSystem); <add>+objects.push(solarSystem); <add> <add>const sunMaterial = new THREE.MeshPhongMaterial({emissive: 0xFFFF00}); <add>const sunMesh = new THREE.Mesh(sphereGeometry, sunMaterial); <add>sunMesh.scale.set(5, 5, 5); <add>-scene.add(sunMesh); <add>+solarSystem.add(sunMesh); <add>objects.push(sunMesh); <add> <add>const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244}); <add>const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial); <add>earthMesh.position.x = 10; <add>-sunMesh.add(earthMesh); <add>+solarSystem.add(earthMesh); <add>objects.push(earthMesh); <add>``` <add> <add>Here we made a `Object3D`. Like a `Mesh` it is also a node in the scene graph <add>but unlike a `Mesh` it has no material or geometry. It just represents a local space. <add> <add>Our new scene graph looks like this <add> <add><img src="resources/images/scenegraph-sun-earth-fixed.svg" align="center"> <add> <add>Both the `sunMesh` and the `earthMesh` are children of the `solarSystem`. All 3 <add>are being rotated and now because the `earthMesh` is not a child of the `sunMesh` <add>it is no longer scaled by 5x. <add> <add>{{{example url="../threejs-scenegraph-sun-earth-orbit-fixed.html" }}} <add> <add>Much better. The earth is smaller than the sun and it's rotating around the sun <add>and rotating itself. <add> <add>Continuing that same pattern let's add a moon. <add> <add>``` <add>+const earthOrbit = new THREE.Object3D(); <add>+earthOrbit.position.x = 10; <add>+solarSystem.add(earthOrbit); <add>+objects.push(earthOrbit); <add> <add>const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244}); <add>const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial); <add>-solarSystem.add(earthMesh); <add>+earthOrbit.add(earthMesh); <add>objects.push(earthMesh); <add> <add>+const moonOrbit = new THREE.Object3D(); <add>+moonOrbit.position.x = 2; <add>+earthOrbit.add(moonOrbit); <add> <add>+const moonMaterial = new THREE.MeshPhongMaterial({color: 0x888888, emissive: 0x222222}); <add>+const moonMesh = new THREE.Mesh(sphereGeometry, moonMaterial); <add>+moonMesh.scale.set(.5, .5, .5); <add>+moonOrbit.add(moonMesh); <add>+objects.push(moonMesh); <add>``` <add> <add>Again we added another invisible scene graph node, a `Object3D` called `earthOrbit` <add>and added both the `earthMesh` and the `moonMesh` to it. The new scene graph looks like <add>this. <add> <add><img src="resources/images/scenegraph-sun-earth-moon.svg" align="center"> <add> <add>and here's that <add> <add>{{{example url="../threejs-scenegraph-sun-earth-moon.html" }}} <add> <add>You can see the moon follows the spirograph pattern shown at the top <add>of this article but we didn't have to manually compute it. We just <add>setup our scene graph to do it for us. <add> <add>It is often useful to draw something to visualize the nodes in the scene graph. <add>Three.js has some helpful ummmm, helpers to ummm, ... help with this. <add> <add>One is called an `AxesHelper`. It draws 3 lines representing the local <add><span style="color:red">X</span>, <add><span style="color:green">Y</span>, and <add><span style="color:blue">Z</span> axes. Let's add one to every node we <add>created. <add> <add>``` <add>// add an AxesHelper to each node <add>objects.forEach((node) => { <add> const axes = new THREE.AxesHelper(); <add> axes.material.depthTest = false; <add> axes.renderOrder = 1; <add> node.add(axes); <add>}); <add>``` <add> <add>On our case we want the axes to appear even though they are inside the spheres. <add>To do this we set their material's `depthTest` to false which means they will <add>not check to see if they are drawing behind something else. We also <add>set their `renderOrder` to 1 (the default is 0) so that they get drawn after <add>all the spheres. Otherwise a sphere might draw over them and cover them up. <add> <add>{{{example url="../threejs-scenegraph-sun-earth-moon-axes.html" }}} <add> <add>We can see the <add><span style="color:red">x (red)</span> and <add><span style="color:blue">z (blue)</span> axes. Since we are looking <add>straight down and each of our objects is only rotating around its <add>y axis we don't see much of the <span style="color:green">y (green)</span> axes. <add> <add>It might be hard to see some of them as there are 2 pairs of overlapping axes. Both the `sunMesh` <add>and the `solarSystem` are at the same position. Similarly the `earthMesh` and <add>`earthOrbit` are at the same position. Let's add some simple controls to allow us <add>to turn them on/off for each node. <add>While we're at it let's also add another helper called the `GridHelper`. It <add>makes a 2D grid on the X,Z plane. By default the grid is 10x10 units. <add> <add>We're also going to use [dat.GUI](https://github.com/dataarts/dat.gui) which is <add>a UI library that is very popular with three.js projects. dat.GUI takes an <add>object and a property name on that object and based on the type of the property <add>automatically makes a UI to manipulate that property. <add> <add>We want to make both a `GridHelper` and an `AxesHelper` for each node. We need <add>a label for each node so we'll get rid of the old loop and switch to calling <add>some function to add the helpers for each node <add> <add>``` <add>-// add an AxesHelper to each node <add>-objects.forEach((node) => { <add>- const axes = new THREE.AxesHelper(); <add>- axes.material.depthTest = false; <add>- axes.renderOrder = 1; <add>- node.add(axes); <add>-}); <add> <add>+function makeAxisGrid(node, label, units) { <add>+ const helper = new AxisGridHelper(node, units); <add>+ gui.add(helper, 'visible').name(label); <add>+} <add>+ <add>+makeAxisGrid(solarSystem, 'solarSystem', 25); <add>+makeAxisGrid(sunMesh, 'sunMesh'); <add>+makeAxisGrid(earthOrbit, 'earthOrbit'); <add>+makeAxisGrid(earthMesh, 'earthMesh'); <add>+makeAxisGrid(moonMesh, 'moonMesh'); <add>``` <add> <add>`makeAxisGrid` makes a `AxisGridHelper` which is class we'll create <add>to make dat.GUI happy. Like it says above dat.GUI <add>will automagically make a UI that manipulates the named property <add>of some object. It will create a different UI depending on the type <add>of property. We want it to create a checkbox so we need to specify <add>a `bool` property. But, we want both the axes and the grid <add>to appear/disappear based on a single property so we'll make a class <add>that has a getter and setter for a property. That way we can let dat.GUI <add>think it's manipulating a single property but internally we can set <add>the visible property of both the `AxesHelper` and `GridHelper` for a node. <add> <add>``` <add>// Turns both axes and grid visible on/off <add>// dat.GUI requires a property that returns a bool <add>// to decide to make a checkbox so we make a setter <add>// can getter for `visible` which we can tell dat.GUI <add>// to look at. <add>class AxisGridHelper { <add> constructor(node, units = 10) { <add> const axes = new THREE.AxesHelper(); <add> axes.material.depthTest = false; <add> axes.renderOrder = 2; // after the grid <add> node.add(axes); <add> <add> const grid = new THREE.GridHelper(units, units); <add> grid.material.depthTest = false; <add> grid.renderOrder = 1; <add> node.add(grid); <add> <add> this.grid = grid; <add> this.axes = axes; <add> this.visible = false; <add> } <add> get visible() { <add> return this._visible; <add> } <add> set visible(v) { <add> this._visible = v; <add> this.grid.visible = v; <add> this.axes.visible = v; <add> } <add>} <add>``` <add> <add>One thing to notice is we set the `renderOrder` of the `AxesHelper` <add>to 2 and for the `GridHelper` to 1 so that the axes get drawn after the grid. <add>Otherwise the grid might overwrite the axes. <add> <add>{{{example url="../threejs-scenegraph-sun-earth-moon-axes-grids.html" }}} <add> <add>Turn on the `solarSystem` and you'll see how the earth is exactly 10 <add>units out from the center just like we set above. You can see how the <add>earth is in the *local space* of the `solarSystem`. Similary if you <add>turn on the `earthOrbit` you'll see how the moon is exactly 2 units <add>from the center of the *local space* of the `earthOrbit`. <add> <add>A few more examples of scene graphs. An automobile in a simple game world might have a scene graph like this <add> <add><img src="resources/images/scenegraph-car.svg" align="center"> <add> <add>If you move the car's body all the wheels will move with it. If you wanted the body <add>to bounce separate from the wheels you might parent the body and the wheels to a "frame" node <add>that represents the car's frame. <add> <add>Another example is a human in a game world. <add> <add><img src="resources/images/scenegraph-human.svg" align="center"> <add> <add>You can see the scene graph gets pretty complex for a human. In fact <add>that scene graph above is simplified. For example you might extend it <add>to cover the every finger (at least another 28 nodes) and every toe <add>(yet another 28 nodes) plus ones for the and jaw, the eyes and maybe more. <add> <add>I hope this gives some idea of how scene graphs work and how you might use them. <add>Making `Object3D` nodes and parenting things to them is an important step to using <add>a 3D engine like three.js well. Often it might seem like some complex math is necessary <add>to make something move and rotate the way you want. For example without a scene graph <add>computing the motion of the moon or where to put the wheels of the car relative to its <add>body would be very complicated but using a scene graph it becomes much easier. <add> <add>[Next up we'll go over materials and lights](threejs-materials-and-lights.html). <ide>\ No newline at end of file
5
PHP
PHP
replace actual view
f50be03c8ea7cc9c675aa594fc9392fad1eb38e1
<ide><path>src/Illuminate/Notifications/Channels/MailChannel.php <ide> public function send(Notification $notification) <ide> <ide> $view = data_get($notification, 'options.view', 'notifications::email'); <ide> <del> $this->mailer->send('notifications::email', $data, function ($m) use ($notification, $emails) { <add> $this->mailer->send($view, $data, function ($m) use ($notification, $emails) { <ide> count($notification->notifiables) === 1 <ide> ? $m->to($emails) : $m->bcc($emails); <ide>
1
Python
Python
remove use of _keras_shape in merge.py
3966daa90b4c47d2ad36e977c36a6895f2697dd8
<ide><path>keras/layers/merge.py <ide> def _merge_function(self, inputs): <ide> if len(inputs) != 2: <ide> raise ValueError('`Subtract` layer should be called ' <ide> 'on exactly 2 inputs') <del> if inputs[0]._keras_shape != inputs[1]._keras_shape: <add> if K.int_shape(inputs[0]) != K.int_shape(inputs[1]): <ide> raise ValueError('`Subtract` layer should be called ' <ide> 'on inputs of the same shape') <ide> return inputs[0] - inputs[1]
1
Go
Go
fix seccomp warning
c68e75e51d58167b5b21e77bbc7b701fe0888096
<ide><path>cli/command/system/info.go <ide> func prettyPrintInfo(dockerCli *command.DockerCli, info types.Info) error { <ide> case "Name": <ide> fmt.Fprintf(dockerCli.Out(), " %s\n", o.Value) <ide> case "Profile": <del> if o.Key != "default" { <del> fmt.Fprintf(dockerCli.Err(), " WARNING: You're not using the Docker's default seccomp profile\n") <add> if o.Value != "default" { <add> fmt.Fprintf(dockerCli.Err(), " WARNING: You're not using the default seccomp profile\n") <ide> } <ide> fmt.Fprintf(dockerCli.Out(), " %s: %s\n", o.Key, o.Value) <ide> }
1
Python
Python
remove unused import
c9d2b3c5d0311158f04ae96bd1b33432aba0ae8c
<ide><path>scripts/ci/pre_commit/pre_commit_check_extras_have_providers.py <ide> import os <ide> import sys <ide> from os.path import dirname <del>from textwrap import wrap <ide> from typing import List <ide> <ide> AIRFLOW_SOURCES_DIR = os.path.abspath(os.path.join(dirname(__file__), os.pardir, os.pardir, os.pardir))
1
PHP
PHP
apply styleci fixes
1ac97b810cc502c71d7f6ae9d08a7f0b010c9ed3
<ide><path>tests/Validation/ValidationValidatorTest.php <ide> public function testValidateGtPlaceHolderIsReplacedProperly() <ide> 'validation.gt.numeric' => ':value', <ide> 'validation.gt.string' => ':value', <ide> 'validation.gt.file' => ':value', <del> 'validation.gt.array' => ':value' <add> 'validation.gt.array' => ':value', <ide> ], 'en'); <ide> <ide> $v = new Validator($trans, ['items' => '3'], ['items' => 'gt:4']); <ide> public function testValidateGtPlaceHolderIsReplacedProperly() <ide> $this->assertFalse($v->passes()); <ide> $this->assertEquals(5, $v->messages()->first('photo')); <ide> <del> $v = new Validator($trans, ['items' => [1,2,3], 'more' => [0,1,2,3]], ['items' => 'gt:more']); <add> $v = new Validator($trans, ['items' => [1, 2, 3], 'more' => [0, 1, 2, 3]], ['items' => 'gt:more']); <ide> $this->assertFalse($v->passes()); <ide> $this->assertEquals(4, $v->messages()->first('items')); <ide> } <ide> public function testValidateLtPlaceHolderIsReplacedProperly() <ide> 'validation.lt.numeric' => ':value', <ide> 'validation.lt.string' => ':value', <ide> 'validation.lt.file' => ':value', <del> 'validation.lt.array' => ':value' <add> 'validation.lt.array' => ':value', <ide> ], 'en'); <ide> <ide> $v = new Validator($trans, ['items' => '3'], ['items' => 'lt:2']); <ide> public function testValidateLtPlaceHolderIsReplacedProperly() <ide> $this->assertFalse($v->passes()); <ide> $this->assertEquals(2, $v->messages()->first('photo')); <ide> <del> $v = new Validator($trans, ['items' => [1,2,3], 'less' => [0,1]], ['items' => 'lt:less']); <add> $v = new Validator($trans, ['items' => [1, 2, 3], 'less' => [0, 1]], ['items' => 'lt:less']); <ide> $this->assertFalse($v->passes()); <ide> $this->assertEquals(2, $v->messages()->first('items')); <ide> } <ide> public function testValidateGtePlaceHolderIsReplacedProperly() <ide> 'validation.gte.numeric' => ':value', <ide> 'validation.gte.string' => ':value', <ide> 'validation.gte.file' => ':value', <del> 'validation.gte.array' => ':value' <add> 'validation.gte.array' => ':value', <ide> ], 'en'); <ide> <ide> $v = new Validator($trans, ['items' => '3'], ['items' => 'gte:4']); <ide> public function testValidateGtePlaceHolderIsReplacedProperly() <ide> $this->assertFalse($v->passes()); <ide> $this->assertEquals(5, $v->messages()->first('photo')); <ide> <del> $v = new Validator($trans, ['items' => [1,2,3], 'more' => [0,1,2,3]], ['items' => 'gte:more']); <add> $v = new Validator($trans, ['items' => [1, 2, 3], 'more' => [0, 1, 2, 3]], ['items' => 'gte:more']); <ide> $this->assertFalse($v->passes()); <ide> $this->assertEquals(4, $v->messages()->first('items')); <ide> } <ide> public function testValidateLtePlaceHolderIsReplacedProperly() <ide> 'validation.lte.numeric' => ':value', <ide> 'validation.lte.string' => ':value', <ide> 'validation.lte.file' => ':value', <del> 'validation.lte.array' => ':value' <add> 'validation.lte.array' => ':value', <ide> ], 'en'); <ide> <ide> $v = new Validator($trans, ['items' => '3'], ['items' => 'lte:2']); <ide> public function testValidateLtePlaceHolderIsReplacedProperly() <ide> $this->assertFalse($v->passes()); <ide> $this->assertEquals(2, $v->messages()->first('photo')); <ide> <del> $v = new Validator($trans, ['items' => [1,2,3], 'less' => [0,1]], ['items' => 'lte:less']); <add> $v = new Validator($trans, ['items' => [1, 2, 3], 'less' => [0, 1]], ['items' => 'lte:less']); <ide> $this->assertFalse($v->passes()); <ide> $this->assertEquals(2, $v->messages()->first('items')); <ide> }
1
Ruby
Ruby
add pcsc-lite to uses_from_macos
24af65302dafb7d554ff0adbc2593f070096f7b0
<ide><path>Library/Homebrew/rubocops/uses_from_macos.rb <ide> class ProvidedByMacos < FormulaCop <ide> netcat <ide> openldap <ide> openlibm <add> pcsc-lite <ide> pod2man <ide> rpcgen <ide> ruby
1
PHP
PHP
release cache lock if callback fails
76dd0c70cac9bdc575b1738fd6a3609a02c0ad51
<ide><path>src/Illuminate/Cache/Lock.php <ide> public function get($callback = null) <ide> $result = $this->acquire(); <ide> <ide> if ($result && is_callable($callback)) { <del> return tap($callback(), function () { <add> try { <add> return $callback(); <add> } finally { <ide> $this->release(); <del> }); <add> } <ide> } <ide> <ide> return $result;
1
PHP
PHP
fix code style
81053b46ff3a3ebb6571cef2d6ec7c8f7f18deea
<ide><path>src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php <ide> public function belongsToMany($related, $table = null, $foreignKey = null, $rela <ide> <ide> $relatedKey = $relatedKey ?: $instance->getForeignKey(); <ide> <del> $localKey = $localKey ?: $this->getKeyName(); <add> $localKey = $localKey ?: $this->getKeyName(); <ide> <ide> // If no table name was provided, we can guess it by concatenating the two <ide> // models using underscores in alphabetical order. The two model names <ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php <ide> public function __construct(Builder $query, Model $parent, $table, $foreignKey, <ide> $this->relatedKey = $relatedKey; <ide> $this->foreignKey = $foreignKey; <ide> $this->relationName = $relationName; <del> $this->localKey = $localKey; <add> $this->localKey = $localKey; <ide> <ide> parent::__construct($query, $parent); <ide> }
2
PHP
PHP
fix datetime widget display
b08319e415a2f76b3ec7e643eb97831e635f1299
<ide><path>src/View/Widget/DateTimeWidget.php <ide> protected function _deconstructDate($value, $options) <ide> } <ide> if (!empty($dateArray['minute']) && isset($options['minute']['interval'])) { <ide> $dateArray['minute'] += $this->_adjustValue($dateArray['minute'], $options['minute']); <add> $dateArray['minute'] = str_pad(strval($dateArray['minute']), 2, '0', STR_PAD_LEFT); <ide> } <ide> <ide> return $dateArray; <ide> protected function _secondSelect($options, $context) <ide> 'val' => null, <ide> 'leadingZeroKey' => true, <ide> 'leadingZeroValue' => true, <del> 'options' => $this->_generateNumbers(1, 60) <add> 'options' => $this->_generateNumbers(0, 59) <ide> ]; <ide> <ide> unset($options['leadingZeroKey'], $options['leadingZeroValue']);
1
Ruby
Ruby
remove warning from railtie
34530f5bd566be360be4030a38b898cba97bee85
<ide><path>railties/lib/rails/railtie.rb <ide> def method_missing(name, *args, &block) <ide> # `#each_registered_block(type, &block)` <ide> def register_block_for(type, &blk) <ide> var_name = "@#{type}" <del> blocks = instance_variable_get(var_name) || instance_variable_set(var_name, []) <add> blocks = instance_variable_defined?(var_name) ? instance_variable_get(var_name) : instance_variable_set(var_name, []) <ide> blocks << blk if blk <ide> blocks <ide> end
1
PHP
PHP
move bundles file into base directory
a850610c865e7ae2b8bb82bc3941394d6997acd4
<ide><path>bundles/bundles.php <del><?php <del> <del>/* <del>|-------------------------------------------------------------------------- <del>| Bundle Configuration <del>|-------------------------------------------------------------------------- <del>| <del>| Bundles allow you to conveniently extend and organize your application. <del>| Think of bundles as self-contained applications. They can have routes, <del>| controllers, models, views, configuration, etc. You can even create <del>| your own bundles to share with the Laravel community. <del>| <del>| This is a list of the bundles installed for your application and tells <del>| Laravel the location of the bundle's root directory, as well as the <del>| root URI the bundle responds to. <del>| <del>| For example, if you have an "admin" bundle located in "bundles/admin" <del>| that you want to handle requests with URIs that begin with "admin", <del>| simply add it to the array like this: <del>| <del>| 'admin' => array( <del>| 'location' => 'admin', <del>| 'handles' => 'admin', <del>| ), <del>| <del>| Note that the "location" is relative to the "bundles" directory. <del>| Now the bundle will be recognized by Laravel and will be able <del>| to respond to requests beginning with "admin"! <del>| <del>| Have a bundle that lives in the root of the bundle directory <del>| and doesn't respond to any requests? Just add the bundle <del>| name to the array and we'll take care of the rest. <del>| <del>*/ <del> <del>return array(); <ide>\ No newline at end of file
1
Javascript
Javascript
add rfc232 variants
cd6b8d423790b27170a7ef31b92cddcb3141b292
<ide><path>blueprints/helper-test/qunit-rfc-232-files/tests/__testType__/helpers/__name__-test.js <add><% if (testType === 'integration') { %>import { module, test } from 'qunit'; <add>import { setupRenderingTest } from 'ember-qunit'; <add>import { render } from '@ember/test-helpers'; <add>import hbs from 'htmlbars-inline-precompile'; <add> <add>module('<%= friendlyTestName %>', function(hooks) { <add> setupRenderingTest(hooks); <add> <add> // Replace this with your real tests. <add> test('it renders', async function(assert) { <add> this.set('inputValue', '1234'); <add> <add> await render(hbs`{{<%= dasherizedModuleName %> inputValue}}`); <add> <add> assert.equal(this.element.textContent.trim(), '1234'); <add> }); <add>});<% } else if (testType === 'unit') { %>import { <%= camelizedModuleName %> } from '<%= dasherizedModulePrefix %>/helpers/<%= dasherizedModuleName %>'; <add>import { module, test } from 'qunit'; <add>import { setupTest } from 'ember-qunit'; <add> <add>module('<%= friendlyTestName %>', function(hooks) { <add> setupTest(hooks); <add> <add> // Replace this with your real tests. <add> test('it works', function(assert) { <add> let result = <%= camelizedModuleName %>([42]); <add> assert.ok(result); <add> }); <add>});<% } %> <ide><path>node-tests/blueprints/helper-test-test.js <ide> describe('Blueprint: helper-test', function() { <ide> }); <ide> }); <ide> <add> describe('with ember-cli-qunit@4.1.1', function() { <add> beforeEach(function() { <add> generateFakePackageManifest('ember-cli-qunit', '4.1.1'); <add> }); <add> <add> it('helper-test foo/bar-baz', function() { <add> return emberGenerateDestroy(['helper-test', 'foo/bar-baz'], _file => { <add> expect(_file('tests/integration/helpers/foo/bar-baz-test.js')) <add> .to.equal(fixture('helper-test/rfc232.js')); <add> }); <add> }); <add> <add> it('helper-test foo/bar-baz --unit', function() { <add> return emberGenerateDestroy(['helper-test', 'foo/bar-baz', '--unit'], _file => { <add> expect(_file('tests/unit/helpers/foo/bar-baz-test.js')) <add> .to.equal(fixture('helper-test/rfc232-unit.js')); <add> }); <add> }); <add> }); <add> <ide> describe('with ember-cli-mocha@0.11.0', function() { <ide> beforeEach(function() { <ide> modifyPackages([ <ide><path>node-tests/fixtures/helper-test/rfc232-unit.js <add>import { fooBarBaz } from 'my-app/helpers/foo/bar-baz'; <add>import { module, test } from 'qunit'; <add>import { setupTest } from 'ember-qunit'; <add> <add>module('Unit | Helper | foo/bar baz', function(hooks) { <add> setupTest(hooks); <add> <add> // Replace this with your real tests. <add> test('it works', function(assert) { <add> let result = fooBarBaz([42]); <add> assert.ok(result); <add> }); <add>}); <ide><path>node-tests/fixtures/helper-test/rfc232.js <add>import { module, test } from 'qunit'; <add>import { setupRenderingTest } from 'ember-qunit'; <add>import { render } from '@ember/test-helpers'; <add>import hbs from 'htmlbars-inline-precompile'; <add> <add>module('Integration | Helper | foo/bar baz', function(hooks) { <add> setupRenderingTest(hooks); <add> <add> // Replace this with your real tests. <add> test('it renders', async function(assert) { <add> this.set('inputValue', '1234'); <add> <add> await render(hbs`{{foo/bar-baz inputValue}}`); <add> <add> assert.equal(this.element.textContent.trim(), '1234'); <add> }); <add>});
4
Javascript
Javascript
fix flaky test-regress-gh-897
80c72c6d55452ffd0e7719b869bc54c3861595ab
<ide><path>test/parallel/test-regress-GH-897.js <add>'use strict'; <add> <add>// Test for bug where a timer duration greater than 0 ms but less than 1 ms <add>// resulted in the duration being set for 1000 ms. The expected behavior is <add>// that the timeout would be set for 1 ms, and thus fire before timers set <add>// with values greater than 1ms. <add>// <add>// Ref: https://github.com/nodejs/node-v0.x-archive/pull/897 <add> <add>const common = require('../common'); <add> <add>let timer; <add> <add>setTimeout(function() { <add> clearTimeout(timer); <add>}, 0.1); // 0.1 should be treated the same as 1, not 1000... <add> <add>timer = setTimeout(function() { <add> common.fail('timers fired out of order'); <add>}, 2); // ...so this timer should fire second. <ide><path>test/sequential/test-regress-GH-897.js <del>'use strict'; <del> <del>// Test for bug where a timer duration greater than 0 ms but less than 1 ms <del>// resulted in the duration being set for 1000 ms. The expected behavior is <del>// that the timeout would be set for 1 ms, and thus fire more-or-less <del>// immediately. <del>// <del>// Ref: https://github.com/nodejs/node-v0.x-archive/pull/897 <del> <del>const common = require('../common'); <del>const assert = require('assert'); <del> <del>const t = Date.now(); <del>setTimeout(common.mustCall(function() { <del> const diff = Date.now() - t; <del> assert.ok(diff < 100, `timer fired after ${diff} ms`); <del>}), 0.1);
2
PHP
PHP
where
74a8738162b4a41a5647d423273720aac1abb0f0
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function mergeWheres($wheres, $bindings) <ide> * Add a basic where clause to the query. <ide> * <ide> * @param string|array|\Closure $column <del> * @param string|null $operator <add> * @param mixed $operator <ide> * @param mixed $value <ide> * @param string $boolean <ide> * @return $this
1
Ruby
Ruby
remove confusing comments
c32e67b83cc5df5c69726f93d543eeee1c4202dd
<ide><path>Library/Homebrew/utils.rb <ide> def locate tool <ide> return @locate_cache[tool] if @locate_cache.has_key? tool <ide> <ide> if File.executable? "/usr/bin/#{tool}" <del> # Always prefer the unix style. <ide> path = Pathname.new "/usr/bin/#{tool}" <ide> else <ide> # Xcrun was provided first with Xcode 4.3 and allows us to proxy <ide> def dev_tools_path <ide> Pathname.new "/usr/bin" <ide> elsif not xctools_fucked? and system "/usr/bin/xcrun -find make 1>/dev/null 2>&1" <ide> # Wherever "make" is there are the dev tools. <del> # The new way of finding stuff via locate. <ide> Pathname.new(`/usr/bin/xcrun -find make`.chomp).dirname <ide> elsif File.exist? "#{xcode_prefix}/usr/bin/make" <ide> # cc stopped existing with Xcode 4.3, there are c89 and c99 options though
1
Text
Text
use enhancement instead of feature
35859500ed282b4975dffdcdcad66bf7aad3bd26
<ide><path>CONTRIBUTING.md <ide> These are just guidelines, not rules, use your best judgment and feel free to pr <ide> <ide> [How Can I Contribute?](#how-can-i-contribute) <ide> * [Reporting Bugs](#reporting-bugs) <del> * [Suggesting Features](#suggesting-features) <add> * [Suggesting Enhancements](#suggesting-enhancements) <ide> * [Your First Code Contribution](#your-first-code-contribution) <ide> * [Pull Requests](#pull-requests) <ide> <ide> Include details about your configuration and environment: <ide> * Problem can be reliably reproduced, doesn't happen randomly: [Yes/No] <ide> * Problem happens with all files and projects, not only some files or projects: [Yes/No] <ide> <del>### Suggesting Features <add>### Suggesting Enhancements <ide> <del>This section guides you through submitting a feature suggestion for Atom. Following these guidelines helps maintainers and the community understand your suggestion :pencil: and find related suggestions :mag_right:. <add>This section guides you through submitting an enhancement suggestion for Atom, including completely new features and minor improvements to existing functionality. Following these guidelines helps maintainers and the community understand your suggestion :pencil: and find related suggestions :mag_right:. <ide> <del>Before creating feature suggestions, please check [this list](#before-submitting-a-feature-suggestion) as you might find out that you don't need to create one. When you are creating a feature suggestion, please [include as many details as possible](#how-do-i-submit-a-good-feature-suggestion). If you'd like, you can use [this template](#template-for-submitting-feature-suggestions) to structure the information. <add>Before creating enhancement suggestions, please check [this list](#before-submitting-an-enhancement-suggestion) as you might find out that you don't need to create one. When you are creating an enhancement suggestion, please [include as many details as possible](#how-do-i-submit-a-good-enhancement-suggestion). If you'd like, you can use [this template](#template-for-submitting-enhancement-suggestions) to structure the information. <ide> <del>#### Before Submitting A Feature Suggestion <add>#### Before Submitting An Enhancement Suggestion <ide> <del>* **Check the [debugging guide](https://atom.io/docs/latest/hacking-atom-debugging)** for tips — you might discover that the feature is already available. Most importantly, check if you're using [the latest version of Atom](https://atom.io/docs/latest/hacking-atom-debugging#update-to-the-latest-version) and if you can get the desired behavior by changing [Atom's or packages' config settings](https://atom.io/docs/latest/hacking-atom-debugging#check-atom-and-package-settings). <del>* **Check if there's already [a package](https://atom.io/packages) which provides that feature.** <del>* **Determine [which repository the feature should be suggested in](#atom-and-packages).** <del>* **Perform a [cursory search](https://github.com/issues?q=+is%3Aissue+user%3Aatom)** to see if the feature has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. <add>* **Check the [debugging guide](https://atom.io/docs/latest/hacking-atom-debugging)** for tips — you might discover that the enhancement is already available. Most importantly, check if you're using [the latest version of Atom](https://atom.io/docs/latest/hacking-atom-debugging#update-to-the-latest-version) and if you can get the desired behavior by changing [Atom's or packages' config settings](https://atom.io/docs/latest/hacking-atom-debugging#check-atom-and-package-settings). <add>* **Check if there's already [a package](https://atom.io/packages) which provides that enhancement.** <add>* **Determine [which repository the enhancement should be suggested in](#atom-and-packages).** <add>* **Perform a [cursory search](https://github.com/issues?q=+is%3Aissue+user%3Aatom)** to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. <ide> <del>#### How Do I Submit A (Good) Feature Suggestion? <add>#### How Do I Submit A (Good) Enhancement Suggestion? <ide> <del>Feature suggestions are tracked as [GitHub issues](https://guides.github.com/features/issues/). After you've determined [which repository](#atom-and-packages) your feature suggestions is related to, create an issue on that repository and provide the following information: <add>Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com/features/issues/). After you've determined [which repository](#atom-and-packages) your enhancement suggestions is related to, create an issue on that repository and provide the following information: <ide> <ide> * **Use a clear and descriptive title** for the issue to identify the suggestion. <del>* **Provide a step-by-step description of the suggested feature** in as many details as possible. <add>* **Provide a step-by-step description of the suggested enhancement** in as many details as possible. <ide> * **Provide specific examples to demonstrate the steps**. Include copy/pasteable snippets which you use in those examples, as [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines). <ide> * **Describe the current behavior** and **explain which behavior you expected to see instead** and why. <ide> * **Include screenshots and animated GIFs** which help you demonstrate the steps or point out the part of Atom which the suggestion is related to. You can use [this tool](http://www.cockos.com/licecap/) to record GIFs on OSX and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. <del>* **Explain why this feature would be useful** to most Atom users and isn't something that can or should be implemented as a [community package](#atom-and-packages). <del>* **List some other text editors or applications where this feature exists.** <add>* **Explain why this enhancement would be useful** to most Atom users and isn't something that can or should be implemented as a [community package](#atom-and-packages). <add>* **List some other text editors or applications where this enhancement exists.** <ide> * **Specify which version of Atom you're using.** You can get the exact version by running `atom -v` in your terminal, or by starting Atom and running the `Application: About` command from the [Command Palette](https://github.com/atom/command-palette). <ide> * **Specify the name and version of the OS you're using.** <ide> <del>#### Template For Submitting Feature Suggestions <add>#### Template For Submitting Enhancement Suggestions <ide> <ide> [Short description of suggestion] <ide> <del> **Steps which explain the feature** <add> **Steps which explain the enhancement** <ide> <ide> 1. [First Step] <ide> 2. [Second Step] <ide> Feature suggestions are tracked as [GitHub issues](https://guides.github.com/fea <ide> <ide> [Describe current and suggested behavior here] <ide> <del> **Why would the feature be useful to most users** <add> **Why would the enhancement be useful to most users** <ide> <del> [Explain why the feature would be useful to most users] <add> [Explain why the enhancement would be useful to most users] <ide> <del> [List some other text editors or applications where this feature exists] <add> [List some other text editors or applications where this enhancement exists] <ide> <ide> **Screenshots and GIFs** <ide> <del> ![Screenshots and GIFs which demonstrate the steps or part of Atom the feature suggestion is related to](url) <add> ![Screenshots and GIFs which demonstrate the steps or part of Atom the enhancement suggestion is related to](url) <ide> <ide> **Atom Version:** [Enter Atom version here] <ide> **OS and Version:** [Enter OS name and version here]
1
Python
Python
add non-linearity after history features
d163115e91aaa6a0f73b05b05bcca9774d76bf7c
<ide><path>spacy/_ml.py <ide> def HistoryFeatures(nr_class, hist_size=8, nr_dim=8): <ide> return layerize(noop()) <ide> embed_tables = [Embed(nr_dim, nr_class, column=i, name='embed%d') <ide> for i in range(hist_size)] <del> embed = concatenate(*embed_tables) <add> embed = chain(concatenate(*embed_tables), <add> LN(Maxout(hist_size*nr_dim, hist_size*nr_dim))) <ide> ops = embed.ops <ide> def add_history_fwd(vectors_hists, drop=0.): <ide> vectors, hist_ids = vectors_hists
1
Javascript
Javascript
remove code duplication
41cec4d68056268a5977399976738cecc343a653
<ide><path>src/ng/directive/select.js <ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) { <ide> <ide> ctrl.$render = render; <ide> <del> scope.$watchCollection(valuesFn, function () { <del> if (!renderScheduled) { <del> scope.$$postDigest(render); <del> renderScheduled = true; <del> } <del> }); <del> if ( multiple ) { <del> scope.$watchCollection(function() { return ctrl.$modelValue; }, function () { <del> if (!renderScheduled) { <del> scope.$$postDigest(render); <del> renderScheduled = true; <del> } <del> }); <add> scope.$watchCollection(valuesFn, scheduleRendering); <add> <add> if (multiple) { <add> scope.$watchCollection(function() { return ctrl.$modelValue; }, scheduleRendering); <ide> } <ide> <add> <ide> function getSelectedSet() { <ide> var selectedSet = false; <ide> if (multiple) { <ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) { <ide> } <ide> <ide> <add> function scheduleRendering() { <add> if (!renderScheduled) { <add> scope.$$postDigest(render); <add> renderScheduled = true; <add> } <add> } <add> <add> <ide> function render() { <ide> renderScheduled = false; <ide>
1
Text
Text
add references to pr communication articles
d179ccac928bd45e4baca8647c3605ec36934eec
<ide><path>COLLABORATOR_GUIDE.md <ide> oppose the PR, it can be landed. Where there is disagreement among TSC members <ide> or objections from one or more Collaborators, `semver-major` pull requests <ide> should be put on the TSC meeting agenda. <ide> <add>#### Helpful resources <add> <add>* How to respectfully and usefully review code, part [one](https://mtlynch.io/human-code-reviews-1/) and [two](https://mtlynch.io/human-code-reviews-2/) <add>* [How to write a positive code review](https://css-tricks.com/code-review-etiquette/) <add> <ide> ### Waiting for Approvals <ide> <ide> Before landing pull requests, sufficient time should be left for input
1
Text
Text
add units that padding can be specified in
cfc0662583a7056248cf06ccf3910623c2d905ad
<ide><path>guide/english/css/padding/index.md <ide> title: Padding <ide> --- <ide> # Padding <ide> <del>The `padding` CSS property sets the padding area on all four sides of an element. This property can be used to generate space around content (inside the border). It is a shorthand to set all individual paddings at once: `padding-top`, `padding-right`, `padding-bottom`, and `padding-left`. Values are defined in the clockwise direction, starting at the top. <add>The `padding` CSS property sets the padding area on all four sides of an element. This property can be used to generate space around content (inside the border) to improve readability of the content inside. It is a shorthand to set all individual paddings at once: `padding-top`, `padding-right`, `padding-bottom`, and `padding-left`. Values are defined in the clockwise direction and are most often specified in pixels, although percentages or ems can also be used. If a percentage is used, the padding will be a percentage of the browser window or of the container it is found in. <ide> <del>Padding values are set using lengths, percentages, or the `inherit` keyword, and cannot accept negative values. The initial, or default, value for all padding properties is 0. The `inherit` keyword cannot be used with a length value. <add>Padding values are set using lengths or percentages or `inherit` keyword, and cannot accept negative values. The initial, or default, value for all padding properties is 0. While you can use `inherit` keyword but it can not be used along with a length value. The `padding` property value is not inherited by the child elements like the `color` value of the `font-family` property is, so the padding must be specified for each element that requires it. <ide> <ide> ## Syntax <ide> ```css
1
Python
Python
fix typo in chord return
29cfdd7f6b3c10f92fa3ef8e26d193dac62f5103
<ide><path>celery/backends/base.py <ide> def on_chord_part_return(self, task, propagate=False): <ide> key = self.get_key_for_chord(gid) <ide> deps = GroupResult.restore(gid, backend=task.backend) <ide> val = self.incr(key) <del> if val >= deps.total: <add> if val >= len(deps): <ide> subtask(task.request.chord).delay(deps.join(propagate=propagate)) <ide> deps.delete() <ide> self.client.delete(key)
1
Go
Go
ensure _tmp dir is always removed
f6577be1c93150149c291f9d18375d7bcae9ebb1
<ide><path>graph/graph.go <ide> type Graph struct { <ide> root string <ide> idIndex *truncindex.TruncIndex <ide> driver graphdriver.Driver <add> imagesMutex sync.Mutex <ide> imageMutex imageMutex // protect images in driver. <ide> retained *retainedLayers <ide> tarSplitDisabled bool <ide> uidMaps []idtools.IDMap <ide> gidMaps []idtools.IDMap <del> parentRefs map[string]int <add> <add> // access to parentRefs must be protected with imageMutex locking the image id <add> // on the key of the map (e.g. imageMutex.Lock(img.ID), parentRefs[img.ID]...) <add> parentRefs map[string]int <ide> } <ide> <ide> // file names for ./graph/<ID>/ <ide> func (graph *Graph) restore() error { <ide> for _, v := range dir { <ide> id := v.Name() <ide> if graph.driver.Exists(id) { <del> pth := filepath.Join(graph.root, id, "json") <del> jsonSource, err := os.Open(pth) <add> img, err := graph.loadImage(id) <ide> if err != nil { <ide> return err <ide> } <del> defer jsonSource.Close() <del> decoder := json.NewDecoder(jsonSource) <del> var img *image.Image <del> if err := decoder.Decode(img); err != nil { <del> return err <del> } <ide> graph.imageMutex.Lock(img.Parent) <ide> graph.parentRefs[img.Parent]++ <ide> graph.imageMutex.Unlock(img.Parent) <ide> func (graph *Graph) Register(im image.Descriptor, layerData io.Reader) (err erro <ide> return err <ide> } <ide> <add> // this is needed cause pull_v2 attemptIDReuse could deadlock <add> graph.imagesMutex.Lock() <add> defer graph.imagesMutex.Unlock() <add> <ide> // We need this entire operation to be atomic within the engine. Note that <ide> // this doesn't mean Register is fully safe yet. <ide> graph.imageMutex.Lock(imgID) <ide> func (graph *Graph) register(im image.Descriptor, layerData io.Reader) (err erro <ide> graph.driver.Remove(imgID) <ide> <ide> tmp, err := graph.mktemp() <del> defer os.RemoveAll(tmp) <ide> if err != nil { <del> return fmt.Errorf("mktemp failed: %s", err) <add> return err <ide> } <add> defer os.RemoveAll(tmp) <ide> <ide> parent := im.Parent() <ide> <ide> func (graph *Graph) register(im image.Descriptor, layerData io.Reader) (err erro <ide> return err <ide> } <ide> <del> graph.idIndex.Add(img.ID) <add> graph.idIndex.Add(imgID) <ide> <del> graph.imageMutex.Lock(img.Parent) <del> graph.parentRefs[img.Parent]++ <del> graph.imageMutex.Unlock(img.Parent) <add> graph.imageMutex.Lock(parent) <add> graph.parentRefs[parent]++ <add> graph.imageMutex.Unlock(parent) <ide> <ide> return nil <ide> } <ide> func (graph *Graph) TempLayerArchive(id string, sf *streamformatter.StreamFormat <ide> if err != nil { <ide> return nil, err <ide> } <add> defer os.RemoveAll(tmp) <ide> a, err := graph.TarLayer(image) <ide> if err != nil { <ide> return nil, err <ide> func (graph *Graph) mktemp() (string, error) { <ide> return dir, nil <ide> } <ide> <del>func (graph *Graph) newTempFile() (*os.File, error) { <del> tmp, err := graph.mktemp() <del> if err != nil { <del> return nil, err <del> } <del> return ioutil.TempFile(tmp, "") <del>} <del> <ide> // Delete atomically removes an image from the graph. <ide> func (graph *Graph) Delete(name string) error { <ide> id, err := graph.idIndex.Get(name) <ide> func (graph *Graph) Delete(name string) error { <ide> if err != nil { <ide> return err <ide> } <del> tmp, err := graph.mktemp() <ide> graph.idIndex.Delete(id) <del> if err == nil { <add> tmp, err := graph.mktemp() <add> if err != nil { <add> tmp = graph.imageRoot(id) <add> } else { <ide> if err := os.Rename(graph.imageRoot(id), tmp); err != nil { <ide> // On err make tmp point to old dir and cleanup unused tmp dir <ide> os.RemoveAll(tmp) <ide> tmp = graph.imageRoot(id) <ide> } <del> } else { <del> // On err make tmp point to old dir for cleanup <del> tmp = graph.imageRoot(id) <ide> } <ide> // Remove rootfs data from the driver <ide> graph.driver.Remove(id) <ide><path>graph/pull_v2.go <ide> import ( <ide> "io" <ide> "io/ioutil" <ide> "os" <del> "sync" <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/distribution" <ide> func (p *v2Puller) pullV2Tag(out io.Writer, tag, taggedName string) (tagUpdated <ide> Action: "Extracting", <ide> }) <ide> <add> p.graph.imagesMutex.Lock() <add> defer p.graph.imagesMutex.Unlock() <add> <ide> p.graph.imageMutex.Lock(d.img.id) <ide> defer p.graph.imageMutex.Unlock(d.img.id) <ide> <ide> func (p *v2Puller) getImageInfos(m *manifest.Manifest) ([]contentAddressableDesc <ide> return imgs, nil <ide> } <ide> <del>var idReuseLock sync.Mutex <del> <ide> // attemptIDReuse does a best attempt to match verified compatibilityIDs <ide> // already in the graph with the computed strongIDs so we can keep using them. <ide> // This process will never fail but may just return the strongIDs if none of <ide> func (p *v2Puller) attemptIDReuse(imgs []contentAddressableDescriptor) { <ide> // This function needs to be protected with a global lock, because it <ide> // locks multiple IDs at once, and there's no good way to make sure <ide> // the locking happens a deterministic order. <del> idReuseLock.Lock() <del> defer idReuseLock.Unlock() <add> p.graph.imagesMutex.Lock() <add> defer p.graph.imagesMutex.Unlock() <ide> <ide> idMap := make(map[string]struct{}) <ide> for _, img := range imgs { <ide><path>integration-cli/docker_cli_images_test.go <ide> func (s *DockerSuite) TestImagesEnsureOnlyHeadsImagesShown(c *check.C) { <ide> head, out, err := buildImageWithOut("scratch-image", dockerfile, false) <ide> c.Assert(err, check.IsNil) <ide> <add> // this is just the output of docker build <add> // we're interested in getting the image id of the MAINTAINER instruction <add> // and that's located at output, line 5, from 7 to end <ide> split := strings.Split(out, "\n") <ide> intermediate := strings.TrimSpace(split[5][7:]) <ide>
3
Text
Text
remove empty lines to ensure javascript is loaded
75123c614bb5a61c383cdc247230b3a76c76e14d
<ide><path>docs/getting-started.md <ide> to the [Tutorial](docs/tutorial.html). <ide> container.className.replace(RegExp('display-' + type + '-[a-z]+ ?'), ''); <ide> event && event.preventDefault(); <ide> } <del> <ide> function convertBlocks() { <ide> // Convert <div>...<span><block /></span>...</div> <ide> // Into <div>...<block />...</div> <ide> to the [Tutorial](docs/tutorial.html). <ide> } <ide> } <ide> } <del> <ide> function guessPlatformAndOS() { <ide> if (!document.querySelector('block')) { <ide> return; <ide> } <del> <ide> // If we are coming to the page with a hash in it (i.e. from a search, for example), try to get <ide> // us as close as possible to the correct platform and dev os using the hashtag and block walk up. <ide> var foundHash = false; <ide> to the [Tutorial](docs/tutorial.html). <ide> if (parent.tagName === 'BLOCK') { <ide> // Could be more than one target os and dev platform, but just choose some sort of order <ide> // of priority here. <del> <ide> // Dev OS <ide> if (parent.className.indexOf('mac') > -1) { <ide> displayTab('os', 'mac'); <ide> to the [Tutorial](docs/tutorial.html). <ide> } else { <ide> break; <ide> } <del> <ide> // Target Platform <ide> if (parent.className.indexOf('ios') > -1) { <ide> displayTab('platform', 'ios'); <ide> to the [Tutorial](docs/tutorial.html). <ide> } else { <ide> break; <ide> } <del> <ide> // Guide <ide> if (parent.className.indexOf('native') > -1) { <ide> displayTab('guide', 'native'); <ide> to the [Tutorial](docs/tutorial.html). <ide> } else { <ide> break; <ide> } <del> <ide> break; <ide> } <ide> parent = parent.parentElement; <ide> } <ide> } <ide> } <ide> } <del> <ide> // Do the default if there is no matching hash <ide> if (!foundHash) { <ide> var isMac = navigator.platform === 'MacIntel'; <ide> to the [Tutorial](docs/tutorial.html). <ide> displayTab('language', 'objc'); <ide> } <ide> } <del> <ide> convertBlocks(); <ide> guessPlatformAndOS(); <ide> </script> <ide><path>docs/integration-with-existing-apps.md <ide> At this point you can continue developing your app as usual. Refer to our [debug <ide> container.className.replace(RegExp('display-' + type + '-[a-z]+ ?'), ''); <ide> event && event.preventDefault(); <ide> } <del> <ide> function convertBlocks() { <ide> // Convert <div>...<span><block /></span>...</div> <ide> // Into <div>...<block />...</div> <ide> At this point you can continue developing your app as usual. Refer to our [debug <ide> } <ide> } <ide> } <del> <ide> function guessPlatformAndOS() { <ide> if (!document.querySelector('block')) { <ide> return; <ide> } <del> <ide> // If we are coming to the page with a hash in it (i.e. from a search, for example), try to get <ide> // us as close as possible to the correct platform and dev os using the hashtag and block walk up. <ide> var foundHash = false; <ide> At this point you can continue developing your app as usual. Refer to our [debug <ide> if (parent.tagName === 'BLOCK') { <ide> // Could be more than one target os and dev platform, but just choose some sort of order <ide> // of priority here. <del> <ide> // Dev OS <ide> if (parent.className.indexOf('mac') > -1) { <ide> displayTab('os', 'mac'); <ide> At this point you can continue developing your app as usual. Refer to our [debug <ide> } else { <ide> break; <ide> } <del> <ide> // Target Platform <ide> if (parent.className.indexOf('ios') > -1) { <ide> displayTab('platform', 'ios'); <ide> At this point you can continue developing your app as usual. Refer to our [debug <ide> } else { <ide> break; <ide> } <del> <ide> // Guide <ide> if (parent.className.indexOf('native') > -1) { <ide> displayTab('guide', 'native'); <ide> At this point you can continue developing your app as usual. Refer to our [debug <ide> } else { <ide> break; <ide> } <del> <ide> break; <ide> } <ide> parent = parent.parentElement; <ide> } <ide> } <ide> } <ide> } <del> <ide> // Do the default if there is no matching hash <ide> if (!foundHash) { <ide> var isMac = navigator.platform === 'MacIntel'; <ide> At this point you can continue developing your app as usual. Refer to our [debug <ide> displayTab('language', 'objc'); <ide> } <ide> } <del> <ide> convertBlocks(); <ide> guessPlatformAndOS(); <ide> </script> <ide><path>docs/running-on-device.md <ide> You have built a great app using React Native, and you are now itching to releas <ide> container.className = 'display-' + type + '-' + value + ' ' + <ide> container.className.replace(RegExp('display-' + type + '-[a-z]+ ?'), ''); <ide> } <del> <ide> function convertBlocks() { <ide> // Convert <div>...<span><block /></span>...</div> <ide> // Into <div>...<block />...</div> <ide> You have built a great app using React Native, and you are now itching to releas <ide> } <ide> } <ide> } <del> <ide> function guessPlatformAndOS() { <ide> if (!document.querySelector('block')) { <ide> return; <ide> } <del> <ide> // If we are coming to the page with a hash in it (i.e. from a search, for example), try to get <ide> // us as close as possible to the correct platform and dev os using the hashtag and block walk up. <ide> var foundHash = false; <ide> You have built a great app using React Native, and you are now itching to releas <ide> if (parent.tagName === 'BLOCK') { <ide> // Could be more than one target os and dev platform, but just choose some sort of order <ide> // of priority here. <del> <ide> // Dev OS <ide> if (parent.className.indexOf('mac') > -1) { <ide> displayTab('os', 'mac'); <ide> You have built a great app using React Native, and you are now itching to releas <ide> } else { <ide> break; <ide> } <del> <ide> // Target Platform <ide> if (parent.className.indexOf('ios') > -1) { <ide> displayTab('platform', 'ios'); <ide> You have built a great app using React Native, and you are now itching to releas <ide> } else { <ide> break; <ide> } <del> <ide> // Guide <ide> if (parent.className.indexOf('native') > -1) { <ide> displayTab('guide', 'native'); <ide> You have built a great app using React Native, and you are now itching to releas <ide> } else { <ide> break; <ide> } <del> <ide> break; <ide> } <ide> parent = parent.parentElement; <ide> } <ide> } <ide> } <ide> } <del> <ide> // Do the default if there is no matching hash <ide> if (!foundHash) { <ide> var isMac = navigator.platform === 'MacIntel'; <ide> You have built a great app using React Native, and you are now itching to releas <ide> displayTab('language', 'objc'); <ide> } <ide> } <del> <ide> convertBlocks(); <ide> guessPlatformAndOS(); <ide> </script>
3
Javascript
Javascript
remove unused $log param
0a9c4681c2f1d15819c8cffde2aceb5e4c818749
<ide><path>test/ng/directive/ngStyleSpec.js <ide> describe('ngStyle', function() { <ide> })); <ide> <ide> <del> it('should support lazy one-time binding for object literals', inject(function($rootScope, $compile, $log) { <add> it('should support lazy one-time binding for object literals', inject(function($rootScope, $compile) { <ide> element = $compile('<div ng-style="::{height: heightStr}"></div>')($rootScope); <ide> $rootScope.$digest(); <ide> expect(parseInt(element.css('height') + 0)).toEqual(0); // height could be '' or '0px'
1
PHP
PHP
wrap long line
12ca48c8b1e88cbab5eb642e1fdc1eaf2cc3ce56
<ide><path>src/Controller/Exception/InvalidParameterException.php <ide> class InvalidParameterException extends CakeException <ide> */ <ide> protected $templates = [ <ide> 'failed_coercion' => 'Unable to coerce "%s" to `%s` for `%s` in action %s::%s().', <del> 'missing_dependency' => 'Failed to inject dependency from service container for parameter `%s` with type `%s` in action %s::%s().', <add> 'missing_dependency' => 'Failed to inject dependency from service container for parameter `%s` ' . <add> 'with type `%s` in action %s::%s().', <ide> 'missing_parameter' => 'Missing passed parameter for `%s` in action %s::%s().', <ide> 'unsupported_type' => 'Type declaration for `%s` in action %s::%s() is unsupported.', <ide> ];
1
Mixed
Javascript
reset player on source change. closes closes
95c29e684f405cb410a7e19dbf9668b5b46d349b
<ide><path>CHANGELOG.md <ide> CHANGELOG <ide> <ide> ## HEAD (Unreleased) <ide> * Updated the UI to support live video ([view](https://github.com/videojs/video.js/pull/1121)) <add>* The UI now resets after a source change [[view](https://github.com/videojs/video.js/pull/1124)] <ide> <ide> -------------------- <ide> <ide><path>src/js/player.js <ide> vjs.Player = vjs.Component.extend({ <ide> // this.addClass('vjs-touch-enabled'); <ide> // } <ide> <del> // Firstplay event implimentation. Not sold on the event yet. <del> // Could probably just check currentTime==0? <del> this.one('play', function(e){ <del> var fpEvent = { type: 'firstplay', target: this.el_ }; <del> // Using vjs.trigger so we can check if default was prevented <del> var keepGoing = vjs.trigger(this.el_, fpEvent); <del> <del> if (!keepGoing) { <del> e.preventDefault(); <del> e.stopPropagation(); <del> e.stopImmediatePropagation(); <del> } <del> }); <del> <add> this.on('loadstart', this.onLoadStart); <ide> this.on('ended', this.onEnded); <ide> this.on('play', this.onPlay); <ide> this.on('firstplay', this.onFirstPlay); <ide> vjs.Player.prototype.stopTrackingCurrentTime = function(){ clearInterval(this.cu <ide> * Fired when the user agent begins looking for media data <ide> * @event loadstart <ide> */ <del>vjs.Player.prototype.onLoadStart; <add>vjs.Player.prototype.onLoadStart = function() { <add> // remove any first play listeners that weren't triggered from a previous video. <add> this.off('play', initFirstPlay); <add> this.one('play', initFirstPlay); <add> <add> vjs.removeClass(this.el_, 'vjs-has-started'); <add>}; <add> <add> // Need to create this outside the scope of onLoadStart so it <add> // can be added and removed (to avoid piling first play listeners). <add>function initFirstPlay(e) { <add> var fpEvent = { type: 'firstplay', target: this.el_ }; <add> // Using vjs.trigger so we can check if default was prevented <add> var keepGoing = vjs.trigger(this.el_, fpEvent); <add> <add> if (!keepGoing) { <add> e.preventDefault(); <add> e.stopPropagation(); <add> e.stopImmediatePropagation(); <add> } <add>} <ide> <ide> /** <ide> * Fired when the player has initial duration and dimension information <ide><path>test/unit/player.js <ide> test('should register players with generated ids', function(){ <ide> equal(player.el().id, player.id(), 'the player and element ids are equal'); <ide> ok(vjs.players[id], 'the generated id is registered'); <ide> }); <add> <add>test('should not add multiple first play events despite subsequent loads', function() { <add> expect(1); <add> <add> var player = PlayerTest.makePlayer({}); <add> <add> player.on('firstplay', function(){ <add> ok('First play should fire once.'); <add> }); <add> <add> // Checking to make sure onLoadStart removes first play listener before adding a new one. <add> player.trigger('loadstart'); <add> player.trigger('loadstart'); <add> player.trigger('play'); <add>}); <add> <add>test('should remove vjs-has-started class', function(){ <add> expect(3); <add> <add> var player = PlayerTest.makePlayer({}); <add> <add> player.trigger('loadstart'); <add> player.trigger('play'); <add> ok(player.el().className.indexOf('vjs-has-started') !== -1, 'vjs-has-started class added'); <add> <add> player.trigger('loadstart'); <add> ok(player.el().className.indexOf('vjs-has-started') === -1, 'vjs-has-started class removed'); <add> <add> player.trigger('play'); <add> ok(player.el().className.indexOf('vjs-has-started') !== -1, 'vjs-has-started class added again'); <add>});
3
Text
Text
fix minor typos in collaborator_guide.md
d8578bad25ef24354027369a56e4e9388035d8a7
<ide><path>COLLABORATOR_GUIDE.md <ide> necessary. <ide> <ide> ## Accepting Modifications <ide> <del>All modifications to the the io.js code and documentation should be <add>All modifications to the io.js code and documentation should be <ide> performed via GitHub pull requests, including modifications by <ide> Collaborators and TC members. <ide> <ide> information regarding the change process: <ide> other Collaborators who have reviewed the change. <ide> - A `PR-URL:` line that references the full GitHub URL of the original <ide> pull request being merged so it's easy to trace a commit back to the <del> conversation that lead up to that change. <add> conversation that led up to that change. <ide> - A `Fixes: X` line, where _X_ is either includes the full GitHub URL <ide> for an issue, and/or the hash and commit message if the commit fixes <ide> a bug in a previous commit. Multiple `Fixes:` lines may be added if <ide> Time to push it: <ide> <ide> ```text <ide> $ git push origin v1.x <del>``` <ide>\ No newline at end of file <add>```
1
Ruby
Ruby
fix rubocop warnings
caecead7a7157e51b4ff3989604816e087707895
<ide><path>Library/Homebrew/os/mac/xquartz.rb <ide> module Mac <ide> module XQuartz <ide> extend self <ide> <del> FORGE_BUNDLE_ID = "org.macosforge.xquartz.X11" <del> APPLE_BUNDLE_ID = "org.x.X11" <del> FORGE_PKG_ID = "org.macosforge.xquartz.pkg" <add> FORGE_BUNDLE_ID = "org.macosforge.xquartz.X11".freeze <add> APPLE_BUNDLE_ID = "org.x.X11".freeze <add> FORGE_PKG_ID = "org.macosforge.xquartz.pkg".freeze <ide> <ide> PKGINFO_VERSION_MAP = { <ide> "2.6.34" => "2.6.3",
1
Ruby
Ruby
add missing require
da06ae88abeaadb560e9ba01621f108f01cf7158
<ide><path>activerecord/test/cases/modules_test.rb <ide> require "cases/helper" <ide> require 'models/company_in_module' <ide> require 'models/shop' <add>require 'models/developer' <ide> <ide> class ModulesTest < ActiveRecord::TestCase <ide> fixtures :accounts, :companies, :projects, :developers, :collections, :products, :variants
1
Text
Text
fix typo in env howto
3fc5f73dc9232acc67bcf9a24e1c2218a8c6dcab
<ide><path>docs/basic-features/environment-variables.md <ide> Next.js allows you to set defaults in `.env` (all environments), `.env.developme <ide> <ide> `.env.local` always overrides the defaults set. <ide> <del>> **Note**: `.env`, `.env.development`, and `.env.production` files should be included in your repository as they define defaults. **`.env*.local` should be added to `.gitignore`**, as those files are intended to be ignored. `.env.local` is where secrets can be stored. <add>> **Note**: `.env`, `.env.development`, and `.env.production` files should be included in your repository as they define defaults. **`.env.*.local` should be added to `.gitignore`**, as those files are intended to be ignored. `.env.local` is where secrets can be stored. <ide> <ide> ## Environment Variables on Vercel <ide>
1
Ruby
Ruby
clear the attribute after done
762088a0ef1f69ab09833732cfe8190098303ee6
<ide><path>activesupport/test/core_ext/class/delegating_attributes_test.rb <ide> def test_delegation_stops_for_nil <ide> <ide> assert_equal "1", Child.some_attribute <ide> assert_nil Mokopuna.some_attribute <add> ensure <add> Child.some_attribute=nil <ide> end <ide> <ide> end
1
Javascript
Javascript
fix instancecontainselem bug from typo
83c3ed290cb9994d89e430fd565d108365b42ac7
<ide><path>packages/react-dom/src/client/ReactDOMHostConfig.js <ide> export function clearSuspenseBoundaryFromContainer( <ide> function instanceContainsElem(instance: Instance, element: HTMLElement) { <ide> let fiber = getClosestInstanceFromNode(element); <ide> while (fiber !== null) { <del> if (fiber.tag === HostComponent && fiber.stateNode === element) { <add> if (fiber.tag === HostComponent && fiber.stateNode === instance) { <ide> return true; <ide> } <ide> fiber = fiber.return;
1
Ruby
Ruby
remove dependency on `from_now` extension
9fbfb4bffe72320cc895e2f4eb4e30e108d58bb2
<ide><path>activesupport/lib/active_support/messages/metadata.rb <ide> def pick_expiry(expires_at, expires_in) <ide> if expires_at <ide> expires_at.utc.iso8601(3) <ide> elsif expires_in <del> expires_in.from_now.utc.iso8601(3) <add> Time.now.utc.advance(seconds: expires_in).iso8601(3) <ide> end <ide> end <ide>
1
Python
Python
fix typo in license docstring
d432a654f6c54351b4c2ba149bc32137c92bed40
<ide><path>examples/pytorch/audio-classification/run_audio_classification.py <ide> # distributed under the License is distributed on an "AS IS" BASIS, <ide> # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <ide> # See the License for the specific language governing permissions and <add># limitations under the License. <ide> <ide> import logging <ide> import os
1
Python
Python
use python 2.6 compatible assertions in tests
bf8d3329d43bf534e45cb8182a6d712138566cdc
<ide><path>numpy/ma/tests/test_core.py <ide> def test_dot(self): <ide> fx = mx.filled(0) <ide> r = mx.dot(mx) <ide> assert_almost_equal(r.filled(0), fx.dot(fx)) <del> self.assertIs(r.mask, nomask) <add> assert_(r.mask is nomask) <ide> <ide> fX = mX.filled(0) <ide> r = mX.dot(mX) <ide> assert_almost_equal(r.filled(0), fX.dot(fX)) <del> self.assertTrue(r.mask[1,3]) <add> assert_(r.mask[1,3]) <ide> r1 = empty_like(r) <ide> mX.dot(mX, r1) <ide> assert_almost_equal(r, r1)
1
Ruby
Ruby
remove the assignment for real this time
0372c5078af38081ebc273eab69687a6b9768751
<ide><path>activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb <ide> def self.build(lhs_class, name, options) <ide> class_name = options.fetch(:class_name) { <ide> model_name = name.to_s.camelize.singularize <ide> <del> if parent_name = lhs_class.parent_name <del> model_name.prepend("#{parent_name}::") <add> if lhs_class.parent_name <add> model_name.prepend("#{lhs_class.parent_name}::") <ide> end <ide> <ide> model_name
1
Mixed
Go
rename a existing container
21a809d9ae0ef8392f37c9262dca93ff31966e22
<ide><path>api/client/commands.go <ide> func (cli *DockerCli) CmdPause(args ...string) error { <ide> return encounteredError <ide> } <ide> <add>func (cli *DockerCli) CmdRename(args ...string) error { <add> cmd := cli.Subcmd("rename", "OLD_NAME NEW_NAME", "Rename a container", true) <add> if err := cmd.Parse(args); err != nil { <add> return nil <add> } <add> <add> if cmd.NArg() != 2 { <add> cmd.Usage() <add> return nil <add> } <add> old_name := cmd.Arg(0) <add> new_name := cmd.Arg(1) <add> <add> if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/rename?name=%s", old_name, new_name), nil, false)); err != nil { <add> fmt.Fprintf(cli.err, "%s\n", err) <add> return fmt.Errorf("Error: failed to rename container named %s", old_name) <add> } <add> return nil <add>} <add> <ide> func (cli *DockerCli) CmdInspect(args ...string) error { <ide> cmd := cli.Subcmd("inspect", "CONTAINER|IMAGE [CONTAINER|IMAGE...]", "Return low-level information on a container or image", true) <ide> tmplStr := cmd.String([]string{"f", "#format", "-format"}, "", "Format the output using the given go template.") <ide><path>api/server/server.go <ide> func postContainersRestart(eng *engine.Engine, version version.Version, w http.R <ide> return nil <ide> } <ide> <add>func postContainerRename(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add> if err := parseForm(r); err != nil { <add> return err <add> } <add> if vars == nil { <add> return fmt.Errorf("Missing parameter") <add> } <add> <add> newName := r.URL.Query().Get("name") <add> job := eng.Job("container_rename", vars["name"], newName) <add> job.Setenv("t", r.Form.Get("t")) <add> if err := job.Run(); err != nil { <add> return err <add> } <add> w.WriteHeader(http.StatusNoContent) <add> return nil <add>} <add> <ide> func deleteContainers(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := parseForm(r); err != nil { <ide> return err <ide> func createRouter(eng *engine.Engine, logging, enableCors bool, dockerVersion st <ide> "/containers/{name:.*}/exec": postContainerExecCreate, <ide> "/exec/{name:.*}/start": postContainerExecStart, <ide> "/exec/{name:.*}/resize": postContainerExecResize, <add> "/containers/{name:.*}/rename": postContainerRename, <ide> }, <ide> "DELETE": { <ide> "/containers/{name:.*}": deleteContainers, <ide><path>daemon/daemon.go <ide> func (daemon *Daemon) Install(eng *engine.Engine) error { <ide> "commit": daemon.ContainerCommit, <ide> "container_changes": daemon.ContainerChanges, <ide> "container_copy": daemon.ContainerCopy, <add> "container_rename": daemon.ContainerRename, <ide> "container_inspect": daemon.ContainerInspect, <ide> "containers": daemon.Containers, <ide> "create": daemon.ContainerCreate, <ide><path>daemon/rename.go <add>package daemon <add> <add>import ( <add> "github.com/docker/docker/engine" <add>) <add> <add>func (daemon *Daemon) ContainerRename(job *engine.Job) engine.Status { <add> if len(job.Args) != 2 { <add> return job.Errorf("usage: %s OLD_NAME NEW_NAME", job.Name) <add> } <add> old_name := job.Args[0] <add> new_name := job.Args[1] <add> <add> container := daemon.Get(old_name) <add> if container == nil { <add> return job.Errorf("No such container: %s", old_name) <add> } <add> <add> container.Lock() <add> defer container.Unlock() <add> if err := daemon.containerGraph.Delete(container.Name); err != nil { <add> return job.Errorf("Failed to delete container %q: %v", old_name, err) <add> } <add> if _, err := daemon.reserveName(container.ID, new_name); err != nil { <add> return job.Errorf("Error when allocating new name: %s", err) <add> } <add> container.Name = new_name <add> <add> return engine.StatusOK <add>} <ide><path>docker/flags.go <ide> func init() { <ide> {"ps", "List containers"}, <ide> {"pull", "Pull an image or a repository from a Docker registry server"}, <ide> {"push", "Push an image or a repository to a Docker registry server"}, <add> {"rename", "Rename an existing container"}, <ide> {"restart", "Restart a running container"}, <ide> {"rm", "Remove one or more containers"}, <ide> {"rmi", "Remove one or more images"}, <ide><path>docs/man/docker-rename.1.md <add>% DOCKER(1) Docker User Manuals <add>% Docker Community <add>% OCTOBER 2014 <add># NAME <add>docker-rename - Rename a container <add> <add># SYNOPSIS <add>**docker rename** <add>OLD_NAME NEW_NAME <add> <add># OPTIONS <add>There are no available options. <add> <ide><path>docs/sources/reference/api/docker_remote_api_v1.15.md <ide> Status Codes: <ide> - **404** – no such container <ide> - **500** – server error <ide> <add>### Rename a container <add> <add>`POST /containers/(id)/rename/(new_name)` <add> <add>Rename the container `id` to a `new_name` <add> <add>**Example request**: <add> <add> POST /containers/e90e34656806/rename/new_name HTTP/1.1 <add> <add>**Example response**: <add> <add> HTTP/1.1 204 No Content <add> <add>Status Codes: <add> <add>- **204** – no error <add>- **404** – no such container <add>- **409** - conflict name already assigned <add>- **500** – server error <add> <ide> ### Pause a container <ide> <ide> `POST /containers/(id)/pause` <ide><path>docs/sources/reference/commandline/cli.md <ide> just a specific mapping: <ide> $ sudo docker port test 7890 <ide> 0.0.0.0:4321 <ide> <add>## pause <add> <add> Usage: docker pause CONTAINER <add> <add> Pause all processes within a container <add> <add>The `docker pause` command uses the cgroups freezer to suspend all processes in <add>a container. Traditionally when suspending a process the `SIGSTOP` signal is <add>used, which is observable by the process being suspended. With the cgroups freezer <add>the process is unaware, and unable to capture, that it is being suspended, <add>and subsequently resumed. <add> <add>See the <add>[cgroups freezer documentation](https://www.kernel.org/doc/Documentation/cgroups/freezer-subsystem.txt) <add>for further details. <add> <add>## rename <add> <add> Usage: docker rename OLD_NAME NEW_NAME <add> <add> rename a existing container to a NEW_NAME <add> <add>The `docker rename` command allows the container to be renamed to a different name. <add> <ide> ## ps <ide> <ide> Usage: docker ps [OPTIONS] <ide><path>integration-cli/docker_cli_links_test.go <ide> package main <ide> <ide> import ( <add> "github.com/docker/docker/pkg/iptables" <ide> "io/ioutil" <ide> "os" <ide> "os/exec" <ide> "reflect" <ide> "strings" <ide> "testing" <ide> "time" <del> <del> "github.com/docker/docker/pkg/iptables" <ide> ) <ide> <ide> func TestLinksEtcHostsRegularFile(t *testing.T) { <ide> func TestLinksPingLinkedContainers(t *testing.T) { <ide> logDone("links - ping linked container") <ide> } <ide> <add>func TestLinksPingLinkedContainersAfterRename(t *testing.T) { <add> out, _, _ := dockerCmd(t, "run", "-d", "--name", "container1", "busybox", "sleep", "10") <add> idA := stripTrailingCharacters(out) <add> out, _, _ = dockerCmd(t, "run", "-d", "--name", "container2", "busybox", "sleep", "10") <add> idB := stripTrailingCharacters(out) <add> dockerCmd(t, "rename", "container1", "container_new") <add> dockerCmd(t, "run", "--rm", "--link", "container_new:alias1", "--link", "container2:alias2", "busybox", "sh", "-c", "ping -c 1 alias1 -W 1 && ping -c 1 alias2 -W 1") <add> dockerCmd(t, "kill", idA) <add> dockerCmd(t, "kill", idB) <add> deleteAllContainers() <add> <add> logDone("links - ping linked container after rename") <add>} <add> <add>func TestLinksPingLinkedContainersOnRename(t *testing.T) { <add> var out string <add> out, _, _ = dockerCmd(t, "run", "-d", "--name", "container1", "busybox", "sleep", "10") <add> idA := stripTrailingCharacters(out) <add> if idA == "" { <add> t.Fatal(out, "id should not be nil") <add> } <add> out, _, _ = dockerCmd(t, "run", "-d", "--link", "container1:alias1", "--name", "container2", "busybox", "sleep", "10") <add> idB := stripTrailingCharacters(out) <add> if idB == "" { <add> t.Fatal(out, "id should not be nil") <add> } <add> <add> execCmd := exec.Command(dockerBinary, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1") <add> out, _, err := runCommandWithOutput(execCmd) <add> if err != nil { <add> t.Fatal(out, err) <add> } <add> <add> dockerCmd(t, "rename", "container1", "container_new") <add> <add> execCmd = exec.Command(dockerBinary, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1") <add> out, _, err = runCommandWithOutput(execCmd) <add> if err != nil { <add> t.Fatal(out, err) <add> } <add> <add> deleteAllContainers() <add> <add> logDone("links - ping linked container upon rename") <add>} <add> <ide> func TestLinksIpTablesRulesWhenLinkAndUnlink(t *testing.T) { <ide> dockerCmd(t, "run", "-d", "--name", "child", "--publish", "8080:80", "busybox", "sleep", "10") <ide> dockerCmd(t, "run", "-d", "--name", "parent", "--link", "child:http", "busybox", "sleep", "10") <ide><path>integration-cli/docker_cli_rename_test.go <add>package main <add> <add>import ( <add> "os/exec" <add> "strings" <add> "testing" <add>) <add> <add>func TestRenameStoppedContainer(t *testing.T) { <add> runCmd := exec.Command(dockerBinary, "run", "--name", "first_name", "-d", "busybox", "sh") <add> out, _, err := runCommandWithOutput(runCmd) <add> if err != nil { <add> t.Fatalf(out, err) <add> } <add> <add> cleanedContainerID := stripTrailingCharacters(out) <add> <add> runCmd = exec.Command(dockerBinary, "wait", cleanedContainerID) <add> out, _, err = runCommandWithOutput(runCmd) <add> if err != nil { <add> t.Fatalf(out, err) <add> } <add> <add> name, err := inspectField(cleanedContainerID, "Name") <add> <add> runCmd = exec.Command(dockerBinary, "rename", "first_name", "new_name") <add> out, _, err = runCommandWithOutput(runCmd) <add> if err != nil { <add> t.Fatalf(out, err) <add> } <add> <add> name, err = inspectField(cleanedContainerID, "Name") <add> if err != nil { <add> t.Fatal(err) <add> } <add> if name != "new_name" { <add> t.Fatal("Failed to rename container ", name) <add> } <add> deleteAllContainers() <add> <add> logDone("rename - stopped container") <add>} <add> <add>func TestRenameRunningContainer(t *testing.T) { <add> runCmd := exec.Command(dockerBinary, "run", "--name", "first_name", "-d", "busybox", "sh") <add> out, _, err := runCommandWithOutput(runCmd) <add> if err != nil { <add> t.Fatalf(out, err) <add> } <add> <add> cleanedContainerID := stripTrailingCharacters(out) <add> runCmd = exec.Command(dockerBinary, "rename", "first_name", "new_name") <add> out, _, err = runCommandWithOutput(runCmd) <add> if err != nil { <add> t.Fatalf(out, err) <add> } <add> <add> name, err := inspectField(cleanedContainerID, "Name") <add> if err != nil { <add> t.Fatal(err) <add> } <add> if name != "new_name" { <add> t.Fatal("Failed to rename container ") <add> } <add> deleteAllContainers() <add> <add> logDone("rename - running container") <add>} <add> <add>func TestRenameCheckNames(t *testing.T) { <add> runCmd := exec.Command(dockerBinary, "run", "--name", "first_name", "-d", "busybox", "sh") <add> out, _, err := runCommandWithOutput(runCmd) <add> if err != nil { <add> t.Fatalf(out, err) <add> } <add> <add> runCmd = exec.Command(dockerBinary, "rename", "first_name", "new_name") <add> out, _, err = runCommandWithOutput(runCmd) <add> if err != nil { <add> t.Fatalf(out, err) <add> } <add> <add> name, err := inspectField("new_name", "Name") <add> if err != nil { <add> t.Fatal(err) <add> } <add> if name != "new_name" { <add> t.Fatal("Failed to rename container ") <add> } <add> <add> name, err = inspectField("first_name", "Name") <add> if err == nil && !strings.Contains(err.Error(), "No such image or container: first_name") { <add> t.Fatal(err) <add> } <add> <add> deleteAllContainers() <add> <add> logDone("rename - running container") <add>}
10
Ruby
Ruby
remove unnecessary chomps
c44c8da5e0becf02ef6d6180fadb8efa8df69714
<ide><path>Library/Homebrew/exceptions.rb <ide> def initialize(flags, bottled: true) <ide> require_text = "requires" <ide> end <ide> <del> message = <<~EOS.chomp! <add> message = <<~EOS <ide> The following #{flag_text}: <ide> #{flags.join(", ")} <ide> #{require_text} building tools, but none are installed. <ide> #{DevelopmentTools.installation_instructions} <ide> EOS <ide> <del> message << <<~EOS.chomp! if bottled <del> \nAlternatively, remove the #{flag_text} to attempt bottle installation. <add> message << <<~EOS if bottled <add> Alternatively, remove the #{flag_text} to attempt bottle installation. <ide> EOS <ide> <ide> super message
1
Javascript
Javascript
improve buffer constructor
4c9b30db675ba3094a733e2691e968b658105334
<ide><path>lib/buffer.js <ide> function Buffer(subject, encoding) { <ide> 'size: 0x' + kMaxLength.toString(16) + ' bytes'); <ide> } <ide> <add> this.parent = null; <ide> if (this.length <= (Buffer.poolSize >>> 1) && this.length > 0) { <ide> if (this.length > poolSize - poolOffset) <ide> createPool(); <ide> Buffer.byteLength = function(str, enc) { <ide> }; <ide> <ide> <del>// pre-set for values that may exist in the future <del>Buffer.prototype.length = undefined; <del>Buffer.prototype.parent = undefined; <del> <del> <ide> // toString(encoding, start=0, end=buffer.length) <ide> Buffer.prototype.toString = function(encoding, start, end) { <ide> var loweredCase = false;
1
PHP
PHP
allow schema path on fresh
4f9300bfa4ea5103f16d9d9a05b933fb21cb83fb
<ide><path>src/Illuminate/Database/Console/Migrations/FreshCommand.php <ide> public function handle() <ide> '--database' => $database, <ide> '--path' => $this->input->getOption('path'), <ide> '--realpath' => $this->input->getOption('realpath'), <add> '--schema-path' => $this->input->getOption('schema-path'), <ide> '--force' => true, <ide> '--step' => $this->option('step'), <ide> ])); <ide> protected function getOptions() <ide> ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production'], <ide> ['path', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'The path(s) to the migrations files to be executed'], <ide> ['realpath', null, InputOption::VALUE_NONE, 'Indicate any provided migration file paths are pre-resolved absolute paths'], <add> ['schema-path', null, InputOption::VALUE_OPTIONAL, 'The path to a schema dump file'], <ide> ['seed', null, InputOption::VALUE_NONE, 'Indicates if the seed task should be re-run'], <ide> ['seeder', null, InputOption::VALUE_OPTIONAL, 'The class name of the root seeder'], <ide> ['step', null, InputOption::VALUE_NONE, 'Force the migrations to be run so they can be rolled back individually'],
1
PHP
PHP
fix another block of at() matchers
89500f74b51f32015dfd01cf0c02e6de47d6b396
<ide><path>tests/TestCase/Mailer/Transport/SmtpTransportTest.php <ide> public function testConnectEhlo() <ide> public function testConnectEhloTls() <ide> { <ide> $this->SmtpTransport->setConfig(['tls' => true]); <del> $this->socket->expects($this->any())->method('connect')->will($this->returnValue(true)); <del> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("220 Welcome message\r\n")); <del> $this->socket->expects($this->at(2))->method('write')->with("EHLO localhost\r\n"); <del> $this->socket->expects($this->at(3))->method('read')->will($this->returnValue("250 Accepted\r\n")); <del> $this->socket->expects($this->at(4))->method('write')->with("STARTTLS\r\n"); <del> $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("220 Server ready\r\n")); <del> $this->socket->expects($this->at(6))->method('enableCrypto')->with('tls')->will($this->returnValue(true)); <del> $this->socket->expects($this->at(7))->method('write')->with("EHLO localhost\r\n"); <del> $this->socket->expects($this->at(8))->method('read')->will($this->returnValue("250 Accepted\r\n")); <add> $this->socket->expects($this->once())->method('connect')->will($this->returnValue(true)); <add> <add> $this->socket->expects($this->exactly(4)) <add> ->method('read') <add> ->will($this->onConsecutiveCalls( <add> "220 Welcome message\r\n", <add> "250 Accepted\r\n", <add> "220 Server ready\r\n", <add> "250 Accepted\r\n", <add> )); <add> $this->socket->expects($this->exactly(3)) <add> ->method('write') <add> ->withConsecutive( <add> ["EHLO localhost\r\n"], <add> ["STARTTLS\r\n"], <add> ["EHLO localhost\r\n"], <add> ); <add> $this->socket->expects($this->once())->method('enableCrypto') <add> ->with('tls') <add> ->will($this->returnValue(true)); <add> <ide> $this->SmtpTransport->connect(); <ide> } <ide> <ide> public function testConnectEhloTlsOnNonTlsServer() <ide> { <ide> $this->SmtpTransport->setConfig(['tls' => true]); <ide> $this->socket->expects($this->any())->method('connect')->will($this->returnValue(true)); <del> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("220 Welcome message\r\n")); <del> $this->socket->expects($this->at(2))->method('write')->with("EHLO localhost\r\n"); <del> $this->socket->expects($this->at(3))->method('read')->will($this->returnValue("250 Accepted\r\n")); <del> $this->socket->expects($this->at(4))->method('write')->with("STARTTLS\r\n"); <del> $this->socket->expects($this->at(5))->method('read') <del> ->will($this->returnValue("500 5.3.3 Unrecognized command\r\n")); <add> <add> $this->socket->expects($this->exactly(3)) <add> ->method('read') <add> ->will($this->onConsecutiveCalls( <add> "220 Welcome message\r\n", <add> "250 Accepted\r\n", <add> "500 5.3.3 Unrecognized command\r\n" <add> )); <add> $this->socket->expects($this->exactly(2)) <add> ->method('write') <add> ->withConsecutive( <add> ["EHLO localhost\r\n"], <add> ["STARTTLS\r\n"] <add> ); <ide> <ide> $e = null; <ide> try { <ide> public function testConnectEhloNoTlsOnRequiredTlsServer() <ide> $this->expectExceptionMessage('SMTP authentication method not allowed, check if SMTP server requires TLS.'); <ide> $this->SmtpTransport->setConfig(['tls' => false] + $this->credentials); <ide> <del> $this->socket->expects($this->any())->method('connect')->will($this->returnValue(true)); <del> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("220 Welcome message\r\n")); <del> $this->socket->expects($this->at(2))->method('write')->with("EHLO localhost\r\n"); <del> $this->socket->expects($this->at(3))->method('read')->will($this->returnValue("250 Accepted\r\n")); <add> $this->socket->expects($this->exactly(4)) <add> ->method('read') <add> ->will($this->onConsecutiveCalls( <add> "220 Welcome message\r\n", <add> "250 Accepted\r\n", <add> "504 5.7.4 Unrecognized Authentication Type\r\n", <add> "504 5.7.4 Unrecognized authentication type\r\n" <add> )); <add> $this->socket->expects($this->exactly(3)) <add> ->method('write') <add> ->withConsecutive( <add> ["EHLO localhost\r\n"], <add> ["AUTH PLAIN {$this->credentialsEncoded}\r\n"], <add> ["AUTH LOGIN\r\n"] <add> ); <ide> <del> $this->socket->expects($this->at(4))->method('write')->with("AUTH PLAIN {$this->credentialsEncoded}\r\n"); <del> $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("504 5.7.4 Unrecognized Authentication Type\r\n")); <add> $this->socket->expects($this->once())->method('connect')->will($this->returnValue(true)); <ide> <del> $this->socket->expects($this->at(6))->method('write')->with("AUTH LOGIN\r\n"); <del> $this->socket->expects($this->at(7))->method('read') <del> ->will($this->returnValue("504 5.7.4 Unrecognized authentication type\r\n")); <ide> $this->SmtpTransport->connect(); <ide> } <ide> <ide> public function testConnectEhloNoTlsOnRequiredTlsServer() <ide> */ <ide> public function testConnectHelo() <ide> { <del> $this->socket->expects($this->any())->method('connect')->will($this->returnValue(true)); <del> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("220 Welcome message\r\n")); <del> $this->socket->expects($this->at(2))->method('write')->with("EHLO localhost\r\n"); <del> $this->socket->expects($this->at(3))->method('read')->will($this->returnValue("200 Not Accepted\r\n")); <del> $this->socket->expects($this->at(4))->method('write')->with("HELO localhost\r\n"); <del> $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("250 Accepted\r\n")); <add> $this->socket->expects($this->exactly(3)) <add> ->method('read') <add> ->will($this->onConsecutiveCalls( <add> "220 Welcome message\r\n", <add> "200 Not Accepted\r\n", <add> "250 Accepted\r\n" <add> )); <add> $this->socket->expects($this->exactly(2)) <add> ->method('write') <add> ->withConsecutive( <add> ["EHLO localhost\r\n"], <add> ["HELO localhost\r\n"], <add> ); <add> <add> $this->socket->expects($this->once())->method('connect')->will($this->returnValue(true)); <ide> $this->SmtpTransport->connect(); <ide> } <ide> <ide> public function testConnectHelo() <ide> */ <ide> public function testConnectFail() <ide> { <del> $this->socket->expects($this->any())->method('connect')->will($this->returnValue(true)); <del> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("220 Welcome message\r\n")); <del> $this->socket->expects($this->at(2))->method('write')->with("EHLO localhost\r\n"); <del> $this->socket->expects($this->at(3))->method('read')->will($this->returnValue("200 Not Accepted\r\n")); <del> $this->socket->expects($this->at(4))->method('write')->with("HELO localhost\r\n"); <del> $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("200 Not Accepted\r\n")); <add> $this->socket->expects($this->exactly(3)) <add> ->method('read') <add> ->will($this->onConsecutiveCalls( <add> "220 Welcome message\r\n", <add> "200 Not Accepted\r\n", <add> "200 Not Accepted\r\n" <add> )); <add> $this->socket->expects($this->exactly(2)) <add> ->method('write') <add> ->withConsecutive( <add> ["EHLO localhost\r\n"], <add> ["HELO localhost\r\n"] <add> ); <add> $this->socket->expects($this->once())->method('connect')->will($this->returnValue(true)); <ide> <ide> $e = null; <ide> try { <ide> public function testAuthPlain() <ide> */ <ide> public function testAuthLogin() <ide> { <del> $this->socket->expects($this->at(0))->method('write')->with("AUTH PLAIN {$this->credentialsEncoded}\r\n"); <del> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("504 5.7.4 Unrecognized Authentication Type\r\n")); <del> <del> $this->socket->expects($this->at(2))->method('write')->with("AUTH LOGIN\r\n"); <del> $this->socket->expects($this->at(3))->method('read')->will($this->returnValue("334 Login\r\n")); <del> $this->socket->expects($this->at(4))->method('write')->with("bWFyaw==\r\n"); <del> $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("334 Pass\r\n")); <del> $this->socket->expects($this->at(6))->method('write')->with("c3Rvcnk=\r\n"); <del> $this->socket->expects($this->at(7))->method('read')->will($this->returnValue("235 OK\r\n")); <add> $this->socket->expects($this->exactly(4)) <add> ->method('read') <add> ->will($this->onConsecutiveCalls( <add> "504 5.7.4 Unrecognized Authentication Type\r\n", <add> "334 Login\r\n", <add> "334 Pass\r\n", <add> "235 OK\r\n" <add> )); <add> $this->socket->expects($this->exactly(4)) <add> ->method('write') <add> ->withConsecutive( <add> ["AUTH PLAIN {$this->credentialsEncoded}\r\n"], <add> ["AUTH LOGIN\r\n"], <add> ["bWFyaw==\r\n"], <add> ["c3Rvcnk=\r\n"] <add> ); <add> <ide> $this->SmtpTransport->setConfig($this->credentials); <ide> $this->SmtpTransport->auth(); <ide> } <ide> public function testAuthNotRecognized() <ide> $this->expectException(\Cake\Network\Exception\SocketException::class); <ide> $this->expectExceptionMessage('AUTH command not recognized or not implemented, SMTP server may not require authentication.'); <ide> <del> $this->socket->expects($this->at(0))->method('write')->with("AUTH PLAIN {$this->credentialsEncoded}\r\n"); <del> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("504 5.7.4 Unrecognized Authentication Type\r\n")); <add> $this->socket->expects($this->exactly(2)) <add> ->method('read') <add> ->will($this->onConsecutiveCalls( <add> "504 5.7.4 Unrecognized Authentication Type\r\n", <add> "500 5.3.3 Unrecognized command\r\n" <add> )); <add> $this->socket->expects($this->exactly(2)) <add> ->method('write') <add> ->withConsecutive( <add> ["AUTH PLAIN {$this->credentialsEncoded}\r\n"], <add> ["AUTH LOGIN\r\n"] <add> ); <ide> <del> $this->socket->expects($this->at(2))->method('write')->with("AUTH LOGIN\r\n"); <del> $this->socket->expects($this->at(3))->method('read') <del> ->will($this->returnValue("500 5.3.3 Unrecognized command\r\n")); <ide> $this->SmtpTransport->setConfig($this->credentials); <ide> $this->SmtpTransport->auth(); <ide> } <ide> public function testAuthNotImplemented() <ide> $this->expectException(\Cake\Network\Exception\SocketException::class); <ide> $this->expectExceptionMessage('AUTH command not recognized or not implemented, SMTP server may not require authentication.'); <ide> <del> $this->socket->expects($this->at(0))->method('write')->with("AUTH PLAIN {$this->credentialsEncoded}\r\n"); <del> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("504 5.7.4 Unrecognized Authentication Type\r\n")); <del> <del> $this->socket->expects($this->at(2))->method('write')->with("AUTH LOGIN\r\n"); <del> $this->socket->expects($this->at(3))->method('read') <del> ->will($this->returnValue("502 5.3.3 Command not implemented\r\n")); <add> $this->socket->expects($this->exactly(2)) <add> ->method('read') <add> ->will($this->onConsecutiveCalls( <add> "504 5.7.4 Unrecognized Authentication Type\r\n", <add> "502 5.3.3 Command not implemented\r\n" <add> )); <add> $this->socket->expects($this->exactly(2)) <add> ->method('write') <add> ->withConsecutive( <add> ["AUTH PLAIN {$this->credentialsEncoded}\r\n"], <add> ["AUTH LOGIN\r\n"] <add> ); <ide> $this->SmtpTransport->setConfig($this->credentials); <ide> $this->SmtpTransport->auth(); <ide> } <ide> public function testAuthBadSequence() <ide> $this->expectException(\Cake\Network\Exception\SocketException::class); <ide> $this->expectExceptionMessage('SMTP Error: 503 5.5.1 Already authenticated'); <ide> <del> $this->socket->expects($this->at(0))->method('write')->with("AUTH PLAIN {$this->credentialsEncoded}\r\n"); <del> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("504 5.7.4 Unrecognized Authentication Type\r\n")); <del> <del> $this->socket->expects($this->at(2))->method('write')->with("AUTH LOGIN\r\n"); <del> $this->socket->expects($this->at(3)) <del> ->method('read')->will($this->returnValue("503 5.5.1 Already authenticated\r\n")); <add> $this->socket->expects($this->exactly(2)) <add> ->method('read') <add> ->will($this->onConsecutiveCalls( <add> "504 5.7.4 Unrecognized Authentication Type\r\n", <add> "503 5.5.1 Already authenticated\r\n" <add> )); <add> $this->socket->expects($this->exactly(2)) <add> ->method('write') <add> ->withConsecutive( <add> ["AUTH PLAIN {$this->credentialsEncoded}\r\n"], <add> ["AUTH LOGIN\r\n"], <add> ); <ide> $this->SmtpTransport->setConfig($this->credentials); <ide> $this->SmtpTransport->auth(); <ide> } <ide> public function testAuthBadSequence() <ide> */ <ide> public function testAuthBadUsername() <ide> { <del> $this->socket->expects($this->at(0))->method('write')->with("AUTH PLAIN {$this->credentialsEncoded}\r\n"); <del> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("504 5.7.4 Unrecognized Authentication Type\r\n")); <del> <del> $this->socket->expects($this->at(2))->method('write')->with("AUTH LOGIN\r\n"); <del> $this->socket->expects($this->at(3))->method('read')->will($this->returnValue("334 Login\r\n")); <del> $this->socket->expects($this->at(4))->method('write')->with("bWFyaw==\r\n"); <del> $this->socket->expects($this->at(5))->method('read') <del> ->will($this->returnValue("535 5.7.8 Authentication failed\r\n")); <add> $this->socket->expects($this->exactly(3)) <add> ->method('read') <add> ->will($this->onConsecutiveCalls( <add> "504 5.7.4 Unrecognized Authentication Type\r\n", <add> "334 Login\r\n", <add> "535 5.7.8 Authentication failed\r\n" <add> )); <add> $this->socket->expects($this->exactly(3)) <add> ->method('write') <add> ->withConsecutive( <add> ["AUTH PLAIN {$this->credentialsEncoded}\r\n"], <add> ["AUTH LOGIN\r\n"], <add> ["bWFyaw==\r\n"], <add> ); <add> <ide> $this->SmtpTransport->setConfig($this->credentials); <ide> <ide> $e = null; <ide> public function testAuthBadUsername() <ide> */ <ide> public function testAuthBadPassword() <ide> { <del> $this->socket->expects($this->at(0))->method('write')->with("AUTH PLAIN {$this->credentialsEncoded}\r\n"); <del> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("504 5.7.4 Unrecognized Authentication Type\r\n")); <del> <del> $this->socket->expects($this->at(2))->method('write')->with("AUTH LOGIN\r\n"); <del> $this->socket->expects($this->at(3))->method('read')->will($this->returnValue("334 Login\r\n")); <del> $this->socket->expects($this->at(4))->method('write')->with("bWFyaw==\r\n"); <del> $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("334 Pass\r\n")); <del> $this->socket->expects($this->at(6))->method('write')->with("c3Rvcnk=\r\n"); <del> $this->socket->expects($this->at(7))->method('read')->will($this->returnValue("535 5.7.8 Authentication failed\r\n")); <add> $this->socket->expects($this->exactly(4)) <add> ->method('read') <add> ->will($this->onConsecutiveCalls( <add> "504 5.7.4 Unrecognized Authentication Type\r\n", <add> "334 Login\r\n", <add> "334 Pass\r\n", <add> "535 5.7.8 Authentication failed\r\n" <add> )); <add> $this->socket->expects($this->exactly(4)) <add> ->method('write') <add> ->withConsecutive( <add> ["AUTH PLAIN {$this->credentialsEncoded}\r\n"], <add> ["AUTH LOGIN\r\n"], <add> ["bWFyaw==\r\n"], <add> ["c3Rvcnk=\r\n"] <add> ); <add> <ide> $this->SmtpTransport->setConfig($this->credentials); <ide> <ide> $e = null; <ide> public function testKeepAlive() <ide> $this->socket->expects($this->any())->method('write')->will($this->returnCallback($callback)); <ide> $this->socket->expects($this->never())->method('disconnect'); <ide> <del> $this->socket->expects($this->at(0))->method('connect')->will($this->returnValue(true)); <del> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("220 Welcome message\r\n")); <del> $this->socket->expects($this->at(2))->method('write')->with("EHLO localhost\r\n"); <del> $this->socket->expects($this->at(3))->method('read')->will($this->returnValue("250 OK\r\n")); <del> <del> $this->socket->expects($this->at(4))->method('write')->with("MAIL FROM:<noreply@cakephp.org>\r\n"); <del> $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("250 OK\r\n")); <del> $this->socket->expects($this->at(6))->method('write')->with("RCPT TO:<cake@cakephp.org>\r\n"); <del> $this->socket->expects($this->at(7))->method('read')->will($this->returnValue("250 OK\r\n")); <del> <del> $this->socket->expects($this->at(8))->method('write')->with("DATA\r\n"); <del> $this->socket->expects($this->at(9))->method('read')->will($this->returnValue("354 OK\r\n")); <del> $this->socket->expects($this->at(10))->method('write')->with($this->stringContains('First Line')); <del> $this->socket->expects($this->at(11))->method('read')->will($this->returnValue("250 OK\r\n")); <del> <del> $this->socket->expects($this->at(12))->method('write')->with("RSET\r\n"); <del> $this->socket->expects($this->at(13))->method('read')->will($this->returnValue("250 OK\r\n")); <del> <del> $this->socket->expects($this->at(14))->method('write')->with("MAIL FROM:<noreply@cakephp.org>\r\n"); <del> $this->socket->expects($this->at(15))->method('read')->will($this->returnValue("250 OK\r\n")); <del> $this->socket->expects($this->at(16))->method('write')->with("RCPT TO:<cake@cakephp.org>\r\n"); <del> $this->socket->expects($this->at(17))->method('read')->will($this->returnValue("250 OK\r\n")); <del> <del> $this->socket->expects($this->at(18))->method('write')->with("DATA\r\n"); <del> $this->socket->expects($this->at(19))->method('read')->will($this->returnValue("354 OK\r\n")); <del> $this->socket->expects($this->at(20))->method('write')->with($this->stringContains('First Line')); <del> $this->socket->expects($this->at(21))->method('read')->will($this->returnValue("250 OK\r\n")); <add> $this->socket->expects($this->exactly(11)) <add> ->method('read') <add> ->will($this->onConsecutiveCalls( <add> "220 Welcome message\r\n", <add> "250 OK\r\n", <add> "250 OK\r\n", <add> "250 OK\r\n", <add> "354 OK\r\n", <add> "250 OK\r\n", <add> "250 OK\r\n", <add> // Second email <add> "250 OK\r\n", <add> "250 OK\r\n", <add> "354 OK\r\n", <add> "250 OK\r\n", <add> )); <add> $this->socket->expects($this->exactly(10)) <add> ->method('write') <add> ->withConsecutive( <add> ["EHLO localhost\r\n"], <add> ["MAIL FROM:<noreply@cakephp.org>\r\n"], <add> ["RCPT TO:<cake@cakephp.org>\r\n"], <add> ["DATA\r\n"], <add> [$this->stringContains('First Line')], <add> ["RSET\r\n"], <add> // Second email <add> ["MAIL FROM:<noreply@cakephp.org>\r\n"], <add> ["RCPT TO:<cake@cakephp.org>\r\n"], <add> ["DATA\r\n"], <add> [$this->stringContains('First Line')], <add> ); <add> <add> $this->socket->expects($this->once())->method('connect')->will($this->returnValue(true)); <ide> <ide> $this->SmtpTransport->send($message); <ide> $this->socket->connected = true;
1
Go
Go
fix rename for containers on swarm network
ed935930b5d72d6166c5b8366533c629ec7c90b7
<ide><path>libnetwork/endpoint.go <ide> func doUpdateHostsFile(n *network, sb *sandbox) bool { <ide> } <ide> <ide> func (ep *endpoint) rename(name string) error { <del> var err error <add> var ( <add> err error <add> netWatch *netWatch <add> ok bool <add> ) <add> <ide> n := ep.getNetwork() <ide> if n == nil { <ide> return fmt.Errorf("network not connected for ep %q", ep.name) <ide> } <ide> <del> n.getController().Lock() <del> netWatch, ok := n.getController().nmap[n.ID()] <del> n.getController().Unlock() <add> c := n.getController() <ide> <del> if !ok { <del> return fmt.Errorf("watch null for network %q", n.Name()) <add> if c.isAgent() { <add> if err = ep.deleteServiceInfoFromCluster(); err != nil { <add> return types.InternalErrorf("Could not delete service state for endpoint %s from cluster on rename: %v", ep.Name(), err) <add> } <add> } else { <add> c.Lock() <add> netWatch, ok = c.nmap[n.ID()] <add> c.Unlock() <add> if !ok { <add> return fmt.Errorf("watch null for network %q", n.Name()) <add> } <add> n.updateSvcRecord(ep, c.getLocalEps(netWatch), false) <ide> } <ide> <del> n.updateSvcRecord(ep, n.getController().getLocalEps(netWatch), false) <del> <ide> oldName := ep.name <ide> oldAnonymous := ep.anonymous <ide> ep.name = name <ide> ep.anonymous = false <ide> <del> n.updateSvcRecord(ep, n.getController().getLocalEps(netWatch), true) <del> defer func() { <del> if err != nil { <del> n.updateSvcRecord(ep, n.getController().getLocalEps(netWatch), false) <del> ep.name = oldName <del> ep.anonymous = oldAnonymous <del> n.updateSvcRecord(ep, n.getController().getLocalEps(netWatch), true) <add> if c.isAgent() { <add> if err = ep.addServiceInfoToCluster(); err != nil { <add> return types.InternalErrorf("Could not add service state for endpoint %s to cluster on rename: %v", ep.Name(), err) <ide> } <del> }() <add> defer func() { <add> if err != nil { <add> ep.deleteServiceInfoFromCluster() <add> ep.name = oldName <add> ep.anonymous = oldAnonymous <add> ep.addServiceInfoToCluster() <add> } <add> }() <add> } else { <add> n.updateSvcRecord(ep, c.getLocalEps(netWatch), true) <add> defer func() { <add> if err != nil { <add> n.updateSvcRecord(ep, c.getLocalEps(netWatch), false) <add> ep.name = oldName <add> ep.anonymous = oldAnonymous <add> n.updateSvcRecord(ep, c.getLocalEps(netWatch), true) <add> } <add> }() <add> } <ide> <ide> // Update the store with the updated name <del> if err = n.getController().updateToStore(ep); err != nil { <add> if err = c.updateToStore(ep); err != nil { <ide> return err <ide> } <ide> // After the name change do a dummy endpoint count update to
1
Javascript
Javascript
use pdfview.error to avoid issues with alert
e0378530e2243ee73cc9d80bba7bfce5f4182061
<ide><path>web/viewer.js <ide> var PDFView = { <ide> if (!this.supportsPrinting) { <ide> var printMessage = mozL10n.get('printing_not_supported', null, <ide> 'Warning: Printing is not fully supported by this browser.'); <del> alert(printMessage); <add> this.error(printMessage); <ide> return; <ide> } <ide> var body = document.querySelector('body');
1
Python
Python
remove unused variable
47ddce6eb74c10f1e6e87b212be92f977e858daf
<ide><path>spacy/__main__.py <ide> def __missing__(self, name): <ide> if __name__ == '__main__': <ide> import plac <ide> import sys <del> cli = CLI() <ide> sys.argv[0] = 'spacy' <ide> plac.Interpreter.call(CLI)
1
Ruby
Ruby
add documentation for arel_table
7ecfe3d30ccfaee8dcca4ee649cc006c090bdfb4
<ide><path>activerecord/lib/active_record/core.rb <ide> def ===(object) <ide> object.is_a?(self) <ide> end <ide> <add> # Returns an instance of +Arel::Table+ loaded with the curent <add> # table name <add> # <add> # class Post < ActiveRecord::Base <add> # scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0)) <add> # end <add> # end <ide> def arel_table <ide> @arel_table ||= Arel::Table.new(table_name, arel_engine) <ide> end <ide> <add> # Returns the Arel engine <ide> def arel_engine <ide> @arel_engine ||= connection_handler.retrieve_connection_pool(self) ? self : active_record_super.arel_engine <ide> end
1
Python
Python
add new recfunctions to numpy function api
61371de744b363eacdb2ae277c33d365164380f3
<ide><path>numpy/lib/recfunctions.py <ide> def _get_fields_and_offsets(dt, offset=0): <ide> fields.extend(_get_fields_and_offsets(field[0], field[1] + offset)) <ide> return fields <ide> <add> <add>def _structured_to_unstructured_dispatcher(arr, dtype=None, copy=None, <add> casting=None): <add> return (arr,) <add> <add>@array_function_dispatch(_structured_to_unstructured_dispatcher) <ide> def structured_to_unstructured(arr, dtype=None, copy=False, casting='unsafe'): <ide> """ <ide> Converts and n-D structured array into an (n+1)-D unstructured array. <ide> def structured_to_unstructured(arr, dtype=None, copy=False, casting='unsafe'): <ide> # finally is it safe to view the packed fields as the unstructured type <ide> return arr.view((out_dtype, sum(counts))) <ide> <add>def _unstructured_to_structured_dispatcher(arr, dtype=None, names=None, <add> align=None, copy=None, casting=None): <add> return (arr,) <add> <add>@array_function_dispatch(_unstructured_to_structured_dispatcher) <ide> def unstructured_to_structured(arr, dtype=None, names=None, align=False, <ide> copy=False, casting='unsafe'): <ide> """ <ide> def unstructured_to_structured(arr, dtype=None, names=None, align=False, <ide> # finally view as the final nested dtype and remove the last axis <ide> return arr.view(out_dtype)[..., 0] <ide> <add>def _apply_along_fields_dispatcher(func, arr): <add> return (arr,) <add> <add>@array_function_dispatch(_apply_along_fields_dispatcher) <ide> def apply_along_fields(func, arr): <ide> """ <ide> Apply function 'func' as a reduction across fields of a structured array. <ide> def apply_along_fields(func, arr): <ide> # works and avoids axis requirement, but very, very slow: <ide> #return np.apply_along_axis(func, -1, uarr) <ide> <add>def _assign_fields_by_name_dispatcher(dst, src, zero_unassigned=None): <add> return dst, src <add> <add>@array_function_dispatch(_assign_fields_by_name_dispatcher) <ide> def assign_fields_by_name(dst, src, zero_unassigned=True): <ide> """ <ide> Assigns values from one structured array to another by field name. <ide> def assign_fields_by_name(dst, src, zero_unassigned=True): <ide> assign_fields_by_name(dst[name], src[name], <ide> zero_unassigned) <ide> <add>def _require_fields_dispatcher(array, required_dtype): <add> return (array,) <add> <add>@array_function_dispatch(_require_fields_dispatcher) <ide> def require_fields(array, required_dtype): <ide> """ <ide> Casts a structured array to a new dtype using assignment by field-name.
1
Text
Text
fix example in node-api docs
6ce085c99b42ff3a63f7e11ebef7934174e825e1
<ide><path>doc/api/n-api.md <ide> snippet: <ide> function AddTwo(num) { <ide> return num + 2; <ide> } <add>global.AddTwo = AddTwo; <ide> ``` <ide> <ide> Then, the above function can be invoked from a native add-on using the
1
Ruby
Ruby
pull autoload fix from 2-3-stable
99803b7cdba13345d267127e14809fc389a0e0c2
<ide><path>actionpack/lib/action_view/helpers.rb <ide> module Helpers #:nodoc: <ide> autoload :FormHelper, 'action_view/helpers/form_helper' <ide> autoload :FormOptionsHelper, 'action_view/helpers/form_options_helper' <ide> autoload :FormTagHelper, 'action_view/helpers/form_tag_helper' <del> autoload :JavascriptHelper, 'action_view/helpers/javascript_helper' <add> autoload :JavaScriptHelper, 'action_view/helpers/javascript_helper' <ide> autoload :NumberHelper, 'action_view/helpers/number_helper' <ide> autoload :PrototypeHelper, 'action_view/helpers/prototype_helper' <ide> autoload :RecordIdentificationHelper, 'action_view/helpers/record_identification_helper'
1
Mixed
Ruby
add bang version to orderedoptions
e768c519fb6015e00961702a5165c6dab548a954
<ide><path>activesupport/CHANGELOG.md <add>* Add a bang version to `ActiveSupport::OrderedOptions` get methods which will raise an `KeyError` if the value is `.blank?` <add> Before: <add> <add> if (slack_url = Rails.application.secrets.slack_url).present?) <add> // Do something worthwhile <add> else <add> // Raise hell as important secret password is not specified <add> end <add> <add> After: <add> <add> slack_url = Rails.application.secrets.slack_url! <add> <add> *Aditya Sanghi*, *Gaurish Sharma* <add> <ide> * Patch `Delegator` to work with `#try`. <ide> <ide> Fixes #5790. <ide><path>activesupport/lib/active_support/ordered_options.rb <ide> def method_missing(name, *args) <ide> if name_string.chomp!('=') <ide> self[name_string] = args.first <ide> else <del> self[name] <add> bangs = name_string.chomp!('!') <add> if bangs <add> fetch(name_string.to_sym).presence || raise(KeyError.new("#{name_string} is nil or undefined")) <add> else <add> self[name_string] <add> end <ide> end <ide> end <ide> <ide><path>activesupport/test/ordered_options_test.rb <ide> def test_introspection <ide> assert_equal 42, a.method(:blah=).call(42) <ide> assert_equal 42, a.method(:blah).call <ide> end <add> <add> def test_raises_with_bang <add> a = ActiveSupport::OrderedOptions.new <add> a[:foo] = :bar <add> assert a.respond_to?(:foo!) <add> <add> assert_nothing_raised { a.foo! } <add> assert_equal a.foo, a.foo! <add> <add> assert_raises(KeyError) do <add> a.foo = nil <add> a.foo! <add> end <add> assert_raises(KeyError){ a.non_existing_key! } <add> end <ide> end
3
PHP
PHP
add explicit test for
67410cd21384827ddfc739c67b6beef7c1d81f72
<ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testHasOne() <ide> $this->assertSame($table, $hasOne->source()); <ide> } <ide> <add> /** <add> * Test has one with a plugin model <add> * <add> * @return void <add> */ <add> public function testHasOnePlugin() <add> { <add> $options = ['className' => 'TestPlugin.Comments']; <add> $table = new Table(['table' => 'users']); <add> <add> $hasOne = $table->hasOne('Comments', $options); <add> $this->assertInstanceOf('Cake\ORM\Association\HasOne', $hasOne); <add> $this->assertSame('Comments', $hasOne->name()); <add> <add> $hasOneTable = $hasOne->target(); <add> $this->assertSame('Comments', $hasOne->alias()); <add> $this->assertSame('TestPlugin.Comments', $hasOne->registryAlias()); <add> } <add> <ide> /** <ide> * Tests that hasMany() creates and configures correctly the association <ide> *
1
Javascript
Javascript
take help message from commands
cb71a7dab3043ecf7016caec2de234624e10360c
<ide><path>lib/_debugger.js <ide> Client.prototype.step = function(action, count, cb) { <ide> }; <ide> <ide> <add>var commands = [ <add> 'backtrace', <add> 'continue', <add> 'help', <add> 'info breakpoints', <add> 'kill', <add> 'list', <add> 'next', <add> 'print', <add> 'quit', <add> 'run', <add> 'scripts', <add> 'step', <add> 'version', <add>]; <ide> <ide> <del>var helpMessage = 'Commands: run, kill, print, step, next, ' + <del> 'continue, list, scripts, backtrace, version, quit'; <add>var helpMessage = 'Commands: ' + commands.join(', '); <add> <ide> <ide> function SourceUnderline(sourceText, position) { <ide> if (!sourceText) return; <ide> function Interface() { <ide> } <ide> <ide> <del>var commands = [ <del> 'backtrace', <del> 'continue', <del> 'help', <del> 'info breakpoints', <del> 'kill', <del> 'list', <del> 'next', <del> 'print', <del> 'quit', <del> 'run', <del> 'scripts', <del> 'step', <del> 'version', <del>]; <del> <del> <ide> Interface.prototype.complete = function(line) { <ide> // Match me with a command. <ide> var matches = [];
1
Ruby
Ruby
use private accessor
05c3ba113c752c1aebc09260bd0ce36f9e3b722b
<ide><path>lib/action_cable/connection/base.rb <ide> def process <ide> if websocket? <ide> @websocket = Faye::WebSocket.new(@env) <ide> <del> @websocket.on(:open) { |event| send_async :on_open } <del> @websocket.on(:message) { |event| on_message event.data } <del> @websocket.on(:close) { |event| send_async :on_close } <del> <del> @websocket.rack_response <add> websocket.on(:open) { |event| send_async :on_open } <add> websocket.on(:message) { |event| on_message event.data } <add> websocket.on(:close) { |event| send_async :on_close } <add> <add> websocket.rack_response <ide> else <ide> respond_to_invalid_request <ide> end <ide> def receive(data_in_json) <ide> end <ide> <ide> def transmit(data) <del> @websocket.send data <add> websocket.send data <ide> end <ide> <ide> def close <ide> logger.error "Closing connection" <del> @websocket.close <add> websocket.close <ide> end <ide> <ide> <ide> def cookies <ide> <ide> <ide> private <add> attr_reader :websocket <ide> attr_reader :heartbeat, :subscriptions, :message_buffer <ide> <ide> def on_open <ide> def respond_to_invalid_request <ide> end <ide> <ide> def websocket_alive? <del> @websocket && @websocket.ready_state == Faye::WebSocket::API::OPEN <add> websocket && websocket.ready_state == Faye::WebSocket::API::OPEN <ide> end <ide> <ide> def websocket?
1
PHP
PHP
add a validate method to the validation factory
e84f0a4b5cb8ff976392a45b645397a7ba7db065
<ide><path>src/Illuminate/Validation/Factory.php <ide> public function make(array $data, array $rules, array $messages = [], array $cus <ide> return $validator; <ide> } <ide> <add> /** <add> * Validate the given data against the provided rules. <add> * <add> * @param array $data <add> * @param array $rules <add> * @param array $messages <add> * @param array $customAttributes <add> * @return void <add> * <add> * @throws \Illuminate\Validation\ValidationException <add> */ <add> public function validate(array $data, array $rules, array $messages = [], array $customAttributes = []) <add> { <add> $this->make($data, $rules, $messages, $customAttributes)->validate(); <add> } <add> <ide> /** <ide> * Add the extensions to a validator instance. <ide> *
1
Python
Python
add kwarg method='get' for make_request()
ea5a6e4408b375340da7739986089fdd7c1bb6e9
<ide><path>py/libcloud/drivers/slicehost.py <ide> def _headers(self): <ide> return { 'Authorization': ('Basic %s' <ide> % (base64.b64encode('%s:' % self.key))) } <ide> <del> def make_request(self, path, data=''): <del> self.api.request('GET', path, headers=self._headers()) <add> def make_request(self, path, data='', method='GET'): <add> self.api.request(method, path, headers=self._headers()) <ide> return self.api.getresponse() <ide> <ide> def slices(self):
1
Javascript
Javascript
fix unused param line
be58df1b0f6f47c7d49a6e2d75fe07ade4326f41
<ide><path>examples/js/loaders/XLoader.js <ide> THREE.XLoader.prototype = { <ide> <ide> }, <ide> <del> endElement: function ( line ) { <add> endElement: function () { <ide> <ide> var scope = this; <ide> if ( scope.nowReadMode == THREE.XLoader.XfileLoadMode.Mesh ) { <ide> THREE.XLoader.prototype = { <ide> <ide> }, <ide> <del> beginMeshNormal: function ( line ) { <add> beginMeshNormal: function () { <ide> <ide> var scope = this; <ide> scope.nowReadMode = THREE.XLoader.XfileLoadMode.Normal_V_init; <ide> THREE.XLoader.prototype = { <ide> <ide> }, <ide> <del> readBoneInit: function ( line ) { <add> readBoneInit: function () { <ide> <ide> var scope = this; <ide> scope.nowReadMode = THREE.XLoader.XfileLoadMode.Weit_init;
1
Ruby
Ruby
add some basic controller logging tests
5cc27f2b0302698ef517755df41f3212587bceb9
<ide><path>actionpack/test/controller/logging_test.rb <add>require 'abstract_unit' <add> <add>class LoggingController < ActionController::Base <add> def show <add> render :nothing => true <add> end <add>end <add> <add>class LoggingTest < ActionController::TestCase <add> tests LoggingController <add> <add> class MockLogger <add> attr_reader :logged <add> <add> def method_missing(method, *args) <add> @logged ||= [] <add> @logged << args.first <add> end <add> end <add> <add> setup :set_logger <add> <add> def test_logging_without_parameters <add> get :show <add> assert_equal 2, logs.size <add> assert_nil logs.detect {|l| l =~ /Parameters/ } <add> end <add> <add> def test_logging_with_parameters <add> get :show, :id => 10 <add> assert_equal 3, logs.size <add> <add> params = logs.detect {|l| l =~ /Parameters/ } <add> assert_equal 'Parameters: {"id"=>"10"}', params <add> end <add> <add> private <add> <add> def set_logger <add> @controller.logger = MockLogger.new <add> end <add> <add> def logs <add> @logs ||= @controller.logger.logged.compact.map {|l| l.strip} <add> end <add>end
1
Mixed
Python
fix action support for viewset suffixes
903204cd7926e9e6ceaaec1bfbf1ba3ed3330ca4
<ide><path>docs/api-guide/viewsets.md <ide> You may inspect these attributes to adjust behaviour based on the current action <ide> <ide> ## Marking extra actions for routing <ide> <del>If you have ad-hoc methods that should be routable, you can mark them as such with the `@action` decorator. Like regular actions, extra actions may be intended for either a list of objects, or a single instance. To indicate this, set the `detail` argument to `True` or `False`. The router will configure its URL patterns accordingly. e.g., the `DefaultRouter` will configure detail actions to contain `pk` in their URL patterns. <add>If you have ad-hoc methods that should be routable, you can mark them as such with the `@action` decorator. Like regular actions, extra actions may be intended for either a single object, or an entire collection. To indicate this, set the `detail` argument to `True` or `False`. The router will configure its URL patterns accordingly. e.g., the `DefaultRouter` will configure detail actions to contain `pk` in their URL patterns. <ide> <ide> A more complete example of extra actions: <ide> <ide> The decorator can additionally take extra arguments that will be set for the rou <ide> def set_password(self, request, pk=None): <ide> ... <ide> <del>These decorator will route `GET` requests by default, but may also accept other HTTP methods by setting the `methods` argument. For example: <add>The `action` decorator will route `GET` requests by default, but may also accept other HTTP methods by setting the `methods` argument. For example: <ide> <ide> @action(detail=True, methods=['post', 'delete']) <ide> def unset_password(self, request, pk=None): <ide> To view all extra actions, call the `.get_extra_actions()` method. <ide> <ide> ### Routing additional HTTP methods for extra actions <ide> <del>Extra actions can be mapped to different `ViewSet` methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments. <add>Extra actions can map additional HTTP methods to separate `ViewSet` methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments. <ide> <ide> ```python <ide> @action(detail=True, methods=['put'], name='Change Password') <ide><path>rest_framework/decorators.py <ide> def decorator(func): <ide> return decorator <ide> <ide> <del>def action(methods=None, detail=None, name=None, url_path=None, url_name=None, **kwargs): <add>def action(methods=None, detail=None, url_path=None, url_name=None, **kwargs): <ide> """ <ide> Mark a ViewSet method as a routable action. <ide> <ide> def action(methods=None, detail=None, name=None, url_path=None, url_name=None, * <ide> "@action() missing required argument: 'detail'" <ide> ) <ide> <add> # name and suffix are mutually exclusive <add> if 'name' in kwargs and 'suffix' in kwargs: <add> raise TypeError("`name` and `suffix` are mutually exclusive arguments.") <add> <ide> def decorator(func): <ide> func.mapping = MethodMapper(func, methods) <ide> <ide> func.detail = detail <del> func.name = name if name else pretty_name(func.__name__) <ide> func.url_path = url_path if url_path else func.__name__ <ide> func.url_name = url_name if url_name else func.__name__.replace('_', '-') <ide> func.kwargs = kwargs <del> func.kwargs.update({ <del> 'name': func.name, <del> 'description': func.__doc__ or None <del> }) <add> <add> # Set descriptive arguments for viewsets <add> if 'name' not in kwargs and 'suffix' not in kwargs: <add> func.kwargs['name'] = pretty_name(func.__name__) <add> func.kwargs['description'] = func.__doc__ or None <ide> <ide> return func <ide> return decorator <ide><path>rest_framework/views.py <ide> <ide> def get_view_name(view): <ide> """ <del> Given a view class, return a textual name to represent the view. <add> Given a view instance, return a textual name to represent the view. <ide> This name is used in the browsable API, and in OPTIONS responses. <ide> <ide> This function is the default for the `VIEW_NAME_FUNCTION` setting. <ide> def get_view_name(view): <ide> <ide> def get_view_description(view, html=False): <ide> """ <del> Given a view class, return a textual description to represent the view. <add> Given a view instance, return a textual description to represent the view. <ide> This name is used in the browsable API, and in OPTIONS responses. <ide> <ide> This function is the default for the `VIEW_DESCRIPTION_FUNCTION` setting. <ide><path>rest_framework/viewsets.py <ide> def get_extra_action_url_map(self): <ide> try: <ide> url_name = '%s-%s' % (self.basename, action.url_name) <ide> url = reverse(url_name, self.args, self.kwargs, request=self.request) <del> action_urls[action.name] = url <add> view = self.__class__(**action.kwargs) <add> action_urls[view.get_view_name()] = url <ide> except NoReverseMatch: <ide> pass # URL requires additional arguments, ignore <ide> <ide><path>tests/test_decorators.py <ide> def test_action(request): <ide> <ide> assert test_action.mapping == {'get': 'test_action'} <ide> assert test_action.detail is True <del> assert test_action.name == 'Test action' <ide> assert test_action.url_path == 'test_action' <ide> assert test_action.url_name == 'test-action' <ide> assert test_action.kwargs == { <ide> def method(): <ide> for name in APIView.http_method_names: <ide> assert test_action.mapping[name] == name <ide> <add> def test_view_name_kwargs(self): <add> """ <add> 'name' and 'suffix' are mutually exclusive kwargs used for generating <add> a view's display name. <add> """ <add> # by default, generate name from method <add> @action(detail=True) <add> def test_action(request): <add> raise NotImplementedError <add> <add> assert test_action.kwargs == { <add> 'description': None, <add> 'name': 'Test action', <add> } <add> <add> # name kwarg supersedes name generation <add> @action(detail=True, name='test name') <add> def test_action(request): <add> raise NotImplementedError <add> <add> assert test_action.kwargs == { <add> 'description': None, <add> 'name': 'test name', <add> } <add> <add> # suffix kwarg supersedes name generation <add> @action(detail=True, suffix='Suffix') <add> def test_action(request): <add> raise NotImplementedError <add> <add> assert test_action.kwargs == { <add> 'description': None, <add> 'suffix': 'Suffix', <add> } <add> <add> # name + suffix is a conflict. <add> with pytest.raises(TypeError) as excinfo: <add> action(detail=True, name='test name', suffix='Suffix') <add> <add> assert str(excinfo.value) == "`name` and `suffix` are mutually exclusive arguments." <add> <ide> def test_method_mapping(self): <ide> @action(detail=False) <ide> def test_action(request): <ide> def test_action_post(request): <ide> raise NotImplementedError <ide> <ide> # The secondary handler methods should not have the action attributes <del> for name in ['mapping', 'detail', 'name', 'url_path', 'url_name', 'kwargs']: <add> for name in ['mapping', 'detail', 'url_path', 'url_name', 'kwargs']: <ide> assert hasattr(test_action, name) and not hasattr(test_action_post, name) <ide> <ide> def test_method_mapping_already_mapped(self): <ide><path>tests/test_utils.py <ide> def list_action(self, request, *args, **kwargs): <ide> def detail_action(self, request, *args, **kwargs): <ide> raise NotImplementedError <ide> <add> @action(detail=True, name='Custom Name') <add> def named_action(self, request, *args, **kwargs): <add> raise NotImplementedError <add> <add> @action(detail=True, suffix='Custom Suffix') <add> def suffixed_action(self, request, *args, **kwargs): <add> raise NotImplementedError <add> <ide> <ide> router = SimpleRouter() <ide> router.register(r'resources', ResourceViewSet) <ide> def test_modelviewset_detail_action_breadcrumbs(self): <ide> ('Detail action', '/resources/1/detail_action/'), <ide> ] <ide> <add> def test_modelviewset_action_name_kwarg(self): <add> url = '/resources/1/named_action/' <add> assert get_breadcrumbs(url) == [ <add> ('Root', '/'), <add> ('Resource List', '/resources/'), <add> ('Resource Instance', '/resources/1/'), <add> ('Custom Name', '/resources/1/named_action/'), <add> ] <add> <add> def test_modelviewset_action_suffix_kwarg(self): <add> url = '/resources/1/suffixed_action/' <add> assert get_breadcrumbs(url) == [ <add> ('Root', '/'), <add> ('Resource List', '/resources/'), <add> ('Resource Instance', '/resources/1/'), <add> ('Resource Custom Suffix', '/resources/1/suffixed_action/'), <add> ] <add> <ide> <ide> class JsonFloatTests(TestCase): <ide> """ <ide><path>tests/test_viewsets.py <ide> def unresolvable_detail_action(self, request, *args, **kwargs): <ide> raise NotImplementedError <ide> <ide> <add>class ActionNamesViewSet(GenericViewSet): <add> <add> def retrieve(self, request, *args, **kwargs): <add> return Response() <add> <add> @action(detail=True) <add> def unnamed_action(self, request, *args, **kwargs): <add> raise NotImplementedError <add> <add> @action(detail=True, name='Custom Name') <add> def named_action(self, request, *args, **kwargs): <add> raise NotImplementedError <add> <add> @action(detail=True, suffix='Custom Suffix') <add> def suffixed_action(self, request, *args, **kwargs): <add> raise NotImplementedError <add> <add> <ide> router = SimpleRouter() <ide> router.register(r'actions', ActionViewSet) <ide> router.register(r'actions-alt', ActionViewSet, basename='actions-alt') <add>router.register(r'names', ActionNamesViewSet, basename='names') <ide> <ide> <ide> urlpatterns = [ <ide> def test_detail_view(self): <ide> def test_uninitialized_view(self): <ide> self.assertEqual(ActionViewSet().get_extra_action_url_map(), OrderedDict()) <ide> <add> def test_action_names(self): <add> # Action 'name' and 'suffix' kwargs should be respected <add> response = self.client.get('/api/names/1/') <add> view = response.renderer_context['view'] <add> <add> expected = OrderedDict([ <add> ('Custom Name', 'http://testserver/api/names/1/named_action/'), <add> ('Action Names Custom Suffix', 'http://testserver/api/names/1/suffixed_action/'), <add> ('Unnamed action', 'http://testserver/api/names/1/unnamed_action/'), <add> ]) <add> <add> self.assertEqual(view.get_extra_action_url_map(), expected) <add> <ide> <ide> @override_settings(ROOT_URLCONF='tests.test_viewsets') <ide> class ReverseActionTests(TestCase):
7
Ruby
Ruby
add explicit mkpath to pathname#write_jar_script
5cbc5437f5578aa206cefe131072f3cc4738e69c
<ide><path>Library/Homebrew/extend/pathname.rb <ide> def env_script_all_files dst, env <ide> <ide> # Writes an exec script that invokes a java jar <ide> def write_jar_script target_jar, script_name, java_opts="" <add> mkpath <ide> (self+script_name).write <<-EOS.undent <ide> #!/bin/bash <ide> exec java #{java_opts} -jar #{target_jar} "$@"
1
Javascript
Javascript
convert `downloadmanager` to an es6 class
cbc411a2c7a0f2c195157beebd7ef1c8b737ffdf
<ide><path>web/download_manager.js <ide> if (typeof PDFJSDev !== 'undefined' && !PDFJSDev.test('CHROME || GENERIC')) { <ide> } <ide> <ide> function download(blobUrl, filename) { <del> var a = document.createElement('a'); <add> let a = document.createElement('a'); <ide> if (a.click) { <ide> // Use a.click() if available. Otherwise, Chrome might show <ide> // "Unsafe JavaScript attempt to initiate a navigation change <ide> function download(blobUrl, filename) { <ide> blobUrl.split('#')[0] === window.location.href.split('#')[0]) { <ide> // If _parent == self, then opening an identical URL with different <ide> // location hash will only cause a navigation, not a download. <del> var padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&'; <add> let padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&'; <ide> blobUrl = blobUrl.replace(/#|$/, padCharacter + '$&'); <ide> } <ide> window.open(blobUrl, '_parent'); <ide> } <ide> } <ide> <del>function DownloadManager() {} <del> <del>DownloadManager.prototype = { <del> downloadUrl: function DownloadManager_downloadUrl(url, filename) { <add>class DownloadManager { <add> downloadUrl(url, filename) { <ide> if (!createValidAbsoluteUrl(url, 'http://example.com')) { <ide> return; // restricted/invalid URL <ide> } <ide> download(url + '#pdfjs.action=download', filename); <del> }, <add> } <ide> <del> downloadData: function DownloadManager_downloadData(data, filename, <del> contentType) { <add> downloadData(data, filename, contentType) { <ide> if (navigator.msSaveBlob) { // IE10 and above <ide> return navigator.msSaveBlob(new Blob([data], { type: contentType, }), <ide> filename); <ide> } <del> <del> var blobUrl = createObjectURL(data, contentType, <add> let blobUrl = createObjectURL(data, contentType, <ide> PDFJS.disableCreateObjectURL); <ide> download(blobUrl, filename); <del> }, <add> } <ide> <del> download: function DownloadManager_download(blob, url, filename) { <add> download(blob, url, filename) { <ide> if (navigator.msSaveBlob) { <ide> // IE10 / IE11 <ide> if (!navigator.msSaveBlob(blob, filename)) { <ide> DownloadManager.prototype = { <ide> return; <ide> } <ide> <del> var blobUrl = URL.createObjectURL(blob); <add> let blobUrl = URL.createObjectURL(blob); <ide> download(blobUrl, filename); <del> }, <del>}; <add> } <add>} <ide> <ide> export { <ide> DownloadManager,
1
Text
Text
fix typo in action pack changelog [ci skip]
ca9e1e210193aaa85d9d8ea750418374d61d2ead
<ide><path>actionpack/CHANGELOG.md <ide> not meant to handle XML requests. <ide> <ide> Third, if the current request is an "interactive" browser request (the user <del> navigated here by entering the URL in the address bar, submiting a form, <add> navigated here by entering the URL in the address bar, submitting a form, <ide> clicking on a link, etc. as opposed to an XHR or non-browser API request), <ide> `ActionView::UnknownFormat` is raised to display a helpful error <ide> message. <ide><path>activesupport/CHANGELOG.md <ide> <ide> *Tara Scherner de la Fuente* <ide> <del>* Make `benchmark('something', silence: true)` actually work <add>* Make `benchmark('something', silence: true)` actually work. <ide> <ide> *DHH* <ide>
2
Text
Text
remove empty paragraphs and missing examples
70a2c7834249328fc8a901fa31ce64e09c0cebbf
<ide><path>packages/next/README.md <ide> So far, we get: <ide> - Server rendering and indexing of `./pages` <ide> - Static file serving. `./static/` is mapped to `/static/` (given you [create a `./static/` directory](#static-file-serving-eg-images) inside your project) <ide> <del>To see how simple this is, check out the [sample app - nextgram](https://github.com/zeit/nextgram) <ide> <ide> ### Automatic code splitting <ide> <ide> export default CowsayHi <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> We bundle [styled-jsx](https://github.com/zeit/styled-jsx) to provide support for isolated scoped CSS. The aim is to support "shadow CSS" similar to Web Components, which unfortunately [do not support server-rendering and are JS-only](https://github.com/w3c/webcomponents/issues/71). <ide> <ide> Please see the [styled-jsx documentation](https://www.npmjs.com/package/styled-j <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> It's possible to use any existing CSS-in-JS solution. The simplest one is inline styles: <ide> <ide> _Note: Don't name the `static` directory anything else. The name is required and <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> We expose a built-in component for appending elements to the `<head>` of the page. <ide> <ide> _Note: `<title>` and `<meta>` elements need to be contained as **direct** childr <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> When you need state, lifecycle hooks or **initial data population** you can export a `React.Component` (instead of a stateless function, like shown above): <ide> <ide> Next.js does not ship a routes manifest with every possible route in the applica <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> Client-side transitions between routes can be enabled via a `<Link>` component. <ide> <ide> To inject the `pathname`, `query` or `asPath` in your component, you can use [wi <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> The component `<Link>` can also receive a URL object and it will automatically format it to create the URL string. <ide> <ide> The default behaviour of `<Link>` is to scroll to the top of the page. When ther <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> You can also do client-side page transitions using the `next/router` <ide> <ide> Router.events.on('routeChangeError', (err, url) => { <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> Shallow routing allows you to change the URL without running `getInitialProps`. You'll receive the updated `pathname` and the `query` via the `router` prop (injected using [`withRouter`](#using-a-higher-order-component)), without losing state. <ide> <ide> componentDidUpdate(prevProps) { <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> If you want to access the `router` object inside any component in your app, you can use the `withRouter` Higher-Order Component. Here's how to use it: <ide> <ide> The above `router` object comes with an API similar to [`next/router`](#imperati <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> Next.js has an API which allows you to prefetch pages. <ide> <ide> export default withRouter(MyLink) <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> Typically you start your next server with `next start`. It's possible, however, to start a server 100% programmatically in order to customize routes, use route patterns, etc. <ide> <ide> app.prepare().then(() => { <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> Next.js supports TC39 [dynamic import proposal](https://github.com/tc39/proposal-dynamic-import) for JavaScript. <ide> With that, you could import JavaScript modules (inc. React Components) dynamically and work with them. <ide> export default DynamicBundle <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> Next.js uses the `App` component to initialize pages. You can override it and control the page initialization. Which allows you to do amazing things like: <ide> <ide> export default MyApp <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> - Is rendered on the server side <ide> - Is used to change the initial server side rendered document markup <ide> NODE_OPTIONS="--inspect" next <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> Some commonly asked for features are available as modules: <ide> <ide> module.exports = { <ide> // Note: we provide webpack above so you should not `require` it <ide> // Perform customizations to webpack config <ide> // Important: return the modified config <del> <add> <ide> // Example using webpack option <ide> config.plugins.push( <ide> new webpack.IgnorePlugin(/\/__tests__\//), <ide> module.exports = { <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> In order to extend our usage of `babel`, you can simply define a `.babelrc` file at the root of your app. This file is optional. <ide> <ide> The [polyfills](https://github.com/zeit/next.js/tree/canary/examples/with-polyfi <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> `next export` is a way to run your Next.js app as a standalone static app without the need for a Node.js server. <ide> The exported app supports almost every feature of Next.js, including dynamic urls, prefetching, preloading and dynamic imports. <ide> The `req` and `res` fields of the `context` object passed to `getInitialProps` a <ide> </ul> <ide> </details> <ide> <del><p></p> <ide> <ide> A zone is a single deployment of a Next.js app. Just like that, you can have multiple zones. Then you can merge them as a single app. <ide> <ide> We’re ecstatic about both the developer experience and end-user performance, s <ide> <ide> </details> <ide> <del><p></p> <ide> <ide> <details> <ide> <summary>How big is it?</summary> <ide> A small Next main bundle is around 65kb gzipped. <ide> <ide> </details> <ide> <del><p></p> <ide> <ide> <details> <ide> <summary>Is this like `create-react-app`?</summary> <ide> If you want to create re-usable React components that you can embed in your Next <ide> <ide> </details> <ide> <del><p></p> <ide> <ide> <details> <ide> <summary>How do I use CSS-in-JS solutions?</summary> <ide> Next.js bundles [styled-jsx](https://github.com/zeit/styled-jsx) supporting scop <ide> <ide> </details> <ide> <del><p></p> <ide> <ide> <details> <ide> <summary>What syntactic features are transpiled? How do I change them?</summary> <ide> See the documentation about [customizing the babel config](#customizing-babel-co <ide> <ide> </details> <ide> <del><p></p> <ide> <ide> <details> <ide> <summary>Why a new Router?</summary> <ide> As a result, we were able to introduce a very simple approach to routing that co <ide> - Every top level component receives a `url` object to inspect the url or perform modifications to the history <ide> - A `<Link />` component is used to wrap elements like anchors (`<a/>`) to perform client-side transitions <ide> <del>We tested the flexibility of the routing with some interesting scenarios. For an example, check out [nextgram](https://github.com/zeit/nextgram). <del> <ide> </details> <ide> <del><p></p> <ide> <ide> <details> <ide> <summary>How do I define a custom fancy route?</summary> <ide> On the client side, we have a parameter call `as` on `<Link>` that _decorates_ t <ide> <ide> </details> <ide> <del><p></p> <ide> <ide> <details> <ide> <summary>How do I fetch data?</summary> <ide> It’s up to you. `getInitialProps` is an `async` function (or a regular functio <ide> <ide> </details> <ide> <del><p></p> <ide> <ide> <details> <ide> <summary>Can I use it with GraphQL?</summary> <ide> Yes! Here's an example with [Apollo](/examples/with-apollo). <ide> <ide> </details> <ide> <del><p></p> <ide> <ide> <details> <ide> <summary>Can I use it with Redux and thunk?</summary> <ide> Yes! Here's an [example](/examples/with-redux-thunk) <ide> <ide> </details> <ide> <del><p></p> <ide> <ide> <details> <ide> <summary>Can I use it with Redux?</summary> <ide> Yes! Here's an [example](/examples/with-redux) <ide> <ide> </details> <ide> <del><p></p> <ide> <ide> <details> <ide> <summary>Can I use Next with my favorite Javascript library or toolkit?</summary> <ide> Since our first release we've had **many** example contributions, you can check <ide> <ide> </details> <ide> <del><p></p> <ide> <ide> <details> <ide> <summary>What is this inspired by?</summary> <ide> As we were researching options for server-rendering React that didn’t involve <ide> <ide> </details> <ide> <del><p></p> <ide> <ide> ## Contributing <ide>
1
Text
Text
fix typo in n-api.md
dcecfb75080dc98176119a81f0afca5805649e75
<ide><path>doc/api/n-api.md <ide> held live for the lifespan of the native method call. <ide> <ide> In many cases, however, it is necessary that the handles remain valid for <ide> either a shorter or longer lifespan than that of the native method. <del>The sections which follow describe the N-API functions than can be used <add>The sections which follow describe the N-API functions that can be used <ide> to change the handle lifespan from the default. <ide> <ide> ### Making handle lifespan shorter than that of the native method
1
Javascript
Javascript
update default values
a7c3713d7532dbf305f9923185e457101f6a7cec
<ide><path>examples/jsm/nodes/materials/nodes/StandardNode.js <ide> function StandardNode() { <ide> <ide> Node.call( this ); <ide> <del> this.color = new ColorNode( 0xEEEEEE ); <del> this.roughness = new FloatNode( 0.5 ); <del> this.metalness = new FloatNode( 0.5 ); <del> <del> this.energyPreservation = true; <add> this.color = new ColorNode( 0xFFFFFF ); <add> this.roughness = new FloatNode( 1 ); <add> this.metalness = new FloatNode( 0 ); <ide> <ide> } <ide>
1
Python
Python
fix loss scaling
6da769b18d25238219fbe299bd0fadbca55b59d5
<ide><path>official/recommendation/ncf_keras_main.py <ide> def _get_keras_model(params): <ide> from_logits=True, <ide> reduction="sum") <ide> <del> loss_scale_factor = (batch_size) #* <del> #tf.distribute.get_strategy().num_replicas_in_sync) <ide> keras_model.add_loss(loss_obj( <ide> y_true=label_input, <ide> y_pred=softmax_logits, <del> sample_weight=valid_pt_mask_input) * 1.0 / loss_scale_factor) <add> sample_weight=valid_pt_mask_input) * 1.0 / batch_size) <ide> <ide> keras_model.summary() <ide> return keras_model
1
Ruby
Ruby
add anlytics to cask installs
6701c207e0d30b16eb6cba24f9da5cb4edf91395
<ide><path>Library/Homebrew/cask/lib/hbc/installer.rb <ide> def install <ide> install_artifacts <ide> enable_accessibility_access <ide> <add> Utils::Analytics.report_event("cask_install", @cask.token) <add> <ide> puts summary <ide> end <ide>
1
Java
Java
download files through rn packager connection
373eb61f1f411458d4c1c24bb08033bc6d16a316
<ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DevServerHelper.java <ide> import com.facebook.react.common.network.OkHttpCallUtil; <ide> import com.facebook.react.devsupport.interfaces.PackagerStatusCallback; <ide> import com.facebook.react.modules.systeminfo.AndroidInfoHelpers; <add>import com.facebook.react.packagerconnection.FileIoHandler; <ide> import com.facebook.react.packagerconnection.JSPackagerClient; <ide> <ide> import org.json.JSONException; <ide> public void onRequest(@Nullable Object params, JSPackagerClient.Responder respon <ide> commandListener.onPokeSamplingProfilerCommand(responder); <ide> } <ide> }); <add> handlers.putAll(new FileIoHandler().handlers()); <ide> <ide> mPackagerClient = new JSPackagerClient(getPackagerConnectionURL(), handlers); <ide> mPackagerClient.init(); <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerImpl.java <ide> public void onOptionSelected() { <ide> mDevSettings.setFpsDebugEnabled(!mDevSettings.isFpsDebugEnabled()); <ide> } <ide> }); <del> options.put( <del> mApplicationContext.getString(R.string.catalyst_heap_capture), <del> new DevOptionHandler() { <del> @Override <del> public void onOptionSelected() { <del> handleCaptureHeap(null); <del> } <del> }); <ide> options.put( <ide> mApplicationContext.getString(R.string.catalyst_poke_sampling_profiler), <ide> new DevOptionHandler() { <ide> public String getDownloadedJSBundleFile() { <ide> return mJSBundleTempFile.getAbsolutePath(); <ide> } <ide> <del> @Override <del> public String getHeapCaptureUploadUrl() { <del> return mDevServerHelper.getHeapCaptureUploadUrl(); <del> } <del> <ide> /** <ide> * @return {@code true} if {@link com.facebook.react.ReactInstanceManager} should use downloaded JS bundle file <ide> * instead of using JS file from assets. This may happen when app has not been updated since <ide> public void run() { <ide> } <ide> <ide> @Override <del> public void onCaptureHeapCommand(@Nullable final JSPackagerClient.Responder responder) { <add> public void onCaptureHeapCommand(final JSPackagerClient.Responder responder) { <ide> UiThreadUtil.runOnUiThread(new Runnable() { <ide> @Override <ide> public void run() { <ide> public void run() { <ide> }); <ide> } <ide> <del> private void handleCaptureHeap(@Nullable final JSPackagerClient.Responder responder) { <add> private void handleCaptureHeap(final JSPackagerClient.Responder responder) { <ide> if (mCurrentContext == null) { <ide> return; <ide> } <ide> JSCHeapCapture heapCapture = mCurrentContext.getNativeModule(JSCHeapCapture.class); <ide> heapCapture.captureHeap( <ide> mApplicationContext.getCacheDir().getPath(), <del> JSCHeapUpload.captureCallback(mDevServerHelper.getHeapCaptureUploadUrl(), responder)); <add> new JSCHeapCapture.CaptureCallback() { <add> @Override <add> public void onSuccess(File capture) { <add> responder.respond(capture.toString()); <add> } <add> <add> @Override <add> public void onFailure(JSCHeapCapture.CaptureException error) { <add> responder.error(error.toString()); <add> } <add> }); <ide> } <ide> <ide> private void handlePokeSamplingProfiler(@Nullable final JSPackagerClient.Responder responder) { <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DisabledDevSupportManager.java <ide> public String getDownloadedJSBundleFile() { <ide> return null; <ide> } <ide> <del> @Override <del> public String getHeapCaptureUploadUrl() { <del> return null; <del> } <del> <ide> @Override <ide> public boolean hasUpToDateJSBundleInCache() { <ide> return false; <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/JSCHeapUpload.java <del>/** <del> * Copyright (c) 2016-present, Facebook, Inc. <del> * All rights reserved. <del> * <del> * This source code is licensed under the BSD-style license found in the <del> * LICENSE file in the root directory of this source tree. An additional grant <del> * of patent rights can be found in the PATENTS file in the same directory. <del> */ <del> <del>package com.facebook.react.devsupport; <del> <del>import javax.annotation.Nullable; <del> <del>import android.util.Log; <del>import java.io.File; <del>import java.io.IOException; <del>import java.util.concurrent.TimeUnit; <del>import com.facebook.react.packagerconnection.JSPackagerClient; <del> <del>import okhttp3.Call; <del>import okhttp3.Callback; <del>import okhttp3.MediaType; <del>import okhttp3.OkHttpClient; <del>import okhttp3.Request; <del>import okhttp3.RequestBody; <del>import okhttp3.Response; <del> <del>/** <del> * Created by cwdick on 7/22/16. <del> */ <del>public class JSCHeapUpload { <del> public static JSCHeapCapture.CaptureCallback captureCallback( <del> final String uploadUrl, <del> @Nullable final JSPackagerClient.Responder responder) { <del> return new JSCHeapCapture.CaptureCallback() { <del> @Override <del> public void onSuccess(File capture) { <del> OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder(); <del> httpClientBuilder.connectTimeout(1, TimeUnit.MINUTES) <del> .writeTimeout(5, TimeUnit.MINUTES) <del> .readTimeout(5, TimeUnit.MINUTES); <del> OkHttpClient httpClient = httpClientBuilder.build(); <del> RequestBody body = RequestBody.create(MediaType.parse("application/json"), capture); <del> Request request = new Request.Builder() <del> .url(uploadUrl) <del> .method("POST", body) <del> .build(); <del> Call call = httpClient.newCall(request); <del> call.enqueue(new Callback() { <del> @Override <del> public void onFailure(Call call, IOException e) { <del> String message = "Upload of heap capture failed: " + e.toString(); <del> Log.e("JSCHeapCapture", message); <del> responder.error(message); <del> } <del> <del> @Override <del> public void onResponse(Call call, Response response) throws IOException { <del> if (!response.isSuccessful()) { <del> String message = "Upload of heap capture failed with code " + Integer.toString(response.code()) + ": " + response.body().string(); <del> Log.e("JSCHeapCapture", message); <del> responder.error(message); <del> } <del> responder.respond(response.body().string()); <del> } <del> }); <del> } <del> <del> @Override <del> public void onFailure(JSCHeapCapture.CaptureException e) { <del> String message = "Heap capture failed: " + e.toString(); <del> Log.e("JSCHeapCapture", message); <del> responder.error(message); <del> } <del> }; <del> } <del>} <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevSupportManager.java <ide> public interface DevSupportManager extends NativeModuleCallExceptionHandler { <ide> String getSourceUrl(); <ide> String getJSBundleURLForRemoteDebugging(); <ide> String getDownloadedJSBundleFile(); <del> String getHeapCaptureUploadUrl(); <ide> boolean hasUpToDateJSBundleInCache(); <ide> void reloadSettings(); <ide> void handleReloadJS(); <ide><path>ReactAndroid/src/main/java/com/facebook/react/packagerconnection/FileIoHandler.java <add>/** <add> * Copyright (c) 2016-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <add>package com.facebook.react.packagerconnection; <add> <add>import javax.annotation.Nullable; <add> <add>import java.io.FileInputStream; <add>import java.io.FileNotFoundException; <add>import java.io.IOException; <add>import java.util.HashMap; <add>import java.util.Iterator; <add>import java.util.Map; <add> <add>import android.os.Handler; <add>import android.os.Looper; <add>import android.util.Base64; <add> <add>import com.facebook.common.logging.FLog; <add> <add>import org.json.JSONObject; <add> <add>public class FileIoHandler implements Runnable { <add> private static final String TAG = JSPackagerClient.class.getSimpleName(); <add> private static final long FILE_TTL = 30 * 1000; <add> <add> private static class TtlFileInputStream { <add> private final FileInputStream mStream; <add> private long mTtl; <add> <add> public TtlFileInputStream(String path) throws FileNotFoundException { <add> mStream = new FileInputStream(path); <add> mTtl = System.currentTimeMillis() + FILE_TTL; <add> } <add> <add> private void extendTtl() { <add> mTtl = System.currentTimeMillis() + FILE_TTL; <add> } <add> <add> public boolean expiredTtl() { <add> return System.currentTimeMillis() >= mTtl; <add> } <add> <add> public String read(int size) throws IOException { <add> extendTtl(); <add> byte[] buffer = new byte[size]; <add> int bytesRead = mStream.read(buffer); <add> return Base64.encodeToString(buffer, 0, bytesRead, Base64.DEFAULT); <add> } <add> <add> public void close() throws IOException { <add> mStream.close(); <add> } <add> }; <add> <add> private int mNextHandle; <add> private final Handler mHandler; <add> private final Map<Integer, TtlFileInputStream> mOpenFiles; <add> private final Map<String, JSPackagerClient.RequestHandler> mRequestHandlers; <add> <add> public FileIoHandler() { <add> mNextHandle = 1; <add> mHandler = new Handler(Looper.getMainLooper()); <add> mOpenFiles = new HashMap<>(); <add> mRequestHandlers = new HashMap<>(); <add> mRequestHandlers.put("fopen", new JSPackagerClient.RequestOnlyHandler() { <add> @Override <add> public void onRequest( <add> @Nullable Object params, JSPackagerClient.Responder responder) { <add> synchronized (mOpenFiles) { <add> try { <add> JSONObject paramsObj = (JSONObject)params; <add> if (paramsObj == null) { <add> throw new Exception("params must be an object { mode: string, filename: string }"); <add> } <add> String mode = paramsObj.optString("mode"); <add> if (mode == null) { <add> throw new Exception("missing params.mode"); <add> } <add> String filename = paramsObj.optString("filename"); <add> if (filename == null) { <add> throw new Exception("missing params.filename"); <add> } <add> if (!mode.equals("r")) { <add> throw new IllegalArgumentException("unsupported mode: " + mode); <add> } <add> <add> responder.respond(addOpenFile(filename)); <add> } catch (Exception e) { <add> responder.error(e.toString()); <add> } <add> } <add> } <add> }); <add> mRequestHandlers.put("fclose", new JSPackagerClient.RequestOnlyHandler() { <add> @Override <add> public void onRequest( <add> @Nullable Object params, JSPackagerClient.Responder responder) { <add> synchronized (mOpenFiles) { <add> try { <add> if (!(params instanceof Number)) { <add> throw new Exception("params must be a file handle"); <add> } <add> TtlFileInputStream stream = mOpenFiles.get((int)params); <add> if (stream == null) { <add> throw new Exception("invalid file handle, it might have timed out"); <add> } <add> <add> mOpenFiles.remove((int)params); <add> stream.close(); <add> responder.respond(""); <add> } catch (Exception e) { <add> responder.error(e.toString()); <add> } <add> } <add> } <add> }); <add> mRequestHandlers.put("fread", new JSPackagerClient.RequestOnlyHandler() { <add> @Override <add> public void onRequest( <add> @Nullable Object params, JSPackagerClient.Responder responder) { <add> synchronized (mOpenFiles) { <add> try { <add> JSONObject paramsObj = (JSONObject)params; <add> if (paramsObj == null) { <add> throw new Exception("params must be an object { file: handle, size: number }"); <add> } <add> int file = paramsObj.optInt("file"); <add> if (file == 0) { <add> throw new Exception("invalid or missing file handle"); <add> } <add> int size = paramsObj.optInt("size"); <add> if (size == 0) { <add> throw new Exception("invalid or missing read size"); <add> } <add> TtlFileInputStream stream = mOpenFiles.get(file); <add> if (stream == null) { <add> throw new Exception("invalid file handle, it might have timed out"); <add> } <add> <add> responder.respond(stream.read(size)); <add> } catch (Exception e) { <add> responder.error(e.toString()); <add> } <add> } <add> } <add> }); <add> } <add> <add> public Map<String, JSPackagerClient.RequestHandler> handlers() { <add> return mRequestHandlers; <add> } <add> <add> private int addOpenFile(String filename) throws FileNotFoundException { <add> int handle = mNextHandle++; <add> mOpenFiles.put(handle, new TtlFileInputStream(filename)); <add> if (mOpenFiles.size() == 1) { <add> mHandler.postDelayed(FileIoHandler.this, FILE_TTL); <add> } <add> return handle; <add> } <add> <add> @Override <add> public void run() { <add> // clean up files that are past their expiry date <add> synchronized (mOpenFiles) { <add> Iterator<TtlFileInputStream> i = mOpenFiles.values().iterator(); <add> while (i.hasNext()) { <add> TtlFileInputStream stream = i.next(); <add> if (stream.expiredTtl()) { <add> i.remove(); <add> try { <add> stream.close(); <add> } catch (IOException e) { <add> FLog.e( <add> TAG, <add> "closing expired file failed: " + e.toString()); <add> } <add> } <add> } <add> if (!mOpenFiles.isEmpty()) { <add> mHandler.postDelayed(this, FILE_TTL); <add> } <add> } <add> } <add>} <ide><path>ReactAndroid/src/main/java/com/facebook/react/packagerconnection/JSPackagerClient.java <ide> <ide> import javax.annotation.Nullable; <ide> <add>import java.util.HashMap; <ide> import java.util.Map; <ide> <ide> import com.facebook.common.logging.FLog;
7
Python
Python
use a pipe for separating japanese inflections
227f98081b86b315907ec672f02b0a2334dd10e8
<ide><path>spacy/lang/ja/__init__.py <ide> def _get_dtokens(self, sudachipy_tokens, need_sub_tokens: bool = True): <ide> DetailedToken( <ide> token.surface(), # orth <ide> "-".join([xx for xx in token.part_of_speech()[:4] if xx != "*"]), # tag <del> "-".join([xx for xx in token.part_of_speech()[4:] if xx != "*"]), # inf <add> "|".join([xx for xx in token.part_of_speech()[4:] if xx != "*"]), # inf <ide> token.dictionary_form(), # lemma <ide> token.normalized_form(), <ide> token.reading_form(),
1
Javascript
Javascript
add missing word to code comment for clarity
fb28e9048292f3c74d056370852e3da49ea5ede2
<ide><path>packages/scheduler/src/Scheduler.js <ide> function unstable_scheduleCallback( <ide> }; <ide> <ide> // Insert the new callback into the list, ordered first by expiration, then <del> // by insertion. So the new callback is inserted any other callback with <del> // equal expiration. <add> // by insertion. So the new callback is inserted after any other callback <add> // with equal expiration. <ide> if (firstCallbackNode === null) { <ide> // This is the first callback in the list. <ide> firstCallbackNode = newNode.next = newNode.previous = newNode;
1
Ruby
Ruby
use constant everywhere for "create a pat" message
9394fe2b5211e5a5f5a3d2bb5b991a3c7ccc7bc4
<ide><path>Library/Homebrew/utils/github.rb <ide> def initialize(reset, github_message) <ide> @github_message = github_message <ide> super <<~EOS <ide> GitHub API Error: #{github_message} <del> Try again in #{pretty_ratelimit_reset(reset)}, or create a personal access token: <del> #{ALL_SCOPES_URL} <del> #{Utils::Shell.set_variable_in_profile("HOMEBREW_GITHUB_API_TOKEN", "your_token_here")} <add> Try again in #{pretty_ratelimit_reset(reset)}, or: <add> #{CREATE_GITHUB_PAT_MESSAGE} <ide> EOS <ide> end <ide> <ide> def initialize(github_message) <ide> The GitHub credentials in the macOS keychain may be invalid. <ide> Clear them with: <ide> printf "protocol=https\\nhost=github.com\\n" | git credential-osxkeychain erase <del> Or create a personal access token: <del> #{ALL_SCOPES_URL} <del> #{Utils::Shell.set_variable_in_profile("HOMEBREW_GITHUB_API_TOKEN", "your_token_here")} <add> #{CREATE_GITHUB_PAT_MESSAGE} <ide> EOS <ide> end <ide> super message.freeze <ide> def api_credentials_error_message(response_headers, needed_scopes) <ide> Your #{what} credentials do not have sufficient scope! <ide> Scopes required: #{needed_scopes} <ide> Scopes present: #{credentials_scopes} <del> Create a personal access token: <del> #{ALL_SCOPES_URL} <del> #{Utils::Shell.set_variable_in_profile("HOMEBREW_GITHUB_API_TOKEN", "your_token_here")} <add> #{CREATE_GITHUB_PAT_MESSAGE} <ide> EOS <ide> end <ide>
1
Ruby
Ruby
fix input handling
ac6295491c771c0da2856524b8e7bb39f1f7da72
<ide><path>Library/Homebrew/cmd/cleanup.rb <ide> def cleanup_args <ide> def cleanup <ide> args = cleanup_args.parse <ide> <add> if args.prune.present? && !Integer(args.prune, exception: false) && args.prune != "all" <add> raise UsageError, "--prune= expects an integer or 'all'." <add> end <add> <ide> cleanup = Cleanup.new(*args.named, dry_run: args.dry_run?, scrub: args.s?, days: args.prune&.to_i) <ide> if args.prune_prefix? <ide> cleanup.prune_prefix_symlinks_and_directories
1
Text
Text
update upgrade guides
f78c004fdca0e99afe7b386a77a037576b5b4fba
<ide><path>guides/source/upgrading_ruby_on_rails.md <ide> Rails.application.configure do <ide> end <ide> ``` <ide> <del>### New config options <add>### New Framework Defaults <ide> <del>## Active Record `belongs_to` Required by Default Option <add>#### Active Record `belongs_to` Required by Default Option <ide> <ide> `belongs_to` will now trigger a validation error by default if the association is not present. <ide> <ide> want to add this feature it will need to be turned on in an initializer. <ide> <ide> config.active_record.belongs_to_required_by_default = true <ide> <del>## Allow configuration of Action Mailer queue name <add>#### Per-form CSRF tokens <add> <add>Rails 5 now supports per-form CSRF tokens to mitigate against code-injection attacks with forms <add>created by JavaScript. With this option turned on forms in your application will each have their <add>own CSRF token that is specified to the action and method for that form. <add> <add> config.action_controller.per_form_csrf_tokens = true <add> <add>#### Forgery protection with origin check <add> <add>You can how configure your application to check if the HTTP `Origin` header should be checked <add>against the site's origin as an additional CSRF defense. Set the following in your config to <add>true: <add> <add> config.action_controller.forgery_protection_origin_check = true <add> <add>#### Allow configuration of Action Mailer queue name <ide> <ide> The default mailer queue name is `mailers`. This configuration option allows you to globally change <ide> the queue name. Set the following in your config. <ide> <del> config.action_mailer.deliver_later_queue_name <add> config.action_mailer.deliver_later_queue_name = :new_queue_name <ide> <del>## Support fragment caching in Action Mailer views <add>#### Support fragment caching in Action Mailer views <ide> <ide> Set `config.action_mailer.perform_caching` in your config to determine whether your Action Mailer views <ide> should support caching. <ide> <del>## Configure the output of `db:structure:dump` <add> config.action_mailer.perform_caching = true <add> <add>#### Configure the output of `db:structure:dump` <ide> <ide> If you're using `schema_search_path` or other PostgreSQL extentions, you can control how the schema is <ide> dumped. Set to `:all` to generate all dumps, or `:schema_search_path` to generate from schema search path. <ide> <ide> config.active_record.dump_schemas = :all <ide> <add>#### Configure SSL options to enable HSTS with subdomains <add> <add>Set the following in your config to enable HSTS when using subdomains. <add> <add> config.ssl_options = { hsts: { subdomains: true } } <add> <add>#### Preserve timezone of the receiver <add> <add>When using Ruby 2.4 you can preserve the timezone of the receiver when calling `to_time`. <add> <add> ActiveSupport.to_time_preserves_timezone = <%= options[:update] ? false : true %> <add> <ide> Upgrading from Rails 4.1 to Rails 4.2 <ide> ------------------------------------- <ide>
1
Python
Python
remove workaround for gh-9968 from test_roundtrip
79410aab355573b9765434126a0e74162e995776
<ide><path>numpy/core/tests/test_scalar_methods.py <ide> def test_roundtrip(self, ftype, frac_vals, exp_vals): <ide> n, d = f.as_integer_ratio() <ide> <ide> try: <del> # workaround for gh-9968 <del> nf = np.longdouble(str(n)) <del> df = np.longdouble(str(d)) <add> nf = np.longdouble(n) <add> df = np.longdouble(d) <ide> except (OverflowError, RuntimeWarning): <ide> # the values may not fit in any float type <ide> pytest.skip("longdouble too small on this platform")
1
Javascript
Javascript
remove poweredbystripe asset
139f8fcb1b06a5903ee43494054295740fb23286
<ide><path>client/src/components/Donation/components/poweredByStripe.js <del>/* eslint-disable max-len */ <del>import React from 'react'; <del> <del>function PoweredByStripe() { <del> return ( <del> <svg height='26px' width='119px' xmlns='http://www.w3.org/2000/svg'> <del> <path <del> d='M113.000,26.000 L6.000,26.000 C2.686,26.000 -0.000,23.314 -0.000,20.000 L-0.000,6.000 C-0.000,2.686 2.686,-0.000 6.000,-0.000 L113.000,-0.000 C116.314,-0.000 119.000,2.686 119.000,6.000 L119.000,20.000 C119.000,23.314 116.314,26.000 113.000,26.000 ZM118.000,6.000 C118.000,3.239 115.761,1.000 113.000,1.000 L6.000,1.000 C3.239,1.000 1.000,3.239 1.000,6.000 L1.000,20.000 C1.000,22.761 3.239,25.000 6.000,25.000 L113.000,25.000 C115.761,25.000 118.000,22.761 118.000,20.000 L118.000,6.000 Z' <del> fill='#858591' <del> fillRule='evenodd' <del> opacity='0.349' <del> /> <del> <path <del> d='M60.700,18.437 L59.395,18.437 L60.405,15.943 L58.395,10.871 L59.774,10.871 L61.037,14.323 L62.310,10.871 L63.689,10.871 L60.700,18.437 ZM55.690,16.259 C55.238,16.259 54.774,16.091 54.354,15.764 L54.354,16.133 L53.007,16.133 L53.007,8.566 L54.354,8.566 L54.354,11.229 C54.774,10.913 55.238,10.745 55.690,10.745 C57.100,10.745 58.068,11.881 58.068,13.502 C58.068,15.122 57.100,16.259 55.690,16.259 ZM55.406,11.902 C55.038,11.902 54.669,12.060 54.354,12.376 L54.354,14.628 C54.669,14.943 55.038,15.101 55.406,15.101 C56.164,15.101 56.690,14.449 56.690,13.502 C56.690,12.555 56.164,11.902 55.406,11.902 ZM47.554,15.764 C47.144,16.091 46.681,16.259 46.218,16.259 C44.818,16.259 43.840,15.122 43.840,13.502 C43.840,11.881 44.818,10.745 46.218,10.745 C46.681,10.745 47.144,10.913 47.554,11.229 L47.554,8.566 L48.912,8.566 L48.912,16.133 L47.554,16.133 L47.554,15.764 ZM47.554,12.376 C47.249,12.060 46.881,11.902 46.513,11.902 C45.744,11.902 45.218,12.555 45.218,13.502 C45.218,14.449 45.744,15.101 46.513,15.101 C46.881,15.101 47.249,14.943 47.554,14.628 L47.554,12.376 ZM39.535,13.870 C39.619,14.670 40.251,15.217 41.134,15.217 C41.619,15.217 42.155,15.038 42.702,14.722 L42.702,15.849 C42.103,16.122 41.503,16.259 40.913,16.259 C39.324,16.259 38.209,15.101 38.209,13.460 C38.209,11.871 39.303,10.745 40.808,10.745 C42.187,10.745 43.123,11.829 43.123,13.375 C43.123,13.523 43.123,13.691 43.102,13.870 L39.535,13.870 ZM40.756,11.786 C40.103,11.786 39.598,12.271 39.535,12.997 L41.829,12.997 C41.787,12.281 41.356,11.786 40.756,11.786 ZM35.988,12.618 L35.988,16.133 L34.641,16.133 L34.641,10.871 L35.988,10.871 L35.988,11.397 C36.367,10.976 36.830,10.745 37.282,10.745 C37.430,10.745 37.577,10.755 37.724,10.797 L37.724,11.997 C37.577,11.955 37.409,11.934 37.251,11.934 C36.809,11.934 36.335,12.176 35.988,12.618 ZM29.979,13.870 C30.063,14.670 30.694,15.217 31.578,15.217 C32.062,15.217 32.599,15.038 33.146,14.722 L33.146,15.849 C32.546,16.122 31.946,16.259 31.357,16.259 C29.768,16.259 28.653,15.101 28.653,13.460 C28.653,11.871 29.747,10.745 31.252,10.745 C32.630,10.745 33.567,11.829 33.567,13.375 C33.567,13.523 33.567,13.691 33.546,13.870 L29.979,13.870 ZM31.199,11.786 C30.547,11.786 30.042,12.271 29.979,12.997 L32.273,12.997 C32.231,12.281 31.799,11.786 31.199,11.786 ZM25.274,16.133 L24.200,12.555 L23.137,16.133 L21.927,16.133 L20.117,10.871 L21.464,10.871 L22.527,14.449 L23.590,10.871 L24.810,10.871 L25.873,14.449 L26.936,10.871 L28.283,10.871 L26.484,16.133 L25.274,16.133 ZM17.043,16.259 C15.454,16.259 14.328,15.112 14.328,13.502 C14.328,11.881 15.454,10.745 17.043,10.745 C18.632,10.745 19.748,11.881 19.748,13.502 C19.748,15.112 18.632,16.259 17.043,16.259 ZM17.043,11.871 C16.254,11.871 15.707,12.534 15.707,13.502 C15.707,14.470 16.254,15.133 17.043,15.133 C17.822,15.133 18.369,14.470 18.369,13.502 C18.369,12.534 17.822,11.871 17.043,11.871 ZM11.128,13.533 L9.918,13.533 L9.918,16.133 L8.571,16.133 L8.571,8.892 L11.128,8.892 C12.602,8.892 13.654,9.850 13.654,11.218 C13.654,12.586 12.602,13.533 11.128,13.533 ZM10.939,9.987 L9.918,9.987 L9.918,12.439 L10.939,12.439 C11.718,12.439 12.265,11.944 12.265,11.218 C12.265,10.482 11.718,9.987 10.939,9.987 Z' <del> fill='#858591' <del> fillRule='evenodd' <del> opacity='0.502' <del> /> <del> <path <del> d='M111.116,14.051 L105.557,14.051 C105.684,15.382 106.659,15.774 107.766,15.774 C108.893,15.774 109.781,15.536 110.555,15.146 L110.555,17.433 C109.784,17.861 108.765,18.169 107.408,18.169 C104.642,18.169 102.704,16.437 102.704,13.013 C102.704,10.121 104.348,7.825 107.049,7.825 C109.746,7.825 111.154,10.120 111.154,13.028 C111.154,13.303 111.129,13.898 111.116,14.051 ZM107.031,10.140 C106.321,10.140 105.532,10.676 105.532,11.955 L108.468,11.955 C108.468,10.677 107.728,10.140 107.031,10.140 ZM98.108,18.169 C97.114,18.169 96.507,17.750 96.099,17.451 L96.093,20.664 L93.254,21.268 L93.253,8.014 L95.753,8.014 L95.901,8.715 C96.293,8.349 97.012,7.825 98.125,7.825 C100.119,7.825 101.997,9.621 101.997,12.927 C101.997,16.535 100.139,18.169 98.108,18.169 ZM97.446,10.340 C96.795,10.340 96.386,10.578 96.090,10.903 L96.107,15.122 C96.383,15.421 96.780,15.661 97.446,15.661 C98.496,15.661 99.200,14.518 99.200,12.989 C99.200,11.504 98.485,10.340 97.446,10.340 ZM89.149,8.014 L91.999,8.014 L91.999,17.966 L89.149,17.966 L89.149,8.014 ZM89.149,4.836 L91.999,4.230 L91.999,6.543 L89.149,7.149 L89.149,4.836 ZM86.110,11.219 L86.110,17.966 L83.272,17.966 L83.272,8.014 L85.727,8.014 L85.905,8.853 C86.570,7.631 87.897,7.879 88.275,8.015 L88.275,10.625 C87.914,10.508 86.781,10.338 86.110,11.219 ZM80.024,14.475 C80.024,16.148 81.816,15.627 82.179,15.482 L82.179,17.793 C81.801,18.001 81.115,18.169 80.187,18.169 C78.502,18.169 77.237,16.928 77.237,15.247 L77.250,6.138 L80.022,5.548 L80.024,8.014 L82.180,8.014 L82.180,10.435 L80.024,10.435 L80.024,14.475 ZM76.485,14.959 C76.485,17.003 74.858,18.169 72.497,18.169 C71.518,18.169 70.448,17.979 69.392,17.525 L69.392,14.814 C70.345,15.332 71.559,15.721 72.500,15.721 C73.133,15.721 73.589,15.551 73.589,15.026 C73.589,13.671 69.273,14.181 69.273,11.038 C69.273,9.028 70.808,7.825 73.111,7.825 C74.052,7.825 74.992,7.969 75.933,8.344 L75.933,11.019 C75.069,10.552 73.972,10.288 73.109,10.288 C72.514,10.288 72.144,10.460 72.144,10.903 C72.144,12.181 76.485,11.573 76.485,14.959 Z' <del> fill='#858591' <del> fillRule='evenodd' <del> opacity='0.502' <del> /> <del> </svg> <del> ); <del>} <del> <del>PoweredByStripe.displayName = 'PoweredByStripe'; <del> <del>export default PoweredByStripe;
1
Java
Java
add fast-path in beanutils#instantiateclass
edcc559b4aabfb71a83a6cb076d5f2f4154b7277
<ide><path>spring-beans/src/main/java/org/springframework/beans/BeanUtils.java <ide> import org.springframework.util.ClassUtils; <ide> import org.springframework.util.CollectionUtils; <ide> import org.springframework.util.ConcurrentReferenceHashMap; <add>import org.springframework.util.ObjectUtils; <ide> import org.springframework.util.ReflectionUtils; <ide> import org.springframework.util.StringUtils; <ide> <ide> public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws <ide> try { <ide> ReflectionUtils.makeAccessible(ctor); <ide> if (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(ctor.getDeclaringClass())) { <add> if (ObjectUtils.isEmpty(args)) { <add> return KotlinDelegate.instantiateClass(ctor); <add> } <ide> return KotlinDelegate.instantiateClass(ctor, args); <ide> } <ide> else { <add> int parameterCount = ctor.getParameterCount(); <add> Assert.isTrue(args.length <= parameterCount, "Can't specify more arguments than constructor parameters"); <add> if (parameterCount == 0) { <add> return ctor.newInstance(); <add> } <ide> Class<?>[] parameterTypes = ctor.getParameterTypes(); <del> Assert.isTrue(args.length <= parameterTypes.length, "Can't specify more arguments than constructor parameters"); <ide> Object[] argsWithDefaultValues = new Object[args.length]; <ide> for (int i = 0 ; i < args.length; i++) { <ide> if (args[i] == null) { <ide> public static <T> T instantiateClass(Constructor<T> ctor, Object... args) <ide> return kotlinConstructor.callBy(argParameters); <ide> } <ide> <add> /** <add> * Instantiate a Kotlin class using provided no-arg constructor. <add> * @param ctor the constructor of the Kotlin class to instantiate <add> */ <add> public static <T> T instantiateClass(Constructor<T> ctor) <add> throws IllegalAccessException, InvocationTargetException, InstantiationException { <add> <add> KFunction<T> kotlinConstructor = ReflectJvmMapping.getKotlinFunction(ctor); <add> if (kotlinConstructor == null) { <add> return ctor.newInstance(); <add> } <add> List<KParameter> parameters = kotlinConstructor.getParameters(); <add> Assert.isTrue(parameters.isEmpty(), "Default no-args constructor must have no params"); <add> Map<KParameter, Object> argParameters = Collections.emptyMap(); <add> return kotlinConstructor.callBy(argParameters); <add> } <add> <add> <ide> } <ide> <ide> }
1
Text
Text
fix typo in `src/crypto/readme.md`
746169de0ec09671c01aeee3a92898cda9b9be6e
<ide><path>src/crypto/README.md <ide> The following provide generalized utility declarations that are used throughout <ide> the various other crypto files and other parts of Node.js: <ide> <ide> * `crypto_util.h` / `crypto_util.cc` (Core crypto definitions) <del>* `crypto_common.h` / `crypto_common.h` (Shared TLS utility functions) <del>* `crypto_bio.c` / `crypto_bio.c` (Custom OpenSSL i/o implementation) <add>* `crypto_common.h` / `crypto_common.cc` (Shared TLS utility functions) <add>* `crypto_bio.h` / `crypto_bio.cc` (Custom OpenSSL i/o implementation) <ide> * `crypto_groups.h` (modp group definitions) <ide> <ide> Of these, `crypto_util.h` and `crypto_util.cc` are the most important, as
1
Ruby
Ruby
handle no sdist for package
b08d1a28ad6c9c12b9f5bbc2cfa3a5df5df95d5c
<ide><path>Library/Homebrew/utils/pypi.rb <ide> def get_pypi_info(package, version) <ide> end <ide> <ide> sdist = json["urls"].find { |url| url["packagetype"] == "sdist" } <add> return json["info"]["name"] if sdist.nil? <add> <ide> [json["info"]["name"], sdist["url"], sdist["digests"]["sha256"]] <ide> end <ide>
1
Javascript
Javascript
remove duplicate test
57ff476c339b08e9a144af38661872ec12d9aead
<ide><path>test/parallel/test-http-agent-no-wait.js <del>'use strict'; <del> <del>const common = require('../common'); <del>const assert = require('assert'); <del>const http = require('http'); <del> <del>const server = http.createServer(function(req, res) { <del> res.writeHead(200); <del> res.end(); <del>}); <del> <del>server.listen(0, common.mustCall(() => { <del> const req = http.get({ port: server.address().port }, (res) => { <del> assert.strictEqual(res.statusCode, 200); <del> <del> res.resume(); <del> server.close(); <del> }); <del> <del> req.end(); <del>})); <del> <del>// This timer should never go off as the server will close the socket <del>setTimeout(common.mustNotCall(), 1000).unref(); <ide><path>test/parallel/test-http-client-close-with-default-agent.js <ide> server.listen(0, common.mustCall(() => { <ide> })); <ide> <ide> // This timer should never go off as the server will close the socket <del>setTimeout(common.mustNotCall(), common.platformTimeout(10000)).unref(); <add>setTimeout(common.mustNotCall(), common.platformTimeout(1000)).unref();
2
Javascript
Javascript
remove ambiguous code"
8c606851056a1bb38abdcf7ab15df8ae35ba0cf9
<ide><path>lib/internal/streams/end-of-stream.js <ide> function eos(stream, opts, callback) { <ide> }; <ide> } <ide> <del> const readable = opts.readable || <add> let readable = opts.readable || <ide> (opts.readable !== false && isReadable(stream)); <del> const writable = opts.writable || <add> let writable = opts.writable || <ide> (opts.writable !== false && isWritable(stream)); <ide> <ide> const onlegacyfinish = () => { <ide> if (!stream.writable) onfinish(); <ide> }; <ide> <ide> const onfinish = () => { <add> writable = false; <ide> writableFinished = true; <del> if (!readable || readableEnded) callback.call(stream); <add> if (!readable) callback.call(stream); <ide> }; <ide> <ide> const onend = () => { <add> readable = false; <ide> readableEnded = true; <del> if (!writable || writableFinished) callback.call(stream); <add> if (!writable) callback.call(stream); <ide> }; <ide> <ide> const onclose = () => {
1
Ruby
Ruby
move macro to class level
a929d78d7b4a1341c0ed538cdcce0b381f410a35
<ide><path>activerecord/lib/active_record/associations/builder/association.rb <ide> def initialize(name, scope, options, extension) <ide> end <ide> <ide> def build(model) <del> ActiveRecord::Reflection.create(macro, name, scope, options, model) <add> ActiveRecord::Reflection.create(self.class.macro, name, scope, options, model) <ide> end <ide> <del> def macro <add> def self.macro <ide> raise NotImplementedError <ide> end <ide> <ide><path>activerecord/lib/active_record/associations/builder/belongs_to.rb <ide> module ActiveRecord::Associations::Builder <ide> class BelongsTo < SingularAssociation #:nodoc: <del> def macro <add> def self.macro <ide> :belongs_to <ide> end <ide> <ide><path>activerecord/lib/active_record/associations/builder/has_many.rb <ide> module ActiveRecord::Associations::Builder <ide> class HasMany < CollectionAssociation #:nodoc: <del> def macro <add> def self.macro <ide> :has_many <ide> end <ide> <ide><path>activerecord/lib/active_record/associations/builder/has_one.rb <ide> module ActiveRecord::Associations::Builder <ide> class HasOne < SingularAssociation #:nodoc: <del> def macro <add> def self.macro <ide> :has_one <ide> end <ide>
4