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
Text
Text
add note about _document being only server side
e1a0f18a92a143db8e19ef663bccbae7d3b6a6cb
<ide><path>readme.md <ide> export default () => <HelloBundle title="Dynamic Bundle" /> <ide> Pages in `Next.js` skip the definition of the surrounding document's markup. For example, you never include `<html>`, `<body>`, etc. To override that default behavior, you must create a file at `./pages/_document.js`, where you can extend the `Document` class: <ide> <ide> ```jsx <add>// _document is only rendered on the server side and not on the client side <add>// Event handlers like onClick can't be added to this file <add> <ide> // ./pages/_document.js <ide> import Document, { Head, Main, NextScript } from 'next/document' <ide> import flush from 'styled-jsx/server'
1
Java
Java
add logs in mounting layer
0c17992485da541d1ef5657479c4fb1e52882280
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java <ide> import androidx.annotation.UiThread; <ide> import android.view.View; <ide> import com.facebook.common.logging.FLog; <add>import com.facebook.debug.holder.PrinterHolder; <add>import com.facebook.debug.tags.ReactDebugOverlayTags; <ide> import com.facebook.infer.annotation.ThreadConfined; <ide> import com.facebook.proguard.annotations.DoNotStrip; <ide> import com.facebook.react.bridge.LifecycleEventListener; <ide> @SuppressLint("MissingNativeLoadLibrary") <ide> public class FabricUIManager implements UIManager, LifecycleEventListener { <ide> <del> private static final String TAG = FabricUIManager.class.getSimpleName(); <add> public static final String TAG = FabricUIManager.class.getSimpleName(); <add> public static final boolean DEBUG = <add> PrinterHolder.getPrinter().shouldDisplayLogMessage(ReactDebugOverlayTags.FABRIC_UI_MANAGER); <ide> <ide> private static final Map<String, String> sComponentNames = new HashMap<>(); <ide> private static final int FRAME_TIME_MS = 16; <ide> public void removeRootView(int reactRootTag) { <ide> mMountingManager.removeRootView(reactRootTag); <ide> mReactContextForRootTag.remove(reactRootTag); <ide> } <del> <add> <ide> @Override <ide> public void initialize() { <ide> mEventDispatcher.registerEventEmitter(FABRIC, new FabricEventEmitter(this)); <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/BatchMountItem.java <ide> */ <ide> package com.facebook.react.fabric.mounting.mountitems; <ide> <add>import static com.facebook.react.fabric.FabricUIManager.DEBUG; <add>import static com.facebook.react.fabric.FabricUIManager.TAG; <add> <ide> import com.facebook.proguard.annotations.DoNotStrip; <ide> import com.facebook.react.fabric.mounting.MountingManager; <ide> import com.facebook.systrace.Systrace; <ide> <add>import com.facebook.common.logging.FLog; <add> <ide> /** <ide> * This class represents a batch of {@link MountItem}s <ide> * <ide> public void execute(MountingManager mountingManager) { <ide> <ide> for (int mountItemIndex = 0; mountItemIndex < mSize; mountItemIndex++) { <ide> MountItem mountItem = mMountItems[mountItemIndex]; <add> if (DEBUG) { <add> FLog.d(TAG, "Executing mountItem: " + mountItem); <add> } <ide> mountItem.execute(mountingManager); <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/PreAllocateViewMountItem.java <ide> */ <ide> package com.facebook.react.fabric.mounting.mountitems; <ide> <add>import static com.facebook.react.fabric.FabricUIManager.DEBUG; <add>import static com.facebook.react.fabric.FabricUIManager.TAG; <add> <add>import com.facebook.common.logging.FLog; <ide> import com.facebook.react.bridge.ReadableMap; <ide> import com.facebook.react.fabric.mounting.MountingManager; <ide> import com.facebook.react.uimanager.ThemedReactContext; <ide> public class PreAllocateViewMountItem implements MountItem { <ide> private final boolean mIsLayoutable; <ide> <ide> public PreAllocateViewMountItem( <del> ThemedReactContext context, int rootTag, int reactTag, String component, ReadableMap props, boolean isLayoutable) { <add> ThemedReactContext context, <add> int rootTag, <add> int reactTag, <add> String component, <add> ReadableMap props, <add> boolean isLayoutable) { <ide> mContext = context; <ide> mComponent = component; <ide> mRootTag = rootTag; <ide> public PreAllocateViewMountItem( <ide> <ide> @Override <ide> public void execute(MountingManager mountingManager) { <add> if (DEBUG) { <add> FLog.d(TAG, "Executing pre-allocation of: " + toString()); <add> } <ide> mountingManager.preallocateView(mContext, mComponent, mReactTag, mProps, mIsLayoutable); <ide> } <ide> <ide> @Override <ide> public String toString() { <del> return "[" + mRootTag + "] - Preallocate " + mComponent; <add> return "PreAllocateViewMountItem [" <add> + mReactTag <add> + "] - component: " <add> + mComponent <add> + " rootTag: " <add> + mRootTag <add> + " mIsLayoutable: " <add> + mIsLayoutable <add> + " props: " <add> + mProps; <ide> } <ide> }
3
Python
Python
fix benchmark suite importability on numpy<1.17
5af6880df87493d0b90cd3dbc9b3a1afe6052140
<ide><path>benchmarks/benchmarks/bench_random.py <ide> <ide> import numpy as np <ide> <del>from numpy.random import RandomState, Generator <add>from numpy.random import RandomState <add> <add>try: <add> from numpy.random import Generator <add>except ImportError: <add> pass <add> <ide> <ide> class Random(Benchmark): <ide> params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5',
1
Javascript
Javascript
give better error messages
3ac494195319efb9c923c0ee89b6e0f2617d53ef
<ide><path>lib/net.js <ide> function isPipeName(s) { <ide> return util.isString(s) && toNumber(s) === false; <ide> } <ide> <add>// format exceptions <add>function detailedException(err, syscall, address, port, additional) { <add> var details; <add> if (port && port > 0) { <add> details = address + ':' + port; <add> } else { <add> details = address; <add> } <add> <add> if (additional) { <add> details += ' - Local (' + additional + ')'; <add> } <add> var ex = errnoException(err, syscall, details); <add> ex.address = address; <add> if (port) { <add> ex.port = port; <add> } <add> return ex; <add>} <ide> <ide> exports.createServer = function() { <ide> return new Server(arguments[0], arguments[1]); <ide> function afterWrite(status, handle, req, err) { <ide> } <ide> <ide> if (status < 0) { <del> var ex = errnoException(status, 'write', err); <add> var ex = detailedException(status, 'write', req.address, req.port); <ide> debug('write failure', ex); <ide> self._destroy(ex, req.cb); <ide> return; <ide> function connect(self, address, port, addressType, localAddress, localPort) { <ide> err = bind(localAddress, localPort); <ide> <ide> if (err) { <del> self._destroy(errnoException(err, 'bind')); <add> var ex = detailedException(err, 'bind', localAddress, localPort); <add> self._destroy(ex); <ide> return; <ide> } <ide> } <ide> <del> var req = { oncomplete: afterConnect }; <add> var req = { <add> oncomplete: afterConnect, <add> port: undefined, <add> address: undefined, <add> localAddress: undefined, <add> localPort: undefined <add> }; <ide> if (addressType === 6 || addressType === 4) { <ide> port = port | 0; <ide> if (port <= 0 || port > 65535) <ide> throw new RangeError('Port should be > 0 and < 65536'); <ide> <add> req.port = port; <add> req.address = address; <ide> if (addressType === 6) { <ide> err = self._handle.connect6(req, address, port); <ide> } else if (addressType === 4) { <ide> err = self._handle.connect(req, address, port); <ide> } <ide> } else { <add> req.address = address; <ide> err = self._handle.connect(req, address, afterConnect); <ide> } <ide> <ide> if (err) { <del> self._destroy(errnoException(err, 'connect')); <add> self._getsockname(); <add> var details; <add> if (self._sockname) { <add> ex.localAddress = self._sockname.address; <add> ex.localPort = self._sockname.port; <add> details = ex.localAddress + ':' + ex.localPort; <add> } <add> var ex = detailedException(err, 'connect', address, port, details); <add> self._destroy(ex); <ide> } <ide> } <ide> <ide> Socket.prototype.connect = function(options, cb) { <ide> // There are no event listeners registered yet so defer the <ide> // error event to the next tick. <ide> process.nextTick(function() { <add> err.host = options.host; <add> err.port = options.port; <add> err.message = err.message + ' ' + options.host + ':' + options.port; <ide> self.emit('error', err); <ide> self._destroy(); <ide> }); <ide> function afterConnect(status, handle, req, readable, writable) { <ide> <ide> } else { <ide> self._connecting = false; <del> self._destroy(errnoException(status, 'connect')); <add> var details; <add> if (req.localAddress && req.localPort) { <add> ex.localAddress = req.localAddress; <add> ex.localPort = req.localPort; <add> details = ex.localAddress + ':' + ex.localPort; <add> } <add> var ex = detailedException(status, <add> 'connect', <add> req.address, <add> req.port, <add> details); <add> self._destroy(ex); <ide> } <ide> } <ide> <ide> Server.prototype._listen2 = function(address, port, addressType, backlog, fd) { <ide> debug('_listen2: create a handle'); <ide> var rval = createServerHandle(address, port, addressType, fd); <ide> if (util.isNumber(rval)) { <del> var error = errnoException(rval, 'listen'); <add> var error = detailedException(rval, 'listen', address, port); <ide> process.nextTick(function() { <ide> self.emit('error', error); <ide> }); <ide> Server.prototype._listen2 = function(address, port, addressType, backlog, fd) { <ide> var err = _listen(self._handle, backlog); <ide> <ide> if (err) { <del> var ex = errnoException(err, 'listen'); <add> var ex = detailedException(err, 'listen', address, port); <ide> self._handle.close(); <ide> self._handle = null; <ide> process.nextTick(function() { <ide> function listen(self, address, port, addressType, backlog, fd, exclusive) { <ide> err = uv.UV_EADDRINUSE; <ide> } <ide> <del> if (err) <del> return self.emit('error', errnoException(err, 'bind')); <add> if (err) { <add> var ex = detailedException(err, 'bind', address, port); <add> return self.emit('error', ex); <add> } <ide> <ide> self._handle = handle; <ide> self._listen2(address, port, addressType, backlog, fd); <ide><path>test/simple/test-net-better-error-messages-listen-path.js <add>var common = require('../common'); <add>var assert = require('assert'); <add>var net = require('net'); <add>var fp = '/blah/fadfa'; <add>var server = net.createServer(assert.fail); <add>server.listen(fp, assert.fail); <add>server.on('error', common.mustCall(function(e) { <add> assert.equal(e.address, fp) <add>})); <ide><path>test/simple/test-net-better-error-messages-listen.js <add>var common = require('../common'); <add>var assert = require('assert'); <add>var net = require('net'); <add> <add>var server = net.createServer(assert.fail); <add>server.listen(1, '1.1.1.1', assert.fail); <add>server.on('error', common.mustCall(function(e) { <add> assert.equal(e.address, '1.1.1.1'); <add> assert.equal(e.port, 1); <add> assert.equal(e.syscall, 'listen'); <add>})); <ide><path>test/simple/test-net-better-error-messages-path.js <add>var common = require('../common'); <add>var net = require('net'); <add>var assert = require('assert'); <add>var fp = '/tmp/fadagagsdfgsdf'; <add>var c = net.connect(fp); <add> <add>c.on('connect', assert.fail); <add> <add>c.on('error', common.mustCall(function(e) { <add> assert.equal(e.code, 'ENOENT'); <add> assert.equal(e.message, 'connect ENOENT ' + fp); <add>})); <ide><path>test/simple/test-net-better-error-messages-port-hostname.js <add>var common = require('../common'); <add>var net = require('net'); <add>var assert = require('assert'); <add> <add>var c = net.createConnection(common.PORT, 'blah.blah'); <add> <add>c.on('connect', assert.fail); <add> <add>c.on('error', common.mustCall(function(e) { <add> assert.equal(e.code, 'ENOTFOUND'); <add> assert.equal(e.port, common.PORT); <add> assert.equal(e.hostname, 'blah.blah'); <add>})); <ide><path>test/simple/test-net-better-error-messages-port.js <add>var common = require('../common'); <add>var net = require('net'); <add>var assert = require('assert'); <add> <add>var c = net.createConnection(common.PORT); <add> <add>c.on('connect', assert.fail); <add> <add>c.on('error', common.mustCall(function(e) { <add> assert.equal(e.code, 'ECONNREFUSED'); <add> assert.equal(e.port, common.PORT); <add> assert.equal(e.address, '127.0.0.1'); <add>}));
6
PHP
PHP
tweak a few variables
b8961bde2a4b3f760156e0d3e970fec795ebc4db
<ide><path>src/Illuminate/Foundation/Http/FormRequest.php <ide> class FormRequest extends Request implements ValidatesWhenResolved { <ide> protected $redirectAction; <ide> <ide> /** <del> * The input keys that should not be flashed on redirect. <add> * The key to be used for the view error bag. <ide> * <del> * @var array <add> * @var string <ide> */ <del> protected $dontFlash = ['password', 'password_confirmation']; <del> <add> protected $errorBag = 'default'; <add> <ide> /** <del> * The key to be used on the withErrors method. <add> * The input keys that should not be flashed on redirect. <ide> * <del> * @var string <add> * @var array <ide> */ <del> protected $errorsKey = 'default'; <add> protected $dontFlash = ['password', 'password_confirmation']; <ide> <ide> /** <ide> * Get the validator instance for the request. <ide> public function response(array $errors) <ide> <ide> return $this->redirector->to($this->getRedirectUrl()) <ide> ->withInput($this->except($this->dontFlash)) <del> ->withErrors($errors, $this->errorsKey); <add> ->withErrors($errors, $this->errorBag); <ide> } <ide> <ide> /**
1
Text
Text
add code-hints to builder page
b5503ef0a511f5be11d9dcfa1359976f159d8a67
<ide><path>docs/reference/commandline/build.md <ide> a subdirectory inside the repository that will be used as a build context. <ide> For example, run this command to use a directory called `docker` in the branch <ide> `container`: <ide> <del> $ docker build https://github.com/docker/rootfs.git#container:docker <add>```bash <add>$ docker build https://github.com/docker/rootfs.git#container:docker <add>``` <ide> <ide> The following table represents all the valid suffixes with their build <ide> contexts: <ide> <del>Build Syntax Suffix | Commit Used | Build Context Used <del>--------------------|-------------|------------------- <del>`myrepo.git` | `refs/heads/master` | `/` <del>`myrepo.git#mytag` | `refs/tags/mytag` | `/` <del>`myrepo.git#mybranch` | `refs/heads/mybranch` | `/` <del>`myrepo.git#abcdef` | `sha1 = abcdef` | `/` <del>`myrepo.git#:myfolder` | `refs/heads/master` | `/myfolder` <del>`myrepo.git#master:myfolder` | `refs/heads/master` | `/myfolder` <del>`myrepo.git#mytag:myfolder` | `refs/tags/mytag` | `/myfolder` <del>`myrepo.git#mybranch:myfolder` | `refs/heads/mybranch` | `/myfolder` <del>`myrepo.git#abcdef:myfolder` | `sha1 = abcdef` | `/myfolder` <add>Build Syntax Suffix | Commit Used | Build Context Used <add>--------------------------------|-----------------------|------------------- <add>`myrepo.git` | `refs/heads/master` | `/` <add>`myrepo.git#mytag` | `refs/tags/mytag` | `/` <add>`myrepo.git#mybranch` | `refs/heads/mybranch` | `/` <add>`myrepo.git#abcdef` | `sha1 = abcdef` | `/` <add>`myrepo.git#:myfolder` | `refs/heads/master` | `/myfolder` <add>`myrepo.git#master:myfolder` | `refs/heads/master` | `/myfolder` <add>`myrepo.git#mytag:myfolder` | `refs/tags/mytag` | `/myfolder` <add>`myrepo.git#mybranch:myfolder` | `refs/heads/mybranch` | `/myfolder` <add>`myrepo.git#abcdef:myfolder` | `sha1 = abcdef` | `/myfolder` <ide> <ide> Instead of specifying a context, you can pass a single Dockerfile in the `URL` <ide> or pipe the file in via `STDIN`. To pipe a Dockerfile from `STDIN`: <ide> <del> $ docker build - < Dockerfile <add>```bash <add>$ docker build - < Dockerfile <add>``` <ide> <ide> With Powershell on Windows, you can run: <ide> <del> Get-Content Dockerfile | docker build - <add>```powershell <add>Get-Content Dockerfile | docker build - <add>``` <ide> <ide> If you use STDIN or specify a `URL`, the system places the contents into a file <ide> called `Dockerfile`, and any `-f`, `--file` option is ignored. In this <ide> build fails, a non-zero failure code will be returned. <ide> There should be informational output of the reason for failure output to <ide> `STDERR`: <ide> <del> $ docker build -t fail . <del> Sending build context to Docker daemon 2.048 kB <del> Sending build context to Docker daemon <del> Step 1 : FROM busybox <del> ---> 4986bf8c1536 <del> Step 2 : RUN exit 13 <del> ---> Running in e26670ec7a0a <del> INFO[0000] The command [/bin/sh -c exit 13] returned a non-zero code: 13 <del> $ echo $? <del> 1 <add>```bash <add>$ docker build -t fail . <add> <add>Sending build context to Docker daemon 2.048 kB <add>Sending build context to Docker daemon <add>Step 1 : FROM busybox <add> ---> 4986bf8c1536 <add>Step 2 : RUN exit 13 <add> ---> Running in e26670ec7a0a <add>INFO[0000] The command [/bin/sh -c exit 13] returned a non-zero code: 13 <add>$ echo $? <add>1 <add>``` <ide> <ide> See also: <ide> <ide> See also: <ide> <ide> ### Build with PATH <ide> <del> $ docker build . <del> Uploading context 10240 bytes <del> Step 1 : FROM busybox <del> Pulling repository busybox <del> ---> e9aa60c60128MB/2.284 MB (100%) endpoint: https://cdn-registry-1.docker.io/v1/ <del> Step 2 : RUN ls -lh / <del> ---> Running in 9c9e81692ae9 <del> total 24 <del> drwxr-xr-x 2 root root 4.0K Mar 12 2013 bin <del> drwxr-xr-x 5 root root 4.0K Oct 19 00:19 dev <del> drwxr-xr-x 2 root root 4.0K Oct 19 00:19 etc <del> drwxr-xr-x 2 root root 4.0K Nov 15 23:34 lib <del> lrwxrwxrwx 1 root root 3 Mar 12 2013 lib64 -> lib <del> dr-xr-xr-x 116 root root 0 Nov 15 23:34 proc <del> lrwxrwxrwx 1 root root 3 Mar 12 2013 sbin -> bin <del> dr-xr-xr-x 13 root root 0 Nov 15 23:34 sys <del> drwxr-xr-x 2 root root 4.0K Mar 12 2013 tmp <del> drwxr-xr-x 2 root root 4.0K Nov 15 23:34 usr <del> ---> b35f4035db3f <del> Step 3 : CMD echo Hello world <del> ---> Running in 02071fceb21b <del> ---> f52f38b7823e <del> Successfully built f52f38b7823e <del> Removing intermediate container 9c9e81692ae9 <del> Removing intermediate container 02071fceb21b <add>```bash <add>$ docker build . <add> <add>Uploading context 10240 bytes <add>Step 1 : FROM busybox <add>Pulling repository busybox <add> ---> e9aa60c60128MB/2.284 MB (100%) endpoint: https://cdn-registry-1.docker.io/v1/ <add>Step 2 : RUN ls -lh / <add> ---> Running in 9c9e81692ae9 <add>total 24 <add>drwxr-xr-x 2 root root 4.0K Mar 12 2013 bin <add>drwxr-xr-x 5 root root 4.0K Oct 19 00:19 dev <add>drwxr-xr-x 2 root root 4.0K Oct 19 00:19 etc <add>drwxr-xr-x 2 root root 4.0K Nov 15 23:34 lib <add>lrwxrwxrwx 1 root root 3 Mar 12 2013 lib64 -> lib <add>dr-xr-xr-x 116 root root 0 Nov 15 23:34 proc <add>lrwxrwxrwx 1 root root 3 Mar 12 2013 sbin -> bin <add>dr-xr-xr-x 13 root root 0 Nov 15 23:34 sys <add>drwxr-xr-x 2 root root 4.0K Mar 12 2013 tmp <add>drwxr-xr-x 2 root root 4.0K Nov 15 23:34 usr <add> ---> b35f4035db3f <add>Step 3 : CMD echo Hello world <add> ---> Running in 02071fceb21b <add> ---> f52f38b7823e <add>Successfully built f52f38b7823e <add>Removing intermediate container 9c9e81692ae9 <add>Removing intermediate container 02071fceb21b <add>``` <ide> <ide> This example specifies that the `PATH` is `.`, and so all the files in the <ide> local directory get `tar`d and sent to the Docker daemon. The `PATH` specifies <ide> you must use `--rm=false`. This does not affect the build cache. <ide> <ide> ### Build with URL <ide> <del> $ docker build github.com/creack/docker-firefox <add>```bash <add>$ docker build github.com/creack/docker-firefox <add>``` <ide> <ide> This will clone the GitHub repository and use the cloned repository as context. <ide> The Dockerfile at the root of the repository is used as Dockerfile. Note that <ide> scheme. <ide> <ide> ### Build with - <ide> <del> $ docker build - < Dockerfile <add>```bash <add>$ docker build - < Dockerfile <add>``` <ide> <ide> This will read a Dockerfile from `STDIN` without context. Due to the lack of a <ide> context, no contents of any local directory will be sent to the Docker daemon. <ide> Since there is no context, a Dockerfile `ADD` only works if it refers to a <ide> remote URL. <ide> <del> $ docker build - < context.tar.gz <add>```bash <add>$ docker build - < context.tar.gz <add>``` <ide> <ide> This will build an image for a compressed context read from `STDIN`. Supported <ide> formats are: bzip2, gzip and xz. <ide> <ide> ### Usage of .dockerignore <ide> <del> $ docker build . <del> Uploading context 18.829 MB <del> Uploading context <del> Step 1 : FROM busybox <del> ---> 769b9341d937 <del> Step 2 : CMD echo Hello world <del> ---> Using cache <del> ---> 99cc1ad10469 <del> Successfully built 99cc1ad10469 <del> $ echo ".git" > .dockerignore <del> $ docker build . <del> Uploading context 6.76 MB <del> Uploading context <del> Step 1 : FROM busybox <del> ---> 769b9341d937 <del> Step 2 : CMD echo Hello world <del> ---> Using cache <del> ---> 99cc1ad10469 <del> Successfully built 99cc1ad10469 <add>```bash <add>$ docker build . <add> <add>Uploading context 18.829 MB <add>Uploading context <add>Step 1 : FROM busybox <add> ---> 769b9341d937 <add>Step 2 : CMD echo Hello world <add> ---> Using cache <add> ---> 99cc1ad10469 <add>Successfully built 99cc1ad10469 <add>$ echo ".git" > .dockerignore <add>$ docker build . <add>Uploading context 6.76 MB <add>Uploading context <add>Step 1 : FROM busybox <add> ---> 769b9341d937 <add>Step 2 : CMD echo Hello world <add> ---> Using cache <add> ---> 99cc1ad10469 <add>Successfully built 99cc1ad10469 <add>``` <ide> <ide> This example shows the use of the `.dockerignore` file to exclude the `.git` <ide> directory from the context. Its effect can be seen in the changed size of the <ide> uploaded context. The builder reference contains detailed information on <ide> <ide> ### Tag image (-t) <ide> <del> $ docker build -t vieux/apache:2.0 . <add>```bash <add>$ docker build -t vieux/apache:2.0 . <add>``` <ide> <ide> This will build like the previous example, but it will then tag the resulting <ide> image. The repository name will be `vieux/apache` and the tag will be `2.0`. <ide> version. <ide> For example, to tag an image both as `whenry/fedora-jboss:latest` and <ide> `whenry/fedora-jboss:v2.1`, use the following: <ide> <del> $ docker build -t whenry/fedora-jboss:latest -t whenry/fedora-jboss:v2.1 . <del> <add>```bash <add>$ docker build -t whenry/fedora-jboss:latest -t whenry/fedora-jboss:v2.1 . <add>``` <ide> ### Specify Dockerfile (-f) <ide> <del> $ docker build -f Dockerfile.debug . <add>```bash <add>$ docker build -f Dockerfile.debug . <add>``` <ide> <ide> This will use a file called `Dockerfile.debug` for the build instructions <ide> instead of `Dockerfile`. <ide> <del> $ docker build -f dockerfiles/Dockerfile.debug -t myapp_debug . <del> $ docker build -f dockerfiles/Dockerfile.prod -t myapp_prod . <add>```bash <add>$ docker build -f dockerfiles/Dockerfile.debug -t myapp_debug . <add>$ docker build -f dockerfiles/Dockerfile.prod -t myapp_prod . <add>``` <ide> <ide> The above commands will build the current build context (as specified by the <ide> `.`) twice, once using a debug version of a `Dockerfile` and once using a <ide> production version. <ide> <del> $ cd /home/me/myapp/some/dir/really/deep <del> $ docker build -f /home/me/myapp/dockerfiles/debug /home/me/myapp <del> $ docker build -f ../../../../dockerfiles/debug /home/me/myapp <add>```bash <add>$ cd /home/me/myapp/some/dir/really/deep <add>$ docker build -f /home/me/myapp/dockerfiles/debug /home/me/myapp <add>$ docker build -f ../../../../dockerfiles/debug /home/me/myapp <add>``` <ide> <ide> These two `docker build` commands do the exact same thing. They both use the <ide> contents of the `debug` file instead of looking for a `Dockerfile` and will use <ide> A good example is `http_proxy` or source versions for pulling intermediate <ide> files. The `ARG` instruction lets Dockerfile authors define values that users <ide> can set at build-time using the `--build-arg` flag: <ide> <del> $ docker build --build-arg HTTP_PROXY=http://10.20.30.2:1234 . <add>```bash <add>$ docker build --build-arg HTTP_PROXY=http://10.20.30.2:1234 . <add>``` <ide> <ide> This flag allows you to pass the build-time variables that are <ide> accessed like regular environment variables in the `RUN` instruction of the <ide> Linux namespaces. On Microsoft Windows, you can specify these values: <ide> |-----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------| <ide> | `default` | Use the value specified by the Docker daemon's `--exec-opt` . If the `daemon` does not specify an isolation technology, Microsoft Windows uses `process` as its default value. | <ide> | `process` | Namespace isolation only. | <del>| `hyperv` | Hyper-V hypervisor partition-based isolation. | <add>| `hyperv` | Hyper-V hypervisor partition-based isolation. | <ide> <ide> Specifying the `--isolation` flag without a value is the same as setting `--isolation="default"`.
1
Text
Text
make minor edits for consistency
606df7c4e79324b9725bfcfe019a8b75bfa04c3f
<ide><path>doc/api/async_hooks.md <ide> of asynchronous operations. <ide> * Returns: {AsyncHook} A reference to `asyncHook`. <ide> <ide> Enable the callbacks for a given `AsyncHook` instance. If no callbacks are <del>provided enabling is a noop. <add>provided, enabling is a no-op. <ide> <ide> The `AsyncHook` instance is disabled by default. If the `AsyncHook` instance <ide> should be enabled immediately after creation, the following pattern can be used. <ide><path>doc/api/stream.md <ide> added: v8.0.0 <ide> changes: <ide> - version: v14.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/29197 <del> description: Work as noop when called on an already `destroyed` stream. <add> description: Work as a no-op on a stream that has already been destroyed. <ide> --> <ide> <ide> * `error` {Error} Optional, an error to emit with `'error'` event. <ide> This is a destructive and immediate way to destroy a stream. Previous calls to <ide> Use `end()` instead of destroy if data should flush before close, or wait for <ide> the `'drain'` event before destroying the stream. <ide> <del>Once `destroy()` has been called any further calls will be a noop and no <del>further errors except from `_destroy` may be emitted as `'error'`. <add>Once `destroy()` has been called any further calls will be a no-op and no <add>further errors except from `_destroy()` may be emitted as `'error'`. <ide> <ide> Implementors should not override this method, <ide> but instead implement [`writable._destroy()`][writable-_destroy]. <ide> added: v8.0.0 <ide> changes: <ide> - version: v14.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/29197 <del> description: Work as noop when called on an already `destroyed` stream. <add> description: Work as a no-op on a stream that has already been destroyed. <ide> --> <ide> <ide> * `error` {Error} Error which will be passed as payload in `'error'` event <ide> event (unless `emitClose` is set to `false`). After this call, the readable <ide> stream will release any internal resources and subsequent calls to `push()` <ide> will be ignored. <ide> <del>Once `destroy()` has been called any further calls will be a noop and no <del>further errors except from `_destroy` may be emitted as `'error'`. <add>Once `destroy()` has been called any further calls will be a no-op and no <add>further errors except from `_destroy()` may be emitted as `'error'`. <ide> <ide> Implementors should not override this method, but instead implement <ide> [`readable._destroy()`][readable-_destroy]. <ide> added: v8.0.0 <ide> changes: <ide> - version: v14.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/29197 <del> description: Work as noop when called on an already `destroyed` stream. <add> description: Work as a no-op on a stream that has already been destroyed. <ide> --> <ide> <ide> * `error` {Error} <ide> Implementors should not override this method, but instead implement <ide> The default implementation of `_destroy()` for `Transform` also emit `'close'` <ide> unless `emitClose` is set in false. <ide> <del>Once `destroy()` has been called any further calls will be a noop and no <del>further errors except from `_destroy` may be emitted as `'error'`. <add>Once `destroy()` has been called, any further calls will be a no-op and no <add>further errors except from `_destroy()` may be emitted as `'error'`. <ide> <ide> ### `stream.finished(stream[, options], callback)` <ide> <!-- YAML <ide> by child classes, and if so, will be called by the internal `Writable` <ide> class methods only. <ide> <ide> This optional function will be called in a tick after the stream constructor <del>has returned, delaying any `_write`, `_final` and `_destroy` calls until <add>has returned, delaying any `_write()`, `_final()` and `_destroy()` calls until <ide> `callback` is called. This is useful to initialize state or asynchronously <ide> initialize resources before the stream can be used. <ide> <ide> by child classes, and if so, will be called by the internal `Readable` <ide> class methods only. <ide> <ide> This optional function will be scheduled in the next tick by the stream <del>constructor, delaying any `_read` and `_destroy` calls until `callback` is <add>constructor, delaying any `_read()` and `_destroy()` calls until `callback` is <ide> called. This is useful to initialize state or asynchronously initialize <ide> resources before the stream can be used. <ide>
2
Javascript
Javascript
add platform basic implementation (fallback)
c7464ebf91af37482912b434a9e5dc25cf46666e
<ide><path>src/platforms/platform.basic.js <add>/** <add> * Platform fallback implementation (minimal). <add> * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939 <add> */ <add> <add>module.exports = { <add> acquireContext: function(item) { <add> if (item && item.canvas) { <add> // Support for any object associated to a canvas (including a context2d) <add> item = item.canvas; <add> } <add> <add> return item && item.getContext('2d') || null; <add> } <add>}; <ide><path>src/platforms/platform.dom.js <ide> function injectCSS(platform, css) { <ide> } <ide> <ide> module.exports = { <add> /** <add> * This property holds whether this platform is enabled for the current environment. <add> * Currently used by platform.js to select the proper implementation. <add> * @private <add> */ <add> _enabled: typeof window !== 'undefined' && typeof document !== 'undefined', <add> <ide> initialize: function() { <ide> var keyframes = 'from{opacity:0.99}to{opacity:1}'; <ide> <ide><path>src/platforms/platform.js <ide> 'use strict'; <ide> <ide> var helpers = require('../helpers/index'); <add>var basic = require('./platform.basic'); <add>var dom = require('./platform.dom'); <ide> <del>// By default, select the browser (DOM) platform. <ide> // @TODO Make possible to select another platform at build time. <del>var implementation = require('./platform.dom'); <add>var implementation = dom._enabled ? dom : basic; <ide> <ide> /** <ide> * @namespace Chart.platform
3
Ruby
Ruby
improve the method
4e2ca9b23fcaa98f4ef375a3a6d8eee579baec94
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> class AbstractMysqlAdapter < AbstractAdapter <ide> <ide> class SchemaCreation < AbstractAdapter::SchemaCreation <ide> def visit_TableDefinition(o) <del> create_sql = "CREATE#{' TEMPORARY' if o.temporary} TABLE " <del> create_sql << "#{quote_table_name(o.name)} " <del> statements = [] <del> statements.concat(o.columns.map { |c| accept c }) <del> statements.concat(o.indexes.map { |(column_name, options)| index_in_create(o.name, column_name, options) }) <add> name = o.name <add> create_sql = "CREATE#{' TEMPORARY' if o.temporary} TABLE #{quote_table_name(name)} " <add> <add> statements = o.columns.map { |c| accept c } <add> statements.concat(o.indexes.map { |column_name, options| index_in_create(name, column_name, options) }) <add> <ide> create_sql << "(#{statements.join(', ')}) " if statements.present? <ide> create_sql << "#{o.options}" <ide> create_sql << " AS #{@conn.to_sql(o.as)}" if o.as
1
Python
Python
add glances and psutil version
49029112c22bf3c11406e1730eab258e0c7ebb59
<ide><path>glances/outputs/glances_stdout_issue.py <ide> from glances.logger import logger <ide> from glances.compat import printandflush <ide> from glances.timer import Counter <add>from glances import __version__, psutil_version <ide> <ide> try: <ide> TERMINAL_WIDTH = shutil.get_terminal_size(fallback=(79, 24)).columns <ide> def __init__(self, config=None, args=None): <ide> def end(self): <ide> pass <ide> <add> def print_version(self): <add> msg = 'Glances version {} with PsUtil {}'.format( <add> colors.BLUE + __version__ + colors.NO, <add> colors.BLUE + psutil_version + colors.NO) <add> sys.stdout.write('='*len(msg) + '\n') <add> sys.stdout.write(msg) <add> sys.stdout.write(colors.NO + '\n') <add> sys.stdout.write('='*len(msg) + '\n') <add> sys.stdout.flush() <add> <ide> def print_issue(self, plugin, result, message): <ide> sys.stdout.write('{}{}{}'.format( <ide> colors.BLUE + plugin, result, message)) <ide> def update(self, <ide> duration=3): <ide> """Display issue <ide> """ <del> for plugin in stats._plugins: <add> self.print_version() <add> for plugin in sorted(stats._plugins): <ide> if stats._plugins[plugin].is_disable(): <ide> # If current plugin is disable <ide> # then continue to next plugin
1
PHP
PHP
add sqs to list of supported drivers
457e76a470bd0b1df51df116f3c5eaad2a8b7d53
<ide><path>app/config/queue.php <ide> | API, giving you convenient access to each back-end using the same <ide> | syntax for each one. Here you may set the default queue driver. <ide> | <del> | Supported: "sync", "beanstalkd" <add> | Supported: "sync", "beanstalkd", "sqs" <ide> | <ide> */ <ide>
1
Java
Java
remove the flag about lazy native modules
407e033b34b6afa0ea96ed72f16cd164d572e911
<ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestHelper.java <ide> public ReactInstanceEasyBuilder addNativeModule(NativeModule nativeModule) { <ide> if (mNativeModuleRegistryBuilder == null) { <ide> mNativeModuleRegistryBuilder = new NativeModuleRegistryBuilder( <ide> (ReactApplicationContext) mContext, <del> null, <del> false); <add> null); <ide> } <ide> Assertions.assertNotNull(nativeModule); <ide> mNativeModuleRegistryBuilder.addNativeModule(nativeModule); <ide> public CatalystInstance build() { <ide> if (mNativeModuleRegistryBuilder == null) { <ide> mNativeModuleRegistryBuilder = new NativeModuleRegistryBuilder( <ide> (ReactApplicationContext) mContext, <del> null, <del> false); <add> null); <ide> } <ide> JavaScriptExecutor executor = null; <ide> try { <ide><path>ReactAndroid/src/main/java/com/facebook/react/NativeModuleRegistryBuilder.java <ide> public class NativeModuleRegistryBuilder { <ide> <ide> private final ReactApplicationContext mReactApplicationContext; <ide> private final ReactInstanceManager mReactInstanceManager; <del> private final boolean mLazyNativeModulesEnabled; <ide> <ide> private final Map<String, ModuleHolder> mModules = new HashMap<>(); <ide> private final Map<String,String> namesToType = new HashMap<>(); <ide> <ide> public NativeModuleRegistryBuilder( <ide> ReactApplicationContext reactApplicationContext, <del> ReactInstanceManager reactInstanceManager, <del> boolean lazyNativeModulesEnabled) { <add> ReactInstanceManager reactInstanceManager) { <ide> mReactApplicationContext = reactApplicationContext; <ide> mReactInstanceManager = reactInstanceManager; <del> // TODO T32034141 Remove mLazyNativeModulesEnabled <del> mLazyNativeModulesEnabled = lazyNativeModulesEnabled; <ide> } <ide> <ide> public void processPackage(ReactPackage reactPackage) { <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java <ide> public interface ReactInstanceEventListener { <ide> private volatile Boolean mHasStartedDestroying = false; <ide> private final MemoryPressureRouter mMemoryPressureRouter; <ide> private final @Nullable NativeModuleCallExceptionHandler mNativeModuleCallExceptionHandler; <del> private final boolean mLazyNativeModulesEnabled; <ide> private final @Nullable JSIModulePackage mJSIModulePackage; <ide> private List<ViewManager> mViewManagers; <ide> <ide> public static ReactInstanceManagerBuilder builder() { <ide> LifecycleState initialLifecycleState, <ide> NativeModuleCallExceptionHandler nativeModuleCallExceptionHandler, <ide> @Nullable RedBoxHandler redBoxHandler, <del> boolean lazyNativeModulesEnabled, <ide> boolean lazyViewManagersEnabled, <ide> @Nullable DevBundleDownloadListener devBundleDownloadListener, <ide> int minNumShakes, <ide> public static ReactInstanceManagerBuilder builder() { <ide> mLifecycleState = initialLifecycleState; <ide> mMemoryPressureRouter = new MemoryPressureRouter(applicationContext); <ide> mNativeModuleCallExceptionHandler = nativeModuleCallExceptionHandler; <del> mLazyNativeModulesEnabled = lazyNativeModulesEnabled; <ide> synchronized (mPackages) { <ide> PrinterHolder.getPrinter() <ide> .logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: Use Split Packages"); <ide> private NativeModuleRegistry processPackages( <ide> boolean checkAndUpdatePackageMembership) { <ide> NativeModuleRegistryBuilder nativeModuleRegistryBuilder = new NativeModuleRegistryBuilder( <ide> reactContext, <del> this, <del> mLazyNativeModulesEnabled); <add> this); <ide> <ide> ReactMarker.logMarker(PROCESS_PACKAGES_START); <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerBuilder.java <ide> public class ReactInstanceManagerBuilder { <ide> private @Nullable Activity mCurrentActivity; <ide> private @Nullable DefaultHardwareBackBtnHandler mDefaultHardwareBackBtnHandler; <ide> private @Nullable RedBoxHandler mRedBoxHandler; <del> private boolean mLazyNativeModulesEnabled; <ide> private boolean mLazyViewManagersEnabled; <ide> private @Nullable DevBundleDownloadListener mDevBundleDownloadListener; <ide> private @Nullable JavaScriptExecutorFactory mJavaScriptExecutorFactory; <ide> public ReactInstanceManagerBuilder setRedBoxHandler(@Nullable RedBoxHandler redB <ide> return this; <ide> } <ide> <del> public ReactInstanceManagerBuilder setLazyNativeModulesEnabled(boolean lazyNativeModulesEnabled) { <del> mLazyNativeModulesEnabled = lazyNativeModulesEnabled; <del> return this; <del> } <del> <ide> public ReactInstanceManagerBuilder setLazyViewManagersEnabled(boolean lazyViewManagersEnabled) { <ide> mLazyViewManagersEnabled = lazyViewManagersEnabled; <ide> return this; <ide> public ReactInstanceManager build() { <ide> Assertions.assertNotNull(mInitialLifecycleState, "Initial lifecycle state was not set"), <ide> mNativeModuleCallExceptionHandler, <ide> mRedBoxHandler, <del> mLazyNativeModulesEnabled, <ide> mLazyViewManagersEnabled, <ide> mDevBundleDownloadListener, <ide> mMinNumShakes,
4
PHP
PHP
move phpunit bootstrap condition to schema loader
64001021646c629abd9417bb599b675a34dd7776
<ide><path>src/TestSuite/Fixture/SchemaGenerator.php <ide> public function __construct(string $file, string $connection) <ide> */ <ide> public function reload(?array $tables = null): void <ide> { <add> // Don't reload schema when we are in a separate process <add> // state. <add> if (isset($GLOBALS['__PHPUNIT_BOOTSTRAP'])) { <add> return; <add> } <ide> $cleaner = new SchemaCleaner(); <ide> $cleaner->dropTables($this->connection, $tables); <ide> <ide><path>tests/bootstrap.php <ide> // has been written to. <ide> session_id('cli'); <ide> <del>// Create test database schema as long as we are not in an isolated process test. <del>if (!isset($GLOBALS['__PHPUNIT_BOOTSTRAP']) && env('FIXTURE_SCHEMA_METADATA')) { <del> $schema = new SchemaGenerator(env('FIXTURE_SCHEMA_METADATA'), 'test'); <del> $schema->reload(); <del>} <add>// Create test database schema <add>$schema = new SchemaGenerator(env('FIXTURE_SCHEMA_METADATA'), 'test'); <add>$schema->reload();
2
Python
Python
add imports to base_rnn example
b7f641961f58876a326d5f94762ad1ae2e83022c
<ide><path>keras/layers/rnn/base_rnn.py <ide> class RNN(base_layer.Layer): <ide> Examples: <ide> <ide> ```python <del> # First, let's define a RNN Cell, as a layer subclass. <add> from keras.layers import RNN <add> from keras import backend <ide> <add> # First, let's define a RNN Cell, as a layer subclass. <ide> class MinimalRNNCell(keras.layers.Layer): <ide> <ide> def __init__(self, units, **kwargs):
1
Mixed
Ruby
remove old test files
f5b2a8f072ab8941eb5ac5fccb1fc8e1dcfc6c8b
<ide><path>test/cat.js <del>var filename = ARGV[2]; <del>File.cat(filename, function (status, content) { <del> if (status == 0) <del> puts(content); <del> else <del> puts("error"); <del>}); <del>puts("hello world"); <ide><path>test/common.rb <del>require 'tempfile' <del> <del>$node = File.join(File.dirname(__FILE__), "../node") <del>$tf = Tempfile.open("node") <del>$tf.puts(DATA.read) <del>$tf.close <del> <del>def assert(x, msg = "") <del> raise(msg) unless x <del>end <del> <del>def assert_equal(x, y, msg = "") <del> raise("expected #{x.inspect} == #{y.inspect}. #{msg}") unless x == y <del>end <del> <del>def assert_less_than(x, y, msg = "") <del> raise("expected #{x.inspect} < #{y.inspect}. #{msg}") unless x < y <del>end <del> <del>def wait_for_server(host, port) <del> loop do <del> begin <del> socket = ::TCPSocket.open(host, port) <del> return <del> rescue Errno::ECONNREFUSED <del> $stderr.print "." if $DEBUG <del> $stderr.flush <del> sleep 0.2 <del> ensure <del> socket.close <del> end <del> end <del>end <del> <ide><path>test/simple.js <del>var f = new File; <del> <del>f.open("/tmp/world", "w+", function (status) { <del> if (status == 0) { <del> stdout.puts("file open"); <del> f.write("hello world\n"); <del> f.write("something else.\n", function () { <del> stdout.puts("written. "); <del> }); <del> f.read(100, function (status, buf) { <del> if (buf) <del> stdout.puts("read: >>" + buf.encodeUtf8() + "<<"); <del> }); <del> } else { <del> stdout.puts("file open failed: " + status.toString()); <del> } <del> <del> f.close(function (status) { <del> stdout.puts("closed: " + status.toString()); <del> File.rename("/tmp/world", "/tmp/hello", function (status) { <del> stdout.puts("rename: " + status.toString()); <del> }); <del> }); <del>}); <ide><path>test/stats.js <del>File.stat(ARGV[2], function (status, stats) { <del> if (status == 0) { <del> for (var i in stats) { <del> puts(i + " : " + stats[i]); <del> } <del> } else { <del> puts("error: " + File.strerror(status)); <del> } <del>}); <del> <del>File.exists(ARGV[2], function (r) { <del> puts("file exists: " + r); <del>}); <del> <del> <ide><path>test/test_clearTimeout.rb <del>#!/usr/bin/env ruby <del>require File.dirname(__FILE__) + "/common" <del> <del>a = Time.now <del>out = `#{$node} #{$tf.path}` <del>b = Time.now <del>assert_equal("hello\nworld\n", out) <del>assert_less_than(b - a, 1) # startup time <del> <del>__END__ <del>log("hello"); <del>timeout1 = setTimeout(function () { log("world"); }, 500); <del>timeout2 = setTimeout(function () { log("ryah"); }, 5000); <del>clearTimeout(timeout2) <ide><path>test/test_http_server_echo.rb <del>#!/usr/bin/env ruby <del>require 'net/http' <del>require File.dirname(__FILE__) + "/common" <del> <del>pid = fork do <del> exec($node, $tf.path) <del>end <del> <del>begin <del> wait_for_server("localhost", 8000) <del> connection = Net::HTTP.new("localhost", 8000) <del> <del> response, body = connection.get("/") <del> assert_equal(response.code, "200") <del> assert(response.chunked?) <del> assert_equal(body, "\n") <del> assert_equal(response.content_type, "text/plain") <del> <del> response, body = connection.post("/", "hello world") <del> assert_equal(response.code, "200") <del> assert(response.chunked?) <del> assert_equal(body, "hello world\n") <del> assert_equal(response.content_type, "text/plain") <del>ensure <del> `kill -9 #{pid}` <del>end <del> <del>__END__ <del>function encode(data) { <del> var chunk = data.toString(); <del> return chunk.length.toString(16) + "\r\n" + chunk + "\r\n"; <del>} <del> <del>var port = 8000; <del>var server = new HTTPServer(null, port, function (request) { <del> <del> // onBody sends null on the last chunk. <del> request.onbody = function (chunk) { <del> if(chunk) { <del> this.respond(encode(chunk)); <del> } else { <del> this.respond(encode("\n")); <del> this.respond("0\r\n\r\n"); <del> this.respond(null); // signals end-of-request <del> } <del> } <del> request.respond("HTTP/1.0 200 OK\r\n"); <del> request.respond("Content-Type: text/plain\r\n"); <del> request.respond("Transfer-Encoding: chunked\r\n"); <del> request.respond("\r\n"); <del>}); <del> <del>log("Running at http://localhost:" + port + "/"); <ide><path>test/test_http_server_null_response.rb <del>#!/usr/bin/env ruby <del>require 'net/http' <del>require File.dirname(__FILE__) + "/common" <del> <del>pid = fork do <del> exec($node, $tf.path) <del>end <del> <del>begin <del> wait_for_server("localhost", 8000) <del> connection = Net::HTTP.new("localhost", 8000) <del> <del> response, body = connection.get("/") <del>ensure <del> `kill -9 #{pid}` <del>end <del> <del>__END__ <del>var server = new HTTPServer(null, 8000, function (request) { <del> log("request"); <del> request.respond("HTTP/1.1 200 OK\r\n"); <del> request.respond("Content-Length: 0\r\n"); <del> request.respond("\r\n"); <del> request.respond(null); <del>}); <ide><path>test/test_setTimeout.rb <del>#!/usr/bin/env ruby <del>require File.dirname(__FILE__) + "/common" <del> <del>prog = IO.popen("#{$node} #{$tf.path}") <del>a = Time.now <del>assert_equal("hello\n", prog.readpartial(100)) <del>b = Time.now <del>assert_equal("world\n", prog.read(100)) <del>c = Time.now <del> <del>assert_less_than(b - a, 0.5) # startup time <del>assert_less_than(1.5, c - b) <del> <del>__END__ <del>log("hello"); <del>setTimeout(function () { log("world"); }, 1500);
8
Ruby
Ruby
fix `time.h` patch not being applied
60cef850bd3fd12c32ee1196bd19a559592d1465
<ide><path>scripts/react_native_pods.rb <ide> def __apply_Xcode_12_5_M1_post_install_workaround(installer) <ide> # "Time.h:52:17: error: typedef redefinition with different types" <ide> # We need to make a patch to RCT-Folly - remove the `__IPHONE_OS_VERSION_MIN_REQUIRED` check. <ide> # See https://github.com/facebook/flipper/issues/834 for more details. <del> `sed -i -e $'s/ && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0)//' Pods/RCT-Folly/folly/portability/Time.h` <add> time_header = "#{Pod::Config.instance.installation_root.to_s}/Pods/RCT-Folly/folly/portability/Time.h" <add> `sed -i -e $'s/ && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0)//' #{time_header}` <ide> end
1
Ruby
Ruby
fix conditional order broken in ea40ec56
173bf3506d99c0767a41d30fbe4d306201369194
<ide><path>actionpack/lib/action_dispatch/testing/integration.rb <ide> def initialize(mime_name, param_encoder, response_parser, url_encoded_form = fal <ide> <ide> def append_format_to(path) <ide> if @url_encoded_form <del> path + @path_format <del> else <ide> path <add> else <add> path + @path_format <ide> end <ide> end <ide>
1
Ruby
Ruby
require both variant of resque-scheduler
392c48278507ef5ac43dd450725ce0ffb6b4d4ce
<ide><path>lib/active_job/queue_adapters/resque_adapter.rb <ide> require 'resque' <ide> require 'active_support/core_ext/enumerable' <ide> require 'active_support/core_ext/array/access' <del>require 'resque-scheduler' <add>begin <add> require 'resque-scheduler' <add>rescue LoadError <add> require 'resque_scheduler' <add>end <ide> <ide> module ActiveJob <ide> module QueueAdapters
1
Javascript
Javascript
remove unnecessary lines in gltf2loader
5622169499f72768399f7430f6cd3ce0f0b50f72
<ide><path>examples/js/loaders/GLTF2Loader.js <ide> THREE.GLTF2Loader = ( function () { <ide> // TODO: implement <ide> if ( target.TANGENT !== undefined ) { <ide> <del> console.log( dependencies.accessors[ target.NORMAL ] ); <del> <ide> } <ide> <ide> } <ide> THREE.GLTF2Loader = ( function () { <ide> <ide> var target = channel.target; <ide> var name = target.node || target.id; // NOTE: target.id is deprecated. <del> <ide> var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input; <ide> var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output; <ide>
1
Javascript
Javascript
use `readableobjectmode` option
9e62ae4304a0bee3aec8c5fb743eb17d78b1cd35
<ide><path>lib/_debug_agent.js <ide> Agent.prototype.notifyWait = function notifyWait() { <ide> }; <ide> <ide> function Client(agent, socket) { <del> Transform.call(this); <del> this._readableState.objectMode = true; <add> Transform.call(this, { <add> readableObjectMode: true <add> }); <ide> <ide> this.agent = agent; <ide> this.binding = this.agent.binding;
1
PHP
PHP
improve findorfail() exceptions
442c5eea031f4bfdcbe1de790a9f383e1314dcec
<ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php <ide> public function findOrFail($id, $columns = ['*']) <ide> return $result; <ide> } <ide> <del> throw (new ModelNotFoundException)->setModel(get_class($this->related)); <add> throw (new ModelNotFoundException)->setModel(get_class($this->related), $id); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php <ide> public function findOrFail($id, $columns = ['*']) <ide> return $result; <ide> } <ide> <del> throw (new ModelNotFoundException)->setModel(get_class($this->related)); <add> throw (new ModelNotFoundException)->setModel(get_class($this->related), $id); <ide> } <ide> <ide> /** <ide><path>tests/Database/DatabaseEloquentHasManyThroughIntegrationTest.php <ide> public function testFirstOrFailThrowsAnException() <ide> <ide> /** <ide> * @expectedException \Illuminate\Database\Eloquent\ModelNotFoundException <del> * @expectedExceptionMessage No query results for model [Illuminate\Tests\Database\HasManyThroughTestPost]. <add> * @expectedExceptionMessage No query results for model [Illuminate\Tests\Database\HasManyThroughTestPost] 1 <ide> */ <ide> public function testFindOrFailThrowsAnException() <ide> {
3
PHP
PHP
use fqcn in sync methods docblocks
a3965d1007f7493c3e31dc34af9a109408addaa4
<ide><path>src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php <ide> public function toggle($ids, $touch = true) <ide> /** <ide> * Sync the intermediate tables with a list of IDs without detaching. <ide> * <del> * @param \Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection|array|Model $ids <add> * @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array $ids <ide> * @return array <ide> */ <ide> public function syncWithoutDetaching($ids) <ide> public function syncWithoutDetaching($ids) <ide> /** <ide> * Sync the intermediate tables with a list of IDs or collection of models. <ide> * <del> * @param \Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection|array|Model $ids <add> * @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array $ids <ide> * @param bool $detaching <ide> * @return array <ide> */
1
Python
Python
fix code style
782d3852e3e66e394b4c6b56029259413de1d54b
<ide><path>research/object_detection/meta_architectures/faster_rcnn_meta_arch.py <ide> def _compute_second_stage_input_feature_maps(self, features_to_crop, <ide> num_levels = len(features_to_crop) <ide> box_levels = None <ide> if num_levels != 1: <del> # If there are mutiple levels to select, get the box levels <del> box_levels = ops.fpn_feature_levels(num_levels, num_levels - 2, <del> tf.sqrt(self._resize_shape[1] * self._resize_shape[2] * 1.0) / 224.0, <del> proposal_boxes_normalized) <del> <add> # If there are mutiple levels to select, get the box levels <add> box_levels = ops.fpn_feature_levels( <add> num_levels, num_levels - 2, <add> tf.sqrt(self._resize_shape[1] * self._resize_shape[2] * 1.0) / 224.0, <add> proposal_boxes_normalized) <add> <ide> cropped_regions = self._flatten_first_two_dimensions( <ide> self._crop_and_resize_fn( <ide> features_to_crop, proposal_boxes_normalized, box_levels, <ide> class targets with the 0th index assumed to map to the background class. <ide> box_list.BoxList(tf.reshape(proposal_boxes, [-1, 4])), <ide> image_shape[1], image_shape[2], check_range=False).get() <ide> <del> # TODO(syiming): check this! <ide> flat_cropped_gt_mask = self._crop_and_resize_fn( <ide> [tf.expand_dims(flat_gt_masks, -1)], <ide> tf.expand_dims(flat_normalized_proposals, axis=1), None,
1
Ruby
Ruby
fix tiny typo in example
061923371cc8f24b93aedb7842938a69fea6ac19
<ide><path>activeresource/lib/active_resource/validations.rb <ide> def from_xml(xml) <ide> # person.valid? # => false <ide> # person.errors.empty? # => false <ide> # person.errors.count # => 1 <del> # person.errors.full_messages # => "Last name can't be empty" <add> # person.errors.full_messages # => ["Last name can't be empty"] <ide> # person.errors.on(:last_name) # => "can't be empty" <ide> # person.last_name = "Halpert" <ide> # person.save # => true (and person is now saved to the remote service)
1
Text
Text
ask more questions in the bug report template
0effc9845f74e7351487644cbd1691196000b93e
<ide><path>.github/ISSUE_TEMPLATE.md <ide> Please fill in as much of the template below as you're able. <ide> Version: output of `node -v` <ide> Platform: output of `uname -a` (UNIX), or version and 32 or 64-bit (Windows) <ide> Subsystem: if known, please specify affected core module name <del> <del>If possible, please provide code that demonstrates the problem, keeping it as <del>simple and free of external dependencies as you are able. <ide> --> <ide> <ide> * **Version**: <ide> * **Platform**: <ide> * **Subsystem**: <ide> <del><!-- Enter your issue details below this comment. --> <add>### What steps will reproduce the bug? <add> <add><!-- <add>Enter details about your bug, preferably a simple code snippet that can be <add>run using `node` directly without installing third-party dependencies. <add>--> <add> <add>### How often does it reproduce? Is there a required condition? <add> <add>### What is the expected behavior? <add> <add><!-- <add>If possible please provide textual output instead of screenshots. <add>--> <add> <add>### What do you see instead? <add> <add><!-- <add>If possible please provide textual output instead of screenshots. <add>--> <add> <add>### Additional information <add> <add><!-- <add>Tell us anything else you think we should know. <add>-->
1
Text
Text
improve grammar and readability
d638b3cd53545d441cd1639bed8b16a7060c0b1e
<ide><path>readme.md <ide> <ide> ## About Laravel <ide> <del>Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as: <add>Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as: <ide> <ide> - [Simple, fast routing engine](https://laravel.com/docs/routing). <ide> - [Powerful dependency injection container](https://laravel.com/docs/container). <ide> Laravel is a web application framework with expressive, elegant syntax. We belie <ide> - [Robust background job processing](https://laravel.com/docs/queues). <ide> - [Real-time event broadcasting](https://laravel.com/docs/broadcasting). <ide> <del>Laravel is accessible, yet powerful, providing tools needed for large, robust applications. <add>Laravel is accessible, powerful, and provides tools required for large, robust applications. <ide> <ide> ## Learning Laravel <ide> <del>Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of any modern web application framework, making it a breeze to get started learning the framework. <add>Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application framework, making it a breeze to get started with the framework. <ide> <del>If you're not in the mood to read, [Laracasts](https://laracasts.com) contains over 1100 video tutorials on a range of topics including Laravel, modern PHP, unit testing, JavaScript, and more. Boost the skill level of yourself and your entire team by digging into our comprehensive video library. <add>If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains over 1100 video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost you and your team's skills by digging into our comprehensive video library. <ide> <ide> ## Laravel Sponsors <ide> <del>We would like to extend our thanks to the following sponsors for helping fund on-going Laravel development. If you are interested in becoming a sponsor, please visit the Laravel [Patreon page](https://patreon.com/taylorotwell): <add>We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the Laravel [Patreon page](https://patreon.com/taylorotwell). <ide> <ide> - **[Vehikl](https://vehikl.com/)** <ide> - **[Tighten Co.](https://tighten.co)** <ide> If you discover a security vulnerability within Laravel, please send an e-mail t <ide> <ide> ## License <ide> <del>The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT). <add>The Laravel framework is open-source software licensed under the [MIT license](https://opensource.org/licenses/MIT).
1
Python
Python
add conversion interfaces for more conv layers
16feb385e5a84c8298b909fb7a8719ca9a99d105
<ide><path>keras/layers/convolutional.py <ide> class Conv1D(_Conv): <ide> `steps` value might have changed due to padding or strides. <ide> """ <ide> <add> @interfaces.legacy_conv1d_support <ide> def __init__(self, filters, <ide> kernel_size, <ide> strides=1, <ide> class Conv3D(_Conv): <ide> `new_conv_dim1`, `new_conv_dim2` and `new_conv_dim3` values might have changed due to padding. <ide> """ <ide> <add> @interfaces.legacy_conv3d_support <ide> def __init__(self, filters, <ide> kernel_size, <ide> strides=(1, 1, 1), <ide> class SeparableConv2D(Conv2D): <ide> `rows` and `cols` values might have changed due to padding. <ide> """ <ide> <add> @interfaces.legacy_separable_conv2d_support <ide> def __init__(self, filters, <ide> kernel_size, <ide> strides=(1, 1), <ide><path>keras/layers/recurrent.py <ide> def call(self, inputs, mask=None, initial_state=None, training=None): <ide> <ide> if len(initial_states) != len(self.states): <ide> raise ValueError('Layer has ' + str(len(self.states)) + <del> ' but was passed ' + str(len(initial_states)) + <add> ' states but was passed ' + <add> str(len(initial_states)) + <ide> ' initial states.') <ide> input_shape = K.int_shape(inputs) <ide> if self.unroll and input_shape[1] is None: <ide><path>keras/legacy/interfaces.py <ide> def lstm_args_preprocessor(args, kwargs): <ide> 'default': None}}) <ide> <ide> <add>def conv1d_args_preprocessor(args, kwargs): <add> if 'input_dim' in kwargs: <add> if 'input_length' in kwargs: <add> length = kwargs.pop('input_length') <add> else: <add> length = None <add> input_shape = (length, kwargs.pop('input_dim')) <add> kwargs['input_shape'] = input_shape <add> return args, kwargs, [('input_shape', 'input_dim')] <add> <add>legacy_conv1d_support = generate_legacy_interface( <add> allowed_positional_args=['filters', 'kernel_size'], <add> conversions=[('nb_filter', 'filters'), <add> ('filter_length', 'kernel_size'), <add> ('subsample_length', 'strides'), <add> ('border_mode', 'padding'), <add> ('init', 'kernel_initializer'), <add> ('W_regularizer', 'kernel_regularizer'), <add> ('b_regularizer', 'bias_regularizer'), <add> ('W_constraint', 'kernel_constraint'), <add> ('b_constraint', 'bias_constraint'), <add> ('bias', 'use_bias')], <add> preprocessor=conv1d_args_preprocessor) <add> <add> <ide> def conv2d_args_preprocessor(args, kwargs): <ide> if len(args) > 4: <ide> raise TypeError('Layer can receive at most 3 positional arguments.') <ide> def conv2d_args_preprocessor(args, kwargs): <ide> 'It seems that you are using the Keras 2 ' <ide> 'and you are passing both `kernel_size` and `strides` ' <ide> 'as integer positional arguments. For safety reasons, ' <del> 'this is disallowed. Pass `strides` as a keyword arugment ' <del> 'instead.') <add> 'this is disallowed. Pass `strides` ' <add> 'as a keyword argument instead.') <ide> kernel_size = (args[2], args[3]) <ide> args = [args[0], args[1], kernel_size] <ide> elif len(args) == 3 and isinstance(args[2], int): <ide> def conv2d_args_preprocessor(args, kwargs): <ide> <ide> legacy_conv2d_support = generate_legacy_interface( <ide> allowed_positional_args=['filters', 'kernel_size'], <del> conversions=[('nb_filters', 'filters'), <add> conversions=[('nb_filter', 'filters'), <ide> ('subsample', 'strides'), <ide> ('border_mode', 'padding'), <ide> ('dim_ordering', 'data_format'), <ide> def conv2d_args_preprocessor(args, kwargs): <ide> 'th': 'channels_first', <ide> 'default': None}}, <ide> preprocessor=conv2d_args_preprocessor) <add> <add> <add>def separable_conv2d_args_preprocessor(args, kwargs): <add> if 'init' in kwargs: <add> init = kwargs.pop('init') <add> kwargs['depthwise_initializer'] = init <add> kwargs['pointwise_initializer'] = init <add> return conv2d_args_preprocessor(args, kwargs) <add> <add>legacy_separable_conv2d_support = generate_legacy_interface( <add> allowed_positional_args=['filters', 'kernel_size'], <add> conversions=[('nb_filter', 'filters'), <add> ('subsample', 'strides'), <add> ('border_mode', 'padding'), <add> ('dim_ordering', 'data_format'), <add> ('b_regularizer', 'bias_regularizer'), <add> ('b_constraint', 'bias_constraint'), <add> ('bias', 'use_bias')], <add> value_conversions={'dim_ordering': {'tf': 'channels_last', <add> 'th': 'channels_first', <add> 'default': None}}, <add> preprocessor=separable_conv2d_args_preprocessor) <add> <add> <add>def conv3d_args_preprocessor(args, kwargs): <add> if len(args) > 5: <add> raise TypeError('Layer can receive at most 4 positional arguments.') <add> if len(args) == 5: <add> if isinstance(args[2], int) and isinstance(args[3], int) and isinstance(args[4], int): <add> kernel_size = (args[2], args[3], args[4]) <add> args = [args[0], args[1], kernel_size] <add> elif len(args) == 4 and isinstance(args[3], int): <add> if isinstance(args[2], int) and isinstance(args[3], int): <add> new_keywords = ['padding', 'strides', 'data_format'] <add> for kwd in new_keywords: <add> if kwd in kwargs: <add> raise ValueError( <add> 'It seems that you are using the Keras 2 ' <add> 'and you are passing both `kernel_size` and `strides` ' <add> 'as integer positional arguments. For safety reasons, ' <add> 'this is disallowed. Pass `strides` ' <add> 'as a keyword argument instead.') <add> if 'kernel_dim3' in kwargs: <add> kernel_size = (args[2], args[3], kwargs.pop('kernel_dim3')) <add> args = [args[0], args[1], kernel_size] <add> elif len(args) == 3: <add> if 'kernel_dim2' in kwargs and 'kernel_dim3' in kwargs: <add> kernel_size = (args[2], <add> kwargs.pop('kernel_dim2'), <add> kwargs.pop('kernel_dim3')) <add> args = [args[0], args[1], kernel_size] <add> elif len(args) == 2: <add> if 'kernel_dim1' in kwargs and 'kernel_dim2' in kwargs and 'kernel_dim3' in kwargs: <add> kernel_size = (kwargs.pop('kernel_dim1'), <add> kwargs.pop('kernel_dim2'), <add> kwargs.pop('kernel_dim3')) <add> args = [args[0], args[1], kernel_size] <add> return args, kwargs, [('kernel_size', 'kernel_dim*')] <add> <add>legacy_conv3d_support = generate_legacy_interface( <add> allowed_positional_args=['filters', 'kernel_size'], <add> conversions=[('nb_filter', 'filters'), <add> ('subsample', 'strides'), <add> ('border_mode', 'padding'), <add> ('dim_ordering', 'data_format'), <add> ('init', 'kernel_initializer'), <add> ('W_regularizer', 'kernel_regularizer'), <add> ('b_regularizer', 'bias_regularizer'), <add> ('W_constraint', 'kernel_constraint'), <add> ('b_constraint', 'bias_constraint'), <add> ('bias', 'use_bias')], <add> value_conversions={'dim_ordering': {'tf': 'channels_last', <add> 'th': 'channels_first', <add> 'default': None}}, <add> preprocessor=conv3d_args_preprocessor) <ide><path>tests/keras/legacy/interface_test.py <ide> def test_conv2d_legacy_interface(): <ide> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config()) <ide> <ide> <add>@keras_test <add>def test_conv1d_legacy_interface(): <add> old_layer = keras.layers.Convolution1D(5, <add> filter_length=3, <add> input_dim=3, <add> input_length=4, <add> name='conv') <add> new_layer = keras.layers.Conv1D(5, 3, name='conv', input_shape=(4, 3)) <add> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config()) <add> <add> old_layer = keras.layers.Convolution1D(5, 3, <add> init='normal', <add> subsample_length=2, <add> border_mode='valid', <add> W_regularizer='l1', <add> b_regularizer='l2', <add> W_constraint='maxnorm', <add> b_constraint='unitnorm', <add> name='conv') <add> new_layer = keras.layers.Conv1D(5, 3, <add> kernel_initializer='normal', <add> strides=2, <add> padding='valid', <add> kernel_regularizer='l1', <add> bias_regularizer='l2', <add> kernel_constraint='max_norm', <add> bias_constraint='unit_norm', <add> name='conv') <add> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config()) <add> <add> <add>@keras_test <add>def test_separable_conv2d_legacy_interface(): <add> old_layer = keras.layers.SeparableConv2D(5, 3, 3, name='conv') <add> new_layer = keras.layers.SeparableConv2D(5, (3, 3), name='conv') <add> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config()) <add> <add> old_layer = keras.layers.SeparableConv2D(5, 3, nb_col=3, name='conv') <add> new_layer = keras.layers.SeparableConv2D(5, (3, 3), name='conv') <add> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config()) <add> <add> old_layer = keras.layers.SeparableConv2D(5, nb_row=3, nb_col=3, name='conv') <add> new_layer = keras.layers.SeparableConv2D(5, (3, 3), name='conv') <add> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config()) <add> <add> old_layer = keras.layers.SeparableConv2D(5, 3, 3, <add> init='normal', <add> subsample=(2, 2), <add> border_mode='valid', <add> dim_ordering='th', <add> depthwise_regularizer='l1', <add> b_regularizer='l2', <add> depthwise_constraint='maxnorm', <add> b_constraint='unitnorm', <add> name='conv') <add> new_layer = keras.layers.SeparableConv2D(5, (3, 3), <add> depthwise_initializer='normal', <add> pointwise_initializer='normal', <add> strides=(2, 2), <add> padding='valid', <add> depthwise_regularizer='l1', <add> bias_regularizer='l2', <add> depthwise_constraint='max_norm', <add> bias_constraint='unit_norm', <add> data_format='channels_first', <add> name='conv') <add> old_config = json.dumps(old_layer.get_config()) <add> new_config = json.dumps(new_layer.get_config()) <add> assert old_config == new_config <add> <add> <add>@keras_test <add>def test_conv3d_legacy_interface(): <add> old_layer = keras.layers.Convolution3D(5, 3, 3, 4, name='conv') <add> new_layer = keras.layers.Conv3D(5, (3, 3, 4), name='conv') <add> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config()) <add> <add> old_layer = keras.layers.Convolution3D(5, 3, 3, kernel_dim3=4, name='conv') <add> new_layer = keras.layers.Conv3D(5, (3, 3, 4), name='conv') <add> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config()) <add> <add> old_layer = keras.layers.Convolution3D(5, 3, <add> kernel_dim2=3, <add> kernel_dim3=4, <add> name='conv') <add> new_layer = keras.layers.Conv3D(5, (3, 3, 4), name='conv') <add> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config()) <add> <add> old_layer = keras.layers.Convolution3D(5, <add> kernel_dim1=3, <add> kernel_dim2=3, <add> kernel_dim3=4, <add> name='conv') <add> new_layer = keras.layers.Conv3D(5, (3, 3, 4), name='conv') <add> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config()) <add> <add> old_layer = keras.layers.Convolution3D(5, 3, 3, 4, <add> init='normal', <add> subsample=(2, 2, 2), <add> border_mode='valid', <add> dim_ordering='th', <add> W_regularizer='l1', <add> b_regularizer='l2', <add> W_constraint='maxnorm', <add> b_constraint='unitnorm', <add> name='conv') <add> new_layer = keras.layers.Conv3D(5, (3, 3, 4), <add> kernel_initializer='normal', <add> strides=(2, 2, 2), <add> padding='valid', <add> kernel_regularizer='l1', <add> bias_regularizer='l2', <add> kernel_constraint='max_norm', <add> bias_constraint='unit_norm', <add> data_format='channels_first', <add> name='conv') <add> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config()) <add> <add> <ide> if __name__ == '__main__': <ide> pytest.main([__file__])
4
Ruby
Ruby
use new hash syntax in generated gemfile
5eb32af28b16cf8d26ce291232239892154227d4
<ide><path>railties/lib/rails/generators/app_base.rb <ide> def comment_if(value) <ide> def rails_gemfile_entry <ide> if options.dev? <ide> <<-GEMFILE.strip_heredoc <del> gem 'rails', :path => '#{Rails::Generators::RAILS_DEV_PATH}' <del> gem 'journey', :github => 'rails/journey' <del> gem 'arel', :github => 'rails/arel' <del> gem 'active_record_deprecated_finders', :github => 'rails/active_record_deprecated_finders' <add> gem 'rails', path: '#{Rails::Generators::RAILS_DEV_PATH}' <add> gem 'journey', github: 'rails/journey' <add> gem 'arel', github: 'rails/arel' <add> gem 'active_record_deprecated_finders', github: 'rails/active_record_deprecated_finders' <ide> GEMFILE <ide> elsif options.edge? <ide> <<-GEMFILE.strip_heredoc <del> gem 'rails', :github => 'rails/rails' <del> gem 'journey', :github => 'rails/journey' <del> gem 'arel', :github => 'rails/arel' <del> gem 'active_record_deprecated_finders', :github => 'rails/active_record_deprecated_finders' <add> gem 'rails', github: 'rails/rails' <add> gem 'journey', github: 'rails/journey' <add> gem 'arel', github: 'rails/arel' <add> gem 'active_record_deprecated_finders', github: 'rails/active_record_deprecated_finders' <ide> GEMFILE <ide> else <ide> <<-GEMFILE.strip_heredoc <ide> gem 'rails', '#{Rails::VERSION::STRING}' <ide> <ide> # Bundle edge Rails instead: <del> # gem 'rails', :github => 'rails/rails' <add> # gem 'rails', github: 'rails/rails' <ide> GEMFILE <ide> end <ide> end <ide> def assets_gemfile_entry <ide> # Gems used only for assets and not required <ide> # in production environments by default. <ide> group :assets do <del> gem 'sprockets-rails', :git => 'https://github.com/rails/sprockets-rails.git' <del> gem 'sass-rails', :git => 'https://github.com/rails/sass-rails.git' <del> gem 'coffee-rails', :git => 'https://github.com/rails/coffee-rails.git' <add> gem 'sprockets-rails', github: 'rails/sprockets-rails' <add> gem 'sass-rails', github: 'rails/sass-rails' <add> gem 'coffee-rails', github: 'rails/coffee-rails' <ide> <ide> # See https://github.com/sstephenson/execjs#readme for more supported runtimes <ide> #{javascript_runtime_gemfile_entry} <ide> def assets_gemfile_entry <ide> # Gems used only for assets and not required <ide> # in production environments by default. <ide> group :assets do <del> gem 'sprockets-rails', :git => 'https://github.com/rails/sprockets-rails.git' <add> gem 'sprockets-rails', github: 'rails/sprockets-rails' <ide> gem 'sass-rails', '~> 4.0.0.beta' <ide> gem 'coffee-rails', '~> 4.0.0.beta' <ide> <ide> def javascript_runtime_gemfile_entry <ide> if defined?(JRUBY_VERSION) <ide> "gem 'therubyrhino'\n" <ide> else <del> "# gem 'therubyracer', :platform => :ruby\n" <add> "# gem 'therubyracer', platform: :ruby\n" <ide> end <ide> end <ide>
1
Ruby
Ruby
handle "manifest unknown"
ae91ec277231a5f3df42af8c27c555a0cee3403e
<ide><path>Library/Homebrew/github_packages.rb <ide> def upload_bottle(user, token, skopeo, formula_full_name, bottle_hash, keep_old: <ide> inspect_result = system_command(skopeo, print_stderr: false, args: inspect_args) <ide> <ide> # Order here is important <del> if !inspect_result.status.success? && inspect_result.stderr.exclude?("name unknown") <add> if !inspect_result.status.success? && !inspect_result.stderr.match?(/(name|manifest) unknown/) <ide> # We got an error, and it was not about the tag or package being unknown. <ide> if warn_on_error <ide> opoo "#{image_uri} inspection returned an error, skipping upload!\n#{inspect_result.stderr}"
1
Python
Python
change hdf5matrix so start and end are optional
c455a19f8e303b5ab1530fe98808808a30c77647
<ide><path>keras/utils/io_utils.py <ide> class HDF5Matrix(): <ide> ''' <ide> refs = defaultdict(int) <ide> <del> def __init__(self, datapath, dataset, start, end, normalizer=None): <add> def __init__(self, datapath, dataset, start=0, end=None, normalizer=None): <ide> import h5py <ide> <ide> if datapath not in list(self.refs.keys()): <ide> f = h5py.File(datapath) <ide> self.refs[datapath] = f <ide> else: <ide> f = self.refs[datapath] <del> self.start = start <del> self.end = end <ide> self.data = f[dataset] <add> self.start = start <add> if end is None: <add> self.end = self.data.shape[0] <add> else: <add> self.end = end <ide> self.normalizer = normalizer <ide> <ide> def __len__(self):
1
Ruby
Ruby
remove this conditional
a64dba1dc59efec39080b8e142894060e2e8d0bb
<ide><path>railties/test/application/rake/dbs_test.rb <ide> def db_create_and_drop(expected_database) <ide> output = rails("db:create") <ide> assert_match(/Created database/, output) <ide> assert File.exist?(expected_database) <del> assert_equal expected_database, ActiveRecord::Base.connection_config[:database] if environment_loaded <add> assert_equal expected_database, ActiveRecord::Base.connection_config[:database] <ide> output = rails("db:drop") <ide> assert_match(/Dropped database/, output) <ide> assert_not File.exist?(expected_database)
1
PHP
PHP
send mail support in mail service provider
5860d05be4e062a2d0525a7f4941c6b7310ce779
<ide><path>src/Illuminate/Mail/MailServiceProvider.php <ide> use Illuminate\Support\ServiceProvider; <ide> use Swift_SmtpTransport as SmtpTransport; <ide> use Swift_MailTransport as MailTransport; <add>use Swift_SendmailTransport as SendmailTransport; <ide> <ide> class MailServiceProvider extends ServiceProvider { <ide> <ide> protected function registerSwiftTransport($config) <ide> case 'smtp': <ide> return $this->registerSmtpTransport($config); <ide> <add> case 'sendmail': <add> return $this->registerSendmailTransport($config); <add> <ide> case 'mail': <ide> return $this->registerMailTransport($config); <ide> <ide> protected function registerSmtpTransport($config) <ide> }); <ide> } <ide> <add> /** <add> * Register the Sendmail Swift Transport instance. <add> * <add> * @param array $config <add> * @return void <add> */ <add> protected function registerSendmailTransport($config) <add> { <add> $this->app['swift.transport'] = $this->app->share(function($app) use ($config) <add> { <add> return SendmailTransport::newInstance($config['sendmail']); <add> }); <add> } <add> <ide> /** <ide> * Register the Mail Swift Transport instance. <ide> *
1
Ruby
Ruby
allow zero parameters
803ea4ed1a8d7c4710f7b0e91f393c2ec1970ba1
<ide><path>Library/Homebrew/tab.rb <ide> def source_modified_time <ide> Time.at(super) <ide> end <ide> <del> def to_json(_opts) <add> def to_json(options = nil) <ide> attributes = { <ide> "homebrew_version" => homebrew_version, <ide> "used_options" => used_options.as_flags, <ide> def to_json(_opts) <ide> "source" => source, <ide> } <ide> <del> JSON.generate(attributes) <add> JSON.generate(attributes, options) <ide> end <ide> <ide> def write
1
Javascript
Javascript
display the actual default `accept` header
b3a3ed34b9c9d965233c0adc4fd4605fbe7c05d3
<ide><path>src/ng/http.js <ide> function $HttpProvider() { <ide> * object, which currently contains this default configuration: <ide> * <ide> * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): <del> * - `Accept: application/json, text/plain, * / *` <add> * - <code>Accept: application/json, text/plain, \*&#65279;/&#65279;\*</code> <ide> * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) <ide> * - `Content-Type: application/json` <ide> * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
1
Javascript
Javascript
add a controltext function to menubutton
4388beae910013f98e0647891df695d0a0a48270
<ide><path>src/js/menu/menu-button.js <ide> class MenuButton extends Component { <ide> return `vjs-menu-button ${menuButtonClass} ${super.buildCSSClass()}`; <ide> } <ide> <add> /** <add> * Get or set the localized control text that will be used for accessibility. <add> * <add> * > NOTE: This will come from the internal `menuButton_` element. <add> * <add> * @param {string} [text] <add> * Control text for element. <add> * <add> * @param {Element} [el=this.menuButton_.el()] <add> * Element to set the title on. <add> * <add> * @return {string} <add> * - The control text when getting <add> */ <add> controlText(text, el = this.menuButton_.el()) { <add> return this.menuButton_.controlText(text, el); <add> } <add> <ide> /** <ide> * Handle a click on a `MenuButton`. <ide> * See {@link ClickableComponent#handleClick} for instances where this is called.
1
Javascript
Javascript
add linear easing to animationutils
a36da5130bbf023ab3a8ece77a81c7a5298541e7
<ide><path>Libraries/Animation/AnimationUtils.js <ide> type EasingFunction = (t: number) => number; <ide> <ide> var defaults = { <add> linear: function(t: number): number { <add> return t; <add> }, <ide> easeInQuad: function(t: number): number { <ide> return t * t; <ide> },
1
Python
Python
add benchmark tests for numpy.random.randint
931e2d1e8ba3fd6b129a6d74e3a1ad9984c1938a
<ide><path>benchmarks/benchmarks/bench_random.py <ide> from .common import Benchmark <ide> <ide> import numpy as np <add>from numpy.lib import NumpyVersion <ide> <ide> <ide> class Random(Benchmark): <ide> def setup(self): <ide> <ide> def time_100000(self): <ide> np.random.shuffle(self.a) <add> <add> <add>class Randint(Benchmark): <add> <add> def time_randint_fast(self): <add> """Compare to uint32 below""" <add> np.random.randint(0, 2**30, size=10**5) <add> <add> def time_randint_slow(self): <add> """Compare to uint32 below""" <add> np.random.randint(0, 2**30 + 1, size=10**5) <add> <add> <add>class Randint_dtype(Benchmark): <add> high = { <add> 'bool': 1, <add> 'uint8': 2**7, <add> 'uint16': 2**15, <add> 'uint32': 2**31, <add> 'uint64': 2**63 <add> } <add> <add> param_names = ['dtype'] <add> params = ['bool', 'uint8', 'uint16', 'uint32', 'uint64'] <add> <add> def setup(self, name): <add> if NumpyVersion(np.__version__) < '1.11.0.dev0': <add> raise NotImplementedError <add> <add> def time_randint_fast(self, name): <add> high = self.high[name] <add> np.random.randint(0, high, size=10**5, dtype=name) <add> <add> def time_randint_slow(self, name): <add> high = self.high[name] <add> np.random.randint(0, high + 1, size=10**5, dtype=name) <add>
1
PHP
PHP
improve error message for missing associations
f680c0824c117c90357a287a9b38b306c4de1aa9
<ide><path>src/ORM/Table.php <ide> public function __get($property) <ide> $association = $this->_associations->get($property); <ide> if (!$association) { <ide> throw new RuntimeException(sprintf( <del> 'Table "%s" is not associated with "%s"', <add> 'Undefined property `%s`. ' . <add> 'You have tried to use the `%s` property on %s, but that association does not exist.', <add> $property, <add> $property, <ide> get_class($this), <del> $property <ide> )); <ide> } <ide> <ide><path>tests/TestCase/ORM/AssociationProxyTest.php <ide> public function testAssociationAsProperty() <ide> public function testGetBadAssociation() <ide> { <ide> $this->expectException(\RuntimeException::class); <del> $this->expectExceptionMessage('Table "Cake\ORM\Table" is not associated with "posts"'); <add> $this->expectExceptionMessage('association does not exist'); <ide> $articles = $this->getTableLocator()->get('articles'); <ide> $articles->posts; <ide> }
2
Java
Java
prepare undertow 1.3.0 compatibility
42588cb03e484565c24298ac834e8d0921dee9ec
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/UndertowXhrTransport.java <ide> import io.undertow.util.HttpString; <ide> import io.undertow.util.Methods; <ide> import io.undertow.util.StringReadChannelListener; <del>import org.xnio.ByteBufferSlicePool; <ide> import org.xnio.ChannelListener; <ide> import org.xnio.ChannelListeners; <ide> import org.xnio.IoUtils; <ide> import org.xnio.OptionMap; <ide> import org.xnio.Options; <del>import org.xnio.Pool; <del>import org.xnio.Pooled; <ide> import org.xnio.Xnio; <ide> import org.xnio.XnioWorker; <ide> import org.xnio.channels.StreamSinkChannel; <ide> public class UndertowXhrTransport extends AbstractXhrTransport implements XhrTra <ide> <ide> private final XnioWorker worker; <ide> <del> private final Pool<ByteBuffer> bufferPool; <add> @SuppressWarnings("deprecation") <add> private final org.xnio.Pool<ByteBuffer> bufferPool; <ide> <ide> <ide> public UndertowXhrTransport() throws IOException { <ide> this(OptionMap.builder().parse(Options.WORKER_NAME, "SockJSClient").getMap()); <ide> } <ide> <add> @SuppressWarnings("deprecation") <ide> public UndertowXhrTransport(OptionMap optionMap) throws IOException { <ide> Assert.notNull(optionMap, "OptionMap is required"); <ide> this.optionMap = optionMap; <ide> this.httpClient = UndertowClient.getInstance(); <ide> this.worker = Xnio.getInstance().createWorker(optionMap); <del> this.bufferPool = new ByteBufferSlicePool(1048, 1048); <add> this.bufferPool = new org.xnio.ByteBufferSlicePool(1048, 1048); <ide> } <ide> <ide> <ide> private ClientCallback<ClientExchange> createRequestCallback(final String body, <ide> public void completed(ClientExchange result) { <ide> result.setResponseListener(new ClientCallback<ClientExchange>() { <ide> @Override <add> @SuppressWarnings("deprecation") <ide> public void completed(final ClientExchange result) { <ide> responses.add(result.getResponse()); <ide> new StringReadChannelListener(result.getConnection().getBufferPool()) { <ide> public void setup(StreamSourceChannel channel) { <ide> } <ide> <ide> @Override <add> @SuppressWarnings("deprecation") <ide> public void handleEvent(StreamSourceChannel channel) { <ide> if (this.session.isDisconnected()) { <ide> if (logger.isDebugEnabled()) { <ide> public void handleEvent(StreamSourceChannel channel) { <ide> throw new SockJsException("Session closed.", this.session.getId(), null); <ide> } <ide> <del> Pooled<ByteBuffer> pooled = this.connection.getBufferPool().allocate(); <add> org.xnio.Pooled<ByteBuffer> pooled = this.connection.getBufferPool().allocate(); <ide> try { <ide> int r; <ide> do { <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/UndertowTestServer.java <ide> import org.springframework.web.context.WebApplicationContext; <ide> import org.springframework.web.servlet.DispatcherServlet; <ide> <del>import org.xnio.ByteBufferSlicePool; <ide> import org.xnio.OptionMap; <ide> import org.xnio.Xnio; <ide> <ide> public int getPort() { <ide> } <ide> <ide> @Override <add> @SuppressWarnings("deprecation") <ide> public void deployConfig(WebApplicationContext wac, Filter... filters) { <ide> Assert.state(this.port != -1, "setup() was never called"); <ide> DispatcherServletInstanceFactory servletFactory = new DispatcherServletInstanceFactory(wac); <ide> public void deployConfig(WebApplicationContext wac, Filter... filters) { <ide> WebSocketDeploymentInfo info = new WebSocketDeploymentInfo(); <ide> try { <ide> info.setWorker(Xnio.getInstance().createWorker(OptionMap.EMPTY)); <del> info.setBuffers(new ByteBufferSlicePool(1024,1024)); <add> info.setBuffers(new org.xnio.ByteBufferSlicePool(1024,1024)); <ide> } <ide> catch (IOException ex) { <ide> throw new IllegalStateException(ex);
2
PHP
PHP
update docblocks to use type "iterator"
f45de4e27e55aec0de99eceb32d6246719bfb7d0
<ide><path>src/Collection/Collection.php <ide> class Collection extends IteratorIterator implements CollectionInterface, Serial <ide> /** <ide> * Constructor. You can provide an array or any traversable object <ide> * <del> * @param array|\Traversable $items Items. <add> * @param iterable $items Items. <ide> * @throws \InvalidArgumentException If passed incorrect type for items. <ide> */ <ide> public function __construct(iterable $items) <ide><path>src/Collection/CollectionInterface.php <ide> public function last(); <ide> * Returns a new collection as the result of concatenating the list of elements <ide> * in this collection with the passed list of elements <ide> * <del> * @param array|\Traversable $items Items list. <add> * @param iterable $items Items list. <ide> * @return \Cake\Collection\CollectionInterface <ide> */ <ide> public function append($items): CollectionInterface; <ide> public function through(callable $handler): CollectionInterface; <ide> * $collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]] <ide> * ``` <ide> * <del> * @param array|\Traversable ...$items The collections to zip. <add> * @param iterable ...$items The collections to zip. <ide> * @return \Cake\Collection\CollectionInterface <ide> */ <ide> public function zip(iterable $items): CollectionInterface; <ide> public function zip(iterable $items): CollectionInterface; <ide> * $zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)] <ide> * ``` <ide> * <del> * @param array|\Traversable ...$items The collections to zip. <add> * @param iterable ...$items The collections to zip. <ide> * @param callable $callable The function to use for zipping the elements together. <ide> * @return \Cake\Collection\CollectionInterface <ide> */ <ide><path>src/Collection/Iterator/BufferedIterator.php <ide> class BufferedIterator extends Collection implements Countable, Serializable <ide> * Maintains an in-memory cache of the results yielded by the internal <ide> * iterator. <ide> * <del> * @param array|\Traversable $items The items to be filtered. <add> * @param iterable $items The items to be filtered. <ide> */ <ide> public function __construct(iterable $items) <ide> { <ide><path>src/Collection/Iterator/ExtractIterator.php <ide> class ExtractIterator extends Collection <ide> * $extractor = new ExtractIterator($items, 'comment.user.name''); <ide> * ``` <ide> * <del> * @param array|\Traversable $items The list of values to iterate <add> * @param iterable $items The list of values to iterate <ide> * @param string $path a dot separated string symbolizing the path to follow <ide> * inside the hierarchy of each value so that the column can be extracted. <ide> */ <ide><path>src/Collection/Iterator/InsertIterator.php <ide> class InsertIterator extends Collection <ide> * Constructs a new collection that will dynamically add properties to it out of <ide> * the values found in $values. <ide> * <del> * @param array|\Traversable $into The target collection to which the values will <add> * @param iterable $into The target collection to which the values will <ide> * be inserted at the specified path. <ide> * @param string $path A dot separated list of properties that need to be traversed <ide> * to insert the value into the target collection. <del> * @param array|\Traversable $values The source collection from which the values will <add> * @param iterable $values The source collection from which the values will <ide> * be inserted at the specified path. <ide> */ <ide> public function __construct(iterable $into, $path, iterable $values) <ide><path>src/Collection/Iterator/NestIterator.php <ide> class NestIterator extends Collection implements RecursiveIterator <ide> /** <ide> * Constructor <ide> * <del> * @param array|\Traversable $items Collection items. <add> * @param iterable $items Collection items. <ide> * @param string|callable $nestKey the property that contains the nested items <ide> * If a callable is passed, it should return the childrens for the passed item <ide> */ <ide><path>src/Collection/Iterator/ReplaceIterator.php <ide> class ReplaceIterator extends Collection <ide> * in the current iteration, the key of the element and the passed $items iterator <ide> * as arguments, in that order. <ide> * <del> * @param array|\Traversable $items The items to be filtered. <add> * @param iterable $items The items to be filtered. <ide> * @param callable $callback Callback. <ide> */ <ide> public function __construct(iterable $items, callable $callback) <ide><path>src/Collection/Iterator/SortIterator.php <ide> class SortIterator extends Collection <ide> * element. Please note that the callback function could be called more than once <ide> * per element. <ide> * <del> * @param array|\Traversable $items The values to sort <add> * @param iterable $items The values to sort <ide> * @param callable|string $callback A function used to return the actual value to <ide> * be compared. It can also be a string representing the path to use to fetch a <ide> * column or property in each element <ide><path>src/Collection/Iterator/StoppableIterator.php <ide> class StoppableIterator extends Collection <ide> * in the current iteration, the key of the element and the passed $items iterator <ide> * as arguments, in that order. <ide> * <del> * @param array|\Traversable $items The list of values to iterate <add> * @param iterable $items The list of values to iterate <ide> * @param callable $condition A function that will be called for each item in <ide> * the collection, if the result evaluates to false, no more items will be <ide> * yielded from this iterator. <ide><path>src/Collection/Iterator/UnfoldIterator.php <ide> class UnfoldIterator extends IteratorIterator implements RecursiveIterator <ide> * Creates the iterator that will generate child iterators from each of the <ide> * elements it was constructed with. <ide> * <del> * @param array|\Traversable $items The list of values to iterate <add> * @param iterable $items The list of values to iterate <ide> * @param callable $unfolder A callable function that will receive the <ide> * current item and key. It must return an array or Traversable object <ide> * out of which the nested iterators will be yielded. <ide><path>src/Collection/functions.php <ide> /** <ide> * Returns a new Cake\Collection\Collection object wrapping the passed argument. <ide> * <del> * @param \Traversable|array $items The items from which the collection will be built. <add> * @param iterable $items The items from which the collection will be built. <ide> * @return \Cake\Collection\Collection <ide> */ <ide> function collection(iterable $items): CollectionInterface <ide><path>src/Database/Expression/Comparison.php <ide> protected function _bindValue($value, ValueBinder $generator, $type): string <ide> * Converts a traversable value into a set of placeholders generated by <ide> * $generator and separated by `,` <ide> * <del> * @param array|\Traversable $value the value to flatten <add> * @param iterable $value the value to flatten <ide> * @param \Cake\Database\ValueBinder $generator The value binder to use <ide> * @param string|array|null $type the type to cast values to <ide> * @return string <ide> protected function _flattenValue(iterable $value, $generator, $type = 'string'): <ide> * and all ExpressionInterface objects that could be found in the second <ide> * position. <ide> * <del> * @param array|\Traversable|\Cake\Database\ExpressionInterface $values The rows to insert <add> * @param iterable|\Cake\Database\ExpressionInterface $values The rows to insert <ide> * @return array <ide> */ <ide> protected function _collectExpressions($values): array <ide><path>src/Database/ValueBinder.php <ide> public function placeholder($token) <ide> * Creates unique named placeholders for each of the passed values <ide> * and binds them with the specified type. <ide> * <del> * @param array|\Traversable $values The list of values to be bound <add> * @param iterable $values The list of values to be bound <ide> * @param string $type The type with which all values will be bound <ide> * @return array with the placeholders to insert in the query <ide> */ <ide><path>src/ORM/Association/BelongsToMany.php <ide> public function saveAssociated(EntityInterface $entity, array $options = []) <ide> * <ide> * @param \Cake\Datasource\EntityInterface $parentEntity the source entity containing the target <ide> * entities to be saved. <del> * @param array|\Traversable $entities list of entities to persist in target table and to <add> * @param iterable $entities list of entities to persist in target table and to <ide> * link to the parent entity <ide> * @param array $options list of options accepted by `Table::save()` <ide> * @throws \InvalidArgumentException if the property representing the association <ide><path>src/ORM/Association/HasMany.php <ide> public function saveAssociated(EntityInterface $entity, array $options = []) <ide> * target entity, and the parent entity. <ide> * @param \Cake\Datasource\EntityInterface $parentEntity The source entity containing the target <ide> * entities to be saved. <del> * @param array|\Traversable $entities list of entities to persist in target table and to <add> * @param iterable $entities list of entities to persist in target table and to <ide> * link to the parent entity <ide> * @param array $options list of options accepted by `Table::save()`. <ide> * @return bool `true` on success, `false` otherwise. <ide><path>src/View/Form/EntityContext.php <ide> protected function _schemaDefault(array $parts) <ide> * Helper method used to extract all the primary key values out of an array, The <ide> * primary key column is guessed out of the provided $path array <ide> * <del> * @param array|\Traversable $values The list from which to extract primary keys from <add> * @param iterable $values The list from which to extract primary keys from <ide> * @param array $path Each one of the parts in a path for a field name <ide> * @return array|null <ide> */ <ide> protected function _extractMultiple($values, $path): ?array <ide> * <ide> * @param array|null $path Each one of the parts in a path for a field name <ide> * or null to get the entity passed in constructor context. <del> * @return \Cake\Datasource\EntityInterface|\Traversable|array|bool <add> * @return \Cake\Datasource\EntityInterface|iterable|bool <ide> * @throws \RuntimeException When properties cannot be read. <ide> */ <ide> public function entity(?array $path = null) <ide><path>src/View/Helper/FormHelper.php <ide> public function checkbox(string $fieldName, array $options = []) <ide> * the radio label will be 'empty'. Set this option to a string to control the label value. <ide> * <ide> * @param string $fieldName Name of a field, like this "modelname.fieldname" <del> * @param array|\Traversable $options Radio button options array. <add> * @param iterable $options Radio button options array. <ide> * @param array $attributes Array of attributes. <ide> * @return string Completed radio widget set. <ide> * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-radio-buttons <ide> public function submit(?string $caption = null, array $options = []): string <ide> * ``` <ide> * <ide> * @param string $fieldName Name attribute of the SELECT <del> * @param array|\Traversable|null $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the <add> * @param iterable|null $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the <ide> * SELECT element <ide> * @param array $attributes The HTML attributes of the select element. <ide> * @return string Formatted SELECT element <ide> public function select(string $fieldName, ?iterable $options = [], array $attrib <ide> * Can be used in place of a select box with the multiple attribute. <ide> * <ide> * @param string $fieldName Name attribute of the SELECT <del> * @param array|\Traversable $options Array of the OPTION elements <add> * @param iterable $options Array of the OPTION elements <ide> * (as 'value'=>'Text' pairs) to be used in the checkboxes element. <ide> * @param array $attributes The HTML attributes of the select element. <ide> * @return string Formatted SELECT element
17
Java
Java
make sourcehttpmessageconverter optional
1e98fb607a274fc3cc49c24902d7c269f2946514
<ide><path>spring-web/src/main/java/org/springframework/http/converter/support/AllEncompassingFormHttpMessageConverter.java <ide> import org.springframework.http.converter.smile.MappingJackson2SmileHttpMessageConverter; <ide> import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter; <ide> import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter; <del>import org.springframework.http.converter.xml.SourceHttpMessageConverter; <ide> import org.springframework.util.ClassUtils; <ide> <ide> /** <ide> public class AllEncompassingFormHttpMessageConverter extends FormHttpMessageConv <ide> <ide> public AllEncompassingFormHttpMessageConverter() { <ide> <del> try { <del> addPartConverter(new SourceHttpMessageConverter<>()); <del> } <del> catch (Error err) { <del> // Ignore when no TransformerFactory implementation is available <del> } <del> <ide> if (jaxb2Present && !jackson2XmlPresent) { <ide> addPartConverter(new Jaxb2RootElementHttpMessageConverter()); <ide> } <ide><path>spring-web/src/main/java/org/springframework/web/client/RestTemplate.java <ide> import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; <ide> import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter; <ide> import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter; <del>import org.springframework.http.converter.xml.SourceHttpMessageConverter; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.ClassUtils; <ide> public RestTemplate() { <ide> this.messageConverters.add(new StringHttpMessageConverter()); <ide> this.messageConverters.add(new ResourceHttpMessageConverter(false)); <ide> <del> try { <del> this.messageConverters.add(new SourceHttpMessageConverter<>()); <del> } <del> catch (Error err) { <del> // Ignore when no TransformerFactory implementation is available <del> } <del> <ide> this.messageConverters.add(new AllEncompassingFormHttpMessageConverter()); <ide> <ide> if (romePresent) { <ide><path>spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java <ide> import org.springframework.http.MockHttpInputMessage; <ide> import org.springframework.http.MockHttpOutputMessage; <ide> import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; <add>import org.springframework.http.converter.xml.SourceHttpMessageConverter; <ide> import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.MultiValueMap; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED; <add>import static org.springframework.http.MediaType.APPLICATION_JSON; <ide> import static org.springframework.http.MediaType.MULTIPART_FORM_DATA; <ide> import static org.springframework.http.MediaType.MULTIPART_MIXED; <ide> import static org.springframework.http.MediaType.TEXT_XML; <ide> * @author Arjen Poutsma <ide> * @author Rossen Stoyanchev <ide> * @author Sam Brannen <add> * @author Sebastien Deleuze <ide> */ <ide> public class FormHttpMessageConverterTests { <ide> <ide> public void writeForm() throws IOException { <ide> <ide> @Test <ide> public void writeMultipart() throws Exception { <add> <add> MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>(); <add> parts.add("name 1", "value 1"); <add> parts.add("name 2", "value 2+1"); <add> parts.add("name 2", "value 2+2"); <add> parts.add("name 3", null); <add> <add> Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg"); <add> parts.add("logo", logo); <add> <add> // SPR-12108 <add> Resource utf8 = new ClassPathResource("/org/springframework/http/converter/logo.jpg") { <add> @Override <add> public String getFilename() { <add> return "Hall\u00F6le.jpg"; <add> } <add> }; <add> parts.add("utf8", utf8); <add> <add> MyBean myBean = new MyBean(); <add> myBean.setString("foo"); <add> HttpHeaders entityHeaders = new HttpHeaders(); <add> entityHeaders.setContentType(APPLICATION_JSON); <add> HttpEntity<MyBean> entity = new HttpEntity<>(myBean, entityHeaders); <add> parts.add("json", entity); <add> <add> Map<String, String> parameters = new LinkedHashMap<>(2); <add> parameters.put("charset", StandardCharsets.UTF_8.name()); <add> parameters.put("foo", "bar"); <add> <add> MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); <add> this.converter.write(parts, new MediaType("multipart", "form-data", parameters), outputMessage); <add> <add> final MediaType contentType = outputMessage.getHeaders().getContentType(); <add> assertThat(contentType.getParameters()).containsKeys("charset", "boundary", "foo"); // gh-21568, gh-25839 <add> <add> // see if Commons FileUpload can read what we wrote <add> FileUpload fileUpload = new FileUpload(); <add> fileUpload.setFileItemFactory(new DiskFileItemFactory()); <add> RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage); <add> List<FileItem> items = fileUpload.parseRequest(requestContext); <add> assertThat(items.size()).isEqualTo(6); <add> FileItem item = items.get(0); <add> assertThat(item.isFormField()).isTrue(); <add> assertThat(item.getFieldName()).isEqualTo("name 1"); <add> assertThat(item.getString()).isEqualTo("value 1"); <add> <add> item = items.get(1); <add> assertThat(item.isFormField()).isTrue(); <add> assertThat(item.getFieldName()).isEqualTo("name 2"); <add> assertThat(item.getString()).isEqualTo("value 2+1"); <add> <add> item = items.get(2); <add> assertThat(item.isFormField()).isTrue(); <add> assertThat(item.getFieldName()).isEqualTo("name 2"); <add> assertThat(item.getString()).isEqualTo("value 2+2"); <add> <add> item = items.get(3); <add> assertThat(item.isFormField()).isFalse(); <add> assertThat(item.getFieldName()).isEqualTo("logo"); <add> assertThat(item.getName()).isEqualTo("logo.jpg"); <add> assertThat(item.getContentType()).isEqualTo("image/jpeg"); <add> assertThat(item.getSize()).isEqualTo(logo.getFile().length()); <add> <add> item = items.get(4); <add> assertThat(item.isFormField()).isFalse(); <add> assertThat(item.getFieldName()).isEqualTo("utf8"); <add> assertThat(item.getName()).isEqualTo("Hall\u00F6le.jpg"); <add> assertThat(item.getContentType()).isEqualTo("image/jpeg"); <add> assertThat(item.getSize()).isEqualTo(logo.getFile().length()); <add> <add> item = items.get(5); <add> assertThat(item.getFieldName()).isEqualTo("json"); <add> assertThat(item.getContentType()).isEqualTo("application/json"); <add> } <add> <add> @Test <add> public void writeMultipartWithSourceHttpMessageConverter() throws Exception { <add> <add> converter.setPartConverters(List.of( <add> new StringHttpMessageConverter(), <add> new ResourceHttpMessageConverter(), <add> new SourceHttpMessageConverter<>())); <add> <ide> MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>(); <ide> parts.add("name 1", "value 1"); <ide> parts.add("name 2", "value 2+1"); <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java <ide> import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; <ide> import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter; <ide> import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter; <del>import org.springframework.http.converter.xml.SourceHttpMessageConverter; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.ClassUtils; <ide> private ManagedList<?> getMessageConverters(Element element, @Nullable Object so <ide> <ide> messageConverters.add(createConverterDefinition(ResourceHttpMessageConverter.class, source)); <ide> messageConverters.add(createConverterDefinition(ResourceRegionHttpMessageConverter.class, source)); <del> messageConverters.add(createConverterDefinition(SourceHttpMessageConverter.class, source)); <ide> messageConverters.add(createConverterDefinition(AllEncompassingFormHttpMessageConverter.class, source)); <ide> <ide> if (romePresent) { <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java <ide> import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; <ide> import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter; <ide> import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter; <del>import org.springframework.http.converter.xml.SourceHttpMessageConverter; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.AntPathMatcher; <ide> import org.springframework.util.Assert; <ide> protected final void addDefaultHttpMessageConverters(List<HttpMessageConverter<? <ide> messageConverters.add(new StringHttpMessageConverter()); <ide> messageConverters.add(new ResourceHttpMessageConverter()); <ide> messageConverters.add(new ResourceRegionHttpMessageConverter()); <del> try { <del> messageConverters.add(new SourceHttpMessageConverter<>()); <del> } <del> catch (Throwable ex) { <del> // Ignore when no TransformerFactory implementation is available... <del> } <del> <ide> messageConverters.add(new AllEncompassingFormHttpMessageConverter()); <ide> <ide> if (romePresent) { <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/support/RouterFunctionMapping.java <ide> import org.springframework.http.converter.HttpMessageConverter; <ide> import org.springframework.http.converter.StringHttpMessageConverter; <ide> import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; <del>import org.springframework.http.converter.xml.SourceHttpMessageConverter; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.CollectionUtils; <ide> import org.springframework.web.filter.ServerHttpObservationFilter; <ide> private void initMessageConverters() { <ide> List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(4); <ide> messageConverters.add(new ByteArrayHttpMessageConverter()); <ide> messageConverters.add(new StringHttpMessageConverter()); <del> try { <del> messageConverters.add(new SourceHttpMessageConverter<>()); <del> } <del> catch (Error err) { <del> // Ignore when no TransformerFactory implementation is available <del> } <ide> messageConverters.add(new AllEncompassingFormHttpMessageConverter()); <ide> <ide> this.messageConverters = messageConverters; <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java <ide> import org.springframework.http.converter.HttpMessageConverter; <ide> import org.springframework.http.converter.StringHttpMessageConverter; <ide> import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; <del>import org.springframework.http.converter.xml.SourceHttpMessageConverter; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.ui.ModelMap; <ide> import org.springframework.web.accept.ContentNegotiationManager; <ide> private void initMessageConverters() { <ide> } <ide> this.messageConverters.add(new ByteArrayHttpMessageConverter()); <ide> this.messageConverters.add(new StringHttpMessageConverter()); <del> try { <del> this.messageConverters.add(new SourceHttpMessageConverter<>()); <del> } <del> catch (Error err) { <del> // Ignore when no TransformerFactory implementation is available <del> } <ide> this.messageConverters.add(new AllEncompassingFormHttpMessageConverter()); <ide> } <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java <ide> import org.springframework.http.converter.HttpMessageConverter; <ide> import org.springframework.http.converter.StringHttpMessageConverter; <ide> import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; <del>import org.springframework.http.converter.xml.SourceHttpMessageConverter; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.ui.ModelMap; <ide> import org.springframework.util.CollectionUtils; <ide> private void initMessageConverters() { <ide> } <ide> this.messageConverters.add(new ByteArrayHttpMessageConverter()); <ide> this.messageConverters.add(new StringHttpMessageConverter()); <del> try { <del> this.messageConverters.add(new SourceHttpMessageConverter<>()); <del> } <del> catch (Error err) { <del> // Ignore when no TransformerFactory implementation is available <del> } <ide> <ide> this.messageConverters.add(new AllEncompassingFormHttpMessageConverter()); <ide> } <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportTests.java <ide> public void requestMappingHandlerAdapter() { <ide> ApplicationContext context = initContext(WebConfig.class); <ide> RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class); <ide> List<HttpMessageConverter<?>> converters = adapter.getMessageConverters(); <del> assertThat(converters).hasSizeGreaterThanOrEqualTo(15); <add> assertThat(converters).hasSizeGreaterThanOrEqualTo(14); <ide> converters.stream() <ide> .filter(converter -> converter instanceof AbstractJackson2HttpMessageConverter) <ide> .forEach(converter -> {
9
Javascript
Javascript
update route-recognizer - fixes
849e6e5248a91f96c95b6242fd1ef1ea16d9e625
<ide><path>packages/ember-routing/lib/vendor/route-recognizer.js <ide> define("route-recognizer", <ide> }, <ide> <ide> recognize: function(path) { <del> var states = [ this.rootState ], i, l; <add> var states = [ this.rootState ], <add> pathLen, i, l; <ide> <ide> // DEBUG GROUP path <ide> <del> var pathLen = path.length; <del> <ide> if (path.charAt(0) !== "/") { path = "/" + path; } <ide> <add> pathLen = path.length; <ide> if (pathLen > 1 && path.charAt(pathLen - 1) === "/") { <ide> path = path.substr(0, pathLen - 1); <ide> }
1
Ruby
Ruby
remove unused assignments from activerecord tests
140b825bdab42eaf535c9847a516773eed27ee6b
<ide><path>activerecord/test/cases/associations/eager_load_nested_include_test.rb <ide> def generate_test_object_graphs <ide> end <ide> <ide> def test_include_query <del> res = 0 <ide> res = ShapeExpression.scoped(:includes => [ :shape, { :paint => :non_poly } ]).all <ide> assert_equal NUM_SHAPE_EXPRESSIONS, res.size <ide> assert_queries(0) do <ide><path>activerecord/test/cases/attribute_methods_test.rb <ide> def test_should_unserialize_attributes_for_frozen_records <ide> end <ide> <ide> def test_typecast_attribute_from_select_to_false <del> topic = Topic.create(:title => 'Budget') <add> Topic.create(:title => 'Budget') <ide> # Oracle does not support boolean expressions in SELECT <ide> if current_adapter?(:OracleAdapter) <ide> topic = Topic.scoped(:select => "topics.*, 0 as is_test").first <ide> def test_typecast_attribute_from_select_to_false <ide> end <ide> <ide> def test_typecast_attribute_from_select_to_true <del> topic = Topic.create(:title => 'Budget') <add> Topic.create(:title => 'Budget') <ide> # Oracle does not support boolean expressions in SELECT <ide> if current_adapter?(:OracleAdapter) <ide> topic = Topic.scoped(:select => "topics.*, 1 as is_test").first <ide><path>activerecord/test/cases/invalid_date_test.rb <ide> def test_assign_valid_dates <ide> <ide> invalid_dates = [[2007, 11, 31], [1993, 2, 29], [2007, 2, 29]] <ide> <del> topic = Topic.new <del> <ide> valid_dates.each do |date_src| <ide> topic = Topic.new("last_read(1i)" => date_src[0].to_s, "last_read(2i)" => date_src[1].to_s, "last_read(3i)" => date_src[2].to_s) <ide> # Oracle DATE columns are datetime columns and Oracle adapter returns Time value <ide><path>activerecord/test/cases/persistence_test.rb <ide> def test_update_attribute_for_readonly_attribute <ide> <ide> def test_update_attribute_with_one_updated <ide> t = Topic.first <del> title = t.title <ide> t.update_attribute(:title, 'super_title') <ide> assert_equal 'super_title', t.title <ide> assert !t.changed?, "topic should not have changed"
4
Javascript
Javascript
use watchcollection not deep watch of ngmodel
47f9fc3e70bc361e8c11fe68dc3ec4489238efb3
<ide><path>src/ng/directive/ngOptions.js <ide> var ngOptionsMinErr = minErr('ngOptions'); <ide> * be nested into the `<select>` element. This element will then represent the `null` or "not selected" <ide> * option. See example below for demonstration. <ide> * <del> * <div class="alert alert-warning"> <del> * **Note:** By default, `ngModel` compares by reference, not value. This is important when binding to an <del> * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/). When using `track by` <del> * in an `ngOptions` expression, however, deep equality checks will be performed. <del> * </div> <add> * ## Complex Models (objects or collections) <add> * <add> * **Note:** By default, `ngModel` watches the model by reference, not value. This is important when <add> * binding any input directive to a model that is an object or a collection. <add> * <add> * Since this is a common situation for `ngOptions` the directive additionally watches the model using <add> * `$watchCollection` when the select has the `multiple` attribute or when there is a `track by` clause in <add> * the options expression. This allows ngOptions to trigger a re-rendering of the options even if the actual <add> * object/collection has not changed identity but only a property on the object or an item in the collection <add> * changes. <add> * <add> * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection <add> * if the model is an array). This means that changing a property deeper inside the object/collection that the <add> * first level will not trigger a re-rendering. <add> * <ide> * <ide> * ## `select` **`as`** <ide> * <ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) { <ide> // We also need to watch to see if the internals of the model changes, since <ide> // ngModel only watches for object identity change <ide> if (ngOptions.trackBy) { <del> scope.$watch(attr.ngModel, function() { ngModelCtrl.$render(); }, true); <add> scope.$watchCollection(attr.ngModel, function() { ngModelCtrl.$render(); }); <ide> } <ide> // ------------------------------------------------------------------ // <ide> <ide><path>test/ng/directive/ngOptionsSpec.js <ide> describe('ngOptions', function() { <ide> }); <ide> <ide> <add> it('should re-render if an item in an array source is added/removed', function() { <add> createSelect({ <add> 'ng-model': 'selected', <add> 'multiple': true, <add> 'ng-options': 'item.id as item.label for item in arr' <add> }); <add> <add> scope.$apply(function() { <add> scope.selected = [10]; <add> }); <add> expect(element).toEqualSelectValue([10], true); <add> <add> scope.$apply(function() { <add> scope.selected.push(20); <add> }); <add> expect(element).toEqualSelectValue([10, 20], true); <add> <add> <add> scope.$apply(function() { <add> scope.selected.shift(); <add> }); <add> expect(element).toEqualSelectValue([20], true); <add> }); <add> <add> <add> it('should handle a options containing circular references', function() { <add> scope.arr[0].ref = scope.arr[0]; <add> scope.selected = [scope.arr[0]]; <add> createSelect({ <add> 'ng-model': 'selected', <add> 'multiple': true, <add> 'ng-options': 'item as item.label for item in arr' <add> }); <add> expect(element).toEqualSelectValue([scope.arr[0]], true); <add> <add> scope.$apply(function() { <add> scope.selected.push(scope.arr[1]); <add> }); <add> expect(element).toEqualSelectValue([scope.arr[0], scope.arr[1]], true); <add> <add> <add> scope.$apply(function() { <add> scope.selected.pop(); <add> }); <add> expect(element).toEqualSelectValue([scope.arr[0]], true); <add> }); <add> <add> <ide> it('should support single select with object source', function() { <ide> createSelect({ <ide> 'ng-model': 'selected', <ide> describe('ngOptions', function() { <ide> <ide> // Update the properties on the object in the selected array, rather than replacing the whole object <ide> scope.$apply(function() { <del> scope.selected[0].id = 20; <del> scope.selected[0].label = 'new twenty'; <add> scope.selected[0] = {id: 20, label: 'new twenty'}; <ide> }); <ide> <ide> // The value of the select should change since the id property changed <ide> describe('ngOptions', function() { <ide> }).not.toThrow(); <ide> }); <ide> <del> it('should setup equality watches on ngModel changes if using trackBy', function() { <add> it('should re-render if a propery of the model is changed when using trackBy', function() { <ide> <ide> createSelect({ <ide> 'ng-model': 'selected', <ide> describe('ngOptions', function() { <ide> <ide> }); <ide> <del> it('should not setup equality watches on ngModel changes if not using trackBy', function() { <add> it('should not re-render if a property of the model is changed when not using trackBy', function() { <ide> <ide> createSelect({ <ide> 'ng-model': 'selected', <ide> describe('ngOptions', function() { <ide> expect(element.controller('ngModel').$render).not.toHaveBeenCalled(); <ide> }); <ide> <add> <add> it('should handle options containing circular references (single)', function() { <add> scope.arr[0].ref = scope.arr[0]; <add> createSelect({ <add> 'ng-model': 'selected', <add> 'ng-options': 'item for item in arr track by item.id' <add> }); <add> <add> expect(function() { <add> scope.$apply(function() { <add> scope.selected = scope.arr[0]; <add> }); <add> }).not.toThrow(); <add> }); <add> <add> <add> it('should handle options containing circular references (multiple)', function() { <add> scope.arr[0].ref = scope.arr[0]; <add> createSelect({ <add> 'ng-model': 'selected', <add> 'multiple': true, <add> 'ng-options': 'item for item in arr track by item.id' <add> }); <add> <add> expect(function() { <add> scope.$apply(function() { <add> scope.selected = [scope.arr[0]]; <add> }); <add> <add> scope.$apply(function() { <add> scope.selected.push(scope.arr[1]); <add> }); <add> }).not.toThrow(); <add> }); <ide> }); <ide> <ide>
2
Python
Python
remove old test dag that is out of place
86b9d3b1e8b2513aa3f614b9a8eba679cdfd25e0
<ide><path>dags/test_dag.py <del># <del># Licensed to the Apache Software Foundation (ASF) under one <del># or more contributor license agreements. See the NOTICE file <del># distributed with this work for additional information <del># regarding copyright ownership. The ASF licenses this file <del># to you under the Apache License, Version 2.0 (the <del># "License"); you may not use this file except in compliance <del># with the License. You may obtain a copy of the License at <del># <del># http://www.apache.org/licenses/LICENSE-2.0 <del># <del># Unless required by applicable law or agreed to in writing, <del># software distributed under the License is distributed on an <del># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <del># KIND, either express or implied. See the License for the <del># specific language governing permissions and limitations <del># under the License. <del>"""This dag only runs some simple tasks to test Airflow's task execution.""" <del>from datetime import datetime, timedelta <del> <del>from airflow.models.dag import DAG <del>from airflow.operators.dummy import DummyOperator <del>from airflow.utils.dates import days_ago <del> <del>now = datetime.now() <del>now_to_the_hour = (now - timedelta(0, 0, 0, 0, 0, 3)).replace(minute=0, second=0, microsecond=0) <del>START_DATE = now_to_the_hour <del>DAG_NAME = 'test_dag_v1' <del> <del>default_args = {'owner': 'airflow', 'depends_on_past': True, 'start_date': days_ago(2)} <del>dag = DAG(DAG_NAME, schedule_interval='*/10 * * * *', default_args=default_args) <del> <del>run_this_1 = DummyOperator(task_id='run_this_1', dag=dag) <del>run_this_2 = DummyOperator(task_id='run_this_2', dag=dag) <del>run_this_2.set_upstream(run_this_1) <del>run_this_3 = DummyOperator(task_id='run_this_3', dag=dag) <del>run_this_3.set_upstream(run_this_2)
1
Javascript
Javascript
remove unused catch bindings
ab14ad1f9dff18a0d6343527cb35ae4470552636
<ide><path>lib/querystring.js <ide> function parse(qs, sep, eq, options) { <ide> function decodeStr(s, decoder) { <ide> try { <ide> return decoder(s); <del> } catch (e) { <add> } catch { <ide> return QueryString.unescape(s, true); <ide> } <ide> }
1
Javascript
Javascript
fix example using-router import wrong pathname
e4da4e5aaaaa7fd488506594b9482a208eb4ce88
<ide><path>examples/using-router/pages/about.js <del>import Header from '../components/header' <add>import Header from '../components/Header' <ide> <ide> export default function About() { <ide> return (
1
Javascript
Javascript
remove scripts for server specific logic (#2)
2cea1bdccc949aac2a11eeff5335dbff761af661
<ide><path>createPathMigrationMap.js <del>require('babel-register'); <del> <del>const fs = require('fs'); <del>const path = require('path'); <del>const { Observable } = require('rx'); <del>const getChallenges = require('./getChallenges'); <del>const { dasherize } = require('../server/utils'); <del> <del>let pathMap = {}; <del> <del>function createPathMigrationMap() { <del> return new Promise(resolve => { <del> Observable.of(getChallenges()) <del>.map(blocks => { <del> blocks.forEach(block => { <del> const {name: blockName, superBlock, challenges } = block; <del> if (!(dasherize(superBlock) in pathMap)) { <del> pathMap[dasherize(superBlock)] = {}; <del> } <del> if (!(dasherize(blockName) in pathMap[superBlock])) { <del> pathMap[dasherize(superBlock)][dasherize(blockName)] = challenges <del> .map(({ title, challengeType }) => ({ <del> dashedName: dasherize(title), <del> challengeType <del> })); <del> } <del> }); <del>}) <del> .subscribe(() => {}, console.error, () => { <del> const migMap = Object.keys(pathMap) <del> .filter(key => !key.includes('certificate')) <del> .map(superBlock => { <del> return Object.keys(pathMap[superBlock]) <del> .map(block => { <del> return pathMap[superBlock][block] <del> .reduce((map, {dashedName, challengeType}) => ({ <del> ...map, <del> [dashedName]: challengeType === 7 ? <del> `/${superBlock}/${block}` : <del> `/${superBlock}/${block}/${dashedName}` <del> }), {}); <del> }).reduce((acc, current) => ({ <del> ...acc, <del> ...current <del> }), {}); <del> }).reduce((acc, current) => ({ <del> ...acc, <del> ...current <del> }), {}); <del> fs.writeFileSync( <del> path.resolve(__dirname, '../server/resources/pathMigration.json'), <del> JSON.stringify(migMap, null, 2) <del> ); <del> resolve(); <del> }); <del> }); <del>} <del> <del> <del> exports.createPathMigrationMap = createPathMigrationMap; <ide><path>get-emails.js <del>/* eslint-disable no-process-exit */ <del>require('dotenv').load(); <del>var secrets = require('../config/secrets'), <del> mongodb = require('mongodb'), <del> MongoClient = mongodb.MongoClient; <del> <del>MongoClient.connect(secrets.db, function(err, database) { <del> if (err) { <del> throw err; <del> } <del> <del> database.collection('user').aggregate([ <del> {$match: { 'email': { $exists: true } } }, <del> {$match: { 'email': { $ne: '' } } }, <del> {$match: { 'email': { $ne: null } } }, <del> {$match: { 'sendQuincyEmail': true } }, <del> {$match: { 'email': { $not: /(test|fake)/i } } }, <del> {$group: { '_id': 1, 'emails': {$addToSet: '$email' } } } <del> ], function(err, results) { <del> if (err) { throw err; } <del> <del> console.log('\"email\"\n\"' + results[0].emails.join('\"\n\"') + '\"'); <del> process.exit(0); <del> }); <del>});
2
Go
Go
remove useless flush method
35641f0ec7ecae16f88ba9affe0aeea0ae864874
<ide><path>api.go <ide> func postImagesCreate(srv *Server, version float64, w http.ResponseWriter, r *ht <ide> } <ide> <ide> job.SetenvBool("json", version > 1.0) <del> job.Stdout.Add(w) <add> job.Stdout.Add(utils.NewWriteFlusher(w)) <ide> if err := job.Run(); err != nil { <ide> if !job.Stdout.Used() { <ide> return err <ide><path>engine/streams.go <ide> func (o *Output) Write(p []byte) (n int, err error) { <ide> return len(p), firstErr <ide> } <ide> <del>func (o *Output) Flush() { <del> o.Mutex.Lock() <del> defer o.Mutex.Unlock() <del> for _, dst := range o.dests { <del> if f, ok := dst.(interface { <del> Flush() <del> }); ok { <del> f.Flush() <del> } <del> } <del>} <del> <ide> // Close unregisters all destinations and waits for all background <ide> // AddTail and AddString tasks to complete. <ide> // The Close method of each destination is called if it exists. <ide><path>server.go <ide> func (srv *Server) ImagePull(job *engine.Job) engine.Status { <ide> localName = job.Args[0] <ide> tag string <ide> sf = utils.NewStreamFormatter(job.GetenvBool("json")) <del> out = utils.NewWriteFlusher(job.Stdout) <ide> authConfig = &auth.AuthConfig{} <ide> metaHeaders map[string][]string <ide> ) <ide> func (srv *Server) ImagePull(job *engine.Job) engine.Status { <ide> if err != nil { <ide> if c != nil { <ide> // Another pull of the same repository is already taking place; just wait for it to finish <del> out.Write(sf.FormatStatus("", "Repository %s already being pulled by another client. Waiting.", localName)) <add> job.Stdout.Write(sf.FormatStatus("", "Repository %s already being pulled by another client. Waiting.", localName)) <ide> <-c <ide> return engine.StatusOK <ide> } <ide> func (srv *Server) ImagePull(job *engine.Job) engine.Status { <ide> localName = remoteName <ide> } <ide> <del> if err = srv.pullRepository(r, out, localName, remoteName, tag, sf, job.GetenvBool("parallel")); err != nil { <add> if err = srv.pullRepository(r, job.Stdout, localName, remoteName, tag, sf, job.GetenvBool("parallel")); err != nil { <ide> job.Error(err) <ide> return engine.StatusErr <ide> } <ide> func (srv *Server) ImageImport(job *engine.Job) engine.Status { <ide> repo = job.Args[1] <ide> tag string <ide> sf = utils.NewStreamFormatter(job.GetenvBool("json")) <del> out = utils.NewWriteFlusher(job.Stdout) <ide> archive io.Reader <ide> resp *http.Response <ide> ) <ide> func (srv *Server) ImageImport(job *engine.Job) engine.Status { <ide> u.Host = src <ide> u.Path = "" <ide> } <del> out.Write(sf.FormatStatus("", "Downloading from %s", u)) <add> job.Stdout.Write(sf.FormatStatus("", "Downloading from %s", u)) <ide> // Download with curl (pretty progress bar) <ide> // If curl is not available, fallback to http.Get() <ide> resp, err = utils.Download(u.String()) <ide> if err != nil { <ide> job.Error(err) <ide> return engine.StatusErr <ide> } <del> archive = utils.ProgressReader(resp.Body, int(resp.ContentLength), out, sf, true, "", "Importing") <add> archive = utils.ProgressReader(resp.Body, int(resp.ContentLength), job.Stdout, sf, true, "", "Importing") <ide> } <ide> img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src, "", nil) <ide> if err != nil { <ide> func (srv *Server) ImageImport(job *engine.Job) engine.Status { <ide> return engine.StatusErr <ide> } <ide> } <del> out.Write(sf.FormatStatus("", img.ID)) <add> job.Stdout.Write(sf.FormatStatus("", img.ID)) <ide> return engine.StatusOK <ide> } <ide>
3
Ruby
Ruby
avoid corrupted elf files
5c068ef82cfb3344f10d7ab3c42003069dd000bb
<ide><path>Library/Homebrew/os/linux/elf.rb <ide> def needed_libraries_using_readelf(path) <ide> soname = nil <ide> needed = [] <ide> command = ["readelf", "-d", path.expand_path.to_s] <del> lines = Utils.safe_popen_read(*command).split("\n") <add> lines = Utils.popen_read(*command, err: :out).split("\n") <ide> lines.each do |s| <add> next if s.start_with?("readelf: Warning: possibly corrupt ELF header") <add> <ide> filename = s[/\[(.*)\]/, 1] <ide> next if filename.nil? <ide>
1
Ruby
Ruby
convert home test to spec
0daf01681268dd19ee5d154e484b3d97832f9ec9
<add><path>Library/Homebrew/cask/spec/cask/cli/home_spec.rb <del><path>Library/Homebrew/cask/test/cask/cli/home_test.rb <del>require "test_helper" <add>require "spec_helper" <ide> <ide> # monkeypatch for testing <ide> module Hbc <ide> def self.system_commands <ide> end <ide> <ide> it "opens the homepage for the specified Cask" do <del> Hbc::CLI::Home.run("alfred") <del> Hbc::CLI::Home.system_commands.must_equal [ <del> ["/usr/bin/open", "--", "https://www.alfredapp.com/"], <add> Hbc::CLI::Home.run("local-caffeine") <add> expect(Hbc::CLI::Home.system_commands).to eq [ <add> ["/usr/bin/open", "--", "http://example.com/local-caffeine"], <ide> ] <ide> end <ide> <ide> it "works for multiple Casks" do <del> Hbc::CLI::Home.run("alfred", "adium") <del> Hbc::CLI::Home.system_commands.must_equal [ <del> ["/usr/bin/open", "--", "https://www.alfredapp.com/"], <del> ["/usr/bin/open", "--", "https://www.adium.im/"], <add> Hbc::CLI::Home.run("local-caffeine", "local-transmission") <add> expect(Hbc::CLI::Home.system_commands).to eq [ <add> ["/usr/bin/open", "--", "http://example.com/local-caffeine"], <add> ["/usr/bin/open", "--", "http://example.com/local-transmission"], <ide> ] <ide> end <ide> <ide> it "opens the project page when no Cask is specified" do <ide> Hbc::CLI::Home.run <del> Hbc::CLI::Home.system_commands.must_equal [ <add> expect(Hbc::CLI::Home.system_commands).to eq [ <ide> ["/usr/bin/open", "--", "http://caskroom.io/"], <ide> ] <ide> end
1
PHP
PHP
make check for `..` more specific
36d8473215007dce853a2c5b8ee1bbad03213844
<ide><path>lib/Cake/Core/App.php <ide> public static function load($className) { <ide> if (!isset(self::$_classMap[$className])) { <ide> return false; <ide> } <del> if (strpos($className, '..')) { <add> if (strpos($className, '..') !== false) { <ide> return false; <ide> } <ide>
1
Javascript
Javascript
add stage to initfragment
e79d4e002be7544b1d2842e5ee8403384f450cd6
<ide><path>lib/InitFragment.js <ide> class InitFragment { <ide> /** <ide> * @param {string|Source} content [TODO] <add> * @param {number} stage [TODO] <ide> * @param {number} priority [TODO] <ide> * @param {string=} key [TODO] <ide> */ <del> constructor(content, priority, key) { <add> constructor(content, stage, priority, key) { <ide> this.content = content; <add> this.stage = stage; <ide> this.priority = priority; <ide> this.key = key; <ide> } <ide> } <ide> <add>InitFragment.STAGE_CONSTANTS = 10; <add>InitFragment.STAGE_HARMONY_EXPORTS = 20; <add>InitFragment.STAGE_HARMONY_IMPORTS = 30; <add>InitFragment.STAGE_PROVIDES = 40; <add> <ide> module.exports = InitFragment; <ide><path>lib/JavascriptGenerator.js <ide> const extractFragmentIndex = (fragment, index) => [fragment, index]; <ide> * @param {[InitFragment, number]} b second pair <ide> * @returns {number} sort value <ide> */ <del>const sortByFragmentIndex = ([a, i], [b, j]) => { <del> const x = a.priority - b.priority; <del> return x !== 0 ? x : i - j; <add>const sortFragmentWithIndex = ([a, i], [b, j]) => { <add> const stageCmp = a.stage - b.stage; <add> if (stageCmp !== 0) return stageCmp; <add> const priorityCmp = a.priority - b.priority; <add> if (priorityCmp !== 0) return priorityCmp; <add> return i - j; <ide> }; <ide> <ide> class JavascriptGenerator { <ide> class JavascriptGenerator { <ide> // use their index. <ide> const sortedFragments = dependencyFragments <ide> .map(extractFragmentIndex) <del> .sort(sortByFragmentIndex); <add> .sort(sortFragmentWithIndex); <ide> <ide> // Deduplicate fragments. If a fragment has no key, it is always included. <ide> const keyedFragments = new Map(); <ide><path>lib/NodeStuffPlugin.js <ide> class ModuleDecoratorDependencyTemplate extends ModuleDependency.Template { <ide> module: dep.module, <ide> request: dep.request <ide> })}(${dep.originalModule.moduleArgument});\n`, <del> -1, <add> InitFragment.STAGE_PROVIDES, <add> 0, <ide> `module decorator ${dep.originalModule.id}` <ide> ) <ide> ]; <ide><path>lib/dependencies/CachedConstDependency.js <ide> CachedConstDependency.Template = class CachedConstDependencyTemplate extends Dep <ide> return [ <ide> new InitFragment( <ide> `var ${dep.identifier} = ${dep.expression};\n`, <del> 1, <add> InitFragment.STAGE_CONSTANTS, <add> 0, <ide> `const ${dep.identifier}` <ide> ) <ide> ]; <ide><path>lib/dependencies/HarmonyCompatibilityDependency.js <ide> HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate <ide> const content = runtimeTemplate.defineEsModuleFlagStatement({ <ide> exportsArgument: dep.originModule.exportsArgument <ide> }); <del> return [new InitFragment(content, -10, "harmony compatibility")]; <add> return [ <add> new InitFragment( <add> content, <add> InitFragment.STAGE_HARMONY_EXPORTS, <add> 0, <add> "harmony compatibility" <add> ) <add> ]; <ide> } else { <ide> return null; <ide> } <ide><path>lib/dependencies/HarmonyExportImportedSpecifierDependency.js <ide> HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS <ide> ); <ide> const exportFragment = new InitFragment( <ide> this.getContent(dep), <add> InitFragment.STAGE_HARMONY_IMPORTS, <ide> dep.sourceOrder <ide> ); <ide> return importFragments <ide><path>lib/dependencies/HarmonyExportSpecifierDependency.js <ide> HarmonyExportSpecifierDependency.Template = class HarmonyExportSpecifierDependen <ide> * @returns {InitFragment[]|null} the init fragments <ide> */ <ide> getInitFragments(dependency, source, runtimeTemplate, dependencyTemplates) { <del> return [new InitFragment(this.getContent(dependency), 0)]; <add> return [ <add> new InitFragment( <add> this.getContent(dependency), <add> InitFragment.STAGE_HARMONY_EXPORTS, <add> 1 <add> ) <add> ]; <ide> } <ide> <ide> getContent(dep) { <ide><path>lib/dependencies/HarmonyImportDependency.js <ide> HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends <ide> return [ <ide> new InitFragment( <ide> dep.getImportStatement(false, runtimeTemplate), <add> InitFragment.STAGE_HARMONY_IMPORTS, <ide> dep.sourceOrder <ide> ) <ide> ]; <ide><path>lib/dependencies/ProvidedDependency.js <ide> class ProvidedDependencyTemplate extends ModuleDependency.Template { <ide> module: dep.module, <ide> request: dep.request <ide> })}${pathToString(dep.path)};\n`, <add> InitFragment.STAGE_PROVIDES, <ide> 1, <ide> `provided ${dep.identifier}` <ide> )
9
Go
Go
use mount filter
ce468f0ad0d075c5d0c44c78bd61c489e6d7d70c
<ide><path>volume/local/local_test.go <ide> func TestCreateWithOpts(t *testing.T) { <ide> if runtime.GOOS == "windows" { <ide> t.Skip() <ide> } <add> if os.Getuid() != 0 { <add> t.Skip("root required") <add> } <add> <ide> rootDir, err := ioutil.TempDir("", "local-volume-test") <ide> if err != nil { <ide> t.Fatal(err) <ide> func TestCreateWithOpts(t *testing.T) { <ide> } <ide> }() <ide> <del> mountInfos, err := mount.GetMounts(nil) <add> mountInfos, err := mount.GetMounts(mount.SingleEntryFilter(dir)) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> <del> var found bool <del> for _, info := range mountInfos { <del> if info.Mountpoint == dir { <del> found = true <del> if info.Fstype != "tmpfs" { <del> t.Fatalf("expected tmpfs mount, got %q", info.Fstype) <del> } <del> if info.Source != "tmpfs" { <del> t.Fatalf("expected tmpfs mount, got %q", info.Source) <del> } <del> if !strings.Contains(info.VfsOpts, "uid=1000") { <del> t.Fatalf("expected mount info to have uid=1000: %q", info.VfsOpts) <del> } <del> if !strings.Contains(info.VfsOpts, "size=1024k") { <del> t.Fatalf("expected mount info to have size=1024k: %q", info.VfsOpts) <del> } <del> break <del> } <add> if len(mountInfos) != 1 { <add> t.Fatalf("expected 1 mount, found %d: %+v", len(mountInfos), mountInfos) <ide> } <ide> <del> if !found { <del> t.Fatal("mount not found") <add> info := mountInfos[0] <add> t.Logf("%+v", info) <add> if info.Fstype != "tmpfs" { <add> t.Fatalf("expected tmpfs mount, got %q", info.Fstype) <add> } <add> if info.Source != "tmpfs" { <add> t.Fatalf("expected tmpfs mount, got %q", info.Source) <add> } <add> if !strings.Contains(info.VfsOpts, "uid=1000") { <add> t.Fatalf("expected mount info to have uid=1000: %q", info.VfsOpts) <add> } <add> if !strings.Contains(info.VfsOpts, "size=1024k") { <add> t.Fatalf("expected mount info to have size=1024k: %q", info.VfsOpts) <ide> } <ide> <ide> if v.active.count != 1 {
1
Javascript
Javascript
fix tooltip body
314f398887d0858802c37a29d4866873e7b7de82
<ide><path>src/core/core.controller.js <ide> module.exports = function(Chart) { <ide> // The usual updates <ide> this.tooltip.initialize(); <ide> this.tooltip._active = this.tooltipActive; <del> this.tooltip.update(); <add> this.tooltip.update(true); <ide> } <ide> <ide> // Hover animations
1
Mixed
Javascript
submit form todo examples and docs
563d7c208bb35c902b8c0bf64bba9fc29f8e9df3
<ide><path>docs/basics/ExampleTodoList.md <ide> let AddTodo = ({ dispatch }) => { <ide> <ide> return ( <ide> <div> <del> <input ref={node => { <del> input = node <del> }} /> <del> <button onClick={() => { <add> <form onSubmit={e => { <add> e.preventDefault() <add> if (!input.value.trim()) { <add> return <add> } <ide> dispatch(addTodo(input.value)) <ide> input.value = '' <ide> }}> <del> Add Todo <del> </button> <add> <input ref={node => { <add> input = node <add> }} /> <add> <button type="submit"> <add> Add Todo <add> </button> <add> </form> <ide> </div> <ide> ) <ide> } <ide><path>examples/todos-with-undo/containers/AddTodo.js <ide> let AddTodo = ({ dispatch }) => { <ide> <div> <ide> <form onSubmit={e => { <ide> e.preventDefault() <del> if (input.value.trim()) { <del> dispatch(addTodo(input.value)) <add> if (!input.value.trim()) { <add> return <ide> } <add> dispatch(addTodo(input.value)) <ide> input.value = '' <ide> }}> <ide> <input ref={node => { <ide><path>examples/todos/containers/AddTodo.js <ide> let AddTodo = ({ dispatch }) => { <ide> <div> <ide> <form onSubmit={e => { <ide> e.preventDefault() <del> if (input.value.trim()) { <del> dispatch(addTodo(input.value)) <add> if (!input.value.trim()) { <add> return <ide> } <add> dispatch(addTodo(input.value)) <ide> input.value = '' <ide> }}> <ide> <input ref={node => {
3
Python
Python
call pip via subprocess, to make it use virtualenv
1754e0db9b9974ce76d935bc1422df8a370265ab
<ide><path>spacy/cli/download.py <ide> import pip <ide> import requests <ide> import os <add>import subprocess <add>import sys <add> <ide> from .link import link_package <ide> from .. import about <ide> from .. import util <ide> def get_version(model, comp): <ide> <ide> def download_model(filename): <ide> util.print_msg("Downloading {f}".format(f=filename)) <del> download_url = os.path.join(about.__download_url__, filename) <del> pip.main(['install', download_url]) <add> download_url = about.__download_url__ + '/' + filename <add> subprocess.call([sys.executable, '-m', 'pip', 'install', download_url], <add> env=os.environ.copy()) <ide> <ide> <ide> def check_error_depr(model):
1
Go
Go
update docker with syncpipe changes
ed556fb38f4d1cba1460650f703cc8147a7b8f32
<ide><path>daemon/execdriver/native/init.go <ide> import ( <ide> "github.com/docker/docker/pkg/reexec" <ide> "github.com/docker/libcontainer" <ide> "github.com/docker/libcontainer/namespaces" <del> "github.com/docker/libcontainer/syncpipe" <ide> ) <ide> <ide> func init() { <ide> func initializer() { <ide> writeError(err) <ide> } <ide> <del> syncPipe, err := syncpipe.NewSyncPipeFromFd(0, uintptr(*pipe)) <del> if err != nil { <del> writeError(err) <del> } <del> <del> if err := namespaces.Init(container, rootfs, *console, syncPipe, flag.Args()); err != nil { <add> if err := namespaces.Init(container, rootfs, *console, os.NewFile(uintptr(*pipe), "child"), flag.Args()); err != nil { <ide> writeError(err) <ide> } <ide> <ide><path>daemon/execdriver/native/utils.go <ide> package native <ide> <ide> import ( <add> "encoding/json" <ide> "os" <ide> <ide> "github.com/docker/libcontainer" <del> "github.com/docker/libcontainer/syncpipe" <ide> ) <ide> <ide> func findUserArgs() []string { <ide> func findUserArgs() []string { <ide> // loadConfigFromFd loads a container's config from the sync pipe that is provided by <ide> // fd 3 when running a process <ide> func loadConfigFromFd() (*libcontainer.Config, error) { <del> syncPipe, err := syncpipe.NewSyncPipeFromFd(0, 3) <del> if err != nil { <del> return nil, err <del> } <del> <ide> var config *libcontainer.Config <del> if err := syncPipe.ReadFromParent(&config); err != nil { <add> if err := json.NewDecoder(os.NewFile(3, "child")).Decode(&config); err != nil { <ide> return nil, err <ide> } <del> <ide> return config, nil <ide> }
2
Java
Java
track the sources used to load aot services
a4f3d1d6e820d247a4781e83cd972f28363c980a
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/aot/AotServices.java <ide> package org.springframework.beans.factory.aot; <ide> <ide> import java.util.ArrayList; <add>import java.util.Collection; <ide> import java.util.Collections; <add>import java.util.IdentityHashMap; <ide> import java.util.Iterator; <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.stream.Stream; <ide> <add>import org.springframework.beans.factory.BeanFactory; <ide> import org.springframework.beans.factory.BeanFactoryUtils; <ide> import org.springframework.beans.factory.ListableBeanFactory; <ide> import org.springframework.beans.factory.config.ConfigurableBeanFactory; <ide> import org.springframework.core.annotation.AnnotationAwareOrderComparator; <ide> import org.springframework.core.io.support.SpringFactoriesLoader; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <add>import org.springframework.util.ObjectUtils; <ide> <ide> /** <ide> * A collection of AOT services that can be {@link Loader loaded} from <ide> <ide> private final Map<String, T> beans; <ide> <add> private final Map<T, Source> sources; <add> <ide> <ide> private AotServices(List<T> loaded, Map<String, T> beans) { <add> this.services = collectServices(loaded, beans); <add> this.sources = collectSources(loaded, beans.values()); <add> this.beans = beans; <add> } <add> <add> private List<T> collectServices(List<T> loaded, Map<String, T> beans) { <ide> List<T> services = new ArrayList<>(); <ide> services.addAll(beans.values()); <ide> services.addAll(loaded); <ide> AnnotationAwareOrderComparator.sort(services); <del> this.services = Collections.unmodifiableList(services); <del> this.beans = beans; <add> return Collections.unmodifiableList(services); <ide> } <ide> <add> private Map<T, Source> collectSources(Collection<T> loaded, <add> Collection<T> beans) { <add> Map<T, Source> sources = new IdentityHashMap<>(); <add> loaded.forEach(service -> sources.put(service, Source.SPRING_FACTORIES_LOADER)); <add> beans.forEach(service -> sources.put(service, Source.BEAN_FACTORY)); <add> return Collections.unmodifiableMap(sources); <add> } <ide> <ide> /** <ide> * Return a new {@link Loader} that will obtain AOT services from <ide> public T findByBeanName(String beanName) { <ide> return this.beans.get(beanName); <ide> } <ide> <add> /** <add> * Return the source of the given service. <add> * @param service the service instance <add> * @return the source of the service <add> */ <add> public Source getSource(T service) { <add> Source source = this.sources.get(service); <add> Assert.state(source != null, <add> "Unable to find service " + ObjectUtils.identityToString(source)); <add> return source; <add> } <add> <ide> <ide> /** <ide> * Loader class used to actually load the services. <ide> private <T> Map<String, T> loadBeans(Class<T> type) { <ide> <ide> } <ide> <add> /** <add> * Sources from which services were obtained. <add> */ <add> public enum Source { <add> <add> /** <add> * An AOT service loaded from {@link SpringFactoriesLoader}. <add> */ <add> SPRING_FACTORIES_LOADER, <add> <add> /** <add> * An AOT service loaded from a {@link BeanFactory}. <add> */ <add> BEAN_FACTORY <add> <add> } <add> <ide> } <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/AotServicesTests.java <ide> <ide> import org.junit.jupiter.api.Test; <ide> <add>import org.springframework.beans.factory.aot.AotServices.Source; <ide> import org.springframework.beans.factory.support.DefaultListableBeanFactory; <ide> import org.springframework.beans.factory.support.RootBeanDefinition; <ide> import org.springframework.core.Ordered; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <add>import static org.assertj.core.api.Assertions.assertThatIllegalStateException; <add>import static org.mockito.Mockito.mock; <ide> <ide> /** <ide> * Tests for {@link AotServices}. <ide> void loadLoadsFromBeanFactoryAndSpringFactoriesLoaderInOrder() { <ide> assertThat(loaded).map(Object::toString).containsExactly("b1", "l1", "b2", "l2"); <ide> } <ide> <add> @Test <add> void getSourceReturnsSource() { <add> MockSpringFactoriesLoader loader = new MockSpringFactoriesLoader(); <add> loader.addInstance(TestService.class, new TestServiceImpl()); <add> DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); <add> beanFactory.registerBeanDefinition("test", new RootBeanDefinition(TestBean.class)); <add> AotServices<TestService> loaded = AotServices.factoriesAndBeans(loader, beanFactory).load(TestService.class); <add> assertThat(loaded.getSource(loaded.asList().get(0))).isEqualTo(Source.SPRING_FACTORIES_LOADER); <add> assertThat(loaded.getSource(loaded.asList().get(1))).isEqualTo(Source.BEAN_FACTORY); <add> TestService missing = mock(TestService.class); <add> assertThatIllegalStateException().isThrownBy(()->loaded.getSource(missing)); <add> } <add> <add> @Test <add> void getSourceWhenMissingThrowsException() { <add> AotServices<TestService> loaded = AotServices.factories().load(TestService.class); <add> TestService missing = mock(TestService.class); <add> assertThatIllegalStateException().isThrownBy(()->loaded.getSource(missing)); <add> } <ide> <ide> interface TestService { <ide> }
2
PHP
PHP
fix unit tests
cbec444542fa9da5fec1a39bd8b602d16016eccd
<ide><path>tests/Cache/CacheFileStoreTest.php <ide> public function testForeversAreStoredWithHighTimestamp() <ide> $store->forever('foo', 'Hello World', 10); <ide> } <ide> <add> public function testRemoveDeletesFileDoesntExist() <add> { <add> $files = $this->mockFilesystem(); <add> $md5 = md5('foobull'); <add> $cache_dir = substr($md5, 0, 2).'/'.substr($md5, 2, 2); <add> $files->expects($this->once())->method('exists')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$md5))->will($this->returnValue(false)); <add> $store = new FileStore($files, __DIR__); <add> $store->forget('foobull'); <add> } <ide> <ide> public function testRemoveDeletesFile() <ide> { <ide> $files = $this->mockFilesystem(); <del> $md5 = md5('foo'); <add> $md5 = md5('foobar'); <ide> $cache_dir = substr($md5, 0, 2).'/'.substr($md5, 2, 2); <del> $files->expects($this->once())->method('delete')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$md5)); <ide> $store = new FileStore($files, __DIR__); <del> $store->forget('foo'); <add> $store->put('foobar', 'Hello Baby', 10); <add> $files->expects($this->once())->method('exists')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$md5))->will($this->returnValue(true)); <add> $files->expects($this->once())->method('delete')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$md5)); <add> $store->forget('foobar'); <ide> } <ide> <del> <ide> public function testFlushCleansDirectory() <ide> { <ide> $files = $this->mockFilesystem();
1
Python
Python
skip large file test on windows
e95cf5f492bf1b181b083ff42ad451319ab23347
<ide><path>numpy/lib/tests/test_format.py <ide> def test_bad_header(): <ide> <ide> def test_large_file_support(): <ide> from nose import SkipTest <add> if (sys.platform == 'win32' or sys.platform == 'cygwin'): <add> raise SkipTest("Unknown if Windows has sparse filesystems") <ide> # try creating a large sparse file <ide> tf_name = os.path.join(tempdir, 'sparse_file') <ide> try:
1
Ruby
Ruby
refactor the methods to use instance variables
15206885eb58978465e5f79a4f20cc3c3766de10
<ide><path>actionpack/lib/action_view/helpers/tags/base.rb <ide> def add_default_name_and_id(options) <ide> options["name"] ||= tag_name_with_index(@auto_index) <ide> options["id"] = options.fetch("id"){ tag_id_with_index(@auto_index) } <ide> else <del> options["name"] ||= tag_name + (options['multiple'] ? '[]' : '') <add> options["name"] ||= options['multiple'] ? tag_name_multiple : tag_name <ide> options["id"] = options.fetch("id"){ tag_id } <ide> end <ide> options["id"] = [options.delete('namespace'), options["id"]].compact.join("_").presence <ide> def tag_name <ide> "#{@object_name}[#{sanitized_method_name}]" <ide> end <ide> <add> def tag_name_multiple <add> "#{tag_name}[]" <add> end <add> <ide> def tag_name_with_index(index) <ide> "#{@object_name}[#{index}][#{sanitized_method_name}]" <ide> end <ide><path>actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb <ide> def render <ide> default_html_options[:multiple] = true <ide> <ide> if block_given? <del> yield sanitize_attribute_name(@method_name, value), text, value, default_html_options <add> yield sanitize_attribute_name(value), text, value, default_html_options <ide> else <ide> check_box(@object_name, @method_name, default_html_options, value, nil) + <del> label(@object_name, sanitize_attribute_name(@method_name, value), text, :class => "collection_check_boxes") <add> label(@object_name, sanitize_attribute_name(value), text, :class => "collection_check_boxes") <ide> end <ide> end <ide> <del> # Prepend a hidden field to make sure something will be sent back to the <del> # server if all checkboxes are unchecked. <del> hidden = @template_object.hidden_field_tag("#{@object_name}[#{@method_name}][]", "", :id => nil) <add> # Append a hidden field to make sure something will be sent back to the <add> # server if all check boxes are unchecked. <add> hidden = @template_object.hidden_field_tag(tag_name_multiple, "", :id => nil) <ide> <del> wrap_rendered_collection(rendered_collection + hidden, @options) <add> wrap_rendered_collection(rendered_collection + hidden) <ide> end <ide> end <ide> end <ide><path>actionpack/lib/action_view/helpers/tags/collection_radio_buttons.rb <ide> class CollectionRadioButtons < CollectionSelect <ide> def render <ide> rendered_collection = render_collection do |value, text, default_html_options| <ide> if block_given? <del> yield sanitize_attribute_name(@method_name, value), text, value, default_html_options <add> yield sanitize_attribute_name(value), text, value, default_html_options <ide> else <ide> radio_button(@object_name, @method_name, value, default_html_options) + <del> label(@object_name, sanitize_attribute_name(@method_name, value), text, :class => "collection_radio_buttons") <add> label(@object_name, sanitize_attribute_name(value), text, :class => "collection_radio_buttons") <ide> end <ide> end <ide> <del> wrap_rendered_collection(rendered_collection, @options) <add> wrap_rendered_collection(rendered_collection) <ide> end <ide> <ide> private <ide> <ide> # Generate default options for collection helpers, such as :checked and <ide> # :disabled. <del> def default_html_options_for_collection(item, value, options, html_options) #:nodoc: <del> html_options = html_options.dup <add> def default_html_options_for_collection(item, value) #:nodoc: <add> html_options = @html_options.dup <ide> <ide> [:checked, :selected, :disabled].each do |option| <del> next unless options[option] <add> next unless @options[option] <ide> <ide> <del> accept = if options[option].respond_to?(:call) <del> options[option].call(item) <add> accept = if @options[option].respond_to?(:call) <add> @options[option].call(item) <ide> else <del> Array(options[option]).include?(value) <add> Array(@options[option]).include?(value) <ide> end <ide> <ide> if accept <ide> def default_html_options_for_collection(item, value, options, html_options) #:no <ide> html_options <ide> end <ide> <del> def sanitize_attribute_name(attribute, value) #:nodoc: <del> "#{attribute}_#{value.to_s.gsub(/\s/, "_").gsub(/[^-\w]/, "").downcase}" <add> def sanitize_attribute_name(value) #:nodoc: <add> "#{sanitized_method_name}_#{value.to_s.gsub(/\s/, "_").gsub(/[^-\w]/, "").downcase}" <ide> end <ide> <ide> def render_collection #:nodoc: <ide> def render_collection #:nodoc: <ide> @collection.map do |item| <ide> value = value_for_collection(item, @value_method) <ide> text = value_for_collection(item, @text_method) <del> default_html_options = default_html_options_for_collection(item, value, @options, @html_options) <add> default_html_options = default_html_options_for_collection(item, value) <ide> <ide> rendered_item = yield value, text, default_html_options <ide> <ide> def value_for_collection(item, value) #:nodoc: <ide> value.respond_to?(:call) ? value.call(item) : item.send(value) <ide> end <ide> <del> def wrap_rendered_collection(collection, options) <del> wrapper_tag = options[:collection_wrapper_tag] <add> def wrap_rendered_collection(collection) <add> wrapper_tag = @options[:collection_wrapper_tag] <ide> <ide> if wrapper_tag <del> wrapper_class = options[:collection_wrapper_class] <add> wrapper_class = @options[:collection_wrapper_class] <ide> @template_object.content_tag(wrapper_tag, collection, :class => wrapper_class) <ide> else <ide> collection
3
Ruby
Ruby
avoid intermediate zipped array
1f75319a9af595d5de3dca55e26547c7f1b166fa
<ide><path>activerecord/lib/active_record/relation/calculations.rb <ide> def pluck(*column_names) <ide> result = result.map do |attributes| <ide> values = klass.initialize_attributes(attributes).values <ide> <del> columns.zip(values).map do |column, value| <del> column.type_cast(value) <del> end <add> iter = columns.each <add> values.map { |value| iter.next.type_cast value } <ide> end <ide> columns.one? ? result.map!(&:first) : result <ide> end
1
Ruby
Ruby
remove 1.8 compatible code
f76340e42b56dc09b42c2e9c209bb5c5d6869fac
<ide><path>actionpack/lib/action_dispatch/journey/router/utils.rb <ide> module UriEscape # :nodoc: <ide> UNSAFE_FRAGMENT = Regexp.new("[^#{safe_fragment}]", false).freeze <ide> end <ide> <del> Parser = URI.const_defined?(:Parser) ? URI::Parser.new : URI <add> Parser = URI::Parser.new <ide> <ide> def self.escape_path(path) <ide> Parser.escape(path.to_s, UriEscape::UNSAFE_SEGMENT)
1
Ruby
Ruby
add a helper to determine if a keg is linked
07b7dd7a7aa1bc2f1628a1081006845374426bc4
<ide><path>Library/Homebrew/keg.rb <ide> def linked_keg_record <ide> @linked_keg_record ||= HOMEBREW_REPOSITORY/"Library/LinkedKegs"/fname <ide> end <ide> <add> def linked? <add> linked_keg_record.directory? and self == linked_keg_record.realpath <add> end <add> <ide> def link <ide> raise "Cannot link #{fname}\nAnother version is already linked: #{linked_keg_record.realpath}" if linked_keg_record.directory? <ide>
1
Ruby
Ruby
fix typo in tab test setup
cd91709120d3666a0dc41076798749a07c1365db
<ide><path>Library/Homebrew/test/test_tab.rb <ide> def setup <ide> @tab = Tab.new({ <ide> :used_options => @used, <ide> :unused_options => @unused, <del> :build_as_bottle => false, <add> :built_as_bottle => false, <ide> :poured_from_bottle => true, <ide> :tapped_from => "Homebrew/homebrew", <ide> :time => nil,
1
Text
Text
improve test runner timeout docs
545ecc57360fad50c49c81b56ae25fcc99d38456
<ide><path>doc/api/test.md <ide> added: v18.0.0 <ide> changes: <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/43505 <del> description: add a timeout to tests and allow setting it in options. <add> description: Add a `timeout` option. <ide> --> <ide> <ide> * `name` {string} The name of the test, which is displayed when reporting test <ide> changes: <ide> the test is `TODO`. **Default:** `false`. <ide> * `timeout` {number} A number of milliseconds the test will fail after. <ide> If unspecified, subtests inherit this value from their parent. <del> **Default:** `30_000`. <add> **Default:** `Infinity`. <ide> * `fn` {Function|AsyncFunction} The function under test. The first argument <ide> to this function is a [`TestContext`][] object. If the test uses callbacks, <ide> the callback function is passed as the second argument. **Default:** A no-op <ide> test('top level test', async (t) => { <ide> }); <ide> ``` <ide> <add>The `timeout` option can be used to fail the test if it takes longer than <add>`timeout` milliseconds to complete. However, it is not a reliable mechanism for <add>canceling tests because a running test might block the application thread and <add>thus prevent the scheduled cancellation. <add> <ide> ## `describe([name][, options][, fn])` <ide> <ide> * `name` {string} The name of the suite, which is displayed when reporting test <ide> added: v18.0.0 <ide> changes: <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/43505 <del> description: add a timeout to tests and allow setting it in options. <add> description: Add a `timeout` option. <ide> --> <ide> <ide> * `name` {string} The name of the subtest, which is displayed when reporting <ide> changes: <ide> the test is `TODO`. **Default:** `false`. <ide> * `timeout` {number} A number of milliseconds the test will fail after. <ide> If unspecified, subtests inherit this value from their parent. <del> **Default:** `30_000`. <add> **Default:** `Infinity`. <ide> * `fn` {Function|AsyncFunction} The function under test. The first argument <ide> to this function is a [`TestContext`][] object. If the test uses callbacks, <ide> the callback function is passed as the second argument. **Default:** A no-op
1
Text
Text
remove smart quotes from code snippet
abddb558ec371e00ecbbe44a110dbcaaeb926289
<ide><path>docs/_posts/2015-12-18-react-components-elements-and-instances.md <ide> Finally, to create elements, use [`React.createElement()`](/react/docs/top-level <ide> * [Streamlining React Elements](/react/blog/2015/02/24/streamlining-react-elements.html) <ide> * [React (Virtual) DOM Terminology](/react/docs/glossary.html) <ide> <del>[^1]: All React elements require an additional ``$$typeof: Symbol.for(‘react.element’)`` field declared on the object for [security reasons](https://github.com/facebook/react/pull/4832). It is omitted in the examples above. This blog entry uses inline objects for elements to give you an idea of what’s happening underneath but the code won’t run as is unless you either add `$$typeof` to the elements, or change the code to use `React.createElement()` or JSX. <add>[^1]: All React elements require an additional ``$$typeof: Symbol.for('react.element')`` field declared on the object for [security reasons](https://github.com/facebook/react/pull/4832). It is omitted in the examples above. This blog entry uses inline objects for elements to give you an idea of what’s happening underneath but the code won’t run as is unless you either add `$$typeof` to the elements, or change the code to use `React.createElement()` or JSX.
1
PHP
PHP
remove some ajax handling
74910637b1c0389ab57f136721dc09404fa470dc
<ide><path>src/Illuminate/Foundation/Auth/AuthenticatesUsers.php <ide> protected function handleUserWasAuthenticated(Request $request, $throttles) <ide> return $this->authenticated($request, Auth::user()); <ide> } <ide> <del> if ($request->ajax() || $request->wantsJson()) { <del> return response()->json(['url' => $request->session()->pull('url.intended')]); <del> } <del> <ide> return redirect()->intended($this->redirectPath()); <ide> } <ide> <ide> protected function handleUserWasAuthenticated(Request $request, $throttles) <ide> */ <ide> protected function sendFailedLoginResponse(Request $request) <ide> { <del> // If the request is an AJAX request or is asking for JSON, we will return the errors <del> // in JSON format so the developers can build JavaScript applications for handling <del> // authentication instead of being forced to use old forms for these situations. <del> if ($request->ajax() || $request->wantsJson()) { <del> return response()->json([ <del> $this->loginUsername() => [$this->getFailedLoginMessage()], <del> ], 422); <del> } <del> <ide> return redirect()->back() <ide> ->withInput($request->only($this->loginUsername(), 'remember')) <ide> ->withErrors([ <ide><path>src/Illuminate/Foundation/Auth/ThrottlesLogins.php <ide> protected function sendLockoutResponse(Request $request) <ide> $this->getThrottleKey($request) <ide> ); <ide> <del> if ($request->ajax() || $request->wantsJson()) { <del> return response()->json([ <del> $this->loginUsername() => [$this->getLockoutErrorMessage($seconds)], <del> ], 429); <del> } <del> <ide> return redirect()->back() <ide> ->withInput($request->only($this->loginUsername(), 'remember')) <ide> ->withErrors([
2
Javascript
Javascript
add files via upload
7e668e1cb853a528c2bb2559fba18d06c996de37
<ide><path>editor/js/Menubar.View.js <ide> Menubar.View = function ( editor ) { <ide> <ide> } else { <ide> <del> alert( 'WebVR nor available' ); <add> alert( 'WebVR not available' ); <ide> <ide> } <ide>
1
Javascript
Javascript
add a new navigator sceneconfig swipefromleft
1888a0af16ea42736faa3d3e99f63cbbb84e2278
<ide><path>Libraries/CustomComponents/Navigator/Navigator.js <ide> var Navigator = React.createClass({ <ide> * - Navigator.SceneConfigs.FloatFromBottom <ide> * - Navigator.SceneConfigs.FloatFromBottomAndroid <ide> * - Navigator.SceneConfigs.FadeAndroid <add> * - Navigator.SceneConfigs.SwipeFromLeft <ide> * - Navigator.SceneConfigs.HorizontalSwipeJump <ide> * - Navigator.SceneConfigs.HorizontalSwipeJumpFromRight <ide> * - Navigator.SceneConfigs.HorizontalSwipeJumpFromLeft <ide><path>Libraries/CustomComponents/Navigator/NavigatorSceneConfigs.js <ide> var NavigatorSceneConfigs = { <ide> out: buildStyleInterpolator(FadeOut), <ide> }, <ide> }, <add> SwipeFromLeft: { <add> ...BaseConfig, <add> gestures: { <add> jumpBack: { <add> ...directionMapping.BaseEndToStartGesture, <add> overswipe: BaseOverswipeConfig, <add> edgeHitWidth: null, <add> isDetachable: true, <add> }, <add> jumpForward: { <add> ...directionMapping.BaseStartToEndGesture, <add> overswipe: BaseOverswipeConfig, <add> edgeHitWidth: null, <add> isDetachable: true, <add> }, <add> }, <add> animationInterpolators: { <add> into: buildStyleInterpolator(directionMapping.FromTheStart), <add> out: buildStyleInterpolator(directionMapping.ToTheEnd), <add> }, <add> }, <ide> HorizontalSwipeJump: { <ide> ...BaseConfig, <ide> gestures: {
2
Python
Python
improve np.finfo docs
84ddedadaee13fe22cc36a0c67c3cb73e818ee9f
<ide><path>numpy/core/getlimits.py <ide> class finfo: <ide> bits : int <ide> The number of bits occupied by the type. <ide> eps : float <del> The smallest representable positive number such that <del> ``1.0 + eps != 1.0``. Type of `eps` is an appropriate floating <del> point type. <del> epsneg : floating point number of the appropriate type <del> The smallest representable positive number such that <del> ``1.0 - epsneg != 1.0``. <add> The difference between 1.0 and the next smallest representable float <add> larger than 1.0. For example, for 64-bit binary floats in the IEEE-754 <add> standard, ``eps = 2**-52``, approximately 2.22e-16. <add> epsneg : float <add> The difference between 1.0 and the next smallest representable float <add> less than 1.0. For example, for 64-bit binary floats in the IEEE-754 <add> standard, ``epsneg = 2**-53``, approximately 1.11e-16. <ide> iexp : int <ide> The number of bits in the exponent portion of the floating point <ide> representation. <ide> class finfo: <ide> -------- <ide> MachAr : The implementation of the tests that produce this information. <ide> iinfo : The equivalent for integer data types. <add> spacing : The distance between a value and the nearest adjacent number <add> nextafter : The next floating point value after x1 towards x2 <ide> <ide> Notes <ide> -----
1
Javascript
Javascript
move extra properties into error creation
39f4158bc38ff2925b86563082c8d26ab3d20b17
<ide><path>lib/_stream_readable.js <ide> function addChunk(stream, state, chunk, addToFront) { <ide> } <ide> <ide> function chunkInvalid(state, chunk) { <del> var er; <ide> if (!Stream._isUint8Array(chunk) && <ide> typeof chunk !== 'string' && <ide> chunk !== undefined && <ide> !state.objectMode) { <del> er = new ERR_INVALID_ARG_TYPE( <add> return new ERR_INVALID_ARG_TYPE( <ide> 'chunk', ['string', 'Buffer', 'Uint8Array'], chunk); <ide> } <del> return er; <ide> } <ide> <ide> <ide><path>lib/internal/encoding.js <ide> function makeTextDecoderICU() { <ide> <ide> const ret = _decode(this[kHandle], input, flags); <ide> if (typeof ret === 'number') { <del> const err = new ERR_ENCODING_INVALID_ENCODED_DATA(this.encoding); <del> err.errno = ret; <del> throw err; <add> throw new ERR_ENCODING_INVALID_ENCODED_DATA(this.encoding, ret); <ide> } <ide> return ret.toString('ucs2'); <ide> } <ide><path>lib/internal/errors.js <ide> function lazyBuffer() { <ide> // and may have .path and .dest. <ide> class SystemError extends Error { <ide> constructor(key, context) { <del> const prefix = getMessage(key, []); <add> super(); <add> const prefix = getMessage(key, [], this); <ide> let message = `${prefix}: ${context.syscall} returned ` + <ide> `${context.code} (${context.message})`; <ide> <ide> class SystemError extends Error { <ide> if (context.dest !== undefined) <ide> message += ` => ${context.dest}`; <ide> <del> super(message); <add> Object.defineProperty(this, 'message', { <add> value: message, <add> enumerable: false, <add> writable: true, <add> configurable: true <add> }); <ide> Object.defineProperty(this, kInfo, { <ide> configurable: false, <ide> enumerable: false, <ide> let useOriginalName = false; <ide> function makeNodeErrorWithCode(Base, key) { <ide> return class NodeError extends Base { <ide> constructor(...args) { <del> super(getMessage(key, args)); <add> super(); <add> const message = getMessage(key, args, this); <add> Object.defineProperty(this, 'message', { <add> value: message, <add> enumerable: false, <add> writable: true, <add> configurable: true <add> }); <ide> } <ide> <ide> get name() { <ide> function E(sym, val, def, ...otherClasses) { <ide> codes[sym] = def; <ide> } <ide> <del>function getMessage(key, args) { <add>function getMessage(key, args, self) { <ide> const msg = messages.get(key); <ide> <ide> if (util === undefined) util = require('util'); <ide> function getMessage(key, args) { <ide> `Code: ${key}; The provided arguments length (${args.length}) does not ` + <ide> `match the required ones (${msg.length}).` <ide> ); <del> return msg.apply(null, args); <add> return msg.apply(self, args); <ide> } <ide> <ide> const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length; <ide> E('ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE', <ide> 'The `domain` module is in use, which is mutually exclusive with calling ' + <ide> 'process.setUncaughtExceptionCaptureCallback()', <ide> Error); <del>E('ERR_ENCODING_INVALID_ENCODED_DATA', <del> 'The encoded data was not valid for encoding %s', TypeError); <add>E('ERR_ENCODING_INVALID_ENCODED_DATA', function(encoding, ret) { <add> this.errno = ret; <add> return `The encoded data was not valid for encoding ${encoding}`; <add>}, TypeError); <ide> E('ERR_ENCODING_NOT_SUPPORTED', 'The "%s" encoding is not supported', <ide> RangeError); <ide> E('ERR_FALSY_VALUE_REJECTION', 'Promise was rejected with falsy value', Error); <ide> E('ERR_HTTP2_INVALID_PSEUDOHEADER', <ide> '"%s" is an invalid pseudoheader or is used incorrectly', TypeError); <ide> E('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed', Error); <ide> E('ERR_HTTP2_INVALID_SETTING_VALUE', <del> 'Invalid value for setting "%s": %s', TypeError, RangeError); <add> // Using default arguments here is important so the arguments are not counted <add> // towards `Function#length`. <add> function(name, actual, min = undefined, max = undefined) { <add> this.actual = actual; <add> if (min !== undefined) { <add> this.min = min; <add> this.max = max; <add> } <add> return `Invalid value for setting "${name}": ${actual}`; <add> }, TypeError, RangeError); <ide> E('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed', Error); <ide> E('ERR_HTTP2_MAX_PENDING_SETTINGS_ACK', <ide> 'Maximum number of pending settings acknowledgements', Error); <ide> E('ERR_HTTP2_SOCKET_UNBOUND', <ide> E('ERR_HTTP2_STATUS_101', <ide> 'HTTP status code 101 (Switching Protocols) is forbidden in HTTP/2', Error); <ide> E('ERR_HTTP2_STATUS_INVALID', 'Invalid status code: %s', RangeError); <del>E('ERR_HTTP2_STREAM_CANCEL', 'The pending stream has been canceled', Error); <add>E('ERR_HTTP2_STREAM_CANCEL', function(error) { <add> let msg = 'The pending stream has been canceled'; <add> if (error) { <add> this.cause = error; <add> if (typeof error.message === 'string') <add> msg += ` (caused by: ${error.message})`; <add> } <add> return msg; <add>}, Error); <ide> E('ERR_HTTP2_STREAM_ERROR', 'Stream closed with error code %s', Error); <ide> E('ERR_HTTP2_STREAM_SELF_DEPENDENCY', <ide> 'A stream cannot depend on itself', Error); <ide> E('ERR_INSPECTOR_CLOSED', 'Session was closed', Error); <ide> E('ERR_INSPECTOR_COMMAND', 'Inspector error %d: %s', Error); <ide> E('ERR_INSPECTOR_NOT_AVAILABLE', 'Inspector is not available', Error); <ide> E('ERR_INSPECTOR_NOT_CONNECTED', 'Session is not connected', Error); <del>E('ERR_INVALID_ADDRESS_FAMILY', 'Invalid address family: %s', RangeError); <add>E('ERR_INVALID_ADDRESS_FAMILY', function(addressType, host, port) { <add> this.host = host; <add> this.port = port; <add> return `Invalid address family: ${addressType} ${host}:${port}`; <add>}, RangeError); <ide> E('ERR_INVALID_ARG_TYPE', <ide> (name, expected, actual) => { <ide> assert(typeof name === 'string', "'name' must be a string"); <ide> E('ERR_INVALID_SYNC_FORK_INPUT', <ide> E('ERR_INVALID_THIS', 'Value of "this" must be of type %s', TypeError); <ide> E('ERR_INVALID_TUPLE', '%s must be an iterable %s tuple', TypeError); <ide> E('ERR_INVALID_URI', 'URI malformed', URIError); <del>E('ERR_INVALID_URL', 'Invalid URL: %s', TypeError); <add>E('ERR_INVALID_URL', function(input) { <add> this.input = input; <add> return `Invalid URL: ${input}`; <add>}, TypeError); <ide> E('ERR_INVALID_URL_SCHEME', <ide> (expected) => `The URL must be ${oneOf(expected, 'scheme')}`, TypeError); <ide> E('ERR_IPC_CHANNEL_CLOSED', 'Channel closed', Error); <ide> E('ERR_STREAM_WRAP', 'Stream has StringDecoder set or is in objectMode', Error); <ide> E('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error); <ide> E('ERR_SYNTHETIC', 'JavaScript Callstack', Error); <ide> E('ERR_SYSTEM_ERROR', 'A system error occurred', SystemError); <del>E('ERR_TLS_CERT_ALTNAME_INVALID', <del> 'Hostname/IP does not match certificate\'s altnames: %s', Error); <add>E('ERR_TLS_CERT_ALTNAME_INVALID', function(reason, host, cert) { <add> this.reason = reason; <add> this.host = host; <add> this.cert = cert; <add> return `Hostname/IP does not match certificate's altnames: ${reason}`; <add>}, Error); <ide> E('ERR_TLS_DH_PARAM_SIZE', 'DH parameter size %s is less than 2048', Error); <ide> E('ERR_TLS_HANDSHAKE_TIMEOUT', 'TLS handshake timeout', Error); <ide> E('ERR_TLS_INVALID_PROTOCOL_VERSION', <ide><path>lib/internal/http2/core.js <ide> function validateSettings(settings) { <ide> typeof settings.enablePush !== 'boolean') { <ide> const err = new ERR_HTTP2_INVALID_SETTING_VALUE('enablePush', <ide> settings.enablePush); <del> err.actual = settings.enablePush; <ide> Error.captureStackTrace(err, 'validateSettings'); <ide> throw err; <ide> } <ide> class Http2Session extends EventEmitter { <ide> this.removeAllListeners('timeout'); <ide> <ide> // Destroy any pending and open streams <del> const cancel = new ERR_HTTP2_STREAM_CANCEL(); <del> if (error) { <del> cancel.cause = error; <del> if (typeof error.message === 'string') <del> cancel.message += ` (caused by: ${error.message})`; <del> } <add> const cancel = new ERR_HTTP2_STREAM_CANCEL(error); <ide> state.pendingStreams.forEach((stream) => stream.destroy(cancel)); <ide> state.streams.forEach((stream) => stream.destroy(error)); <ide> <ide><path>lib/internal/http2/util.js <ide> function assertIsObject(value, name, types) { <ide> function assertWithinRange(name, value, min = 0, max = Infinity) { <ide> if (value !== undefined && <ide> (typeof value !== 'number' || value < min || value > max)) { <del> const err = new ERR_HTTP2_INVALID_SETTING_VALUE.RangeError(name, value); <del> err.min = min; <del> err.max = max; <del> err.actual = value; <add> const err = new ERR_HTTP2_INVALID_SETTING_VALUE.RangeError( <add> name, value, min, max); <ide> Error.captureStackTrace(err, assertWithinRange); <ide> throw err; <ide> } <ide><path>lib/internal/url.js <ide> function onParseComplete(flags, protocol, username, password, <ide> } <ide> <ide> function onParseError(flags, input) { <del> const error = new ERR_INVALID_URL(input); <del> error.input = input; <del> throw error; <add> throw new ERR_INVALID_URL(input); <ide> } <ide> <ide> function onParseProtocolComplete(flags, protocol, username, password, <ide><path>lib/net.js <ide> function lookupAndConnect(self, options) { <ide> if (!self.connecting) return; <ide> <ide> if (err) { <del> // net.createConnection() creates a net.Socket object and <del> // immediately calls net.Socket.connect() on it (that's us). <del> // There are no event listeners registered yet so defer the <del> // error event to the next tick. <add> // net.createConnection() creates a net.Socket object and immediately <add> // calls net.Socket.connect() on it (that's us). There are no event <add> // listeners registered yet so defer the error event to the next tick. <add> // TODO(BridgeAR): The error could either originate from user code or <add> // by the C++ layer. The port is never the cause for the error as it is <add> // not used in the lookup. We should probably just remove this. <ide> err.host = options.host; <ide> err.port = options.port; <ide> err.message = err.message + ' ' + options.host + ':' + options.port; <ide> process.nextTick(connectErrorNT, self, err); <ide> } else if (addressType !== 4 && addressType !== 6) { <del> err = new ERR_INVALID_ADDRESS_FAMILY(addressType); <del> err.host = options.host; <del> err.port = options.port; <del> err.message = err.message + ' ' + options.host + ':' + options.port; <add> err = new ERR_INVALID_ADDRESS_FAMILY(addressType, <add> options.host, <add> options.port); <ide> process.nextTick(connectErrorNT, self, err); <ide> } else { <ide> self._unrefTimer(); <ide><path>lib/tls.js <ide> exports.checkServerIdentity = function checkServerIdentity(hostname, cert) { <ide> } <ide> <ide> if (!valid) { <del> const err = new ERR_TLS_CERT_ALTNAME_INVALID(reason); <del> err.reason = reason; <del> err.host = hostname; <del> err.cert = cert; <del> return err; <add> return new ERR_TLS_CERT_ALTNAME_INVALID(reason, hostname, cert); <ide> } <ide> }; <ide> <ide><path>test/parallel/test-net-options-lookup.js <ide> function connectDoesNotThrow(input) { <ide> cb(null, '127.0.0.1', 100); <ide> }); <ide> <del> s.on('error', common.expectsError({ code: 'ERR_INVALID_ADDRESS_FAMILY' })); <add> s.on('error', common.expectsError({ <add> code: 'ERR_INVALID_ADDRESS_FAMILY', <add> host: 'localhost', <add> port: 0, <add> message: 'Invalid address family: 100 localhost:0' <add> })); <ide> }
9
Javascript
Javascript
update example to use a module
e89916cf0ade8c999d73990f076c0a5ece8eba2a
<ide><path>src/ng/filter/limitTo.js <ide> * had less than `limit` elements. <ide> * <ide> * @example <del> <example> <add> <example module="limitToExample"> <ide> <file name="index.html"> <ide> <script> <del> function Ctrl($scope) { <del> $scope.numbers = [1,2,3,4,5,6,7,8,9]; <del> $scope.letters = "abcdefghi"; <del> $scope.numLimit = 3; <del> $scope.letterLimit = 3; <del> } <add> angular.module('limitToExample', []) <add> .controller('ExampleController', ['$scope', function($scope) { <add> $scope.numbers = [1,2,3,4,5,6,7,8,9]; <add> $scope.letters = "abcdefghi"; <add> $scope.numLimit = 3; <add> $scope.letterLimit = 3; <add> }]); <ide> </script> <del> <div ng-controller="Ctrl"> <add> <div ng-controller="ExampleController"> <ide> Limit {{numbers}} to: <input type="integer" ng-model="numLimit"> <ide> <p>Output numbers: {{ numbers | limitTo:numLimit }}</p> <ide> Limit {{letters}} to: <input type="integer" ng-model="letterLimit">
1
Text
Text
add code of conduct to contributing guidelines
8a4b631dfedd855bda445b2697cd8fb5cd60cfb0
<ide><path>CONTRIBUTING.md <ide> which are hosted in the [Atom Organization](https://github.com/atom) on GitHub. <ide> These are just guidelines, not rules, use your best judgment and feel free to <ide> propose changes to this document in a pull request. <ide> <add>This project adheres to the [Open Code of Conduct][code-of-conduct]. By participating, you are expected to uphold this code. <add>[code-of-conduct]: http://todogroup.org/opencodeofconduct/#Atom/opensource@github.com <add> <ide> ## Submitting Issues <ide> <ide> * You can create an issue [here](https://github.com/atom/atom/issues/new), but
1
Ruby
Ruby
improve grammar for multiple version message
62addcfce8d942eaa96f48f80b8b82ad7d934853
<ide><path>Library/Homebrew/cmd/uninstall.rb <ide> def uninstall <ide> <ide> rack = keg/".." <ide> if rack.directory? <del> versions = rack.subdirs.map(&:basename).join(", ") <del> puts "#{keg.name} #{versions} are still installed." <add> versions = rack.subdirs.map(&:basename) <add> verb = versions.length == 1 ? "is" : "are" <add> puts "#{keg.name} #{versions.join(", ")} #{verb} still installed." <ide> puts "Remove them all with `brew uninstall --force #{keg.name}`." <ide> end <ide> end
1
Mixed
Javascript
increase server headers timeout
e17403ede37d5879c2fa8e9d2c71f1eacbea9366
<ide><path>doc/api/http.md <ide> Stops the server from accepting new connections. See [`net.Server.close()`][]. <ide> added: v11.3.0 <ide> --> <ide> <del>* {number} **Default:** `40000` <add>* {number} **Default:** `60000` <ide> <ide> Limit the amount of time the parser will wait to receive the complete HTTP <ide> headers. <ide><path>doc/api/https.md <ide> See [`server.close()`][`http.close()`] from the HTTP module for details. <ide> added: v11.3.0 <ide> --> <ide> <del>* {number} **Default:** `40000` <add>* {number} **Default:** `60000` <ide> <ide> See [`http.Server#headersTimeout`][]. <ide> <ide><path>lib/_http_server.js <ide> function Server(options, requestListener) { <ide> this.timeout = 0; <ide> this.keepAliveTimeout = 5000; <ide> this.maxHeadersCount = null; <del> this.headersTimeout = 40 * 1000; // 40 seconds <add> this.headersTimeout = 60 * 1000; // 60 seconds <ide> } <ide> ObjectSetPrototypeOf(Server.prototype, net.Server.prototype); <ide> ObjectSetPrototypeOf(Server, net.Server); <ide><path>lib/https.js <ide> function Server(opts, requestListener) { <ide> this.timeout = 0; <ide> this.keepAliveTimeout = 5000; <ide> this.maxHeadersCount = null; <del> this.headersTimeout = 40 * 1000; // 40 seconds <add> this.headersTimeout = 60 * 1000; // 60 seconds <ide> } <ide> ObjectSetPrototypeOf(Server.prototype, tls.Server.prototype); <ide> ObjectSetPrototypeOf(Server, tls.Server); <ide><path>test/parallel/test-http-slow-headers.js <ide> const headers = <ide> const server = createServer(common.mustNotCall()); <ide> let sendCharEvery = 1000; <ide> <del>// 40 seconds is the default <del>assert.strictEqual(server.headersTimeout, 40 * 1000); <add>// 60 seconds is the default <add>assert.strictEqual(server.headersTimeout, 60 * 1000); <ide> <ide> // Pass a REAL env variable to shortening up the default <ide> // value which is 40s otherwise this is useful for manual <ide><path>test/parallel/test-https-slow-headers.js <ide> const server = createServer({ <ide> <ide> let sendCharEvery = 1000; <ide> <del>// 40 seconds is the default <del>assert.strictEqual(server.headersTimeout, 40 * 1000); <add>// 60 seconds is the default <add>assert.strictEqual(server.headersTimeout, 60 * 1000); <ide> <ide> // Pass a REAL env variable to shortening up the default <ide> // value which is 40s otherwise
6
PHP
PHP
update listfailedcommand.php
524cf5b9c3700a5d50121f4e6448e08d81c62c1c
<ide><path>src/Illuminate/Queue/Console/ListFailedCommand.php <ide> protected function parseFailedJob(array $failed) <ide> { <ide> $row = array_values(Arr::except($failed, ['payload', 'exception'])); <ide> <del> array_splice($row, 3, 0, $this->extractJobName($failed['payload'])); <add> array_splice($row, 3, 0, $this->extractJobName($failed['payload']) ?: ''); <ide> <ide> return $row; <ide> }
1
Javascript
Javascript
add jsdoc property descriptions
42c8f099ff2dc6af69cd9503f7ab03ea2da72b20
<ide><path>lib/http.js <ide> function createServer(opts, requestListener) { <ide> <ide> /** <ide> * @typedef {object} HTTPRequestOptions <del> * @property {httpAgent.Agent | boolean} [agent] <del> * @property {string} [auth] <del> * @property {Function} [createConnection] <del> * @property {number} [defaultPort] <del> * @property {number} [family] <del> * @property {object} [headers] <del> * @property {number} [hints] <del> * @property {string} [host] <del> * @property {string} [hostname] <del> * @property {boolean} [insecureHTTPParser] <del> * @property {string} [localAddress] <del> * @property {number} [localPort] <del> * @property {Function} [lookup] <del> * @property {number} [maxHeaderSize] <del> * @property {string} [method] <del> * @property {string} [path] <del> * @property {number} [port] <del> * @property {string} [protocol] <del> * @property {boolean} [setHost] <del> * @property {string} [socketPath] <del> * @property {number} [timeout] <del> * @property {AbortSignal} [signal] <add> * @property {httpAgent.Agent | boolean} [agent] Controls Agent behavior. <add> * @property {string} [auth] Basic authentication ('user:password') to compute an Authorization header. <add> * @property {Function} [createConnection] Produces a socket/stream to use when the agent option is not used. <add> * @property {number} [defaultPort] Default port for the protocol. <add> * @property {number} [family] IP address family to use when resolving host or hostname. <add> * @property {object} [headers] An object containing request headers. <add> * @property {number} [hints] Optional dns.lookup() hints. <add> * @property {string} [host] A domain name or IP address of the server to issue the request to. <add> * @property {string} [hostname] Alias for host. <add> * @property {boolean} [insecureHTTPParser] Use an insecure HTTP parser that accepts invalid HTTP headers when true. <add> * @property {string} [localAddress] Local interface to bind for network connections. <add> * @property {number} [localPort] Local port to connect from. <add> * @property {Function} [lookup] Custom lookup function. Default: dns.lookup(). <add> * @property {number} [maxHeaderSize] Overrides the --max-http-header-size value for responses received from the server. <add> * @property {string} [method] A string specifying the HTTP request method. <add> * @property {string} [path] Request path. <add> * @property {number} [port] Port of remote server. <add> * @property {string} [protocol] Protocol to use. <add> * @property {boolean} [setHost] Specifies whether or not to automatically add the Host header. <add> * @property {AbortSignal} [signal] An AbortSignal that may be used to abort an ongoing request. <add> * @property {string} [socketPath] Unix domain socket. <add> * @property {number} [timeout] A number specifying the socket timeout in milliseconds. <ide> */ <ide> <ide> /**
1
Java
Java
add @since section to doonrequest() javadocs
4c1417729f4810b4fe8ac974b68564aefad2dd60
<ide><path>src/main/java/rx/Observable.java <ide> public final void onNext(T args) { <ide> } <ide> <ide> /** <del> * Modifies the source {@code Observable} so that it invokes the given action when it receives a request for more items. <add> * Modifies the source {@code Observable} so that it invokes the given action when it receives a request for <add> * more items. <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>{@code doOnRequest} does not operate by default on a particular {@link Scheduler}.</dd> <ide> public final void onNext(T args) { <ide> * @param onRequest <ide> * the action that gets called when an observer requests items from this {@code Observable} <ide> * @return the source {@code Observable} modified so as to call this Action when appropriate <add> * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) <ide> */ <ide> @Beta <ide> public final Observable<T> doOnRequest(final Action1<Long> onRequest) { <ide> public final Observable<T> onBackpressureBuffer() { <ide> * <ide> * @return the source Observable modified to buffer items up to the given capacity <ide> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> <del> * @Beta <ide> * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) <ide> */ <ide> @Beta <ide> public final Observable<T> onBackpressureBuffer(long capacity) { <ide> * @return the source Observable modified to buffer items up to the given capacity <ide> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> <ide> * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) <del> * @Beta <ide> */ <ide> @Beta <ide> public final Observable<T> onBackpressureBuffer(long capacity, Action0 onOverflow) {
1
Ruby
Ruby
reduce number of subscriptions created
b925074bdd403e678f8dada49bf68a6d9e4e00ee
<ide><path>actionpack/lib/action_controller/test_case.rb <ide> def setup_subscriptions <ide> end <ide> <ide> @_subscribers << ActiveSupport::Notifications.subscribe("!render_template.action_view") do |_name, _start, _finish, _id, payload| <del> path = payload[:virtual_path] <del> next unless path <del> partial = path =~ /^.*\/_[^\/]*$/ <add> if virtual_path = payload[:virtual_path] <add> partial = virtual_path =~ /^.*\/_[^\/]*$/ <ide> <del> if partial <del> @_partials[path] += 1 <del> @_partials[path.split("/").last] += 1 <del> end <del> <del> @_templates[path] += 1 <del> end <del> <del> @_subscribers << ActiveSupport::Notifications.subscribe("!render_template.action_view") do |_name, _start, _finish, _id, payload| <del> next if payload[:virtual_path] # files don't have virtual path <add> if partial <add> @_partials[virtual_path] += 1 <add> @_partials[virtual_path.split("/").last] += 1 <add> end <ide> <del> path = payload[:identifier] <del> if path <del> @_files[path] += 1 <del> @_files[path.split("/").last] += 1 <add> @_templates[virtual_path] += 1 <add> else <add> path = payload[:identifier] <add> if path <add> @_files[path] += 1 <add> @_files[path.split("/").last] += 1 <add> end <ide> end <ide> end <ide> end
1
Javascript
Javascript
add stylesheet.absolutefill convenience constant
e79f5d7e7a129f30a8817c0676c98990fbe01686
<ide><path>Libraries/ReactIOS/renderApplication.android.js <ide> <ide> 'use strict'; <ide> <del>var Inspector = require('Inspector'); <del>var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter'); <del>var React = require('React'); <del>var ReactNative = require('ReactNative'); <del>var StyleSheet = require('StyleSheet'); <del>var Subscribable = require('Subscribable'); <del>var View = require('View'); <add>const Inspector = require('Inspector'); <add>const RCTDeviceEventEmitter = require('RCTDeviceEventEmitter'); <add>const React = require('React'); <add>const ReactNative = require('ReactNative'); <add>const StyleSheet = require('StyleSheet'); <add>const Subscribable = require('Subscribable'); <add>const View = require('View'); <ide> <del>var invariant = require('fbjs/lib/invariant'); <add>const invariant = require('fbjs/lib/invariant'); <ide> <del>var YellowBox = __DEV__ ? require('YellowBox') : null; <add>const YellowBox = __DEV__ ? require('YellowBox') : null; <ide> <ide> // require BackAndroid so it sets the default handler that exits the app if no listeners respond <ide> require('BackAndroid'); <ide> <del>var AppContainer = React.createClass({ <add>const AppContainer = React.createClass({ <ide> mixins: [Subscribable.Mixin], <ide> <ide> getInitialState: function() { <ide> var AppContainer = React.createClass({ <ide> toggleElementInspector: function() { <ide> this.setState({ <ide> inspectorVisible: !this.state.inspectorVisible, <del> rootNodeHandle: ReactNative.findNodeHandle(this.refs.main), <add> rootNodeHandle: ReactNative.findNodeHandle(this._mainRef), <ide> }); <ide> }, <ide> <ide> var AppContainer = React.createClass({ <ide> onRequestRerenderApp={(updateInspectedViewTag) => { <ide> this.setState( <ide> (s) => ({mainKey: s.mainKey + 1}), <del> () => updateInspectedViewTag(ReactNative.findNodeHandle(this.refs.main)) <add> () => updateInspectedViewTag(ReactNative.findNodeHandle(this._mainRef)) <ide> ); <ide> }} <ide> /> : <ide> var AppContainer = React.createClass({ <ide> this._unmounted = true; <ide> }, <ide> <add> _setMainRef: function(ref) { <add> this._mainRef = ref; <add> }, <add> <ide> render: function() { <del> var RootComponent = this.props.rootComponent; <del> var appView = <add> const RootComponent = this.props.rootComponent; <add> const appView = <ide> <View <del> ref="main" <add> ref={this._setMainRef} <ide> key={this.state.mainKey} <ide> collapsable={!this.state.inspectorVisible} <del> style={styles.appContainer}> <add> style={StyleSheet.absoluteFill}> <ide> <RootComponent <ide> {...this.props.initialProps} <ide> rootTag={this.props.rootTag} <del> importantForAccessibility={this.state.rootImportanceForAccessibility}/> <add> importantForAccessibility={this.state.rootImportanceForAccessibility} <add> /> <ide> </View>; <ide> return __DEV__ ? <del> <View style={styles.appContainer}> <add> <View style={StyleSheet.absoluteFill}> <ide> {appView} <ide> <YellowBox /> <ide> {this.renderInspector()} <ide> function renderApplication<D, P, S>( <ide> <AppContainer <ide> rootComponent={RootComponent} <ide> initialProps={initialProps} <del> rootTag={rootTag} />, <add> rootTag={rootTag} <add> />, <ide> rootTag <ide> ); <ide> } <ide> <del>var styles = StyleSheet.create({ <del> appContainer: { <del> position: 'absolute', <del> left: 0, <del> top: 0, <del> right: 0, <del> bottom: 0, <del> }, <del>}); <del> <ide> module.exports = renderApplication; <ide><path>Libraries/StyleSheet/StyleSheet.js <ide> if (hairlineWidth === 0) { <ide> hairlineWidth = 1 / PixelRatio.get(); <ide> } <ide> <add>const absoluteFillObject = { <add> position: 'absolute', <add> left: 0, <add> right: 0, <add> top: 0, <add> bottom: 0, <add>}; <add>const absoluteFill = ReactNativePropRegistry.register(absoluteFillObject); // This also freezes it <add> <ide> /** <ide> * A StyleSheet is an abstraction similar to CSS StyleSheets <ide> * <ide> module.exports = { <ide> */ <ide> hairlineWidth, <ide> <add> /** <add> * A very common pattern is to create overlays with position absolute and zero positioning, <add> * so `absoluteFill` can be used for convenience and to reduce duplication of these repeated <add> * styles. <add> */ <add> absoluteFill, <add> <add> /** <add> * Sometimes you may want `absoluteFill` but with a couple tweaks - `absoluteFillObject` can be <add> * used to create a customized entry in a `StyleSheet`, e.g.: <add> * <add> * const styles = StyleSheet.create({ <add> * wrapper: { <add> * ...StyleSheet.absoluteFillObject, <add> * top: 10, <add> * backgroundColor: 'transparent', <add> * }, <add> * }); <add> */ <add> absoluteFillObject, <add> <ide> /** <ide> * Flattens an array of style objects, into one aggregated style object. <ide> * Alternatively, this method can be used to lookup IDs, returned by
2
Javascript
Javascript
remove unused dependency
d924629e391d1dbf42693fdbe08f232ba7c1ae01
<ide><path>lib/dependencies/ImportDependenciesBlock.js <ide> "use strict"; <ide> const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); <ide> const ImportDependency = require("./ImportDependency"); <del>const ImportWeakDependency = require("./ImportWeakDependency"); <ide> <ide> module.exports = class ImportDependenciesBlock extends AsyncDependenciesBlock { <ide> constructor(request, range, chunkName, module, loc) {
1
Text
Text
clarify usage of `connect` in readme.md
b543795fc04264c326001dd523cc6edd7cb116bf
<ide><path>examples/with-apollo-and-redux/README.md <ide> now <ide> ``` <ide> <ide> ## The idea behind the example <del>By default, Apollo Client creates its own internal Redux store to manage queries and their results. If you are already using Redux for the rest of your app, [you can have the client integrate with your existing store instead](http://dev.apollodata.com/react/redux.html). This example is identical to the [`with-apollo`](https://github.com/zeit/next.js/tree/master/examples/with-apollo) with the exception of this Redux store integration. <add>By default, Apollo Client creates its own internal Redux store to manage queries and their results. If you are already using Redux for the rest of your app, [you can have the client integrate with your existing store instead](http://dev.apollodata.com/react/redux.html), which is what this example does. This example is identical to the [`with-apollo`](https://github.com/zeit/next.js/tree/master/examples/with-apollo) with the exception of this Redux store integration. <add> <add>Note that you can acesss the redux store like you normally would using `react-redux`'s `connect` as per [here](http://dev.apollodata.com/react/redux.html#using-connect). Here's a quick example: <add> <add>```js <add>const mapStateToProps = state => ({ <add> location: state.form.location, <add>}); <add> <add>export default withData(connect(mapStateToProps, null)(Index)); <add>``` <add> <add>`connect` must go inside `withData` otherwise `connect` will not be able to find the store. <add>
1
Javascript
Javascript
move all imports to closures in fiber
de4a7b972bad8c0fdc4256577c54eb3e1b8a7b27
<ide><path>src/renderers/shared/fiber/ReactChildFiber.js <ide> var { <ide> var ReactFiber = require('ReactFiber'); <ide> var ReactReifiedYield = require('ReactReifiedYield'); <ide> <add>const { <add> cloneFiber, <add> createFiberFromElement, <add> createFiberFromCoroutine, <add> createFiberFromYield, <add>} = ReactFiber; <add> <add>const { <add> createReifiedYield, <add>} = ReactReifiedYield; <add> <add>const isArray = Array.isArray; <add> <ide> function createSubsequentChild( <del> returnFiber : Fiber, <del> existingChild : ?Fiber, <del> previousSibling : Fiber, <del> newChildren, <add> returnFiber : Fiber, <add> existingChild : ?Fiber, <add> previousSibling : Fiber, <add> newChildren, <ide> priority : PriorityLevel <ide> ) : Fiber { <ide> if (typeof newChildren !== 'object' || newChildren === null) { <ide> function createSubsequentChild( <ide> element.key === existingChild.key) { <ide> // TODO: This is not sufficient since previous siblings could be new. <ide> // Will fix reconciliation properly later. <del> const clone = ReactFiber.cloneFiber(existingChild, priority); <add> const clone = cloneFiber(existingChild, priority); <ide> clone.pendingProps = element.props; <ide> clone.child = existingChild.child; <ide> clone.sibling = null; <ide> clone.return = returnFiber; <ide> previousSibling.sibling = clone; <ide> return clone; <ide> } <del> const child = ReactFiber.createFiberFromElement(element, priority); <add> const child = createFiberFromElement(element, priority); <ide> previousSibling.sibling = child; <ide> child.return = returnFiber; <ide> return child; <ide> } <ide> <ide> case REACT_COROUTINE_TYPE: { <ide> const coroutine = (newChildren : ReactCoroutine); <del> const child = ReactFiber.createFiberFromCoroutine(coroutine, priority); <add> const child = createFiberFromCoroutine(coroutine, priority); <ide> previousSibling.sibling = child; <ide> child.return = returnFiber; <ide> return child; <ide> } <ide> <ide> case REACT_YIELD_TYPE: { <ide> const yieldNode = (newChildren : ReactYield); <del> const reifiedYield = ReactReifiedYield.createReifiedYield(yieldNode); <del> const child = ReactFiber.createFiberFromYield(yieldNode, priority); <add> const reifiedYield = createReifiedYield(yieldNode); <add> const child = createFiberFromYield(yieldNode, priority); <ide> child.output = reifiedYield; <ide> previousSibling.sibling = child; <ide> child.return = returnFiber; <ide> return child; <ide> } <ide> } <ide> <del> if (Array.isArray(newChildren)) { <add> if (isArray(newChildren)) { <ide> let prev : Fiber = previousSibling; <ide> let existing : ?Fiber = existingChild; <ide> for (var i = 0; i < newChildren.length; i++) { <ide> function createFirstChild(returnFiber, existingChild, newChildren, priority) { <ide> element.type === existingChild.type && <ide> element.key === existingChild.key) { <ide> // Get the clone of the existing fiber. <del> const clone = ReactFiber.cloneFiber(existingChild, priority); <add> const clone = cloneFiber(existingChild, priority); <ide> clone.pendingProps = element.props; <ide> clone.child = existingChild.child; <ide> clone.sibling = null; <ide> clone.return = returnFiber; <ide> return clone; <ide> } <del> const child = ReactFiber.createFiberFromElement(element, priority); <add> const child = createFiberFromElement(element, priority); <ide> child.return = returnFiber; <ide> return child; <ide> } <ide> <ide> case REACT_COROUTINE_TYPE: { <ide> const coroutine = (newChildren : ReactCoroutine); <del> const child = ReactFiber.createFiberFromCoroutine(coroutine, priority); <add> const child = createFiberFromCoroutine(coroutine, priority); <ide> child.return = returnFiber; <ide> return child; <ide> } <ide> function createFirstChild(returnFiber, existingChild, newChildren, priority) { <ide> // TODO: When there is only a single child, we can optimize this to avoid <ide> // the fragment. <ide> const yieldNode = (newChildren : ReactYield); <del> const reifiedYield = ReactReifiedYield.createReifiedYield(yieldNode); <del> const child = ReactFiber.createFiberFromYield(yieldNode, priority); <add> const reifiedYield = createReifiedYield(yieldNode); <add> const child = createFiberFromYield(yieldNode, priority); <ide> child.output = reifiedYield; <ide> child.return = returnFiber; <ide> return child; <ide> } <ide> } <ide> <del> if (Array.isArray(newChildren)) { <add> if (isArray(newChildren)) { <ide> var first : ?Fiber = null; <ide> var prev : ?Fiber = null; <ide> var existing : ?Fiber = existingChild; <ide> function createFirstChild(returnFiber, existingChild, newChildren, priority) { <ide> // TODO: This API won't work because we'll need to transfer the side-effects of <ide> // unmounting children to the returnFiber. <ide> exports.reconcileChildFibers = function( <del> returnFiber : Fiber, <del> currentFirstChild : ?Fiber, <del> newChildren : ReactNodeList, <add> returnFiber : Fiber, <add> currentFirstChild : ?Fiber, <add> newChildren : ReactNodeList, <ide> priority : PriorityLevel <ide> ) : ?Fiber { <ide> return createFirstChild(returnFiber, currentFirstChild, newChildren, priority); <ide><path>src/renderers/shared/fiber/ReactFiber.js <ide> exports.createHostContainerFiber = function() { <ide> }; <ide> <ide> exports.createFiberFromElement = function(element : ReactElement, priorityLevel : PriorityLevel) { <del> const fiber = exports.createFiberFromElementType(element.type, element.key); <add> const fiber = createFiberFromElementType(element.type, element.key); <ide> fiber.pendingProps = element.props; <ide> fiber.pendingWorkPriority = priorityLevel; <ide> return fiber; <ide> }; <ide> <del>exports.createFiberFromElementType = function(type : mixed, key : null | string) { <add>function createFiberFromElementType(type : mixed, key : null | string) { <ide> let fiber; <ide> if (typeof type === 'function') { <ide> fiber = shouldConstruct(type) ? <ide> exports.createFiberFromElementType = function(type : mixed, key : null | string) <ide> return fiber; <ide> }; <ide> <add>exports.createFiberFromElementType = createFiberFromElementType; <add> <ide> exports.createFiberFromCoroutine = function(coroutine : ReactCoroutine, priorityLevel : PriorityLevel) { <ide> const fiber = createFiber(CoroutineComponent, coroutine.key); <ide> fiber.type = coroutine.handler; <ide><path>src/renderers/shared/fiber/ReactFiberBeginWork.js <ide> import type { ReactCoroutine } from 'ReactCoroutine'; <ide> import type { Fiber } from 'ReactFiber'; <ide> import type { HostConfig } from 'ReactFiberReconciler'; <ide> <del>var ReactChildFiber = require('ReactChildFiber'); <add>var { reconcileChildFibers } = require('ReactChildFiber'); <ide> var ReactTypeOfWork = require('ReactTypeOfWork'); <ide> var { <ide> IndeterminateComponent, <ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) { <ide> <ide> function reconcileChildren(current, workInProgress, nextChildren) { <ide> const priority = workInProgress.pendingWorkPriority; <del> workInProgress.child = ReactChildFiber.reconcileChildFibers( <add> workInProgress.child = reconcileChildFibers( <ide> workInProgress, <ide> current ? current.child : null, <ide> nextChildren, <ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) { <ide> // If this host component is hidden, we can reconcile its children at <ide> // the lowest priority and bail out from this particular pass. Unless, we're <ide> // currently reconciling the lowest priority. <del> workInProgress.child = ReactChildFiber.reconcileChildFibers( <add> workInProgress.child = reconcileChildFibers( <ide> workInProgress, <ide> current ? current.child : null, <ide> nextChildren, <ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) { <ide> workInProgress.pendingWorkPriority = OffscreenPriority; <ide> return null; <ide> } else { <del> workInProgress.child = ReactChildFiber.reconcileChildFibers( <add> workInProgress.child = reconcileChildFibers( <ide> workInProgress, <ide> current ? current.child : null, <ide> nextChildren, <ide><path>src/renderers/shared/fiber/ReactFiberCompleteWork.js <ide> import type { Fiber } from 'ReactFiber'; <ide> import type { HostConfig } from 'ReactFiberReconciler'; <ide> import type { ReifiedYield } from 'ReactReifiedYield'; <ide> <del>var ReactChildFiber = require('ReactChildFiber'); <add>var { reconcileChildFibers } = require('ReactChildFiber'); <ide> var ReactTypeOfWork = require('ReactTypeOfWork'); <ide> var { <ide> IndeterminateComponent, <ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) { <ide> var currentFirstChild = current ? current.stateNode : null; <ide> // Inherit the priority of the returnFiber. <ide> const priority = workInProgress.pendingWorkPriority; <del> workInProgress.stateNode = ReactChildFiber.reconcileChildFibers( <add> workInProgress.stateNode = reconcileChildFibers( <ide> workInProgress, <ide> currentFirstChild, <ide> nextChildren, <ide><path>src/renderers/shared/fiber/ReactFiberPendingWork.js <ide> import type { Fiber } from 'ReactFiber'; <ide> import type { PriorityLevel } from 'ReactPriorityLevel'; <ide> <del>var ReactFiber = require('ReactFiber'); <add>var { cloneFiber } = require('ReactFiber'); <ide> <ide> var { <ide> NoWork, <ide> var { <ide> function cloneSiblings(current : Fiber, workInProgress : Fiber, returnFiber : Fiber) { <ide> while (current.sibling) { <ide> current = current.sibling; <del> workInProgress = workInProgress.sibling = ReactFiber.cloneFiber( <add> workInProgress = workInProgress.sibling = cloneFiber( <ide> current, <ide> current.pendingWorkPriority <ide> ); <ide> exports.findNextUnitOfWorkAtPriority = function(currentRoot : Fiber, priorityLev <ide> throw new Error('Should have wip now'); <ide> } <ide> workInProgress.pendingWorkPriority = current.pendingWorkPriority; <del> workInProgress.child = ReactFiber.cloneFiber(currentChild, NoWork); <add> workInProgress.child = cloneFiber(currentChild, NoWork); <ide> workInProgress.child.return = workInProgress; <ide> cloneSiblings(currentChild, workInProgress.child, workInProgress); <ide> current = current.child; <ide><path>src/renderers/shared/fiber/ReactReifiedYield.js <ide> import type { ReactYield } from 'ReactCoroutine'; <ide> import type { Fiber } from 'ReactFiber'; <ide> <del>var ReactFiber = require('ReactFiber'); <add>var { createFiberFromElementType } = require('ReactFiber'); <ide> <ide> export type ReifiedYield = { continuation: Fiber, props: Object }; <ide> <ide> exports.createReifiedYield = function(yieldNode : ReactYield) : ReifiedYield { <del> var fiber = ReactFiber.createFiberFromElementType( <add> var fiber = createFiberFromElementType( <ide> yieldNode.continuation, <ide> yieldNode.key <ide> );
6
Javascript
Javascript
remove unused binding const
aaea70693e0b186672c0912a2bea6a68f691d9f8
<ide><path>lib/_tls_common.js <ide> const { SSL_OP_CIPHER_SERVER_PREFERENCE } = process.binding('constants').crypto; <ide> // Lazily loaded <ide> var crypto = null; <ide> <del>const binding = process.binding('crypto'); <del>const NativeSecureContext = binding.SecureContext; <add>const { SecureContext: NativeSecureContext } = process.binding('crypto'); <ide> <ide> function SecureContext(secureProtocol, secureOptions, context) { <ide> if (!(this instanceof SecureContext)) {
1
Ruby
Ruby
add line break to string
fea5350d52de54eca9d6f30c67bd2fa008ca8328
<ide><path>Library/Homebrew/cask/lib/hbc/cli/internal_stanza.rb <ide> def initialize(*) <ide> <ide> return if DSL::DSL_METHODS.include?(stanza) <ide> raise ArgumentError, <del> "Unknown/unsupported stanza: '#{stanza}' Check cask reference"\ <del> " for supported stanzas." <add> <<~EOS <add> Unknown/unsupported stanza: '#{stanza}' <add> Check cask reference for supported stanzas. <add> EOS <ide> end <ide> <ide> def run <ide><path>Library/Homebrew/test/cask/cli/internal_stanza_spec.rb <ide> it "raises an exception when stanza is unknown/unsupported" do <ide> expect { <ide> described_class.new("this_stanza_does_not_exist", "with-gpg") <del> }.to raise_error(/Unknown\/unsupported stanza/) <add> }.to raise_error(%r{Unknown/unsupported stanza}) <ide> end <ide> <ide> it "raises an exception when normal stanza is not present on cask" do
2
Javascript
Javascript
fix single subpath bug
8bebe3e184bef7af700ef76a77d1d2dd1e71f85f
<ide><path>src/extras/core/Path.js <ide> THREE.Path.prototype.fromPoints = function ( vectors ) { <ide> <ide> this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); <ide> <del> for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) { <add> var v, vlen = vectors.length; <add> <add> for ( v = 1; v < vlen; v++ ) { <ide> <ide> this.lineTo( vectors[ v ].x, vectors[ v ].y ); <ide> <ide> THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) { <ide> <ide> var x0 = lastargs[ lastargs.length - 2 ]; <ide> var y0 = lastargs[ lastargs.length - 1 ]; <del> <del> // --- <del> <add>//--- <ide> var npts = [ new THREE.Vector2( x0, y0 ) ]; <ide> Array.prototype.push.apply( npts, pts ); <ide> <ide> THREE.Path.prototype.arc = function ( aX, aY, aRadius, <ide> <ide> THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) { <ide> <del> if ( ! divisions ) divisions = 40; <add> if ( !divisions ) divisions = 40; <ide> <ide> var points = []; <ide> <ide> THREE.Path.prototype.getPoints = function( divisions, closedPath ) { <ide> var deltaAngle = aEndAngle - aStartAngle; <ide> var angle; <ide> var tdivisions = divisions * 2; <add> var t; <ide> <ide> for ( j = 1; j <= tdivisions; j ++ ) { <ide> <ide> t = j / tdivisions; <ide> <del> if ( ! aClockwise ) { <add> if ( !aClockwise ) { <ide> <ide> t = 1 - t; <ide> <ide> THREE.Path.prototype.debug = function( canvas ) { <ide> <ide> var p, points = this.getPoints(); <ide> <del> //var theta = -90 /180 * Math.PI; <del> //var p, points = this.transform( 0.866, - 0.866,0, 0.500 , 0.50,-50 ); <del> <del> //0.866, - 0.866,0, 0.500 , 0.50,-50 <del> <del> // Math.cos(theta),Math.sin(theta),100, <del> // Math.cos(theta),-Math.sin(theta),-50 <del> <del> // translate, scale, rotation <del> <del> <ide> for ( i = 0, il = points.length; i < il; i ++ ) { <ide> <ide> p = points[ i ]; <ide> THREE.Path.prototype.toShapes = function() { <ide> <ide> } <ide> <del> //console.log(subPaths); <add> // console.log(subPaths); <ide> <ide> if ( subPaths.length == 0 ) return []; <ide> <ide> var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() ); <add> if ( subPaths.length == 1) { <add> tmpPath = subPaths[0]; <add> tmpShape = new THREE.Shape(); <add> tmpShape.actions = tmpPath.actions; <add> tmpShape.curves = tmpPath.curves; <add> return tmpShape; <add> }; <ide> <ide> var tmpPath, tmpShape, shapes = []; <ide> <del> //console.log("Holes first", holesFirst); <add> // console.log("Holes first", holesFirst); <add> <add> <ide> <ide> if ( holesFirst ) { <ide>
1
PHP
PHP
support temporary tables in schema builder
5505d26ba67746c3e229a789ba5f62ebbeea1c3d
<ide><path>src/Illuminate/Database/Schema/Blueprint.php <ide> class Blueprint <ide> */ <ide> protected $commands = []; <ide> <add> /** <add> * Whether to make the table temporary. <add> * <add> * @var bool <add> */ <add> public $temporary = false; <add> <ide> /** <ide> * The storage engine that should be used for the table. <ide> * <ide> public function create() <ide> return $this->addCommand('create'); <ide> } <ide> <add> /** <add> * Indicate that the table needs to be temporary. <add> * <add> * @return void <add> */ <add> public function temporary() <add> { <add> $this->temporary = true; <add> } <add> <ide> /** <ide> * Indicate that the table should be dropped. <ide> * <ide><path>src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php <ide> public function compileCreate(Blueprint $blueprint, Fluent $command, Connection <ide> { <ide> $columns = implode(', ', $this->getColumns($blueprint)); <ide> <del> $sql = 'create table '.$this->wrapTable($blueprint)." ($columns)"; <add> $sql = 'create'; <add> if ($blueprint->temporary === true) { <add> $sql .= ' temporary'; <add> } <add> $sql .= ' table '.$this->wrapTable($blueprint)." ($columns)"; <ide> <ide> // Once we have the primary SQL, we can add the encoding option to the SQL for <ide> // the table. Then, we can check if a storage engine has been supplied for <ide><path>src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php <ide> public function compileCreate(Blueprint $blueprint, Fluent $command) <ide> { <ide> $columns = implode(', ', $this->getColumns($blueprint)); <ide> <del> return 'create table '.$this->wrapTable($blueprint)." ($columns)"; <add> $sql = 'create'; <add> if ($blueprint->temporary === true) { <add> $sql .= ' temporary'; <add> } <add> $sql .= ' table '.$this->wrapTable($blueprint)." ($columns)"; <add> <add> return $sql; <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Database/Schema/Grammars/SQLiteGrammar.php <ide> public function compileCreate(Blueprint $blueprint, Fluent $command) <ide> { <ide> $columns = implode(', ', $this->getColumns($blueprint)); <ide> <del> $sql = 'create table '.$this->wrapTable($blueprint)." ($columns"; <add> $sql = 'create'; <add> if ($blueprint->temporary === true) { <add> $sql .= ' temporary'; <add> } <add> $sql .= ' table '.$this->wrapTable($blueprint)." ($columns"; <ide> <ide> // SQLite forces primary keys to be added when the table is initially created <ide> // so we will need to check for a primary key commands and add the columns
4
Go
Go
compare v2metadata with associated auth config
0928f3f2e3eda75a295b651d27f9dd992fd951a4
<ide><path>distribution/metadata/v2_metadata_service.go <ide> package metadata <ide> <ide> import ( <add> "crypto/hmac" <add> "crypto/sha256" <add> "encoding/hex" <ide> "encoding/json" <ide> <ide> "github.com/docker/distribution/digest" <add> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/layer" <ide> ) <ide> <ide> type V2MetadataService struct { <ide> type V2Metadata struct { <ide> Digest digest.Digest <ide> SourceRepository string <add> // HMAC hashes above attributes with recent authconfig digest used as a key in order to determine matching <add> // metadata entries accompanied by the same credentials without actually exposing them. <add> HMAC string <add>} <add> <add>// CheckV2MetadataHMAC return true if the given "meta" is tagged with a hmac hashed by the given "key". <add>func CheckV2MetadataHMAC(meta *V2Metadata, key []byte) bool { <add> if len(meta.HMAC) == 0 || len(key) == 0 { <add> return len(meta.HMAC) == 0 && len(key) == 0 <add> } <add> mac := hmac.New(sha256.New, key) <add> mac.Write([]byte(meta.Digest)) <add> mac.Write([]byte(meta.SourceRepository)) <add> expectedMac := mac.Sum(nil) <add> <add> storedMac, err := hex.DecodeString(meta.HMAC) <add> if err != nil { <add> return false <add> } <add> <add> return hmac.Equal(storedMac, expectedMac) <add>} <add> <add>// ComputeV2MetadataHMAC returns a hmac for the given "meta" hash by the given key. <add>func ComputeV2MetadataHMAC(key []byte, meta *V2Metadata) string { <add> if len(key) == 0 || meta == nil { <add> return "" <add> } <add> mac := hmac.New(sha256.New, key) <add> mac.Write([]byte(meta.Digest)) <add> mac.Write([]byte(meta.SourceRepository)) <add> return hex.EncodeToString(mac.Sum(nil)) <add>} <add> <add>// ComputeV2MetadataHMACKey returns a key for the given "authConfig" that can be used to hash v2 metadata <add>// entries. <add>func ComputeV2MetadataHMACKey(authConfig *types.AuthConfig) ([]byte, error) { <add> if authConfig == nil { <add> return nil, nil <add> } <add> key := authConfigKeyInput{ <add> Username: authConfig.Username, <add> Password: authConfig.Password, <add> Auth: authConfig.Auth, <add> IdentityToken: authConfig.IdentityToken, <add> RegistryToken: authConfig.RegistryToken, <add> } <add> buf, err := json.Marshal(&key) <add> if err != nil { <add> return nil, err <add> } <add> return []byte(digest.FromBytes([]byte(buf))), nil <add>} <add> <add>// authConfigKeyInput is a reduced AuthConfig structure holding just relevant credential data eligible for <add>// hmac key creation. <add>type authConfigKeyInput struct { <add> Username string `json:"username,omitempty"` <add> Password string `json:"password,omitempty"` <add> Auth string `json:"auth,omitempty"` <add> <add> IdentityToken string `json:"identitytoken,omitempty"` <add> RegistryToken string `json:"registrytoken,omitempty"` <ide> } <ide> <ide> // maxMetadata is the number of metadata entries to keep per layer DiffID. <ide> func (serv *V2MetadataService) Add(diffID layer.DiffID, metadata V2Metadata) err <ide> return serv.store.Set(serv.digestNamespace(), serv.digestKey(metadata.Digest), []byte(diffID)) <ide> } <ide> <add>// TagAndAdd amends the given "meta" for hmac hashed by the given "hmacKey" and associates it with a layer <add>// DiffID. If too many metadata entries are present, the oldest one is dropped. <add>func (serv *V2MetadataService) TagAndAdd(diffID layer.DiffID, hmacKey []byte, meta V2Metadata) error { <add> meta.HMAC = ComputeV2MetadataHMAC(hmacKey, &meta) <add> return serv.Add(diffID, meta) <add>} <add> <ide> // Remove unassociates a metadata entry from a layer DiffID. <ide> func (serv *V2MetadataService) Remove(metadata V2Metadata) error { <ide> diffID, err := serv.GetDiffID(metadata.Digest) <ide><path>distribution/push_v2.go <ide> import ( <ide> "fmt" <ide> "io" <ide> "runtime" <add> "sort" <add> "strings" <ide> "sync" <ide> <add> "golang.org/x/net/context" <add> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/distribution" <ide> "github.com/docker/distribution/digest" <ide> import ( <ide> "github.com/docker/docker/pkg/stringid" <ide> "github.com/docker/docker/reference" <ide> "github.com/docker/docker/registry" <del> "golang.org/x/net/context" <ide> ) <ide> <add>const maxRepositoryMountAttempts = 3 <add> <ide> // PushResult contains the tag, manifest digest, and manifest size from the <ide> // push. It's used to signal this information to the trust code in the client <ide> // so it can sign the manifest if necessary. <ide> func (p *v2Pusher) pushV2Tag(ctx context.Context, ref reference.NamedTagged, ima <ide> defer layer.ReleaseAndLog(p.config.LayerStore, l) <ide> } <ide> <add> hmacKey, err := metadata.ComputeV2MetadataHMACKey(p.config.AuthConfig) <add> if err != nil { <add> return fmt.Errorf("failed to compute hmac key of auth config: %v", err) <add> } <add> <ide> var descriptors []xfer.UploadDescriptor <ide> <ide> descriptorTemplate := v2PushDescriptor{ <ide> v2MetadataService: p.v2MetadataService, <add> hmacKey: hmacKey, <ide> repoInfo: p.repoInfo, <ide> ref: p.ref, <ide> repo: p.repo, <ide> func manifestFromBuilder(ctx context.Context, builder distribution.ManifestBuild <ide> type v2PushDescriptor struct { <ide> layer layer.Layer <ide> v2MetadataService *metadata.V2MetadataService <add> hmacKey []byte <ide> repoInfo reference.Named <ide> ref reference.Named <ide> repo distribution.Repository <ide> func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress. <ide> bs := pd.repo.Blobs(ctx) <ide> <ide> var layerUpload distribution.BlobWriter <del> mountAttemptsRemaining := 3 <del> <del> // Attempt to find another repository in the same registry to mount the layer <del> // from to avoid an unnecessary upload. <del> // Note: metadata is stored from oldest to newest, so we iterate through this <del> // slice in reverse to maximize our chances of the blob still existing in the <del> // remote repository. <del> for i := len(v2Metadata) - 1; i >= 0 && mountAttemptsRemaining > 0; i-- { <del> mountFrom := v2Metadata[i] <ide> <del> sourceRepo, err := reference.ParseNamed(mountFrom.SourceRepository) <del> if err != nil { <del> continue <del> } <del> if pd.repoInfo.Hostname() != sourceRepo.Hostname() { <del> // don't mount blobs from another registry <del> continue <del> } <add> // Attempt to find another repository in the same registry to mount the layer from to avoid an unnecessary upload <add> candidates := getRepositoryMountCandidates(pd.repoInfo, pd.hmacKey, maxRepositoryMountAttempts, v2Metadata) <add> for _, mountCandidate := range candidates { <add> logrus.Debugf("attempting to mount layer %s (%s) from %s", diffID, mountCandidate.Digest, mountCandidate.SourceRepository) <add> createOpts := []distribution.BlobCreateOption{} <add> <add> if len(mountCandidate.SourceRepository) > 0 { <add> namedRef, err := reference.WithName(mountCandidate.SourceRepository) <add> if err != nil { <add> logrus.Errorf("failed to parse source repository reference %v: %v", namedRef.String(), err) <add> pd.v2MetadataService.Remove(mountCandidate) <add> continue <add> } <ide> <del> namedRef, err := reference.WithName(mountFrom.SourceRepository) <del> if err != nil { <del> continue <del> } <add> // TODO (brianbland): We need to construct a reference where the Name is <add> // only the full remote name, so clean this up when distribution has a <add> // richer reference package <add> remoteRef, err := distreference.WithName(namedRef.RemoteName()) <add> if err != nil { <add> logrus.Errorf("failed to make remote reference out of %q: %v", namedRef.RemoteName(), namedRef.RemoteName()) <add> continue <add> } <ide> <del> // TODO (brianbland): We need to construct a reference where the Name is <del> // only the full remote name, so clean this up when distribution has a <del> // richer reference package <del> remoteRef, err := distreference.WithName(namedRef.RemoteName()) <del> if err != nil { <del> continue <del> } <add> canonicalRef, err := distreference.WithDigest(remoteRef, mountCandidate.Digest) <add> if err != nil { <add> logrus.Errorf("failed to make canonical reference: %v", err) <add> continue <add> } <ide> <del> canonicalRef, err := distreference.WithDigest(remoteRef, mountFrom.Digest) <del> if err != nil { <del> continue <add> createOpts = append(createOpts, client.WithMountFrom(canonicalRef)) <ide> } <ide> <del> logrus.Debugf("attempting to mount layer %s (%s) from %s", diffID, mountFrom.Digest, sourceRepo.FullName()) <del> <del> layerUpload, err = bs.Create(ctx, client.WithMountFrom(canonicalRef)) <add> // send the layer <add> lu, err := bs.Create(ctx, createOpts...) <ide> switch err := err.(type) { <add> case nil: <add> // noop <ide> case distribution.ErrBlobMounted: <ide> progress.Updatef(progressOutput, pd.ID(), "Mounted from %s", err.From.Name()) <ide> <ide> func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress. <ide> pd.pushState.Unlock() <ide> <ide> // Cache mapping from this layer's DiffID to the blobsum <del> if err := pd.v2MetadataService.Add(diffID, metadata.V2Metadata{Digest: mountFrom.Digest, SourceRepository: pd.repoInfo.FullName()}); err != nil { <add> if err := pd.v2MetadataService.TagAndAdd(diffID, pd.hmacKey, metadata.V2Metadata{ <add> Digest: err.Descriptor.Digest, <add> SourceRepository: pd.repoInfo.FullName(), <add> }); err != nil { <ide> return distribution.Descriptor{}, xfer.DoNotRetry{Err: err} <ide> } <ide> return err.Descriptor, nil <del> case nil: <del> // blob upload session created successfully, so begin the upload <del> mountAttemptsRemaining = 0 <ide> default: <del> // unable to mount layer from this repository, so this source mapping is no longer valid <del> logrus.Debugf("unassociating layer %s (%s) with %s", diffID, mountFrom.Digest, mountFrom.SourceRepository) <del> pd.v2MetadataService.Remove(mountFrom) <del> mountAttemptsRemaining-- <add> logrus.Infof("failed to mount layer %s (%s) from %s: %v", diffID, mountCandidate.Digest, mountCandidate.SourceRepository, err) <add> } <add> <add> if len(mountCandidate.SourceRepository) > 0 && <add> (metadata.CheckV2MetadataHMAC(&mountCandidate, pd.hmacKey) || <add> len(mountCandidate.HMAC) == 0) { <add> cause := "blob mount failure" <add> if err != nil { <add> cause = fmt.Sprintf("an error: %v", err.Error()) <add> } <add> logrus.Debugf("removing association between layer %s and %s due to %s", mountCandidate.Digest, mountCandidate.SourceRepository, cause) <add> pd.v2MetadataService.Remove(mountCandidate) <add> } <add> <add> layerUpload = lu <add> if layerUpload != nil { <add> break <ide> } <ide> } <ide> <ide> func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress. <ide> } <ide> defer layerUpload.Close() <ide> <add> // upload the blob <add> desc, err := pd.uploadUsingSession(ctx, progressOutput, diffID, layerUpload) <add> if err != nil { <add> return desc, err <add> } <add> <add> pd.pushState.Lock() <add> // If Commit succeeded, that's an indication that the remote registry speaks the v2 protocol. <add> pd.pushState.confirmedV2 = true <add> pd.pushState.remoteLayers[diffID] = desc <add> pd.pushState.Unlock() <add> <add> return desc, nil <add>} <add> <add>func (pd *v2PushDescriptor) SetRemoteDescriptor(descriptor distribution.Descriptor) { <add> pd.remoteDescriptor = descriptor <add>} <add> <add>func (pd *v2PushDescriptor) Descriptor() distribution.Descriptor { <add> return pd.remoteDescriptor <add>} <add> <add>func (pd *v2PushDescriptor) uploadUsingSession( <add> ctx context.Context, <add> progressOutput progress.Output, <add> diffID layer.DiffID, <add> layerUpload distribution.BlobWriter, <add>) (distribution.Descriptor, error) { <ide> arch, err := pd.layer.TarStream() <ide> if err != nil { <ide> return distribution.Descriptor{}, xfer.DoNotRetry{Err: err} <ide> func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress. <ide> progress.Update(progressOutput, pd.ID(), "Pushed") <ide> <ide> // Cache mapping from this layer's DiffID to the blobsum <del> if err := pd.v2MetadataService.Add(diffID, metadata.V2Metadata{Digest: pushDigest, SourceRepository: pd.repoInfo.FullName()}); err != nil { <add> if err := pd.v2MetadataService.TagAndAdd(diffID, pd.hmacKey, metadata.V2Metadata{ <add> Digest: pushDigest, <add> SourceRepository: pd.repoInfo.FullName(), <add> }); err != nil { <ide> return distribution.Descriptor{}, xfer.DoNotRetry{Err: err} <ide> } <ide> <del> pd.pushState.Lock() <del> <del> // If Commit succeeded, that's an indication that the remote registry <del> // speaks the v2 protocol. <del> pd.pushState.confirmedV2 = true <del> <del> descriptor := distribution.Descriptor{ <add> return distribution.Descriptor{ <ide> Digest: pushDigest, <ide> MediaType: schema2.MediaTypeLayer, <ide> Size: nn, <del> } <del> pd.pushState.remoteLayers[diffID] = descriptor <del> <del> pd.pushState.Unlock() <del> <del> return descriptor, nil <del>} <del> <del>func (pd *v2PushDescriptor) SetRemoteDescriptor(descriptor distribution.Descriptor) { <del> pd.remoteDescriptor = descriptor <del>} <del> <del>func (pd *v2PushDescriptor) Descriptor() distribution.Descriptor { <del> return pd.remoteDescriptor <add> }, nil <ide> } <ide> <ide> // layerAlreadyExists checks if the registry already know about any of the <ide> func layerAlreadyExists(ctx context.Context, metadata []metadata.V2Metadata, rep <ide> } <ide> return distribution.Descriptor{}, false, nil <ide> } <add> <add>// getRepositoryMountCandidates returns an array of v2 metadata items belonging to the given registry. The <add>// array is sorted from youngest to oldest. If requireReigstryMatch is true, the resulting array will contain <add>// only metadata entries having registry part of SourceRepository matching the part of repoInfo. <add>func getRepositoryMountCandidates( <add> repoInfo reference.Named, <add> hmacKey []byte, <add> max int, <add> v2Metadata []metadata.V2Metadata, <add>) []metadata.V2Metadata { <add> candidates := []metadata.V2Metadata{} <add> for _, meta := range v2Metadata { <add> sourceRepo, err := reference.ParseNamed(meta.SourceRepository) <add> if err != nil || repoInfo.Hostname() != sourceRepo.Hostname() { <add> continue <add> } <add> // target repository is not a viable candidate <add> if meta.SourceRepository == repoInfo.FullName() { <add> continue <add> } <add> candidates = append(candidates, meta) <add> } <add> <add> sortV2MetadataByLikenessAndAge(repoInfo, hmacKey, candidates) <add> if max >= 0 && len(candidates) > max { <add> // select the youngest metadata <add> candidates = candidates[:max] <add> } <add> <add> return candidates <add>} <add> <add>// byLikeness is a sorting container for v2 metadata candidates for cross repository mount. The <add>// candidate "a" is preferred over "b": <add>// <add>// 1. if it was hashed using the same AuthConfig as the one used to authenticate to target repository and the <add>// "b" was not <add>// 2. if a number of its repository path components exactly matching path components of target repository is higher <add>type byLikeness struct { <add> arr []metadata.V2Metadata <add> hmacKey []byte <add> pathComponents []string <add>} <add> <add>func (bla byLikeness) Less(i, j int) bool { <add> aMacMatch := metadata.CheckV2MetadataHMAC(&bla.arr[i], bla.hmacKey) <add> bMacMatch := metadata.CheckV2MetadataHMAC(&bla.arr[j], bla.hmacKey) <add> if aMacMatch != bMacMatch { <add> return aMacMatch <add> } <add> aMatch := numOfMatchingPathComponents(bla.arr[i].SourceRepository, bla.pathComponents) <add> bMatch := numOfMatchingPathComponents(bla.arr[j].SourceRepository, bla.pathComponents) <add> return aMatch > bMatch <add>} <add>func (bla byLikeness) Swap(i, j int) { <add> bla.arr[i], bla.arr[j] = bla.arr[j], bla.arr[i] <add>} <add>func (bla byLikeness) Len() int { return len(bla.arr) } <add> <add>func sortV2MetadataByLikenessAndAge(repoInfo reference.Named, hmacKey []byte, marr []metadata.V2Metadata) { <add> // reverse the metadata array to shift the newest entries to the beginning <add> for i := 0; i < len(marr)/2; i++ { <add> marr[i], marr[len(marr)-i-1] = marr[len(marr)-i-1], marr[i] <add> } <add> // keep equal entries ordered from the youngest to the oldest <add> sort.Stable(byLikeness{ <add> arr: marr, <add> hmacKey: hmacKey, <add> pathComponents: getPathComponents(repoInfo.FullName()), <add> }) <add>} <add> <add>// numOfMatchingPathComponents returns a number of path components in "pth" that exactly match "matchComponents". <add>func numOfMatchingPathComponents(pth string, matchComponents []string) int { <add> pthComponents := getPathComponents(pth) <add> i := 0 <add> for ; i < len(pthComponents) && i < len(matchComponents); i++ { <add> if matchComponents[i] != pthComponents[i] { <add> return i <add> } <add> } <add> return i <add>} <add> <add>func getPathComponents(path string) []string { <add> // make sure to add docker.io/ prefix to the path <add> named, err := reference.ParseNamed(path) <add> if err == nil { <add> path = named.FullName() <add> } <add> return strings.Split(path, "/") <add>} <ide><path>distribution/push_v2_test.go <add>package distribution <add> <add>import ( <add> "reflect" <add> "testing" <add> <add> "github.com/docker/distribution/digest" <add> "github.com/docker/docker/distribution/metadata" <add> "github.com/docker/docker/reference" <add>) <add> <add>func TestGetRepositoryMountCandidates(t *testing.T) { <add> for _, tc := range []struct { <add> name string <add> hmacKey string <add> targetRepo string <add> maxCandidates int <add> metadata []metadata.V2Metadata <add> candidates []metadata.V2Metadata <add> }{ <add> { <add> name: "empty metadata", <add> targetRepo: "busybox", <add> maxCandidates: -1, <add> metadata: []metadata.V2Metadata{}, <add> candidates: []metadata.V2Metadata{}, <add> }, <add> { <add> name: "one item not matching", <add> targetRepo: "busybox", <add> maxCandidates: -1, <add> metadata: []metadata.V2Metadata{taggedMetadata("key", "dgst", "127.0.0.1/repo")}, <add> candidates: []metadata.V2Metadata{}, <add> }, <add> { <add> name: "one item matching", <add> targetRepo: "busybox", <add> maxCandidates: -1, <add> metadata: []metadata.V2Metadata{taggedMetadata("hash", "1", "hello-world")}, <add> candidates: []metadata.V2Metadata{taggedMetadata("hash", "1", "hello-world")}, <add> }, <add> { <add> name: "allow missing SourceRepository", <add> targetRepo: "busybox", <add> maxCandidates: -1, <add> metadata: []metadata.V2Metadata{ <add> {Digest: digest.Digest("1")}, <add> {Digest: digest.Digest("3")}, <add> {Digest: digest.Digest("2")}, <add> }, <add> candidates: []metadata.V2Metadata{}, <add> }, <add> { <add> name: "handle docker.io", <add> targetRepo: "user/app", <add> maxCandidates: -1, <add> metadata: []metadata.V2Metadata{ <add> {Digest: digest.Digest("1"), SourceRepository: "docker.io/user/foo"}, <add> {Digest: digest.Digest("3"), SourceRepository: "user/bar"}, <add> {Digest: digest.Digest("2"), SourceRepository: "app"}, <add> }, <add> candidates: []metadata.V2Metadata{ <add> {Digest: digest.Digest("3"), SourceRepository: "user/bar"}, <add> {Digest: digest.Digest("1"), SourceRepository: "docker.io/user/foo"}, <add> {Digest: digest.Digest("2"), SourceRepository: "app"}, <add> }, <add> }, <add> { <add> name: "sort more items", <add> hmacKey: "abcd", <add> targetRepo: "127.0.0.1/foo/bar", <add> maxCandidates: -1, <add> metadata: []metadata.V2Metadata{ <add> taggedMetadata("hash", "1", "hello-world"), <add> taggedMetadata("efgh", "2", "127.0.0.1/hello-world"), <add> taggedMetadata("abcd", "3", "busybox"), <add> taggedMetadata("hash", "4", "busybox"), <add> taggedMetadata("hash", "5", "127.0.0.1/foo"), <add> taggedMetadata("hash", "6", "127.0.0.1/bar"), <add> taggedMetadata("efgh", "7", "127.0.0.1/foo/bar"), <add> taggedMetadata("abcd", "8", "127.0.0.1/xyz"), <add> taggedMetadata("hash", "9", "127.0.0.1/foo/app"), <add> }, <add> candidates: []metadata.V2Metadata{ <add> // first by matching hash <add> taggedMetadata("abcd", "8", "127.0.0.1/xyz"), <add> // then by longest matching prefix <add> taggedMetadata("hash", "9", "127.0.0.1/foo/app"), <add> taggedMetadata("hash", "5", "127.0.0.1/foo"), <add> // sort the rest of the matching items in reversed order <add> taggedMetadata("hash", "6", "127.0.0.1/bar"), <add> taggedMetadata("efgh", "2", "127.0.0.1/hello-world"), <add> }, <add> }, <add> { <add> name: "limit max candidates", <add> hmacKey: "abcd", <add> targetRepo: "user/app", <add> maxCandidates: 3, <add> metadata: []metadata.V2Metadata{ <add> taggedMetadata("abcd", "1", "user/app1"), <add> taggedMetadata("abcd", "2", "user/app/base"), <add> taggedMetadata("hash", "3", "user/app"), <add> taggedMetadata("abcd", "4", "127.0.0.1/user/app"), <add> taggedMetadata("hash", "5", "user/foo"), <add> taggedMetadata("hash", "6", "app/bar"), <add> }, <add> candidates: []metadata.V2Metadata{ <add> // first by matching hash <add> taggedMetadata("abcd", "2", "user/app/base"), <add> taggedMetadata("abcd", "1", "user/app1"), <add> // then by longest matching prefix <add> taggedMetadata("hash", "3", "user/app"), <add> }, <add> }, <add> } { <add> repoInfo, err := reference.ParseNamed(tc.targetRepo) <add> if err != nil { <add> t.Fatalf("[%s] failed to parse reference name: %v", tc.name, err) <add> } <add> candidates := getRepositoryMountCandidates(repoInfo, []byte(tc.hmacKey), tc.maxCandidates, tc.metadata) <add> if len(candidates) != len(tc.candidates) { <add> t.Errorf("[%s] got unexpected number of candidates: %d != %d", tc.name, len(candidates), len(tc.candidates)) <add> } <add> for i := 0; i < len(candidates) && i < len(tc.candidates); i++ { <add> if !reflect.DeepEqual(candidates[i], tc.candidates[i]) { <add> t.Errorf("[%s] candidate %d does not match expected: %#+v != %#+v", tc.name, i, candidates[i], tc.candidates[i]) <add> } <add> } <add> for i := len(candidates); i < len(tc.candidates); i++ { <add> t.Errorf("[%s] missing expected candidate at position %d (%#+v)", tc.name, i, tc.candidates[i]) <add> } <add> for i := len(tc.candidates); i < len(candidates); i++ { <add> t.Errorf("[%s] got unexpected candidate at position %d (%#+v)", tc.name, i, candidates[i]) <add> } <add> } <add>} <add> <add>func taggedMetadata(key string, dgst string, sourceRepo string) metadata.V2Metadata { <add> meta := metadata.V2Metadata{ <add> Digest: digest.Digest(dgst), <add> SourceRepository: sourceRepo, <add> } <add> <add> meta.HMAC = metadata.ComputeV2MetadataHMAC([]byte(key), &meta) <add> return meta <add>}
3
Go
Go
add mode check for device
429423624c61b38efeaeda95792077a0da65c4ef
<ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunAddingOptionalDevices(c *check.C) { <ide> } <ide> } <ide> <add>func (s *DockerSuite) TestRunAddingOptionalDevicesNoSrc(c *check.C) { <add> out, _ := dockerCmd(c, "run", "--device", "/dev/zero:rw", "busybox", "sh", "-c", "ls /dev/zero") <add> if actual := strings.Trim(out, "\r\n"); actual != "/dev/zero" { <add> c.Fatalf("expected output /dev/zero, received %s", actual) <add> } <add>} <add> <add>func (s *DockerSuite) TestRunAddingOptionalDevicesInvalideMode(c *check.C) { <add> _, _, err := dockerCmdWithError("run", "--device", "/dev/zero:ro", "busybox", "sh", "-c", "ls /dev/zero") <add> if err == nil { <add> c.Fatalf("run container with device mode ro should fail") <add> } <add>} <add> <ide> func (s *DockerSuite) TestRunModeHostname(c *check.C) { <ide> testRequires(c, SameHostDaemon) <ide> <ide><path>opts/opts.go <ide> func ValidateLink(val string) (string, error) { <ide> return val, nil <ide> } <ide> <add>// ValidDeviceMode checks if the mode for device is valid or not. <add>// Valid mode is a composition of r (read), w (write), and m (mknod). <add>func ValidDeviceMode(mode string) bool { <add> var legalDeviceMode = map[rune]bool{ <add> 'r': true, <add> 'w': true, <add> 'm': true, <add> } <add> if mode == "" { <add> return false <add> } <add> for _, c := range mode { <add> if !legalDeviceMode[c] { <add> return false <add> } <add> legalDeviceMode[c] = false <add> } <add> return true <add>} <add> <ide> // ValidateDevice Validate a path for devices <ide> // It will make sure 'val' is in the form: <ide> // [host-dir:]container-path[:mode] <add>// It will also validate the device mode. <ide> func ValidateDevice(val string) (string, error) { <del> return validatePath(val, false) <add> return validatePath(val, ValidDeviceMode) <ide> } <ide> <ide> // ValidatePath Validate a path for volumes <ide> // It will make sure 'val' is in the form: <ide> // [host-dir:]container-path[:rw|ro] <ide> // It will also validate the mount mode. <ide> func ValidatePath(val string) (string, error) { <del> return validatePath(val, true) <add> return validatePath(val, volume.ValidMountMode) <ide> } <ide> <del>func validatePath(val string, validateMountMode bool) (string, error) { <add>func validatePath(val string, validator func(string) bool) (string, error) { <ide> var containerPath string <ide> var mode string <ide> <ide> if strings.Count(val, ":") > 2 { <del> return val, fmt.Errorf("bad format for volumes: %s", val) <add> return val, fmt.Errorf("bad format for path: %s", val) <ide> } <ide> <ide> splited := strings.SplitN(val, ":", 3) <ide> if splited[0] == "" { <del> return val, fmt.Errorf("bad format for volumes: %s", val) <add> return val, fmt.Errorf("bad format for path: %s", val) <ide> } <ide> switch len(splited) { <ide> case 1: <ide> containerPath = splited[0] <ide> val = path.Clean(containerPath) <ide> case 2: <del> if isValid := volume.ValidMountMode(splited[1]); validateMountMode && isValid { <add> if isValid := validator(splited[1]); isValid { <ide> containerPath = splited[0] <ide> mode = splited[1] <ide> val = fmt.Sprintf("%s:%s", path.Clean(containerPath), mode) <ide> func validatePath(val string, validateMountMode bool) (string, error) { <ide> case 3: <ide> containerPath = splited[1] <ide> mode = splited[2] <del> if isValid := volume.ValidMountMode(splited[2]); validateMountMode && !isValid { <del> return val, fmt.Errorf("bad mount mode specified : %s", mode) <add> if isValid := validator(splited[2]); !isValid { <add> return val, fmt.Errorf("bad mode specified: %s", mode) <ide> } <ide> val = fmt.Sprintf("%s:%s:%s", splited[0], containerPath, mode) <ide> } <ide><path>opts/opts_test.go <ide> func TestValidatePath(t *testing.T) { <ide> "/rw:rw", <ide> } <ide> invalid := map[string]string{ <del> "": "bad format for volumes: ", <add> "": "bad format for path: ", <ide> "./": "./ is not an absolute path", <ide> "../": "../ is not an absolute path", <ide> "/:../": "../ is not an absolute path", <ide> "/:path": "path is not an absolute path", <del> ":": "bad format for volumes: :", <add> ":": "bad format for path: :", <ide> "/tmp:": " is not an absolute path", <del> ":test": "bad format for volumes: :test", <del> ":/test": "bad format for volumes: :/test", <add> ":test": "bad format for path: :test", <add> ":/test": "bad format for path: :/test", <ide> "tmp:": " is not an absolute path", <del> ":test:": "bad format for volumes: :test:", <del> "::": "bad format for volumes: ::", <del> ":::": "bad format for volumes: :::", <del> "/tmp:::": "bad format for volumes: /tmp:::", <del> ":/tmp::": "bad format for volumes: :/tmp::", <add> ":test:": "bad format for path: :test:", <add> "::": "bad format for path: ::", <add> ":::": "bad format for path: :::", <add> "/tmp:::": "bad format for path: /tmp:::", <add> ":/tmp::": "bad format for path: :/tmp::", <ide> "path:ro": "path is not an absolute path", <del> "/path:/path:sw": "bad mount mode specified : sw", <del> "/path:/path:rwz": "bad mount mode specified : rwz", <add> "/path:/path:sw": "bad mode specified: sw", <add> "/path:/path:rwz": "bad mode specified: rwz", <ide> } <ide> <ide> for _, path := range valid { <ide> func TestValidateDevice(t *testing.T) { <ide> "/with space", <ide> "/home:/with space", <ide> "relative:/absolute-path", <del> "hostPath:/containerPath:ro", <add> "hostPath:/containerPath:r", <ide> "/hostPath:/containerPath:rw", <ide> "/hostPath:/containerPath:mrw", <ide> } <ide> invalid := map[string]string{ <del> "": "bad format for volumes: ", <add> "": "bad format for path: ", <ide> "./": "./ is not an absolute path", <ide> "../": "../ is not an absolute path", <ide> "/:../": "../ is not an absolute path", <ide> "/:path": "path is not an absolute path", <del> ":": "bad format for volumes: :", <add> ":": "bad format for path: :", <ide> "/tmp:": " is not an absolute path", <del> ":test": "bad format for volumes: :test", <del> ":/test": "bad format for volumes: :/test", <add> ":test": "bad format for path: :test", <add> ":/test": "bad format for path: :/test", <ide> "tmp:": " is not an absolute path", <del> ":test:": "bad format for volumes: :test:", <del> "::": "bad format for volumes: ::", <del> ":::": "bad format for volumes: :::", <del> "/tmp:::": "bad format for volumes: /tmp:::", <del> ":/tmp::": "bad format for volumes: :/tmp::", <add> ":test:": "bad format for path: :test:", <add> "::": "bad format for path: ::", <add> ":::": "bad format for path: :::", <add> "/tmp:::": "bad format for path: /tmp:::", <add> ":/tmp::": "bad format for path: :/tmp::", <ide> "path:ro": "ro is not an absolute path", <add> "path:rr": "rr is not an absolute path", <add> "a:/b:ro": "bad mode specified: ro", <add> "a:/b:rr": "bad mode specified: rr", <ide> } <ide> <ide> for _, path := range valid { <ide><path>runconfig/parse.go <ide> func ParseDevice(device string) (DeviceMapping, error) { <ide> permissions = arr[2] <ide> fallthrough <ide> case 2: <del> dst = arr[1] <add> if opts.ValidDeviceMode(arr[1]) { <add> permissions = arr[1] <add> } else { <add> dst = arr[1] <add> } <ide> fallthrough <ide> case 1: <ide> src = arr[0] <ide><path>runconfig/parse_test.go <ide> func TestParseDevice(t *testing.T) { <ide> PathInContainer: "/dev/snd", <ide> CgroupPermissions: "rwm", <ide> }, <add> "/dev/snd:rw": { <add> PathOnHost: "/dev/snd", <add> PathInContainer: "/dev/snd", <add> CgroupPermissions: "rw", <add> }, <ide> "/dev/snd:/something": { <ide> PathOnHost: "/dev/snd", <ide> PathInContainer: "/something", <ide> CgroupPermissions: "rwm", <ide> }, <del> "/dev/snd:/something:ro": { <add> "/dev/snd:/something:rw": { <ide> PathOnHost: "/dev/snd", <ide> PathInContainer: "/something", <del> CgroupPermissions: "ro", <add> CgroupPermissions: "rw", <ide> }, <ide> } <ide> for device, deviceMapping := range valids {
5
Javascript
Javascript
remove event pooling in the modern system
4a3f779d67d7d7f69cb2340c788826b86b34ce05
<ide><path>packages/legacy-events/SyntheticEvent.js <ide> Object.assign(SyntheticEvent.prototype, { <ide> * won't be added back into the pool. <ide> */ <ide> persist: function() { <del> this.isPersistent = functionThatReturnsTrue; <add> // Modern event system doesn't use pooling. <add> if (!enableModernEventSystem) { <add> this.isPersistent = functionThatReturnsTrue; <add> } <ide> }, <ide> <ide> /** <ide> * Checks if this event should be released back into the pool. <ide> * <ide> * @return {boolean} True if this should not be released, false otherwise. <ide> */ <del> isPersistent: functionThatReturnsFalse, <add> isPersistent: enableModernEventSystem <add> ? functionThatReturnsTrue <add> : functionThatReturnsFalse, <ide> <ide> /** <ide> * `PooledClass` looks for `destructor` on each instance it releases. <ide> */ <ide> destructor: function() { <del> const Interface = this.constructor.Interface; <del> for (const propName in Interface) { <add> // Modern event system doesn't use pooling. <add> if (!enableModernEventSystem) { <add> const Interface = this.constructor.Interface; <add> for (const propName in Interface) { <add> if (__DEV__) { <add> Object.defineProperty( <add> this, <add> propName, <add> getPooledWarningPropertyDefinition(propName, Interface[propName]), <add> ); <add> } else { <add> this[propName] = null; <add> } <add> } <add> this.dispatchConfig = null; <add> this._targetInst = null; <add> this.nativeEvent = null; <add> this.isDefaultPrevented = functionThatReturnsFalse; <add> this.isPropagationStopped = functionThatReturnsFalse; <add> this._dispatchListeners = null; <add> this._dispatchInstances = null; <ide> if (__DEV__) { <ide> Object.defineProperty( <ide> this, <del> propName, <del> getPooledWarningPropertyDefinition(propName, Interface[propName]), <add> 'nativeEvent', <add> getPooledWarningPropertyDefinition('nativeEvent', null), <ide> ); <del> } else { <del> this[propName] = null; <del> } <del> } <del> this.dispatchConfig = null; <del> this._targetInst = null; <del> this.nativeEvent = null; <del> this.isDefaultPrevented = functionThatReturnsFalse; <del> this.isPropagationStopped = functionThatReturnsFalse; <del> if (!enableModernEventSystem) { <del> this._dispatchListeners = null; <del> this._dispatchInstances = null; <del> } <del> if (__DEV__) { <del> Object.defineProperty( <del> this, <del> 'nativeEvent', <del> getPooledWarningPropertyDefinition('nativeEvent', null), <del> ); <del> Object.defineProperty( <del> this, <del> 'isDefaultPrevented', <del> getPooledWarningPropertyDefinition( <add> Object.defineProperty( <add> this, <ide> 'isDefaultPrevented', <del> functionThatReturnsFalse, <del> ), <del> ); <del> Object.defineProperty( <del> this, <del> 'isPropagationStopped', <del> getPooledWarningPropertyDefinition( <add> getPooledWarningPropertyDefinition( <add> 'isDefaultPrevented', <add> functionThatReturnsFalse, <add> ), <add> ); <add> Object.defineProperty( <add> this, <ide> 'isPropagationStopped', <del> functionThatReturnsFalse, <del> ), <del> ); <del> Object.defineProperty( <del> this, <del> 'preventDefault', <del> getPooledWarningPropertyDefinition('preventDefault', () => {}), <del> ); <del> Object.defineProperty( <del> this, <del> 'stopPropagation', <del> getPooledWarningPropertyDefinition('stopPropagation', () => {}), <del> ); <add> getPooledWarningPropertyDefinition( <add> 'isPropagationStopped', <add> functionThatReturnsFalse, <add> ), <add> ); <add> Object.defineProperty( <add> this, <add> 'preventDefault', <add> getPooledWarningPropertyDefinition('preventDefault', () => {}), <add> ); <add> Object.defineProperty( <add> this, <add> 'stopPropagation', <add> getPooledWarningPropertyDefinition('stopPropagation', () => {}), <add> ); <add> } <ide> } <ide> }, <ide> }); <ide> function getPooledWarningPropertyDefinition(propName, getVal) { <ide> } <ide> } <ide> <del>function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { <add>function createOrGetPooledEvent( <add> dispatchConfig, <add> targetInst, <add> nativeEvent, <add> nativeInst, <add>) { <ide> const EventConstructor = this; <del> if (EventConstructor.eventPool.length) { <del> const instance = EventConstructor.eventPool.pop(); <del> EventConstructor.call( <del> instance, <del> dispatchConfig, <del> targetInst, <del> nativeEvent, <del> nativeInst, <del> ); <del> return instance; <add> // Modern event system doesn't use pooling. <add> if (!enableModernEventSystem) { <add> if (EventConstructor.eventPool.length) { <add> const instance = EventConstructor.eventPool.pop(); <add> EventConstructor.call( <add> instance, <add> dispatchConfig, <add> targetInst, <add> nativeEvent, <add> nativeInst, <add> ); <add> return instance; <add> } <ide> } <ide> return new EventConstructor( <ide> dispatchConfig, <ide> function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { <ide> } <ide> <ide> function releasePooledEvent(event) { <del> const EventConstructor = this; <del> invariant( <del> event instanceof EventConstructor, <del> 'Trying to release an event instance into a pool of a different type.', <del> ); <del> event.destructor(); <del> if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) { <del> EventConstructor.eventPool.push(event); <add> // Modern event system doesn't use pooling. <add> if (!enableModernEventSystem) { <add> const EventConstructor = this; <add> invariant( <add> event instanceof EventConstructor, <add> 'Trying to release an event instance into a pool of a different type.', <add> ); <add> event.destructor(); <add> if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) { <add> EventConstructor.eventPool.push(event); <add> } <ide> } <ide> } <ide> <ide> function addEventPoolingTo(EventConstructor) { <del> EventConstructor.eventPool = []; <del> EventConstructor.getPooled = getPooledEvent; <del> EventConstructor.release = releasePooledEvent; <add> EventConstructor.getPooled = createOrGetPooledEvent; <add> <add> // Modern event system doesn't use pooling. <add> if (!enableModernEventSystem) { <add> EventConstructor.eventPool = []; <add> EventConstructor.release = releasePooledEvent; <add> } <ide> } <ide> <ide> export default SyntheticEvent; <ide><path>packages/react-dom/src/events/DOMModernPluginEventSystem.js <ide> export function dispatchEventsInBatch(dispatchQueue: DispatchQueue): void { <ide> const dispatchQueueItem: DispatchQueueItem = dispatchQueue[i]; <ide> const {event, capture, bubble} = dispatchQueueItem; <ide> executeDispatchesInOrder(event, capture, bubble); <del> // Release the event from the pool if needed <del> if (!event.isPersistent()) { <del> event.constructor.release(event); <del> } <add> // Modern event system doesn't use pooling. <ide> } <ide> // This would be a good time to rethrow if any of the event handlers threw. <ide> rethrowCaughtError(); <ide><path>packages/react-dom/src/events/__tests__/DOMModernPluginEventSystem-test.internal.js <ide> describe('DOMModernPluginEventSystem', () => { <ide> endNativeEventListenerClearDown(); <ide> }); <ide> <add> it('does not pool events', () => { <add> const buttonRef = React.createRef(); <add> const log = []; <add> const onClick = jest.fn(e => log.push(e)); <add> <add> function Test() { <add> return <button ref={buttonRef} onClick={onClick} />; <add> } <add> <add> ReactDOM.render(<Test />, container); <add> <add> let buttonElement = buttonRef.current; <add> dispatchClickEvent(buttonElement); <add> expect(onClick).toHaveBeenCalledTimes(1); <add> dispatchClickEvent(buttonElement); <add> expect(onClick).toHaveBeenCalledTimes(2); <add> expect(log[0]).not.toBe(log[1]); <add> expect(log[0].type).toBe('click'); <add> expect(log[1].type).toBe('click'); <add> }); <add> <ide> it('handle propagation of click events', () => { <ide> const buttonRef = React.createRef(); <ide> const divRef = React.createRef(); <ide><path>packages/react-dom/src/events/__tests__/SyntheticClipboardEvent-test.js <ide> <ide> let React; <ide> let ReactDOM; <add>const ReactFeatureFlags = require('shared/ReactFeatureFlags'); <ide> <ide> describe('SyntheticClipboardEvent', () => { <ide> let container; <ide> describe('SyntheticClipboardEvent', () => { <ide> expect(expectedCount).toBe(3); <ide> }); <ide> <del> it('is able to `persist`', () => { <del> const persistentEvents = []; <del> const eventHandler = event => { <del> expect(event.isPersistent()).toBe(false); <del> event.persist(); <del> expect(event.isPersistent()).toBe(true); <del> persistentEvents.push(event); <del> }; <del> <del> const div = ReactDOM.render( <del> <div <del> onCopy={eventHandler} <del> onCut={eventHandler} <del> onPaste={eventHandler} <del> />, <del> container, <del> ); <del> <del> let event; <del> event = document.createEvent('Event'); <del> event.initEvent('copy', true, true); <del> div.dispatchEvent(event); <del> <del> event = document.createEvent('Event'); <del> event.initEvent('cut', true, true); <del> div.dispatchEvent(event); <del> <del> event = document.createEvent('Event'); <del> event.initEvent('paste', true, true); <del> div.dispatchEvent(event); <del> <del> expect(persistentEvents.length).toBe(3); <del> expect(persistentEvents[0].type).toBe('copy'); <del> expect(persistentEvents[1].type).toBe('cut'); <del> expect(persistentEvents[2].type).toBe('paste'); <del> }); <add> if (!ReactFeatureFlags.enableModernEventSystem) { <add> it('is able to `persist`', () => { <add> const persistentEvents = []; <add> const eventHandler = event => { <add> expect(event.isPersistent()).toBe(false); <add> event.persist(); <add> expect(event.isPersistent()).toBe(true); <add> persistentEvents.push(event); <add> }; <add> <add> const div = ReactDOM.render( <add> <div <add> onCopy={eventHandler} <add> onCut={eventHandler} <add> onPaste={eventHandler} <add> />, <add> container, <add> ); <add> <add> let event; <add> event = document.createEvent('Event'); <add> event.initEvent('copy', true, true); <add> div.dispatchEvent(event); <add> <add> event = document.createEvent('Event'); <add> event.initEvent('cut', true, true); <add> div.dispatchEvent(event); <add> <add> event = document.createEvent('Event'); <add> event.initEvent('paste', true, true); <add> div.dispatchEvent(event); <add> <add> expect(persistentEvents.length).toBe(3); <add> expect(persistentEvents[0].type).toBe('copy'); <add> expect(persistentEvents[1].type).toBe('cut'); <add> expect(persistentEvents[2].type).toBe('paste'); <add> }); <add> } <ide> }); <ide> }); <ide><path>packages/react-dom/src/events/__tests__/SyntheticEvent-test.js <ide> <ide> let React; <ide> let ReactDOM; <add>const ReactFeatureFlags = require('shared/ReactFeatureFlags'); <ide> <ide> describe('SyntheticEvent', () => { <ide> let container; <ide> describe('SyntheticEvent', () => { <ide> expect(expectedCount).toBe(1); <ide> }); <ide> <del> it('should be able to `persist`', () => { <del> let expectedCount = 0; <del> let syntheticEvent; <del> <del> const eventHandler = e => { <del> expect(e.isPersistent()).toBe(false); <del> e.persist(); <del> syntheticEvent = e; <del> expect(e.isPersistent()).toBe(true); <del> <del> expectedCount++; <del> }; <del> const node = ReactDOM.render(<div onClick={eventHandler} />, container); <del> <del> const event = document.createEvent('Event'); <del> event.initEvent('click', true, true); <del> node.dispatchEvent(event); <del> <del> expect(syntheticEvent.type).toBe('click'); <del> expect(syntheticEvent.bubbles).toBe(true); <del> expect(syntheticEvent.cancelable).toBe(true); <del> expect(expectedCount).toBe(1); <del> }); <add> if (!ReactFeatureFlags.enableModernEventSystem) { <add> it('should be able to `persist`', () => { <add> let expectedCount = 0; <add> let syntheticEvent; <add> <add> const eventHandler = e => { <add> expect(e.isPersistent()).toBe(false); <add> e.persist(); <add> syntheticEvent = e; <add> expect(e.isPersistent()).toBe(true); <add> <add> expectedCount++; <add> }; <add> const node = ReactDOM.render(<div onClick={eventHandler} />, container); <add> <add> const event = document.createEvent('Event'); <add> event.initEvent('click', true, true); <add> node.dispatchEvent(event); <add> <add> expect(syntheticEvent.type).toBe('click'); <add> expect(syntheticEvent.bubbles).toBe(true); <add> expect(syntheticEvent.cancelable).toBe(true); <add> expect(expectedCount).toBe(1); <add> }); <ide> <del> it('should be nullified and log warnings if the synthetic event has not been persisted', () => { <del> let expectedCount = 0; <del> let syntheticEvent; <add> it('should be nullified and log warnings if the synthetic event has not been persisted', () => { <add> let expectedCount = 0; <add> let syntheticEvent; <ide> <del> const eventHandler = e => { <del> syntheticEvent = e; <add> const eventHandler = e => { <add> syntheticEvent = e; <ide> <del> expectedCount++; <del> }; <del> const node = ReactDOM.render(<div onClick={eventHandler} />, container); <add> expectedCount++; <add> }; <add> const node = ReactDOM.render(<div onClick={eventHandler} />, container); <ide> <del> const event = document.createEvent('Event'); <del> event.initEvent('click', true, true); <del> node.dispatchEvent(event); <add> const event = document.createEvent('Event'); <add> event.initEvent('click', true, true); <add> node.dispatchEvent(event); <ide> <del> const getExpectedWarning = property => <del> 'Warning: This synthetic event is reused for performance reasons. If ' + <del> `you're seeing this, you're accessing the property \`${property}\` on a ` + <del> 'released/nullified synthetic event. This is set to null. If you must ' + <del> 'keep the original synthetic event around, use event.persist(). ' + <del> 'See https://fb.me/react-event-pooling for more information.'; <del> <del> // once for each property accessed <del> expect(() => <del> expect(syntheticEvent.type).toBe(null), <del> ).toErrorDev(getExpectedWarning('type'), {withoutStack: true}); <del> expect(() => <del> expect(syntheticEvent.nativeEvent).toBe(null), <del> ).toErrorDev(getExpectedWarning('nativeEvent'), {withoutStack: true}); <del> expect(() => <del> expect(syntheticEvent.target).toBe(null), <del> ).toErrorDev(getExpectedWarning('target'), {withoutStack: true}); <add> const getExpectedWarning = property => <add> 'Warning: This synthetic event is reused for performance reasons. If ' + <add> `you're seeing this, you're accessing the property \`${property}\` on a ` + <add> 'released/nullified synthetic event. This is set to null. If you must ' + <add> 'keep the original synthetic event around, use event.persist(). ' + <add> 'See https://fb.me/react-event-pooling for more information.'; <add> <add> // once for each property accessed <add> expect(() => <add> expect(syntheticEvent.type).toBe(null), <add> ).toErrorDev(getExpectedWarning('type'), {withoutStack: true}); <add> expect(() => <add> expect(syntheticEvent.nativeEvent).toBe(null), <add> ).toErrorDev(getExpectedWarning('nativeEvent'), {withoutStack: true}); <add> expect(() => <add> expect(syntheticEvent.target).toBe(null), <add> ).toErrorDev(getExpectedWarning('target'), {withoutStack: true}); <add> <add> expect(expectedCount).toBe(1); <add> }); <ide> <del> expect(expectedCount).toBe(1); <del> }); <add> it('should warn when setting properties of a synthetic event that has not been persisted', () => { <add> let expectedCount = 0; <add> let syntheticEvent; <ide> <del> it('should warn when setting properties of a synthetic event that has not been persisted', () => { <del> let expectedCount = 0; <del> let syntheticEvent; <add> const eventHandler = e => { <add> syntheticEvent = e; <ide> <del> const eventHandler = e => { <del> syntheticEvent = e; <add> expectedCount++; <add> }; <add> const node = ReactDOM.render(<div onClick={eventHandler} />, container); <ide> <del> expectedCount++; <del> }; <del> const node = ReactDOM.render(<div onClick={eventHandler} />, container); <add> const event = document.createEvent('Event'); <add> event.initEvent('click', true, true); <add> node.dispatchEvent(event); <ide> <del> const event = document.createEvent('Event'); <del> event.initEvent('click', true, true); <del> node.dispatchEvent(event); <add> expect(() => { <add> syntheticEvent.type = 'MouseEvent'; <add> }).toErrorDev( <add> 'Warning: This synthetic event is reused for performance reasons. If ' + <add> "you're seeing this, you're setting the property `type` on a " + <add> 'released/nullified synthetic event. This is effectively a no-op. If you must ' + <add> 'keep the original synthetic event around, use event.persist(). ' + <add> 'See https://fb.me/react-event-pooling for more information.', <add> {withoutStack: true}, <add> ); <add> expect(expectedCount).toBe(1); <add> }); <ide> <del> expect(() => { <del> syntheticEvent.type = 'MouseEvent'; <del> }).toErrorDev( <del> 'Warning: This synthetic event is reused for performance reasons. If ' + <del> "you're seeing this, you're setting the property `type` on a " + <del> 'released/nullified synthetic event. This is effectively a no-op. If you must ' + <del> 'keep the original synthetic event around, use event.persist(). ' + <del> 'See https://fb.me/react-event-pooling for more information.', <del> {withoutStack: true}, <del> ); <del> expect(expectedCount).toBe(1); <del> }); <add> it('should warn when calling `preventDefault` if the synthetic event has not been persisted', () => { <add> let expectedCount = 0; <add> let syntheticEvent; <ide> <del> it('should warn when calling `preventDefault` if the synthetic event has not been persisted', () => { <del> let expectedCount = 0; <del> let syntheticEvent; <add> const eventHandler = e => { <add> syntheticEvent = e; <add> expectedCount++; <add> }; <add> const node = ReactDOM.render(<div onClick={eventHandler} />, container); <ide> <del> const eventHandler = e => { <del> syntheticEvent = e; <del> expectedCount++; <del> }; <del> const node = ReactDOM.render(<div onClick={eventHandler} />, container); <add> const event = document.createEvent('Event'); <add> event.initEvent('click', true, true); <add> node.dispatchEvent(event); <ide> <del> const event = document.createEvent('Event'); <del> event.initEvent('click', true, true); <del> node.dispatchEvent(event); <add> expect(() => <add> syntheticEvent.preventDefault(), <add> ).toErrorDev( <add> 'Warning: This synthetic event is reused for performance reasons. If ' + <add> "you're seeing this, you're accessing the method `preventDefault` on a " + <add> 'released/nullified synthetic event. This is a no-op function. If you must ' + <add> 'keep the original synthetic event around, use event.persist(). ' + <add> 'See https://fb.me/react-event-pooling for more information.', <add> {withoutStack: true}, <add> ); <add> expect(expectedCount).toBe(1); <add> }); <ide> <del> expect(() => <del> syntheticEvent.preventDefault(), <del> ).toErrorDev( <del> 'Warning: This synthetic event is reused for performance reasons. If ' + <del> "you're seeing this, you're accessing the method `preventDefault` on a " + <del> 'released/nullified synthetic event. This is a no-op function. If you must ' + <del> 'keep the original synthetic event around, use event.persist(). ' + <del> 'See https://fb.me/react-event-pooling for more information.', <del> {withoutStack: true}, <del> ); <del> expect(expectedCount).toBe(1); <del> }); <add> it('should warn when calling `stopPropagation` if the synthetic event has not been persisted', () => { <add> let expectedCount = 0; <add> let syntheticEvent; <ide> <del> it('should warn when calling `stopPropagation` if the synthetic event has not been persisted', () => { <del> let expectedCount = 0; <del> let syntheticEvent; <add> const eventHandler = e => { <add> syntheticEvent = e; <add> expectedCount++; <add> }; <add> const node = ReactDOM.render(<div onClick={eventHandler} />, container); <ide> <del> const eventHandler = e => { <del> syntheticEvent = e; <del> expectedCount++; <del> }; <del> const node = ReactDOM.render(<div onClick={eventHandler} />, container); <add> const event = document.createEvent('Event'); <add> event.initEvent('click', true, true); <ide> <del> const event = document.createEvent('Event'); <del> event.initEvent('click', true, true); <add> node.dispatchEvent(event); <ide> <del> node.dispatchEvent(event); <add> expect(() => <add> syntheticEvent.stopPropagation(), <add> ).toErrorDev( <add> 'Warning: This synthetic event is reused for performance reasons. If ' + <add> "you're seeing this, you're accessing the method `stopPropagation` on a " + <add> 'released/nullified synthetic event. This is a no-op function. If you must ' + <add> 'keep the original synthetic event around, use event.persist(). ' + <add> 'See https://fb.me/react-event-pooling for more information.', <add> {withoutStack: true}, <add> ); <add> expect(expectedCount).toBe(1); <add> }); <ide> <del> expect(() => <del> syntheticEvent.stopPropagation(), <del> ).toErrorDev( <del> 'Warning: This synthetic event is reused for performance reasons. If ' + <del> "you're seeing this, you're accessing the method `stopPropagation` on a " + <del> 'released/nullified synthetic event. This is a no-op function. If you must ' + <del> 'keep the original synthetic event around, use event.persist(). ' + <del> 'See https://fb.me/react-event-pooling for more information.', <del> {withoutStack: true}, <del> ); <del> expect(expectedCount).toBe(1); <del> }); <add> it('should warn when calling `isPropagationStopped` if the synthetic event has not been persisted', () => { <add> let expectedCount = 0; <add> let syntheticEvent; <ide> <del> it('should warn when calling `isPropagationStopped` if the synthetic event has not been persisted', () => { <del> let expectedCount = 0; <del> let syntheticEvent; <add> const eventHandler = e => { <add> syntheticEvent = e; <add> expectedCount++; <add> }; <add> const node = ReactDOM.render(<div onClick={eventHandler} />, container); <ide> <del> const eventHandler = e => { <del> syntheticEvent = e; <del> expectedCount++; <del> }; <del> const node = ReactDOM.render(<div onClick={eventHandler} />, container); <add> const event = document.createEvent('Event'); <add> event.initEvent('click', true, true); <add> node.dispatchEvent(event); <ide> <del> const event = document.createEvent('Event'); <del> event.initEvent('click', true, true); <del> node.dispatchEvent(event); <add> expect(() => <add> expect(syntheticEvent.isPropagationStopped()).toBe(false), <add> ).toErrorDev( <add> 'Warning: This synthetic event is reused for performance reasons. If ' + <add> "you're seeing this, you're accessing the method `isPropagationStopped` on a " + <add> 'released/nullified synthetic event. This is a no-op function. If you must ' + <add> 'keep the original synthetic event around, use event.persist(). ' + <add> 'See https://fb.me/react-event-pooling for more information.', <add> {withoutStack: true}, <add> ); <add> expect(expectedCount).toBe(1); <add> }); <ide> <del> expect(() => <del> expect(syntheticEvent.isPropagationStopped()).toBe(false), <del> ).toErrorDev( <del> 'Warning: This synthetic event is reused for performance reasons. If ' + <del> "you're seeing this, you're accessing the method `isPropagationStopped` on a " + <del> 'released/nullified synthetic event. This is a no-op function. If you must ' + <del> 'keep the original synthetic event around, use event.persist(). ' + <del> 'See https://fb.me/react-event-pooling for more information.', <del> {withoutStack: true}, <del> ); <del> expect(expectedCount).toBe(1); <del> }); <add> it('should warn when calling `isDefaultPrevented` if the synthetic event has not been persisted', () => { <add> let expectedCount = 0; <add> let syntheticEvent; <ide> <del> it('should warn when calling `isDefaultPrevented` if the synthetic event has not been persisted', () => { <del> let expectedCount = 0; <del> let syntheticEvent; <add> const eventHandler = e => { <add> syntheticEvent = e; <add> expectedCount++; <add> }; <add> const node = ReactDOM.render(<div onClick={eventHandler} />, container); <ide> <del> const eventHandler = e => { <del> syntheticEvent = e; <del> expectedCount++; <del> }; <del> const node = ReactDOM.render(<div onClick={eventHandler} />, container); <add> const event = document.createEvent('Event'); <add> event.initEvent('click', true, true); <add> node.dispatchEvent(event); <ide> <del> const event = document.createEvent('Event'); <del> event.initEvent('click', true, true); <del> node.dispatchEvent(event); <add> expect(() => <add> expect(syntheticEvent.isDefaultPrevented()).toBe(false), <add> ).toErrorDev( <add> 'Warning: This synthetic event is reused for performance reasons. If ' + <add> "you're seeing this, you're accessing the method `isDefaultPrevented` on a " + <add> 'released/nullified synthetic event. This is a no-op function. If you must ' + <add> 'keep the original synthetic event around, use event.persist(). ' + <add> 'See https://fb.me/react-event-pooling for more information.', <add> {withoutStack: true}, <add> ); <add> expect(expectedCount).toBe(1); <add> }); <ide> <del> expect(() => <del> expect(syntheticEvent.isDefaultPrevented()).toBe(false), <del> ).toErrorDev( <del> 'Warning: This synthetic event is reused for performance reasons. If ' + <del> "you're seeing this, you're accessing the method `isDefaultPrevented` on a " + <del> 'released/nullified synthetic event. This is a no-op function. If you must ' + <del> 'keep the original synthetic event around, use event.persist(). ' + <del> 'See https://fb.me/react-event-pooling for more information.', <del> {withoutStack: true}, <del> ); <del> expect(expectedCount).toBe(1); <del> }); <add> it('should properly log warnings when events simulated with rendered components', () => { <add> let event; <add> function assignEvent(e) { <add> event = e; <add> } <add> const node = ReactDOM.render(<div onClick={assignEvent} />, container); <add> node.click(); <ide> <del> it('should properly log warnings when events simulated with rendered components', () => { <del> let event; <del> function assignEvent(e) { <del> event = e; <del> } <del> const node = ReactDOM.render(<div onClick={assignEvent} />, container); <del> node.click(); <del> <del> // access a property to cause the warning <del> expect(() => { <del> event.nativeEvent; // eslint-disable-line no-unused-expressions <del> }).toErrorDev( <del> 'Warning: This synthetic event is reused for performance reasons. If ' + <del> "you're seeing this, you're accessing the property `nativeEvent` on a " + <del> 'released/nullified synthetic event. This is set to null. If you must ' + <del> 'keep the original synthetic event around, use event.persist(). ' + <del> 'See https://fb.me/react-event-pooling for more information.', <del> {withoutStack: true}, <del> ); <del> }); <add> // access a property to cause the warning <add> expect(() => { <add> event.nativeEvent; // eslint-disable-line no-unused-expressions <add> }).toErrorDev( <add> 'Warning: This synthetic event is reused for performance reasons. If ' + <add> "you're seeing this, you're accessing the property `nativeEvent` on a " + <add> 'released/nullified synthetic event. This is set to null. If you must ' + <add> 'keep the original synthetic event around, use event.persist(). ' + <add> 'See https://fb.me/react-event-pooling for more information.', <add> {withoutStack: true}, <add> ); <add> }); <add> } <ide> <ide> // TODO: we might want to re-add a warning like this in the future, <ide> // but it shouldn't use Proxies because they make debugging difficult. <ide><path>packages/react-dom/src/events/__tests__/SyntheticKeyboardEvent-test.js <ide> <ide> let React; <ide> let ReactDOM; <add>const ReactFeatureFlags = require('shared/ReactFeatureFlags'); <ide> <ide> describe('SyntheticKeyboardEvent', () => { <ide> let container; <ide> describe('SyntheticKeyboardEvent', () => { <ide> expect(expectedCount).toBe(3); <ide> }); <ide> <del> it('is able to `persist`', () => { <del> const persistentEvents = []; <del> const eventHandler = event => { <del> expect(event.isPersistent()).toBe(false); <del> event.persist(); <del> expect(event.isPersistent()).toBe(true); <del> persistentEvents.push(event); <del> }; <del> const div = ReactDOM.render( <del> <div <del> onKeyDown={eventHandler} <del> onKeyUp={eventHandler} <del> onKeyPress={eventHandler} <del> />, <del> container, <del> ); <add> if (!ReactFeatureFlags.enableModernEventSystem) { <add> it('is able to `persist`', () => { <add> const persistentEvents = []; <add> const eventHandler = event => { <add> expect(event.isPersistent()).toBe(false); <add> event.persist(); <add> expect(event.isPersistent()).toBe(true); <add> persistentEvents.push(event); <add> }; <add> const div = ReactDOM.render( <add> <div <add> onKeyDown={eventHandler} <add> onKeyUp={eventHandler} <add> onKeyPress={eventHandler} <add> />, <add> container, <add> ); <ide> <del> div.dispatchEvent( <del> new KeyboardEvent('keydown', { <del> keyCode: 40, <del> bubbles: true, <del> cancelable: true, <del> }), <del> ); <del> div.dispatchEvent( <del> new KeyboardEvent('keyup', { <del> keyCode: 40, <del> bubbles: true, <del> cancelable: true, <del> }), <del> ); <del> div.dispatchEvent( <del> new KeyboardEvent('keypress', { <del> charCode: 40, <del> keyCode: 40, <del> bubbles: true, <del> cancelable: true, <del> }), <del> ); <del> expect(persistentEvents.length).toBe(3); <del> expect(persistentEvents[0].type).toBe('keydown'); <del> expect(persistentEvents[1].type).toBe('keyup'); <del> expect(persistentEvents[2].type).toBe('keypress'); <del> }); <add> div.dispatchEvent( <add> new KeyboardEvent('keydown', { <add> keyCode: 40, <add> bubbles: true, <add> cancelable: true, <add> }), <add> ); <add> div.dispatchEvent( <add> new KeyboardEvent('keyup', { <add> keyCode: 40, <add> bubbles: true, <add> cancelable: true, <add> }), <add> ); <add> div.dispatchEvent( <add> new KeyboardEvent('keypress', { <add> charCode: 40, <add> keyCode: 40, <add> bubbles: true, <add> cancelable: true, <add> }), <add> ); <add> expect(persistentEvents.length).toBe(3); <add> expect(persistentEvents[0].type).toBe('keydown'); <add> expect(persistentEvents[1].type).toBe('keyup'); <add> expect(persistentEvents[2].type).toBe('keypress'); <add> }); <add> } <ide> }); <ide> }); <ide><path>packages/react-dom/src/events/__tests__/SyntheticWheelEvent-test.js <ide> <ide> let React; <ide> let ReactDOM; <add>const ReactFeatureFlags = require('shared/ReactFeatureFlags'); <ide> <ide> describe('SyntheticWheelEvent', () => { <ide> let container; <ide> describe('SyntheticWheelEvent', () => { <ide> expect(events.length).toBe(2); <ide> }); <ide> <del> it('should be able to `persist`', () => { <del> const events = []; <del> const onWheel = event => { <del> expect(event.isPersistent()).toBe(false); <del> event.persist(); <del> expect(event.isPersistent()).toBe(true); <del> events.push(event); <del> }; <del> ReactDOM.render(<div onWheel={onWheel} />, container); <del> <del> container.firstChild.dispatchEvent( <del> new MouseEvent('wheel', { <del> bubbles: true, <del> }), <del> ); <del> <del> expect(events.length).toBe(1); <del> expect(events[0].type).toBe('wheel'); <del> }); <add> if (!ReactFeatureFlags.enableModernEventSystem) { <add> it('should be able to `persist`', () => { <add> const events = []; <add> const onWheel = event => { <add> expect(event.isPersistent()).toBe(false); <add> event.persist(); <add> expect(event.isPersistent()).toBe(true); <add> events.push(event); <add> }; <add> ReactDOM.render(<div onWheel={onWheel} />, container); <add> <add> container.firstChild.dispatchEvent( <add> new MouseEvent('wheel', { <add> bubbles: true, <add> }), <add> ); <add> <add> expect(events.length).toBe(1); <add> expect(events[0].type).toBe('wheel'); <add> }); <add> } <ide> });
7
Python
Python
drop cronky tests
d8ede0355c32455989ca5f955d555ffaf827b296
<ide><path>djangorestframework/tests/accept.py <del>from django.conf.urls.defaults import patterns, url, include <del>from django.test import TestCase <del> <del>from djangorestframework.compat import RequestFactory <del>from djangorestframework.views import APIView <del>from djangorestframework.response import Response <del> <del> <del># See: http://www.useragentstring.com/ <del>MSIE_9_USER_AGENT = 'Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))' <del>MSIE_8_USER_AGENT = 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; Media Center PC 4.0; SLCC1; .NET CLR 3.0.04320)' <del>MSIE_7_USER_AGENT = 'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)' <del>FIREFOX_4_0_USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)' <del>CHROME_11_0_USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.17 (KHTML, like Gecko) Chrome/11.0.655.0 Safari/534.17' <del>SAFARI_5_0_USER_AGENT = 'Mozilla/5.0 (X11; U; Linux x86_64; en-ca) AppleWebKit/531.2+ (KHTML, like Gecko) Version/5.0 Safari/531.2+' <del>OPERA_11_0_MSIE_USER_AGENT = 'Mozilla/4.0 (compatible; MSIE 8.0; X11; Linux x86_64; pl) Opera 11.00' <del>OPERA_11_0_OPERA_USER_AGENT = 'Opera/9.80 (X11; Linux x86_64; U; pl) Presto/2.7.62 Version/11.00' <del> <del> <del>urlpatterns = patterns('', <del> url(r'^api', include('djangorestframework.urls', namespace='djangorestframework')) <del>) <del> <del> <del>class UserAgentMungingTest(TestCase): <del> """ <del> We need to fake up the accept headers when we deal with MSIE. Blergh. <del> http://www.gethifi.com/blog/browser-rest-http-accept-headers <del> """ <del> <del> urls = 'djangorestframework.tests.accept' <del> <del> def setUp(self): <del> <del> class MockView(APIView): <del> permissions = () <del> response_class = Response <del> <del> def get(self, request): <del> return self.response_class({'a': 1, 'b': 2, 'c': 3}) <del> <del> self.req = RequestFactory() <del> self.MockView = MockView <del> self.view = MockView.as_view() <del> <del> def test_munge_msie_accept_header(self): <del> """Send MSIE user agent strings and ensure that we get an HTML response, <del> even if we set a */* accept header.""" <del> for user_agent in (MSIE_9_USER_AGENT, <del> MSIE_8_USER_AGENT, <del> MSIE_7_USER_AGENT): <del> req = self.req.get('/', HTTP_ACCEPT='*/*', HTTP_USER_AGENT=user_agent) <del> resp = self.view(req) <del> resp.render() <del> self.assertEqual(resp['Content-Type'], 'text/html') <del> <del> def test_dont_rewrite_msie_accept_header(self): <del> """Turn off _IGNORE_IE_ACCEPT_HEADER, send MSIE user agent strings and ensure <del> that we get a JSON response if we set a */* accept header.""" <del> class IgnoreIEAcceptResponse(Response): <del> _IGNORE_IE_ACCEPT_HEADER = False <del> view = self.MockView.as_view(response_class=IgnoreIEAcceptResponse) <del> <del> for user_agent in (MSIE_9_USER_AGENT, <del> MSIE_8_USER_AGENT, <del> MSIE_7_USER_AGENT): <del> req = self.req.get('/', HTTP_ACCEPT='*/*', HTTP_USER_AGENT=user_agent) <del> resp = view(req) <del> resp.render() <del> self.assertEqual(resp['Content-Type'], 'application/json') <del> <del> def test_dont_munge_nice_browsers_accept_header(self): <del> """Send Non-MSIE user agent strings and ensure that we get a JSON response, <del> if we set a */* Accept header. (Other browsers will correctly set the Accept header)""" <del> for user_agent in (FIREFOX_4_0_USER_AGENT, <del> CHROME_11_0_USER_AGENT, <del> SAFARI_5_0_USER_AGENT, <del> OPERA_11_0_MSIE_USER_AGENT, <del> OPERA_11_0_OPERA_USER_AGENT): <del> req = self.req.get('/', HTTP_ACCEPT='*/*', HTTP_USER_AGENT=user_agent) <del> resp = self.view(req) <del> resp.render() <del> self.assertEqual(resp['Content-Type'], 'application/json')
1
Javascript
Javascript
add title to default error page
4df7e48f94b70a02ca89bf8889f8c7e432c5ac48
<ide><path>lib/error.js <ide> export default class Error extends React.Component { <ide> return <div style={styles.error}> <ide> <Head> <ide> <meta name='viewport' content='width=device-width, initial-scale=1.0' /> <add> <title>{statusCode}: {title}</title> <ide> </Head> <ide> <div> <ide> <style dangerouslySetInnerHTML={{ __html: 'body { margin: 0 }' }} />
1
Text
Text
add v4.9.0-beta.3 to changelog
cca036eb575e10676e089f0d8efa01edd474cdb1
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v4.9.0-beta.3 (November 2, 2022) <add> <add>- [CVE pending](https://emberjs.com/blog/ember-4-8-1-released) Fix a prototype pollution vulnerability in `set` and `setProperties` <add>- [#20233](https://github.com/emberjs/ember.js/pull/20233) [BUGFIX] Include package name in deprecation error message <add>- [#20235](https://github.com/emberjs/ember.js/pull/20235) [BUGFIX] Update `@types/node` for TS 4.9 issue <add>- [#20238](https://github.com/emberjs/ember.js/pull/20238) [BUGFIX] Update Node.js versions to match support policy <add>- [#20244](https://github.com/emberjs/ember.js/pull/20244) [BUGFIX] Expose getComponentTemplate type <add> <ide> ### v4.8.1 (November 2, 2022) <ide> <ide> - [CVE pending](https://emberjs.com/blog/ember-4-8-1-released) Fix a prototype pollution vulnerability in `set` and `setProperties`
1
Ruby
Ruby
reduce loops in head route matching
d7ac60719a104df5f81e10459da0734369b34ab5
<ide><path>actionpack/lib/action_dispatch/journey/router.rb <ide> def find_routes(req) <ide> r.path.match?(req.path_info) <ide> } <ide> <del> routes = <del> if req.head? <del> match_head_routes(routes, req) <del> else <del> match_routes(routes, req) <del> end <add> if req.head? <add> routes = match_head_routes(routes, req) <add> else <add> routes.select! { |r| r.matches?(req) } <add> end <ide> <ide> routes.sort_by!(&:precedence) <ide> <ide> def find_routes(req) <ide> end <ide> <ide> def match_head_routes(routes, req) <del> verb_specific_routes = routes.select(&:requires_matching_verb?) <del> head_routes = match_routes(verb_specific_routes, req) <del> <del> if head_routes.empty? <del> begin <del> req.request_method = "GET" <del> match_routes(routes, req) <del> ensure <del> req.request_method = "HEAD" <del> end <del> else <del> head_routes <add> head_routes = routes.select { |r| r.requires_matching_verb? && r.matches?(req) } <add> return head_routes unless head_routes.empty? <add> <add> begin <add> req.request_method = "GET" <add> routes.select! { |r| r.matches?(req) } <add> routes <add> ensure <add> req.request_method = "HEAD" <ide> end <ide> end <del> <del> def match_routes(routes, req) <del> routes.select { |r| r.matches?(req) } <del> end <ide> end <ide> end <ide> end
1
Python
Python
use log.debug instead of print in setup.py's
bfb1633766b1e6b1c72de094aa565c6e6ec0db80
<ide><path>numpy/f2py/setup.py <ide> import os <ide> import sys <ide> from distutils.dep_util import newer <add>from numpy.distutils import log <ide> from numpy.distutils.core import setup <ide> from numpy.distutils.misc_util import Configuration <ide> <ide> def generate_f2py_py(build_dir): <ide> f2py_exe = f2py_exe + '.py' <ide> target = os.path.join(build_dir,f2py_exe) <ide> if newer(__file__,target): <del> print 'Creating',target <add> log.info('Creating %s', target) <ide> f = open(target,'w') <ide> f.write('''\ <ide> #!/usr/bin/env %s <ide> def generate_f2py_py(build_dir): <ide> <ide> config.add_scripts(generate_f2py_py) <ide> <del> print 'F2PY Version',config.get_version() <add> log.info('F2PY Version %s', config.get_version()) <ide> <ide> return config <ide>
1
Python
Python
add docs to bigquery check operators
d8a72893a314602a296308312aa658f3afce2d0b
<ide><path>airflow/contrib/operators/bigquery_check_operator.py <ide> <ide> <ide> class BigQueryCheckOperator(CheckOperator): <del> # TODO pydocs <add> """ <add> Performs checks against Presto. The ``BigQueryCheckOperator`` expects <add> a sql query that will return a single row. Each value on that <add> first row is evaluated using python ``bool`` casting. If any of the <add> values return ``False`` the check is failed and errors out. <add> <add> Note that Python bool casting evals the following as ``False``: <add> * False <add> * 0 <add> * Empty string (``""``) <add> * Empty list (``[]``) <add> * Empty dictionary or set (``{}``) <add> <add> Given a query like ``SELECT COUNT(*) FROM foo``, it will fail only if <add> the count ``== 0``. You can craft much more complex query that could, <add> for instance, check that the table has the same number of rows as <add> the source table upstream, or that the count of today's partition is <add> greater than yesterday's partition, or that a set of metrics are less <add> than 3 standard deviation for the 7 day average. <add> <add> This operator can be used as a data quality check in your pipeline, and <add> depending on where you put it in your DAG, you have the choice to <add> stop the critical path, preventing from <add> publishing dubious data, or on the side and receive email alterts <add> without stopping the progress of the DAG. <add> <add> :param sql: the sql to be executed <add> :type sql: string <add> :param bigquery_conn_id: reference to the BigQuery database <add> :type presto_conn_id: string <add> """ <add> <ide> @apply_defaults <ide> def __init__( <ide> self, <ide> def get_db_hook(self): <ide> return BigQueryHook(bigquery_conn_id=self.bigquery_conn_id) <ide> <ide> class BigQueryValueCheckOperator(ValueCheckOperator): <del> # TODO pydocs <add> """ <add> Performs a simple value check using sql code. <add> <add> :param sql: the sql to be executed <add> :type sql: string <add> """ <ide> <ide> @apply_defaults <ide> def __init__( <ide> def __init__( <ide> def get_db_hook(self): <ide> return BigQueryHook(bigquery_conn_id=self.bigquery_conn_id) <ide> <del> <ide> class BigQueryIntervalCheckOperator(IntervalCheckOperator): <del> # TODO pydocs <add> """ <add> Checks that the values of metrics given as SQL expressions are within <add> a certain tolerance of the ones from days_back before. <add> <add> This method constructs a query like so: <add> <add> SELECT {metrics_threshold_dict_key} FROM {table} <add> WHERE {date_filter_column}=<date> <add> <add> :param table: the table name <add> :type table: str <add> :param days_back: number of days between ds and the ds we want to check <add> against. Defaults to 7 days <add> :type days_back: int <add> :param metrics_threshold: a dictionary of ratios indexed by metrics, for <add> example 'COUNT(*)': 1.5 would require a 50 percent or less difference <add> between the current day, and the prior days_back. <add> :type metrics_threshold: dict <add> """ <ide> <ide> @apply_defaults <ide> def __init__(
1
Go
Go
check nil before set resource.oomkilldisable
09a33b5f60557ee3846baa48f5628bc6b8a70a9b
<ide><path>daemon/container_operations_unix.go <ide> func (daemon *Daemon) populateCommand(c *container.Container, env []string) erro <ide> BlkioThrottleWriteBpsDevice: writeBpsDevice, <ide> BlkioThrottleReadIOpsDevice: readIOpsDevice, <ide> BlkioThrottleWriteIOpsDevice: writeIOpsDevice, <del> OomKillDisable: *c.HostConfig.OomKillDisable, <ide> MemorySwappiness: -1, <ide> } <ide> <add> if c.HostConfig.OomKillDisable != nil { <add> resources.OomKillDisable = *c.HostConfig.OomKillDisable <add> } <ide> if c.HostConfig.MemorySwappiness != nil { <ide> resources.MemorySwappiness = *c.HostConfig.MemorySwappiness <ide> }
1
Ruby
Ruby
fix broken driver test
fef8d97a2c75511df62915b617743b47f1a2f43a
<ide><path>actionpack/test/dispatch/system_testing/driver_test.rb <ide> class DriverTest < ActiveSupport::TestCase <ide> end <ide> driver.use <ide> <del> expected = { args: ["start-maximized"], mobileEmulation: { deviceName: "iphone 6" }, prefs: { detach: true } } <add> expected = { "goog:chromeOptions" => { args: ["start-maximized"], mobileEmulation: { deviceName: "iphone 6" }, prefs: { detach: true } } } <ide> assert_equal expected, driver_option.as_json <ide> end <ide> <ide> class DriverTest < ActiveSupport::TestCase <ide> end <ide> driver.use <ide> <del> expected = { args: ["start-maximized"], mobileEmulation: { deviceName: "iphone 6" }, prefs: { detach: true } } <add> expected = { "goog:chromeOptions" => { args: ["start-maximized"], mobileEmulation: { deviceName: "iphone 6" }, prefs: { detach: true } } } <ide> assert_equal expected, driver_option.as_json <ide> end <ide>
1