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 missing documentation for static ip options | ee14232647085ce2faf7167959728977d36e5503 | <ide><path>docs/reference/api/docker_remote_api_v1.22.md
<ide> Content-Type: application/json
<ide>
<ide> {
<ide> "Container":"3613f73ba0e4",
<del> "endpoint_config": {
<add> "EndpointConfig": {
<ide> "test_nw": {
<ide> "IPv4Address":"172.24.56.89",
<ide> "IPv6Address":"2001:db8::5689"
<ide><path>docs/reference/commandline/create.md
<ide> Creates a new container.
<ide> -h, --hostname="" Container host name
<ide> --help Print usage
<ide> -i, --interactive Keep STDIN open even if not attached
<add> --ip="" Container IPv4 address (e.g. 172.30.100.104)
<add> --ip6="" Container IPv6 address (e.g. 2001:db8::33)
<ide> --ipc="" IPC namespace to use
<ide> --isolation="" Container isolation technology
<ide> --kernel-memory="" Kernel memory limit
<ide><path>docs/reference/commandline/network_connect.md
<ide> parent = "smn_cli"
<ide> Connects a container to a network
<ide>
<ide> --help Print usage
<del> --ip IP Address
<add> --ip IPv4 Address
<ide> --ip6 IPv6 Address
<ide> --link=[] Add a link to another container
<ide>
<ide> $ docker network connect --link container1:c1 multi-host-network container2
<ide> ```
<ide>
<ide> You can pause, restart, and stop containers that are connected to a network.
<del>Paused containers remain connected and a revealed by a `network inspect`. When
<del>the container is stopped, it does not appear on the network until you restart
<del>it. The container's IP address is not guaranteed to remain the same when a
<del>stopped container rejoins the network, unless you specified one when you run
<del>`docker network connect` command.
<add>Paused containers remain connected and can be revealed by a `network inspect`.
<add>When the container is stopped, it does not appear on the network until you restart
<add>it. If specified, the container's IP address(es) will be reapplied (if still available)
<add>when a stopped container rejoins the network. One way to guarantee that the container
<add>will be assigned the same IP addresses when it rejoins the network after a stop
<add>or a disconnect, is to specify the `--ip-range` when creating the network, and choose
<add>the static IP address(es) from outside the range. This will ensure that the IP address
<add>will not be given to other dynamic containers while this container is not on the network.
<add>
<add>```bash
<add>$ docker network create --subnet 172.20.0.0/16 --ip-range 172.20.240.0/20 multi-host-network
<add>```
<add>
<add>```bash
<add>$ docker network connect --ip 172.20.128.2 multi-host-network container2
<add>```
<ide>
<ide> To verify the container is connected, use the `docker network inspect` command. Use `docker network disconnect` to remove a container from the network.
<ide>
<ide><path>docs/reference/commandline/run.md
<ide> parent = "smn_cli"
<ide> -h, --hostname="" Container host name
<ide> --help Print usage
<ide> -i, --interactive Keep STDIN open even if not attached
<add> --ip="" Container IPv4 address (e.g. 172.30.100.104)
<add> --ip6="" Container IPv6 address (e.g. 2001:db8::33)
<ide> --ipc="" IPC namespace to use
<ide> --isolation="" Container isolation technology
<ide> --kernel-memory="" Kernel memory limit
<ide> parent = "smn_cli"
<ide> --log-opt=[] Log driver specific options
<ide> -m, --memory="" Memory limit
<ide> --mac-address="" Container MAC address (e.g. 92:d0:c6:0a:29:33)
<del> --ip="" Container IPv4 address (e.g. 172.30.100.104)
<del> --ip6="" Container IPv6 address (e.g. 2001:db8::33)
<ide> --memory-reservation="" Memory soft limit
<ide> --memory-swap="" A positive integer equal to memory plus swap. Specify -1 to enable unlimited swap.
<ide> --memory-swappiness="" Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100.
<ide> This adds the `busybox` container to the `mynet` network.
<ide> $ docker run -itd --net=my-multihost-network busybox
<ide> ```
<ide>
<add>You can also choose the IP addresses for the container with `--ip` and `--ip6`
<add>flags when you start the container on a user-defined network.
<add>
<add>```bash
<add>$ docker run -itd --net=my-multihost-network --ip=10.10.9.75 busybox
<add>```
<add>
<ide> If you want to add a running container to a network use the `docker network connect` subcommand.
<ide>
<ide> You can connect multiple containers to the same network. Once connected, the
<ide><path>docs/reference/run.md
<ide> of the containers.
<ide> --add-host="" : Add a line to /etc/hosts (host:IP)
<ide> --mac-address="" : Sets the container's Ethernet device's MAC address
<ide> --ip="" : Sets the container's Ethernet device's IPv4 address
<del> --ip6="" : Sets the container's Ethernet device's IPv6 address
<add> --ip6="" : Sets the container's Ethernet device's IPv6 address
<ide>
<ide> By default, all containers have networking enabled and they can make any
<ide> outgoing connections. The operator can completely disable networking
<ide><path>man/docker-create.1.md
<ide> docker-create - Create a new container
<ide> [**-h**|**--hostname**[=*HOSTNAME*]]
<ide> [**--help**]
<ide> [**-i**|**--interactive**]
<add>[**--ip**[=*IPv4-ADDRESS*]]
<add>[**--ip6**[=*IPv6-ADDRESS*]]
<ide> [**--ipc**[=*IPC*]]
<ide> [**--isolation**[=*default*]]
<ide> [**--kernel-memory**[=*KERNEL-MEMORY*]]
<ide> two memory nodes.
<ide> **-i**, **--interactive**=*true*|*false*
<ide> Keep STDIN open even if not attached. The default is *false*.
<ide>
<add>**--ip**=""
<add> Sets the container's interface IPv4 address (e.g. 172.23.0.9)
<add>
<add> It can only be used in conjunction with **--net** for user-defined networks
<add>
<add>**--ip6**=""
<add> Sets the container's interface IPv6 address (e.g. 2001:db8::1b99)
<add>
<add> It can only be used in conjunction with **--net** for user-defined networks
<add>
<ide> **--ipc**=""
<ide> Default is to create a private IPC namespace (POSIX SysV IPC) for the container
<ide> 'container:<name|id>': reuses another container shared memory, semaphores and message queues
<ide><path>man/docker-network-connect.1.md
<ide> $ docker network connect multi-host-network container1
<ide> You can also use the `docker run --net=<network-name>` option to start a container and immediately connect it to a network.
<ide>
<ide> ```bash
<del>$ docker run -itd --net=multi-host-network busybox
<add>$ docker run -itd --net=multi-host-network --ip 172.20.88.22 --ip6 2001:db8::8822 busybox
<ide> ```
<ide>
<ide> You can pause, restart, and stop containers that are connected to a network.
<del>Paused containers remain connected and a revealed by a `network inspect`. When
<del>the container is stopped, it does not appear on the network until you restart
<del>it. The container's IP address is not guaranteed to remain the same when a
<del>stopped container rejoins the network.
<add>Paused containers remain connected and can be revealed by a `network inspect`.
<add>When the container is stopped, it does not appear on the network until you restart
<add>it. If specified, the container's IP address(es) will be reapplied (if still available)
<add>when a stopped container rejoins the network. One way to guarantee that the container
<add>will be assigned the same IP addresses when it rejoins the network after a stop
<add>or a disconnect, is to specify the `--ip-range` when creating the network, and choose
<add>the static IP address(es) from outside the range. This will ensure that the IP address
<add>will not be given to other dynamic containers while this container is not on the network.
<add>
<add>```bash
<add>$ docker network create --subnet 172.20.0.0/16 --ip-range 172.20.240.0/20 multi-host-network
<add>```
<add>
<add>```bash
<add>$ docker network connect --ip 172.20.128.2 multi-host-network container2
<add>```
<ide>
<ide> To verify the container is connected, use the `docker network inspect` command. Use `docker network disconnect` to remove a container from the network.
<ide>
<ide><path>man/docker-run.1.md
<ide> docker-run - Run a command in a new container
<ide> [**-h**|**--hostname**[=*HOSTNAME*]]
<ide> [**--help**]
<ide> [**-i**|**--interactive**]
<add>[**--ip**[=*IPv4-ADDRESS*]]
<add>[**--ip6**[=*IPv6-ADDRESS*]]
<ide> [**--ipc**[=*IPC*]]
<ide> [**--isolation**[=*default*]]
<ide> [**--kernel-memory**[=*KERNEL-MEMORY*]]
<ide> redirection on the host system.
<ide>
<ide> When set to true, keep stdin open even if not attached. The default is false.
<ide>
<add>**--ip**=""
<add> Sets the container's interface IPv4 address (e.g. 172.23.0.9)
<add>
<add> It can only be used in conjunction with **--net** for user-defined networks
<add>
<add>**--ip6**=""
<add> Sets the container's interface IPv6 address (e.g. 2001:db8::1b99)
<add>
<add> It can only be used in conjunction with **--net** for user-defined networks
<add>
<ide> **--ipc**=""
<ide> Default is to create a private IPC namespace (POSIX SysV IPC) for the container
<ide> 'container:<name|id>': reuses another container shared memory, semaphores and message queues | 8 |
Python | Python | set version to v2.3.3 | ce18fc6588ff6f1a45e0e5aed4f1e23e2efa1bcb | <ide><path>spacy/about.py
<ide> # fmt: off
<ide> __title__ = "spacy"
<del>__version__ = "2.3.3.dev0"
<add>__version__ = "2.3.3"
<ide> __release__ = True
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" | 1 |
PHP | PHP | remove unused tests constant | e5cbf95bb225587db39296b3493903dc20f8beb6 | <ide><path>tests/bootstrap.php
<ide> // Point app constants to the test app.
<ide> define('APP', TEST_APP . 'TestApp' . DS);
<ide> define('WWW_ROOT', TEST_APP . 'webroot' . DS);
<del>define('TESTS', TEST_APP . 'tests' . DS);
<ide> define('CONFIG', TEST_APP . 'config' . DS);
<ide>
<ide> //@codingStandardsIgnoreStart | 1 |
Javascript | Javascript | initialize update queue object on mount | 7bf40e1cfdb780788700a41bf30163fdb8d105a3 | <ide><path>packages/react-noop-renderer/src/createReactNoop.js
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide>
<ide> function logUpdateQueue(updateQueue: UpdateQueue<mixed>, depth) {
<ide> log(' '.repeat(depth + 1) + 'QUEUED UPDATES');
<del> const firstUpdate = updateQueue.firstUpdate;
<del> if (!firstUpdate) {
<add> const last = updateQueue.baseQueue;
<add> if (last === null) {
<ide> return;
<ide> }
<add> const first = last.next;
<add> let update = first;
<add> if (update !== null) {
<add> do {
<add> log(
<add> ' '.repeat(depth + 1) + '~',
<add> '[' + update.expirationTime + ']',
<add> );
<add> } while (update !== null && update !== first);
<add> }
<ide>
<del> log(
<del> ' '.repeat(depth + 1) + '~',
<del> '[' + firstUpdate.expirationTime + ']',
<del> );
<del> while (firstUpdate.next) {
<del> log(
<del> ' '.repeat(depth + 1) + '~',
<del> '[' + firstUpdate.expirationTime + ']',
<del> );
<add> const lastPending = updateQueue.shared.pending;
<add> if (lastPending !== null) {
<add> const firstPending = lastPending.next;
<add> let pendingUpdate = firstPending;
<add> if (pendingUpdate !== null) {
<add> do {
<add> log(
<add> ' '.repeat(depth + 1) + '~',
<add> '[' + pendingUpdate.expirationTime + ']',
<add> );
<add> } while (pendingUpdate !== null && pendingUpdate !== firstPending);
<add> }
<ide> }
<ide> }
<ide>
<ide><path>packages/react-reconciler/src/ReactFiberBeginWork.js
<ide> import {
<ide> reconcileChildFibers,
<ide> cloneChildFibers,
<ide> } from './ReactChildFiber';
<del>import {processUpdateQueue} from './ReactUpdateQueue';
<add>import {
<add> processUpdateQueue,
<add> cloneUpdateQueue,
<add> initializeUpdateQueue,
<add>} from './ReactUpdateQueue';
<ide> import {
<ide> NoWork,
<ide> Never,
<ide> function updateHostRoot(current, workInProgress, renderExpirationTime) {
<ide> pushHostRootContext(workInProgress);
<ide> const updateQueue = workInProgress.updateQueue;
<ide> invariant(
<del> updateQueue !== null,
<add> current !== null && updateQueue !== null,
<ide> 'If the root does not have an updateQueue, we should have already ' +
<ide> 'bailed out. This error is likely caused by a bug in React. Please ' +
<ide> 'file an issue.',
<ide> );
<ide> const nextProps = workInProgress.pendingProps;
<ide> const prevState = workInProgress.memoizedState;
<ide> const prevChildren = prevState !== null ? prevState.element : null;
<del> processUpdateQueue(
<del> workInProgress,
<del> updateQueue,
<del> nextProps,
<del> null,
<del> renderExpirationTime,
<del> );
<add> cloneUpdateQueue(current, workInProgress);
<add> processUpdateQueue(workInProgress, nextProps, null, renderExpirationTime);
<ide> const nextState = workInProgress.memoizedState;
<ide> // Caution: React DevTools currently depends on this property
<ide> // being called "element".
<ide> function mountIndeterminateComponent(
<ide> workInProgress.memoizedState =
<ide> value.state !== null && value.state !== undefined ? value.state : null;
<ide>
<add> initializeUpdateQueue(workInProgress);
<add>
<ide> const getDerivedStateFromProps = Component.getDerivedStateFromProps;
<ide> if (typeof getDerivedStateFromProps === 'function') {
<ide> applyDerivedStateFromProps(
<ide><path>packages/react-reconciler/src/ReactFiberClassComponent.js
<ide>
<ide> import type {Fiber} from './ReactFiber';
<ide> import type {ExpirationTime} from './ReactFiberExpirationTime';
<add>import type {UpdateQueue} from './ReactUpdateQueue';
<ide>
<ide> import React from 'react';
<ide> import {Update, Snapshot} from 'shared/ReactSideEffectTags';
<ide> import {
<ide> createUpdate,
<ide> ReplaceState,
<ide> ForceUpdate,
<add> initializeUpdateQueue,
<add> cloneUpdateQueue,
<ide> } from './ReactUpdateQueue';
<ide> import {NoWork} from './ReactFiberExpirationTime';
<ide> import {
<ide> export function applyDerivedStateFromProps(
<ide>
<ide> // Once the update queue is empty, persist the derived state onto the
<ide> // base state.
<del> const updateQueue = workInProgress.updateQueue;
<del> if (updateQueue !== null && workInProgress.expirationTime === NoWork) {
<add> if (workInProgress.expirationTime === NoWork) {
<add> // Queue is always non-null for classes
<add> const updateQueue: UpdateQueue<any> = (workInProgress.updateQueue: any);
<ide> updateQueue.baseState = memoizedState;
<ide> }
<ide> }
<ide> function mountClassInstance(
<ide> instance.state = workInProgress.memoizedState;
<ide> instance.refs = emptyRefsObject;
<ide>
<add> initializeUpdateQueue(workInProgress);
<add>
<ide> const contextType = ctor.contextType;
<ide> if (typeof contextType === 'object' && contextType !== null) {
<ide> instance.context = readContext(contextType);
<ide> function mountClassInstance(
<ide> }
<ide> }
<ide>
<del> let updateQueue = workInProgress.updateQueue;
<del> if (updateQueue !== null) {
<del> processUpdateQueue(
<del> workInProgress,
<del> updateQueue,
<del> newProps,
<del> instance,
<del> renderExpirationTime,
<del> );
<del> instance.state = workInProgress.memoizedState;
<del> }
<add> processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);
<add> instance.state = workInProgress.memoizedState;
<ide>
<ide> const getDerivedStateFromProps = ctor.getDerivedStateFromProps;
<ide> if (typeof getDerivedStateFromProps === 'function') {
<ide> function mountClassInstance(
<ide> callComponentWillMount(workInProgress, instance);
<ide> // If we had additional state updates during this life-cycle, let's
<ide> // process them now.
<del> updateQueue = workInProgress.updateQueue;
<del> if (updateQueue !== null) {
<del> processUpdateQueue(
<del> workInProgress,
<del> updateQueue,
<del> newProps,
<del> instance,
<del> renderExpirationTime,
<del> );
<del> instance.state = workInProgress.memoizedState;
<del> }
<add> processUpdateQueue(
<add> workInProgress,
<add> newProps,
<add> instance,
<add> renderExpirationTime,
<add> );
<add> instance.state = workInProgress.memoizedState;
<ide> }
<ide>
<ide> if (typeof instance.componentDidMount === 'function') {
<ide> function resumeMountClassInstance(
<ide>
<ide> const oldState = workInProgress.memoizedState;
<ide> let newState = (instance.state = oldState);
<del> let updateQueue = workInProgress.updateQueue;
<del> if (updateQueue !== null) {
<del> processUpdateQueue(
<del> workInProgress,
<del> updateQueue,
<del> newProps,
<del> instance,
<del> renderExpirationTime,
<del> );
<del> newState = workInProgress.memoizedState;
<del> }
<add> processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);
<add> newState = workInProgress.memoizedState;
<ide> if (
<ide> oldProps === newProps &&
<ide> oldState === newState &&
<ide> function updateClassInstance(
<ide> ): boolean {
<ide> const instance = workInProgress.stateNode;
<ide>
<add> cloneUpdateQueue(current, workInProgress);
<add>
<ide> const oldProps = workInProgress.memoizedProps;
<ide> instance.props =
<ide> workInProgress.type === workInProgress.elementType
<ide> function updateClassInstance(
<ide>
<ide> const oldState = workInProgress.memoizedState;
<ide> let newState = (instance.state = oldState);
<del> let updateQueue = workInProgress.updateQueue;
<del> if (updateQueue !== null) {
<del> processUpdateQueue(
<del> workInProgress,
<del> updateQueue,
<del> newProps,
<del> instance,
<del> renderExpirationTime,
<del> );
<del> newState = workInProgress.memoizedState;
<del> }
<add> processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);
<add> newState = workInProgress.memoizedState;
<ide>
<ide> if (
<ide> oldProps === newProps &&
<ide><path>packages/react-reconciler/src/ReactFiberHooks.js
<ide> import type {ReactPriorityLevel} from './SchedulerWithReactIntegration';
<ide>
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide>
<del>import {NoWork} from './ReactFiberExpirationTime';
<add>import {NoWork, Sync} from './ReactFiberExpirationTime';
<ide> import {readContext} from './ReactFiberNewContext';
<ide> import {createResponderListener} from './ReactFiberEvents';
<ide> import {
<ide> type Update<S, A> = {
<ide> action: A,
<ide> eagerReducer: ((S, A) => S) | null,
<ide> eagerState: S | null,
<del> next: Update<S, A> | null,
<add> next: Update<S, A>,
<ide>
<ide> priority?: ReactPriorityLevel,
<ide> };
<ide>
<ide> type UpdateQueue<S, A> = {
<del> last: Update<S, A> | null,
<add> pending: Update<S, A> | null,
<ide> dispatch: (A => mixed) | null,
<ide> lastRenderedReducer: ((S, A) => S) | null,
<ide> lastRenderedState: S | null,
<ide> export type Hook = {
<ide> memoizedState: any,
<ide>
<ide> baseState: any,
<del> baseUpdate: Update<any, any> | null,
<add> baseQueue: Update<any, any> | null,
<ide> queue: UpdateQueue<any, any> | null,
<ide>
<ide> next: Hook | null,
<ide> function mountWorkInProgressHook(): Hook {
<ide> memoizedState: null,
<ide>
<ide> baseState: null,
<add> baseQueue: null,
<ide> queue: null,
<del> baseUpdate: null,
<ide>
<ide> next: null,
<ide> };
<ide> function updateWorkInProgressHook(): Hook {
<ide> memoizedState: currentHook.memoizedState,
<ide>
<ide> baseState: currentHook.baseState,
<add> baseQueue: currentHook.baseQueue,
<ide> queue: currentHook.queue,
<del> baseUpdate: currentHook.baseUpdate,
<ide>
<ide> next: null,
<ide> };
<ide> function mountReducer<S, I, A>(
<ide> }
<ide> hook.memoizedState = hook.baseState = initialState;
<ide> const queue = (hook.queue = {
<del> last: null,
<add> pending: null,
<ide> dispatch: null,
<ide> lastRenderedReducer: reducer,
<ide> lastRenderedState: (initialState: any),
<ide> function updateReducer<S, I, A>(
<ide> // the base state unless the queue is empty.
<ide> // TODO: Not sure if this is the desired semantics, but it's what we
<ide> // do for gDSFP. I can't remember why.
<del> if (hook.baseUpdate === queue.last) {
<add> if (hook.baseQueue === null) {
<ide> hook.baseState = newState;
<ide> }
<ide>
<ide> function updateReducer<S, I, A>(
<ide> return [hook.memoizedState, dispatch];
<ide> }
<ide>
<del> // The last update in the entire queue
<del> const last = queue.last;
<del> // The last update that is part of the base state.
<del> const baseUpdate = hook.baseUpdate;
<del> const baseState = hook.baseState;
<del>
<del> // Find the first unprocessed update.
<del> let first;
<del> if (baseUpdate !== null) {
<del> if (last !== null) {
<del> // For the first update, the queue is a circular linked list where
<del> // `queue.last.next = queue.first`. Once the first update commits, and
<del> // the `baseUpdate` is no longer empty, we can unravel the list.
<del> last.next = null;
<add> const current: Hook = (currentHook: any);
<add>
<add> // The last rebase update that is NOT part of the base state.
<add> let baseQueue = current.baseQueue;
<add>
<add> // The last pending update that hasn't been processed yet.
<add> let pendingQueue = queue.pending;
<add> if (pendingQueue !== null) {
<add> // We have new updates that haven't been processed yet.
<add> // We'll add them to the base queue.
<add> if (baseQueue !== null) {
<add> // Merge the pending queue and the base queue.
<add> let baseFirst = baseQueue.next;
<add> let pendingFirst = pendingQueue.next;
<add> baseQueue.next = pendingFirst;
<add> pendingQueue.next = baseFirst;
<ide> }
<del> first = baseUpdate.next;
<del> } else {
<del> first = last !== null ? last.next : null;
<add> current.baseQueue = baseQueue = pendingQueue;
<add> queue.pending = null;
<ide> }
<del> if (first !== null) {
<del> let newState = baseState;
<add>
<add> if (baseQueue !== null) {
<add> // We have a queue to process.
<add> let first = baseQueue.next;
<add> let newState = current.baseState;
<add>
<ide> let newBaseState = null;
<del> let newBaseUpdate = null;
<del> let prevUpdate = baseUpdate;
<add> let newBaseQueueFirst = null;
<add> let newBaseQueueLast = null;
<ide> let update = first;
<del> let didSkip = false;
<ide> do {
<ide> const updateExpirationTime = update.expirationTime;
<ide> if (updateExpirationTime < renderExpirationTime) {
<ide> // Priority is insufficient. Skip this update. If this is the first
<ide> // skipped update, the previous update/state is the new base
<ide> // update/state.
<del> if (!didSkip) {
<del> didSkip = true;
<del> newBaseUpdate = prevUpdate;
<add> const clone: Update<S, A> = {
<add> expirationTime: update.expirationTime,
<add> suspenseConfig: update.suspenseConfig,
<add> action: update.action,
<add> eagerReducer: update.eagerReducer,
<add> eagerState: update.eagerState,
<add> next: (null: any),
<add> };
<add> if (newBaseQueueLast === null) {
<add> newBaseQueueFirst = newBaseQueueLast = clone;
<ide> newBaseState = newState;
<add> } else {
<add> newBaseQueueLast = newBaseQueueLast.next = clone;
<ide> }
<ide> // Update the remaining priority in the queue.
<ide> if (updateExpirationTime > currentlyRenderingFiber.expirationTime) {
<ide> function updateReducer<S, I, A>(
<ide> } else {
<ide> // This update does have sufficient priority.
<ide>
<add> if (newBaseQueueLast !== null) {
<add> const clone: Update<S, A> = {
<add> expirationTime: Sync, // This update is going to be committed so we never want uncommit it.
<add> suspenseConfig: update.suspenseConfig,
<add> action: update.action,
<add> eagerReducer: update.eagerReducer,
<add> eagerState: update.eagerState,
<add> next: (null: any),
<add> };
<add> newBaseQueueLast = newBaseQueueLast.next = clone;
<add> }
<add>
<ide> // Mark the event time of this update as relevant to this render pass.
<ide> // TODO: This should ideally use the true event time of this update rather than
<ide> // its priority which is a derived and not reverseable value.
<ide> function updateReducer<S, I, A>(
<ide> newState = reducer(newState, action);
<ide> }
<ide> }
<del> prevUpdate = update;
<ide> update = update.next;
<ide> } while (update !== null && update !== first);
<ide>
<del> if (!didSkip) {
<del> newBaseUpdate = prevUpdate;
<add> if (newBaseQueueLast === null) {
<ide> newBaseState = newState;
<add> } else {
<add> newBaseQueueLast.next = (newBaseQueueFirst: any);
<ide> }
<ide>
<ide> // Mark that the fiber performed work, but only if the new state is
<ide> function updateReducer<S, I, A>(
<ide> }
<ide>
<ide> hook.memoizedState = newState;
<del> hook.baseUpdate = newBaseUpdate;
<ide> hook.baseState = newBaseState;
<add> hook.baseQueue = newBaseQueueLast;
<ide>
<ide> queue.lastRenderedState = newState;
<ide> }
<ide> function mountState<S>(
<ide> }
<ide> hook.memoizedState = hook.baseState = initialState;
<ide> const queue = (hook.queue = {
<del> last: null,
<add> pending: null,
<ide> dispatch: null,
<ide> lastRenderedReducer: basicStateReducer,
<ide> lastRenderedState: (initialState: any),
<ide> function dispatchAction<S, A>(
<ide> action,
<ide> eagerReducer: null,
<ide> eagerState: null,
<del> next: null,
<add> next: (null: any),
<ide> };
<ide> if (__DEV__) {
<ide> update.priority = getCurrentPriorityLevel();
<ide> function dispatchAction<S, A>(
<ide> action,
<ide> eagerReducer: null,
<ide> eagerState: null,
<del> next: null,
<add> next: (null: any),
<ide> };
<ide>
<ide> if (__DEV__) {
<ide> update.priority = getCurrentPriorityLevel();
<ide> }
<ide>
<ide> // Append the update to the end of the list.
<del> const last = queue.last;
<del> if (last === null) {
<add> const pending = queue.pending;
<add> if (pending === null) {
<ide> // This is the first update. Create a circular list.
<ide> update.next = update;
<ide> } else {
<del> const first = last.next;
<del> if (first !== null) {
<del> // Still circular.
<del> update.next = first;
<del> }
<del> last.next = update;
<add> update.next = pending.next;
<add> pending.next = update;
<ide> }
<del> queue.last = update;
<add> queue.pending = update;
<ide>
<ide> if (
<ide> fiber.expirationTime === NoWork &&
<ide><path>packages/react-reconciler/src/ReactFiberRoot.js
<ide> import {
<ide> } from 'shared/ReactFeatureFlags';
<ide> import {unstable_getThreadID} from 'scheduler/tracing';
<ide> import {NoPriority} from './SchedulerWithReactIntegration';
<add>import {initializeUpdateQueue} from './ReactUpdateQueue';
<ide>
<ide> export type PendingInteractionMap = Map<ExpirationTime, Set<Interaction>>;
<ide>
<ide> export function createFiberRoot(
<ide> root.current = uninitializedFiber;
<ide> uninitializedFiber.stateNode = root;
<ide>
<add> initializeUpdateQueue(uninitializedFiber);
<add>
<ide> return root;
<ide> }
<ide>
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.js
<ide> import type {ReactPriorityLevel} from './SchedulerWithReactIntegration';
<ide> import type {Interaction} from 'scheduler/src/Tracing';
<ide> import type {SuspenseConfig} from './ReactFiberSuspenseConfig';
<ide> import type {SuspenseState} from './ReactFiberSuspenseComponent';
<add>import type {Hook} from './ReactFiberHooks';
<ide>
<ide> import {
<ide> warnAboutDeprecatedLifecycles,
<ide> export function checkForWrongSuspensePriorityInDEV(sourceFiber: Fiber) {
<ide> // has triggered any high priority updates
<ide> const updateQueue = current.updateQueue;
<ide> if (updateQueue !== null) {
<del> let update = updateQueue.firstUpdate;
<add> let update = updateQueue.baseQueue;
<ide> while (update !== null) {
<ide> const priorityLevel = update.priority;
<ide> if (
<ide> export function checkForWrongSuspensePriorityInDEV(sourceFiber: Fiber) {
<ide> break;
<ide> case FunctionComponent:
<ide> case ForwardRef:
<del> case SimpleMemoComponent:
<del> if (
<del> workInProgressNode.memoizedState !== null &&
<del> workInProgressNode.memoizedState.baseUpdate !== null
<del> ) {
<del> let update = workInProgressNode.memoizedState.baseUpdate;
<add> case SimpleMemoComponent: {
<add> let firstHook: null | Hook = current.memoizedState;
<add> // TODO: This just checks the first Hook. Isn't it suppose to check all Hooks?
<add> if (firstHook !== null && firstHook.baseQueue !== null) {
<add> let update = firstHook.baseQueue;
<ide> // Loop through the functional component's memoized state to see whether
<ide> // the component has triggered any high pri updates
<ide> while (update !== null) {
<ide> export function checkForWrongSuspensePriorityInDEV(sourceFiber: Fiber) {
<ide> }
<ide> break;
<ide> }
<del> if (
<del> update.next === workInProgressNode.memoizedState.baseUpdate
<del> ) {
<add> if (update.next === firstHook.baseQueue) {
<ide> break;
<ide> }
<ide> update = update.next;
<ide> }
<ide> }
<ide> break;
<add> }
<ide> default:
<ide> break;
<ide> }
<ide><path>packages/react-reconciler/src/ReactUpdateQueue.js
<ide> import type {ExpirationTime} from './ReactFiberExpirationTime';
<ide> import type {SuspenseConfig} from './ReactFiberSuspenseConfig';
<ide> import type {ReactPriorityLevel} from './SchedulerWithReactIntegration';
<ide>
<del>import {NoWork} from './ReactFiberExpirationTime';
<add>import {NoWork, Sync} from './ReactFiberExpirationTime';
<ide> import {
<ide> enterDisallowedContextReadInDEV,
<ide> exitDisallowedContextReadInDEV,
<ide> } from './ReactFiberNewContext';
<ide> import {Callback, ShouldCapture, DidCapture} from 'shared/ReactSideEffectTags';
<del>import {ClassComponent} from 'shared/ReactWorkTags';
<ide>
<ide> import {debugRenderPhaseSideEffectsForStrictMode} from 'shared/ReactFeatureFlags';
<ide>
<ide> export type Update<State> = {
<ide> payload: any,
<ide> callback: (() => mixed) | null,
<ide>
<del> next: Update<State> | null,
<del> nextEffect: Update<State> | null,
<add> next: Update<State>,
<ide>
<ide> //DEV only
<ide> priority?: ReactPriorityLevel,
<ide> };
<ide>
<add>type SharedQueue<State> = {
<add> pending: Update<State> | null,
<add>};
<add>
<ide> export type UpdateQueue<State> = {
<ide> baseState: State,
<del>
<del> firstUpdate: Update<State> | null,
<del> lastUpdate: Update<State> | null,
<del>
<del> firstCapturedUpdate: Update<State> | null,
<del> lastCapturedUpdate: Update<State> | null,
<del>
<del> firstEffect: Update<State> | null,
<del> lastEffect: Update<State> | null,
<del>
<del> firstCapturedEffect: Update<State> | null,
<del> lastCapturedEffect: Update<State> | null,
<add> baseQueue: Update<State> | null,
<add> shared: SharedQueue<State>,
<add> effects: Array<Update<State>> | null,
<ide> };
<ide>
<ide> export const UpdateState = 0;
<ide> if (__DEV__) {
<ide> };
<ide> }
<ide>
<del>export function createUpdateQueue<State>(baseState: State): UpdateQueue<State> {
<add>export function initializeUpdateQueue<State>(fiber: Fiber): void {
<ide> const queue: UpdateQueue<State> = {
<del> baseState,
<del> firstUpdate: null,
<del> lastUpdate: null,
<del> firstCapturedUpdate: null,
<del> lastCapturedUpdate: null,
<del> firstEffect: null,
<del> lastEffect: null,
<del> firstCapturedEffect: null,
<del> lastCapturedEffect: null,
<add> baseState: fiber.memoizedState,
<add> baseQueue: null,
<add> shared: {
<add> pending: null,
<add> },
<add> effects: null,
<ide> };
<del> return queue;
<add> fiber.updateQueue = queue;
<ide> }
<ide>
<del>function cloneUpdateQueue<State>(
<del> currentQueue: UpdateQueue<State>,
<del>): UpdateQueue<State> {
<del> const queue: UpdateQueue<State> = {
<del> baseState: currentQueue.baseState,
<del> firstUpdate: currentQueue.firstUpdate,
<del> lastUpdate: currentQueue.lastUpdate,
<del>
<del> // TODO: With resuming, if we bail out and resuse the child tree, we should
<del> // keep these effects.
<del> firstCapturedUpdate: null,
<del> lastCapturedUpdate: null,
<del>
<del> firstEffect: null,
<del> lastEffect: null,
<del>
<del> firstCapturedEffect: null,
<del> lastCapturedEffect: null,
<del> };
<del> return queue;
<add>export function cloneUpdateQueue<State>(
<add> current: Fiber,
<add> workInProgress: Fiber,
<add>): void {
<add> // Clone the update queue from current. Unless it's already a clone.
<add> const queue: UpdateQueue<State> = (workInProgress.updateQueue: any);
<add> const currentQueue: UpdateQueue<State> = (current.updateQueue: any);
<add> if (queue === currentQueue) {
<add> const clone: UpdateQueue<State> = {
<add> baseState: currentQueue.baseState,
<add> baseQueue: currentQueue.baseQueue,
<add> shared: currentQueue.shared,
<add> effects: currentQueue.effects,
<add> };
<add> workInProgress.updateQueue = clone;
<add> }
<ide> }
<ide>
<ide> export function createUpdate(
<ide> export function createUpdate(
<ide> payload: null,
<ide> callback: null,
<ide>
<del> next: null,
<del> nextEffect: null,
<add> next: (null: any),
<ide> };
<add> update.next = update;
<ide> if (__DEV__) {
<ide> update.priority = getCurrentPriorityLevel();
<ide> }
<ide> return update;
<ide> }
<ide>
<del>function appendUpdateToQueue<State>(
<del> queue: UpdateQueue<State>,
<del> update: Update<State>,
<del>) {
<del> // Append the update to the end of the list.
<del> if (queue.lastUpdate === null) {
<del> // Queue is empty
<del> queue.firstUpdate = queue.lastUpdate = update;
<del> } else {
<del> queue.lastUpdate.next = update;
<del> queue.lastUpdate = update;
<del> }
<del>}
<del>
<ide> export function enqueueUpdate<State>(fiber: Fiber, update: Update<State>) {
<del> // Update queues are created lazily.
<del> const alternate = fiber.alternate;
<del> let queue1;
<del> let queue2;
<del> if (alternate === null) {
<del> // There's only one fiber.
<del> queue1 = fiber.updateQueue;
<del> queue2 = null;
<del> if (queue1 === null) {
<del> queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
<del> }
<del> } else {
<del> // There are two owners.
<del> queue1 = fiber.updateQueue;
<del> queue2 = alternate.updateQueue;
<del> if (queue1 === null) {
<del> if (queue2 === null) {
<del> // Neither fiber has an update queue. Create new ones.
<del> queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
<del> queue2 = alternate.updateQueue = createUpdateQueue(
<del> alternate.memoizedState,
<del> );
<del> } else {
<del> // Only one fiber has an update queue. Clone to create a new one.
<del> queue1 = fiber.updateQueue = cloneUpdateQueue(queue2);
<del> }
<del> } else {
<del> if (queue2 === null) {
<del> // Only one fiber has an update queue. Clone to create a new one.
<del> queue2 = alternate.updateQueue = cloneUpdateQueue(queue1);
<del> } else {
<del> // Both owners have an update queue.
<del> }
<del> }
<add> const updateQueue = fiber.updateQueue;
<add> if (updateQueue === null) {
<add> // Only occurs if the fiber has been unmounted.
<add> return;
<ide> }
<del> if (queue2 === null || queue1 === queue2) {
<del> // There's only a single queue.
<del> appendUpdateToQueue(queue1, update);
<add>
<add> const sharedQueue = updateQueue.shared;
<add> const pending = sharedQueue.pending;
<add> if (pending === null) {
<add> // This is the first update. Create a circular list.
<add> update.next = update;
<ide> } else {
<del> // There are two queues. We need to append the update to both queues,
<del> // while accounting for the persistent structure of the list — we don't
<del> // want the same update to be added multiple times.
<del> if (queue1.lastUpdate === null || queue2.lastUpdate === null) {
<del> // One of the queues is not empty. We must add the update to both queues.
<del> appendUpdateToQueue(queue1, update);
<del> appendUpdateToQueue(queue2, update);
<del> } else {
<del> // Both queues are non-empty. The last update is the same in both lists,
<del> // because of structural sharing. So, only append to one of the lists.
<del> appendUpdateToQueue(queue1, update);
<del> // But we still need to update the `lastUpdate` pointer of queue2.
<del> queue2.lastUpdate = update;
<del> }
<add> update.next = pending.next;
<add> pending.next = update;
<ide> }
<add> sharedQueue.pending = update;
<ide>
<ide> if (__DEV__) {
<ide> if (
<del> fiber.tag === ClassComponent &&
<del> (currentlyProcessingQueue === queue1 ||
<del> (queue2 !== null && currentlyProcessingQueue === queue2)) &&
<add> currentlyProcessingQueue === sharedQueue &&
<ide> !didWarnUpdateInsideUpdate
<ide> ) {
<ide> warningWithoutStack(
<ide> export function enqueueCapturedUpdate<State>(
<ide> workInProgress: Fiber,
<ide> update: Update<State>,
<ide> ) {
<del> // Captured updates go into a separate list, and only on the work-in-
<del> // progress queue.
<del> let workInProgressQueue = workInProgress.updateQueue;
<del> if (workInProgressQueue === null) {
<del> workInProgressQueue = workInProgress.updateQueue = createUpdateQueue(
<del> workInProgress.memoizedState,
<del> );
<del> } else {
<del> // TODO: I put this here rather than createWorkInProgress so that we don't
<del> // clone the queue unnecessarily. There's probably a better way to
<del> // structure this.
<del> workInProgressQueue = ensureWorkInProgressQueueIsAClone(
<del> workInProgress,
<del> workInProgressQueue,
<del> );
<add> const current = workInProgress.alternate;
<add> if (current !== null) {
<add> // Ensure the work-in-progress queue is a clone
<add> cloneUpdateQueue(current, workInProgress);
<ide> }
<ide>
<add> // Captured updates go only on the work-in-progress queue.
<add> const queue: UpdateQueue<State> = (workInProgress.updateQueue: any);
<ide> // Append the update to the end of the list.
<del> if (workInProgressQueue.lastCapturedUpdate === null) {
<del> // This is the first render phase update
<del> workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update;
<add> const last = queue.baseQueue;
<add> if (last === null) {
<add> queue.baseQueue = update.next = update;
<add> update.next = update;
<ide> } else {
<del> workInProgressQueue.lastCapturedUpdate.next = update;
<del> workInProgressQueue.lastCapturedUpdate = update;
<add> update.next = last.next;
<add> last.next = update;
<ide> }
<ide> }
<ide>
<del>function ensureWorkInProgressQueueIsAClone<State>(
<del> workInProgress: Fiber,
<del> queue: UpdateQueue<State>,
<del>): UpdateQueue<State> {
<del> const current = workInProgress.alternate;
<del> if (current !== null) {
<del> // If the work-in-progress queue is equal to the current queue,
<del> // we need to clone it first.
<del> if (queue === current.updateQueue) {
<del> queue = workInProgress.updateQueue = cloneUpdateQueue(queue);
<del> }
<del> }
<del> return queue;
<del>}
<del>
<ide> function getStateFromUpdate<State>(
<ide> workInProgress: Fiber,
<ide> queue: UpdateQueue<State>,
<ide> function getStateFromUpdate<State>(
<ide>
<ide> export function processUpdateQueue<State>(
<ide> workInProgress: Fiber,
<del> queue: UpdateQueue<State>,
<ide> props: any,
<ide> instance: any,
<ide> renderExpirationTime: ExpirationTime,
<ide> ): void {
<del> hasForceUpdate = false;
<add> // This is always non-null on a ClassComponent or HostRoot
<add> const queue: UpdateQueue<State> = (workInProgress.updateQueue: any);
<ide>
<del> queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue);
<add> hasForceUpdate = false;
<ide>
<ide> if (__DEV__) {
<del> currentlyProcessingQueue = queue;
<add> currentlyProcessingQueue = queue.shared;
<ide> }
<ide>
<del> // These values may change as we process the queue.
<del> let newBaseState = queue.baseState;
<del> let newFirstUpdate = null;
<del> let newExpirationTime = NoWork;
<del>
<del> // Iterate through the list of updates to compute the result.
<del> let update = queue.firstUpdate;
<del> let resultState = newBaseState;
<del> while (update !== null) {
<del> const updateExpirationTime = update.expirationTime;
<del> if (updateExpirationTime < renderExpirationTime) {
<del> // This update does not have sufficient priority. Skip it.
<del> if (newFirstUpdate === null) {
<del> // This is the first skipped update. It will be the first update in
<del> // the new list.
<del> newFirstUpdate = update;
<del> // Since this is the first update that was skipped, the current result
<del> // is the new base state.
<del> newBaseState = resultState;
<del> }
<del> // Since this update will remain in the list, update the remaining
<del> // expiration time.
<del> if (newExpirationTime < updateExpirationTime) {
<del> newExpirationTime = updateExpirationTime;
<del> }
<del> } else {
<del> // This update does have sufficient priority.
<del>
<del> // Mark the event time of this update as relevant to this render pass.
<del> // TODO: This should ideally use the true event time of this update rather than
<del> // its priority which is a derived and not reverseable value.
<del> // TODO: We should skip this update if it was already committed but currently
<del> // we have no way of detecting the difference between a committed and suspended
<del> // update here.
<del> markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig);
<del>
<del> // Process it and compute a new result.
<del> resultState = getStateFromUpdate(
<del> workInProgress,
<del> queue,
<del> update,
<del> resultState,
<del> props,
<del> instance,
<del> );
<del> const callback = update.callback;
<del> if (callback !== null) {
<del> workInProgress.effectTag |= Callback;
<del> // Set this to null, in case it was mutated during an aborted render.
<del> update.nextEffect = null;
<del> if (queue.lastEffect === null) {
<del> queue.firstEffect = queue.lastEffect = update;
<del> } else {
<del> queue.lastEffect.nextEffect = update;
<del> queue.lastEffect = update;
<del> }
<add> // The last rebase update that is NOT part of the base state.
<add> let baseQueue = queue.baseQueue;
<add>
<add> // The last pending update that hasn't been processed yet.
<add> let pendingQueue = queue.shared.pending;
<add> if (pendingQueue !== null) {
<add> // We have new updates that haven't been processed yet.
<add> // We'll add them to the base queue.
<add> if (baseQueue !== null) {
<add> // Merge the pending queue and the base queue.
<add> let baseFirst = baseQueue.next;
<add> let pendingFirst = pendingQueue.next;
<add> baseQueue.next = pendingFirst;
<add> pendingQueue.next = baseFirst;
<add> }
<add>
<add> baseQueue = pendingQueue;
<add>
<add> queue.shared.pending = null;
<add> // TODO: Pass `current` as argument
<add> const current = workInProgress.alternate;
<add> if (current !== null) {
<add> const currentQueue = current.updateQueue;
<add> if (currentQueue !== null) {
<add> currentQueue.baseQueue = pendingQueue;
<ide> }
<ide> }
<del> // Continue to the next update.
<del> update = update.next;
<ide> }
<ide>
<del> // Separately, iterate though the list of captured updates.
<del> let newFirstCapturedUpdate = null;
<del> update = queue.firstCapturedUpdate;
<del> while (update !== null) {
<del> const updateExpirationTime = update.expirationTime;
<del> if (updateExpirationTime < renderExpirationTime) {
<del> // This update does not have sufficient priority. Skip it.
<del> if (newFirstCapturedUpdate === null) {
<del> // This is the first skipped captured update. It will be the first
<del> // update in the new list.
<del> newFirstCapturedUpdate = update;
<del> // If this is the first update that was skipped, the current result is
<del> // the new base state.
<del> if (newFirstUpdate === null) {
<del> newBaseState = resultState;
<del> }
<del> }
<del> // Since this update will remain in the list, update the remaining
<del> // expiration time.
<del> if (newExpirationTime < updateExpirationTime) {
<del> newExpirationTime = updateExpirationTime;
<del> }
<del> } else {
<del> // This update does have sufficient priority. Process it and compute
<del> // a new result.
<del> resultState = getStateFromUpdate(
<del> workInProgress,
<del> queue,
<del> update,
<del> resultState,
<del> props,
<del> instance,
<del> );
<del> const callback = update.callback;
<del> if (callback !== null) {
<del> workInProgress.effectTag |= Callback;
<del> // Set this to null, in case it was mutated during an aborted render.
<del> update.nextEffect = null;
<del> if (queue.lastCapturedEffect === null) {
<del> queue.firstCapturedEffect = queue.lastCapturedEffect = update;
<add> // These values may change as we process the queue.
<add> if (baseQueue !== null) {
<add> let first = baseQueue.next;
<add> // Iterate through the list of updates to compute the result.
<add> let newState = queue.baseState;
<add> let newExpirationTime = NoWork;
<add>
<add> let newBaseState = null;
<add> let newBaseQueueFirst = null;
<add> let newBaseQueueLast = null;
<add>
<add> if (first !== null) {
<add> let update = first;
<add> do {
<add> const updateExpirationTime = update.expirationTime;
<add> if (updateExpirationTime < renderExpirationTime) {
<add> // Priority is insufficient. Skip this update. If this is the first
<add> // skipped update, the previous update/state is the new base
<add> // update/state.
<add> const clone: Update<State> = {
<add> expirationTime: update.expirationTime,
<add> suspenseConfig: update.suspenseConfig,
<add>
<add> tag: update.tag,
<add> payload: update.payload,
<add> callback: update.callback,
<add>
<add> next: (null: any),
<add> };
<add> if (newBaseQueueLast === null) {
<add> newBaseQueueFirst = newBaseQueueLast = clone;
<add> newBaseState = newState;
<add> } else {
<add> newBaseQueueLast = newBaseQueueLast.next = clone;
<add> }
<add> // Update the remaining priority in the queue.
<add> if (updateExpirationTime > newExpirationTime) {
<add> newExpirationTime = updateExpirationTime;
<add> }
<ide> } else {
<del> queue.lastCapturedEffect.nextEffect = update;
<del> queue.lastCapturedEffect = update;
<add> // This update does have sufficient priority.
<add>
<add> if (newBaseQueueLast !== null) {
<add> const clone: Update<State> = {
<add> expirationTime: Sync, // This update is going to be committed so we never want uncommit it.
<add> suspenseConfig: update.suspenseConfig,
<add>
<add> tag: update.tag,
<add> payload: update.payload,
<add> callback: update.callback,
<add>
<add> next: (null: any),
<add> };
<add> newBaseQueueLast = newBaseQueueLast.next = clone;
<add> }
<add>
<add> // Mark the event time of this update as relevant to this render pass.
<add> // TODO: This should ideally use the true event time of this update rather than
<add> // its priority which is a derived and not reverseable value.
<add> // TODO: We should skip this update if it was already committed but currently
<add> // we have no way of detecting the difference between a committed and suspended
<add> // update here.
<add> markRenderEventTimeAndConfig(
<add> updateExpirationTime,
<add> update.suspenseConfig,
<add> );
<add>
<add> // Process this update.
<add> newState = getStateFromUpdate(
<add> workInProgress,
<add> queue,
<add> update,
<add> newState,
<add> props,
<add> instance,
<add> );
<add> const callback = update.callback;
<add> if (callback !== null) {
<add> workInProgress.effectTag |= Callback;
<add> let effects = queue.effects;
<add> if (effects === null) {
<add> queue.effects = [update];
<add> } else {
<add> effects.push(update);
<add> }
<add> }
<ide> }
<del> }
<add> update = update.next;
<add> if (update === null || update === first) {
<add> pendingQueue = queue.shared.pending;
<add> if (pendingQueue === null) {
<add> break;
<add> } else {
<add> // An update was scheduled from inside a reducer. Add the new
<add> // pending updates to the end of the list and keep processing.
<add> update = baseQueue.next = pendingQueue.next;
<add> pendingQueue.next = first;
<add> queue.baseQueue = baseQueue = pendingQueue;
<add> queue.shared.pending = null;
<add> }
<add> }
<add> } while (true);
<ide> }
<del> update = update.next;
<del> }
<ide>
<del> if (newFirstUpdate === null) {
<del> queue.lastUpdate = null;
<del> }
<del> if (newFirstCapturedUpdate === null) {
<del> queue.lastCapturedUpdate = null;
<del> } else {
<del> workInProgress.effectTag |= Callback;
<del> }
<del> if (newFirstUpdate === null && newFirstCapturedUpdate === null) {
<del> // We processed every update, without skipping. That means the new base
<del> // state is the same as the result state.
<del> newBaseState = resultState;
<del> }
<add> if (newBaseQueueLast === null) {
<add> newBaseState = newState;
<add> } else {
<add> newBaseQueueLast.next = (newBaseQueueFirst: any);
<add> }
<ide>
<del> queue.baseState = newBaseState;
<del> queue.firstUpdate = newFirstUpdate;
<del> queue.firstCapturedUpdate = newFirstCapturedUpdate;
<del>
<del> // Set the remaining expiration time to be whatever is remaining in the queue.
<del> // This should be fine because the only two other things that contribute to
<del> // expiration time are props and context. We're already in the middle of the
<del> // begin phase by the time we start processing the queue, so we've already
<del> // dealt with the props. Context in components that specify
<del> // shouldComponentUpdate is tricky; but we'll have to account for
<del> // that regardless.
<del> markUnprocessedUpdateTime(newExpirationTime);
<del> workInProgress.expirationTime = newExpirationTime;
<del> workInProgress.memoizedState = resultState;
<add> queue.baseState = ((newBaseState: any): State);
<add> queue.baseQueue = newBaseQueueLast;
<add>
<add> // Set the remaining expiration time to be whatever is remaining in the queue.
<add> // This should be fine because the only two other things that contribute to
<add> // expiration time are props and context. We're already in the middle of the
<add> // begin phase by the time we start processing the queue, so we've already
<add> // dealt with the props. Context in components that specify
<add> // shouldComponentUpdate is tricky; but we'll have to account for
<add> // that regardless.
<add> markUnprocessedUpdateTime(newExpirationTime);
<add> workInProgress.expirationTime = newExpirationTime;
<add> workInProgress.memoizedState = newState;
<add> }
<ide>
<ide> if (__DEV__) {
<ide> currentlyProcessingQueue = null;
<ide> export function commitUpdateQueue<State>(
<ide> instance: any,
<ide> renderExpirationTime: ExpirationTime,
<ide> ): void {
<del> // If the finished render included captured updates, and there are still
<del> // lower priority updates left over, we need to keep the captured updates
<del> // in the queue so that they are rebased and not dropped once we process the
<del> // queue again at the lower priority.
<del> if (finishedQueue.firstCapturedUpdate !== null) {
<del> // Join the captured update list to the end of the normal list.
<del> if (finishedQueue.lastUpdate !== null) {
<del> finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate;
<del> finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate;
<del> }
<del> // Clear the list of captured updates.
<del> finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null;
<del> }
<del>
<ide> // Commit the effects
<del> commitUpdateEffects(finishedQueue.firstEffect, instance);
<del> finishedQueue.firstEffect = finishedQueue.lastEffect = null;
<del>
<del> commitUpdateEffects(finishedQueue.firstCapturedEffect, instance);
<del> finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null;
<del>}
<del>
<del>function commitUpdateEffects<State>(
<del> effect: Update<State> | null,
<del> instance: any,
<del>): void {
<del> while (effect !== null) {
<del> const callback = effect.callback;
<del> if (callback !== null) {
<del> effect.callback = null;
<del> callCallback(callback, instance);
<add> const effects = finishedQueue.effects;
<add> finishedQueue.effects = null;
<add> if (effects !== null) {
<add> for (let i = 0; i < effects.length; i++) {
<add> const effect = effects[i];
<add> const callback = effect.callback;
<add> if (callback !== null) {
<add> effect.callback = null;
<add> callCallback(callback, instance);
<add> }
<ide> }
<del> effect = effect.nextEffect;
<ide> }
<ide> }
<ide><path>packages/react-reconciler/src/__tests__/ReactIncrementalUpdates-test.internal.js
<ide> describe('ReactIncrementalUpdates', () => {
<ide> expect(Scheduler).toFlushAndYield(['Commit: goodbye']);
<ide> });
<ide> });
<add>
<add> it('when rebasing, does not exclude updates that were already committed, regardless of priority', async () => {
<add> const {useState, useLayoutEffect} = React;
<add>
<add> let pushToLog;
<add> function App() {
<add> const [log, setLog] = useState('');
<add> pushToLog = msg => {
<add> setLog(prevLog => prevLog + msg);
<add> };
<add>
<add> useLayoutEffect(
<add> () => {
<add> Scheduler.unstable_yieldValue('Committed: ' + log);
<add> if (log === 'B') {
<add> // Right after B commits, schedule additional updates.
<add> Scheduler.unstable_runWithPriority(
<add> Scheduler.unstable_UserBlockingPriority,
<add> () => {
<add> pushToLog('C');
<add> },
<add> );
<add> setLog(prevLog => prevLog + 'D');
<add> }
<add> },
<add> [log],
<add> );
<add>
<add> return log;
<add> }
<add>
<add> const root = ReactNoop.createRoot();
<add> await ReactNoop.act(async () => {
<add> root.render(<App />);
<add> });
<add> expect(Scheduler).toHaveYielded(['Committed: ']);
<add> expect(root).toMatchRenderedOutput('');
<add>
<add> await ReactNoop.act(async () => {
<add> pushToLog('A');
<add> Scheduler.unstable_runWithPriority(
<add> Scheduler.unstable_UserBlockingPriority,
<add> () => {
<add> pushToLog('B');
<add> },
<add> );
<add> });
<add> expect(Scheduler).toHaveYielded([
<add> // A and B are pending. B is higher priority, so we'll render that first.
<add> 'Committed: B',
<add> // Because A comes first in the queue, we're now in rebase mode. B must
<add> // be rebased on top of A. Also, in a layout effect, we received two new
<add> // updates: C and D. C is user-blocking and D is synchronous.
<add> //
<add> // First render the synchronous update. What we're testing here is that
<add> // B *is not dropped* even though it has lower than sync priority. That's
<add> // because we already committed it. However, this render should not
<add> // include C, because that update wasn't already committed.
<add> 'Committed: BD',
<add> 'Committed: BCD',
<add> 'Committed: ABCD',
<add> ]);
<add> expect(root).toMatchRenderedOutput('ABCD');
<add> });
<add>
<add> it('when rebasing, does not exclude updates that were already committed, regardless of priority (classes)', async () => {
<add> let pushToLog;
<add> class App extends React.Component {
<add> state = {log: ''};
<add> pushToLog = msg => {
<add> this.setState(prevState => ({log: prevState.log + msg}));
<add> };
<add> componentDidUpdate() {
<add> Scheduler.unstable_yieldValue('Committed: ' + this.state.log);
<add> if (this.state.log === 'B') {
<add> // Right after B commits, schedule additional updates.
<add> Scheduler.unstable_runWithPriority(
<add> Scheduler.unstable_UserBlockingPriority,
<add> () => {
<add> this.pushToLog('C');
<add> },
<add> );
<add> this.pushToLog('D');
<add> }
<add> }
<add> render() {
<add> pushToLog = this.pushToLog;
<add> return this.state.log;
<add> }
<add> }
<add>
<add> const root = ReactNoop.createRoot();
<add> await ReactNoop.act(async () => {
<add> root.render(<App />);
<add> });
<add> expect(Scheduler).toHaveYielded([]);
<add> expect(root).toMatchRenderedOutput('');
<add>
<add> await ReactNoop.act(async () => {
<add> pushToLog('A');
<add> Scheduler.unstable_runWithPriority(
<add> Scheduler.unstable_UserBlockingPriority,
<add> () => {
<add> pushToLog('B');
<add> },
<add> );
<add> });
<add> expect(Scheduler).toHaveYielded([
<add> // A and B are pending. B is higher priority, so we'll render that first.
<add> 'Committed: B',
<add> // Because A comes first in the queue, we're now in rebase mode. B must
<add> // be rebased on top of A. Also, in a layout effect, we received two new
<add> // updates: C and D. C is user-blocking and D is synchronous.
<add> //
<add> // First render the synchronous update. What we're testing here is that
<add> // B *is not dropped* even though it has lower than sync priority. That's
<add> // because we already committed it. However, this render should not
<add> // include C, because that update wasn't already committed.
<add> 'Committed: BD',
<add> 'Committed: BCD',
<add> 'Committed: ABCD',
<add> ]);
<add> expect(root).toMatchRenderedOutput('ABCD');
<add> });
<add>
<add> it("base state of update queue is initialized to its fiber's memoized state", async () => {
<add> // This test is very weird because it tests an implementation detail but
<add> // is tested in terms of public APIs. When it was originally written, the
<add> // test failed because the update queue was initialized to the state of
<add> // the alternate fiber.
<add> let app;
<add> class App extends React.Component {
<add> state = {prevProp: 'A', count: 0};
<add> static getDerivedStateFromProps(props, state) {
<add> // Add 100 whenever the label prop changes. The prev label is stored
<add> // in state. If the state is dropped incorrectly, we'll fail to detect
<add> // prop changes.
<add> if (props.prop !== state.prevProp) {
<add> return {
<add> prevProp: props.prop,
<add> count: state.count + 100,
<add> };
<add> }
<add> return null;
<add> }
<add> render() {
<add> app = this;
<add> return this.state.count;
<add> }
<add> }
<add>
<add> const root = ReactNoop.createRoot();
<add> await ReactNoop.act(async () => {
<add> root.render(<App prop="A" />);
<add> });
<add> expect(root).toMatchRenderedOutput('0');
<add>
<add> // Changing the prop causes the count to increase by 100
<add> await ReactNoop.act(async () => {
<add> root.render(<App prop="B" />);
<add> });
<add> expect(root).toMatchRenderedOutput('100');
<add>
<add> // Now increment the count by 1 with a state update. And, in the same
<add> // batch, change the prop back to its original value.
<add> await ReactNoop.act(async () => {
<add> root.render(<App prop="A" />);
<add> app.setState(state => ({count: state.count + 1}));
<add> });
<add> // There were two total prop changes, plus an increment.
<add> expect(root).toMatchRenderedOutput('201');
<add> });
<ide> }); | 8 |
Ruby | Ruby | remove deprecate #update_all usage | 2f0c8c52e66f1a2a3d1c00efc207f227124e96c2 | <ide><path>activerecord/lib/active_record/counter_cache.rb
<ide> def update_counters(id, counters)
<ide> "#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{value.abs}"
<ide> end
<ide>
<del> update_all(updates.join(', '), primary_key => id)
<add> where(primary_key => id).update_all updates.join(', ')
<ide> end
<ide>
<ide> # Increment a number field by one, usually representing a count.
<ide><path>activerecord/lib/active_record/persistence.rb
<ide> def update_column(name, value)
<ide> verify_readonly_attribute(name)
<ide> raise ActiveRecordError, "can not update on a new record object" unless persisted?
<ide> raw_write_attribute(name, value)
<del> self.class.update_all({ name => value }, self.class.primary_key => id) == 1
<add> self.class.where(self.class.primary_key => id).update_all(name => value) == 1
<ide> end
<ide>
<ide> # Updates the attributes of the model from the passed-in hash and saves the
<ide> def touch(name = nil)
<ide>
<ide> @changed_attributes.except!(*changes.keys)
<ide> primary_key = self.class.primary_key
<del> self.class.unscoped.update_all(changes, { primary_key => self[primary_key] }) == 1
<add> self.class.unscoped.where(primary_key => self[primary_key]).update_all(changes) == 1
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/dirty_test.rb
<ide> def test_partial_update
<ide>
<ide> with_partial_updates Pirate, false do
<ide> assert_queries(2) { 2.times { pirate.save! } }
<del> Pirate.update_all({ :updated_on => old_updated_on }, :id => pirate.id)
<add> Pirate.where(id: pirate.id).update_all(:updated_on => old_updated_on)
<ide> end
<ide>
<ide> with_partial_updates Pirate, true do
<ide> def test_partial_update_with_optimistic_locking
<ide>
<ide> with_partial_updates Person, false do
<ide> assert_queries(2) { 2.times { person.save! } }
<del> Person.update_all({ :first_name => 'baz' }, :id => person.id)
<add> Person.where(id: person.id).update_all(:first_name => 'baz')
<ide> end
<ide>
<ide> with_partial_updates Person, true do
<ide><path>activerecord/test/cases/persistence_test.rb
<ide> def test_delete_all_with_joins_and_where_part_is_not_hash
<ide> assert_equal count, Pet.joins(:toys).where(where_args).delete_all
<ide> end
<ide>
<del> def test_update_by_condition
<del> Topic.update_all "content = 'bulk updated!'", ["approved = ?", true]
<del> assert_equal "Have a nice day", Topic.find(1).content
<del> assert_equal "bulk updated!", Topic.find(2).content
<del> end
<del>
<ide> def test_increment_attribute
<ide> assert_equal 50, accounts(:signals37).credit_limit
<ide> accounts(:signals37).increment! :credit_limit
<ide> def test_update_all_with_hash
<ide> end
<ide>
<ide> def test_update_all_with_non_standard_table_name
<del> assert_equal 1, WarehouseThing.update_all(['value = ?', 0], ['id = ?', 1])
<add> assert_equal 1, WarehouseThing.where(id: 1).update_all(['value = ?', 0])
<ide> assert_equal 0, WarehouseThing.find(1).value
<ide> end
<ide> | 4 |
Javascript | Javascript | add test case of passthrough | 63e889a256de8576875a8367923d87c704332980 | <ide><path>test/parallel/test-stream2-transform.js
<ide> test('object passthrough', function(t) {
<ide> t.end();
<ide> });
<ide>
<add>test('passthrough constructor', function(t) {
<add> const pt = PassThrough();
<add>
<add> assert(pt instanceof PassThrough);
<add>
<add> t.end();
<add>});
<add>
<ide> test('simple transform', function(t) {
<ide> var pt = new Transform();
<ide> pt._transform = function(c, e, cb) { | 1 |
PHP | PHP | allow higher order groupby | 87838b56581bca1d5bc52f6d38de8bf1d52ace11 | <ide><path>src/Illuminate/Support/Collection.php
<ide> class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate
<ide> * @var array
<ide> */
<ide> protected static $proxies = [
<del> 'average', 'avg', 'contains', 'each', 'every', 'filter', 'first', 'flatMap', 'keyBy',
<del> 'map', 'max', 'min', 'partition', 'reject', 'sortBy', 'sortByDesc', 'sum', 'unique',
<add> 'average', 'avg', 'contains', 'each', 'every', 'filter', 'first',
<add> 'flatMap', 'groupBy', 'keyBy', 'map', 'max', 'min', 'partition',
<add> 'reject', 'sortBy', 'sortByDesc', 'sum', 'unique',
<ide> ];
<ide>
<ide> /**
<ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testSplitEmptyCollection()
<ide> );
<ide> }
<ide>
<add> public function testHigherOrderCollectionGroupBy()
<add> {
<add> $collection = collect([
<add> new TestSupportCollectionHigherOrderItem,
<add> new TestSupportCollectionHigherOrderItem('TAYLOR'),
<add> new TestSupportCollectionHigherOrderItem('foo'),
<add> ]);
<add>
<add> $this->assertEquals([
<add> 'taylor' => [$collection[0]],
<add> 'TAYLOR' => [$collection[1]],
<add> 'foo' => [$collection[2]],
<add> ], $collection->groupBy->name->toArray());
<add>
<add> $this->assertEquals([
<add> 'TAYLOR' => [$collection[0], $collection[1]],
<add> 'FOO' => [$collection[2]],
<add> ], $collection->groupBy->uppercase()->toArray());
<add> }
<add>
<ide> public function testHigherOrderCollectionMap()
<ide> {
<ide> $person1 = (object) ['name' => 'Taylor'];
<ide> public function testGetWithNullReturnsNull()
<ide>
<ide> class TestSupportCollectionHigherOrderItem
<ide> {
<del> public $name = 'taylor';
<add> public $name;
<add>
<add> public function __construct($name = 'taylor')
<add> {
<add> $this->name = $name;
<add> }
<ide>
<ide> public function uppercase()
<ide> {
<del> $this->name = strtoupper($this->name);
<add> return $this->name = strtoupper($this->name);
<ide> }
<ide> }
<ide> | 2 |
Javascript | Javascript | remove some unnecessary next ticks | ab755484a8a5113cb6d74f8e8ae5a26c44ae4582 | <ide><path>lib/internal/http2/core.js
<ide> function onSettings() {
<ide> session[kUpdateTimer]();
<ide> debug(`Http2Session ${sessionName(session[kType])}: new settings received`);
<ide> session[kRemoteSettings] = undefined;
<del> process.nextTick(emit, session, 'remoteSettings', session.remoteSettings);
<add> session.emit('remoteSettings', session.remoteSettings);
<ide> }
<ide>
<ide> // If the stream exists, an attempt will be made to emit an event
<ide> function onPriority(id, parent, weight, exclusive) {
<ide> const emitter = session[kState].streams.get(id) || session;
<ide> if (!emitter.destroyed) {
<ide> emitter[kUpdateTimer]();
<del> process.nextTick(emit, emitter, 'priority', id, parent, weight, exclusive);
<add> emitter.emit('priority', id, parent, weight, exclusive);
<ide> }
<ide> }
<ide>
<ide> function onFrameError(id, type, code) {
<ide> `type ${type} on stream ${id}, code: ${code}`);
<ide> const emitter = session[kState].streams.get(id) || session;
<ide> emitter[kUpdateTimer]();
<del> process.nextTick(emit, emitter, 'frameError', type, code, id);
<add> emitter.emit('frameError', type, code, id);
<ide> }
<ide>
<ide> function onAltSvc(stream, origin, alt) {
<ide> function onAltSvc(stream, origin, alt) {
<ide> debug(`Http2Session ${sessionName(session[kType])}: altsvc received: ` +
<ide> `stream: ${stream}, origin: ${origin}, alt: ${alt}`);
<ide> session[kUpdateTimer]();
<del> process.nextTick(emit, session, 'altsvc', alt, origin, stream);
<add> session.emit('altsvc', alt, origin, stream);
<ide> }
<ide>
<ide> // Receiving a GOAWAY frame from the connected peer is a signal that no
<ide> function setupHandle(socket, type, options) {
<ide> // core will check for session.destroyed before progressing, this
<ide> // ensures that those at l`east get cleared out.
<ide> if (this.destroyed) {
<del> process.nextTick(emit, this, 'connect', this, socket);
<add> this.emit('connect', this, socket);
<ide> return;
<ide> }
<ide> debug(`Http2Session ${sessionName(type)}: setting up session handle`);
<ide> function setupHandle(socket, type, options) {
<ide> options.settings : {};
<ide>
<ide> this.settings(settings);
<del> process.nextTick(emit, this, 'connect', this, socket);
<add> this.emit('connect', this, socket);
<ide> }
<ide>
<ide> // Emits a close event followed by an error event if err is truthy. Used
<ide> class Http2Session extends EventEmitter {
<ide> }
<ide> }
<ide>
<del> process.nextTick(emit, this, 'timeout');
<add> this.emit('timeout');
<ide> }
<ide>
<ide> ref() {
<ide> function streamOnPause() {
<ide> function abort(stream) {
<ide> if (!stream.aborted &&
<ide> !(stream._writableState.ended || stream._writableState.ending)) {
<del> process.nextTick(emit, stream, 'aborted');
<ide> stream[kState].flags |= STREAM_FLAGS_ABORTED;
<add> stream.emit('aborted');
<ide> }
<ide> }
<ide>
<ide> class Http2Stream extends Duplex {
<ide> }
<ide> }
<ide>
<del> process.nextTick(emit, this, 'timeout');
<add> this.emit('timeout');
<ide> }
<ide>
<ide> // true if the HEADERS frame has been sent | 1 |
Javascript | Javascript | fix counter example | e621c79639d4ca661196024c04ed63aaf0c0fd0a | <ide><path>examples/counter/containers/App.js
<ide> import React from 'react';
<ide> import CounterApp from './CounterApp';
<del>import { createStore } from 'redux';
<add>import { createStore, applyMiddleware } from 'redux';
<ide> import { Provider } from 'redux/react';
<ide> import * as reducers from '../reducers';
<ide>
<del>const store = createStore(reducers);
<add>const createStoreWithMiddleware = applyMiddleware()(createStore);
<add>const store = createStoreWithMiddleware(reducers);
<ide>
<ide> export default class App {
<ide> render() { | 1 |
PHP | PHP | add error binder | a9bddfc0e0573aa2b6d9d553126e9bf0af064e7b | <ide><path>app/Providers/AppServiceProvider.php
<ide> class AppServiceProvider extends ServiceProvider {
<ide> 'Illuminate\Cookie\Middleware\Queue',
<ide> 'Illuminate\Session\Middleware\Reader',
<ide> 'Illuminate\Session\Middleware\Writer',
<add> 'Illuminate\View\Middleware\ErrorBinder',
<ide> ];
<ide>
<ide> /** | 1 |
PHP | PHP | fix union queries with order by bindings | 7d2c2c4d8b0fcf533ca6df68ad5ecc921e424e94 | <ide><path>src/Illuminate/Database/Query/Builder.php
<ide> class Builder
<ide> 'having' => [],
<ide> 'order' => [],
<ide> 'union' => [],
<add> 'unionOrder' => [],
<ide> ];
<ide>
<ide> /**
<ide> public function orderBy($column, $direction = 'asc')
<ide>
<ide> $column = new Expression('('.$query.')');
<ide>
<del> $this->addBinding($bindings, 'order');
<add> $this->addBinding($bindings, $this->unions ? 'unionOrder' : 'order');
<ide> }
<ide>
<ide> $direction = strtolower($direction);
<ide> public function orderByRaw($sql, $bindings = [])
<ide>
<ide> $this->{$this->unions ? 'unionOrders' : 'orders'}[] = compact('type', 'sql');
<ide>
<del> $this->addBinding($bindings, 'order');
<add> $this->addBinding($bindings, $this->unions ? 'unionOrder' : 'order');
<ide>
<ide> return $this;
<ide> }
<ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> public function testOrderBys()
<ide> $builder = $this->getBuilder();
<ide> $builder->select('*')->from('users')->orderByDesc('name');
<ide> $this->assertEquals('select * from "users" order by "name" desc', $builder->toSql());
<add>
<add> $builder = $this->getBuilder();
<add> $builder->select('*')->from('posts')->where('public', 1)
<add> ->unionAll($this->getBuilder()->select('*')->from('videos')->where('public', 1))
<add> ->orderByRaw('field(category, ?, ?) asc', ['news', 'opinion']);
<add> $this->assertEquals('(select * from "posts" where "public" = ?) union all (select * from "videos" where "public" = ?) order by field(category, ?, ?) asc', $builder->toSql());
<add> $this->assertEquals([1, 1, 'news', 'opinion'], $builder->getBindings());
<ide> }
<ide>
<ide> public function testOrderBySubQueries()
<ide> public function testOrderBySubQueries()
<ide>
<ide> $builder = $this->getBuilder()->select('*')->from('users')->orderByDesc($subQuery);
<ide> $this->assertEquals("$expected desc", $builder->toSql());
<add>
<add> $builder = $this->getBuilder();
<add> $builder->select('*')->from('posts')->where('public', 1)
<add> ->unionAll($this->getBuilder()->select('*')->from('videos')->where('public', 1))
<add> ->orderBy($this->getBuilder()->selectRaw('field(category, ?, ?)', ['news', 'opinion']));
<add> $this->assertEquals('(select * from "posts" where "public" = ?) union all (select * from "videos" where "public" = ?) order by (select field(category, ?, ?)) asc', $builder->toSql());
<add> $this->assertEquals([1, 1, 'news', 'opinion'], $builder->getBindings());
<ide> }
<ide>
<ide> public function testOrderByInvalidDirectionParam() | 2 |
Text | Text | improve section in constant autoload guide | 3aebff160d10770f828e485f020e1a84d8835d94 | <ide><path>guides/source/constant_autoloading_and_reloading.md
<ide> been triggered in the first place. Thus, Rails assumes a qualified reference and
<ide> considers the file `admin/user.rb` and directory `admin/user` to be the only
<ide> valid options.
<ide>
<del>In practice this works quite well as long as the nesting matches all parent
<add>In practice, this works quite well as long as the nesting matches all parent
<ide> namespaces respectively and the constants that make the rule apply are known at
<ide> that time.
<ide>
<del>But since autoloading happens on demand, if the top-level `User` by chance was
<del>not yet loaded then Rails has no way to know whether `Admin::User` should load it
<del>or raise `NameError`.
<add>However, autoloading happens on demand. If by chance the top-level `User` was
<add>not yet loaded, then Rails has no way to know whether `Admin::User` should load
<add>it or raise `NameError`.
<ide>
<del>These kind of name conflicts are rare in practice but, in case there's one,
<del>`require_dependency` provides a solution by making sure the constant needed to
<del>trigger the heuristic is defined in the conflicting place.
<add>Naming conflicts of this kind are rare in practice, but if one occurs,
<add>`require_dependency` provides a solution by ensuring that the constant needed
<add>to trigger the heuristic is defined in the conflicting place.
<ide>
<ide> ### Automatic Modules
<ide> | 1 |
Text | Text | add 2.5.1 to changelog.md | bfa224201dea93efa012e6429db505d191a5167a | <ide><path>CHANGELOG.md
<ide> - [#13285](https://github.com/emberjs/ember.js/pull/13285) [BUGFIX] Make `Enumerable#firstObject` read only.
<ide> - [#13289](https://github.com/emberjs/ember.js/pull/13289) [BUGFIX] Make `Enumerable#lastObject` read only.
<ide>
<add>### 2.5.1 (April 21, 2016)
<add>
<add>- [#13310](https://github.com/emberjs/ember.js/pull/13310) [BUGFIX] Fix `mouseenter` typo in ember-testing helpers.
<add>- [#13333](https://github.com/emberjs/ember.js/pull/13333) [BUGFIX] Prevent the `toString` property from being added to the objects own
<add> properties. Fixes scenarios where the list of own properties changed in debug builds.
<add>- [#13335](https://github.com/emberjs/ember.js/pull/13335) [BUGFIX] Ensure injected property assertion checks `container`. Fixes issues
<add> with usage of objects created by older addons that are attempting to use `Ember.inject.service()`.
<add>- [#13344](https://github.com/emberjs/ember.js/pull/13344) [BUGFIX] Remove Ember.merge deprecation.
<add>
<ide> ### 2.5.0 (April 11, 2016)
<ide>
<ide> - [#13239](https://github.com/emberjs/ember.js/pull/13239) [BUGFIX] Prevent warnings for unknown feature flags | 1 |
PHP | PHP | add strict_types to database/schema | 13a498cffd5ab1a858dcb3dd9f32efc842768fc3 | <ide><path>src/Database/Schema/BaseSchema.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Database/Schema/CachedCollection.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Database/Schema/Collection.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Database/Schema/MysqlSchema.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Database/Schema/PostgresSchema.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Database/Schema/SqlGeneratorInterface.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/Database/Schema/SqliteSchema.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function convertColumnDescription(TableSchema $schema, $row)
<ide> */
<ide> protected function _defaultValue($default)
<ide> {
<del> if ($default === 'NULL') {
<add> if ($default === 'NULL' || $default === null) {
<ide> return null;
<ide> }
<ide>
<ide> // Remove quotes
<del> if (preg_match("/^'(.*)'$/", $default, $matches)) {
<add> if (preg_match("/^'(.*)'$/", (string)$default, $matches)) {
<ide> return str_replace("''", "'", $matches[1]);
<ide> }
<ide>
<ide><path>src/Database/Schema/SqlserverSchema.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Database/Schema/TableSchema.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Database/Schema/TableSchemaAwareInterface.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/Database/Schema/TableSchemaInterface.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>tests/TestCase/Database/Schema/CollectionTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Database/Schema/SqliteSchemaTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Database/Schema/SqlserverSchemaTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Database/Schema/TableSchemaTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) | 17 |
Python | Python | replace the todo with a proper bug | c277bcb0417f5c682f945627bd9d78a5763c38cf | <ide><path>keras/dtensor/layout_map.py
<ide> def _create_dvariable(layout_map, object_path, variable):
<ide> Returns:
<ide> A new tf.Variable with correct layout information.
<ide> """
<del> # TODO(scottzhu): Revisit this in future and see if we can just reuse the
<add> # TODO(b/228209108): Revisit this in future and see if we can just reuse the
<ide> # LazyInitVariable rather than creating a new tf.Variable instance.
<ide> layout = layout_map[object_path]
<ide> if layout is None: | 1 |
Javascript | Javascript | update jsm modules | a4e573604cf1694db8f0059798bc97653fd538a6 | <ide><path>examples/jsm/renderers/CSS3DRenderer.js
<ide> var CSS3DObject = function ( element ) {
<ide>
<ide> this.addEventListener( 'removed', function () {
<ide>
<del> if ( this.element.parentNode !== null ) {
<add> this.traverse( function( object ) {
<ide>
<del> this.element.parentNode.removeChild( this.element );
<add> if ( object.element instanceof Element && object.element.parentNode !== null ) {
<ide>
<del> }
<add> object.element.parentNode.removeChild( object.element );
<add>
<add> }
<add>
<add> } );
<ide>
<ide> } );
<ide> | 1 |
PHP | PHP | remove fallback locale | 227683be9fbddbd646c005face523dadf297a49a | <ide><path>app/config/app.php
<ide>
<ide> 'locale' => 'en',
<ide>
<del> /*
<del> |--------------------------------------------------------------------------
<del> | Application Fallback Locale
<del> |--------------------------------------------------------------------------
<del> |
<del> | The fallback locale determines the locale to use when the current one
<del> | is not available. You may change the value to correspond to any of
<del> | the language folders that are provided through your application.
<del> |
<del> */
<del>
<del> 'fallback_locale' => 'en',
<del>
<ide> /*
<ide> |--------------------------------------------------------------------------
<ide> | Encryption Key | 1 |
Mixed | Text | add support for 'docker cp' to write to stdout | f3d96e81e9c2a738ec577b814092f8953932de3a | <ide><path>api/client/commands.go
<ide> func (cli *DockerCli) CmdRun(args ...string) error {
<ide> }
<ide>
<ide> func (cli *DockerCli) CmdCp(args ...string) error {
<del> cmd := cli.Subcmd("cp", "CONTAINER:PATH HOSTPATH", "Copy files/folders from the PATH to the HOSTPATH", true)
<add> cmd := cli.Subcmd("cp", "CONTAINER:PATH HOSTPATH|-", "Copy files/folders from the PATH to the HOSTPATH. Use '-' to write the data\nas a tar file to STDOUT.", true)
<ide> cmd.Require(flag.Exact, 2)
<ide>
<ide> utils.ParseFlags(cmd, args, true)
<ide> func (cli *DockerCli) CmdCp(args ...string) error {
<ide> }
<ide>
<ide> if statusCode == 200 {
<del> if err := archive.Untar(stream, copyData.Get("HostPath"), &archive.TarOptions{NoLchown: true}); err != nil {
<add> dest := copyData.Get("HostPath")
<add>
<add> if dest == "-" {
<add> _, err = io.Copy(cli.out, stream)
<add> } else {
<add> err = archive.Untar(stream, dest, &archive.TarOptions{NoLchown: true})
<add> }
<add> if err != nil {
<ide> return err
<ide> }
<ide> }
<ide><path>docs/man/docker-cp.1.md
<ide> % Docker Community
<ide> % JUNE 2014
<ide> # NAME
<del>docker-cp - Copy files/folders from the PATH to the HOSTPATH
<add>docker-cp - Copy files/folders from the PATH to the HOSTPATH, or STDOUT
<ide>
<ide> # SYNOPSIS
<ide> **docker cp**
<ide> [**--help**]
<del>CONTAINER:PATH HOSTPATH
<add>CONTAINER:PATH HOSTPATH|-
<ide>
<ide> # DESCRIPTION
<del>Copy files/folders from a container's filesystem to the host
<del>path. Paths are relative to the root of the filesystem. Files
<add>Copy files/folders from a container's filesystem to the
<add>path. Use '-' to write the data as a tar file to STDOUT.
<add>Paths are relative to the root of the filesystem. Files
<ide> can be copied from a running or stopped container.
<ide>
<ide> # OPTIONS
<ide><path>docs/man/docker.1.md
<ide> unix://[/path/to/socket] to use.
<ide> Create a new image from a container's changes
<ide>
<ide> **docker-cp(1)**
<del> Copy files/folders from a container's filesystem to the host at path
<add> Copy files/folders from a container's filesystem to the host
<ide>
<ide> **docker-create(1)**
<ide> Create a new container
<ide><path>docs/sources/reference/commandline/cli.md
<ide> Supported `Dockerfile` instructions: `CMD`, `ENTRYPOINT`, `ENV`, `EXPOSE`,
<ide>
<ide> ## cp
<ide>
<del>Copy files/folders from a container's filesystem to the host
<del>path. Paths are relative to the root of the filesystem.
<add>Copy files/folders from a container's filesystem to the
<add>path. Use '-' to write the data as a tar file to STDOUT.
<add>Paths are relative to the root of the filesystem.
<ide>
<del> Usage: docker cp CONTAINER:PATH HOSTPATH
<add> Usage: docker cp CONTAINER:PATH HOSTPATH|-
<add>
<add> Copy files/folders from the PATH to the HOSTPATH. Use '-' to write the data
<add> as a tar file to STDOUT.
<ide>
<del> Copy files/folders from the PATH to the HOSTPATH
<ide>
<ide> ## create
<ide>
<ide><path>integration-cli/docker_cli_cp_test.go
<ide> import (
<ide> "os/exec"
<ide> "path"
<ide> "path/filepath"
<add> "strings"
<ide> "testing"
<ide> )
<ide>
<ide> func TestCpToDot(t *testing.T) {
<ide> }
<ide> logDone("cp - to dot path")
<ide> }
<add>
<add>func TestCpToStdout(t *testing.T) {
<add> out, exitCode, err := dockerCmd(t, "run", "-d", "busybox", "/bin/sh", "-c", "echo lololol > /test")
<add> if err != nil || exitCode != 0 {
<add> t.Fatalf("failed to create a container:%s\n%s", out, err)
<add> }
<add>
<add> cID := stripTrailingCharacters(out)
<add> defer deleteContainer(cID)
<add>
<add> out, _, err = dockerCmd(t, "wait", cID)
<add> if err != nil || stripTrailingCharacters(out) != "0" {
<add> t.Fatalf("failed to set up container:%s\n%s", out, err)
<add> }
<add>
<add> out, _, err = runCommandPipelineWithOutput(
<add> exec.Command(dockerBinary, "cp", cID+":/test", "-"),
<add> exec.Command("tar", "-vtf", "-"))
<add> if err != nil {
<add> t.Fatalf("Failed to run commands: %s", err)
<add> }
<add>
<add> if !strings.Contains(out, "test") || !strings.Contains(out, "-rw") {
<add> t.Fatalf("Missing file from tar TOC:\n%s", out)
<add> }
<add> logDone("cp - to stdout")
<add>} | 5 |
Python | Python | remove unused testpy code | dc4313c62007c8473331221c501d09fa70fa3478 | <ide><path>test/testpy/__init__.py
<ide> def __init__(self, path, file, arch, mode, context, config, additional=None):
<ide> self.config = config
<ide> self.arch = arch
<ide> self.mode = mode
<del> self.tmpdir = join(dirname(self.config.root), 'tmp')
<ide> if additional is not None:
<ide> self.additional_flags = additional
<ide> else: | 1 |
Text | Text | update ruby symbols portuguese guide | f1e6fad974b3b9191e41af85a65c0ae76f2199c9 | <ide><path>guide/portuguese/ruby/ruby-symbols/index.md
<ide> localeTitle: Ruby Symbols
<ide> ---
<ide> ## Ruby Symbols
<ide>
<del>Um símbolo se parece com um nome de variável, mas é prefixado com dois pontos. Exemplos -: action,: line\_items Você não tem que pré-declarar um símbolo e é garantido que ele é único. Não há necessidade de atribuir algum tipo de valor a um símbolo - Ruby cuida disso para você. O Ruby também garante que, não importa onde ele apareça no seu programa, um símbolo específico terá o mesmo valor.
<add>Um símbolo se parece com um nome de variável, mas é prefixado com dois pontos. Exemplos - `:action`, `:line_items`. Você não tem que pré-declarar um símbolo e é garantido que ele é único. Não há necessidade de atribuir algum tipo de valor a um símbolo - Ruby cuida disso para você. O Ruby também garante que, não importa onde ele apareça no seu programa, um símbolo específico terá o mesmo valor.
<ide>
<del>Alternativamente, você pode considerar os dois pontos para significar "coisa chamada" assim: id é "a coisa chamada id". Você também pode pensar em: id como significando o nome da variável id e plain id como significando o valor da variável.
<add>Alternativamente, você pode considerar os dois pontos para significar "coisa chamada" assim `:id` é "a coisa chamada id". Você também pode pensar em `:id` como significando o nome da variável id e plain id como significando o valor da variável.
<ide>
<del>Por ex: Assim, se Fred é uma constante em um contexto, um método em outro e uma classe em um terceiro, o símbolo: Fred será o mesmo objeto em todos os três contextos.
<add>Por ex: Assim, se Fred é uma constante em um contexto, um método em outro e uma classe em um terceiro, o símbolo `:Fred` será o mesmo objeto em todos os três contextos.
<ide>
<ide> ```ruby
<del>module One
<add>module One
<ide> class Fred
<ide> end
<ide> $f1 = :Fred
<del> end
<del> module Two
<add>end
<add>
<add>module Two
<ide> Fred = 1
<ide> $f2 = :Fred
<del> end
<del> def Fred()
<del> end
<del> $f3 = :Fred
<del> $f1.object_id #=> 2514190
<del> $f2.object_id #=> 2514190
<del> $f3.object_id #=> 2514190
<add>end
<add>
<add>def Fred()
<add>end
<add>
<add>$f3 = :Fred
<add>$f1.object_id #=> 2514190
<add>$f2.object_id #=> 2514190
<add>$f3.object_id #=> 2514190
<ide> ```
<ide>
<ide> ## Trabalhando com Símbolos
<ide>
<del>Você pode reconhecer um Símbolo Ruby porque será uma palavra que começa com:.
<add>Você pode reconhecer um Símbolo Ruby porque será uma palavra que começa com `:`.
<ide>
<ide> Até agora nós os vimos como a chave em um Hash (Trabalhando com Hashes em Ruby):
<ide>
<ide> Então, a primeira coisa que podemos fazer é inspecionar um símbolo para ver q
<ide>
<ide> ```ruby
<ide> :hello.class
<del> => Symbol
<add>=> Symbol
<ide>
<del> "hello".class
<del> => String
<add>"hello".class
<add>=> String
<ide> ```
<ide>
<ide> Assim, podemos ver que Símbolos e Strings são instâncias de dois objetos diferentes.
<ide>
<del>Você pode chamar métodos String-como como `upcase` , `downcase` e `capitalize` sobre Símbolos:
<add>Você pode chamar métodos String como `upcase`, `downcase` e `capitalize` em Símbolos:
<ide>
<ide> ```ruby
<ide> :hello.upcase
<del> => :HELLO
<add>=> :HELLO
<ide>
<del> :HELLO.downcase
<del> => :hello
<add>:HELLO.downcase
<add>=> :hello
<ide>
<del> :hello.capitalize
<del> => :Hello
<add>:hello.capitalize
<add>=> :Hello
<ide> ```
<ide>
<ide> ## Por que você usaria um símbolo em vez de uma String?
<ide> Então, se um símbolo é apenas uma string imutável, por que você o usaria, e
<ide>
<ide> Em primeiro lugar, uma das grandes razões é, como mencionei acima, os símbolos são imutáveis. Erros imprevistos podem surgir em seu aplicativo quando um valor pode mudar. Se você precisa garantir que o valor de um objeto nunca mude, é muito mais seguro usar um objeto imutável.
<ide>
<del>No entanto, com isso dito, é possível tornar uma String imutável em Ruby chamando o método `freeze` :
<add>No entanto, com isso dito, é possível tornar uma String imutável em Ruby chamando o método `freeze`:
<ide>
<ide> ```ruby
<ide> name = "Philip"
<del> => "Philip"
<add>=> "Philip"
<ide>
<del> name.freeze
<del> => "Philip"
<add>name.freeze
<add>=> "Philip"
<ide>
<del> name << "Jim"
<del> RuntimeError: can't modify frozen String
<add>name << "Jim"
<add>RuntimeError: can't modify frozen String
<ide> ```
<ide>
<ide> Como você pode ver no exemplo acima, depois de chamar o método freeze em uma instância de String, não será mais possível modificá-lo.
<ide> Uma segunda razão pela qual você usaria um símbolo em uma sequência em deter
<ide> Por exemplo:
<ide>
<ide> ```ruby
<del>philip".object_id
<del> => 70288511587360
<del> "philip".object_id
<del> => 70288504327720
<del>
<del> :philip.object_id
<del> => 539368
<del> :philip.object_id
<del> => 539368
<add>"philip".object_id
<add>=> 70288511587360
<add>"philip".object_id
<add>=> 70288504327720
<add>:philip.object_id
<add>=> 539368
<add>:philip.object_id
<add>=> 539368
<ide> ```
<ide>
<ide> Quando você cria dois objetos String com o mesmo valor, esses dois objetos são tratados como dois objetos diferentes. Quando você cria um símbolo, referenciando o símbolo sempre usará o mesmo objeto.
<ide>
<del>Isso é muito melhor para o desempenho porque o mesmo objeto String será criado e destruído repetidamente quando, na realidade, o mesmo objeto pode ser reutilizado a cada vez.
<add>Isso é muito melhor para o desempenho porque o mesmo objeto String será criado e destruído repetidamente quando na realidade o mesmo objeto pode ser reutilizado a cada vez.
<ide>
<ide> #### Métodos de Classe Pública
<ide>
<del>all\_symbols => array clica para alternar a fonte Retorna uma matriz de todos os símbolos atualmente na tabela de símbolos do Ruby.
<add>`all_symbols` - Retorna uma matriz de todos os símbolos atualmente na tabela de símbolos do Ruby.
<ide>
<ide> ```ruby
<ide> Symbol.all_symbols.size #=> 903
<del> Symbol.all_symbols[1,20] #=> [:floor, :ARGV, :Binding, :symlink,
<add>Symbol.all_symbols[1,20] #=> [:floor, :ARGV, :Binding, :symlink,
<ide> :chown, :EOFError, :$;, :String,
<ide> :LOCK_SH, :"setuid?", :$<,
<ide> :default_proc, :compact, :extend,
<ide> :Tms, :getwd, :$=, :ThreadGroup,
<del> :wait2, :$>]
<add> :wait2, :$>]
<ide> ```
<ide>
<ide> #### Mais Informações:
<ide>
<del>[Documentação de Símbolos Ruby](http://ruby-doc.org/core-2.5.1/Symbol.html)
<ide>\ No newline at end of file
<add>[Documentação de Símbolos Ruby](http://ruby-doc.org/core-2.5.1/Symbol.html) | 1 |
Ruby | Ruby | allow some forms of gist patches | 192e6e052cd5e0ab47aa53e8b438640efedc3630 | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_patches
<ide> Patches.new(f.patches).select { |p| p.external? }.each do |p|
<ide> case p.url
<ide> when %r[raw\.github\.com], %r[gist\.github\.com/raw]
<del> problem "Using raw GitHub URLs is not recommended:\n#{p.url}"
<add> unless p.url =~ /[a-fA-F0-9]{40}/
<add> problem "GitHub/Gist patches should specify a revision:\n#{p.url}"
<add> end
<ide> when %r[macports/trunk]
<ide> problem "MacPorts patches should specify a revision instead of trunk:\n#{p.url}"
<ide> end | 1 |
Javascript | Javascript | add emberall to showcase | a5083a3cd5f463a94f4e4bd382a768c2f960b841 | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> icon: 'http://a4.mzstatic.com/us/r30/Purple60/v4/1a/42/5b/1a425b56-848a-91f5-8078-9f5473c9021f/icon350x350.png',
<ide> link: 'https://itunes.apple.com/us/app/clapit/id1062124740?mt=8',
<ide> author: 'Refined Edge Solutions, LLC'
<del> },
<add> },
<ide> {
<ide> name: 'Codementor - Live 1:1 Expert Developer Help',
<ide> icon: 'http://a1.mzstatic.com/us/r30/Purple3/v4/db/cf/35/dbcf3523-bac7-0f54-c6a8-a80bf4f43c38/icon175x175.jpeg',
<ide> var apps = [
<ide> link: 'http://android.myapp.com/myapp/detail.htm?apkName=com.tencent.karaoke',
<ide> author: '石玉磊',
<ide> },
<add> {
<add> name: 'Emberall',
<add> icon: 'http://assets.emberall.com/images/app/icons/medium.png',
<add> link: 'https://emberall.com/',
<add> author: 'Kyle Corbitt',
<add> },
<ide> ];
<ide>
<ide> var AppList = React.createClass({ | 1 |
Javascript | Javascript | remove outdated code | 268aa2d46f9ca88f0d57621e59c1128f6c0241a5 | <ide><path>examples/jsm/shaders/MMDToonShader.js
<ide> void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in Geometric
<ide>
<ide> #define RE_Direct RE_Direct_BlinnPhong
<ide> #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong
<del>
<del>#define Material_LightProbeLOD( material ) (0)
<ide> `;
<ide>
<ide> const mmd_toon_matcap_fragment = /* glsl */`
<ide><path>src/renderers/shaders/ShaderChunk/lights_fragment_begin.glsl.js
<ide> export default /* glsl */`
<ide> *
<ide> * Instructions for use:
<ide> * - Ensure that both RE_Direct, RE_IndirectDiffuse and RE_IndirectSpecular are defined
<del> * - If you have defined an RE_IndirectSpecular, you need to also provide a Material_LightProbeLOD. <---- ???
<ide> * - Create a material parameter that is to be passed as the third parameter to your lighting functions.
<ide> *
<ide> * TODO:
<ide><path>src/renderers/shaders/ShaderChunk/lights_lambert_pars_fragment.glsl.js
<ide> void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricCon
<ide>
<ide> #define RE_Direct RE_Direct_Lambert
<ide> #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert
<del>
<del>#define Material_LightProbeLOD( material ) (0)
<ide> `;
<ide><path>src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl.js
<ide> void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in Geometric
<ide>
<ide> #define RE_Direct RE_Direct_BlinnPhong
<ide> #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong
<del>
<del>#define Material_LightProbeLOD( material ) (0)
<ide> `;
<ide><path>src/renderers/shaders/ShaderChunk/lights_toon_pars_fragment.glsl.js
<ide> void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContex
<ide>
<ide> #define RE_Direct RE_Direct_Toon
<ide> #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon
<del>
<del>#define Material_LightProbeLOD( material ) (0)
<ide> `; | 5 |
Javascript | Javascript | increase coverage for fs.promises.truncate | e5a3579a50a7095c337da25054c9c610a3484779 | <ide><path>test/parallel/test-fs-promises-file-handle-truncate.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const path = require('path');
<add>const { open, readFile } = require('fs').promises;
<add>const tmpdir = require('../common/tmpdir');
<add>
<add>tmpdir.refresh();
<add>common.crashOnUnhandledRejection();
<add>
<add>async function validateTruncate() {
<add> const text = 'Hello world';
<add> const filename = path.resolve(tmpdir.path, 'truncate-file.txt');
<add> const fileHandle = await open(filename, 'w+');
<add>
<add> const buffer = Buffer.from(text, 'utf8');
<add> await fileHandle.write(buffer, 0, buffer.length);
<add>
<add> assert.deepStrictEqual((await readFile(filename)).toString(), text);
<add>
<add> await fileHandle.truncate(5);
<add> assert.deepStrictEqual((await readFile(filename)).toString(), 'Hello');
<add>}
<add>
<add>validateTruncate().then(common.mustCall());
<ide><path>test/parallel/test-fs-promises.js
<ide> const {
<ide> mkdir,
<ide> mkdtemp,
<ide> open,
<add> readFile,
<ide> readdir,
<ide> readlink,
<ide> realpath,
<ide> rename,
<ide> rmdir,
<ide> stat,
<ide> symlink,
<add> truncate,
<ide> unlink,
<ide> utimes
<ide> } = fsPromises;
<ide> function verifyStatObject(stat) {
<ide> const ret2 = await handle.read(Buffer.alloc(buf2Len), 0, buf2Len, 0);
<ide> assert.strictEqual(ret2.bytesRead, buf2Len);
<ide> assert.deepStrictEqual(ret2.buffer, buf2);
<add> await truncate(dest, 5);
<add> assert.deepStrictEqual((await readFile(dest)).toString(), 'hello');
<ide>
<ide> await chmod(dest, 0o666);
<ide> await handle.chmod(0o666); | 2 |
Go | Go | add implementation for lookupcontainerid | 0969e192f2aa23e3d54087eb37540503cadb1e99 | <ide><path>libnetwork/client/client_test.go
<ide> func setupMockHTTPCallback() {
<ide> rsp = string(mockServiceListJSON)
<ide> } else if strings.HasSuffix(path, "services/"+mockServiceID) {
<ide> rsp = string(mockServiceJSON)
<add> } else if strings.Contains(path, "containers") {
<add> return nopCloser{bytes.NewBufferString("")}, 400, fmt.Errorf("Bad Request")
<ide> }
<ide> case "POST":
<ide> var data []byte
<ide><path>libnetwork/client/service.go
<ide> func lookupServiceID(cli *NetworkCli, nwName, svNameID string) (string, error) {
<ide> }
<ide>
<ide> func lookupContainerID(cli *NetworkCli, cnNameID string) (string, error) {
<del> // TODO : containerID to sandbox-key ?
<del> return cnNameID, nil
<add> // Container is a Docker resource, ask docker about it.
<add> // In case of connecton error, we assume we are running in dnet and return whatever was passed to us
<add> obj, _, err := readBody(cli.call("GET", fmt.Sprintf("/containers/%s/json", cnNameID), nil, nil))
<add> if err != nil {
<add> // We are probably running outside of docker
<add> return cnNameID, nil
<add> }
<add>
<add> var x map[string]interface{}
<add> err = json.Unmarshal(obj, &x)
<add> if err != nil {
<add> return "", err
<add> }
<add> if iid, ok := x["Id"]; ok {
<add> if id, ok := iid.(string); ok {
<add> return id, nil
<add> }
<add> return "", fmt.Errorf("Unexpected data type for container ID in json response")
<add> }
<add> return "", fmt.Errorf("Cannot find container ID in json response")
<ide> }
<ide>
<ide> // CmdService handles the service UI | 2 |
PHP | PHP | update xcache tests | b4df11028bee38dc718172813e07c586f94c95fb | <ide><path>lib/Cake/Test/TestCase/Cache/Engine/XcacheEngineTest.php
<ide> <?php
<ide> /**
<del> * XcacheEngineTest file
<del> *
<del> * PHP 5
<del> *
<del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
<add> * CakePHP(tm) <http://book.cakephp.org/2.0/en/development/testing.html>
<ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<ide> * Licensed under The MIT License
<ide> * Redistributions of files must retain the above copyright notice
<ide> *
<ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<del> * @package Cake.Test.Case.Cache.Engine
<ide> * @since CakePHP(tm) v 1.2.0.5434
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> namespace Cake\Test\TestCase\Cache\Engine;
<add>
<ide> use Cake\Cache\Cache;
<ide> use Cake\Core\Configure;
<ide> use Cake\TestSuite\TestCase;
<ide> public function setUp() {
<ide> if (!function_exists('xcache_set')) {
<ide> $this->markTestSkipped('Xcache is not installed or configured properly');
<ide> }
<del> $this->_cacheDisable = Configure::read('Cache.disable');
<ide> Configure::write('Cache.disable', false);
<del> Cache::config('xcache', array('engine' => 'Xcache', 'prefix' => 'cake_'));
<add> Configure::write('Cache.xcache', ['engine' => 'Xcache', 'prefix' => 'cake_']);
<ide> }
<ide>
<ide> /**
<ide> public function setUp() {
<ide> */
<ide> public function tearDown() {
<ide> parent::tearDown();
<del> Configure::write('Cache.disable', $this->_cacheDisable);
<ide> Cache::drop('xcache');
<ide> Cache::drop('xcache_groups');
<del> Cache::config('default');
<ide> }
<ide>
<ide> /**
<ide> public function tearDown() {
<ide> */
<ide> public function testSettings() {
<ide> $settings = Cache::settings();
<del> $expecting = array(
<add> $expecting = [
<ide> 'prefix' => 'cake_',
<ide> 'duration' => 3600,
<ide> 'probability' => 100,
<ide> 'engine' => 'Xcache',
<del> );
<add> ];
<ide> $this->assertTrue(isset($settings['PHP_AUTH_USER']));
<ide> $this->assertTrue(isset($settings['PHP_AUTH_PW']));
<ide>
<ide> public function testSettings() {
<ide> * @return void
<ide> */
<ide> public function testReadAndWriteCache() {
<del> Cache::set(array('duration' => 1));
<add> Cache::set(['duration' => 1], 'xcache');
<ide>
<del> $result = Cache::read('test');
<add> $result = Cache::read('test', 'xcache');
<ide> $expecting = '';
<ide> $this->assertEquals($expecting, $result);
<ide>
<ide> $data = 'this is a test of the emergency broadcasting system';
<del> $result = Cache::write('test', $data);
<add> $result = Cache::write('test', $data, 'xcache');
<ide> $this->assertTrue($result);
<ide>
<del> $result = Cache::read('test');
<add> $result = Cache::read('test', 'xcache');
<ide> $expecting = $data;
<ide> $this->assertEquals($expecting, $result);
<ide>
<del> Cache::delete('test');
<add> Cache::delete('test', 'xcache');
<ide> }
<ide>
<ide> /**
<ide> public function testReadAndWriteCache() {
<ide> * @return void
<ide> */
<ide> public function testExpiry() {
<del> Cache::set(array('duration' => 1));
<del> $result = Cache::read('test');
<add> Cache::set(['duration' => 1], 'xcache');
<add> $result = Cache::read('test', 'xcache');
<ide> $this->assertFalse($result);
<ide>
<ide> $data = 'this is a test of the emergency broadcasting system';
<del> $result = Cache::write('other_test', $data);
<add> $result = Cache::write('other_test', $data, 'xcache');
<ide> $this->assertTrue($result);
<ide>
<ide> sleep(2);
<del> $result = Cache::read('other_test');
<add> $result = Cache::read('other_test', 'xcache');
<ide> $this->assertFalse($result);
<ide>
<del> Cache::set(array('duration' => "+1 second"));
<add> Cache::set(['duration' => "+1 second"], 'xcache');
<ide>
<ide> $data = 'this is a test of the emergency broadcasting system';
<del> $result = Cache::write('other_test', $data);
<add> $result = Cache::write('other_test', $data, 'xcache');
<ide> $this->assertTrue($result);
<ide>
<ide> sleep(2);
<del> $result = Cache::read('other_test');
<add> $result = Cache::read('other_test', 'xcache');
<ide> $this->assertFalse($result);
<ide> }
<ide>
<ide> public function testExpiry() {
<ide> */
<ide> public function testDeleteCache() {
<ide> $data = 'this is a test of the emergency broadcasting system';
<del> $result = Cache::write('delete_test', $data);
<add> $result = Cache::write('delete_test', $data, 'xcache');
<ide> $this->assertTrue($result);
<ide>
<del> $result = Cache::delete('delete_test');
<add> $result = Cache::delete('delete_test', 'xcache');
<ide> $this->assertTrue($result);
<ide> }
<ide>
<ide> public function testDeleteCache() {
<ide> */
<ide> public function testClearCache() {
<ide> $data = 'this is a test of the emergency broadcasting system';
<del> $result = Cache::write('clear_test_1', $data);
<add> $result = Cache::write('clear_test_1', $data, 'xcache');
<ide> $this->assertTrue($result);
<ide>
<del> $result = Cache::write('clear_test_2', $data);
<add> $result = Cache::write('clear_test_2', $data, 'xcache');
<ide> $this->assertTrue($result);
<ide>
<ide> $result = Cache::clear();
<ide> public function testClearCache() {
<ide> * @return void
<ide> */
<ide> public function testDecrement() {
<del> $result = Cache::write('test_decrement', 5);
<add> $result = Cache::write('test_decrement', 5, 'xcache');
<ide> $this->assertTrue($result);
<ide>
<del> $result = Cache::decrement('test_decrement');
<add> $result = Cache::decrement('test_decrement', 'xcache');
<ide> $this->assertEquals(4, $result);
<ide>
<del> $result = Cache::read('test_decrement');
<add> $result = Cache::read('test_decrement', 'xcache');
<ide> $this->assertEquals(4, $result);
<ide>
<del> $result = Cache::decrement('test_decrement', 2);
<add> $result = Cache::decrement('test_decrement', 2, 'xcache');
<ide> $this->assertEquals(2, $result);
<ide>
<del> $result = Cache::read('test_decrement');
<add> $result = Cache::read('test_decrement', 'xcache');
<ide> $this->assertEquals(2, $result);
<ide> }
<ide>
<ide> public function testDecrement() {
<ide> * @return void
<ide> */
<ide> public function testIncrement() {
<del> $result = Cache::write('test_increment', 5);
<add> $result = Cache::write('test_increment', 5, 'xcache');
<ide> $this->assertTrue($result);
<ide>
<del> $result = Cache::increment('test_increment');
<add> $result = Cache::increment('test_increment', 'xcache');
<ide> $this->assertEquals(6, $result);
<ide>
<del> $result = Cache::read('test_increment');
<add> $result = Cache::read('test_increment', 'xcache');
<ide> $this->assertEquals(6, $result);
<ide>
<del> $result = Cache::increment('test_increment', 2);
<add> $result = Cache::increment('test_increment', 2, 'xcache');
<ide> $this->assertEquals(8, $result);
<ide>
<del> $result = Cache::read('test_increment');
<add> $result = Cache::read('test_increment', 'xcache');
<ide> $this->assertEquals(8, $result);
<ide> }
<ide>
<ide> public function testIncrement() {
<ide> * @return void
<ide> */
<ide> public function testGroupsReadWrite() {
<del> Cache::config('xcache_groups', array(
<add> Configure::write('Cache.xcache_groups', [
<ide> 'engine' => 'Xcache',
<ide> 'duration' => 0,
<del> 'groups' => array('group_a', 'group_b'),
<add> 'groups' => ['group_a', 'group_b'],
<ide> 'prefix' => 'test_'
<del> ));
<add> ]);
<ide> $this->assertTrue(Cache::write('test_groups', 'value', 'xcache_groups'));
<ide> $this->assertEquals('value', Cache::read('test_groups', 'xcache_groups'));
<ide>
<ide> public function testGroupsReadWrite() {
<ide> * @return void
<ide> */
<ide> public function testGroupDelete() {
<del> Cache::config('xcache_groups', array(
<add> Configure::write('Cache.xcache_groups', [
<ide> 'engine' => 'Xcache',
<ide> 'duration' => 0,
<del> 'groups' => array('group_a', 'group_b'),
<add> 'groups' => ['group_a', 'group_b'],
<ide> 'prefix' => 'test_'
<del> ));
<add> ]);
<ide> $this->assertTrue(Cache::write('test_groups', 'value', 'xcache_groups'));
<ide> $this->assertEquals('value', Cache::read('test_groups', 'xcache_groups'));
<ide> $this->assertTrue(Cache::delete('test_groups', 'xcache_groups'));
<ide> public function testGroupDelete() {
<ide> * @return void
<ide> **/
<ide> public function testGroupClear() {
<del> Cache::config('xcache_groups', array(
<add> Configure::write('Cache.xcache_groups', [
<ide> 'engine' => 'Xcache',
<ide> 'duration' => 0,
<del> 'groups' => array('group_a', 'group_b'),
<add> 'groups' => ['group_a', 'group_b'],
<ide> 'prefix' => 'test_'
<del> ));
<add> ]);
<ide>
<ide> $this->assertTrue(Cache::write('test_groups', 'value', 'xcache_groups'));
<ide> $this->assertTrue(Cache::clearGroup('group_a', 'xcache_groups')); | 1 |
Python | Python | fix the decode call | 8ec2140730f6306e652d3b9197a013da3f98f12f | <ide><path>libcloud/compute/drivers/ec2.py
<ide> def create_node(self, **kwargs):
<ide>
<ide> if 'ex_userdata' in kwargs:
<ide> params['UserData'] = base64.b64encode(b(kwargs['ex_userdata'])) \
<del> .decode('utf8')
<add> .decode('utf-8')
<ide>
<ide> if 'ex_clienttoken' in kwargs:
<ide> params['ClientToken'] = kwargs['ex_clienttoken'] | 1 |
Text | Text | fix example usage | f40384972bf92bc2c4f2e5b0a626ec5efb1df64c | <ide><path>guide/english/bash/bash-chmod/index.md
<ide> title: Bash chmod
<ide>
<ide> **Change the permissions of a File/Directory**, for example `chmod u+x hello.py`. (Gives the user the permission to execute the file)
<ide>
<add>### Usage
<add>
<add>**Change the permissions of a File/Directory**
<add>
<add>```bash
<add>chmod [permission] [file_names]
<add>```
<add>permission can be r+w or r+w+x ...etc
<add>
<add>* r = read
<add>* w = write
<add>* x = execute
<ide>
<ide> ### More Information:
<ide> * [Wikipedia](https://en.wikipedia.org/wiki/Chmod) | 1 |
PHP | PHP | use keyby instead of flatmap | 0f66352eb394e5f7ca10cd937bddef2898c49170 | <ide><path>src/Illuminate/Database/Eloquent/Relations/MorphTo.php
<ide> protected function getResultsByType($type)
<ide> */
<ide> protected function getEagerLoadsForInstance(Model $instance)
<ide> {
<del> $eagers = BaseCollection::make($this->query->getEagerLoads());
<add> $relations = BaseCollection::make($this->query->getEagerLoads());
<ide>
<del> return $eagers->filter(function ($constraint, $relation) {
<add> return $relations->filter(function ($constraint, $relation) {
<ide> return Str::startsWith($relation, $this->relation.'.');
<del> })->flatMap(function ($constraint, $relation) {
<del> return [Str::replaceFirst($this->relation.'.', '', $relation) => $constraint];
<add> })->keyBy(function ($constraint, $relation) {
<add> return Str::replaceFirst($this->relation.'.', '', $relation);
<ide> })->merge($instance->getEagerLoads())->all();
<ide> }
<ide> | 1 |
PHP | PHP | change fallbacks to accept a route class | 5af6464a49204f873aeac52024d295787809822a | <ide><path>src/Routing/RouteBuilder.php
<ide> public function scope($path, $params, $callback = null) {
<ide> *
<ide> * This is a shortcut method for connecting fallback routes in a given scope.
<ide> *
<add> * @param string $routeClass the route class to use, uses the default routeClass
<add> * if not specified
<ide> * @return void
<ide> */
<del> public function fallbacks() {
<del> $routeClass = $this->_routeClass;
<del> if ($routeClass === 'Cake\Routing\Route\Route') {
<del> $routeClass = 'InflectedRoute';
<del> }
<add> public function fallbacks($routeClass = null) {
<add> $routeClass = $routeClass ?: $this->_routeClass;
<ide> $this->connect('/:controller', ['action' => 'index'], compact('routeClass'));
<ide> $this->connect('/:controller/:action/*', [], compact('routeClass'));
<ide> }
<ide><path>tests/TestCase/Routing/RouteBuilderTest.php
<ide> public function testFallbacks() {
<ide> $routes = new RouteBuilder($this->collection, '/api', ['prefix' => 'api']);
<ide> $routes->fallbacks();
<ide>
<add> $all = $this->collection->routes();
<add> $this->assertEquals('/api/:controller', $all[0]->template);
<add> $this->assertEquals('/api/:controller/:action/*', $all[1]->template);
<add> $this->assertInstanceOf('Cake\Routing\Route\Route', $all[0]);
<add> }
<add>
<add>/**
<add> * Test connecting fallback routes with specific route class
<add> *
<add> * @return void
<add> */
<add> public function testFallbacksWithClass() {
<add> $routes = new RouteBuilder($this->collection, '/api', ['prefix' => 'api']);
<add> $routes->fallbacks('InflectedRoute');
<add>
<ide> $all = $this->collection->routes();
<ide> $this->assertEquals('/api/:controller', $all[0]->template);
<ide> $this->assertEquals('/api/:controller/:action/*', $all[1]->template); | 2 |
Text | Text | fix spelling mistakes in classic_to_zeitwerk_howto | 94a029ce98c2e74a6b2874cdb59bb3d07595f7e6 | <ide><path>guides/source/classic_to_zeitwerk_howto.md
<ide> config.autoloader = :classic # DELETE THIS LINE
<ide>
<ide> As noted, just delete the override, `zeitwerk` mode is the default.
<ide>
<del>On the other hand, if the application is loading old framework defaults you need to enable `zeitwerk` mode explictly:
<add>On the other hand, if the application is loading old framework defaults you need to enable `zeitwerk` mode explicitly:
<ide>
<ide> ```ruby
<ide> # config/application.rb
<ide> Hold on, I am eager loading the application.
<ide> All is good!
<ide> ```
<ide>
<del>There can be additional ouput depending on the application configuration, but the last "All is good!" is what you are looking for.
<add>There can be additional output depending on the application configuration, but the last "All is good!" is what you are looking for.
<ide>
<ide> If there's any file that does not define the expected constant, the task will tell you. It does so one file at a time, because if it moved on, the failure loading one file could cascade into other failures unrelated to the check we want to run and the error report would be confusing.
<ide>
<ide> Rails.autoloaders.each do |autoloader|
<ide> end
<ide> ```
<ide>
<del>With that in place, the check passes 🎉:
<add>With that in place, the check passes :
<ide>
<ide> ```
<ide> % bin/rails zeitwerk:check | 1 |
Ruby | Ruby | add suffix for migrations copied from engines | ed0b1f6eed6d894f9a0f32a226d29337782ada3c | <ide><path>activerecord/lib/active_record/migration.rb
<ide> def copy(destination, sources, options = {})
<ide> end
<ide>
<ide> migration.version = next_migration_number(last ? last.version + 1 : 0).to_i
<del> new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.rb")
<add> new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.#{name}.rb")
<ide> old_path, migration.filename = migration.filename, new_path
<ide> last = migration
<ide>
<ide> def remove_origin_comment(migration_source)
<ide>
<ide> # MigrationProxy is used to defer loading of the actual migration classes
<ide> # until they are needed
<del> class MigrationProxy < Struct.new(:name, :version, :filename)
<add> class MigrationProxy < Struct.new(:name, :version, :filename, :scope)
<ide>
<del> def initialize(name, version, filename)
<add> def initialize(name, version, filename, scope)
<ide> super
<ide> @migration = nil
<ide> end
<ide> def migrations(paths, subdirectories = true)
<ide> seen = Hash.new false
<ide>
<ide> migrations = files.map do |file|
<del> version, name = file.scan(/([0-9]+)_([_a-z0-9]*).rb/).first
<add> version, name, scope = file.scan(/([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?.rb/).first
<ide>
<ide> raise IllegalMigrationNameError.new(file) unless version
<ide> version = version.to_i
<ide> def migrations(paths, subdirectories = true)
<ide>
<ide> seen[version] = seen[name] = true
<ide>
<del> MigrationProxy.new(name, version, file)
<add> MigrationProxy.new(name, version, file, scope)
<ide> end
<ide>
<ide> migrations.sort_by(&:version)
<ide><path>activerecord/test/cases/migration_test.rb
<ide> def test_copying_migrations_without_timestamps
<ide> @existing_migrations = Dir[@migrations_path + "/*.rb"]
<ide>
<ide> copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"})
<del> assert File.exists?(@migrations_path + "/4_people_have_hobbies.rb")
<del> assert File.exists?(@migrations_path + "/5_people_have_descriptions.rb")
<del> assert_equal [@migrations_path + "/4_people_have_hobbies.rb", @migrations_path + "/5_people_have_descriptions.rb"], copied.map(&:filename)
<add> assert File.exists?(@migrations_path + "/4_people_have_hobbies.bukkits.rb")
<add> assert File.exists?(@migrations_path + "/5_people_have_descriptions.bukkits.rb")
<add> assert_equal [@migrations_path + "/4_people_have_hobbies.bukkits.rb", @migrations_path + "/5_people_have_descriptions.bukkits.rb"], copied.map(&:filename)
<ide>
<ide> expected = "# This migration comes from bukkits (originally 1)"
<del> assert_equal expected, IO.readlines(@migrations_path + "/4_people_have_hobbies.rb")[0].chomp
<add> assert_equal expected, IO.readlines(@migrations_path + "/4_people_have_hobbies.bukkits.rb")[0].chomp
<ide>
<ide> files_count = Dir[@migrations_path + "/*.rb"].length
<ide> copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"})
<ide> def test_copying_migrations_without_timestamps_from_2_sources
<ide> sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy"
<ide> sources[:omg] = MIGRATIONS_ROOT + "/to_copy2"
<ide> ActiveRecord::Migration.copy(@migrations_path, sources)
<del> assert File.exists?(@migrations_path + "/4_people_have_hobbies.rb")
<del> assert File.exists?(@migrations_path + "/5_people_have_descriptions.rb")
<del> assert File.exists?(@migrations_path + "/6_create_articles.rb")
<del> assert File.exists?(@migrations_path + "/7_create_comments.rb")
<add> assert File.exists?(@migrations_path + "/4_people_have_hobbies.bukkits.rb")
<add> assert File.exists?(@migrations_path + "/5_people_have_descriptions.bukkits.rb")
<add> assert File.exists?(@migrations_path + "/6_create_articles.omg.rb")
<add> assert File.exists?(@migrations_path + "/7_create_comments.omg.rb")
<ide>
<ide> files_count = Dir[@migrations_path + "/*.rb"].length
<ide> ActiveRecord::Migration.copy(@migrations_path, sources)
<ide> def test_copying_migrations_with_timestamps
<ide>
<ide> Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
<ide> copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
<del> assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb")
<del> assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
<del> expected = [@migrations_path + "/20100726101010_people_have_hobbies.rb",
<del> @migrations_path + "/20100726101011_people_have_descriptions.rb"]
<add> assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
<add> assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
<add> expected = [@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb",
<add> @migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb"]
<ide> assert_equal expected, copied.map(&:filename)
<ide>
<ide> files_count = Dir[@migrations_path + "/*.rb"].length
<ide> def test_copying_migrations_with_timestamps_from_2_sources
<ide>
<ide> Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
<ide> copied = ActiveRecord::Migration.copy(@migrations_path, sources)
<del> assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb")
<del> assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
<del> assert File.exists?(@migrations_path + "/20100726101012_create_articles.rb")
<del> assert File.exists?(@migrations_path + "/20100726101013_create_comments.rb")
<add> assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
<add> assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
<add> assert File.exists?(@migrations_path + "/20100726101012_create_articles.omg.rb")
<add> assert File.exists?(@migrations_path + "/20100726101013_create_comments.omg.rb")
<ide> assert_equal 4, copied.length
<ide>
<ide> files_count = Dir[@migrations_path + "/*.rb"].length
<ide> def test_copying_migrations_with_timestamps_to_destination_with_timestamps_in_fu
<ide>
<ide> Time.travel_to(Time.utc(2010, 2, 20, 10, 10, 10)) do
<ide> ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
<del> assert File.exists?(@migrations_path + "/20100301010102_people_have_hobbies.rb")
<del> assert File.exists?(@migrations_path + "/20100301010103_people_have_descriptions.rb")
<add> assert File.exists?(@migrations_path + "/20100301010102_people_have_hobbies.bukkits.rb")
<add> assert File.exists?(@migrations_path + "/20100301010103_people_have_descriptions.bukkits.rb")
<ide>
<ide> files_count = Dir[@migrations_path + "/*.rb"].length
<ide> copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
<ide> def test_skip_ignores_origin_comment
<ide> copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip)
<ide>
<ide> # remove origin comment
<del> migration = @migrations_path + "/4_people_have_hobbies.rb"
<add> migration = @migrations_path + "/4_people_have_hobbies.bukkits.rb"
<ide> migration_source = File.read(migration).lines.to_a[1..-1].join
<ide> File.open(migration, "w") { |f| f.write migration_source }
<ide>
<ide> def test_copying_migrations_to_non_existing_directory
<ide>
<ide> Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
<ide> copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
<del> assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb")
<del> assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
<add> assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
<add> assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
<ide> assert_equal 2, copied.length
<ide> end
<ide> ensure
<ide> def test_copying_migrations_to_empty_directory
<ide>
<ide> Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
<ide> copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
<del> assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb")
<del> assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
<add> assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
<add> assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
<ide> assert_equal 2, copied.length
<ide> end
<ide> ensure
<ide><path>railties/test/railties/shared_tests.rb
<ide> class CreateYaffles < ActiveRecord::Migration
<ide> Dir.chdir(app_path) do
<ide> output = `bundle exec rake bukkits:install:migrations`
<ide>
<del> assert File.exists?("#{app_path}/db/migrate/2_create_users.rb")
<del> assert File.exists?("#{app_path}/db/migrate/3_add_last_name_to_users.rb")
<del> assert_match(/Copied migration 2_create_users.rb from bukkits/, output)
<del> assert_match(/Copied migration 3_add_last_name_to_users.rb from bukkits/, output)
<add> assert File.exists?("#{app_path}/db/migrate/2_create_users.bukkits.rb")
<add> assert File.exists?("#{app_path}/db/migrate/3_add_last_name_to_users.bukkits.rb")
<add> assert_match(/Copied migration 2_create_users.bukkits.rb from bukkits/, output)
<add> assert_match(/Copied migration 3_add_last_name_to_users.bukkits.rb from bukkits/, output)
<ide> assert_match(/NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/, output)
<ide> assert_equal 3, Dir["#{app_path}/db/migrate/*.rb"].length
<ide>
<ide> output = `bundle exec rake railties:install:migrations`.split("\n")
<ide>
<del> assert File.exists?("#{app_path}/db/migrate/4_create_yaffles.rb")
<add> assert File.exists?("#{app_path}/db/migrate/4_create_yaffles.acts_as_yaffle.rb")
<ide> assert_no_match(/2_create_users/, output.join("\n"))
<ide>
<del> yaffle_migration_order = output.index(output.detect{|o| /Copied migration 4_create_yaffles.rb from acts_as_yaffle/ =~ o })
<add> yaffle_migration_order = output.index(output.detect{|o| /Copied migration 4_create_yaffles.acts_as_yaffle.rb from acts_as_yaffle/ =~ o })
<ide> bukkits_migration_order = output.index(output.detect{|o| /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/ =~ o })
<ide> assert_not_nil yaffle_migration_order, "Expected migration to be copied"
<ide> assert_not_nil bukkits_migration_order, "Expected migration to be skipped" | 3 |
Text | Text | add closing section tag | 64286b4f13fa6e0de3d36c53f399eee6ff6b7120 | <ide><path>curriculum/challenges/arabic/01-responsive-web-design/applied-accessibility/add-an-accessible-date-picker.arabic.md
<ide> localeTitle: إضافة منتقي تاريخ يسهل الوصول إليه
<ide> <label for="input1">أدخل تاريخًا:</label>
<ide> <input type="date" id="input1" name="input1">
<ide> ```
<add></section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions"> يقوم كامبر كات بإعداد بطولة مورتال كومبات ويريد أن يطلب من منافسيه معرفة التاريخ الأفضل. إضافة علامة <code>input</code> تحتوي على سمة <code>type</code> من "date" ، وسمة <code>id</code> من "pickdate" ، وسمة <code>name</code> من "date". </section> | 1 |
Text | Text | improve async_hooks snippets | f39a12113a96d8bbc08aac55dec25437a5958dde | <ide><path>doc/api/async_hooks.md
<ide> async_hooks.createHook({
<ide> init(asyncId, type, triggerAsyncId) {
<ide> const eid = async_hooks.executionAsyncId();
<ide> fs.writeSync(
<del> 1, `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
<add> process.stdout.fd,
<add> `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
<ide> }
<ide> }).enable();
<ide>
<ide> async_hooks.createHook({
<ide> const eid = async_hooks.executionAsyncId();
<ide> const indentStr = ' '.repeat(indent);
<ide> fs.writeSync(
<del> 1,
<add> process.stdout.fd,
<ide> `${indentStr}${type}(${asyncId}):` +
<ide> ` trigger: ${triggerAsyncId} execution: ${eid}\n`);
<ide> }, | 1 |
Javascript | Javascript | attach listontimeout function to timerwrap | eb34278dccc85a572b307253983721929b3fb1a8 | <ide><path>lib/timers.js
<ide> function TimersList(msecs, unrefed) {
<ide> if (unrefed === true)
<ide> timer.unref();
<ide> timer.start(msecs);
<del>
<del> timer[kOnTimeout] = listOnTimeout;
<ide> }
<ide>
<del>function listOnTimeout() {
<add>// adds listOnTimeout to the C++ object prototype, as
<add>// V8 would not inline it otherwise.
<add>TimerWrap.prototype[kOnTimeout] = function listOnTimeout() {
<ide> var list = this._list;
<ide> var msecs = list.msecs;
<ide>
<ide> function listOnTimeout() {
<ide> return;
<ide>
<ide> this.close();
<del>}
<add>};
<ide>
<ide>
<ide> // An optimization so that the try/finally only de-optimizes (since at least v8 | 1 |
PHP | PHP | add config orfail() wrapper | 0209b453dacd59c0584e839f4a352bf0cc13cd0d | <ide><path>src/Core/Configure.php
<ide> public static function version(): string
<ide> * @param string $cacheConfig The cache configuration to save into. Defaults to 'default'
<ide> * @param array|null $data Either an array of data to store, or leave empty to store all values.
<ide> * @return bool Success
<add> * @throws \RuntimeException
<ide> */
<ide> public static function store(string $name, string $cacheConfig = 'default', ?array $data = null): bool
<ide> {
<ide> public static function store(string $name, string $cacheConfig = 'default', ?arr
<ide> * @param string $name Name of the stored config file to load.
<ide> * @param string $cacheConfig Name of the Cache configuration to read from.
<ide> * @return bool Success.
<add> * @throws \RuntimeException
<ide> */
<ide> public static function restore(string $name, string $cacheConfig = 'default'): bool
<ide> {
<ide><path>src/Core/InstanceConfigTrait.php
<ide>
<ide> use Cake\Core\Exception\Exception;
<ide> use Cake\Utility\Hash;
<add>use InvalidArgumentException;
<ide>
<ide> /**
<ide> * A trait for reading and writing instance config
<ide> public function setConfig($key, $value = null, $merge = true)
<ide> * ```
<ide> *
<ide> * @param string|null $key The key to get or null for the whole config.
<del> * @param mixed $default The return value when the key does not exist.
<del> * @return mixed Configuration data at the named key or null if the key does not exist.
<add> * @param mixed|null $default The return value when the key does not exist.
<add> * @return mixed|null Configuration data at the named key or null if the key does not exist.
<ide> */
<ide> public function getConfig(?string $key = null, $default = null)
<ide> {
<ide> public function getConfig(?string $key = null, $default = null)
<ide> return $return ?? $default;
<ide> }
<ide>
<add> /**
<add> * Returns the config for this specific key.
<add> *
<add> * The config value for this key must exist, it can never be null.
<add> *
<add> * @param string $key The key to get.
<add> * @return mixed Configuration data at the named key
<add> * @throws \InvalidArgumentException
<add> */
<add> public function getConfigOrFail(string $key)
<add> {
<add> $config = $this->getConfig($key);
<add> if ($config === null) {
<add> throw new InvalidArgumentException(sprintf('Expected configuration `%s` not found.', $key));
<add> }
<add>
<add> return $config;
<add> }
<add>
<ide> /**
<ide> * Merge provided config with existing config. Unlike `config()` which does
<ide> * a recursive merge for nested keys, this method does a simple merge.
<ide><path>src/Core/StaticConfigTrait.php
<ide> public static function setConfig($key, $config = null): void
<ide> * Reads existing configuration.
<ide> *
<ide> * @param string $key The name of the configuration.
<del> * @return mixed Configuration data at the named key or null if the key does not exist.
<add> * @return mixed|null Configuration data at the named key or null if the key does not exist.
<ide> */
<ide> public static function getConfig(string $key)
<ide> {
<ide> return static::$_config[$key] ?? null;
<ide> }
<ide>
<add> /**
<add> * Reads existing configuration for a specific key.
<add> *
<add> * The config value for this key must exist, it can never be null.
<add> *
<add> * @param string $key The name of the configuration.
<add> * @return mixed|null Configuration data at the named key.
<add> * @throws \InvalidArgumentException If value does not exist.
<add> */
<add> public static function getConfigOrFail(string $key)
<add> {
<add> if (!isset(static::$_config[$key])) {
<add> throw new InvalidArgumentException(sprintf('Expected configuration `%s` not found.', $key));
<add> }
<add>
<add> return static::$_config[$key];
<add> }
<add>
<ide> /**
<ide> * Drops a constructed adapter.
<ide> *
<ide><path>tests/TestCase/Core/InstanceConfigTraitTest.php
<ide> namespace Cake\Test\TestCase\Core;
<ide>
<ide> use Cake\TestSuite\TestCase;
<add>use InvalidArgumentException;
<ide> use TestApp\Config\ReadOnlyTestInstanceConfig;
<ide> use TestApp\Config\TestInstanceConfig;
<ide>
<ide> public function testSetArray()
<ide> );
<ide> }
<ide>
<add> /**
<add> * @return void
<add> */
<add> public function testGetConfigOrFail()
<add> {
<add> $this->object->setConfig(['foo' => 'bar']);
<add> $this->assertSame(
<add> 'bar',
<add> $this->object->getConfigOrFail('foo'),
<add> 'should return the same value just set'
<add> );
<add> }
<add>
<add> /**
<add> * @return void
<add> */
<add> public function testGetConfigOrFailException()
<add> {
<add> $this->expectException(InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Expected configuration `foo` not found.');
<add>
<add> $this->object->getConfigOrFail('foo');
<add> }
<add>
<ide> /**
<ide> * test shallow merge
<ide> *
<ide><path>tests/TestCase/Core/StaticConfigTraitTest.php
<ide>
<ide> use Cake\Core\StaticConfigTrait;
<ide> use Cake\TestSuite\TestCase;
<add>use InvalidArgumentException;
<ide> use TestApp\Config\TestEmailStaticConfig;
<ide> use TestApp\Config\TestLogStaticConfig;
<ide> use TypeError;
<ide> */
<ide> class StaticConfigTraitTest extends TestCase
<ide> {
<add> /**
<add> * @var object
<add> */
<add> protected $subject;
<add>
<ide> /**
<ide> * setup method
<ide> *
<ide> public function testParseBadType()
<ide> $className::parseDsn(['url' => 'http://:80']);
<ide> }
<ide>
<add> /**
<add> * @return void
<add> */
<add> public function testGetConfigOrFail()
<add> {
<add> $className = get_class($this->subject);
<add> $className::setConfig('foo', 'bar');
<add>
<add> $result = $className::getConfigOrFail('foo');
<add> $this->assertSame('bar', $result);
<add> }
<add>
<add> /**
<add> * @return void
<add> */
<add> public function testGetConfigOrFailException()
<add> {
<add> $this->expectException(InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Expected configuration `foo` not found.');
<add>
<add> $className = get_class($this->subject);
<add> $result = $className::getConfigOrFail('foo');
<add> $this->assertSame('bar', $result);
<add> }
<add>
<ide> /**
<ide> * Tests parsing querystring values
<ide> *
<ide><path>tests/TestCase/View/StringTemplateTest.php
<ide>
<ide> class StringTemplateTest extends TestCase
<ide> {
<add> /**
<add> * @var \Cake\View\StringTemplate
<add> */
<add> protected $template;
<add>
<ide> /**
<ide> * setUp
<ide> *
<ide><path>tests/test_app/TestApp/Config/ReadOnlyTestInstanceConfig.php
<ide> class ReadOnlyTestInstanceConfig
<ide> * Example of how to prevent modifying config at run time
<ide> *
<ide> * @throws \Exception
<del> * @param mixed $key
<add> * @param string|array $key
<ide> * @param mixed $value
<ide> * @return void
<ide> */
<del> protected function _configWrite($key, $value = null)
<add> protected function _configWrite($key, $value): void
<ide> {
<ide> throw new Exception('This Instance is readonly');
<ide> } | 7 |
Javascript | Javascript | make terminate() resolve for unref’ed workers | 2833a0d8b7c3f0f5e80059d7a428328c96cbee54 | <ide><path>lib/internal/worker.js
<ide> class Worker extends EventEmitter {
<ide> terminate(callback) {
<ide> debug(`[${threadId}] terminates Worker with ID ${this.threadId}`);
<ide>
<add> this.ref();
<add>
<ide> if (typeof callback === 'function') {
<ide> process.emitWarning(
<ide> 'Passing a callback to worker.terminate() is deprecated. ' +
<ide><path>test/parallel/test-worker-terminate-unrefed.js
<add>'use strict';
<add>const common = require('../common');
<add>const { once } = require('events');
<add>const { Worker } = require('worker_threads');
<add>
<add>// Test that calling worker.terminate() on an unref()’ed Worker instance
<add>// still resolves the returned Promise.
<add>
<add>async function test() {
<add> const worker = new Worker('setTimeout(() => {}, 1000000);', { eval: true });
<add> await once(worker, 'online');
<add> worker.unref();
<add> await worker.terminate();
<add>}
<add>
<add>test().then(common.mustCall()); | 2 |
PHP | PHP | fix merge conflicts | cc84229a96870027793e11e7e8cf2182fc9fbba1 | <ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php
<ide> use Illuminate\Queue\Console\ForgetFailedCommand as ForgetFailedQueueCommand;
<ide> use Illuminate\Queue\Console\ListenCommand as QueueListenCommand;
<ide> use Illuminate\Queue\Console\ListFailedCommand as ListFailedQueueCommand;
<del><<<<<<< HEAD
<ide> use Illuminate\Queue\Console\PruneBatchesCommand as QueuePruneBatchesCommand;
<del>=======
<del>use Illuminate\Queue\Console\PruneBatchesCommand as PruneBatchesQueueCommand;
<del>use Illuminate\Queue\Console\PruneFailedJobsCommand;
<del>>>>>>>> 8.x
<add>use Illuminate\Queue\Console\PruneFailedJobsCommand as QueuePruneFailedJobsCommand;
<ide> use Illuminate\Queue\Console\RestartCommand as QueueRestartCommand;
<ide> use Illuminate\Queue\Console\RetryBatchCommand as QueueRetryBatchCommand;
<ide> use Illuminate\Queue\Console\RetryCommand as QueueRetryCommand;
<ide> class ArtisanServiceProvider extends ServiceProvider implements DeferrableProvid
<ide> 'ConfigCache' => ConfigCacheCommand::class,
<ide> 'ConfigClear' => ConfigClearCommand::class,
<ide> 'Db' => DbCommand::class,
<del><<<<<<< HEAD
<ide> 'DbWipe' => WipeCommand::class,
<ide> 'Down' => DownCommand::class,
<ide> 'Environment' => EnvironmentCommand::class,
<ide> class ArtisanServiceProvider extends ServiceProvider implements DeferrableProvid
<ide> 'QueueForget' => ForgetFailedQueueCommand::class,
<ide> 'QueueListen' => QueueListenCommand::class,
<ide> 'QueuePruneBatches' => QueuePruneBatchesCommand::class,
<add> 'QueuePruneFailedJobs' => QueuePruneFailedJobsCommand::class,
<ide> 'QueueRestart' => QueueRestartCommand::class,
<ide> 'QueueRetry' => QueueRetryCommand::class,
<ide> 'QueueRetryBatch' => QueueRetryBatchCommand::class,
<ide> class ArtisanServiceProvider extends ServiceProvider implements DeferrableProvid
<ide> 'RouteList' => RouteListCommand::class,
<ide> 'SchemaDump' => DumpCommand::class,
<ide> 'Seed' => SeedCommand::class,
<del>=======
<del> 'DbWipe' => 'command.db.wipe',
<del> 'Down' => 'command.down',
<del> 'Environment' => 'command.environment',
<del> 'EventCache' => 'command.event.cache',
<del> 'EventClear' => 'command.event.clear',
<del> 'EventList' => 'command.event.list',
<del> 'KeyGenerate' => 'command.key.generate',
<del> 'Optimize' => 'command.optimize',
<del> 'OptimizeClear' => 'command.optimize.clear',
<del> 'PackageDiscover' => 'command.package.discover',
<del> 'QueueClear' => 'command.queue.clear',
<del> 'QueueFailed' => 'command.queue.failed',
<del> 'QueueFlush' => 'command.queue.flush',
<del> 'QueueForget' => 'command.queue.forget',
<del> 'QueueListen' => 'command.queue.listen',
<del> 'QueuePruneBatches' => 'command.queue.prune-batches',
<del> 'QueuePruneFailedJobs' => 'command.queue.prune-failed-jobs',
<del> 'QueueRestart' => 'command.queue.restart',
<del> 'QueueRetry' => 'command.queue.retry',
<del> 'QueueRetryBatch' => 'command.queue.retry-batch',
<del> 'QueueWork' => 'command.queue.work',
<del> 'RouteCache' => 'command.route.cache',
<del> 'RouteClear' => 'command.route.clear',
<del> 'RouteList' => 'command.route.list',
<del> 'SchemaDump' => 'command.schema.dump',
<del> 'Seed' => 'command.seed',
<del>>>>>>>> 8.x
<ide> 'ScheduleFinish' => ScheduleFinishCommand::class,
<ide> 'ScheduleList' => ScheduleListCommand::class,
<ide> 'ScheduleRun' => ScheduleRunCommand::class,
<ide> protected function registerQueuePruneBatchesCommand()
<ide> protected function registerQueuePruneFailedJobsCommand()
<ide> {
<ide> $this->app->singleton('command.queue.prune-failed-jobs', function () {
<del> return new PruneFailedJobsCommand;
<add> return new QueuePruneFailedJobsCommand;
<ide> });
<ide> }
<ide> | 1 |
PHP | PHP | fix types in docblocks | 7de44d754986a44ab817f2af6ecea0df42ad570e | <ide><path>src/Http/MiddlewareQueue.php
<ide> use SeekableIterator;
<ide>
<ide> /**
<del> * Provides methods for creating and manipulating a "queue" of middleware callables.
<add> * Provides methods for creating and manipulating a "queue" of middlewares.
<ide> * This queue is used to process a request and generate response via \Cake\Http\Runner.
<ide> */
<ide> class MiddlewareQueue implements Countable, SeekableIterator
<ide> public function __construct(array $middleware = [])
<ide> /**
<ide> * Resolve middleware name to a PSR 15 compliant middleware instance.
<ide> *
<del> * @param string|callable|\Psr\Http\Server\MiddlewareInterface $middleware The middleware to resolve.
<add> * @param string|\Closure|\Psr\Http\Server\MiddlewareInterface $middleware The middleware to resolve.
<ide> * @return \Psr\Http\Server\MiddlewareInterface
<ide> * @throws \RuntimeException If Middleware not found.
<ide> */
<ide> protected function resolve($middleware): MiddlewareInterface
<ide> /**
<ide> * Append a middleware to the end of the queue.
<ide> *
<del> * @param callable|string|array|\Psr\Http\Server\MiddlewareInterface $middleware The middleware(s) to append.
<add> * @param string|array|\Closure|\Psr\Http\Server\MiddlewareInterface $middleware The middleware(s) to append.
<ide> * @return $this
<ide> */
<ide> public function add($middleware)
<ide> public function add($middleware)
<ide> /**
<ide> * Alias for MiddlewareQueue::add().
<ide> *
<del> * @param callable|string|array|\Psr\Http\Server\MiddlewareInterface $middleware The middleware(s) to append.
<add> * @param string|array|\Closure|\Psr\Http\Server\MiddlewareInterface $middleware The middleware(s) to append.
<ide> * @return $this
<ide> * @see MiddlewareQueue::add()
<ide> */
<ide> public function push($middleware)
<ide> /**
<ide> * Prepend a middleware to the start of the queue.
<ide> *
<del> * @param callable|string|array|\Psr\Http\Server\MiddlewareInterface $middleware The middleware(s) to prepend.
<add> * @param string|array|\Closure|\Psr\Http\Server\MiddlewareInterface $middleware The middleware(s) to prepend.
<ide> * @return $this
<ide> */
<ide> public function prepend($middleware)
<ide> public function prepend($middleware)
<ide> }
<ide>
<ide> /**
<del> * Insert a middleware callable at a specific index.
<add> * Insert a middleware at a specific index.
<ide> *
<del> * If the index already exists, the new callable will be inserted,
<add> * If the index already exists, the new middleware will be inserted,
<ide> * and the existing element will be shifted one index greater.
<ide> *
<ide> * @param int $index The index to insert at.
<del> * @param callable|string|\Psr\Http\Server\MiddlewareInterface $middleware The middleware to insert.
<add> * @param string|\Closure|\Psr\Http\Server\MiddlewareInterface $middleware The middleware to insert.
<ide> * @return $this
<ide> */
<ide> public function insertAt(int $index, $middleware)
<ide> public function insertAt(int $index, $middleware)
<ide> }
<ide>
<ide> /**
<del> * Insert a middleware object before the first matching class.
<add> * Insert a middleware before the first matching class.
<ide> *
<ide> * Finds the index of the first middleware that matches the provided class,
<del> * and inserts the supplied callable before it.
<add> * and inserts the supplied middleware before it.
<ide> *
<ide> * @param string $class The classname to insert the middleware before.
<del> * @param callable|string|\Psr\Http\Server\MiddlewareInterface $middleware The middleware to insert.
<add> * @param string|\Closure|\Psr\Http\Server\MiddlewareInterface $middleware The middleware to insert.
<ide> * @return $this
<ide> * @throws \LogicException If middleware to insert before is not found.
<ide> */
<ide> public function insertBefore(string $class, $middleware)
<ide> * Insert a middleware object after the first matching class.
<ide> *
<ide> * Finds the index of the first middleware that matches the provided class,
<del> * and inserts the supplied callable after it. If the class is not found,
<add> * and inserts the supplied middleware after it. If the class is not found,
<ide> * this method will behave like add().
<ide> *
<ide> * @param string $class The classname to insert the middleware before.
<del> * @param callable|string|\Psr\Http\Server\MiddlewareInterface $middleware The middleware to insert.
<add> * @param string|\Closure|\Psr\Http\Server\MiddlewareInterface $middleware The middleware to insert.
<ide> * @return $this
<ide> */
<ide> public function insertAfter(string $class, $middleware) | 1 |
Java | Java | support utf-16/utf-32 in jackson message converter | b61643b71a04fee5bb74d6bf1b35aae4125afb9e | <ide><path>spring-web/src/main/java/org/springframework/http/converter/json/AbstractJackson2HttpMessageConverter.java
<ide> private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) th
<ide> ObjectMapper objectMapper = selectObjectMapper(javaType.getRawClass(), contentType);
<ide> Assert.state(objectMapper != null, "No ObjectMapper for " + javaType);
<ide>
<del> boolean isUnicode = ENCODINGS.containsKey(charset.name());
<add> boolean isUnicode = ENCODINGS.containsKey(charset.name()) ||
<add> "UTF-16".equals(charset.name()) ||
<add> "UTF-32".equals(charset.name());
<ide> try {
<ide> if (inputMessage instanceof MappingJacksonInputMessage) {
<ide> Class<?> deserializationView = ((MappingJacksonInputMessage) inputMessage).getDeserializationView(); | 1 |
Java | Java | replace jetty 9 only constant with explicit value | fbf4724d781a30347b3830567417eef0dd803c3b | <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/jetty/Jetty10RequestUpgradeStrategy.java
<ide>
<ide> import org.aopalliance.intercept.MethodInterceptor;
<ide> import org.aopalliance.intercept.MethodInvocation;
<del>import org.eclipse.jetty.websocket.server.HandshakeRFC6455;
<ide>
<ide> import org.springframework.aop.framework.ProxyFactory;
<ide> import org.springframework.aop.target.EmptyTargetSource;
<ide> */
<ide> public class Jetty10RequestUpgradeStrategy implements RequestUpgradeStrategy {
<ide>
<del> private static final String[] SUPPORTED_VERSIONS = new String[] { String.valueOf(HandshakeRFC6455.VERSION) };
<add> private static final String[] SUPPORTED_VERSIONS = new String[] { String.valueOf(13) };
<ide>
<ide> private static final Class<?> webSocketCreatorClass;
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/jetty/JettyRequestUpgradeStrategy.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> import org.eclipse.jetty.websocket.api.WebSocketPolicy;
<ide> import org.eclipse.jetty.websocket.api.extensions.ExtensionConfig;
<del>import org.eclipse.jetty.websocket.server.HandshakeRFC6455;
<ide> import org.eclipse.jetty.websocket.server.WebSocketServerFactory;
<ide>
<ide> import org.springframework.context.Lifecycle;
<ide> public boolean isRunning() {
<ide>
<ide> @Override
<ide> public String[] getSupportedVersions() {
<del> return new String[] { String.valueOf(HandshakeRFC6455.VERSION) };
<add> return new String[] { String.valueOf(13) };
<ide> }
<ide>
<ide> @Override | 2 |
Python | Python | add inputs vector to calculate metric method | 09a272b02af6fa04f05b3cd7f1f7b32cdf2ab5e4 | <ide><path>src/transformers/trainer.py
<ide> def evaluation_loop(
<ide> losses_host = None
<ide> preds_host = None
<ide> labels_host = None
<add> inputs_host = None
<add>
<ide> # losses/preds/labels on CPU (final containers)
<ide> all_losses = None
<ide> all_preds = None
<ide> all_labels = None
<add> all_inputs = None
<ide> # Will be useful when we have an iterable dataset so don't know its length.
<ide>
<ide> observed_num_examples = 0
<ide> def evaluation_loop(
<ide>
<ide> # Prediction step
<ide> loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys)
<add> inputs_decode = inputs["input_ids"] if args.include_inputs_for_metrics else None
<ide>
<ide> if is_torch_tpu_available():
<ide> xm.mark_step()
<ide> def evaluation_loop(
<ide> labels = self._pad_across_processes(labels)
<ide> labels = self._nested_gather(labels)
<ide> labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100)
<add> if inputs_decode is not None:
<add> inputs_decode = self._pad_across_processes(inputs_decode)
<add> inputs_decode = self._nested_gather(inputs_decode)
<add> inputs_host = (
<add> inputs_decode
<add> if inputs_host is None
<add> else nested_concat(inputs_host, inputs_decode, padding_index=-100)
<add> )
<ide> if logits is not None:
<ide> logits = self._pad_across_processes(logits)
<ide> logits = self._nested_gather(logits)
<ide> def evaluation_loop(
<ide> if preds_host is not None:
<ide> logits = nested_numpify(preds_host)
<ide> all_preds = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100)
<add> if inputs_host is not None:
<add> inputs_decode = nested_numpify(inputs_host)
<add> all_inputs = (
<add> inputs_decode
<add> if all_inputs is None
<add> else nested_concat(all_inputs, inputs_decode, padding_index=-100)
<add> )
<ide> if labels_host is not None:
<ide> labels = nested_numpify(labels_host)
<ide> all_labels = (
<ide> labels if all_labels is None else nested_concat(all_labels, labels, padding_index=-100)
<ide> )
<ide>
<ide> # Set back to None to begin a new accumulation
<del> losses_host, preds_host, labels_host = None, None, None
<add> losses_host, preds_host, inputs_host, labels_host = None, None, None, None
<ide>
<ide> if args.past_index and hasattr(self, "_past"):
<ide> # Clean the state at the end of the evaluation loop
<ide> def evaluation_loop(
<ide> if preds_host is not None:
<ide> logits = nested_numpify(preds_host)
<ide> all_preds = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100)
<add> if inputs_host is not None:
<add> inputs_decode = nested_numpify(inputs_host)
<add> all_inputs = (
<add> inputs_decode if all_inputs is None else nested_concat(all_inputs, inputs_decode, padding_index=-100)
<add> )
<ide> if labels_host is not None:
<ide> labels = nested_numpify(labels_host)
<ide> all_labels = labels if all_labels is None else nested_concat(all_labels, labels, padding_index=-100)
<ide> def evaluation_loop(
<ide> all_preds = nested_truncate(all_preds, num_samples)
<ide> if all_labels is not None:
<ide> all_labels = nested_truncate(all_labels, num_samples)
<add> if all_inputs is not None:
<add> all_inputs = nested_truncate(all_inputs, num_samples)
<ide>
<ide> # Metrics!
<ide> if self.compute_metrics is not None and all_preds is not None and all_labels is not None:
<del> metrics = self.compute_metrics(EvalPrediction(predictions=all_preds, label_ids=all_labels))
<add> if args.include_inputs_for_metrics:
<add> metrics = self.compute_metrics(
<add> EvalPrediction(predictions=all_preds, label_ids=all_labels, inputs=all_inputs)
<add> )
<add> else:
<add> metrics = self.compute_metrics(EvalPrediction(predictions=all_preds, label_ids=all_labels))
<ide> else:
<ide> metrics = {}
<ide>
<ide> def prediction_loop(
<ide>
<ide> # if eval is called w/o train init deepspeed here
<ide> if args.deepspeed and not self.deepspeed:
<del>
<ide> # XXX: eval doesn't have `resume_from_checkpoint` arg but we should be able to do eval
<ide> # from the checkpoint eventually
<ide> deepspeed_engine, _, _ = deepspeed_init(self, num_training_steps=0, resume_from_checkpoint=None)
<ide> def prediction_loop(
<ide> losses_host: torch.Tensor = None
<ide> preds_host: Union[torch.Tensor, List[torch.Tensor]] = None
<ide> labels_host: Union[torch.Tensor, List[torch.Tensor]] = None
<add> inputs_host: Union[torch.Tensor, List[torch.Tensor]] = None
<ide>
<ide> world_size = max(1, args.world_size)
<ide>
<ide> def prediction_loop(
<ide> make_multiple_of = dataloader.sampler.batch_size
<ide> preds_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=make_multiple_of)
<ide> labels_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=make_multiple_of)
<add> inputs_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=make_multiple_of)
<ide>
<ide> model.eval()
<ide>
<ide> def prediction_loop(
<ide>
<ide> for step, inputs in enumerate(dataloader):
<ide> loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys)
<add> inputs_decode = inputs["input_ids"] if args.include_inputs_for_metrics else None
<add>
<ide> if loss is not None:
<ide> losses = loss.repeat(batch_size)
<ide> losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0)
<ide> if logits is not None:
<ide> preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100)
<ide> if labels is not None:
<ide> labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100)
<add> if inputs_decode is not None:
<add> inputs_host = (
<add> inputs_decode
<add> if inputs_host is None
<add> else nested_concat(inputs_host, inputs_decode, padding_index=-100)
<add> )
<ide> self.control = self.callback_handler.on_prediction_step(args, self.state, self.control)
<ide>
<ide> # Gather all tensors and put them back on the CPU if we have done enough accumulation steps.
<ide> def prediction_loop(
<ide> if not prediction_loss_only:
<ide> preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds"))
<ide> labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids"))
<add> inputs_gatherer.add_arrays(self._gather_and_numpify(inputs_host, "eval_inputs_ids"))
<ide>
<ide> # Set back to None to begin a new accumulation
<del> losses_host, preds_host, labels_host = None, None, None
<add> losses_host, preds_host, labels_host, inputs_host = None, None, None, None
<ide>
<ide> if args.past_index and hasattr(self, "_past"):
<ide> # Clean the state at the end of the evaluation loop
<ide> def prediction_loop(
<ide> if not prediction_loss_only:
<ide> preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds"))
<ide> labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids"))
<add> inputs_gatherer.add_arrays(self._gather_and_numpify(inputs_host, "eval_inputs_ids"))
<ide>
<ide> eval_loss = eval_losses_gatherer.finalize()
<ide> preds = preds_gatherer.finalize() if not prediction_loss_only else None
<ide> label_ids = labels_gatherer.finalize() if not prediction_loss_only else None
<add> inputs_ids = inputs_gatherer.finalize() if not prediction_loss_only else None
<ide>
<ide> if self.compute_metrics is not None and preds is not None and label_ids is not None:
<del> metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids))
<add> if args.include_inputs_for_metrics:
<add> metrics = self.compute_metrics(
<add> EvalPrediction(predictions=preds, label_ids=label_ids, inputs=inputs_ids)
<add> )
<add> else:
<add> metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids))
<ide> else:
<ide> metrics = {}
<ide>
<ide><path>src/transformers/trainer_utils.py
<ide> def set_seed(seed: int):
<ide> tf.random.set_seed(seed)
<ide>
<ide>
<del>class EvalPrediction(NamedTuple):
<add>class EvalPrediction:
<ide> """
<ide> Evaluation output (always contains labels), to be used to compute metrics.
<ide>
<ide> Parameters:
<ide> predictions (`np.ndarray`): Predictions of the model.
<ide> label_ids (`np.ndarray`): Targets to be matched.
<add> inputs (`np.ndarray`, *optional*)
<ide> """
<ide>
<del> predictions: Union[np.ndarray, Tuple[np.ndarray]]
<del> label_ids: Union[np.ndarray, Tuple[np.ndarray]]
<add> def __init__(
<add> self,
<add> predictions: Union[np.ndarray, Tuple[np.ndarray]],
<add> label_ids: Union[np.ndarray, Tuple[np.ndarray]],
<add> inputs: Optional[Union[np.ndarray, Tuple[np.ndarray]]] = None,
<add> ):
<add> self.predictions = predictions
<add> self.label_ids = label_ids
<add> self.inputs = inputs
<add>
<add> def __iter__(self):
<add> if self.inputs is not None:
<add> return iter((self.predictions, self.label_ids, self.inputs))
<add> else:
<add> return iter((self.predictions, self.label_ids))
<add>
<add> def __getitem__(self, idx):
<add> if idx < 0 or idx > 2:
<add> raise IndexError("tuple index out of range")
<add> if idx == 2 and self.inputs is None:
<add> raise IndexError("tuple index out of range")
<add> if idx == 0:
<add> return self.predictions
<add> elif idx == 1:
<add> return self.label_ids
<add> elif idx == 2:
<add> return self.inputs
<ide>
<ide>
<ide> class EvalLoopOutput(NamedTuple):
<ide><path>src/transformers/training_args.py
<ide> class TrainingArguments:
<ide> `huggingface-cli login`.
<ide> gradient_checkpointing (`bool`, *optional*, defaults to `False`):
<ide> If True, use gradient checkpointing to save memory at the expense of slower backward pass.
<add> include_inputs_for_metrics (`bool`, *optional*, defaults to `False`):
<add> Whether or not the inputs will be passed to the `compute_metrics` function. This is intended for metrics
<add> that need inputs, predictions and references for scoring calculation in Metric class.
<ide> """
<ide>
<ide> output_dir: str = field(
<ide> class TrainingArguments:
<ide> "help": "If True, use gradient checkpointing to save memory at the expense of slower backward pass."
<ide> },
<ide> )
<add> include_inputs_for_metrics: bool = field(
<add> default=False, metadata={"help": "Whether or not the inputs will be passed to the `compute_metrics` function."}
<add> )
<ide> # Deprecated arguments
<ide> fp16_backend: str = field(
<ide> default="auto", | 3 |
Ruby | Ruby | use safe_constantize where possible | e8987c30d0dc3ae5903a6d3a6e293641759b6fc4 | <ide><path>actionpack/lib/action_controller/metal/params_wrapper.rb
<ide> def inherited(klass)
<ide> # try to find Foo::Bar::User, Foo::User and finally User.
<ide> def _default_wrap_model #:nodoc:
<ide> return nil if self.anonymous?
<del>
<ide> model_name = self.name.sub(/Controller$/, '').singularize
<ide>
<ide> begin
<del> model_klass = model_name.constantize
<del> rescue NameError, ArgumentError => e
<del> if e.message =~ /is not missing constant|uninitialized constant #{model_name}/
<add> if model_klass = model_name.safe_constantize
<add> model_klass
<add> else
<ide> namespaces = model_name.split("::")
<ide> namespaces.delete_at(-2)
<ide> break if namespaces.last == model_name
<ide> model_name = namespaces.join("::")
<del> else
<del> raise
<ide> end
<ide> end until model_klass
<ide>
<ide><path>actionpack/lib/action_view/test_case.rb
<ide> def tests(helper_class)
<ide> end
<ide>
<ide> def determine_default_helper_class(name)
<del> mod = name.sub(/Test$/, '').constantize
<add> mod = name.sub(/Test$/, '').safe_constantize
<ide> mod.is_a?(Class) ? nil : mod
<del> rescue NameError
<del> nil
<ide> end
<ide>
<ide> def helper_method(*methods)
<ide><path>activesupport/lib/active_support/core_ext/module/reachable.rb
<ide>
<ide> class Module
<ide> def reachable? #:nodoc:
<del> !anonymous? && name.constantize.equal?(self)
<del> rescue NameError
<del> false
<add> !anonymous? && name.safe_constantize.equal?(self)
<ide> end
<ide> end | 3 |
Go | Go | add note about lxc.cap.keep > lxc.cap.drop | 788d66f409ce3a7e464bbb68d909960648f2515c | <ide><path>lxc_template.go
<ide> lxc.mount.entry = {{$realPath}} {{$ROOTFS}}/{{$virtualPath}} none bind,rw 0 0
<ide> {{end}}
<ide>
<ide> # drop linux capabilities (apply mainly to the user root in the container)
<add># (Note: 'lxc.cap.keep' is coming soon and should replace this under the
<add># security principle 'deny all unless explicitly permitted', see
<add># http://sourceforge.net/mailarchive/message.php?msg_id=31054627 )
<ide> lxc.cap.drop = audit_control audit_write mac_admin mac_override mknod setfcap setpcap sys_admin sys_boot sys_module sys_nice sys_pacct sys_rawio sys_resource sys_time sys_tty_config
<ide>
<ide> # limits | 1 |
Javascript | Javascript | use focusin/focusout for onfocus/onblur | a59f899a1d021b231f8bd830436708294d9022c0 | <ide><path>packages/react-dom/src/__tests__/ReactDOMInput-test.js
<ide> describe('ReactDOMInput', () => {
<ide> // bypass the lazy event attachment system so we won't actually test this.
<ide> dispatchEventOnNode(instance.a, 'input');
<ide> dispatchEventOnNode(instance.a, 'blur');
<add> dispatchEventOnNode(instance.a, 'focusout');
<ide>
<ide> expect(instance.a.value).toBe('giraffe');
<ide> expect(instance.switchedFocus).toBe(true);
<ide> describe('ReactDOMInput', () => {
<ide> expect(node.hasAttribute('value')).toBe(false);
<ide> } else {
<ide> dispatchEventOnNode(node, 'blur');
<add> dispatchEventOnNode(node, 'focusout');
<ide>
<ide> expect(node.value).toBe('0.0');
<ide> expect(node.getAttribute('value')).toBe('0.0');
<ide> describe('ReactDOMInput', () => {
<ide> // be the only way to remove focus in JSDOM
<ide> node.blur();
<ide> dispatchEventOnNode(node, 'blur');
<add> dispatchEventOnNode(node, 'focusout');
<ide>
<ide> if (disableInputAttributeSyncing) {
<ide> expect(node.value).toBe('2');
<ide> describe('ReactDOMInput', () => {
<ide> // be the only way to remove focus in JSDOM
<ide> node.blur();
<ide> dispatchEventOnNode(node, 'blur');
<add> dispatchEventOnNode(node, 'focusout');
<ide>
<ide> expect(node.getAttribute('value')).toBe('1');
<ide> });
<ide> describe('ReactDOMInput', () => {
<ide> // be the only way to remove focus in JSDOM
<ide> node.blur();
<ide> dispatchEventOnNode(node, 'blur');
<add> dispatchEventOnNode(node, 'focusout');
<ide>
<ide> expect(node.getAttribute('value')).toBe('1');
<ide> });
<ide><path>packages/react-dom/src/events/DOMEventProperties.js
<ide> const eventPriorities = new Map();
<ide>
<ide> // prettier-ignore
<ide> const discreteEventPairsForSimpleEventPlugin = [
<del> DOMTopLevelEventTypes.TOP_BLUR, 'blur',
<ide> DOMTopLevelEventTypes.TOP_CANCEL, 'cancel',
<ide> DOMTopLevelEventTypes.TOP_CLICK, 'click',
<ide> DOMTopLevelEventTypes.TOP_CLOSE, 'close',
<ide> const discreteEventPairsForSimpleEventPlugin = [
<ide> DOMTopLevelEventTypes.TOP_DRAG_END, 'dragEnd',
<ide> DOMTopLevelEventTypes.TOP_DRAG_START, 'dragStart',
<ide> DOMTopLevelEventTypes.TOP_DROP, 'drop',
<del> DOMTopLevelEventTypes.TOP_FOCUS, 'focus',
<add> DOMTopLevelEventTypes.TOP_FOCUS_IN, 'focus',
<add> DOMTopLevelEventTypes.TOP_FOCUS_OUT, 'blur',
<ide> DOMTopLevelEventTypes.TOP_INPUT, 'input',
<ide> DOMTopLevelEventTypes.TOP_INVALID, 'invalid',
<ide> DOMTopLevelEventTypes.TOP_KEY_DOWN, 'keyDown',
<ide><path>packages/react-dom/src/events/DOMModernPluginEventSystem.js
<ide> import {
<ide>
<ide> import getEventTarget from './getEventTarget';
<ide> import {
<del> TOP_FOCUS,
<ide> TOP_LOAD,
<ide> TOP_ABORT,
<ide> TOP_CANCEL,
<ide> TOP_INVALID,
<del> TOP_BLUR,
<ide> TOP_SCROLL,
<ide> TOP_CLOSE,
<ide> TOP_RESET,
<ide> function extractEvents(
<ide> }
<ide>
<ide> export const capturePhaseEvents: Set<DOMTopLevelEventType> = new Set([
<del> TOP_FOCUS,
<del> TOP_BLUR,
<ide> TOP_SCROLL,
<ide> TOP_LOAD,
<ide> TOP_ABORT,
<ide><path>packages/react-dom/src/events/DOMTopLevelEventTypes.js
<ide> export const TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(
<ide> export const TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(
<ide> getVendorPrefixedEventName('animationstart'),
<ide> );
<del>export const TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');
<ide> export const TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');
<ide> export const TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType(
<ide> 'canplaythrough',
<ide> export const TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');
<ide> export const TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');
<ide> export const TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');
<ide> export const TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');
<del>export const TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');
<ide> export const TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType(
<ide> 'gotpointercapture',
<ide> );
<ide> export const TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel');
<ide> export const TOP_AFTER_BLUR = unsafeCastStringToDOMTopLevelType('afterblur');
<ide> export const TOP_BEFORE_BLUR = unsafeCastStringToDOMTopLevelType('beforeblur');
<ide>
<add>export const TOP_FOCUS_IN = unsafeCastStringToDOMTopLevelType('focusin');
<add>export const TOP_FOCUS_OUT = unsafeCastStringToDOMTopLevelType('focusout');
<add>
<ide> // List of events that need to be individually attached to media elements.
<ide> // Note that events in this list will *not* be listened to at the top level
<ide> // unless they're explicitly listed in `ReactBrowserEventEmitter.listenTo`.
<ide><path>packages/react-dom/src/events/ReactDOMEventReplaying.js
<ide> import {
<ide> TOP_POINTER_OUT,
<ide> TOP_GOT_POINTER_CAPTURE,
<ide> TOP_LOST_POINTER_CAPTURE,
<del> TOP_FOCUS,
<del> TOP_BLUR,
<add> TOP_FOCUS_IN,
<add> TOP_FOCUS_OUT,
<ide> } from './DOMTopLevelEventTypes';
<ide> import {IS_REPLAYED, PLUGIN_EVENT_SYSTEM} from './EventSystemFlags';
<ide> import {
<ide> const discreteReplayableEvents = [
<ide> ];
<ide>
<ide> const continuousReplayableEvents = [
<del> TOP_FOCUS,
<del> TOP_BLUR,
<ide> TOP_DRAG_ENTER,
<ide> TOP_DRAG_LEAVE,
<add> TOP_FOCUS_IN,
<add> TOP_FOCUS_OUT,
<ide> TOP_MOUSE_OVER,
<ide> TOP_MOUSE_OUT,
<ide> TOP_POINTER_OVER,
<ide> export function clearIfContinuousEvent(
<ide> nativeEvent: AnyNativeEvent,
<ide> ): void {
<ide> switch (topLevelType) {
<del> case TOP_FOCUS:
<del> case TOP_BLUR:
<add> case TOP_FOCUS_IN:
<add> case TOP_FOCUS_OUT:
<ide> queuedFocus = null;
<ide> break;
<ide> case TOP_DRAG_ENTER:
<ide> export function queueIfContinuousEvent(
<ide> // moved from outside the window (no target) onto the target once it hydrates.
<ide> // Instead of mutating we could clone the event.
<ide> switch (topLevelType) {
<del> case TOP_FOCUS: {
<add> case TOP_FOCUS_IN: {
<ide> const focusEvent = ((nativeEvent: any): FocusEvent);
<ide> queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(
<ide> queuedFocus,
<ide><path>packages/react-dom/src/events/__tests__/DOMModernPluginEventSystem-test.internal.js
<ide> describe('DOMModernPluginEventSystem', () => {
<ide> expect(onFocus).toHaveBeenCalledTimes(3);
<ide> expect(onFocusCapture).toHaveBeenCalledTimes(3);
<ide> expect(log[2]).toEqual(['capture', buttonElement]);
<del> expect(log[3]).toEqual(['bubble', buttonElement]);
<del> expect(log[4]).toEqual(['capture', divElement]);
<del> expect(log[5]).toEqual(['bubble', divElement]);
<add> expect(log[3]).toEqual(['capture', divElement]);
<add> expect(log[4]).toEqual(['bubble', divElement]);
<add> expect(log[5]).toEqual(['bubble', buttonElement]);
<ide> });
<ide>
<ide> it('handle propagation of focus events between portals', () => {
<ide><path>packages/react-dom/src/events/plugins/ModernBeforeInputEventPlugin.js
<ide> import {canUseDOM} from 'shared/ExecutionEnvironment';
<ide>
<ide> import {registerTwoPhaseEvent} from '../EventRegistry';
<ide> import {
<del> TOP_BLUR,
<add> TOP_FOCUS_OUT,
<ide> TOP_COMPOSITION_START,
<ide> TOP_COMPOSITION_END,
<ide> TOP_COMPOSITION_UPDATE,
<ide> function registerEvents() {
<ide> TOP_PASTE,
<ide> ]);
<ide> registerTwoPhaseEvent('onCompositionEnd', [
<del> TOP_BLUR,
<ide> TOP_COMPOSITION_END,
<add> TOP_FOCUS_OUT,
<ide> TOP_KEY_DOWN,
<ide> TOP_KEY_PRESS,
<ide> TOP_KEY_UP,
<ide> TOP_MOUSE_DOWN,
<ide> ]);
<ide> registerTwoPhaseEvent('onCompositionStart', [
<del> TOP_BLUR,
<ide> TOP_COMPOSITION_START,
<add> TOP_FOCUS_OUT,
<ide> TOP_KEY_DOWN,
<ide> TOP_KEY_PRESS,
<ide> TOP_KEY_UP,
<ide> TOP_MOUSE_DOWN,
<ide> ]);
<ide> registerTwoPhaseEvent('onCompositionUpdate', [
<del> TOP_BLUR,
<ide> TOP_COMPOSITION_UPDATE,
<add> TOP_FOCUS_OUT,
<ide> TOP_KEY_DOWN,
<ide> TOP_KEY_PRESS,
<ide> TOP_KEY_UP,
<ide> function isFallbackCompositionEnd(topLevelType, nativeEvent) {
<ide> return nativeEvent.keyCode !== START_KEYCODE;
<ide> case TOP_KEY_PRESS:
<ide> case TOP_MOUSE_DOWN:
<del> case TOP_BLUR:
<add> case TOP_FOCUS_OUT:
<ide> // Events are not possible without cancelling IME.
<ide> return true;
<ide> default:
<ide><path>packages/react-dom/src/events/plugins/ModernChangeEventPlugin.js
<ide> import isTextInputElement from '../isTextInputElement';
<ide> import {canUseDOM} from 'shared/ExecutionEnvironment';
<ide>
<ide> import {
<del> TOP_BLUR,
<add> TOP_FOCUS_OUT,
<ide> TOP_CHANGE,
<ide> TOP_CLICK,
<del> TOP_FOCUS,
<add> TOP_FOCUS_IN,
<ide> TOP_INPUT,
<ide> TOP_KEY_DOWN,
<ide> TOP_KEY_UP,
<ide> import {
<ide>
<ide> function registerEvents() {
<ide> registerTwoPhaseEvent('onChange', [
<del> TOP_BLUR,
<ide> TOP_CHANGE,
<ide> TOP_CLICK,
<del> TOP_FOCUS,
<add> TOP_FOCUS_IN,
<add> TOP_FOCUS_OUT,
<ide> TOP_INPUT,
<ide> TOP_KEY_DOWN,
<ide> TOP_KEY_UP,
<ide> function handlePropertyChange(nativeEvent) {
<ide> }
<ide>
<ide> function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) {
<del> if (topLevelType === TOP_FOCUS) {
<add> if (topLevelType === TOP_FOCUS_IN) {
<ide> // In IE9, propertychange fires for most input events but is buggy and
<ide> // doesn't fire when text is deleted, but conveniently, selectionchange
<ide> // appears to fire in all of the remaining cases so we catch those and
<ide> function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) {
<ide> // missed a blur event somehow.
<ide> stopWatchingForValueChange();
<ide> startWatchingForValueChange(target, targetInst);
<del> } else if (topLevelType === TOP_BLUR) {
<add> } else if (topLevelType === TOP_FOCUS_OUT) {
<ide> stopWatchingForValueChange();
<ide> }
<ide> }
<ide> function extractEvents(
<ide> }
<ide>
<ide> // When blurring, set the value attribute for number inputs
<del> if (topLevelType === TOP_BLUR) {
<add> if (topLevelType === TOP_FOCUS_OUT) {
<ide> handleControlledInputBlur(((targetNode: any): HTMLInputElement));
<ide> }
<ide> }
<ide><path>packages/react-dom/src/events/plugins/ModernSelectEventPlugin.js
<ide> import shallowEqual from 'shared/shallowEqual';
<ide>
<ide> import {registerTwoPhaseEvent} from '../EventRegistry';
<ide> import {
<del> TOP_BLUR,
<add> TOP_FOCUS_OUT,
<ide> TOP_CONTEXT_MENU,
<ide> TOP_DRAG_END,
<del> TOP_FOCUS,
<add> TOP_FOCUS_IN,
<ide> TOP_KEY_DOWN,
<ide> TOP_KEY_UP,
<ide> TOP_MOUSE_DOWN,
<ide> const skipSelectionChangeEvent =
<ide> canUseDOM && 'documentMode' in document && document.documentMode <= 11;
<ide>
<ide> const rootTargetDependencies = [
<del> TOP_BLUR,
<add> TOP_FOCUS_OUT,
<ide> TOP_CONTEXT_MENU,
<ide> TOP_DRAG_END,
<del> TOP_FOCUS,
<add> TOP_FOCUS_IN,
<ide> TOP_KEY_DOWN,
<ide> TOP_KEY_UP,
<ide> TOP_MOUSE_DOWN,
<ide> function extractEvents(
<ide>
<ide> switch (topLevelType) {
<ide> // Track the input node that has focus.
<del> case TOP_FOCUS:
<add> case TOP_FOCUS_IN:
<ide> if (
<ide> isTextInputElement(targetNode) ||
<ide> targetNode.contentEditable === 'true'
<ide> function extractEvents(
<ide> lastSelection = null;
<ide> }
<ide> break;
<del> case TOP_BLUR:
<add> case TOP_FOCUS_OUT:
<ide> activeElement = null;
<ide> activeElementInst = null;
<ide> lastSelection = null;
<ide><path>packages/react-dom/src/events/plugins/ModernSimpleEventPlugin.js
<ide> function extractEvents(
<ide> case DOMTopLevelEventTypes.TOP_KEY_UP:
<ide> EventConstructor = SyntheticKeyboardEvent;
<ide> break;
<del> case DOMTopLevelEventTypes.TOP_BLUR:
<del> case DOMTopLevelEventTypes.TOP_FOCUS:
<add> case DOMTopLevelEventTypes.TOP_FOCUS_IN:
<add> case DOMTopLevelEventTypes.TOP_FOCUS_OUT:
<ide> case DOMTopLevelEventTypes.TOP_BEFORE_BLUR:
<ide> case DOMTopLevelEventTypes.TOP_AFTER_BLUR:
<ide> EventConstructor = SyntheticFocusEvent;
<ide><path>packages/react-interactions/events/src/dom/create-event-handle/Focus.js
<ide> function handleGlobalFocusVisibleEvent(
<ide> }
<ide>
<ide> const passiveObject = {passive: true};
<del>const passiveObjectWithPriority = {passive: true, priority: 0};
<ide>
<ide> function handleFocusVisibleTargetEvent(
<ide> type: string,
<ide> export function useFocus(
<ide> ): void {
<ide> // Setup controlled state for this useFocus hook
<ide> const stateRef = useRef({isFocused: false, isFocusVisible: false});
<del> const focusHandle = useEvent('focusin', passiveObjectWithPriority);
<del> const blurHandle = useEvent('focusout', passiveObjectWithPriority);
<add> const focusHandle = useEvent('focusin', passiveObject);
<add> const blurHandle = useEvent('focusout', passiveObject);
<ide> const focusVisibleHandles = useFocusVisibleInputHandles();
<ide>
<ide> useEffect(() => {
<ide> export function useFocusWithin(
<ide> const stateRef = useRef<null | {isFocused: boolean, isFocusVisible: boolean}>(
<ide> {isFocused: false, isFocusVisible: false},
<ide> );
<del> const focusHandle = useEvent('focusin', passiveObjectWithPriority);
<del> const blurHandle = useEvent('focusout', passiveObjectWithPriority);
<add> const focusHandle = useEvent('focusin', passiveObject);
<add> const blurHandle = useEvent('focusout', passiveObject);
<ide> const afterBlurHandle = useEvent('afterblur', passiveObject);
<ide> const beforeBlurHandle = useEvent('beforeblur', passiveObject);
<ide> const focusVisibleHandles = useFocusVisibleInputHandles();
<ide> export function useFocusWithin(
<ide> if (disabled) {
<ide> return;
<ide> }
<del> const {relatedTarget} = (event.nativeEvent: any);
<add> const {relatedTarget} = (event: any);
<ide>
<ide> if (
<ide> state.isFocused && | 11 |
Javascript | Javascript | fix time tests by adding date to sandbox | f69040c9d2b21491e33a9676a68ce20d97787ab4 | <ide><path>test/load.js
<ide> require("./XMLHttpRequest");
<ide> module.exports = function() {
<ide> var files = [].slice.call(arguments).map(function(d) { return "src/" + d; }),
<ide> expression = "d3",
<del> sandbox = null;
<add> sandbox = {Date: Date}; // so we can use deepEqual in tests
<ide>
<ide> files.unshift("src/start");
<ide> files.push("src/end");
<ide> module.exports = function() {
<ide> window: document.createWindow(),
<ide> setTimeout: setTimeout,
<ide> clearTimeout: clearTimeout,
<del> Date: Date // so we can override Date.now in tests
<add> Date: Date // so we can override Date.now in tests, and use deepEqual
<ide> };
<ide>
<ide> return topic; | 1 |
Javascript | Javascript | remove react suspense from client runtime | d9c6f20023a805604381e7d7a65169dd7ef5cf81 | <ide><path>packages/next/client/index.js
<ide> /* global location */
<del>import React, { Suspense } from 'react'
<add>import React from 'react'
<ide> import ReactDOM from 'react-dom'
<ide> import HeadManager from './head-manager'
<ide> import { createRouter, makePublicRouterInstance } from 'next/router'
<ide> function AppContainer ({ children }) {
<ide> )
<ide> }
<ide> >
<del> <Suspense fallback={<div>Loading...</div>}>
<del> <RouterContext.Provider value={makePublicRouterInstance(router)}>
<del> <DataManagerContext.Provider value={dataManager}>
<del> <HeadManagerContext.Provider value={headManager.updateHead}>
<del> {children}
<del> </HeadManagerContext.Provider>
<del> </DataManagerContext.Provider>
<del> </RouterContext.Provider>
<del> </Suspense>
<add> <RouterContext.Provider value={makePublicRouterInstance(router)}>
<add> <DataManagerContext.Provider value={dataManager}>
<add> <HeadManagerContext.Provider value={headManager.updateHead}>
<add> {children}
<add> </HeadManagerContext.Provider>
<add> </DataManagerContext.Provider>
<add> </RouterContext.Provider>
<ide> </Container>
<ide> )
<ide> }
<ide><path>test/integration/data/pages/_app.js
<add>import React, { Suspense } from 'react'
<add>import App from 'next/app'
<add>
<add>class MyApp extends App {
<add> render () {
<add> const { Component, pageProps } = this.props
<add> if (typeof window === 'undefined') {
<add> return <Component {...pageProps} />
<add> }
<add>
<add> return (
<add> <Suspense fallback={<div>Loading...</div>}>
<add> <Component {...pageProps} />
<add> </Suspense>
<add> )
<add> }
<add>}
<add>
<add>export default MyApp | 2 |
Python | Python | add examples to np.char.multiply | 0b7b940ecb436427289093b3becb51f935eb05df | <ide><path>numpy/core/defchararray.py
<ide> def multiply(a, i):
<ide> -------
<ide> out : ndarray
<ide> Output array of str or unicode, depending on input types
<del>
<add>
<add> Examples
<add> --------
<add> >>> a = np.array(["a", "b", "c"])
<add> >>> np.char.multiply(x, 3)
<add> array(['aaa', 'bbb', 'ccc'], dtype='<U3')
<add> >>> i = np.array([1, 2, 3])
<add> >>> np.char.multiply(a, i)
<add> array(['a', 'bb', 'ccc'], dtype='<U3')
<add> >>> np.char.multiply(np.array(['a']), i)
<add> array(['a', 'aa', 'aaa'], dtype='<U3')
<add> >>> a = np.array(['a', 'b', 'c', 'd', 'e', 'f']).reshape((2, 3))
<add> >>> np.char.multiply(a, 3)
<add> array([['aaa', 'bbb', 'ccc'],
<add> ['ddd', 'eee', 'fff']], dtype='<U3')
<add> >>> np.char.multiply(a, i)
<add> array([['a', 'bb', 'ccc'],
<add> ['d', 'ee', 'fff']], dtype='<U3')
<ide> """
<ide> a_arr = numpy.asarray(a)
<ide> i_arr = numpy.asarray(i) | 1 |
PHP | PHP | make translator parameters like l3 | 37fc266596f17d0e1e55f93f6f4ec404018b0f8a | <ide><path>src/Illuminate/Translation/Translator.php
<ide> public function get($key, $parameters = array(), $locale = null)
<ide> {
<ide> list($namespace, $group, $item) = $this->parseKey($key);
<ide>
<add> $parameters = $this->formatParameters($parameters);
<add>
<ide> // Once we call the "load" method, we will receive back the "domain" for the
<ide> // namespace and group. The "domain" is used by the Symfony translator to
<ide> // logically separate related groups of messages, and should be unique.
<ide> public function choice($key, $number, $parameters = array(), $locale = null)
<ide> {
<ide> list($namespace, $group, $item) = $this->parseKey($key);
<ide>
<add> $parameters = $this->formatParameters($parameters);
<add>
<add> // Once we call the "load" method, we will receive back the "domain" for the
<add> // namespace and group. The "domain" is used by the Symfony translator to
<add> // logically separate related groups of messages, and should be unique.
<ide> $domain = $this->load($group, $namespace, $locale);
<ide>
<ide> $line = $this->trans->transChoice($item, $number, $parameters, $domain, $locale);
<ide> public function transChoice($id, $number, array $parameters = array(), $domain =
<ide> */
<ide> public function load($group, $namespace, $locale)
<ide> {
<del> // The domain is used to store the messages in the Symfony translator object
<del> // and functions as a sort of logical separator of message types so we'll
<del> // use the namespace and group as the "domain", which should be unique.
<ide> $domain = $namespace.'::'.$group;
<ide>
<ide> $locale = $locale ?: $this->getLocale();
<ide>
<add> // The domain is used to store the messages in the Symfony translator object
<add> // and functions as a sort of logical separator of message types so we'll
<add> // use the namespace and group as the "domain", which should be unique.
<ide> if ($this->loaded($group, $namespace, $locale))
<ide> {
<ide> return $domain;
<ide> protected function addResource(array $lines, $locale, $domain)
<ide> $this->trans->refreshCatalogue($locale);
<ide> }
<ide>
<add> /**
<add> * Format the parameter array.
<add> *
<add> * @param array $parameters
<add> * @return array
<add> */
<add> protected function formatParameters($parameters)
<add> {
<add> foreach ($parameters as $key => $value)
<add> {
<add> $parameters[':'.$key] = $value;
<add>
<add> unset($parameters[$key]);
<add> }
<add>
<add> return $parameters;
<add> }
<add>
<ide> /**
<ide> * Determine if the given group has been loaded.
<ide> *
<ide><path>tests/Translation/TranslationTranslatorTest.php
<ide> public function testGetMethodProperlyLoadsAndRetrievesItem()
<ide> $t = $this->getMock('Illuminate\Translation\Translator', array('load', 'trans'), array($this->getLoader(), 'en', 'sp'));
<ide> $t->expects($this->once())->method('load')->with($this->equalTo('bar'), $this->equalTo('foo'), $this->equalTo('en'))->will($this->returnValue('foo::bar'));
<ide> $t->setSymfonyTranslator($base = m::mock('Illuminate\Translation\SymfonyTranslator'));
<del> $base->shouldReceive('trans')->once()->with('baz', array('foo'), 'foo::bar', 'en')->andReturn('breeze');
<add> $base->shouldReceive('trans')->once()->with('baz', array(':foo' => 'bar'), 'foo::bar', 'en')->andReturn('breeze');
<ide>
<del> $this->assertEquals('breeze', $t->get('foo::bar.baz', array('foo'), 'en'));
<add> $this->assertEquals('breeze', $t->get('foo::bar.baz', array('foo' => 'bar'), 'en'));
<ide> }
<ide>
<ide>
<ide> public function testChoiceMethodProperlyLoadsAndRetrievesItem()
<ide> $t = $this->getMock('Illuminate\Translation\Translator', array('load', 'transChoice'), array($this->getLoader(), 'en', 'sp'));
<ide> $t->expects($this->once())->method('load')->with($this->equalTo('bar'), $this->equalTo('foo'), $this->equalTo('en'))->will($this->returnValue('foo::bar'));
<ide> $t->setSymfonyTranslator($base = m::mock('Illuminate\Translation\SymfonyTranslator'));
<del> $base->shouldReceive('transChoice')->once()->with('baz', 10, array('foo'), 'foo::bar', 'en')->andReturn('breeze');
<add> $base->shouldReceive('transChoice')->once()->with('baz', 10, array(':foo' => 'bar'), 'foo::bar', 'en')->andReturn('breeze');
<ide>
<del> $this->assertEquals('breeze', $t->choice('foo::bar.baz', 10, array('foo'), 'en'));
<add> $this->assertEquals('breeze', $t->choice('foo::bar.baz', 10, array('foo' => 'bar'), 'en'));
<ide> }
<ide>
<ide> | 2 |
Javascript | Javascript | fix misleading docs [fixes | 39e9ef7923a549a617854268d7286173e2d0c8e4 | <ide><path>packages/ember-application/lib/system/application.js
<ide> DeprecatedContainer.prototype = {
<ide> If there is any setup required before routing begins, you can implement a
<ide> `ready()` method on your app that will be invoked immediately before routing
<ide> begins.
<del>
<del> To begin routing, you must have at a minimum a top-level controller and view.
<del> You define these as `App.ApplicationController` and `App.ApplicationView`,
<del> respectively. Your application will not work if you do not define these two
<del> mandatory classes. For example:
<del>
<del> ```javascript
<del> App.ApplicationView = Ember.View.extend({
<del> templateName: 'application'
<del> });
<del> App.ApplicationController = Ember.Controller.extend();
<ide> ```
<ide>
<ide> @class Application | 1 |
PHP | PHP | fix a styling issue | db8419641c6ccdc7d6e4673267027aba92868b53 | <ide><path>tests/Integration/Database/SchemaBuilderTest.php
<ide> namespace Illuminate\Tests\Integration\Database\SchemaTest;
<ide>
<ide> use Doctrine\DBAL\Types\Type;
<del>use Illuminate\Database\Schema\Grammars\SQLiteGrammar;
<ide> use Illuminate\Support\Facades\DB;
<ide> use Illuminate\Support\Facades\Schema;
<ide> use Illuminate\Database\Schema\Blueprint;
<ide> use Illuminate\Database\Schema\Types\TinyInteger;
<add>use Illuminate\Database\Schema\Grammars\SQLiteGrammar;
<ide> use Illuminate\Tests\Integration\Database\DatabaseTestCase;
<ide>
<ide> /**
<ide> public function test_register_custom_DBAL_type()
<ide> 'DROP TABLE test',
<ide> 'CREATE TABLE test (test_column TINYINT NOT NULL COLLATE BINARY)',
<ide> 'INSERT INTO test (test_column) SELECT test_column FROM __temp__test',
<del> 'DROP TABLE __temp__test'
<add> 'DROP TABLE __temp__test',
<ide> ];
<ide>
<ide> $statements = $blueprint->toSql($this->getConnection(), new SQLiteGrammar()); | 1 |
Text | Text | add information for heap snapshot flag | 4fbefc4283592e13d50888d9a1a62bb0c2f3356b | <ide><path>doc/api/cli.md
<ide> reference. Code may break under this flag.
<ide> added: v12.0.0
<ide> -->
<ide>
<add>Enables a signal handler that causes the Node.js process to write a heap dump
<add>when the specified signal is received.
<add>
<add>```console
<add>$ node --heapsnapshot-signal=SIGUSR2 index.js &
<add>$ ps aux
<add>USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
<add>node 1 5.5 6.1 787252 247004 ? Ssl 16:43 0:02 node --heapsnapshot-signal=SIGUSR2 index.js
<add>$ kill -USR2 1
<add>$ ls
<add>Heap.20190718.133405.15554.0.001.heapsnapshot
<add>```
<add>
<ide> ### `--heap-prof`
<ide> <!-- YAML
<ide> added: v12.4.0 | 1 |
Python | Python | remove mask_val from time_distributed_softmax | 86a9445ffd5a789b359e49057771332138cc2bfe | <ide><path>keras/activations.py
<ide> def softmax(x):
<ide> return T.nnet.softmax(x)
<ide>
<del>def time_distributed_softmax(x, mask_val=default_mask_val):
<add>def time_distributed_softmax(x):
<ide> xshape = x.shape
<ide> X = x.reshape((xshape[0] * xshape[1], xshape[2]))
<ide> return T.nnet.softmax(X).reshape(xshape) | 1 |
Ruby | Ruby | remove unused `fork` arg for `rails` | 39f3ab51e9d9c585dd65c09dcfe9a3ece4521c1f | <ide><path>railties/test/isolation/abstract_unit.rb
<ide> def engine(name)
<ide> # stderr:: true to pass STDERR output straight to the "real" STDERR.
<ide> # By default, the STDERR and STDOUT of the process will be
<ide> # combined in the returned string.
<del> # fork:: false to not use fork even when it's available. By default,
<del> # when possible, the command is executed in a fork of the current
<del> # process, avoiding the need to load core Rails libraries anew.
<del> def rails(*args, allow_failure: false, stderr: false, fork: true)
<add> def rails(*args, allow_failure: false, stderr: false)
<ide> args = args.flatten
<add> fork = true
<ide>
<ide> command = "bin/rails #{Shellwords.join args}#{' 2>&1' unless stderr}"
<ide> | 1 |
Javascript | Javascript | add logical assignment support | aea7ce053d5ca96c5bec45f8910caed67cb42c3b | <ide><path>lib/javascript/JavascriptParser.js
<ide> const StackedMap = require("../util/StackedMap");
<ide> const memorize = require("../util/memorize");
<ide> const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
<ide>
<del>/** @typedef {import("acorn").Options} AcornOptions */
<add>// Todo: revert to /** @typedef {import("acorn").Options} AcornOptions */
<add>// when https://github.com/acornjs/acorn/pull/979 is published
<add>/** @typedef {Omit<import("acorn").Options, "ecmaVersion"> & { ecmaVersion: "latest" } } AcornOptions */
<ide> /** @typedef {import("estree").ArrayExpression} ArrayExpressionNode */
<ide> /** @typedef {import("estree").BinaryExpression} BinaryExpressionNode */
<ide> /** @typedef {import("estree").BlockStatement} BlockStatementNode */
<ide> const getRootName = expression => {
<ide> const defaultParserOptions = {
<ide> ranges: true,
<ide> locations: true,
<del> ecmaVersion: 11,
<add> ecmaVersion: "latest",
<ide> sourceType: "module",
<ide> allowAwaitOutsideFunction: true,
<ide> onComment: null
<ide><path>test/cases/parsing/logical-assignment/index.js
<add>import f from "./module";
<add>
<add>it("should support logical assignment", () => {
<add> expect(f()).toBe(true);
<add>});
<ide><path>test/cases/parsing/logical-assignment/module.js
<add>export default function() {
<add> a ??= b &&= c ||= d;
<add>}
<ide><path>test/cases/parsing/logical-assignment/test.filter.js
<add>var supportsLogicalAssignment = require("../../../helpers/supportsLogicalAssignment");
<add>
<add>module.exports = function(config) {
<add> return supportsLogicalAssignment();
<add>}; | 4 |
Ruby | Ruby | move migrations into `updatemigrator` module | 516a39f5a471822b0565ae24189cc5389caaf923 | <ide><path>Library/Homebrew/brew.rb
<ide>
<ide> require_relative "global"
<ide>
<add>require "update_migrator"
<add>
<ide> begin
<ide> trap("INT", std_trap) # restore default CTRL-C handler
<ide>
<ide> end
<ide>
<ide> # Migrate LinkedKegs/PinnedKegs if update didn't already do so
<del> migrate_legacy_keg_symlinks_if_necessary
<add> UpdateMigrator.migrate_legacy_keg_symlinks_if_necessary
<ide>
<ide> # Uninstall old brew-cask if it's still around; we just use the tap now.
<ide> if cmd == "cask" && (HOMEBREW_CELLAR/"brew-cask").exist?
<ide><path>Library/Homebrew/cmd/update-report.rb
<ide> require "formulary"
<ide> require "descriptions"
<ide> require "cleanup"
<del>require "hbc/download"
<add>require "update_migrator"
<ide>
<ide> module Homebrew
<ide> module_function
<ide> def update_report
<ide> updated = true
<ide> end
<ide>
<del> migrate_legacy_cache_if_necessary
<del> migrate_cache_entries_to_double_dashes(initial_version)
<del> migrate_cache_entries_to_symlinks(initial_version)
<del> migrate_legacy_keg_symlinks_if_necessary
<add> UpdateMigrator.migrate_legacy_cache_if_necessary
<add> UpdateMigrator.migrate_cache_entries_to_double_dashes(initial_version)
<add> UpdateMigrator.migrate_cache_entries_to_symlinks(initial_version)
<add> UpdateMigrator.migrate_legacy_keg_symlinks_if_necessary
<ide>
<ide> if !updated
<ide> if !ARGV.include?("--preinstall") && !ENV["HOMEBREW_UPDATE_FAILED"]
<ide> def update_report
<ide> # This should always be the last thing to run (but skip on auto-update).
<ide> if !ARGV.include?("--preinstall") ||
<ide> ENV["HOMEBREW_ENABLE_AUTO_UPDATE_MIGRATION"]
<del> migrate_legacy_repository_if_necessary
<add> UpdateMigrator.migrate_legacy_repository_if_necessary
<ide> end
<ide> end
<ide>
<ide> def install_core_tap_if_necessary
<ide> ENV["HOMEBREW_UPDATE_AFTER_HOMEBREW_HOMEBREW_CORE"] = revision
<ide> end
<ide>
<del> def migrate_legacy_cache_if_necessary
<del> legacy_cache = Pathname.new "/Library/Caches/Homebrew"
<del> return if HOMEBREW_CACHE.to_s == legacy_cache.to_s
<del> return unless legacy_cache.directory?
<del> return unless legacy_cache.readable_real?
<del>
<del> migration_attempted_file = legacy_cache/".migration_attempted"
<del> return if migration_attempted_file.exist?
<del>
<del> return unless legacy_cache.writable_real?
<del> FileUtils.touch migration_attempted_file
<del>
<del> # This directory could have been compromised if it's world-writable/
<del> # a symlink/owned by another user so don't copy files in those cases.
<del> world_writable = legacy_cache.stat.mode & 0777 == 0777
<del> return if world_writable
<del> return if legacy_cache.symlink?
<del> return if !legacy_cache.owned? && legacy_cache.lstat.uid.nonzero?
<del>
<del> ohai "Migrating #{legacy_cache} to #{HOMEBREW_CACHE}..."
<del> HOMEBREW_CACHE.mkpath
<del> legacy_cache.cd do
<del> legacy_cache.entries.each do |f|
<del> next if [".", "..", ".migration_attempted"].include? f.to_s
<del> begin
<del> FileUtils.cp_r f, HOMEBREW_CACHE
<del> rescue
<del> @migration_failed ||= true
<del> end
<del> end
<del> end
<del>
<del> if @migration_failed
<del> opoo <<~EOS
<del> Failed to migrate #{legacy_cache} to
<del> #{HOMEBREW_CACHE}. Please do so manually.
<del> EOS
<del> else
<del> ohai "Deleting #{legacy_cache}..."
<del> FileUtils.rm_rf legacy_cache
<del> if legacy_cache.exist?
<del> FileUtils.touch migration_attempted_file
<del> opoo <<~EOS
<del> Failed to delete #{legacy_cache}.
<del> Please do so manually.
<del> EOS
<del> end
<del> end
<del> end
<del>
<del> def formula_resources(formula)
<del> specs = [formula.stable, formula.devel, formula.head].compact
<del>
<del> [*formula.bottle&.resource] + specs.flat_map do |spec|
<del> [
<del> spec,
<del> *spec.resources.values,
<del> *spec.patches.select(&:external?).map(&:resource),
<del> ]
<del> end
<del> end
<del>
<del> def parse_extname(url)
<del> uri_path = if URI::DEFAULT_PARSER.make_regexp =~ url
<del> uri = URI(url)
<del> uri.query ? "#{uri.path}?#{uri.query}" : uri.path
<del> else
<del> url
<del> end
<del>
<del> # Given a URL like https://example.com/download.php?file=foo-1.0.tar.gz
<del> # the extension we want is ".tar.gz", not ".php".
<del> Pathname.new(uri_path).ascend do |path|
<del> ext = path.extname[/[^?&]+/]
<del> return ext if ext
<del> end
<del>
<del> nil
<del> end
<del>
<del> def migrate_cache_entries_to_double_dashes(initial_version)
<del> return if initial_version && initial_version > "1.7.1"
<del>
<del> return if ENV.key?("HOMEBREW_DISABLE_LOAD_FORMULA")
<del>
<del> ohai "Migrating cache entries..."
<del>
<del> Formula.each do |formula|
<del> formula_resources(formula).each do |resource|
<del> downloader = resource.downloader
<del>
<del> url = downloader.url
<del> name = resource.download_name
<del> version = resource.version
<del>
<del> extname = parse_extname(url)
<del> old_location = downloader.cache/"#{name}-#{version}#{extname}"
<del> new_location = downloader.cache/"#{name}--#{version}#{extname}"
<del>
<del> next unless old_location.file?
<del>
<del> if new_location.exist?
<del> begin
<del> FileUtils.rm_rf old_location
<del> rescue Errno::EACCES
<del> opoo "Could not remove #{old_location}, please do so manually."
<del> end
<del> else
<del> begin
<del> FileUtils.mv old_location, new_location
<del> rescue Errno::EACCES
<del> opoo "Could not move #{old_location} to #{new_location}, please do so manually."
<del> end
<del> end
<del> end
<del> end
<del> end
<del>
<del> def migrate_cache_entries_to_symlinks(initial_version)
<del> return if initial_version && initial_version > "1.7.2"
<del>
<del> return if ENV.key?("HOMEBREW_DISABLE_LOAD_FORMULA")
<del>
<del> ohai "Migrating cache entries..."
<del>
<del> load_formula = lambda do |formula|
<del> begin
<del> Formula[formula]
<del> rescue FormulaUnavailableError
<del> nil
<del> end
<del> end
<del>
<del> load_cask = lambda do |cask|
<del> begin
<del> Hbc::CaskLoader.load(cask)
<del> rescue Hbc::CaskUnavailableError
<del> nil
<del> end
<del> end
<del>
<del> formula_downloaders = if HOMEBREW_CACHE.directory?
<del> HOMEBREW_CACHE.children
<del> .select(&:file?)
<del> .map { |child| child.basename.to_s.sub(/\-\-.*/, "") }
<del> .uniq
<del> .map(&load_formula)
<del> .compact
<del> .flat_map { |formula| formula_resources(formula) }
<del> .map { |resource| [resource.downloader, resource.download_name, resource.version] }
<del> else
<del> []
<del> end
<del>
<del> cask_downloaders = if (HOMEBREW_CACHE/"Cask").directory?
<del> (HOMEBREW_CACHE/"Cask").children
<del> .map { |child| child.basename.to_s.sub(/\-\-.*/, "") }
<del> .uniq
<del> .map(&load_cask)
<del> .compact
<del> .map { |cask| [Hbc::Download.new(cask).downloader, cask.token, cask.version] }
<del> else
<del> []
<del> end
<del>
<del> downloaders = formula_downloaders + cask_downloaders
<del>
<del> downloaders.each do |downloader, name, version|
<del> next unless downloader.respond_to?(:symlink_location)
<del>
<del> url = downloader.url
<del> extname = parse_extname(url)
<del> old_location = downloader.cache/"#{name}--#{version}#{extname}"
<del> next unless old_location.file?
<del>
<del> new_symlink_location = downloader.symlink_location
<del> new_location = downloader.cached_location
<del>
<del> if new_location.exist? && new_symlink_location.symlink?
<del> begin
<del> FileUtils.rm_rf old_location unless old_location == new_symlink_location
<del> rescue Errno::EACCES
<del> opoo "Could not remove #{old_location}, please do so manually."
<del> end
<del> else
<del> begin
<del> new_location.dirname.mkpath
<del> FileUtils.mv old_location, new_location unless new_location.exist?
<del> symlink_target = new_location.relative_path_from(new_symlink_location.dirname)
<del> new_symlink_location.dirname.mkpath
<del> FileUtils.ln_s symlink_target, new_symlink_location, force: true
<del> rescue Errno::EACCES
<del> opoo "Could not move #{old_location} to #{new_location}, please do so manually."
<del> end
<del> end
<del> end
<del> end
<del>
<del> def migrate_legacy_repository_if_necessary
<del> return unless HOMEBREW_PREFIX.to_s == "/usr/local"
<del> return unless HOMEBREW_REPOSITORY.to_s == "/usr/local"
<del>
<del> ohai "Migrating HOMEBREW_REPOSITORY (please wait)..."
<del>
<del> unless HOMEBREW_PREFIX.writable_real?
<del> ofail <<~EOS
<del> #{HOMEBREW_PREFIX} is not writable.
<del>
<del> You should change the ownership and permissions of #{HOMEBREW_PREFIX}
<del> temporarily back to your user account so we can complete the Homebrew
<del> repository migration:
<del> sudo chown -R $(whoami) #{HOMEBREW_PREFIX}
<del> EOS
<del> return
<del> end
<del>
<del> new_homebrew_repository = Pathname.new "/usr/local/Homebrew"
<del> new_homebrew_repository.rmdir_if_possible
<del> if new_homebrew_repository.exist?
<del> ofail <<~EOS
<del> #{new_homebrew_repository} already exists.
<del> Please remove it manually or uninstall and reinstall Homebrew into a new
<del> location as the migration cannot be done automatically.
<del> EOS
<del> return
<del> end
<del> new_homebrew_repository.mkpath
<del>
<del> repo_files = HOMEBREW_REPOSITORY.cd do
<del> Utils.popen_read("git ls-files").lines.map(&:chomp)
<del> end
<del>
<del> unless Utils.popen_read("git status --untracked-files=all --porcelain").empty?
<del> HOMEBREW_REPOSITORY.cd do
<del> quiet_system "git", "merge", "--abort"
<del> quiet_system "git", "rebase", "--abort"
<del> quiet_system "git", "reset", "--mixed"
<del> safe_system "git", "-c", "user.email=brew-update@localhost",
<del> "-c", "user.name=brew update",
<del> "stash", "save", "--include-untracked"
<del> end
<del> stashed = true
<del> end
<del>
<del> FileUtils.cp_r "#{HOMEBREW_REPOSITORY}/.git", "#{new_homebrew_repository}/.git"
<del> new_homebrew_repository.cd do
<del> safe_system "git", "checkout", "--force", "."
<del> safe_system "git", "stash", "pop" if stashed
<del> end
<del>
<del> if (HOMEBREW_REPOSITORY/"Library/Locks").exist?
<del> FileUtils.cp_r "#{HOMEBREW_REPOSITORY}/Library/Locks", "#{new_homebrew_repository}/Library/Locks"
<del> end
<del>
<del> if (HOMEBREW_REPOSITORY/"Library/Taps").exist?
<del> FileUtils.cp_r "#{HOMEBREW_REPOSITORY}/Library/Taps", "#{new_homebrew_repository}/Library/Taps"
<del> end
<del>
<del> unremovable_paths = []
<del> extra_remove_paths = [".git", "Library/Locks", "Library/Taps",
<del> "Library/Homebrew/cask", "Library/Homebrew/test"]
<del> (repo_files + extra_remove_paths).each do |file|
<del> path = Pathname.new "#{HOMEBREW_REPOSITORY}/#{file}"
<del> begin
<del> FileUtils.rm_rf path
<del> rescue Errno::EACCES
<del> unremovable_paths << path
<del> end
<del> quiet_system "rmdir", "-p", path.parent if path.parent.exist?
<del> end
<del>
<del> unless unremovable_paths.empty?
<del> ofail <<~EOS
<del> Could not remove old HOMEBREW_REPOSITORY paths!
<del> Please do this manually with:
<del> sudo rm -rf #{unremovable_paths.join " "}
<del> EOS
<del> end
<del>
<del> (Keg::ALL_TOP_LEVEL_DIRECTORIES + ["Cellar"]).each do |dir|
<del> FileUtils.mkdir_p "#{HOMEBREW_PREFIX}/#{dir}"
<del> end
<del>
<del> src = Pathname.new("#{new_homebrew_repository}/bin/brew")
<del> dst = Pathname.new("#{HOMEBREW_PREFIX}/bin/brew")
<del> begin
<del> FileUtils.ln_s(src.relative_path_from(dst.parent), dst)
<del> rescue Errno::EACCES, Errno::ENOENT
<del> ofail <<~EOS
<del> Could not create symlink at #{dst}!
<del> Please do this manually with:
<del> sudo ln -sf #{src} #{dst}
<del> sudo chown $(whoami) #{dst}
<del> EOS
<del> end
<del>
<del> link_completions_manpages_and_docs(new_homebrew_repository)
<del>
<del> ohai "Migrated HOMEBREW_REPOSITORY to #{new_homebrew_repository}!"
<del> puts <<~EOS
<del> Homebrew no longer needs to have ownership of /usr/local. If you wish you can
<del> return /usr/local to its default ownership with:
<del> sudo chown root:wheel #{HOMEBREW_PREFIX}
<del> EOS
<del> rescue => e
<del> ofail <<~EOS
<del> #{Tty.bold}Failed to migrate HOMEBREW_REPOSITORY to #{new_homebrew_repository}!#{Tty.reset}
<del> The error was:
<del> #{e}
<del> Please try to resolve this error yourself and then run `brew update` again to
<del> complete the migration. If you need help please +1 an existing error or comment
<del> with your new error in issue:
<del> #{Formatter.url("https://github.com/Homebrew/brew/issues/987")}
<del> EOS
<del> $stderr.puts e.backtrace
<del> end
<del>
<ide> def link_completions_manpages_and_docs(repository = HOMEBREW_REPOSITORY)
<ide> command = "brew update"
<ide> Utils::Link.link_completions(repository, command)
<add><path>Library/Homebrew/test/update_migrator_spec.rb
<del><path>Library/Homebrew/test/cmd/update-report_spec.rb
<del>require "cmd/update-report"
<add>require "update_migrator"
<ide>
<del>describe "brew update-report" do
<add>describe UpdateMigrator do
<ide> describe "::migrate_cache_entries_to_double_dashes" do
<ide> let(:formula_name) { "foo" }
<ide> let(:f) {
<ide> end
<ide>
<ide> it "moves old files to use double dashes when upgrading from <= 1.7.1" do
<del> Homebrew.migrate_cache_entries_to_double_dashes(Version.new("1.7.1"))
<add> described_class.migrate_cache_entries_to_double_dashes(Version.new("1.7.1"))
<ide>
<ide> expect(old_cache_file).not_to exist
<ide> expect(new_cache_file).to exist
<ide> let(:formula_name) { "foo-bar" }
<ide>
<ide> it "does not introduce extra double dashes when called multiple times" do
<del> Homebrew.migrate_cache_entries_to_double_dashes(Version.new("1.7.1"))
<del> Homebrew.migrate_cache_entries_to_double_dashes(Version.new("1.7.1"))
<add> described_class.migrate_cache_entries_to_double_dashes(Version.new("1.7.1"))
<add> described_class.migrate_cache_entries_to_double_dashes(Version.new("1.7.1"))
<ide>
<ide> expect(old_cache_file).not_to exist
<ide> expect(new_cache_file).to exist
<ide> end
<ide> end
<ide>
<ide> it "does not move files if upgrading from > 1.7.1" do
<del> Homebrew.migrate_cache_entries_to_double_dashes(Version.new("1.7.2"))
<add> described_class.migrate_cache_entries_to_double_dashes(Version.new("1.7.2"))
<ide>
<ide> expect(old_cache_file).to exist
<ide> expect(new_cache_file).not_to exist
<ide> end
<ide>
<ide> it "moves old files to use symlinks when upgrading from <= 1.7.2" do
<del> Homebrew.migrate_cache_entries_to_symlinks(Version.new("1.7.2"))
<add> described_class.migrate_cache_entries_to_symlinks(Version.new("1.7.2"))
<ide>
<ide> expect(old_cache_file).to eq(new_cache_symlink)
<ide> expect(new_cache_symlink).to be_a_symlink
<ide> end
<ide>
<ide> it "does not move files if upgrading from > 1.7.2" do
<del> Homebrew.migrate_cache_entries_to_symlinks(Version.new("1.7.3"))
<add> described_class.migrate_cache_entries_to_symlinks(Version.new("1.7.3"))
<ide>
<ide> expect(old_cache_file).to exist
<ide> expect(new_cache_file).not_to exist
<ide><path>Library/Homebrew/update_migrator.rb
<add>require "update_migrator/cache_entries_to_double_dashes"
<add>require "update_migrator/cache_entries_to_symlinks"
<add>require "update_migrator/legacy_cache"
<add>require "update_migrator/legacy_keg_symlinks"
<add>require "update_migrator/legacy_repository"
<add>
<add>module UpdateMigrator
<add> module_function
<add>
<add> def formula_resources(formula)
<add> specs = [formula.stable, formula.devel, formula.head].compact
<add>
<add> [*formula.bottle&.resource] + specs.flat_map do |spec|
<add> [
<add> spec,
<add> *spec.resources.values,
<add> *spec.patches.select(&:external?).map(&:resource),
<add> ]
<add> end
<add> end
<add>
<add> def parse_extname(url)
<add> uri_path = if URI::DEFAULT_PARSER.make_regexp =~ url
<add> uri = URI(url)
<add> uri.query ? "#{uri.path}?#{uri.query}" : uri.path
<add> else
<add> url
<add> end
<add>
<add> # Given a URL like https://example.com/download.php?file=foo-1.0.tar.gz
<add> # the extension we want is ".tar.gz", not ".php".
<add> Pathname.new(uri_path).ascend do |path|
<add> ext = path.extname[/[^?&]+/]
<add> return ext if ext
<add> end
<add>
<add> nil
<add> end
<add>end
<ide><path>Library/Homebrew/update_migrator/cache_entries_to_double_dashes.rb
<add>module UpdateMigrator
<add> module_function
<add>
<add> def migrate_cache_entries_to_double_dashes(initial_version)
<add> return if initial_version && initial_version > "1.7.1"
<add>
<add> return if ENV.key?("HOMEBREW_DISABLE_LOAD_FORMULA")
<add>
<add> ohai "Migrating cache entries..."
<add>
<add> Formula.each do |formula|
<add> formula_resources(formula).each do |resource|
<add> downloader = resource.downloader
<add>
<add> url = downloader.url
<add> name = resource.download_name
<add> version = resource.version
<add>
<add> extname = parse_extname(url)
<add> old_location = downloader.cache/"#{name}-#{version}#{extname}"
<add> new_location = downloader.cache/"#{name}--#{version}#{extname}"
<add>
<add> next unless old_location.file?
<add>
<add> if new_location.exist?
<add> begin
<add> FileUtils.rm_rf old_location
<add> rescue Errno::EACCES
<add> opoo "Could not remove #{old_location}, please do so manually."
<add> end
<add> else
<add> begin
<add> FileUtils.mv old_location, new_location
<add> rescue Errno::EACCES
<add> opoo "Could not move #{old_location} to #{new_location}, please do so manually."
<add> end
<add> end
<add> end
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/update_migrator/cache_entries_to_symlinks.rb
<add>require "hbc/cask_loader"
<add>require "hbc/download"
<add>
<add>module UpdateMigrator
<add> module_function
<add>
<add> def migrate_cache_entries_to_symlinks(initial_version)
<add> return if initial_version && initial_version > "1.7.2"
<add>
<add> return if ENV.key?("HOMEBREW_DISABLE_LOAD_FORMULA")
<add>
<add> ohai "Migrating cache entries..."
<add>
<add> load_formula = lambda do |formula|
<add> begin
<add> Formula[formula]
<add> rescue FormulaUnavailableError
<add> nil
<add> end
<add> end
<add>
<add> load_cask = lambda do |cask|
<add> begin
<add> Hbc::CaskLoader.load(cask)
<add> rescue Hbc::CaskUnavailableError
<add> nil
<add> end
<add> end
<add>
<add> formula_downloaders = if HOMEBREW_CACHE.directory?
<add> HOMEBREW_CACHE.children
<add> .select(&:file?)
<add> .map { |child| child.basename.to_s.sub(/\-\-.*/, "") }
<add> .uniq
<add> .map(&load_formula)
<add> .compact
<add> .flat_map { |formula| formula_resources(formula) }
<add> .map { |resource| [resource.downloader, resource.download_name, resource.version] }
<add> else
<add> []
<add> end
<add>
<add> cask_downloaders = if (HOMEBREW_CACHE/"Cask").directory?
<add> (HOMEBREW_CACHE/"Cask").children
<add> .map { |child| child.basename.to_s.sub(/\-\-.*/, "") }
<add> .uniq
<add> .map(&load_cask)
<add> .compact
<add> .map { |cask| [Hbc::Download.new(cask).downloader, cask.token, cask.version] }
<add> else
<add> []
<add> end
<add>
<add> downloaders = formula_downloaders + cask_downloaders
<add>
<add> downloaders.each do |downloader, name, version|
<add> next unless downloader.respond_to?(:symlink_location)
<add>
<add> url = downloader.url
<add> extname = parse_extname(url)
<add> old_location = downloader.cache/"#{name}--#{version}#{extname}"
<add> next unless old_location.file?
<add>
<add> new_symlink_location = downloader.symlink_location
<add> new_location = downloader.cached_location
<add>
<add> if new_location.exist? && new_symlink_location.symlink?
<add> begin
<add> FileUtils.rm_rf old_location unless old_location == new_symlink_location
<add> rescue Errno::EACCES
<add> opoo "Could not remove #{old_location}, please do so manually."
<add> end
<add> else
<add> begin
<add> new_location.dirname.mkpath
<add> if new_location.exist?
<add> FileUtils.rm_rf old_location
<add> else
<add> FileUtils.mv old_location, new_location
<add> end
<add> symlink_target = new_location.relative_path_from(new_symlink_location.dirname)
<add> new_symlink_location.dirname.mkpath
<add> FileUtils.ln_s symlink_target, new_symlink_location, force: true
<add> rescue Errno::EACCES
<add> opoo "Could not move #{old_location} to #{new_location}, please do so manually."
<add> end
<add> end
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/update_migrator/legacy_cache.rb
<add>module UpdateMigrator
<add> module_function
<add>
<add> def migrate_legacy_cache_if_necessary
<add> legacy_cache = Pathname.new "/Library/Caches/Homebrew"
<add> return if HOMEBREW_CACHE.to_s == legacy_cache.to_s
<add> return unless legacy_cache.directory?
<add> return unless legacy_cache.readable_real?
<add>
<add> migration_attempted_file = legacy_cache/".migration_attempted"
<add> return if migration_attempted_file.exist?
<add>
<add> return unless legacy_cache.writable_real?
<add> FileUtils.touch migration_attempted_file
<add>
<add> # This directory could have been compromised if it's world-writable/
<add> # a symlink/owned by another user so don't copy files in those cases.
<add> world_writable = legacy_cache.stat.mode & 0777 == 0777
<add> return if world_writable
<add> return if legacy_cache.symlink?
<add> return if !legacy_cache.owned? && legacy_cache.lstat.uid.nonzero?
<add>
<add> ohai "Migrating #{legacy_cache} to #{HOMEBREW_CACHE}..."
<add> HOMEBREW_CACHE.mkpath
<add> legacy_cache.cd do
<add> legacy_cache.entries.each do |f|
<add> next if [".", "..", ".migration_attempted"].include? f.to_s
<add> begin
<add> FileUtils.cp_r f, HOMEBREW_CACHE
<add> rescue
<add> @migration_failed ||= true
<add> end
<add> end
<add> end
<add>
<add> if @migration_failed
<add> opoo <<~EOS
<add> Failed to migrate #{legacy_cache} to
<add> #{HOMEBREW_CACHE}. Please do so manually.
<add> EOS
<add> else
<add> ohai "Deleting #{legacy_cache}..."
<add> FileUtils.rm_rf legacy_cache
<add> if legacy_cache.exist?
<add> FileUtils.touch migration_attempted_file
<add> opoo <<~EOS
<add> Failed to delete #{legacy_cache}.
<add> Please do so manually.
<add> EOS
<add> end
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/update_migrator/legacy_keg_symlinks.rb
<add>module UpdateMigrator
<add> module_function
<add>
<add> def migrate_legacy_keg_symlinks_if_necessary
<add> legacy_linked_kegs = HOMEBREW_LIBRARY/"LinkedKegs"
<add> return unless legacy_linked_kegs.directory?
<add>
<add> HOMEBREW_LINKED_KEGS.mkpath unless legacy_linked_kegs.children.empty?
<add> legacy_linked_kegs.children.each do |link|
<add> name = link.basename.to_s
<add> src = begin
<add> link.realpath
<add> rescue Errno::ENOENT
<add> begin
<add> (HOMEBREW_PREFIX/"opt/#{name}").realpath
<add> rescue Errno::ENOENT
<add> begin
<add> Formulary.factory(name).installed_prefix
<add> rescue
<add> next
<add> end
<add> end
<add> end
<add> dst = HOMEBREW_LINKED_KEGS/name
<add> dst.unlink if dst.exist?
<add> FileUtils.ln_sf(src.relative_path_from(dst.parent), dst)
<add> end
<add> FileUtils.rm_rf legacy_linked_kegs
<add>
<add> legacy_pinned_kegs = HOMEBREW_LIBRARY/"PinnedKegs"
<add> return unless legacy_pinned_kegs.directory?
<add>
<add> HOMEBREW_PINNED_KEGS.mkpath unless legacy_pinned_kegs.children.empty?
<add> legacy_pinned_kegs.children.each do |link|
<add> name = link.basename.to_s
<add> src = link.realpath
<add> dst = HOMEBREW_PINNED_KEGS/name
<add> FileUtils.ln_sf(src.relative_path_from(dst.parent), dst)
<add> end
<add> FileUtils.rm_rf legacy_pinned_kegs
<add> end
<add>end
<ide><path>Library/Homebrew/update_migrator/legacy_repository.rb
<add>module UpdateMigrator
<add> module_function
<add>
<add> def migrate_legacy_repository_if_necessary
<add> return unless HOMEBREW_PREFIX.to_s == "/usr/local"
<add> return unless HOMEBREW_REPOSITORY.to_s == "/usr/local"
<add>
<add> ohai "Migrating HOMEBREW_REPOSITORY (please wait)..."
<add>
<add> unless HOMEBREW_PREFIX.writable_real?
<add> ofail <<~EOS
<add> #{HOMEBREW_PREFIX} is not writable.
<add>
<add> You should change the ownership and permissions of #{HOMEBREW_PREFIX}
<add> temporarily back to your user account so we can complete the Homebrew
<add> repository migration:
<add> sudo chown -R $(whoami) #{HOMEBREW_PREFIX}
<add> EOS
<add> return
<add> end
<add>
<add> new_homebrew_repository = Pathname.new "/usr/local/Homebrew"
<add> new_homebrew_repository.rmdir_if_possible
<add> if new_homebrew_repository.exist?
<add> ofail <<~EOS
<add> #{new_homebrew_repository} already exists.
<add> Please remove it manually or uninstall and reinstall Homebrew into a new
<add> location as the migration cannot be done automatically.
<add> EOS
<add> return
<add> end
<add> new_homebrew_repository.mkpath
<add>
<add> repo_files = HOMEBREW_REPOSITORY.cd do
<add> Utils.popen_read("git ls-files").lines.map(&:chomp)
<add> end
<add>
<add> unless Utils.popen_read("git status --untracked-files=all --porcelain").empty?
<add> HOMEBREW_REPOSITORY.cd do
<add> quiet_system "git", "merge", "--abort"
<add> quiet_system "git", "rebase", "--abort"
<add> quiet_system "git", "reset", "--mixed"
<add> safe_system "git", "-c", "user.email=brew-update@localhost",
<add> "-c", "user.name=brew update",
<add> "stash", "save", "--include-untracked"
<add> end
<add> stashed = true
<add> end
<add>
<add> FileUtils.cp_r "#{HOMEBREW_REPOSITORY}/.git", "#{new_homebrew_repository}/.git"
<add> new_homebrew_repository.cd do
<add> safe_system "git", "checkout", "--force", "."
<add> safe_system "git", "stash", "pop" if stashed
<add> end
<add>
<add> if (HOMEBREW_REPOSITORY/"Library/Locks").exist?
<add> FileUtils.cp_r "#{HOMEBREW_REPOSITORY}/Library/Locks", "#{new_homebrew_repository}/Library/Locks"
<add> end
<add>
<add> if (HOMEBREW_REPOSITORY/"Library/Taps").exist?
<add> FileUtils.cp_r "#{HOMEBREW_REPOSITORY}/Library/Taps", "#{new_homebrew_repository}/Library/Taps"
<add> end
<add>
<add> unremovable_paths = []
<add> extra_remove_paths = [".git", "Library/Locks", "Library/Taps",
<add> "Library/Homebrew/cask", "Library/Homebrew/test"]
<add> (repo_files + extra_remove_paths).each do |file|
<add> path = Pathname.new "#{HOMEBREW_REPOSITORY}/#{file}"
<add> begin
<add> FileUtils.rm_rf path
<add> rescue Errno::EACCES
<add> unremovable_paths << path
<add> end
<add> quiet_system "rmdir", "-p", path.parent if path.parent.exist?
<add> end
<add>
<add> unless unremovable_paths.empty?
<add> ofail <<~EOS
<add> Could not remove old HOMEBREW_REPOSITORY paths!
<add> Please do this manually with:
<add> sudo rm -rf #{unremovable_paths.join " "}
<add> EOS
<add> end
<add>
<add> (Keg::ALL_TOP_LEVEL_DIRECTORIES + ["Cellar"]).each do |dir|
<add> FileUtils.mkdir_p "#{HOMEBREW_PREFIX}/#{dir}"
<add> end
<add>
<add> src = Pathname.new("#{new_homebrew_repository}/bin/brew")
<add> dst = Pathname.new("#{HOMEBREW_PREFIX}/bin/brew")
<add> begin
<add> FileUtils.ln_s(src.relative_path_from(dst.parent), dst)
<add> rescue Errno::EACCES, Errno::ENOENT
<add> ofail <<~EOS
<add> Could not create symlink at #{dst}!
<add> Please do this manually with:
<add> sudo ln -sf #{src} #{dst}
<add> sudo chown $(whoami) #{dst}
<add> EOS
<add> end
<add>
<add> link_completions_manpages_and_docs(new_homebrew_repository)
<add>
<add> ohai "Migrated HOMEBREW_REPOSITORY to #{new_homebrew_repository}!"
<add> puts <<~EOS
<add> Homebrew no longer needs to have ownership of /usr/local. If you wish you can
<add> return /usr/local to its default ownership with:
<add> sudo chown root:wheel #{HOMEBREW_PREFIX}
<add> EOS
<add> rescue => e
<add> ofail <<~EOS
<add> #{Tty.bold}Failed to migrate HOMEBREW_REPOSITORY to #{new_homebrew_repository}!#{Tty.reset}
<add> The error was:
<add> #{e}
<add> Please try to resolve this error yourself and then run `brew update` again to
<add> complete the migration. If you need help please +1 an existing error or comment
<add> with your new error in issue:
<add> #{Formatter.url("https://github.com/Homebrew/brew/issues/987")}
<add> EOS
<add> $stderr.puts e.backtrace
<add> end
<add>end
<ide><path>Library/Homebrew/utils.rb
<ide> def truncate_text_to_approximate_size(s, max_bytes, options = {})
<ide> out
<ide> end
<ide>
<del>def migrate_legacy_keg_symlinks_if_necessary
<del> legacy_linked_kegs = HOMEBREW_LIBRARY/"LinkedKegs"
<del> return unless legacy_linked_kegs.directory?
<del>
<del> HOMEBREW_LINKED_KEGS.mkpath unless legacy_linked_kegs.children.empty?
<del> legacy_linked_kegs.children.each do |link|
<del> name = link.basename.to_s
<del> src = begin
<del> link.realpath
<del> rescue Errno::ENOENT
<del> begin
<del> (HOMEBREW_PREFIX/"opt/#{name}").realpath
<del> rescue Errno::ENOENT
<del> begin
<del> Formulary.factory(name).installed_prefix
<del> rescue
<del> next
<del> end
<del> end
<del> end
<del> dst = HOMEBREW_LINKED_KEGS/name
<del> dst.unlink if dst.exist?
<del> FileUtils.ln_sf(src.relative_path_from(dst.parent), dst)
<del> end
<del> FileUtils.rm_rf legacy_linked_kegs
<del>
<del> legacy_pinned_kegs = HOMEBREW_LIBRARY/"PinnedKegs"
<del> return unless legacy_pinned_kegs.directory?
<del>
<del> HOMEBREW_PINNED_KEGS.mkpath unless legacy_pinned_kegs.children.empty?
<del> legacy_pinned_kegs.children.each do |link|
<del> name = link.basename.to_s
<del> src = link.realpath
<del> dst = HOMEBREW_PINNED_KEGS/name
<del> FileUtils.ln_sf(src.relative_path_from(dst.parent), dst)
<del> end
<del> FileUtils.rm_rf legacy_pinned_kegs
<del>end
<del>
<ide> # Calls the given block with the passed environment variables
<ide> # added to ENV, then restores ENV afterwards.
<ide> # Example: | 10 |
Text | Text | add alternate way of creating array | cecb7d9adfdac4979a8bb1d31be2a9d34a954691 | <ide><path>guide/english/ruby/ruby-arrays/index.md
<ide> An array represents a list of values. The individual values are often called "el
<ide> my_array = [1, 2, 3, 4, 5]
<ide> ```
<ide>
<add>You can also create an empty array by using the 'new' method in the 'Array' class:
<add>
<add>```ruby
<add>my_array = Array.new
<add>```
<add>
<ide> That first example is an array of numbers, but a Ruby array can contain values of different types, even other arrays:
<ide>
<ide> ```ruby | 1 |
Text | Text | deprecate ios 9 in readme | d1265077d6638bb9219180628caf6ff83f8d6019 | <ide><path>README.md
<ide> React Native is developed and supported by many companies and individual core co
<ide>
<ide> ## 📋 Requirements
<ide>
<del>React Native apps may target iOS 9.0 and Android 4.1 (API 16) or newer. You may use Windows, macOS, or Linux as your development operating system, though building and running iOS apps is limited to macOS. Tools like [Expo](https://expo.io) can be used to work around this.
<add>React Native apps may target iOS 10.0 and Android 4.1 (API 16) or newer. You may use Windows, macOS, or Linux as your development operating system, though building and running iOS apps is limited to macOS. Tools like [Expo](https://expo.io) can be used to work around this.
<ide>
<ide> ## 🎉 Building your first React Native app
<ide> | 1 |
Ruby | Ruby | pass log_rescued_responses as environment config | d6b66ebb6ebd66f6699c3c10f5417f02a2b0129f | <ide><path>actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
<ide> module ActionDispatch
<ide> # This middleware is responsible for logging exceptions and
<ide> # showing a debugging page in case the request is local.
<ide> class DebugExceptions
<del> cattr_accessor :log_rescued_responses, instance_accessor: false, default: true
<ide> cattr_reader :interceptors, instance_accessor: false, default: []
<ide>
<ide> def self.register_interceptor(object = nil, &block)
<ide> def api_request?(content_type)
<ide> end
<ide>
<ide> def log_rescued_responses?(request)
<del> per_request = request.get_header("action_dispatch.log_rescued_responses")
<del> per_request.nil? ? @@log_rescued_responses : per_request
<add> request.get_header("action_dispatch.log_rescued_responses")
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/lib/action_dispatch/railtie.rb
<ide> class Railtie < Rails::Railtie # :nodoc:
<ide> self.ignore_accept_header = app.config.action_dispatch.ignore_accept_header
<ide> self.return_only_media_type_on_content_type = app.config.action_dispatch.return_only_request_media_type_on_content_type
<ide> ActionDispatch::Request::Utils.perform_deep_munge = app.config.action_dispatch.perform_deep_munge
<del> ActionDispatch::DebugExceptions.log_rescued_responses = app.config.action_dispatch.log_rescued_responses
<ide> end
<ide>
<ide> ActiveSupport.on_load(:action_dispatch_response) do
<ide><path>actionpack/test/dispatch/debug_exceptions_test.rb
<ide> def call(env)
<ide> backtrace_cleaner = ActiveSupport::BacktraceCleaner.new
<ide> backtrace_cleaner.add_silencer { true }
<ide>
<del> env = { "action_dispatch.show_exceptions" => true,
<del> "action_dispatch.logger" => Logger.new(output),
<del> "action_dispatch.backtrace_cleaner" => backtrace_cleaner }
<add> env = { "action_dispatch.show_exceptions" => true,
<add> "action_dispatch.logger" => Logger.new(output),
<add> "action_dispatch.log_rescued_responses" => true,
<add> "action_dispatch.backtrace_cleaner" => backtrace_cleaner }
<ide>
<ide> assert_raises ActionController::RoutingError do
<ide> get "/pass", headers: env
<ide> def call(env)
<ide> backtrace_cleaner.add_silencer { true }
<ide>
<ide> env = { "Accept" => "text/html,*",
<del> "action_dispatch.show_exceptions" => true,
<del> "action_dispatch.logger" => Logger.new(output),
<del> "action_dispatch.backtrace_cleaner" => backtrace_cleaner }
<add> "action_dispatch.show_exceptions" => true,
<add> "action_dispatch.logger" => Logger.new(output),
<add> "action_dispatch.log_rescued_responses" => true,
<add> "action_dispatch.backtrace_cleaner" => backtrace_cleaner }
<ide>
<ide> assert_raises ActionDispatch::Http::MimeNegotiation::InvalidType do
<ide> get "/invalid_mimetype", headers: env
<ide> def call(env)
<ide> assert_equal 3, log.lines.count
<ide> end
<ide>
<del> test "skips logging when rescued" do
<add> test "skips logging when rescued and log_rescued_responses is false" do
<ide> @app = DevelopmentApp
<ide>
<ide> output = StringIO.new
<ide> def call(env)
<ide> assert_empty (output.rewind && output.read).lines
<ide> end
<ide>
<add> test "does not skip logging when rescued and log_rescued_responses is true" do
<add> @app = DevelopmentApp
<add>
<add> output = StringIO.new
<add>
<add> env = { "action_dispatch.show_exceptions" => true,
<add> "action_dispatch.logger" => Logger.new(output),
<add> "action_dispatch.log_rescued_responses" => true }
<add>
<add> get "/parameter_missing", headers: env
<add> assert_response 400
<add> assert_not_empty (output.rewind && output.read).lines
<add> end
<add>
<ide> test "display backtrace when error type is SyntaxError" do
<ide> @app = DevelopmentApp
<ide>
<ide><path>railties/lib/rails/application.rb
<ide> def env_config
<ide> "action_dispatch.secret_key_base" => secret_key_base,
<ide> "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions,
<ide> "action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local,
<add> "action_dispatch.log_rescued_responses" => config.action_dispatch.log_rescued_responses,
<ide> "action_dispatch.logger" => Rails.logger,
<ide> "action_dispatch.backtrace_cleaner" => Rails.backtrace_cleaner,
<ide> "action_dispatch.key_generator" => key_generator,
<ide><path>railties/test/application/configuration_test.rb
<ide> class MyLogger < ::Logger
<ide> assert_equal false, ActionDispatch::Request.return_only_media_type_on_content_type
<ide> end
<ide>
<del> test "ActionDispatch::DebugExceptions.log_rescued_responses is true by default" do
<add> test "action_dispatch.log_rescued_responses is true by default" do
<ide> app "development"
<ide>
<del> assert_equal true, ActionDispatch::DebugExceptions.log_rescued_responses
<add> assert_equal true, Rails.application.env_config["action_dispatch.log_rescued_responses"]
<ide> end
<ide>
<del> test "ActionDispatch::DebugExceptions.log_rescued_responses can be configured" do
<add> test "action_dispatch.log_rescued_responses can be configured" do
<ide> add_to_config <<-RUBY
<ide> config.action_dispatch.log_rescued_responses = false
<ide> RUBY
<ide>
<ide> app "development"
<ide>
<del> assert_equal false, ActionDispatch::DebugExceptions.log_rescued_responses
<add> assert_equal false, Rails.application.env_config["action_dispatch.log_rescued_responses"]
<ide> end
<ide>
<ide> test "logs a warning when running SQLite3 in production" do | 5 |
Ruby | Ruby | pass the template format to the digestor | 1581cab9ff26731ed03a17f7ddec3c85d536988a | <ide><path>actionpack/lib/action_controller/metal/etag_with_template_digest.rb
<ide> def pick_template_for_etag(options)
<ide> end
<ide>
<ide> def lookup_and_digest_template(template)
<del> ActionView::Digestor.digest name: template, finder: lookup_context
<add> ActionView::Digestor.digest name: template, format: nil, finder: lookup_context
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/test/controller/caching_test.rb
<ide> def test_fragment_caching
<ide> assert_equal expected_body, @response.body
<ide>
<ide> assert_equal "This bit's fragment cached",
<del> @store.read("views/functional_caching/fragment_cached:#{template_digest("functional_caching/fragment_cached")}/fragment")
<add> @store.read("views/functional_caching/fragment_cached:#{template_digest("functional_caching/fragment_cached", "html")}/fragment")
<ide> end
<ide>
<ide> def test_fragment_caching_in_partials
<ide> def test_fragment_caching_in_partials
<ide> assert_match(/Old fragment caching in a partial/, @response.body)
<ide>
<ide> assert_match("Old fragment caching in a partial",
<del> @store.read("views/functional_caching/_partial:#{template_digest("functional_caching/_partial")}/test.host/functional_caching/html_fragment_cached_with_partial"))
<add> @store.read("views/functional_caching/_partial:#{template_digest("functional_caching/_partial", "html")}/test.host/functional_caching/html_fragment_cached_with_partial"))
<ide> end
<ide>
<ide> def test_skipping_fragment_cache_digesting
<ide> def test_render_inline_before_fragment_caching
<ide> assert_match(/Some inline content/, @response.body)
<ide> assert_match(/Some cached content/, @response.body)
<ide> assert_match("Some cached content",
<del> @store.read("views/functional_caching/inline_fragment_cached:#{template_digest("functional_caching/inline_fragment_cached")}/test.host/functional_caching/inline_fragment_cached"))
<add> @store.read("views/functional_caching/inline_fragment_cached:#{template_digest("functional_caching/inline_fragment_cached", "html")}/test.host/functional_caching/inline_fragment_cached"))
<ide> end
<ide>
<ide> def test_fragment_cache_instrumentation
<ide> def test_fragment_cache_instrumentation
<ide> end
<ide>
<ide> def test_html_formatted_fragment_caching
<del> get :formatted_fragment_cached, format: "html"
<add> format = "html"
<add> get :formatted_fragment_cached, format: format
<ide> assert_response :success
<ide> expected_body = "<body>\n<p>ERB</p>\n</body>\n"
<ide>
<ide> assert_equal expected_body, @response.body
<ide>
<ide> assert_equal "<p>ERB</p>",
<del> @store.read("views/functional_caching/formatted_fragment_cached:#{template_digest("functional_caching/formatted_fragment_cached")}/fragment")
<add> @store.read("views/functional_caching/formatted_fragment_cached:#{template_digest("functional_caching/formatted_fragment_cached", format)}/fragment")
<ide> end
<ide>
<ide> def test_xml_formatted_fragment_caching
<del> get :formatted_fragment_cached, format: "xml"
<add> format = "xml"
<add> get :formatted_fragment_cached, format: format
<ide> assert_response :success
<ide> expected_body = "<body>\n <p>Builder</p>\n</body>\n"
<ide>
<ide> assert_equal expected_body, @response.body
<ide>
<ide> assert_equal " <p>Builder</p>\n",
<del> @store.read("views/functional_caching/formatted_fragment_cached:#{template_digest("functional_caching/formatted_fragment_cached")}/fragment")
<add> @store.read("views/functional_caching/formatted_fragment_cached:#{template_digest("functional_caching/formatted_fragment_cached", format)}/fragment")
<ide> end
<ide>
<ide> def test_fragment_caching_with_variant
<del> get :formatted_fragment_cached_with_variant, format: "html", params: { v: :phone }
<add> format = "html"
<add> get :formatted_fragment_cached_with_variant, format: format, params: { v: :phone }
<ide> assert_response :success
<ide> expected_body = "<body>\n<p>PHONE</p>\n</body>\n"
<ide>
<ide> assert_equal expected_body, @response.body
<ide>
<ide> assert_equal "<p>PHONE</p>",
<del> @store.read("views/functional_caching/formatted_fragment_cached_with_variant:#{template_digest("functional_caching/formatted_fragment_cached_with_variant")}/fragment")
<add> @store.read("views/functional_caching/formatted_fragment_cached_with_variant:#{template_digest("functional_caching/formatted_fragment_cached_with_variant", format)}/fragment")
<ide> end
<ide>
<ide> def test_fragment_caching_with_html_partials_in_xml
<ide> def test_fragment_caching_with_html_partials_in_xml
<ide> end
<ide>
<ide> private
<del> def template_digest(name)
<del> ActionView::Digestor.digest(name: name, finder: @controller.lookup_context)
<add> def template_digest(name, format)
<add> ActionView::Digestor.digest(name: name, format: format, finder: @controller.lookup_context)
<ide> end
<ide> end
<ide>
<ide><path>actionview/lib/action_view/base.rb
<ide> def initialize(lookup_context = nil, assigns = {}, controller = nil, formats = N
<ide> end
<ide>
<ide> @view_renderer = ActionView::Renderer.new @lookup_context
<add> @current_template = nil
<ide>
<ide> @cache_hit = {}
<ide> assign(assigns)
<ide> assign_controller(controller)
<ide> _prepare_context
<ide> end
<ide>
<del> def run(method, locals, buffer, &block)
<del> _old_output_buffer, _old_virtual_path = @output_buffer, @virtual_path
<add> def run(method, template, locals, buffer, &block)
<add> _old_output_buffer, _old_virtual_path, _old_template = @output_buffer, @virtual_path, @current_template
<add> @current_template = template
<ide> @output_buffer = buffer
<ide> send(method, locals, buffer, &block)
<ide> ensure
<del> @output_buffer, @virtual_path = _old_output_buffer, _old_virtual_path
<add> @output_buffer, @virtual_path, @current_template = _old_output_buffer, _old_virtual_path, _old_template
<ide> end
<ide>
<ide> def compiled_method_container
<ide><path>actionview/lib/action_view/digestor.rb
<ide> class << self
<ide> # * <tt>name</tt> - Template name
<ide> # * <tt>finder</tt> - An instance of <tt>ActionView::LookupContext</tt>
<ide> # * <tt>dependencies</tt> - An array of dependent views
<del> def digest(name:, finder:, dependencies: nil)
<add> def digest(name:, format:, finder:, dependencies: nil)
<ide> if dependencies.nil? || dependencies.empty?
<del> cache_key = "#{name}.#{finder.rendered_format}"
<add> cache_key = "#{name}.#{format}"
<ide> else
<del> cache_key = [ name, finder.rendered_format, dependencies ].flatten.compact.join(".")
<add> cache_key = [ name, format, dependencies ].flatten.compact.join(".")
<ide> end
<ide>
<ide> # this is a correctly done double-checked locking idiom
<ide> def tree(name, finder, partial = false, seen = {})
<ide> private
<ide> def find_template(finder, name, prefixes, partial, keys)
<ide> finder.disable_cache do
<del> format = finder.rendered_format
<del> result = finder.find_all(name, prefixes, partial, keys, formats: [format]).first if format
<del> result || finder.find_all(name, prefixes, partial, keys).first
<add> finder.find_all(name, prefixes, partial, keys).first
<ide> end
<ide> end
<ide> end
<ide><path>actionview/lib/action_view/helpers/cache_helper.rb
<ide> def cache_fragment_name(name = {}, skip_digest: nil, virtual_path: nil, digest_p
<ide> end
<ide> end
<ide>
<del> def digest_path_from_virtual(virtual_path) # :nodoc:
<del> digest = Digestor.digest(name: virtual_path, finder: lookup_context, dependencies: view_cache_dependencies)
<add> def digest_path_from_template(template) # :nodoc:
<add> digest = Digestor.digest(name: template.virtual_path, format: template.formats.first, finder: lookup_context, dependencies: view_cache_dependencies)
<ide>
<ide> if digest.present?
<del> "#{virtual_path}:#{digest}"
<add> "#{template.virtual_path}:#{digest}"
<ide> else
<del> virtual_path
<add> template.virtual_path
<ide> end
<ide> end
<ide>
<ide> def fragment_name_with_digest(name, virtual_path, digest_path)
<ide> if virtual_path || digest_path
<ide> name = controller.url_for(name).split("://").last if name.is_a?(Hash)
<ide>
<del> digest_path ||= digest_path_from_virtual(virtual_path)
<add> digest_path ||= digest_path_from_template(@current_template)
<ide>
<ide> [ digest_path, name ]
<ide> else
<ide><path>actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb
<ide> def callable_cache_key?
<ide> def collection_by_cache_keys(view, template)
<ide> seed = callable_cache_key? ? @options[:cached] : ->(i) { i }
<ide>
<del> digest_path = view.digest_path_from_virtual(template.virtual_path)
<add> digest_path = view.digest_path_from_template(template)
<ide>
<ide> @collection.each_with_object({}) do |item, hash|
<ide> hash[expanded_cache_key(seed.call(item), view, template, digest_path)] = item
<ide><path>actionview/lib/action_view/template.rb
<ide> def supports_streaming?
<ide> def render(view, locals, buffer = ActionView::OutputBuffer.new, &block)
<ide> instrument_render_template do
<ide> compile!(view)
<del> view.run(method_name, locals, buffer, &block)
<add> view.run(method_name, self, locals, buffer, &block)
<ide> end
<ide> rescue => e
<ide> handle_render_error(view, e)
<ide><path>actionview/lib/action_view/template/handlers/erb/erubi.rb
<ide> def evaluate(action_view_erb_handler_context)
<ide> include action_view_erb_handler_context._routes.url_helpers
<ide> class_eval("define_method(:_template) { |local_assigns, output_buffer| #{src} }", @filename || "(erubi)", 0)
<ide> }.empty
<del> view.run(:_template, {}, ActionView::OutputBuffer.new)
<add> view.run(:_template, nil, {}, ActionView::OutputBuffer.new)
<ide> end
<ide>
<ide> private
<ide><path>actionview/test/activerecord/relation_cache_test.rb
<ide> def setup
<ide> lookup_context = ActionView::LookupContext.new(view_paths, {}, ["test"])
<ide> @view_renderer = ActionView::Renderer.new(lookup_context)
<ide> @virtual_path = "path"
<add> @current_template = lookup_context.find "test/hello_world"
<ide>
<ide> controller.cache_store = ActiveSupport::Cache::MemoryStore.new
<ide> end
<ide>
<ide> def test_cache_relation_other
<ide> cache(Project.all) { concat("Hello World") }
<del> assert_equal "Hello World", controller.cache_store.read("views/path/projects-#{Project.count}")
<add> assert_equal "Hello World", controller.cache_store.read("views/test/hello_world:fa9482a68ce25bf7589b8eddad72f736/projects-#{Project.count}")
<ide> end
<ide>
<ide> def view_cache_dependencies; []; end
<ide><path>actionview/test/template/digestor_test.rb
<ide> class FixtureFinder < ActionView::LookupContext
<ide> FIXTURES_DIR = File.expand_path("../fixtures/digestor", __dir__)
<ide>
<del> def initialize(details = {})
<del> super(ActionView::PathSet.new(["digestor", "digestor/api"]), details, [])
<del> @rendered_format = :html
<add> def self.build(details = {})
<add> new(ActionView::PathSet.new(["digestor", "digestor/api"]), details, [])
<ide> end
<ide> end
<ide>
<ide> def test_nested_template_deps
<ide> end
<ide>
<ide> def test_nested_template_deps_with_non_default_rendered_format
<del> finder.rendered_format = nil
<ide> nested_deps = [{ "comments/comments" => ["comments/comment"] }]
<ide> assert_equal nested_deps, nested_dependencies("messages/thread")
<ide> end
<ide>
<ide> def test_template_formats_of_nested_deps_with_non_default_rendered_format
<del> finder.rendered_format = nil
<add> @finder = finder.with_prepended_formats([:json])
<ide> assert_equal [:json], tree_template_formats("messages/thread").uniq
<ide> end
<ide>
<ide> def test_template_formats_of_dependencies_with_same_logical_name_and_different_r
<ide> end
<ide>
<ide> def test_template_dependencies_with_fallback_from_js_to_html_format
<del> finder.rendered_format = :js
<ide> assert_equal ["comments/comment"], dependencies("comments/show")
<ide> end
<ide>
<ide> def test_template_digest_with_fallback_from_js_to_html_format
<del> finder.rendered_format = :js
<ide> assert_digest_difference("comments/show") do
<ide> change_template("comments/_comment")
<ide> end
<ide> def test_collection_derived_from_record_dependency
<ide>
<ide> def test_details_are_included_in_cache_key
<ide> # Cache the template digest.
<del> @finder = FixtureFinder.new(formats: [:html])
<add> @finder = FixtureFinder.build(formats: [:html])
<ide> old_digest = digest("events/_event")
<ide>
<ide> # Change the template; the cached digest remains unchanged.
<ide> change_template("events/_event")
<ide>
<ide> # The details are changed, so a new cache key is generated.
<del> @finder = FixtureFinder.new
<add> @finder = FixtureFinder.build
<ide>
<ide> # The cache is busted.
<ide> assert_not_equal old_digest, digest("events/_event")
<ide> def digest(template_name, options = {})
<ide> finder_options = options.extract!(:variants, :format)
<ide>
<ide> finder.variants = finder_options[:variants] || []
<del> finder.rendered_format = finder_options[:format] if finder_options[:format]
<ide>
<del> ActionView::Digestor.digest(name: template_name, finder: finder, dependencies: (options[:dependencies] || []))
<add> finder_with_formats = if finder_options[:format]
<add> finder.with_prepended_formats(Array(finder_options[:format]))
<add> else
<add> finder
<add> end
<add>
<add> ActionView::Digestor.digest(name: template_name, format: finder_options[:format], finder: finder_with_formats, dependencies: (options[:dependencies] || []))
<ide> end
<ide>
<ide> def dependencies(template_name)
<ide> def disable_resolver_caching
<ide> end
<ide>
<ide> def finder
<del> @finder ||= FixtureFinder.new
<add> @finder ||= FixtureFinder.build
<ide> end
<ide>
<ide> def change_template(template_name, variant = nil)
<ide><path>actionview/test/template/render_test.rb
<ide> def b.to_partial_path; "test/partial_iteration_2"; end
<ide>
<ide> private
<ide> def cache_key(*names, virtual_path)
<del> digest = ActionView::Digestor.digest name: virtual_path, finder: @view.lookup_context, dependencies: []
<add> digest = ActionView::Digestor.digest name: virtual_path, format: :html, finder: @view.lookup_context, dependencies: []
<ide> @view.combined_fragment_cache_key([ "#{virtual_path}:#{digest}", *names ])
<ide> end
<ide> end | 11 |
Javascript | Javascript | simplify wording+improve grammar | 1bd451d0825bdbeb52bcc7d66838909ef7afe3df | <ide><path>src/loader.js
<ide> function setupModuleLoader(window) {
<ide> * All modules (angular core or 3rd party) that should be available to an application must be
<ide> * registered using this mechanism.
<ide> *
<del> * When passed two or more arguments, a new module is created. If passed only one argument, an
<del> * existing module (the name passed as the first argument to `module`) is retrieved.
<add> * Passing one argument retrieves an existing {@link angular.Module},
<add> * whereas passing more than one argument creates a new {@link angular.Module}
<ide> *
<ide> *
<ide> * # Module | 1 |
Ruby | Ruby | grab files in subdirectories too | 34c1a6f850261022ceca4c09faef1e3124bfcf40 | <ide><path>Library/Homebrew/cmd/gist-logs.rb
<ide> def noecho_gets
<ide> result
<ide> end
<ide>
<del> def load_logs(dir)
<add> def load_logs(dir, basedir = dir)
<ide> logs = {}
<ide> if dir.exist?
<ide> dir.children.sort.each do |file|
<del> contents = file.size? ? file.read : "empty log"
<del> # small enough to avoid GitHub "unicorn" page-load-timeout errors
<del> max_file_size = 1_000_000
<del> contents = truncate_text_to_approximate_size(contents, max_file_size, front_weight: 0.2)
<del> logs[file.basename.to_s] = { content: contents }
<add> if file.directory?
<add> logs.merge! load_logs(file, basedir)
<add> else
<add> contents = file.size? ? file.read : "empty log"
<add> # small enough to avoid GitHub "unicorn" page-load-timeout errors
<add> max_file_size = 1_000_000
<add> contents = truncate_text_to_approximate_size(contents, max_file_size, front_weight: 0.2)
<add> logs[file.relative_path_from(basedir).to_s.tr("/", ":")] = { content: contents }
<add> end
<ide> end
<ide> end
<ide> odie "No logs." if logs.empty? | 1 |
Text | Text | fix small grammar mistake | 057aa07ec33e948bb7f63c5f025becce803a14ce | <ide><path>guide/english/ionic/index.md
<ide> Hybrid apps have many benefits over pure native apps, specifically in terms of p
<ide>
<ide> ### Building Hybrid Apps With Ionic
<ide>
<del>Those familiar with web development will find the structure of an Ionic app straightforward. At its core, it’s just a web page running in an native app shell! That means we can use any kind of HTML, CSS, and Javascript we want.
<add>Those familiar with web development will find the structure of an Ionic app straightforward. At its core, it’s just a web page running in a native app shell! That means we can use any kind of HTML, CSS, and Javascript we want.
<ide>
<ide> As of Ionic 2, the framwork uses Angular (previously using AngularJS), please see seperate freeCodeCamp guides on Angular.
<ide> | 1 |
Javascript | Javascript | fix vector iterator | 4bc0670689baba3d237f29a690353d09ec600827 | <ide><path>dist/Immutable.dev.js
<ide> var VectorIterator = function VectorIterator(vector, origin, size, level, root,
<ide> stack.rawIndex++;
<ide> return {
<ide> value: [index, value],
<del> done: true
<add> done: false
<ide> };
<ide> } else {
<ide> stack.rawIndex++;
<ide><path>dist/Immutable.js
<ide> return r.length=e.length,r.__reversedIndices=!!(t^e.__reversedIndices),r.__itera
<ide> return v?(this.bitmap=g,this.nodes=p,this):new De(t,g,p)},iterate:function(t,e){for(var r=this.nodes,n=0,i=r.length-1;i>=n;n++)if(r[e?i-n:n].iterate(t,e)===!1)return!1}},{});var Oe=function(t,e,r){this.ownerID=t,this.count=e,this.nodes=r},be=Oe;ne.createClass(Oe,{get:function(t,e,r,n){var i=e>>>t&pe,u=this.nodes[i];return u?u.get(t+ve,e,r,n):n},update:function(t,e,r,n,i,u){var s=r>>>e&pe,a=i===me,h=this.nodes,o=h[s];if(a&&!o)return this;var c=x(o,t,e+ve,r,n,i,u);if(c===o)return this;var f=this.count;if(o){if(!c&&(f--,Re>f))return A(t,h,f,s)}else f++;var l=t&&t===this.ownerID,_=W(h,s,c,l);return l?(this.count=f,this.nodes=_,this):new be(t,f,_)},iterate:function(t,e){for(var r=this.nodes,n=0,i=r.length-1;i>=n;n++){var u=r[e?i-n:n];if(u&&u.iterate(t,e)===!1)return!1}}},{});var Me=function(t,e,r){this.ownerID=t,this.hash=e,this.entries=r},ke=Me;ne.createClass(Me,{get:function(t,e,r,n){for(var i=this.entries,u=0,s=i.length;s>u;u++)if(w(r,i[u][0]))return i[u][1];return n},update:function(t,e,r,n,i,u){var s=i===me;if(r!==this.hash)return s?this:(u&&(u.value=!0),C(this,t,e,r,[n,i]));for(var a=this.entries,h=0,o=a.length;o>h&&!w(n,a[h][0]);h++);var c=o>h;if(s&&!c)return this;if((s||!c)&&u&&(u.value=!0),s&&2===o)return new Se(t,this.hash,a[1^h]);var f=t&&t===this.ownerID,l=f?a:b(a);return c?s?h===o-1?l.pop():l[h]=l.pop():l[h]=[n,i]:l.push([n,i]),f?(this.entries=l,this):new ke(t,this.hash,l)},iterate:function(t,e){for(var r=this.entries,n=0,i=r.length-1;i>=n;n++)if(t(r[e?i-n:n])===!1)return!1}},{});var Se=function(t,e,r){this.ownerID=t,this.hash=e,this.entry=r},xe=Se;ne.createClass(Se,{get:function(t,e,r,n){return w(r,this.entry[0])?this.entry[1]:n},update:function(t,e,r,n,i,u){var s=w(n,this.entry[0]);return i===me?(s&&u&&(u.value=!0),s?null:this):s?i===this.entry[1]?this:t&&t===this.ownerID?(this.entry[1]=i,this):new xe(t,r,[n,i]):(u&&(u.value=!0),C(this,t,e,r,[n,i]))},iterate:function(t){return t(this.entry)}},{});var Ee,Ce={value:!1},Ae=2147483647,qe=16,je=255,Pe=0,Ue={},ze=ge/2,Re=ge/4,We=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];
<ide> return Je.from(t)},Je=We;ne.createClass(We,{toString:function(){return this.__toString("Vector [","]")},get:function(t,e){if(t=Q(t,this._origin),t>=this._size)return e;var r=F(this,t),n=t&pe;return r&&(void 0===e||r.array.hasOwnProperty(n))?r.array[n]:e},first:function(){return this.get(0)},last:function(){return this.get(this.length?this.length-1:0)},set:function(t,e){var r=T(this._size);if(t>=this.length)return this.withMutations(function(r){return G(r,0,t+1).set(t,e)});if(this.get(t,me)===e)return this;if(t=Q(t,this._origin),t>=r){var n=this._tail.ensureOwner(this.__ownerID);n.array[t&pe]=e;var i=t>=this._size?t+1:this._size;return this.__ownerID?(this.length=i-this._origin,this._size=i,this._tail=n,this):N(this._origin,i,this._level,this._root,n)}for(var u=this._root.ensureOwner(this.__ownerID),s=u,a=this._level;a>0;a-=ve){var h=t>>>a&pe;s=s.array[h]=s.array[h]?s.array[h].ensureOwner(this.__ownerID):new Le([],this.__ownerID)}return s.array[t&pe]=e,this.__ownerID?(this._root=u,this):N(this._origin,this._size,this._level,u,this._tail)},"delete":function(t){if(!this.has(t))return this;var e=T(this._size);if(t=Q(t,this._origin),t>=e){var r=this._tail.ensureOwner(this.__ownerID);return delete r.array[t&pe],this.__ownerID?(this._tail=r,this):N(this._origin,this._size,this._level,this._root,r)}for(var n=this._root.ensureOwner(this.__ownerID),i=n,u=this._level;u>0;u-=ve){var s=t>>>u&pe;i=i.array[s]=i.array[s].ensureOwner(this.__ownerID)}return delete i.array[t&pe],this.__ownerID?(this._root=n,this):N(this._origin,this._size,this._level,n,this._tail)},clear:function(){return this.__ownerID?(this.length=this._origin=this._size=0,this._level=ve,this._root=this._tail=Fe,this):Je.empty()},push:function(){var t=arguments,e=this.length;return this.withMutations(function(r){G(r,0,e+t.length);for(var n=0;t.length>n;n++)r.set(e+n,t[n])})},pop:function(){return G(this,0,-1)},unshift:function(){var t=arguments;return this.withMutations(function(e){G(e,-t.length);for(var r=0;t.length>r;r++)e.set(r,t[r])})},shift:function(){return G(this,1)
<ide> },merge:function(){return H(this,null,arguments)},mergeWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return H(this,t,e)},mergeDeep:function(){return H(this,P(null),arguments)},mergeDeepWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return H(this,P(t),e)},setLength:function(t){return G(this,0,t)},slice:function(t,e,r){var n=ne.superCall(this,Je.prototype,"slice",[t,e,r]);if(!r&&n!==this){var i=this,u=i.length;n.toVector=function(){return G(i,0>t?Math.max(0,u+t):u?Math.min(u,t):t,null==e?u:0>e?Math.max(0,u+e):u?Math.min(u,e):e)}}return n},iterator:function(){return new Ke(this,this._origin,this._size,this._level,this._root,this._tail)},__iterate:function(t,e,r){var n=this,i=0,u=n.length-1;r^=e;var s,a=function(e,s){return t(e,r?u-s:s,n)===!1?!1:(i=s,!0)},h=T(this._size);return s=e?this._tail.iterate(0,h-this._origin,this._size-this._origin,a,e)&&this._root.iterate(this._level,-this._origin,h-this._origin,a,e):this._root.iterate(this._level,-this._origin,h-this._origin,a,e)&&this._tail.iterate(0,h-this._origin,this._size-this._origin,a,e),(s?u:e?u-i:i)+1},__deepEquals:function(t){var e=this.iterator();return t.every(function(t,r){var n=e.next().value;return n&&r===n[0]&&w(t,n[1])})},__ensureOwner:function(t){return t===this.__ownerID?this:t?N(this._origin,this._size,this._level,this._root,this._tail,t):(this.__ownerID=t,this)}},{empty:function(){return Ne||(Ne=N(0,0,ve,Fe,Fe))},from:function(t){if(!t||0===t.length)return Je.empty();if(t.constructor===Je)return t;var e=Array.isArray(t);return t.length>0&&ge>t.length?N(0,t.length,ve,Fe,new Le(e?b(t):ie(t).toArray())):(e||(t=ie(t),t instanceof ae||(t=t.values())),Je.empty().merge(t))}},ae);var Be=We.prototype;Be["@@iterator"]=Be.__iterator__,Be.update=we.update,Be.updateIn=we.updateIn,Be.cursor=we.cursor,Be.withMutations=we.withMutations,Be.asMutable=we.asMutable,Be.asImmutable=we.asImmutable;var Le=function(t,e){this.array=t,this.ownerID=e},Ve=Le;ne.createClass(Le,{ensureOwner:function(t){return t&&t===this.ownerID?this:new Ve(this.array.slice(),t)
<del>},removeBefore:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r>>>e&pe;if(n>=this.array.length)return new Ve([],t);var i,u=0===n;if(e>0){var s=this.array[n];if(i=s&&s.removeBefore(t,e-ve,r),i===s&&u)return this}if(u&&!i)return this;var a=this.ensureOwner();if(!u)for(var h=0;n>h;h++)delete a.array[h];return i&&(a.array[n]=i),a},removeAfter:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r-1>>>e&pe;if(n>=this.array.length)return this;var i,u=n===this.array.length-1;if(e>0){var s=this.array[n];if(i=s&&s.removeAfter(t,e-ve,r),i===s&&u)return this}if(u&&!i)return this;var a=this.ensureOwner();return u||(a.array.length=n+1),i&&(a.array[n]=i),a},iterate:function(t,e,r,n,i){if(0===t){if(i){for(var u=this.array.length-1;u>=0;u--)if(this.array.hasOwnProperty(u)){var s=u+e;if(s>=0&&r>s&&n(this.array[u],s)===!1)return!1}return!0}return this.array.every(function(t,i){var u=i+e;return 0>u||u>=r||n(t,u)!==!1})}var a=1<<t,h=t-ve;if(i){for(var o=this.array.length-1;o>=0;o--){var c=e+o*a;if(r>c&&c+a>0&&this.array.hasOwnProperty(o)&&!this.array[o].iterate(h,c,r,n,i))return!1}return!0}return this.array.every(function(t,u){var s=e+u*a;return s>=r||0>=s+a||t.iterate(h,s,r,n,i)})}},{});var Ke=function(t,e,r,n,i,u){var s=T(r);this._stack={node:i.array,level:n,offset:-e,max:s-e,__prev:{node:u.array,level:0,offset:s-e,max:r-e}}};ne.createClass(Ke,{next:function(){var t=this._stack;t:for(;t;){if(0===t.level)for(t.rawIndex||(t.rawIndex=0);t.node.length>t.rawIndex;){var e=t.rawIndex+t.offset;if(e>=0&&t.max>e&&t.node.hasOwnProperty(t.rawIndex)){var r=t.node[t.rawIndex];return t.rawIndex++,{value:[e,r],done:!0}}t.rawIndex++}else{var n=1<<t.level;for(t.levelIndex||(t.levelIndex=0);t.node.length>t.levelIndex;){var i=t.offset+t.levelIndex*n;if(i+n>0&&t.max>i&&t.node.hasOwnProperty(t.levelIndex)){var u=t.node[t.levelIndex].array;t.levelIndex++,t=this._stack={node:u,level:t.level-ve,offset:i,max:t.max,__prev:t};continue t}t.levelIndex++}}t=this._stack=this._stack.__prev}return{done:!0}}},{});var Ne,Fe=new Le([]),Ge=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];
<add>},removeBefore:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r>>>e&pe;if(n>=this.array.length)return new Ve([],t);var i,u=0===n;if(e>0){var s=this.array[n];if(i=s&&s.removeBefore(t,e-ve,r),i===s&&u)return this}if(u&&!i)return this;var a=this.ensureOwner();if(!u)for(var h=0;n>h;h++)delete a.array[h];return i&&(a.array[n]=i),a},removeAfter:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r-1>>>e&pe;if(n>=this.array.length)return this;var i,u=n===this.array.length-1;if(e>0){var s=this.array[n];if(i=s&&s.removeAfter(t,e-ve,r),i===s&&u)return this}if(u&&!i)return this;var a=this.ensureOwner();return u||(a.array.length=n+1),i&&(a.array[n]=i),a},iterate:function(t,e,r,n,i){if(0===t){if(i){for(var u=this.array.length-1;u>=0;u--)if(this.array.hasOwnProperty(u)){var s=u+e;if(s>=0&&r>s&&n(this.array[u],s)===!1)return!1}return!0}return this.array.every(function(t,i){var u=i+e;return 0>u||u>=r||n(t,u)!==!1})}var a=1<<t,h=t-ve;if(i){for(var o=this.array.length-1;o>=0;o--){var c=e+o*a;if(r>c&&c+a>0&&this.array.hasOwnProperty(o)&&!this.array[o].iterate(h,c,r,n,i))return!1}return!0}return this.array.every(function(t,u){var s=e+u*a;return s>=r||0>=s+a||t.iterate(h,s,r,n,i)})}},{});var Ke=function(t,e,r,n,i,u){var s=T(r);this._stack={node:i.array,level:n,offset:-e,max:s-e,__prev:{node:u.array,level:0,offset:s-e,max:r-e}}};ne.createClass(Ke,{next:function(){var t=this._stack;t:for(;t;){if(0===t.level)for(t.rawIndex||(t.rawIndex=0);t.node.length>t.rawIndex;){var e=t.rawIndex+t.offset;if(e>=0&&t.max>e&&t.node.hasOwnProperty(t.rawIndex)){var r=t.node[t.rawIndex];return t.rawIndex++,{value:[e,r],done:!1}}t.rawIndex++}else{var n=1<<t.level;for(t.levelIndex||(t.levelIndex=0);t.node.length>t.levelIndex;){var i=t.offset+t.levelIndex*n;if(i+n>0&&t.max>i&&t.node.hasOwnProperty(t.levelIndex)){var u=t.node[t.levelIndex].array;t.levelIndex++,t=this._stack={node:u,level:t.level-ve,offset:i,max:t.max,__prev:t};continue t}t.levelIndex++}}t=this._stack=this._stack.__prev}return{done:!0}}},{});var Ne,Fe=new Le([]),Ge=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];
<ide> return He.from(t)},He=Ge;ne.createClass(Ge,{toString:function(){return this.__toString("Set {","}")},has:function(t){return this._map?this._map.has(t):!1},get:function(t,e){return this.has(t)?t:e},add:function(t){var e=this._map;return e||(e=de.empty().__ensureOwner(this.__ownerID)),e=e.set(t,null),this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:X(e)},"delete":function(t){if(null==this._map)return this;var e=this._map.delete(t);return 0===e.length?this.clear():this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:X(e)},clear:function(){return this.__ownerID?(this.length=0,this._map=null,this):He.empty()},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var r=0;t.length>r;r++){var n=t[r];n=n.forEach?n:ie(n),n.forEach(function(t){return e.add(t)})}})},intersect:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return ie(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.every(function(t){return t.contains(r)})||e.delete(r)})})},subtract:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return ie(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.some(function(t){return t.contains(r)})&&e.delete(r)})})},isSubset:function(t){return t=ie(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){var e=this;return t=ie(t),t.every(function(t){return e.contains(t)})},__iterate:function(t,e){var r=this;return this._map?this._map.__iterate(function(e,n){return t(n,n,r)},e):0},__deepEquals:function(t){return!(this._map||t._map)||this._map.equals(t._map)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?X(e,t):(this.__ownerID=t,this._map=e,this)}},{empty:function(){return Te||(Te=X())},from:function(t){var e=He.empty();return t?t.constructor===He?t:e.union(t):e},fromKeys:function(t){return He.from(ie(t).flip())
<ide> }},ie);var Qe=Ge.prototype;Qe.contains=Qe.has,Qe.withMutations=de.prototype.withMutations,Qe.asMutable=de.prototype.asMutable,Qe.asImmutable=de.prototype.asImmutable,Qe.__toJS=ae.prototype.__toJS,Qe.__toStringMapper=ae.prototype.__toStringMapper;var Te,Xe=function(t){var e=Ye.empty();return t?t.constructor===Ye?t:e.merge(t):e},Ye=Xe;ne.createClass(Xe,{toString:function(){return this.__toString("OrderedMap {","}")},get:function(t,e){if(null!=t&&this._map){var r=this._map.get(t);if(null!=r)return this._vector.get(r)[1]}return e},clear:function(){return this.__ownerID?(this.length=0,this._map=this._vector=null,this):Ye.empty()},set:function(t,e){if(null==t)return this;var r=this._map,n=this._vector;if(r){var i=r.get(t);null==i?(r=r.set(t,n.length),n=n.push([t,e])):n.get(i)[1]!==e&&(n=n.set(i,[t,e]))}else n=We.empty().__ensureOwner(this.__ownerID).set(0,[t,e]),r=de.empty().__ensureOwner(this.__ownerID).set(t,0);return this.__ownerID?(this.length=r.length,this._map=r,this._vector=n,this):n===this._vector?this:Y(r,n)},"delete":function(t){if(null==t||null==this._map)return this;var e=this._map.get(t);if(null==e)return this;var r=this._map.delete(t),n=this._vector.delete(e);return 0===r.length?this.clear():this.__ownerID?(this.length=r.length,this._map=r,this._vector=n,this):r===this._map?this:Y(r,n)},__iterate:function(t,e){return this._vector?this._vector.fromEntries().__iterate(t,e):0},__deepEqual:function(t){var e=this._vector.iterator();return t.every(function(t,r){var n=e.next().value;return n&&(n=n[1]),n&&w(r,n[0])&&w(t,n[1])})},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t),r=this._vector&&this._vector.__ensureOwner(t);return t?Y(e,r,t):(this.__ownerID=t,this._map=e,this._vector=r,this)}},{empty:function(){return Ze||(Ze=Y())}},de),Xe.from=Xe;var Ze,$e=function(t,e){var r=function(t){this._map=de(t)};t=ie(t);var n=r.prototype=Object.create(er);n.constructor=r,n._name=e,n._defaultValues=t;var i=Object.keys(t);return r.prototype.length=i.length,Object.defineProperty&&t.forEach(function(t,e){Object.defineProperty(r.prototype,e,{get:function(){return this.get(e)
<ide> },set:function(t){I(this.__ownerID,"Cannot set on an immutable record."),this.set(e,t)}})}),r},tr=$e;ne.createClass($e,{toString:function(){return this.__toString((this._name||"Record")+" {","}")},has:function(t){return this._defaultValues.has(t)},get:function(t,e){return void 0===e||this.has(t)?this._map.get(t,this._defaultValues.get(t)):e},clear:function(){if(this.__ownerID)return this._map.clear(),this;Object.getPrototypeOf(this).constructor;return tr._empty||(tr._empty=Z(this,de.empty()))},set:function(t,e){if(null==t||!this.has(t))return this;var r=this._map.set(t,e);return this.__ownerID||r===this._map?this:Z(this,r)},"delete":function(t){if(null==t||!this.has(t))return this;var e=this._map.delete(t);return this.__ownerID||e===this._map?this:Z(this,e)},__iterate:function(t,e){var r=this;return this._defaultValues.map(function(t,e){return r.get(e)}).__iterate(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?Z(this,e,t):(this.__ownerID=t,this._map=e,this)}},{},ie);var er=$e.prototype;er.__deepEqual=we.__deepEqual,er.merge=we.merge,er.mergeWith=we.mergeWith,er.mergeDeep=we.mergeDeep,er.mergeDeepWith=we.mergeDeepWith,er.update=we.update,er.updateIn=we.updateIn,er.cursor=we.cursor,er.withMutations=we.withMutations,er.asMutable=we.asMutable,er.asImmutable=we.asImmutable;var rr=function(t,e,r){return this instanceof nr?(I(0!==r,"Cannot step a Range by 0"),t=t||0,null==e&&(e=1/0),t===e&&ur?ur:(r=null==r?1:Math.abs(r),t>e&&(r=-r),this._start=t,this._end=e,this._step=r,void(this.length=Math.max(0,Math.ceil((e-t)/r-1)+1)))):new nr(t,e,r)},nr=rr;ne.createClass(rr,{toString:function(){return 0===this.length?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},has:function(t){return I(t>=0,"Index out of bounds"),this.length>t},get:function(t,e){return I(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._start+t*this._step:e},contains:function(t){var e=(t-this._start)/this._step;return e>=0&&this.length>e&&e===Math.floor(e)
<ide><path>src/Vector.js
<ide> class VectorIterator {
<ide> if (index >= 0 && index < stack.max && stack.node.hasOwnProperty(stack.rawIndex)) {
<ide> var value = stack.node[stack.rawIndex];
<ide> stack.rawIndex++;
<del> return { value: [index, value], done: true };
<add> return { value: [index, value], done: false };
<ide> } else {
<ide> stack.rawIndex++;
<ide> } | 3 |
Text | Text | add multi-zones docs. | 7a1d9c18a39860f5711446595543468bfbdef04e | <ide><path>readme.md
<ide> Next.js is a minimalistic framework for server-rendered React applications.
<ide> - [CDN support with Asset Prefix](#cdn-support-with-asset-prefix)
<ide> - [Production deployment](#production-deployment)
<ide> - [Static HTML export](#static-html-export)
<add>- [Multi Zones](#multi-zones)
<ide> - [Recipes](#recipes)
<ide> - [FAQ](#faq)
<ide> - [Contributing](#contributing)
<ide> So, you could only use `pathname`, `query` and `asPath` fields of the `context`
<ide>
<ide> > Basically, you won't be able to render HTML content dynamically as we pre-build HTML files. If you need that, you need run your app with `next start`.
<ide>
<add>## Multi Zones
<add>
<add><p><details>
<add> <summary><b>Examples</b></summary>
<add> <ul><li><a href="./examples/with-zones">With Zones</a></li></ul>
<add></details></p>
<add>
<add>A zone is a single deployment of a Next.js app. Just like that, you can have multiple zones. Then you can merge them as a single app.
<add>
<add>For an example, you can have two zones like this:
<add>
<add>* https://docs.my-app.com for serving `/docs/**`
<add>* https://ui.my-app.com for serving all other pages
<add>
<add>With multi zones support, you can merge both these apps into a single one. Which allows your customers to browse it using a single URL. But you can develop and deploy both apps independently.
<add>
<add>> This is exactly the same concept as microservices, but for frontend apps.
<add>
<add>### How to define a zone
<add>
<add>There are no special zones related APIs. You only need to do following things:
<add>
<add>* Make sure to keep only the pages you need in your app. (For an example, https://ui.my-app.com should not contain pages for `/docs/**`)
<add>* Make sure your app has an [assetPrefix](https://github.com/zeit/next.js#cdn-support-with-asset-prefix). (You can also define the assetPrefix [dynamically](https://github.com/zeit/next.js#dynamic-assetprefix).)
<add>
<add>### How to merge them
<add>
<add>You can merge zones using any HTTP proxy.
<add>
<add>You can use [micro proxy](https://github.com/zeit/micro-proxy) as your local proxy server. It allows you to easily define routing rules like below:
<add>
<add>```json
<add>{
<add> "rules": [
<add> {"pathname": "/docs**", "method":["GET", "POST", "OPTIONS"], "dest": "https://docs.my-app.com"},
<add> {"pathname": "/**", "dest": "https://ui.my-app.com"}
<add> ]
<add>}
<add>```
<add>
<add>For the production deployment, you can use the [path alias](https://zeit.co/docs/features/path-aliases) feature if you are using [ZEIT now](https://zeit.co/now). Otherwise, you can configure your existing proxy server to route HTML pages using a set of rules as show above.
<add>
<ide> ## Recipes
<ide>
<ide> - [Setting up 301 redirects](https://www.raygesualdo.com/posts/301-redirects-with-nextjs/) | 1 |
PHP | PHP | remove bad default from fixture | e7b77a7b714ca9c82b9bfa39cc148d3439c60b6c | <ide><path>lib/Cake/Test/Fixture/DatatypeFixture.php
<ide> class DatatypeFixture extends TestFixture {
<ide> * @var array
<ide> */
<ide> public $fields = array(
<del> 'id' => ['type' => 'integer', 'null' => false, 'default' => 0],
<add> 'id' => ['type' => 'integer', 'null' => false],
<ide> 'float_field' => ['type' => 'float', 'length' => '5,2', 'null' => false, 'default' => null],
<ide> 'huge_int' => ['type' => 'biginteger'],
<ide> 'bool' => ['type' => 'boolean', 'null' => false, 'default' => false], | 1 |
Java | Java | expose executor name in reactinstancemanager | f71c6b6feb4599954539ab8094234b918f43e12a | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java
<ide> public LifecycleState getLifecycleState() {
<ide> return mLifecycleState;
<ide> }
<ide>
<add> public String getJsExecutorName() {
<add> return mJavaScriptExecutorFactory.toString();
<add> }
<add>
<ide> @ThreadConfined(UI)
<ide> private void onReloadWithJSDebugger(JavaJSExecutor.Factory jsExecutorFactory) {
<ide> Log.d(ReactConstants.TAG, "ReactInstanceManager.onReloadWithJSDebugger()");
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/JSCJavaScriptExecutorFactory.java
<ide> public JavaScriptExecutor create() throws Exception {
<ide> jscConfig.putString("DeviceIdentity", mDeviceName);
<ide> return new JSCJavaScriptExecutor(jscConfig);
<ide> }
<add>
<add> @Override
<add> public String toString() {
<add> return "JSCExecutor";
<add> }
<ide> } | 2 |
PHP | PHP | support other configuration option for consistency | 7efb6157741da04eedfa077abe283f9f39f89839 | <ide><path>src/Illuminate/Log/LogManager.php
<ide> protected function createMonologDriver(array $config)
<ide> );
<ide> }
<ide>
<add> $with = array_merge($config['with'] ?? [], $config['handler_with'] ?? []);
<add>
<ide> return new Monolog($this->parseChannel($config), [$this->prepareHandler(
<del> $this->app->make($config['handler'], $config['with'] ?? []), $config
<add> $this->app->make($config['handler'], $with), $config
<ide> )]);
<ide> }
<ide> | 1 |
Javascript | Javascript | add atom target | b5c4d9fd1f6f272327c4f1c8843e8fd8afcf5918 | <ide><path>lib/WebpackOptionsApply.js
<ide> WebpackOptionsApply.prototype.process = function(options, compiler) {
<ide> new LoaderTargetPlugin("node-webkit")
<ide> );
<ide> break;
<add> case "atom":
<add> var JsonpTemplatePlugin = require("./JsonpTemplatePlugin");
<add> var NodeTargetPlugin = require("./node/NodeTargetPlugin");
<add> var ExternalsPlugin = require("./ExternalsPlugin");
<add> compiler.apply(
<add> new JsonpTemplatePlugin(options.output),
<add> new FunctionModulePlugin(options.output),
<add> new NodeTargetPlugin(),
<add> new ExternalsPlugin("commonjs", "app"),
<add> new ExternalsPlugin("commonjs", "auto-updater"),
<add> new ExternalsPlugin("commonjs", "browser-window"),
<add> new ExternalsPlugin("commonjs", "content-tracing"),
<add> new ExternalsPlugin("commonjs", "dialog"),
<add> new ExternalsPlugin("commonjs", "global-shortcut"),
<add> new ExternalsPlugin("commonjs", "ipc"),
<add> new ExternalsPlugin("commonjs", "menu"),
<add> new ExternalsPlugin("commonjs", "menu-item"),
<add> new ExternalsPlugin("commonjs", "power-monitor"),
<add> new ExternalsPlugin("commonjs", "protocol"),
<add> new ExternalsPlugin("commonjs", "tray"),
<add> new ExternalsPlugin("commonjs", "remote"),
<add> new ExternalsPlugin("commonjs", "web-view"),
<add> new ExternalsPlugin("commonjs", "clipboard"),
<add> new ExternalsPlugin("commonjs", "crash-reporter"),
<add> new ExternalsPlugin("commonjs", "screen"),
<add> new ExternalsPlugin("commonjs", "shell"),
<add> new LoaderTargetPlugin("atom")
<add> );
<add> break;
<ide> default:
<ide> throw new Error("Unsupported target '" + options.target + "'.");
<ide> } | 1 |
Ruby | Ruby | expose chunked downloads | f66a69076f43617bacfe45961e229268ed15faa7 | <ide><path>lib/active_storage/blob.rb
<ide> def upload(io)
<ide> service.upload(key, io, checksum: checksum)
<ide> end
<ide>
<del> def download
<del> service.download key
<add> def download(&block)
<add> service.download key, &block
<ide> end
<ide>
<ide>
<ide><path>lib/active_storage/service/disk_service.rb
<ide> def upload(key, io, checksum: nil)
<ide> def download(key)
<ide> if block_given?
<ide> instrument :streaming_download, key do
<del> File.open(path_for(key)) do |file|
<del> while data = file.binread(64.kilobytes)
<add> File.open(path_for(key), 'rb') do |file|
<add> while data = file.read(64.kilobytes)
<ide> yield data
<ide> end
<ide> end
<ide> def url(key, expires_in:, disposition:, filename:)
<ide> instrument :url, key do |payload|
<ide> verified_key_with_expiration = ActiveStorage::VerifiedKeyWithExpiration.encode(key, expires_in: expires_in)
<ide>
<del> generated_url =
<add> generated_url =
<ide> if defined?(Rails) && defined?(Rails.application)
<ide> Rails.application.routes.url_helpers.rails_disk_blob_path(verified_key_with_expiration, disposition: disposition, filename: filename)
<ide> else
<ide> "/rails/active_storage/disk/#{verified_key_with_expiration}/#{filename}?disposition=#{disposition}"
<ide> end
<ide>
<ide> payload[:url] = generated_url
<del>
<add>
<ide> generated_url
<ide> end
<ide> end
<ide><path>test/blob_test.rb
<ide> class ActiveStorage::BlobTest < ActiveSupport::TestCase
<ide> assert_equal Digest::MD5.base64digest(data), blob.checksum
<ide> end
<ide>
<add> test "download yields chunks" do
<add> blob = create_blob data: 'a' * 75.kilobytes
<add> chunks = []
<add>
<add> blob.download do |chunk|
<add> chunks << chunk
<add> end
<add>
<add> assert_equal 2, chunks.size
<add> assert_equal 'a' * 64.kilobytes, chunks.first
<add> assert_equal 'a' * 11.kilobytes, chunks.second
<add> end
<add>
<ide> test "urls expiring in 5 minutes" do
<ide> blob = create_blob
<ide> | 3 |
Text | Text | remove next/future/image ref | 75aab126a28a74e103cc292601993770d32563df | <ide><path>docs/basic-features/image-optimization.md
<ide> If none of the suggested methods works for sizing your images, the `next/image`
<ide>
<ide> ## Styling
<ide>
<del>> Note: Many of the styling issues listed below can be solved with [`next/future/image`](/docs/api-reference/next/future/image.md)
<del>
<ide> Styling the Image component is similar to styling a normal `<img>` element, but there are a few guidelines to keep in mind:
<ide>
<ide> **Use `className` or `style`, not `styled-jsx`** | 1 |
Python | Python | set version to v2.2.0.dev11 | a4d4c4bfa4d73e9f974d38ea5e9a11ac99728bfa | <ide><path>spacy/about.py
<ide> # fmt: off
<ide> __title__ = "spacy"
<del>__version__ = "2.2.0.dev10"
<add>__version__ = "2.2.0.dev11"
<ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) in Python"
<ide> __uri__ = "https://spacy.io"
<ide> __author__ = "Explosion" | 1 |
Javascript | Javascript | use arrow function for lexical `this` | a9387db86737cb6e10d1fe61851bb9072204f776 | <ide><path>lib/_debug_agent.js
<ide> function Agent() {
<ide> this.binding = process._debugAPI;
<ide> assert(this.binding, 'Debugger agent running without bindings!');
<ide>
<del> var self = this;
<del> this.binding.onmessage = function(msg) {
<del> self.clients.forEach(function(client) {
<add> this.binding.onmessage = (msg) => {
<add> this.clients.forEach((client) => {
<ide> client.send({}, msg);
<ide> });
<ide> };
<ide> Agent.prototype.onConnection = function onConnection(socket) {
<ide> c.start();
<ide> this.clients.push(c);
<ide>
<del> var self = this;
<del> c.once('close', function() {
<del> var index = self.clients.indexOf(c);
<add> c.once('close', () => {
<add> var index = this.clients.indexOf(c);
<ide> assert(index !== -1);
<del> self.clients.splice(index, 1);
<add> this.clients.splice(index, 1);
<ide> });
<ide> };
<ide>
<ide> function Client(agent, socket) {
<ide>
<ide> this.on('data', this.onCommand);
<ide>
<del> var self = this;
<del> this.socket.on('close', function() {
<del> self.destroy();
<add> this.socket.on('close', () => {
<add> this.destroy();
<ide> });
<ide> }
<ide> util.inherits(Client, Transform); | 1 |
Go | Go | fix registry filepath and location | 81e7d3571be357205fc7ab65012771cadc2a967b | <ide><path>registry/registry.go
<ide> import (
<ide> "net/http/httputil"
<ide> "os"
<ide> "path"
<add> "path/filepath"
<ide> "runtime"
<ide> "strings"
<ide> "time"
<ide> type httpsRequestModifier struct{ tlsConfig *tls.Config }
<ide> // prefer an fsnotify implementation, but that was out of scope of my refactoring.
<ide> func (m *httpsRequestModifier) ModifyRequest(req *http.Request) error {
<ide> var (
<del> roots *x509.CertPool
<del> certs []tls.Certificate
<add> roots *x509.CertPool
<add> certs []tls.Certificate
<add> hostDir string
<ide> )
<ide>
<ide> if req.URL.Scheme == "https" {
<ide> func (m *httpsRequestModifier) ModifyRequest(req *http.Request) error {
<ide> return false
<ide> }
<ide>
<del> hostDir := path.Join("/etc/docker/certs.d", req.URL.Host)
<add> if runtime.GOOS == "windows" {
<add> hostDir = path.Join(os.TempDir(), "/docker/certs.d", req.URL.Host)
<add> } else {
<add> hostDir = path.Join("/etc/docker/certs.d", req.URL.Host)
<add> }
<ide> logrus.Debugf("hostDir: %s", hostDir)
<ide> fs, err := ioutil.ReadDir(hostDir)
<ide> if err != nil && !os.IsNotExist(err) {
<ide> func (m *httpsRequestModifier) ModifyRequest(req *http.Request) error {
<ide> roots = x509.NewCertPool()
<ide> }
<ide> logrus.Debugf("crt: %s", hostDir+"/"+f.Name())
<del> data, err := ioutil.ReadFile(path.Join(hostDir, f.Name()))
<add> data, err := ioutil.ReadFile(filepath.Join(hostDir, f.Name()))
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (m *httpsRequestModifier) ModifyRequest(req *http.Request) error {
<ide> if !hasFile(fs, keyName) {
<ide> return fmt.Errorf("Missing key %s for certificate %s", keyName, certName)
<ide> }
<del> cert, err := tls.LoadX509KeyPair(path.Join(hostDir, certName), path.Join(hostDir, keyName))
<add> cert, err := tls.LoadX509KeyPair(filepath.Join(hostDir, certName), path.Join(hostDir, keyName))
<ide> if err != nil {
<ide> return err
<ide> } | 1 |
Mixed | Go | add a flag to override the default seccomp profile | b237189e6c8a4f97be59f08c63cdcb1f2f4680a8 | <ide><path>api/server/router/system/system_routes.go
<ide> func (s *systemRouter) getInfo(ctx context.Context, w http.ResponseWriter, r *ht
<ide> if versions.LessThan(httputils.VersionFromContext(ctx), "1.25") {
<ide> // TODO: handle this conversion in engine-api
<ide> type oldInfo struct {
<del> *types.Info
<add> *types.InfoBase
<ide> ExecutionDriver string
<add> SecurityOptions []string
<ide> }
<del> return httputils.WriteJSON(w, http.StatusOK, &oldInfo{Info: info, ExecutionDriver: "<not supported>"})
<add> old := &oldInfo{
<add> InfoBase: info.InfoBase,
<add> ExecutionDriver: "<not supported>",
<add> }
<add> for _, s := range info.SecurityOptions {
<add> if s.Key == "Name" {
<add> old.SecurityOptions = append(old.SecurityOptions, s.Value)
<add> }
<add> }
<add> return httputils.WriteJSON(w, http.StatusOK, old)
<ide> }
<ide> return httputils.WriteJSON(w, http.StatusOK, info)
<ide> }
<ide><path>api/types/types.go
<ide> type Version struct {
<ide> BuildTime string `json:",omitempty"`
<ide> }
<ide>
<del>// Info contains response of Remote API:
<add>// InfoBase contains the base response of Remote API:
<ide> // GET "/info"
<del>type Info struct {
<add>type InfoBase struct {
<ide> ID string
<ide> Containers int
<ide> ContainersRunning int
<ide> type Info struct {
<ide> ServerVersion string
<ide> ClusterStore string
<ide> ClusterAdvertise string
<del> SecurityOptions []string
<ide> Runtimes map[string]Runtime
<ide> DefaultRuntime string
<ide> Swarm swarm.Info
<ide> type Info struct {
<ide> Isolation container.Isolation
<ide> }
<ide>
<add>// SecurityOpt holds key/value pair about a security option
<add>type SecurityOpt struct {
<add> Key, Value string
<add>}
<add>
<add>// Info contains response of Remote API:
<add>// GET "/info"
<add>type Info struct {
<add> *InfoBase
<add> SecurityOptions []SecurityOpt
<add>}
<add>
<ide> // PluginsInfo is a temp struct holding Plugins name
<ide> // registered with docker daemon. It is used by Info struct
<ide> type PluginsInfo struct {
<ide><path>cli/command/system/info.go
<ide> func prettyPrintInfo(dockerCli *command.DockerCli, info types.Info) error {
<ide> }
<ide>
<ide> if info.OSType == "linux" {
<del> fmt.Fprintf(dockerCli.Out(), "Security Options:")
<del> ioutils.FprintfIfNotEmpty(dockerCli.Out(), " %s", strings.Join(info.SecurityOptions, " "))
<del> fmt.Fprintf(dockerCli.Out(), "\n")
<add> if len(info.SecurityOptions) != 0 {
<add> fmt.Fprintf(dockerCli.Out(), "Security Options:\n")
<add> for _, o := range info.SecurityOptions {
<add> switch o.Key {
<add> case "Name":
<add> fmt.Fprintf(dockerCli.Out(), " %s\n", o.Value)
<add> case "Profile":
<add> if o.Key != "default" {
<add> fmt.Fprintf(dockerCli.Err(), " WARNING: You're not using the Docker's default seccomp profile\n")
<add> }
<add> fmt.Fprintf(dockerCli.Out(), " %s: %s\n", o.Key, o.Value)
<add> }
<add> }
<add> }
<ide> }
<ide>
<ide> // Isolation only has meaning on a Windows daemon.
<ide><path>client/info_test.go
<ide> func TestInfo(t *testing.T) {
<ide> return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL)
<ide> }
<ide> info := &types.Info{
<del> ID: "daemonID",
<del> Containers: 3,
<add> InfoBase: &types.InfoBase{
<add> ID: "daemonID",
<add> Containers: 3,
<add> },
<ide> }
<ide> b, err := json.Marshal(info)
<ide> if err != nil {
<ide><path>daemon/config_unix.go
<ide> type Config struct {
<ide> OOMScoreAdjust int `json:"oom-score-adjust,omitempty"`
<ide> Init bool `json:"init,omitempty"`
<ide> InitPath string `json:"init-path,omitempty"`
<add> SeccompProfile string `json:"seccomp-profile,omitempty"`
<ide> }
<ide>
<ide> // bridgeConfig stores all the bridge driver specific
<ide> func (config *Config) InstallFlags(flags *pflag.FlagSet) {
<ide> flags.StringVar(&config.InitPath, "init-path", "", "Path to the docker-init binary")
<ide> flags.Int64Var(&config.CPURealtimePeriod, "cpu-rt-period", 0, "Limit the CPU real-time period in microseconds")
<ide> flags.Int64Var(&config.CPURealtimeRuntime, "cpu-rt-runtime", 0, "Limit the CPU real-time runtime in microseconds")
<add> flags.StringVar(&config.SeccompProfile, "seccomp-profile", "", "Path to seccomp profile")
<ide>
<ide> config.attachExperimentalFlags(flags)
<ide> }
<ide><path>daemon/daemon.go
<ide> type Daemon struct {
<ide> defaultIsolation containertypes.Isolation // Default isolation mode on Windows
<ide> clusterProvider cluster.Provider
<ide> cluster Cluster
<add>
<add> seccompProfile []byte
<add> seccompProfilePath string
<ide> }
<ide>
<ide> // HasExperimental returns whether the experimental features of the daemon are enabled or not
<ide> func NewDaemon(config *Config, registryService registry.Service, containerdRemot
<ide> }
<ide> }()
<ide>
<add> if err := d.setupSeccompProfile(); err != nil {
<add> return nil, err
<add> }
<add>
<ide> // Set the default isolation mode (only applicable on Windows)
<ide> if err := d.setDefaultIsolation(); err != nil {
<ide> return nil, fmt.Errorf("error setting default isolation mode: %v", err)
<ide><path>daemon/daemon_solaris.go
<ide> func setupDaemonProcess(config *Config) error {
<ide> func (daemon *Daemon) verifyVolumesInfo(container *container.Container) error {
<ide> return nil
<ide> }
<add>
<add>func (daemon *Daemon) setupSeccompProfile() error {
<add> return nil
<add>}
<ide><path>daemon/daemon_unix.go
<ide> package daemon
<ide>
<ide> import (
<ide> "bytes"
<add> "encoding/json"
<ide> "fmt"
<ide> "io/ioutil"
<ide> "net"
<ide> func (daemon *Daemon) initCgroupsPath(path string) error {
<ide> return err
<ide> }
<ide> }
<add> return nil
<add>}
<ide>
<add>func (daemon *Daemon) setupSeccompProfile() error {
<add> if daemon.configStore.SeccompProfile != "" {
<add> daemon.seccompProfilePath = daemon.configStore.SeccompProfile
<add> b, err := ioutil.ReadFile(daemon.configStore.SeccompProfile)
<add> if err != nil {
<add> return fmt.Errorf("opening seccomp profile (%s) failed: %v", daemon.configStore.SeccompProfile, err)
<add> }
<add> daemon.seccompProfile = b
<add> p := struct {
<add> DefaultAction string `json:"defaultAction"`
<add> }{}
<add> if err := json.Unmarshal(daemon.seccompProfile, &p); err != nil {
<add> return err
<add> }
<add> }
<ide> return nil
<ide> }
<ide><path>daemon/daemon_windows.go
<ide> func setupDaemonProcess(config *Config) error {
<ide> func (daemon *Daemon) verifyVolumesInfo(container *container.Container) error {
<ide> return nil
<ide> }
<add>
<add>func (daemon *Daemon) setupSeccompProfile() error {
<add> return nil
<add>}
<ide><path>daemon/info.go
<ide> func (daemon *Daemon) SystemInfo() (*types.Info, error) {
<ide> }
<ide> })
<ide>
<del> var securityOptions []string
<add> securityOptions := []types.SecurityOpt{}
<ide> if sysInfo.AppArmor {
<del> securityOptions = append(securityOptions, "apparmor")
<add> securityOptions = append(securityOptions, types.SecurityOpt{Key: "Name", Value: "apparmor"})
<ide> }
<ide> if sysInfo.Seccomp && supportsSeccomp {
<del> securityOptions = append(securityOptions, "seccomp")
<add> profile := daemon.seccompProfilePath
<add> if profile == "" {
<add> profile = "default"
<add> }
<add> securityOptions = append(securityOptions,
<add> types.SecurityOpt{Key: "Name", Value: "seccomp"},
<add> types.SecurityOpt{Key: "Profile", Value: profile},
<add> )
<ide> }
<ide> if selinuxEnabled() {
<del> securityOptions = append(securityOptions, "selinux")
<add> securityOptions = append(securityOptions, types.SecurityOpt{Key: "Name", Value: "selinux"})
<ide> }
<ide> uid, gid := daemon.GetRemappedUIDGID()
<ide> if uid != 0 || gid != 0 {
<del> securityOptions = append(securityOptions, "userns")
<add> securityOptions = append(securityOptions, types.SecurityOpt{Key: "Name", Value: "userns"})
<ide> }
<ide>
<del> v := &types.Info{
<add> v := &types.InfoBase{
<ide> ID: daemon.ID,
<ide> Containers: int(cRunning + cPaused + cStopped),
<ide> ContainersRunning: int(cRunning),
<ide> func (daemon *Daemon) SystemInfo() (*types.Info, error) {
<ide> HTTPProxy: sockets.GetProxyEnv("http_proxy"),
<ide> HTTPSProxy: sockets.GetProxyEnv("https_proxy"),
<ide> NoProxy: sockets.GetProxyEnv("no_proxy"),
<del> SecurityOptions: securityOptions,
<ide> LiveRestoreEnabled: daemon.configStore.LiveRestoreEnabled,
<ide> Isolation: daemon.defaultIsolation,
<ide> }
<ide> func (daemon *Daemon) SystemInfo() (*types.Info, error) {
<ide> }
<ide> v.Name = hostname
<ide>
<del> return v, nil
<add> i := &types.Info{
<add> InfoBase: v,
<add> SecurityOptions: securityOptions,
<add> }
<add>
<add> return i, nil
<ide> }
<ide>
<ide> // SystemVersion returns version information about the daemon.
<ide><path>daemon/seccomp_linux.go
<ide> func setSeccomp(daemon *Daemon, rs *specs.Spec, c *container.Container) error {
<ide> return err
<ide> }
<ide> } else {
<del> profile, err = seccomp.GetDefaultProfile(rs)
<del> if err != nil {
<del> return err
<add> if daemon.seccompProfile != nil {
<add> profile, err = seccomp.LoadProfile(string(daemon.seccompProfile), rs)
<add> if err != nil {
<add> return err
<add> }
<add> } else {
<add> profile, err = seccomp.GetDefaultProfile(rs)
<add> if err != nil {
<add> return err
<add> }
<ide> }
<ide> }
<ide>
<ide><path>docs/reference/commandline/dockerd.md
<ide> Options:
<ide> -p, --pidfile string Path to use for daemon PID file (default "/var/run/docker.pid")
<ide> --raw-logs Full timestamps without ANSI coloring
<ide> --registry-mirror value Preferred Docker registry mirror (default [])
<add> --seccomp-profile value Path to seccomp profile
<ide> --selinux-enabled Enable selinux support
<ide> --shutdown-timeout=15 Set the shutdown timeout value in seconds
<ide> -s, --storage-driver string Storage driver to use
<ide> This is a full example of the allowed configuration options on Linux:
<ide> "icc": false,
<ide> "raw-logs": false,
<ide> "registry-mirrors": [],
<add> "seccomp-profile": "",
<ide> "insecure-registries": [],
<ide> "disable-legacy-registry": false,
<ide> "default-runtime": "runc",
<ide><path>integration-cli/docker_cli_info_unix_test.go
<ide> func (s *DockerSuite) TestInfoSecurityOptions(c *check.C) {
<ide> testRequires(c, SameHostDaemon, seccompEnabled, Apparmor, DaemonIsLinux)
<ide>
<ide> out, _ := dockerCmd(c, "info")
<del> c.Assert(out, checker.Contains, "Security Options: apparmor seccomp")
<add> c.Assert(out, checker.Contains, "Security Options:\n apparmor\n seccomp\n Profile: default\n")
<ide> }
<ide><path>integration-cli/docker_cli_run_unix_test.go
<ide> func (s *DockerDaemonSuite) TestRunSeccompJSONNoArchAndArchMap(c *check.C) {
<ide> c.Assert(err, check.NotNil)
<ide> c.Assert(out, checker.Contains, "'architectures' and 'archMap' were specified in the seccomp profile, use either 'architectures' or 'archMap'")
<ide> }
<add>
<add>func (s *DockerDaemonSuite) TestRunWithDaemonDefaultSeccompProfile(c *check.C) {
<add> testRequires(c, SameHostDaemon, seccompEnabled)
<add>
<add> err := s.d.StartWithBusybox()
<add> c.Assert(err, check.IsNil)
<add>
<add> // 1) verify I can run containers with the Docker default shipped profile which allows chmod
<add> _, err = s.d.Cmd("run", "busybox", "chmod", "777", ".")
<add> c.Assert(err, check.IsNil)
<add>
<add> jsonData := `{
<add> "defaultAction": "SCMP_ACT_ALLOW",
<add> "syscalls": [
<add> {
<add> "name": "chmod",
<add> "action": "SCMP_ACT_ERRNO"
<add> }
<add> ]
<add>}`
<add> tmpFile, err := ioutil.TempFile("", "profile.json")
<add> c.Assert(err, check.IsNil)
<add> defer tmpFile.Close()
<add> _, err = tmpFile.Write([]byte(jsonData))
<add> c.Assert(err, check.IsNil)
<add>
<add> // 2) restart the daemon and add a custom seccomp profile in which we deny chmod
<add> err = s.d.Restart("--seccomp-profile=" + tmpFile.Name())
<add> c.Assert(err, check.IsNil)
<add>
<add> out, err := s.d.Cmd("run", "busybox", "chmod", "777", ".")
<add> c.Assert(err, check.NotNil)
<add> c.Assert(out, checker.Contains, "Operation not permitted")
<add>}
<ide><path>man/dockerd.8.md
<ide> dockerd - Enable daemon mode
<ide> [**--raw-logs**]
<ide> [**--registry-mirror**[=*[]*]]
<ide> [**-s**|**--storage-driver**[=*STORAGE-DRIVER*]]
<add>[**--seccomp-profile**[=*SECCOMP-PROFILE-PATH*]]
<ide> [**--selinux-enabled**]
<ide> [**--shutdown-timeout**[=*15*]]
<ide> [**--storage-opt**[=*[]*]]
<ide> output otherwise.
<ide> **-s**, **--storage-driver**=""
<ide> Force the Docker runtime to use a specific storage driver.
<ide>
<add>**--seccomp-profile**=""
<add> Path to seccomp profile.
<add>
<ide> **--selinux-enabled**=*true*|*false*
<ide> Enable selinux support. Default is false.
<ide> | 15 |
Javascript | Javascript | add test for title and routechangecomplete | 0a02efbfcc1ff5a8e0be780efee4f3c4ce0c5c85 | <ide><path>test/integration/production/pages/with-title.js
<add>import Head from 'next/head'
<add>
<add>export default () => (
<add> <>
<add> <Head>
<add> <title>hello from title</title>
<add> </Head>
<add> <p id="with-title">hi</p>
<add> </>
<add>)
<ide><path>test/integration/production/test/index.test.js
<ide> describe('Production Usage', () => {
<ide> expect(text).toBe('Hello World')
<ide> await browser.close()
<ide> })
<add>
<add> it('should set title by routeChangeComplete event', async () => {
<add> const browser = await webdriver(appPort, '/')
<add> await browser.eval(function setup() {
<add> window.next.router.events.on('routeChangeComplete', function handler(
<add> url
<add> ) {
<add> window.routeChangeTitle = document.title
<add> window.routeChangeUrl = url
<add> })
<add> window.next.router.push('/with-title')
<add> })
<add> await browser.waitForElementByCss('#with-title')
<add>
<add> const title = await browser.eval(`window.routeChangeTitle`)
<add> const url = await browser.eval(`window.routeChangeUrl`)
<add> expect(title).toBe('hello from title')
<add> expect(url).toBe('/with-title')
<add> })
<ide> })
<ide>
<ide> it('should navigate to external site and back', async () => { | 2 |
Python | Python | add missing verbose opt for evaluate_generator | 416783156c1b07f28131c493a55a93936b5fe163 | <ide><path>keras/engine/training.py
<ide> def generate_arrays_from_file(path):
<ide> def evaluate_generator(self, generator, steps=None,
<ide> max_queue_size=10,
<ide> workers=1,
<del> use_multiprocessing=False):
<add> use_multiprocessing=False,
<add> verbose=0):
<ide> """Evaluates the model on a data generator.
<ide>
<ide> The generator should return the same kind of data
<ide> def evaluate_generator(self, generator, steps=None,
<ide> non picklable arguments to the generator
<ide> as they can't be passed
<ide> easily to children processes.
<add> verbose: verbosity mode, 0 or 1.
<ide>
<ide> # Returns
<ide> Scalar test loss (if the model has a single output and no metrics)
<ide> def evaluate_generator(self, generator, steps=None,
<ide> else:
<ide> output_generator = generator
<ide>
<add> if verbose == 1:
<add> progbar = Progbar(target=steps)
<add>
<ide> while steps_done < steps:
<ide> generator_output = next(output_generator)
<ide> if not hasattr(generator_output, '__len__'):
<ide> def evaluate_generator(self, generator, steps=None,
<ide>
<ide> steps_done += 1
<ide> batch_sizes.append(batch_size)
<add> if verbose == 1:
<add> progbar.update(steps_done)
<ide>
<ide> finally:
<ide> if enqueuer is not None:
<ide><path>tests/keras/engine/test_training.py
<ide> def mse(y_true, y_pred):
<ide> out = model.evaluate([input_a_np, input_b_np], [output_a_np, output_b_np], batch_size=4)
<ide> out = model.predict([input_a_np, input_b_np], batch_size=4)
<ide>
<add> # enable verbose for evaluate_generator
<add> out = model.evaluate_generator(gen_data(4), steps=3, verbose=1)
<add>
<ide> # empty batch
<ide> with pytest.raises(ValueError):
<ide> def gen_data(): | 2 |
Ruby | Ruby | copy the cache too | 326548770d694fbc5dc4cccc3a293a2d4eabe0b0 | <ide><path>activerecord/lib/active_record/base.rb
<ide> def clone
<ide> def becomes(klass)
<ide> returning klass.new do |became|
<ide> became.instance_variable_set("@attributes", @attributes)
<add> became.instance_variable_set("@attributes_cache", @attributes_cache)
<ide> became.instance_variable_set("@new_record", new_record?)
<ide> end
<ide> end | 1 |
Python | Python | add some tests for ticket . do some cleanups | ae2ebe1beb13b766c07c25d35cfff90eaf63ca09 | <ide><path>numpy/lib/tests/test_twodim_base.py
<ide> def test_dtype(self):
<ide> assert_array_equal(tri(3,dtype=bool),out.astype(bool))
<ide>
<ide>
<del>def test_mask_indices():
<del> # simple test without offset
<del> iu = mask_indices(3, np.triu)
<del> a = np.arange(9).reshape(3, 3)
<del> yield (assert_array_equal, a[iu], array([0, 1, 2, 4, 5, 8]))
<del> # Now with an offset
<del> iu1 = mask_indices(3, np.triu, 1)
<del> yield (assert_array_equal, a[iu1], array([1, 2, 5]))
<del>
<del>
<del>def test_tril_indices():
<del> # indices without and with offset
<del> il1 = tril_indices(4)
<del> il2 = tril_indices(4, 2)
<del>
<del> a = np.array([[1, 2, 3, 4],
<del> [5, 6, 7, 8],
<del> [9, 10, 11, 12],
<del> [13, 14, 15, 16]])
<del>
<del> # indexing:
<del> yield (assert_array_equal, a[il1],
<del> array([ 1, 5, 6, 9, 10, 11, 13, 14, 15, 16]) )
<del>
<del> # And for assigning values:
<del> a[il1] = -1
<del> yield (assert_array_equal, a,
<del> array([[-1, 2, 3, 4],
<del> [-1, -1, 7, 8],
<del> [-1, -1, -1, 12],
<del> [-1, -1, -1, -1]]) )
<del>
<del> # These cover almost the whole array (two diagonals right of the main one):
<del> a[il2] = -10
<del> yield (assert_array_equal, a,
<del> array([[-10, -10, -10, 4],
<del> [-10, -10, -10, -10],
<del> [-10, -10, -10, -10],
<del> [-10, -10, -10, -10]]) )
<del>
<del>
<del>def test_triu_indices():
<del> iu1 = triu_indices(4)
<del> iu2 = triu_indices(4, 2)
<del>
<del> a = np.array([[1, 2, 3, 4],
<del> [5, 6, 7, 8],
<del> [9, 10, 11, 12],
<del> [13, 14, 15, 16]])
<del>
<del> # Both for indexing:
<del> yield (assert_array_equal, a[iu1],
<del> array([1, 2, 3, 4, 6, 7, 8, 11, 12, 16]))
<del>
<del> # And for assigning values:
<del> a[iu1] = -1
<del> yield (assert_array_equal, a,
<del> array([[-1, -1, -1, -1],
<del> [ 5, -1, -1, -1],
<del> [ 9, 10, -1, -1],
<del> [13, 14, 15, -1]]) )
<del>
<del> # These cover almost the whole array (two diagonals right of the main one):
<del> a[iu2] = -10
<del> yield ( assert_array_equal, a,
<del> array([[ -1, -1, -10, -10],
<del> [ 5, -1, -1, -10],
<del> [ 9, 10, -1, -1],
<del> [ 13, 14, 15, -1]]) )
<add>class TestMaskIndices(TestCase):
<add> def test_mask_indices(self):
<add> # simple test without offset
<add> iu = mask_indices(3, np.triu)
<add> a = np.arange(9).reshape(3, 3)
<add> yield (assert_array_equal, a[iu], array([0, 1, 2, 4, 5, 8]))
<add> # Now with an offset
<add> iu1 = mask_indices(3, np.triu, 1)
<add> yield (assert_array_equal, a[iu1], array([1, 2, 5]))
<add>
<add>
<add>class TestTrilIndices(TestCase):
<add> def test_tril_indices():
<add> # indices without and with offset
<add> il1 = tril_indices(4)
<add> il2 = tril_indices(4, 2)
<add>
<add> a = np.array([[1, 2, 3, 4],
<add> [5, 6, 7, 8],
<add> [9, 10, 11, 12],
<add> [13, 14, 15, 16]])
<add>
<add> # indexing:
<add> yield (assert_array_equal, a[il1],
<add> array([ 1, 5, 6, 9, 10, 11, 13, 14, 15, 16]) )
<add>
<add> # And for assigning values:
<add> a[il1] = -1
<add> yield (assert_array_equal, a,
<add> array([[-1, 2, 3, 4],
<add> [-1, -1, 7, 8],
<add> [-1, -1, -1, 12],
<add> [-1, -1, -1, -1]]) )
<add>
<add> # These cover almost the whole array (two diagonals right of the main one):
<add> a[il2] = -10
<add> yield (assert_array_equal, a,
<add> array([[-10, -10, -10, 4],
<add> [-10, -10, -10, -10],
<add> [-10, -10, -10, -10],
<add> [-10, -10, -10, -10]]) )
<add>
<add>
<add>class TestTrilIndicesFrom(TestCase):
<add>
<add> def test_exceptions(self):
<add> yield assert_raises(ValueError, tril_indices_from, np.ones((2,)))
<add> yield assert_raises(ValueError, tril_indices_from, np.ones((2,2,2)))
<add> yield assert_raises(ValueError, tril_indices_from, np.ones((2,3)))
<add>
<add>
<add>class TestTriuIndices(TestCase):
<add> def test_triu_indices():
<add> iu1 = triu_indices(4)
<add> iu2 = triu_indices(4, 2)
<add>
<add> a = np.array([[1, 2, 3, 4],
<add> [5, 6, 7, 8],
<add> [9, 10, 11, 12],
<add> [13, 14, 15, 16]])
<add>
<add> # Both for indexing:
<add> yield (assert_array_equal, a[iu1],
<add> array([1, 2, 3, 4, 6, 7, 8, 11, 12, 16]))
<add>
<add> # And for assigning values:
<add> a[iu1] = -1
<add> yield (assert_array_equal, a,
<add> array([[-1, -1, -1, -1],
<add> [ 5, -1, -1, -1],
<add> [ 9, 10, -1, -1],
<add> [13, 14, 15, -1]]) )
<add>
<add> # These cover almost the whole array (two diagonals right of the main one):
<add> a[iu2] = -10
<add> yield ( assert_array_equal, a,
<add> array([[ -1, -1, -10, -10],
<add> [ 5, -1, -1, -10],
<add> [ 9, 10, -1, -1],
<add> [ 13, 14, 15, -1]]) )
<add>
<add>
<add>class TestTriuIndicesFrom(TestCase):
<add>
<add> def test_exceptions(self):
<add> yield assert_raises(ValueError, triu_indices_from, np.ones((2,)))
<add> yield assert_raises(ValueError, triu_indices_from, np.ones((2,2,2)))
<add> yield assert_raises(ValueError, triu_indices_from, np.ones((2,3)))
<ide>
<ide>
<ide> if __name__ == "__main__": | 1 |
Python | Python | remove session reference | bb78151bdd42df82057e510d516618a4ffc86df0 | <ide><path>airflow/models.py
<ide> def run(
<ide> self.pool = pool or task.pool
<ide> self.test_mode = test_mode
<ide> self.force = force
<del> session = settings.Session()
<del> self.refresh_from_db(session)
<del> session.commit()
<add> self.refresh_from_db()
<ide> self.clear_xcom_data()
<ide> self.job_id = job_id
<ide> iso = datetime.now().isoformat() | 1 |
Java | Java | expose request in webclientresponseexception | 3258ac1ec4159b3fe69cc9daad4ab054b90d0e6c | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultWebClient.java
<ide> import java.util.LinkedHashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.function.BiFunction;
<ide> import java.util.function.Consumer;
<ide> import java.util.function.Function;
<ide> import java.util.function.Predicate;
<add>import java.util.function.Supplier;
<ide>
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<ide> import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<add>import org.springframework.http.HttpRequest;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.client.reactive.ClientHttpRequest;
<ide> public RequestBodyUriSpec method(HttpMethod httpMethod) {
<ide> return methodInternal(httpMethod);
<ide> }
<ide>
<del> @SuppressWarnings("unchecked")
<ide> private RequestBodyUriSpec methodInternal(HttpMethod httpMethod) {
<ide> return new DefaultRequestBodyUriSpec(httpMethod);
<ide> }
<ide> else if (CollectionUtils.isEmpty(defaultCookies)) {
<ide>
<ide> @Override
<ide> public ResponseSpec retrieve() {
<del> return new DefaultResponseSpec(exchange());
<add> return new DefaultResponseSpec(exchange(), this::createRequest);
<add> }
<add>
<add> private HttpRequest createRequest() {
<add> return new HttpRequest() {
<add>
<add> private HttpHeaders headers = initHeaders();
<add>
<add>
<add> @Override
<add> public HttpMethod getMethod() {
<add> return httpMethod;
<add> }
<add>
<add> @Override
<add> public String getMethodValue() {
<add> return httpMethod.name();
<add> }
<add>
<add> @Override
<add> public URI getURI() {
<add> return uri;
<add> }
<add>
<add> @Override
<add> public HttpHeaders getHeaders() {
<add> return headers;
<add> }
<add> };
<ide> }
<ide> }
<ide>
<ide> private static class DefaultResponseSpec implements ResponseSpec {
<ide>
<ide> private final Mono<ClientResponse> responseMono;
<ide>
<add> private final Supplier<HttpRequest> requestSupplier;
<add>
<ide> private final List<StatusHandler> statusHandlers = new ArrayList<>(1);
<ide>
<ide>
<del> DefaultResponseSpec(Mono<ClientResponse> responseMono) {
<add> DefaultResponseSpec(Mono<ClientResponse> responseMono,
<add> Supplier<HttpRequest> requestSupplier) {
<ide> this.responseMono = responseMono;
<add> this.requestSupplier = requestSupplier;
<ide> this.statusHandlers.add(DEFAULT_STATUS_HANDLER);
<ide> }
<ide>
<ide> public ResponseSpec onStatus(Predicate<HttpStatus> statusPredicate,
<ide> if (this.statusHandlers.size() == 1 && this.statusHandlers.get(0) == DEFAULT_STATUS_HANDLER) {
<ide> this.statusHandlers.clear();
<ide> }
<del> this.statusHandlers.add(new StatusHandler(statusPredicate, exceptionFunction));
<add> this.statusHandlers.add(new StatusHandler(statusPredicate,
<add> (clientResponse, request) -> exceptionFunction.apply(clientResponse)));
<ide>
<ide> return this;
<ide> }
<ide> public <T> Mono<T> bodyToMono(Class<T> bodyType) {
<ide> }
<ide>
<ide> @Override
<del> @SuppressWarnings("unchecked")
<ide> public <T> Mono<T> bodyToMono(ParameterizedTypeReference<T> bodyType) {
<ide> return this.responseMono.flatMap(response ->
<ide> handleBody(response, response.bodyToMono(bodyType), mono -> mono.flatMap(Mono::error)));
<ide> }
<ide>
<ide> @Override
<del> @SuppressWarnings("unchecked")
<ide> public <T> Flux<T> bodyToFlux(Class<T> elementType) {
<ide> return this.responseMono.flatMapMany(response ->
<ide> handleBody(response, response.bodyToFlux(elementType), mono -> mono.flatMapMany(Flux::error)));
<ide> }
<ide>
<ide> @Override
<del> @SuppressWarnings("unchecked")
<ide> public <T> Flux<T> bodyToFlux(ParameterizedTypeReference<T> elementType) {
<ide> return this.responseMono.flatMapMany(response -> handleBody(response,
<ide> response.bodyToFlux(elementType), mono -> mono.flatMapMany(Flux::error)));
<ide> private <T extends Publisher<?>> T handleBody(ClientResponse response,
<ide> if (HttpStatus.resolve(response.rawStatusCode()) != null) {
<ide> for (StatusHandler handler : this.statusHandlers) {
<ide> if (handler.test(response.statusCode())) {
<del> Mono<? extends Throwable> exMono = handler.apply(response);
<add> HttpRequest request = this.requestSupplier.get();
<add> Mono<? extends Throwable> exMono = handler.apply(response, request);
<ide> exMono = exMono.flatMap(ex -> drainBody(response, ex));
<ide> exMono = exMono.onErrorResume(ex -> drainBody(response, ex));
<ide> return errorFunction.apply(exMono);
<ide> private <T extends Publisher<?>> T handleBody(ClientResponse response,
<ide> return bodyPublisher;
<ide> }
<ide> else {
<del> return errorFunction.apply(createResponseException(response));
<add> return errorFunction.apply(createResponseException(response,
<add> this.requestSupplier.get()));
<ide> }
<ide> }
<ide>
<ide> private <T> Mono<T> drainBody(ClientResponse response, Throwable ex) {
<ide> .onErrorResume(ex2 -> Mono.empty()).thenReturn(ex);
<ide> }
<ide>
<del> private static Mono<WebClientResponseException> createResponseException(ClientResponse response) {
<add> private static Mono<WebClientResponseException> createResponseException(ClientResponse response,
<add> HttpRequest request) {
<ide> return DataBufferUtils.join(response.body(BodyExtractors.toDataBuffers()))
<ide> .map(dataBuffer -> {
<ide> byte[] bytes = new byte[dataBuffer.readableByteCount()];
<ide> private static Mono<WebClientResponseException> createResponseException(ClientRe
<ide> response.statusCode().getReasonPhrase(),
<ide> response.headers().asHttpHeaders(),
<ide> bodyBytes,
<del> charset);
<add> charset,
<add> request);
<ide> }
<ide> else {
<ide> return new UnknownHttpStatusCodeException(
<ide> response.rawStatusCode(),
<ide> response.headers().asHttpHeaders(),
<ide> bodyBytes,
<del> charset);
<add> charset,
<add> request);
<ide> }
<ide> });
<ide> }
<ide> private static class StatusHandler {
<ide>
<ide> private final Predicate<HttpStatus> predicate;
<ide>
<del> private final Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction;
<add> private final BiFunction<ClientResponse, HttpRequest, Mono<? extends Throwable>> exceptionFunction;
<ide>
<ide>
<ide> public StatusHandler(Predicate<HttpStatus> predicate,
<del> Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) {
<add> BiFunction<ClientResponse, HttpRequest, Mono<? extends Throwable>> exceptionFunction) {
<ide>
<ide> Assert.notNull(predicate, "Predicate must not be null");
<ide> Assert.notNull(exceptionFunction, "Function must not be null");
<ide> public boolean test(HttpStatus status) {
<ide> return this.predicate.test(status);
<ide> }
<ide>
<del> public Mono<? extends Throwable> apply(ClientResponse response) {
<del> return this.exceptionFunction.apply(response);
<add> public Mono<? extends Throwable> apply(ClientResponse response, HttpRequest request) {
<add> return this.exceptionFunction.apply(response, request);
<ide> }
<ide> }
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/UnknownHttpStatusCodeException.java
<ide> import java.nio.charset.Charset;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.HttpRequest;
<add>import org.springframework.lang.Nullable;
<ide>
<ide> /**
<ide> * Exception thrown when an unknown (or custom) HTTP status code is received.
<ide> public class UnknownHttpStatusCodeException extends WebClientResponseException {
<ide> private static final long serialVersionUID = 2407169540168185007L;
<ide>
<ide>
<add> /**
<add> * Create a new instance of the {@code UnknownHttpStatusCodeException} with the given
<add> * parameters.
<add> */
<ide> public UnknownHttpStatusCodeException(
<ide> int statusCode, HttpHeaders headers, byte[] responseBody, Charset responseCharset) {
<ide>
<ide> super("Unknown status code [" + statusCode + "]", statusCode, "",
<ide> headers, responseBody, responseCharset);
<ide> }
<ide>
<add> /**
<add> * Create a new instance of the {@code UnknownHttpStatusCodeException} with the given
<add> * parameters.
<add> * @since 5.1.4
<add> */
<add> public UnknownHttpStatusCodeException(
<add> int statusCode, HttpHeaders headers, byte[] responseBody, Charset responseCharset,
<add> @Nullable HttpRequest request) {
<add>
<add> super("Unknown status code [" + statusCode + "]", statusCode, "",
<add> headers, responseBody, responseCharset, request);
<add> }
<add>
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/WebClientResponseException.java
<ide> import java.nio.charset.StandardCharsets;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.HttpRequest;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.lang.Nullable;
<ide>
<ide> public class WebClientResponseException extends WebClientException {
<ide>
<ide> private final Charset responseCharset;
<ide>
<add> @Nullable
<add> private final HttpRequest request;
<add>
<ide>
<ide> /**
<ide> * Constructor with response data only, and a default message.
<ide> public class WebClientResponseException extends WebClientException {
<ide> public WebClientResponseException(int statusCode, String statusText,
<ide> @Nullable HttpHeaders headers, @Nullable byte[] body, @Nullable Charset charset) {
<ide>
<del> this(statusCode + " " + statusText, statusCode, statusText, headers, body, charset);
<add> this(statusCode, statusText, headers, body, charset, null);
<add> }
<add>
<add> /**
<add> * Constructor with response data only, and a default message.
<add> * @since 5.1.4
<add> */
<add> public WebClientResponseException(int statusCode, String statusText,
<add> @Nullable HttpHeaders headers, @Nullable byte[] body, @Nullable Charset charset,
<add> @Nullable HttpRequest request) {
<add>
<add> this(statusCode + " " + statusText, statusCode, statusText, headers, body, charset, request);
<add> }
<add>
<add> /**
<add> * Constructor with a prepared message.
<add> */
<add> public WebClientResponseException(String message, int statusCode, String statusText,
<add> @Nullable HttpHeaders headers, @Nullable byte[] responseBody, @Nullable Charset charset) {
<add> this(message, statusCode, statusText, headers, responseBody, charset, null);
<ide> }
<ide>
<ide> /**
<ide> * Constructor with a prepared message.
<add> * @since 5.1.4
<ide> */
<ide> public WebClientResponseException(String message, int statusCode, String statusText,
<del> @Nullable HttpHeaders headers, @Nullable byte[] responsebody, @Nullable Charset charset) {
<add> @Nullable HttpHeaders headers, @Nullable byte[] responseBody, @Nullable Charset charset,
<add> @Nullable HttpRequest request) {
<ide>
<ide> super(message);
<ide>
<ide> this.statusCode = statusCode;
<ide> this.statusText = statusText;
<ide> this.headers = (headers != null ? headers : HttpHeaders.EMPTY);
<del> this.responseBody = (responsebody != null ? responsebody : new byte[0]);
<add> this.responseBody = (responseBody != null ? responseBody : new byte[0]);
<ide> this.responseCharset = (charset != null ? charset : StandardCharsets.ISO_8859_1);
<add> this.request = request;
<ide> }
<ide>
<ide>
<ide> public String getResponseBodyAsString() {
<ide> return new String(this.responseBody, this.responseCharset);
<ide> }
<ide>
<add> /**
<add> * Return the corresponding request.
<add> * @since 5.1.4
<add> */
<add> @Nullable
<add> public HttpRequest getRequest() {
<add> return this.request;
<add> }
<ide>
<ide> /**
<ide> * Create {@code WebClientResponseException} or an HTTP status specific sub-class.
<ide> public String getResponseBodyAsString() {
<ide> public static WebClientResponseException create(
<ide> int statusCode, String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<ide>
<add> return create(statusCode, statusText, headers, body, charset, null);
<add> }
<add>
<add> /**
<add> * Create {@code WebClientResponseException} or an HTTP status specific sub-class.
<add> * @since 5.1.4
<add> */
<add> public static WebClientResponseException create(
<add> int statusCode, String statusText, HttpHeaders headers, byte[] body,
<add> @Nullable Charset charset, @Nullable HttpRequest request) {
<add>
<ide> HttpStatus httpStatus = HttpStatus.resolve(statusCode);
<ide> if (httpStatus != null) {
<ide> switch (httpStatus) {
<ide> case BAD_REQUEST:
<del> return new WebClientResponseException.BadRequest(statusText, headers, body, charset);
<add> return new WebClientResponseException.BadRequest(statusText, headers, body, charset, request);
<ide> case UNAUTHORIZED:
<del> return new WebClientResponseException.Unauthorized(statusText, headers, body, charset);
<add> return new WebClientResponseException.Unauthorized(statusText, headers, body, charset, request);
<ide> case FORBIDDEN:
<del> return new WebClientResponseException.Forbidden(statusText, headers, body, charset);
<add> return new WebClientResponseException.Forbidden(statusText, headers, body, charset, request);
<ide> case NOT_FOUND:
<del> return new WebClientResponseException.NotFound(statusText, headers, body, charset);
<add> return new WebClientResponseException.NotFound(statusText, headers, body, charset, request);
<ide> case METHOD_NOT_ALLOWED:
<del> return new WebClientResponseException.MethodNotAllowed(statusText, headers, body, charset);
<add> return new WebClientResponseException.MethodNotAllowed(statusText, headers, body, charset, request);
<ide> case NOT_ACCEPTABLE:
<del> return new WebClientResponseException.NotAcceptable(statusText, headers, body, charset);
<add> return new WebClientResponseException.NotAcceptable(statusText, headers, body, charset, request);
<ide> case CONFLICT:
<del> return new WebClientResponseException.Conflict(statusText, headers, body, charset);
<add> return new WebClientResponseException.Conflict(statusText, headers, body, charset, request);
<ide> case GONE:
<del> return new WebClientResponseException.Gone(statusText, headers, body, charset);
<add> return new WebClientResponseException.Gone(statusText, headers, body, charset, request);
<ide> case UNSUPPORTED_MEDIA_TYPE:
<del> return new WebClientResponseException.UnsupportedMediaType(statusText, headers, body, charset);
<add> return new WebClientResponseException.UnsupportedMediaType(statusText, headers, body, charset, request);
<ide> case TOO_MANY_REQUESTS:
<del> return new WebClientResponseException.TooManyRequests(statusText, headers, body, charset);
<add> return new WebClientResponseException.TooManyRequests(statusText, headers, body, charset, request);
<ide> case UNPROCESSABLE_ENTITY:
<del> return new WebClientResponseException.UnprocessableEntity(statusText, headers, body, charset);
<add> return new WebClientResponseException.UnprocessableEntity(statusText, headers, body, charset, request);
<ide> case INTERNAL_SERVER_ERROR:
<del> return new WebClientResponseException.InternalServerError(statusText, headers, body, charset);
<add> return new WebClientResponseException.InternalServerError(statusText, headers, body, charset, request);
<ide> case NOT_IMPLEMENTED:
<del> return new WebClientResponseException.NotImplemented(statusText, headers, body, charset);
<add> return new WebClientResponseException.NotImplemented(statusText, headers, body, charset, request);
<ide> case BAD_GATEWAY:
<del> return new WebClientResponseException.BadGateway(statusText, headers, body, charset);
<add> return new WebClientResponseException.BadGateway(statusText, headers, body, charset, request);
<ide> case SERVICE_UNAVAILABLE:
<del> return new WebClientResponseException.ServiceUnavailable(statusText, headers, body, charset);
<add> return new WebClientResponseException.ServiceUnavailable(statusText, headers, body, charset, request);
<ide> case GATEWAY_TIMEOUT:
<del> return new WebClientResponseException.GatewayTimeout(statusText, headers, body, charset);
<add> return new WebClientResponseException.GatewayTimeout(statusText, headers, body, charset, request);
<ide> }
<ide> }
<del> return new WebClientResponseException(statusCode, statusText, headers, body, charset);
<add> return new WebClientResponseException(statusCode, statusText, headers, body, charset, request);
<ide> }
<ide>
<ide>
<ide> public static WebClientResponseException create(
<ide> @SuppressWarnings("serial")
<ide> public static class BadRequest extends WebClientResponseException {
<ide>
<del> BadRequest(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<del> super(HttpStatus.BAD_REQUEST.value(), statusText, headers, body, charset);
<add> BadRequest(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset,
<add> @Nullable HttpRequest request) {
<add> super(HttpStatus.BAD_REQUEST.value(), statusText, headers, body, charset, request);
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public static class BadRequest extends WebClientResponseException {
<ide> @SuppressWarnings("serial")
<ide> public static class Unauthorized extends WebClientResponseException {
<ide>
<del> Unauthorized(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<del> super(HttpStatus.UNAUTHORIZED.value(), statusText, headers, body, charset);
<add> Unauthorized(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset,
<add> @Nullable HttpRequest request) {
<add> super(HttpStatus.UNAUTHORIZED.value(), statusText, headers, body, charset, request);
<ide> }
<ide> }
<ide>
<ide> public static class Unauthorized extends WebClientResponseException {
<ide> @SuppressWarnings("serial")
<ide> public static class Forbidden extends WebClientResponseException {
<ide>
<del> Forbidden(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<del> super(HttpStatus.FORBIDDEN.value(), statusText, headers, body, charset);
<add> Forbidden(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset,
<add> @Nullable HttpRequest request) {
<add> super(HttpStatus.FORBIDDEN.value(), statusText, headers, body, charset, request);
<ide> }
<ide> }
<ide>
<ide> public static class Forbidden extends WebClientResponseException {
<ide> @SuppressWarnings("serial")
<ide> public static class NotFound extends WebClientResponseException {
<ide>
<del> NotFound(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<del> super(HttpStatus.NOT_FOUND.value(), statusText, headers, body, charset);
<add> NotFound(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset,
<add> @Nullable HttpRequest request) {
<add> super(HttpStatus.NOT_FOUND.value(), statusText, headers, body, charset, request);
<ide> }
<ide> }
<ide>
<ide> public static class NotFound extends WebClientResponseException {
<ide> @SuppressWarnings("serial")
<ide> public static class MethodNotAllowed extends WebClientResponseException {
<ide>
<del> MethodNotAllowed(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<del> super(HttpStatus.METHOD_NOT_ALLOWED.value(), statusText, headers, body, charset);
<add> MethodNotAllowed(String statusText, HttpHeaders headers, byte[] body,
<add> @Nullable Charset charset, @Nullable HttpRequest request) {
<add> super(HttpStatus.METHOD_NOT_ALLOWED.value(), statusText, headers, body, charset,
<add> request);
<ide> }
<ide> }
<ide>
<ide> public static class MethodNotAllowed extends WebClientResponseException {
<ide> @SuppressWarnings("serial")
<ide> public static class NotAcceptable extends WebClientResponseException {
<ide>
<del> NotAcceptable(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<del> super(HttpStatus.NOT_ACCEPTABLE.value(), statusText, headers, body, charset);
<add> NotAcceptable(String statusText, HttpHeaders headers, byte[] body,
<add> @Nullable Charset charset, @Nullable HttpRequest request) {
<add> super(HttpStatus.NOT_ACCEPTABLE.value(), statusText, headers, body, charset, request);
<ide> }
<ide> }
<ide>
<ide> public static class NotAcceptable extends WebClientResponseException {
<ide> @SuppressWarnings("serial")
<ide> public static class Conflict extends WebClientResponseException {
<ide>
<del> Conflict(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<del> super(HttpStatus.CONFLICT.value(), statusText, headers, body, charset);
<add> Conflict(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset,
<add> @Nullable HttpRequest request) {
<add> super(HttpStatus.CONFLICT.value(), statusText, headers, body, charset, request);
<ide> }
<ide> }
<ide>
<ide> public static class Conflict extends WebClientResponseException {
<ide> @SuppressWarnings("serial")
<ide> public static class Gone extends WebClientResponseException {
<ide>
<del> Gone(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<del> super(HttpStatus.GONE.value(), statusText, headers, body, charset);
<add> Gone(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset,
<add> @Nullable HttpRequest request) {
<add> super(HttpStatus.GONE.value(), statusText, headers, body, charset, request);
<ide> }
<ide> }
<ide>
<ide> public static class Gone extends WebClientResponseException {
<ide> @SuppressWarnings("serial")
<ide> public static class UnsupportedMediaType extends WebClientResponseException {
<ide>
<del> UnsupportedMediaType(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<del> super(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), statusText, headers, body, charset);
<add> UnsupportedMediaType(String statusText, HttpHeaders headers, byte[] body,
<add> @Nullable Charset charset, @Nullable HttpRequest request) {
<add>
<add> super(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), statusText, headers, body, charset,
<add> request);
<ide> }
<ide> }
<ide>
<ide> public static class UnsupportedMediaType extends WebClientResponseException {
<ide> @SuppressWarnings("serial")
<ide> public static class UnprocessableEntity extends WebClientResponseException {
<ide>
<del> UnprocessableEntity(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<del> super(HttpStatus.UNPROCESSABLE_ENTITY.value(), statusText, headers, body, charset);
<add> UnprocessableEntity(String statusText, HttpHeaders headers, byte[] body,
<add> @Nullable Charset charset, @Nullable HttpRequest request) {
<add> super(HttpStatus.UNPROCESSABLE_ENTITY.value(), statusText, headers, body, charset,
<add> request);
<ide> }
<ide> }
<ide>
<ide> public static class UnprocessableEntity extends WebClientResponseException {
<ide> @SuppressWarnings("serial")
<ide> public static class TooManyRequests extends WebClientResponseException {
<ide>
<del> TooManyRequests(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<del> super(HttpStatus.TOO_MANY_REQUESTS.value(), statusText, headers, body, charset);
<add> TooManyRequests(String statusText, HttpHeaders headers, byte[] body,
<add> @Nullable Charset charset, @Nullable HttpRequest request) {
<add> super(HttpStatus.TOO_MANY_REQUESTS.value(), statusText, headers, body, charset,
<add> request);
<ide> }
<ide> }
<ide>
<ide> public static class TooManyRequests extends WebClientResponseException {
<ide> @SuppressWarnings("serial")
<ide> public static class InternalServerError extends WebClientResponseException {
<ide>
<del> InternalServerError(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<del> super(HttpStatus.INTERNAL_SERVER_ERROR.value(), statusText, headers, body, charset);
<add> InternalServerError(String statusText, HttpHeaders headers, byte[] body,
<add> @Nullable Charset charset, @Nullable HttpRequest request) {
<add> super(HttpStatus.INTERNAL_SERVER_ERROR.value(), statusText, headers, body, charset,
<add> request);
<ide> }
<ide> }
<ide>
<ide> public static class InternalServerError extends WebClientResponseException {
<ide> @SuppressWarnings("serial")
<ide> public static class NotImplemented extends WebClientResponseException {
<ide>
<del> NotImplemented(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<del> super(HttpStatus.NOT_IMPLEMENTED.value(), statusText, headers, body, charset);
<add> NotImplemented(String statusText, HttpHeaders headers, byte[] body,
<add> @Nullable Charset charset, @Nullable HttpRequest request) {
<add> super(HttpStatus.NOT_IMPLEMENTED.value(), statusText, headers, body, charset, request);
<ide> }
<ide> }
<ide>
<ide> public static class NotImplemented extends WebClientResponseException {
<ide> @SuppressWarnings("serial")
<ide> public static class BadGateway extends WebClientResponseException {
<ide>
<del> BadGateway(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<del> super(HttpStatus.BAD_GATEWAY.value(), statusText, headers, body, charset);
<add> BadGateway(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset,
<add> @Nullable HttpRequest request) {
<add> super(HttpStatus.BAD_GATEWAY.value(), statusText, headers, body, charset, request);
<ide> }
<ide> }
<ide>
<ide> public static class BadGateway extends WebClientResponseException {
<ide> @SuppressWarnings("serial")
<ide> public static class ServiceUnavailable extends WebClientResponseException {
<ide>
<del> ServiceUnavailable(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<del> super(HttpStatus.SERVICE_UNAVAILABLE.value(), statusText, headers, body, charset);
<add> ServiceUnavailable(String statusText, HttpHeaders headers, byte[] body,
<add> @Nullable Charset charset, @Nullable HttpRequest request) {
<add> super(HttpStatus.SERVICE_UNAVAILABLE.value(), statusText, headers, body, charset,
<add> request);
<ide> }
<ide> }
<ide>
<ide> public static class ServiceUnavailable extends WebClientResponseException {
<ide> @SuppressWarnings("serial")
<ide> public static class GatewayTimeout extends WebClientResponseException {
<ide>
<del> GatewayTimeout(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
<del> super(HttpStatus.GATEWAY_TIMEOUT.value(), statusText, headers, body, charset);
<add> GatewayTimeout(String statusText, HttpHeaders headers, byte[] body,
<add> @Nullable Charset charset, @Nullable HttpRequest request) {
<add> super(HttpStatus.GATEWAY_TIMEOUT.value(), statusText, headers, body, charset,
<add> request);
<ide> }
<ide> }
<ide>
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientIntegrationTests.java
<ide>
<ide> import java.io.ByteArrayOutputStream;
<ide> import java.io.IOException;
<add>import java.net.URI;
<ide> import java.nio.file.Files;
<ide> import java.time.Duration;
<ide> import java.util.Arrays;
<ide> import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory;
<ide> import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.HttpMethod;
<add>import org.springframework.http.HttpRequest;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.ResponseEntity;
<ide> public void shouldGetInternalServerErrorSignal() {
<ide> prepareResponse(response -> response.setResponseCode(500)
<ide> .setHeader("Content-Type", "text/plain").setBody(errorMessage));
<ide>
<add> String path = "/greeting?name=Spring";
<ide> Mono<String> result = this.webClient.get()
<del> .uri("/greeting?name=Spring")
<add> .uri(path)
<ide> .retrieve()
<ide> .bodyToMono(String.class);
<ide>
<ide> public void shouldGetInternalServerErrorSignal() {
<ide> ex.getStatusText());
<ide> assertEquals(MediaType.TEXT_PLAIN, ex.getHeaders().getContentType());
<ide> assertEquals(errorMessage, ex.getResponseBodyAsString());
<add>
<add> HttpRequest request = ex.getRequest();
<add> assertEquals(HttpMethod.GET, request.getMethod());
<add> assertEquals(URI.create(this.server.url(path).toString()), request.getURI());
<add> assertNotNull(request.getHeaders());
<ide> })
<ide> .verify(Duration.ofSeconds(3));
<ide>
<ide> expectRequestCount(1);
<ide> expectRequest(request -> {
<ide> assertEquals("*/*", request.getHeader(HttpHeaders.ACCEPT));
<del> assertEquals("/greeting?name=Spring", request.getPath());
<add> assertEquals(path, request.getPath());
<ide> });
<ide> }
<ide> | 4 |
Text | Text | change rating to ratings | a68e3ef39d4958b1c5c933e3eb3a3c7799e00d15 | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/functional-programming/use-the-map-method-to-extract-data-from-an-array.english.md
<ide> for(var i=0; i < watchList.length; i++){
<ide>
<ide> // Add your code above this line
<ide>
<del>console.log(JSON.stringify(rating));
<add>console.log(JSON.stringify(ratings));
<ide> ```
<ide>
<ide> </div> | 1 |
Text | Text | add fleek fashion to the list of airflow users | bafd258e66ba2a9711118cd024488fb485e2dc22 | <ide><path>INTHEWILD.md
<ide> Currently, **officially** using Airflow:
<ide> 1. [Farfetch](https://github.com/farfetch) [[@davidmarques78](https://github.com/davidmarques78)]
<ide> 1. [Fathom Health](https://www.fathomhealth.co/)
<ide> 1. [Firestone Inventing](https://www.hsmap.com/) [[@zihengCat](https://github.com/zihengCat)]
<add>1. [Fleek Fashion](https://www.fleekfashion.app/) [[@ghodouss](https://github.com/ghodoussG)]
<ide> 1. [Flipp](https://www.flipp.com) [[@sethwilsonwishabi](https://github.com/sethwilsonwishabi)]
<ide> 1. [Format](https://www.format.com) [[@format](https://github.com/4ormat) & [@jasonicarter](https://github.com/jasonicarter)]
<ide> 1. [FreeNow](https://free-now.com) [[@freenowtech](https://github.com/freenowtech)] | 1 |
Javascript | Javascript | add missing test for [ng-app] bootstrap | 9398040a41d0041f949d5b5219eaaf1074cd5699 | <ide><path>test/AngularSpec.js
<ide> describe('angular', function() {
<ide> return element.getElementById[id] || [];
<ide> },
<ide>
<add>
<add> querySelectorAll: function(arg) {
<add> return element.querySelectorAll[arg] || [];
<add> },
<add>
<add>
<ide> getAttribute: function(name) {
<ide> return element[name];
<ide> }
<ide> describe('angular', function() {
<ide> });
<ide>
<ide>
<add> it('should look for ngApp directive as attr', function() {
<add> var appElement = jqLite('<div ng-app="ABC"></div>')[0];
<add> element.querySelectorAll['[ng-app]'] = [appElement];
<add> angularInit(element, bootstrap);
<add> expect(bootstrap).toHaveBeenCalledOnceWith(appElement, ['ABC']);
<add> });
<add>
<add>
<ide> it('should look for ngApp directive in id', function() {
<ide> var appElement = jqLite('<div id="ng-app" data-ng-app="ABC"></div>')[0];
<ide> jqLite(document.body).append(appElement);
<ide> describe('angular', function() {
<ide>
<ide> it('should look for ngApp directive in className', function() {
<ide> var appElement = jqLite('<div data-ng-app="ABC"></div>')[0];
<del> element.querySelectorAll = function(arg) { return element.querySelectorAll[arg] || []; }
<ide> element.querySelectorAll['.ng\\:app'] = [appElement];
<ide> angularInit(element, bootstrap);
<ide> expect(bootstrap).toHaveBeenCalledOnceWith(appElement, ['ABC']);
<ide> describe('angular', function() {
<ide>
<ide> it('should look for ngApp directive using querySelectorAll', function() {
<ide> var appElement = jqLite('<div x-ng-app="ABC"></div>')[0];
<del> element.querySelectorAll = function(arg) { return element.querySelectorAll[arg] || []; }
<ide> element.querySelectorAll['[ng\\:app]'] = [ appElement ];
<ide> angularInit(element, bootstrap);
<ide> expect(bootstrap).toHaveBeenCalledOnceWith(appElement, ['ABC']);
<ide> describe('angular', function() {
<ide>
<ide> it('should bootstrap anonymously', function() {
<ide> var appElement = jqLite('<div x-ng-app></div>')[0];
<del> element.querySelectorAll = function(arg) { return element.querySelectorAll[arg] || []; }
<ide> element.querySelectorAll['[x-ng-app]'] = [ appElement ];
<ide> angularInit(element, bootstrap);
<ide> expect(bootstrap).toHaveBeenCalledOnceWith(appElement, []); | 1 |
Javascript | Javascript | remove obsolete promise filtering | b8c70bd977247fcf0ebaa5df4c76ce4646442cc9 | <ide><path>packages/internal-test-helpers/lib/module-for.js
<ide> export default function moduleFor(description, TestClass, ...mixins) {
<ide> promises.push(instance.afterEach());
<ide> }
<ide>
<del> // this seems odd, but actually saves significant time
<del> // in the test suite
<del> //
<del> // returning a promise from a QUnit test always adds a 13ms
<del> // delay to the test, this filtering prevents returning a
<del> // promise when it is not needed
<del> //
<del> // Remove after we can update to QUnit that includes
<del> // https://github.com/qunitjs/qunit/pull/1246
<del> let filteredPromises = promises.filter(Boolean);
<del> if (filteredPromises.length > 0) {
<del> return all(filteredPromises);
<del> }
<add> return all(promises);
<ide> },
<ide> });
<ide> | 1 |
Ruby | Ruby | use new syntax | d6e0b7d2bfa41e529c9055c13695afdba50b4a9a | <ide><path>Library/Homebrew/linkage_checker.rb
<ide> def display_items(label, things)
<ide> return if things.empty?
<ide> puts "#{label}:"
<ide> if things.is_a? Hash
<del> things.sort_by { |k, | k.to_s }.each do |list_label, list|
<add> things.sort_by(&:to_s).each do |list_label, list|
<ide> list.sort.each do |item|
<ide> puts " #{item} (#{list_label})"
<ide> end | 1 |
PHP | PHP | fix coding standards | 521c293eb182257253e4b073f63f0a95b978a0e0 | <ide><path>lib/Cake/Test/Case/Network/CakeRequestTest.php
<ide> public function testBaseUrlwithModRewriteAlias() {
<ide> */
<ide> public function testBaseUrlWithModRewriteAndIndexPhp() {
<ide> $_SERVER['REQUEST_URI'] = '/cakephp/app/webroot/index.php';
<del> $_SERVER['PHP_SELF'] = '/cakephp/app/webroot/index.php';
<add> $_SERVER['PHP_SELF'] = '/cakephp/app/webroot/index.php';
<ide> unset($_SERVER['PATH_INFO']);
<ide> $request = new CakeRequest();
<ide>
<ide> public function testBaseUrlWithModRewriteAndIndexPhp() {
<ide> $this->assertEquals('/cakephp/', $request->here);
<ide>
<ide> $_SERVER['REQUEST_URI'] = '/cakephp/app/webroot/index.php/';
<del> $_SERVER['PHP_SELF'] = '/cakephp/app/webroot/index.php/';
<del> $_SERVER['PATH_INFO'] = '/';
<add> $_SERVER['PHP_SELF'] = '/cakephp/app/webroot/index.php/';
<add> $_SERVER['PATH_INFO'] = '/';
<ide> $request = new CakeRequest();
<ide>
<ide> $this->assertEquals('/cakephp', $request->base);
<ide> public function testBaseUrlWithModRewriteAndIndexPhp() {
<ide> $this->assertEquals('/cakephp/', $request->here);
<ide>
<ide> $_SERVER['REQUEST_URI'] = '/cakephp/app/webroot/index.php/apples';
<del> $_SERVER['PHP_SELF'] = '/cakephp/app/webroot/index.php/apples';
<del> $_SERVER['PATH_INFO'] = '/apples';
<add> $_SERVER['PHP_SELF'] = '/cakephp/app/webroot/index.php/apples';
<add> $_SERVER['PATH_INFO'] = '/apples';
<ide> $request = new CakeRequest();
<ide>
<ide> $this->assertEquals('/cakephp', $request->base);
<ide> public function testBaseUrlWithModRewriteAndIndexPhp() {
<ide> $this->assertEquals('/cakephp/apples', $request->here);
<ide>
<ide> $_SERVER['REQUEST_URI'] = '/cakephp/app/webroot/index.php/melons/share/';
<del> $_SERVER['PHP_SELF'] = '/cakephp/app/webroot/index.php/melons/share/';
<del> $_SERVER['PATH_INFO'] = '/melons/share/';
<add> $_SERVER['PHP_SELF'] = '/cakephp/app/webroot/index.php/melons/share/';
<add> $_SERVER['PATH_INFO'] = '/melons/share/';
<ide> $request = new CakeRequest();
<ide>
<ide> $this->assertEquals('/cakephp', $request->base);
<ide> public function testBaseUrlWithModRewriteAndIndexPhp() {
<ide> $this->assertEquals('/cakephp/melons/share/', $request->here);
<ide>
<ide> $_SERVER['REQUEST_URI'] = '/cakephp/app/webroot/index.php/bananas/eat/tasty_banana';
<del> $_SERVER['PHP_SELF'] = '/cakephp/app/webroot/index.php/bananas/eat/tasty_banana';
<del> $_SERVER['PATH_INFO'] = '/bananas/eat/tasty_banana';
<add> $_SERVER['PHP_SELF'] = '/cakephp/app/webroot/index.php/bananas/eat/tasty_banana';
<add> $_SERVER['PATH_INFO'] = '/bananas/eat/tasty_banana';
<ide> $request = new CakeRequest();
<ide>
<ide> $this->assertEquals('/cakephp', $request->base);
<ide> public function testBaseUrlWithNoModRewrite() {
<ide> $this->assertEquals('posts/index', $request->url);
<ide> }
<ide>
<del> /**
<add>/**
<ide> * Test baseUrl and webroot with baseUrl
<ide> *
<ide> * @return void | 1 |
Javascript | Javascript | add helpful error message if no filename | 1619a09da25e7a3704101395bcea6790eb159145 | <ide><path>server/utils/getFromDisk$.js
<ide> import { Observable } from 'rx';
<ide> const basePath = process.cwd() + '/seed/challenges/';
<ide>
<ide> export default function getFromDisk$(challenge) {
<add> if (challenge && !challenge.fileName) {
<add> throw new Error(
<add> `Challenge ${challenge.name} has no fileName.
<add> Did you remember run node seed?`
<add> );
<add> }
<ide> delete require.cache[require.resolve(
<ide> path.join(basePath, challenge.fileName)
<ide> )]; | 1 |
Javascript | Javascript | add missing semicolon | 5e53c0cea44d7827e60e51b2dfa1ccb86f1368d6 | <ide><path>fixtures/src/components/fixtures/textareas/index.js
<ide> const TextAreaFixtures = React.createClass({
<ide> return { value: '' };
<ide> },
<ide> onChange(event) {
<del> this.setState({ value: event.target.value })
<add> this.setState({ value: event.target.value });
<ide> },
<ide> render() {
<ide> return ( | 1 |
Ruby | Ruby | remove unneeded test | 0906fc67667c618d5a90fc696799d588e8752709 | <ide><path>railties/test/generators/plugin_generator_test.rb
<ide> def test_generation_does_not_run_bundle_install_with_full_and_mountable
<ide> assert_no_file "#{destination_root}/Gemfile.lock"
<ide> end
<ide>
<del> def test_skip_javascript
<del> run_generator [destination_root, "--skip-javascript", "--mountable"]
<del> assert_file "app/views/layouts/bukkits/application.html.erb" do |content|
<del> assert_no_match "javascript_pack_tag", content
<del> end
<del> end
<del>
<ide> def test_skip_action_mailer_and_skip_active_job_with_mountable
<ide> run_generator [destination_root, "--mountable", "--skip-action-mailer", "--skip-active-job"]
<ide> assert_no_directory "app/mailers" | 1 |
PHP | PHP | move request to http package | 49722a80c424230df1c3510404d15267f2faac9a | <ide><path>src/Http/ServerRequest.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since 2.0.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Http;
<add>
<add>use ArrayAccess;
<add>use BadMethodCallException;
<add>use Cake\Core\Configure;
<add>use Cake\Http\ServerRequestFactory;
<add>use Cake\Network\Session;
<add>use Cake\Network\Exception\MethodNotAllowedException;
<add>use Cake\Utility\Hash;
<add>use InvalidArgumentException;
<add>use Psr\Http\Message\ServerRequestInterface;
<add>use Psr\Http\Message\StreamInterface;
<add>use Psr\Http\Message\UploadedFileInterface;
<add>use Psr\Http\Message\UriInterface;
<add>use Zend\Diactoros\PhpInputStream;
<add>use Zend\Diactoros\Stream;
<add>use Zend\Diactoros\UploadedFile;
<add>
<add>/**
<add> * A class that helps wrap Request information and particulars about a single request.
<add> * Provides methods commonly used to introspect on the request headers and request body.
<add> */
<add>class ServerRequest implements ArrayAccess, ServerRequestInterface
<add>{
<add>
<add> /**
<add> * Array of parameters parsed from the URL.
<add> *
<add> * @var array
<add> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use param() instead.
<add> */
<add> public $params = [
<add> 'plugin' => null,
<add> 'controller' => null,
<add> 'action' => null,
<add> '_ext' => null,
<add> 'pass' => []
<add> ];
<add>
<add> /**
<add> * Array of POST data. Will contain form data as well as uploaded files.
<add> * In PUT/PATCH/DELETE requests this property will contain the form-urlencoded
<add> * data.
<add> *
<add> * @var array
<add> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use data() instead.
<add> */
<add> public $data = [];
<add>
<add> /**
<add> * Array of querystring arguments
<add> *
<add> * @var array
<add> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use query() instead.
<add> */
<add> public $query = [];
<add>
<add> /**
<add> * Array of cookie data.
<add> *
<add> * @var array
<add> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use cookie() instead.
<add> */
<add> public $cookies = [];
<add>
<add> /**
<add> * Array of environment data.
<add> *
<add> * @var array
<add> */
<add> protected $_environment = [];
<add>
<add> /**
<add> * The URL string used for the request.
<add> *
<add> * @var string
<add> */
<add> public $url;
<add>
<add> /**
<add> * Base URL path.
<add> *
<add> * @var string
<add> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getAttribute('base') instead.
<add> */
<add> public $base;
<add>
<add> /**
<add> * webroot path segment for the request.
<add> *
<add> * @var string
<add> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getAttribute('webroot') instead.
<add> */
<add> public $webroot = '/';
<add>
<add> /**
<add> * The full address to the current request
<add> *
<add> * @var string
<add> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use here() instead.
<add> */
<add> public $here;
<add>
<add> /**
<add> * Whether or not to trust HTTP_X headers set by most load balancers.
<add> * Only set to true if your application runs behind load balancers/proxies
<add> * that you control.
<add> *
<add> * @var bool
<add> */
<add> public $trustProxy = false;
<add>
<add> /**
<add> * The built in detectors used with `is()` can be modified with `addDetector()`.
<add> *
<add> * There are several ways to specify a detector, see Cake\Network\Request::addDetector() for the
<add> * various formats and ways to define detectors.
<add> *
<add> * @var array
<add> */
<add> protected static $_detectors = [
<add> 'get' => ['env' => 'REQUEST_METHOD', 'value' => 'GET'],
<add> 'post' => ['env' => 'REQUEST_METHOD', 'value' => 'POST'],
<add> 'put' => ['env' => 'REQUEST_METHOD', 'value' => 'PUT'],
<add> 'patch' => ['env' => 'REQUEST_METHOD', 'value' => 'PATCH'],
<add> 'delete' => ['env' => 'REQUEST_METHOD', 'value' => 'DELETE'],
<add> 'head' => ['env' => 'REQUEST_METHOD', 'value' => 'HEAD'],
<add> 'options' => ['env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'],
<add> 'ssl' => ['env' => 'HTTPS', 'options' => [1, 'on']],
<add> 'ajax' => ['env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'],
<add> 'flash' => ['env' => 'HTTP_USER_AGENT', 'pattern' => '/^(Shockwave|Adobe) Flash/'],
<add> 'requested' => ['param' => 'requested', 'value' => 1],
<add> 'json' => ['accept' => ['application/json'], 'param' => '_ext', 'value' => 'json'],
<add> 'xml' => ['accept' => ['application/xml', 'text/xml'], 'param' => '_ext', 'value' => 'xml'],
<add> ];
<add>
<add> /**
<add> * Instance cache for results of is(something) calls
<add> *
<add> * @var array
<add> */
<add> protected $_detectorCache = [];
<add>
<add> /**
<add> * Request body stream. Contains php://input unless `input` constructor option is used.
<add> *
<add> * @var \Psr\Http\Message\StreamInterface
<add> */
<add> protected $stream;
<add>
<add> /**
<add> * Uri instance
<add> *
<add> * @var \Psr\Http\Message\UriInterface
<add> */
<add> protected $uri;
<add>
<add> /**
<add> * Instance of a Session object relative to this request
<add> *
<add> * @var \Cake\Network\Session
<add> */
<add> protected $session;
<add>
<add> /**
<add> * Store the additional attributes attached to the request.
<add> *
<add> * @var array
<add> */
<add> protected $attributes = [];
<add>
<add> /**
<add> * A list of propertes that emulated by the PSR7 attribute methods.
<add> *
<add> * @var array
<add> */
<add> protected $emulatedAttributes = ['session', 'webroot', 'base', 'params'];
<add>
<add> /**
<add> * Array of Psr\Http\Message\UploadedFileInterface objects.
<add> *
<add> * @var array
<add> */
<add> protected $uploadedFiles = [];
<add>
<add> /**
<add> * The HTTP protocol version used.
<add> *
<add> * @var string|null
<add> */
<add> protected $protocol;
<add>
<add> /**
<add> * The request target if overridden
<add> *
<add> * @var string|null
<add> */
<add> protected $requestTarget;
<add>
<add> /**
<add> * Wrapper method to create a new request from PHP superglobals.
<add> *
<add> * Uses the $_GET, $_POST, $_FILES, $_COOKIE, $_SERVER, $_ENV and php://input data to construct
<add> * the request.
<add> *
<add> * @return \Cake\Network\Request
<add> * @deprecated 3.4.0 Use `Cake\Http\ServerRequestFactory` instead.
<add> */
<add> public static function createFromGlobals()
<add> {
<add> return ServerRequestFactory::fromGlobals();
<add> }
<add>
<add> /**
<add> * Create a new request object.
<add> *
<add> * You can supply the data as either an array or as a string. If you use
<add> * a string you can only supply the URL for the request. Using an array will
<add> * let you provide the following keys:
<add> *
<add> * - `post` POST data or non query string data
<add> * - `query` Additional data from the query string.
<add> * - `files` Uploaded file data formatted like $_FILES.
<add> * - `cookies` Cookies for this request.
<add> * - `environment` $_SERVER and $_ENV data.
<add> * - ~~`url`~~ The URL without the base path for the request. This option is deprecated and will be removed in 4.0.0
<add> * - `uri` The PSR7 UriInterface object. If null, one will be created.
<add> * - `base` The base URL for the request.
<add> * - `webroot` The webroot directory for the request.
<add> * - `input` The data that would come from php://input this is useful for simulating
<add> * requests with put, patch or delete data.
<add> * - `session` An instance of a Session object
<add> *
<add> * @param string|array $config An array of request data to create a request with.
<add> * The string version of this argument is *deprecated* and will be removed in 4.0.0
<add> */
<add> public function __construct($config = [])
<add> {
<add> if (is_string($config)) {
<add> $config = ['url' => $config];
<add> }
<add> $config += [
<add> 'params' => $this->params,
<add> 'query' => [],
<add> 'post' => [],
<add> 'files' => [],
<add> 'cookies' => [],
<add> 'environment' => [],
<add> 'url' => '',
<add> 'uri' => null,
<add> 'base' => '',
<add> 'webroot' => '',
<add> 'input' => null,
<add> ];
<add>
<add> $this->_setConfig($config);
<add> }
<add>
<add> /**
<add> * Process the config/settings data into properties.
<add> *
<add> * @param array $config The config data to use.
<add> * @return void
<add> */
<add> protected function _setConfig($config)
<add> {
<add> if (!empty($config['url']) && $config['url'][0] === '/') {
<add> $config['url'] = substr($config['url'], 1);
<add> }
<add>
<add> if (empty($config['session'])) {
<add> $config['session'] = new Session([
<add> 'cookiePath' => $config['base']
<add> ]);
<add> }
<add>
<add> $this->_environment = $config['environment'];
<add> $this->cookies = $config['cookies'];
<add>
<add> if (isset($config['uri']) && $config['uri'] instanceof UriInterface) {
<add> $uri = $config['uri'];
<add> } else {
<add> $uri = ServerRequestFactory::createUri($config['environment']);
<add> }
<add>
<add> // Extract a query string from config[url] if present.
<add> // This is required for backwards compatbility and keeping
<add> // UriInterface implementations happy.
<add> $querystr = '';
<add> if (strpos($config['url'], '?') !== false) {
<add> list($config['url'], $querystr) = explode('?', $config['url']);
<add> }
<add> if ($config['url']) {
<add> $uri = $uri->withPath('/' . $config['url']);
<add> }
<add>
<add> $this->uri = $uri;
<add> $this->base = $config['base'];
<add> $this->webroot = $config['webroot'];
<add>
<add> $this->url = substr($uri->getPath(), 1);
<add> $this->here = $this->base . '/' . $this->url;
<add>
<add> if (isset($config['input'])) {
<add> $stream = new Stream('php://memory', 'rw');
<add> $stream->write($config['input']);
<add> $stream->rewind();
<add> } else {
<add> $stream = new PhpInputStream();
<add> }
<add> $this->stream = $stream;
<add>
<add> $config['post'] = $this->_processPost($config['post']);
<add> $this->data = $this->_processFiles($config['post'], $config['files']);
<add> $this->query = $this->_processGet($config['query'], $querystr);
<add> $this->params = $config['params'];
<add> $this->session = $config['session'];
<add> }
<add>
<add> /**
<add> * Sets the REQUEST_METHOD environment variable based on the simulated _method
<add> * HTTP override value. The 'ORIGINAL_REQUEST_METHOD' is also preserved, if you
<add> * want the read the non-simulated HTTP method the client used.
<add> *
<add> * @param array $data Array of post data.
<add> * @return array
<add> */
<add> protected function _processPost($data)
<add> {
<add> $method = $this->env('REQUEST_METHOD');
<add> $override = false;
<add>
<add> if (in_array($method, ['PUT', 'DELETE', 'PATCH']) &&
<add> strpos($this->contentType(), 'application/x-www-form-urlencoded') === 0
<add> ) {
<add> $data = $this->input();
<add> parse_str($data, $data);
<add> }
<add> if ($this->hasHeader('X-Http-Method-Override')) {
<add> $data['_method'] = $this->getHeaderLine('X-Http-Method-Override');
<add> $override = true;
<add> }
<add> $this->_environment['ORIGINAL_REQUEST_METHOD'] = $method;
<add> if (isset($data['_method'])) {
<add> $this->_environment['REQUEST_METHOD'] = $data['_method'];
<add> unset($data['_method']);
<add> $override = true;
<add> }
<add>
<add> if ($override && !in_array($this->_environment['REQUEST_METHOD'], ['PUT', 'POST', 'DELETE', 'PATCH'])) {
<add> $data = [];
<add> }
<add>
<add> return $data;
<add> }
<add>
<add> /**
<add> * Process the GET parameters and move things into the object.
<add> *
<add> * @param array $query The array to which the parsed keys/values are being added.
<add> * @param string $queryString A query string from the URL if provided
<add> * @return array An array containing the parsed querystring keys/values.
<add> */
<add> protected function _processGet($query, $queryString = '')
<add> {
<add> $unsetUrl = '/' . str_replace(['.', ' '], '_', urldecode($this->url));
<add> unset($query[$unsetUrl]);
<add> unset($query[$this->base . $unsetUrl]);
<add> if (strlen($queryString)) {
<add> parse_str($queryString, $queryArgs);
<add> $query += $queryArgs;
<add> }
<add>
<add> return $query;
<add> }
<add>
<add> /**
<add> * Process uploaded files and move things onto the post data.
<add> *
<add> * @param array $post Post data to merge files onto.
<add> * @param array $files Uploaded files to merge in.
<add> * @return array merged post + file data.
<add> */
<add> protected function _processFiles($post, $files)
<add> {
<add> if (!is_array($files)) {
<add> return $post;
<add> }
<add> $fileData = [];
<add> foreach ($files as $key => $value) {
<add> if ($value instanceof UploadedFileInterface) {
<add> $fileData[$key] = $value;
<add> continue;
<add> }
<add>
<add> if (is_array($value) && isset($value['tmp_name'])) {
<add> $fileData[$key] = $this->_createUploadedFile($value);
<add> continue;
<add> }
<add>
<add> throw new InvalidArgumentException(sprintf(
<add> 'Invalid value in FILES "%s"',
<add> json_encode($value)
<add> ));
<add> }
<add> $this->uploadedFiles = $fileData;
<add>
<add> // Make a flat map that can be inserted into $post for BC.
<add> $fileMap = Hash::flatten($fileData);
<add> foreach ($fileMap as $key => $file) {
<add> $error = $file->getError();
<add> $tmpName = '';
<add> if ($error === UPLOAD_ERR_OK) {
<add> $tmpName = $file->getStream()->getMetadata('uri');
<add> }
<add> $post = Hash::insert($post, $key, [
<add> 'tmp_name' => $tmpName,
<add> 'error' => $error,
<add> 'name' => $file->getClientFilename(),
<add> 'type' => $file->getClientMediaType(),
<add> 'size' => $file->getSize(),
<add> ]);
<add> }
<add>
<add> return $post;
<add> }
<add>
<add> /**
<add> * Create an UploadedFile instance from a $_FILES array.
<add> *
<add> * If the value represents an array of values, this method will
<add> * recursively process the data.
<add> *
<add> * @param array $value $_FILES struct
<add> * @return array|UploadedFileInterface
<add> */
<add> protected function _createUploadedFile(array $value)
<add> {
<add> if (is_array($value['tmp_name'])) {
<add> return $this->_normalizeNestedFiles($value);
<add> }
<add>
<add> return new UploadedFile(
<add> $value['tmp_name'],
<add> $value['size'],
<add> $value['error'],
<add> $value['name'],
<add> $value['type']
<add> );
<add> }
<add>
<add> /**
<add> * Normalize an array of file specifications.
<add> *
<add> * Loops through all nested files and returns a normalized array of
<add> * UploadedFileInterface instances.
<add> *
<add> * @param array $files The file data to normalize & convert.
<add> * @return array An array of UploadedFileInterface objects.
<add> */
<add> protected function _normalizeNestedFiles(array $files = [])
<add> {
<add> $normalizedFiles = [];
<add> foreach (array_keys($files['tmp_name']) as $key) {
<add> $spec = [
<add> 'tmp_name' => $files['tmp_name'][$key],
<add> 'size' => $files['size'][$key],
<add> 'error' => $files['error'][$key],
<add> 'name' => $files['name'][$key],
<add> 'type' => $files['type'][$key],
<add> ];
<add> $normalizedFiles[$key] = $this->_createUploadedFile($spec);
<add> }
<add>
<add> return $normalizedFiles;
<add> }
<add>
<add> /**
<add> * Get the content type used in this request.
<add> *
<add> * @return string
<add> */
<add> public function contentType()
<add> {
<add> $type = $this->env('CONTENT_TYPE');
<add> if ($type) {
<add> return $type;
<add> }
<add>
<add> return $this->env('HTTP_CONTENT_TYPE');
<add> }
<add>
<add> /**
<add> * Returns the instance of the Session object for this request
<add> *
<add> * If a session object is passed as first argument it will be set as
<add> * the session to use for this request
<add> *
<add> * @param \Cake\Network\Session|null $session the session object to use
<add> * @return \Cake\Network\Session
<add> */
<add> public function session(Session $session = null)
<add> {
<add> if ($session === null) {
<add> return $this->session;
<add> }
<add>
<add> return $this->session = $session;
<add> }
<add>
<add> /**
<add> * Get the IP the client is using, or says they are using.
<add> *
<add> * @return string The client IP.
<add> */
<add> public function clientIp()
<add> {
<add> if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_FOR')) {
<add> $ipaddr = preg_replace('/(?:,.*)/', '', $this->env('HTTP_X_FORWARDED_FOR'));
<add> } elseif ($this->trustProxy && $this->env('HTTP_CLIENT_IP')) {
<add> $ipaddr = $this->env('HTTP_CLIENT_IP');
<add> } else {
<add> $ipaddr = $this->env('REMOTE_ADDR');
<add> }
<add>
<add> return trim($ipaddr);
<add> }
<add>
<add> /**
<add> * Returns the referer that referred this request.
<add> *
<add> * @param bool $local Attempt to return a local address.
<add> * Local addresses do not contain hostnames.
<add> * @return string The referring address for this request.
<add> */
<add> public function referer($local = false)
<add> {
<add> $ref = $this->env('HTTP_REFERER');
<add>
<add> $base = Configure::read('App.fullBaseUrl') . $this->webroot;
<add> if (!empty($ref) && !empty($base)) {
<add> if ($local && strpos($ref, $base) === 0) {
<add> $ref = substr($ref, strlen($base));
<add> if (!strlen($ref)) {
<add> $ref = '/';
<add> }
<add> if ($ref[0] !== '/') {
<add> $ref = '/' . $ref;
<add> }
<add>
<add> return $ref;
<add> }
<add> if (!$local) {
<add> return $ref;
<add> }
<add> }
<add>
<add> return '/';
<add> }
<add>
<add> /**
<add> * Missing method handler, handles wrapping older style isAjax() type methods
<add> *
<add> * @param string $name The method called
<add> * @param array $params Array of parameters for the method call
<add> * @return mixed
<add> * @throws \BadMethodCallException when an invalid method is called.
<add> */
<add> public function __call($name, $params)
<add> {
<add> if (strpos($name, 'is') === 0) {
<add> $type = strtolower(substr($name, 2));
<add>
<add> array_unshift($params, $type);
<add>
<add> return call_user_func_array([$this, 'is'], $params);
<add> }
<add> throw new BadMethodCallException(sprintf('Method %s does not exist', $name));
<add> }
<add>
<add> /**
<add> * Magic get method allows access to parsed routing parameters directly on the object.
<add> *
<add> * Allows access to `$this->params['controller']` via `$this->controller`
<add> *
<add> * @param string $name The property being accessed.
<add> * @return mixed Either the value of the parameter or null.
<add> * @deprecated 3.4.0 Accessing routing parameters through __get will removed in 4.0.0.
<add> * Use param() instead.
<add> */
<add> public function __get($name)
<add> {
<add> if (isset($this->params[$name])) {
<add> return $this->params[$name];
<add> }
<add>
<add> return null;
<add> }
<add>
<add> /**
<add> * Magic isset method allows isset/empty checks
<add> * on routing parameters.
<add> *
<add> * @param string $name The property being accessed.
<add> * @return bool Existence
<add> * @deprecated 3.4.0 Accessing routing parameters through __isset will removed in 4.0.0.
<add> * Use param() instead.
<add> */
<add> public function __isset($name)
<add> {
<add> return isset($this->params[$name]);
<add> }
<add>
<add> /**
<add> * Check whether or not a Request is a certain type.
<add> *
<add> * Uses the built in detection rules as well as additional rules
<add> * defined with Cake\Network\CakeRequest::addDetector(). Any detector can be called
<add> * as `is($type)` or `is$Type()`.
<add> *
<add> * @param string|array $type The type of request you want to check. If an array
<add> * this method will return true if the request matches any type.
<add> * @return bool Whether or not the request is the type you are checking.
<add> */
<add> public function is($type)
<add> {
<add> if (is_array($type)) {
<add> $result = array_map([$this, 'is'], $type);
<add>
<add> return count(array_filter($result)) > 0;
<add> }
<add> $args = func_get_args();
<add> array_shift($args);
<add>
<add> $type = strtolower($type);
<add> if (!isset(static::$_detectors[$type])) {
<add> return false;
<add> }
<add> if ($args) {
<add> return $this->_is($type, $args);
<add> }
<add> if (!isset($this->_detectorCache[$type])) {
<add> $this->_detectorCache[$type] = $this->_is($type, $args);
<add> }
<add>
<add> return $this->_detectorCache[$type];
<add> }
<add>
<add> /**
<add> * Clears the instance detector cache, used by the is() function
<add> *
<add> * @return void
<add> */
<add> public function clearDetectorCache()
<add> {
<add> $this->_detectorCache = [];
<add> }
<add>
<add> /**
<add> * Worker for the public is() function
<add> *
<add> * @param string|array $type The type of request you want to check. If an array
<add> * this method will return true if the request matches any type.
<add> * @param array $args Array of custom detector arguments.
<add> * @return bool Whether or not the request is the type you are checking.
<add> */
<add> protected function _is($type, $args)
<add> {
<add> $detect = static::$_detectors[$type];
<add> if (is_callable($detect)) {
<add> array_unshift($args, $this);
<add>
<add> return call_user_func_array($detect, $args);
<add> }
<add> if (isset($detect['env']) && $this->_environmentDetector($detect)) {
<add> return true;
<add> }
<add> if (isset($detect['header']) && $this->_headerDetector($detect)) {
<add> return true;
<add> }
<add> if (isset($detect['accept']) && $this->_acceptHeaderDetector($detect)) {
<add> return true;
<add> }
<add> if (isset($detect['param']) && $this->_paramDetector($detect)) {
<add> return true;
<add> }
<add>
<add> return false;
<add> }
<add>
<add> /**
<add> * Detects if a specific accept header is present.
<add> *
<add> * @param array $detect Detector options array.
<add> * @return bool Whether or not the request is the type you are checking.
<add> */
<add> protected function _acceptHeaderDetector($detect)
<add> {
<add> $acceptHeaders = explode(',', $this->env('HTTP_ACCEPT'));
<add> foreach ($detect['accept'] as $header) {
<add> if (in_array($header, $acceptHeaders)) {
<add> return true;
<add> }
<add> }
<add>
<add> return false;
<add> }
<add>
<add> /**
<add> * Detects if a specific header is present.
<add> *
<add> * @param array $detect Detector options array.
<add> * @return bool Whether or not the request is the type you are checking.
<add> */
<add> protected function _headerDetector($detect)
<add> {
<add> foreach ($detect['header'] as $header => $value) {
<add> $header = $this->env('http_' . $header);
<add> if ($header !== null) {
<add> if (!is_string($value) && !is_bool($value) && is_callable($value)) {
<add> return call_user_func($value, $header);
<add> }
<add>
<add> return ($header === $value);
<add> }
<add> }
<add>
<add> return false;
<add> }
<add>
<add> /**
<add> * Detects if a specific request parameter is present.
<add> *
<add> * @param array $detect Detector options array.
<add> * @return bool Whether or not the request is the type you are checking.
<add> */
<add> protected function _paramDetector($detect)
<add> {
<add> $key = $detect['param'];
<add> if (isset($detect['value'])) {
<add> $value = $detect['value'];
<add>
<add> return isset($this->params[$key]) ? $this->params[$key] == $value : false;
<add> }
<add> if (isset($detect['options'])) {
<add> return isset($this->params[$key]) ? in_array($this->params[$key], $detect['options']) : false;
<add> }
<add>
<add> return false;
<add> }
<add>
<add> /**
<add> * Detects if a specific environment variable is present.
<add> *
<add> * @param array $detect Detector options array.
<add> * @return bool Whether or not the request is the type you are checking.
<add> */
<add> protected function _environmentDetector($detect)
<add> {
<add> if (isset($detect['env'])) {
<add> if (isset($detect['value'])) {
<add> return $this->env($detect['env']) == $detect['value'];
<add> }
<add> if (isset($detect['pattern'])) {
<add> return (bool)preg_match($detect['pattern'], $this->env($detect['env']));
<add> }
<add> if (isset($detect['options'])) {
<add> $pattern = '/' . implode('|', $detect['options']) . '/i';
<add>
<add> return (bool)preg_match($pattern, $this->env($detect['env']));
<add> }
<add> }
<add>
<add> return false;
<add> }
<add>
<add> /**
<add> * Check that a request matches all the given types.
<add> *
<add> * Allows you to test multiple types and union the results.
<add> * See Request::is() for how to add additional types and the
<add> * built-in types.
<add> *
<add> * @param array $types The types to check.
<add> * @return bool Success.
<add> * @see \Cake\Network\Request::is()
<add> */
<add> public function isAll(array $types)
<add> {
<add> $result = array_filter(array_map([$this, 'is'], $types));
<add>
<add> return count($result) === count($types);
<add> }
<add>
<add> /**
<add> * Add a new detector to the list of detectors that a request can use.
<add> * There are several different formats and types of detectors that can be set.
<add> *
<add> * ### Callback detectors
<add> *
<add> * Callback detectors allow you to provide a callable to handle the check.
<add> * The callback will receive the request object as its only parameter.
<add> *
<add> * ```
<add> * addDetector('custom', function ($request) { //Return a boolean });
<add> * addDetector('custom', ['SomeClass', 'somemethod']);
<add> * ```
<add> *
<add> * ### Environment value comparison
<add> *
<add> * An environment value comparison, compares a value fetched from `env()` to a known value
<add> * the environment value is equality checked against the provided value.
<add> *
<add> * e.g `addDetector('post', ['env' => 'REQUEST_METHOD', 'value' => 'POST'])`
<add> *
<add> * ### Pattern value comparison
<add> *
<add> * Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
<add> *
<add> * ```
<add> * addDetector('iphone', ['env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i']);
<add> * ```
<add> *
<add> * ### Option based comparison
<add> *
<add> * Option based comparisons use a list of options to create a regular expression. Subsequent calls
<add> * to add an already defined options detector will merge the options.
<add> *
<add> * ```
<add> * addDetector('mobile', ['env' => 'HTTP_USER_AGENT', 'options' => ['Fennec']]);
<add> * ```
<add> *
<add> * ### Request parameter detectors
<add> *
<add> * Allows for custom detectors on the request parameters.
<add> *
<add> * e.g `addDetector('requested', ['param' => 'requested', 'value' => 1]`
<add> *
<add> * You can also make parameter detectors that accept multiple values
<add> * using the `options` key. This is useful when you want to check
<add> * if a request parameter is in a list of options.
<add> *
<add> * `addDetector('extension', ['param' => 'ext', 'options' => ['pdf', 'csv']]`
<add> *
<add> * @param string $name The name of the detector.
<add> * @param callable|array $callable A callable or options array for the detector definition.
<add> * @return void
<add> */
<add> public static function addDetector($name, $callable)
<add> {
<add> $name = strtolower($name);
<add> if (is_callable($callable)) {
<add> static::$_detectors[$name] = $callable;
<add>
<add> return;
<add> }
<add> if (isset(static::$_detectors[$name], $callable['options'])) {
<add> $callable = Hash::merge(static::$_detectors[$name], $callable);
<add> }
<add> static::$_detectors[$name] = $callable;
<add> }
<add>
<add> /**
<add> * Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
<add> * This modifies the parameters available through `$request->params`.
<add> *
<add> * @param array $params Array of parameters to merge in
<add> * @return $this The current object, you can chain this method.
<add> */
<add> public function addParams(array $params)
<add> {
<add> $this->params = array_merge($this->params, $params);
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Add paths to the requests' paths vars. This will overwrite any existing paths.
<add> * Provides an easy way to modify, here, webroot and base.
<add> *
<add> * @param array $paths Array of paths to merge in
<add> * @return $this The current object, you can chain this method.
<add> */
<add> public function addPaths(array $paths)
<add> {
<add> foreach (['webroot', 'here', 'base'] as $element) {
<add> if (isset($paths[$element])) {
<add> $this->{$element} = $paths[$element];
<add> }
<add> }
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Get the value of the current requests URL. Will include querystring arguments.
<add> *
<add> * @param bool $base Include the base path, set to false to trim the base path off.
<add> * @return string The current request URL including query string args.
<add> * @deprecated 3.4.0 This method will be removed in 4.0.0. You should use getRequestTarget() instead.
<add> */
<add> public function here($base = true)
<add> {
<add> $url = $this->here;
<add> if (!empty($this->query)) {
<add> $url .= '?' . http_build_query($this->query, null, '&');
<add> }
<add> if (!$base) {
<add> $url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
<add> }
<add>
<add> return $url;
<add> }
<add>
<add> /**
<add> * Normalize a header name into the SERVER version.
<add> *
<add> * @param string $name The header name.
<add> * @return string The normalized header name.
<add> */
<add> protected function normalizeHeaderName($name)
<add> {
<add> $name = str_replace('-', '_', strtoupper($name));
<add> if (!in_array($name, ['CONTENT_LENGTH', 'CONTENT_TYPE'])) {
<add> $name = 'HTTP_' . $name;
<add> }
<add>
<add> return $name;
<add> }
<add>
<add> /**
<add> * Read an HTTP header from the Request information.
<add> *
<add> * If the header is not defined in the request, this method
<add> * will fallback to reading data from $_SERVER and $_ENV.
<add> * This fallback behavior is deprecated, and will be removed in 4.0.0
<add> *
<add> * @param string $name Name of the header you want.
<add> * @return string|null Either null on no header being set or the value of the header.
<add> * @deprecated 4.0.0 The automatic fallback to env() will be removed in 4.0.0
<add> */
<add> public function header($name)
<add> {
<add> $name = $this->normalizeHeaderName($name);
<add>
<add> return $this->env($name);
<add> }
<add>
<add> /**
<add> * Get all headers in the request.
<add> *
<add> * Returns an associative array where the header names are
<add> * the keys and the values are a list of header values.
<add> *
<add> * While header names are not case-sensitive, getHeaders() will normalize
<add> * the headers.
<add> *
<add> * @return array An associative array of headers and their values.
<add> */
<add> public function getHeaders()
<add> {
<add> $headers = [];
<add> foreach ($this->_environment as $key => $value) {
<add> $name = null;
<add> if (strpos($key, 'HTTP_') === 0) {
<add> $name = substr($key, 5);
<add> }
<add> if (strpos($key, 'CONTENT_') === 0) {
<add> $name = $key;
<add> }
<add> if ($name !== null) {
<add> $name = strtr(strtolower($name), '_', ' ');
<add> $name = strtr(ucwords($name), ' ', '-');
<add> $headers[$name] = (array)$value;
<add> }
<add> }
<add>
<add> return $headers;
<add> }
<add>
<add> /**
<add> * Check if a header is set in the request.
<add> *
<add> * @param string $name The header you want to get (case-insensitive)
<add> * @return bool Whether or not the header is defined.
<add> */
<add> public function hasHeader($name)
<add> {
<add> $name = $this->normalizeHeaderName($name);
<add>
<add> return isset($this->_environment[$name]);
<add> }
<add>
<add> /**
<add> * Get a single header from the request.
<add> *
<add> * Return the header value as an array. If the header
<add> * is not present an empty array will be returned.
<add> *
<add> * @param string $name The header you want to get (case-insensitive)
<add> * @return array An associative array of headers and their values.
<add> * If the header doesn't exist, an empty array will be returned.
<add> */
<add> public function getHeader($name)
<add> {
<add> $name = $this->normalizeHeaderName($name);
<add> if (isset($this->_environment[$name])) {
<add> return (array)$this->_environment[$name];
<add> }
<add>
<add> return [];
<add> }
<add>
<add> /**
<add> * Get a single header as a string from the request.
<add> *
<add> * Return an array of header values
<add> *
<add> * @param string $name The header you want to get (case-insensitive)
<add> * @return string Header values collapsed into a comma separated string.
<add> */
<add> public function getHeaderLine($name)
<add> {
<add> $value = $this->getHeader($name);
<add>
<add> return implode(', ', $value);
<add> }
<add>
<add> /**
<add> * Get a modified request with the provided header.
<add> *
<add> * @param string $name The header name.
<add> * @param string|array $value The header value
<add> * @return static
<add> */
<add> public function withHeader($name, $value)
<add> {
<add> $new = clone $this;
<add> $name = $this->normalizeHeaderName($name);
<add> $new->_environment[$name] = $value;
<add>
<add> return $new;
<add> }
<add>
<add> /**
<add> * Get a modified request with the provided header.
<add> *
<add> * Existing header values will be retained. The provided value
<add> * will be appended into the existing values.
<add> *
<add> * @param string $name The header name.
<add> * @param string|array $value The header value
<add> * @return static
<add> */
<add> public function withAddedHeader($name, $value)
<add> {
<add> $new = clone $this;
<add> $name = $this->normalizeHeaderName($name);
<add> $existing = [];
<add> if (isset($new->_environment[$name])) {
<add> $existing = (array)$new->_environment[$name];
<add> }
<add> $existing = array_merge($existing, (array)$value);
<add> $new->_environment[$name] = $existing;
<add>
<add> return $new;
<add> }
<add>
<add> /**
<add> * Get a modified request without a provided header.
<add> *
<add> * @param string $name The header name to remove.
<add> * @return static
<add> */
<add> public function withoutHeader($name)
<add> {
<add> $new = clone $this;
<add> $name = $this->normalizeHeaderName($name);
<add> unset($new->_environment[$name]);
<add>
<add> return $new;
<add> }
<add>
<add> /**
<add> * Get the HTTP method used for this request.
<add> *
<add> * @return string The name of the HTTP method used.
<add> * @deprecated 3.4.0 This method will be removed in 4.0.0. Use getMethod() instead.
<add> */
<add> public function method()
<add> {
<add> return $this->env('REQUEST_METHOD');
<add> }
<add>
<add> /**
<add> * Get the HTTP method used for this request.
<add> * There are a few ways to specify a method.
<add> *
<add> * - If your client supports it you can use native HTTP methods.
<add> * - You can set the HTTP-X-Method-Override header.
<add> * - You can submit an input with the name `_method`
<add> *
<add> * Any of these 3 approaches can be used to set the HTTP method used
<add> * by CakePHP internally, and will effect the result of this method.
<add> *
<add> * @return string The name of the HTTP method used.
<add> */
<add> public function getMethod()
<add> {
<add> return $this->env('REQUEST_METHOD');
<add> }
<add>
<add> /**
<add> * Update the request method and get a new instance.
<add> *
<add> * @param string $method The HTTP method to use.
<add> * @return static A new instance with the updated method.
<add> */
<add> public function withMethod($method)
<add> {
<add> $new = clone $this;
<add>
<add> if (!is_string($method) ||
<add> !preg_match('/^[!#$%&\'*+.^_`\|~0-9a-z-]+$/i', $method)
<add> ) {
<add> throw new InvalidArgumentException(sprintf(
<add> 'Unsupported HTTP method "%s" provided',
<add> $method
<add> ));
<add> }
<add> $new->_environment['REQUEST_METHOD'] = $method;
<add>
<add> return $new;
<add> }
<add>
<add> /**
<add> * Get all the server environment parameters.
<add> *
<add> * Read all of the 'environment' or 'server' data that was
<add> * used to create this request.
<add> *
<add> * @return array
<add> */
<add> public function getServerParams()
<add> {
<add> return $this->_environment;
<add> }
<add>
<add> /**
<add> * Get all the query parameters.
<add> *
<add> * @return array
<add> */
<add> public function getQueryParams()
<add> {
<add> return $this->query;
<add> }
<add>
<add> /**
<add> * Update the query string data and get a new instance.
<add> *
<add> * @param array $query The query string data to use
<add> * @return static A new instance with the updated query string data.
<add> */
<add> public function withQueryParams(array $query)
<add> {
<add> $new = clone $this;
<add> $new->query = $query;
<add>
<add> return $new;
<add> }
<add>
<add> /**
<add> * Get the host that the request was handled on.
<add> *
<add> * @return string
<add> */
<add> public function host()
<add> {
<add> if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_HOST')) {
<add> return $this->env('HTTP_X_FORWARDED_HOST');
<add> }
<add>
<add> return $this->env('HTTP_HOST');
<add> }
<add>
<add> /**
<add> * Get the port the request was handled on.
<add> *
<add> * @return string
<add> */
<add> public function port()
<add> {
<add> if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_PORT')) {
<add> return $this->env('HTTP_X_FORWARDED_PORT');
<add> }
<add>
<add> return $this->env('SERVER_PORT');
<add> }
<add>
<add> /**
<add> * Get the current url scheme used for the request.
<add> *
<add> * e.g. 'http', or 'https'
<add> *
<add> * @return string The scheme used for the request.
<add> */
<add> public function scheme()
<add> {
<add> if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_PROTO')) {
<add> return $this->env('HTTP_X_FORWARDED_PROTO');
<add> }
<add>
<add> return $this->env('HTTPS') ? 'https' : 'http';
<add> }
<add>
<add> /**
<add> * Get the domain name and include $tldLength segments of the tld.
<add> *
<add> * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
<add> * While `example.co.uk` contains 2.
<add> * @return string Domain name without subdomains.
<add> */
<add> public function domain($tldLength = 1)
<add> {
<add> $segments = explode('.', $this->host());
<add> $domain = array_slice($segments, -1 * ($tldLength + 1));
<add>
<add> return implode('.', $domain);
<add> }
<add>
<add> /**
<add> * Get the subdomains for a host.
<add> *
<add> * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
<add> * While `example.co.uk` contains 2.
<add> * @return array An array of subdomains.
<add> */
<add> public function subdomains($tldLength = 1)
<add> {
<add> $segments = explode('.', $this->host());
<add>
<add> return array_slice($segments, 0, -1 * ($tldLength + 1));
<add> }
<add>
<add> /**
<add> * Find out which content types the client accepts or check if they accept a
<add> * particular type of content.
<add> *
<add> * #### Get all types:
<add> *
<add> * ```
<add> * $this->request->accepts();
<add> * ```
<add> *
<add> * #### Check for a single type:
<add> *
<add> * ```
<add> * $this->request->accepts('application/json');
<add> * ```
<add> *
<add> * This method will order the returned content types by the preference values indicated
<add> * by the client.
<add> *
<add> * @param string|null $type The content type to check for. Leave null to get all types a client accepts.
<add> * @return array|bool Either an array of all the types the client accepts or a boolean if they accept the
<add> * provided type.
<add> */
<add> public function accepts($type = null)
<add> {
<add> $raw = $this->parseAccept();
<add> $accept = [];
<add> foreach ($raw as $types) {
<add> $accept = array_merge($accept, $types);
<add> }
<add> if ($type === null) {
<add> return $accept;
<add> }
<add>
<add> return in_array($type, $accept);
<add> }
<add>
<add> /**
<add> * Parse the HTTP_ACCEPT header and return a sorted array with content types
<add> * as the keys, and pref values as the values.
<add> *
<add> * Generally you want to use Cake\Network\Request::accept() to get a simple list
<add> * of the accepted content types.
<add> *
<add> * @return array An array of prefValue => [content/types]
<add> */
<add> public function parseAccept()
<add> {
<add> return $this->_parseAcceptWithQualifier($this->getHeaderLine('Accept'));
<add> }
<add>
<add> /**
<add> * Get the languages accepted by the client, or check if a specific language is accepted.
<add> *
<add> * Get the list of accepted languages:
<add> *
<add> * ``` \Cake\Network\Request::acceptLanguage(); ```
<add> *
<add> * Check if a specific language is accepted:
<add> *
<add> * ``` \Cake\Network\Request::acceptLanguage('es-es'); ```
<add> *
<add> * @param string|null $language The language to test.
<add> * @return array|bool If a $language is provided, a boolean. Otherwise the array of accepted languages.
<add> */
<add> public function acceptLanguage($language = null)
<add> {
<add> $raw = $this->_parseAcceptWithQualifier($this->getHeaderLine('Accept-Language'));
<add> $accept = [];
<add> foreach ($raw as $languages) {
<add> foreach ($languages as &$lang) {
<add> if (strpos($lang, '_')) {
<add> $lang = str_replace('_', '-', $lang);
<add> }
<add> $lang = strtolower($lang);
<add> }
<add> $accept = array_merge($accept, $languages);
<add> }
<add> if ($language === null) {
<add> return $accept;
<add> }
<add>
<add> return in_array(strtolower($language), $accept);
<add> }
<add>
<add> /**
<add> * Parse Accept* headers with qualifier options.
<add> *
<add> * Only qualifiers will be extracted, any other accept extensions will be
<add> * discarded as they are not frequently used.
<add> *
<add> * @param string $header Header to parse.
<add> * @return array
<add> */
<add> protected function _parseAcceptWithQualifier($header)
<add> {
<add> $accept = [];
<add> $header = explode(',', $header);
<add> foreach (array_filter($header) as $value) {
<add> $prefValue = '1.0';
<add> $value = trim($value);
<add>
<add> $semiPos = strpos($value, ';');
<add> if ($semiPos !== false) {
<add> $params = explode(';', $value);
<add> $value = trim($params[0]);
<add> foreach ($params as $param) {
<add> $qPos = strpos($param, 'q=');
<add> if ($qPos !== false) {
<add> $prefValue = substr($param, $qPos + 2);
<add> }
<add> }
<add> }
<add>
<add> if (!isset($accept[$prefValue])) {
<add> $accept[$prefValue] = [];
<add> }
<add> if ($prefValue) {
<add> $accept[$prefValue][] = $value;
<add> }
<add> }
<add> krsort($accept);
<add>
<add> return $accept;
<add> }
<add>
<add> /**
<add> * Provides a read accessor for `$this->query`. Allows you
<add> * to use a syntax similar to `CakeSession` for reading URL query data.
<add> *
<add> * @param string|null $name Query string variable name or null to read all.
<add> * @return string|array|null The value being read
<add> */
<add> public function query($name = null)
<add> {
<add> if ($name === null) {
<add> return $this->query;
<add> }
<add>
<add> return Hash::get($this->query, $name);
<add> }
<add>
<add> /**
<add> * Provides a read/write accessor for `$this->data`. Allows you
<add> * to use a syntax similar to `Cake\Model\Datasource\Session` for reading post data.
<add> *
<add> * ### Reading values.
<add> *
<add> * ```
<add> * $request->data('Post.title');
<add> * ```
<add> *
<add> * When reading values you will get `null` for keys/values that do not exist.
<add> *
<add> * ### Writing values
<add> *
<add> * ```
<add> * $request->data('Post.title', 'New post!');
<add> * ```
<add> *
<add> * As of 3.4.0, the setter mode of this method is *deprecated*.
<add> * Use `withData` instead.
<add> *
<add> * You can write to any value, even paths/keys that do not exist, and the arrays
<add> * will be created for you.
<add> *
<add> * @param string|null $name Dot separated name of the value to read/write
<add> * @param mixed ...$args The data to set (deprecated)
<add> * @return mixed|$this Either the value being read, or this so you can chain consecutive writes.
<add> */
<add> public function data($name = null, ...$args)
<add> {
<add> if (count($args) === 1) {
<add> $this->data = Hash::insert($this->data, $name, $args[0]);
<add>
<add> return $this;
<add> }
<add> if ($name !== null) {
<add> return Hash::get($this->data, $name);
<add> }
<add>
<add> return $this->data;
<add> }
<add>
<add> /**
<add> * Safely access the values in $this->params.
<add> *
<add> * As of 3.4.0, the setter mode of this method is *deprecated*.
<add> * Use `withParam` instead.
<add> *
<add> * @param string $name The name of the parameter to get.
<add> * @param mixed ...$args Value to set (deprecated).
<add> * @return mixed|$this The value of the provided parameter. Will
<add> * return false if the parameter doesn't exist or is falsey.
<add> */
<add> public function param($name, ...$args)
<add> {
<add> if (count($args) === 1) {
<add> $this->params = Hash::insert($this->params, $name, $args[0]);
<add>
<add> return $this;
<add> }
<add> if (!isset($this->params[$name])) {
<add> return Hash::get($this->params, $name, false);
<add> }
<add>
<add> return $this->params[$name];
<add> }
<add>
<add> /**
<add> * Read data from `php://input`. Useful when interacting with XML or JSON
<add> * request body content.
<add> *
<add> * Getting input with a decoding function:
<add> *
<add> * ```
<add> * $this->request->input('json_decode');
<add> * ```
<add> *
<add> * Getting input using a decoding function, and additional params:
<add> *
<add> * ```
<add> * $this->request->input('Xml::build', ['return' => 'DOMDocument']);
<add> * ```
<add> *
<add> * Any additional parameters are applied to the callback in the order they are given.
<add> *
<add> * @param string|null $callback A decoding callback that will convert the string data to another
<add> * representation. Leave empty to access the raw input data. You can also
<add> * supply additional parameters for the decoding callback using var args, see above.
<add> * @param array ...$args The additional arguments
<add> * @return string The decoded/processed request data.
<add> */
<add> public function input($callback = null, ...$args)
<add> {
<add> $input = $this->stream->getContents();
<add> if ($callback) {
<add> array_unshift($args, $input);
<add>
<add> return call_user_func_array($callback, $args);
<add> }
<add>
<add> return $input;
<add> }
<add>
<add> /**
<add> * Read cookie data from the request's cookie data.
<add> *
<add> * @param string $key The key you want to read.
<add> * @return null|string Either the cookie value, or null if the value doesn't exist.
<add> */
<add> public function cookie($key)
<add> {
<add> if (isset($this->cookies[$key])) {
<add> return $this->cookies[$key];
<add> }
<add>
<add> return null;
<add> }
<add>
<add> /**
<add> * Get all the cookie data from the request.
<add> *
<add> * @return array An array of cookie data.
<add> */
<add> public function getCookieParams()
<add> {
<add> return $this->cookies;
<add> }
<add>
<add> /**
<add> * Replace the cookies and get a new request instance.
<add> *
<add> * @param array $cookies The new cookie data to use.
<add> * @return static
<add> */
<add> public function withCookieParams(array $cookies)
<add> {
<add> $new = clone $this;
<add> $new->cookies = $cookies;
<add>
<add> return $new;
<add> }
<add>
<add> /**
<add> * Get the parsed request body data.
<add> *
<add> * If the request Content-Type is either application/x-www-form-urlencoded
<add> * or multipart/form-data, nd the request method is POST, this will be the
<add> * post data. For other content types, it may be the deserialized request
<add> * body.
<add> *
<add> * @return null|array|object The deserialized body parameters, if any.
<add> * These will typically be an array or object.
<add> */
<add> public function getParsedBody()
<add> {
<add> return $this->data;
<add> }
<add>
<add> /**
<add> * Update the parsed body and get a new instance.
<add> *
<add> * @param null|array|object $data The deserialized body data. This will
<add> * typically be in an array or object.
<add> * @return static
<add> */
<add> public function withParsedBody($data)
<add> {
<add> $new = clone $this;
<add> $new->data = $data;
<add>
<add> return $new;
<add> }
<add>
<add> /**
<add> * Retrieves the HTTP protocol version as a string.
<add> *
<add> * @return string HTTP protocol version.
<add> */
<add> public function getProtocolVersion()
<add> {
<add> if ($this->protocol) {
<add> return $this->protocol;
<add> }
<add>
<add> // Lazily populate this data as it is generally not used.
<add> preg_match('/^HTTP\/([\d.]+)$/', $this->env('SERVER_PROTOCOL'), $match);
<add> $protocol = '1.1';
<add> if (isset($match[1])) {
<add> $protocol = $match[1];
<add> }
<add> $this->protocol = $protocol;
<add>
<add> return $this->protocol;
<add> }
<add>
<add> /**
<add> * Return an instance with the specified HTTP protocol version.
<add> *
<add> * The version string MUST contain only the HTTP version number (e.g.,
<add> * "1.1", "1.0").
<add> *
<add> * @param string $version HTTP protocol version
<add> * @return static
<add> */
<add> public function withProtocolVersion($version)
<add> {
<add> if (!preg_match('/^(1\.[01]|2)$/', $version)) {
<add> throw new InvalidArgumentException("Unsupported protocol version '{$version}' provided");
<add> }
<add> $new = clone $this;
<add> $new->protocol = $version;
<add>
<add> return $new;
<add> }
<add>
<add> /**
<add> * Get/Set value from the request's environment data.
<add> * Fallback to using env() if key not set in $environment property.
<add> *
<add> * @param string $key The key you want to read/write from/to.
<add> * @param string|null $value Value to set. Default null.
<add> * @param string|null $default Default value when trying to retrieve an environment
<add> * variable's value that does not exist. The value parameter must be null.
<add> * @return $this|string|null This instance if used as setter,
<add> * if used as getter either the environment value, or null if the value doesn't exist.
<add> */
<add> public function env($key, $value = null, $default = null)
<add> {
<add> if ($value !== null) {
<add> $this->_environment[$key] = $value;
<add> $this->clearDetectorCache();
<add>
<add> return $this;
<add> }
<add>
<add> $key = strtoupper($key);
<add> if (!array_key_exists($key, $this->_environment)) {
<add> $this->_environment[$key] = env($key);
<add> }
<add>
<add> return $this->_environment[$key] !== null ? $this->_environment[$key] : $default;
<add> }
<add>
<add> /**
<add> * Allow only certain HTTP request methods, if the request method does not match
<add> * a 405 error will be shown and the required "Allow" response header will be set.
<add> *
<add> * Example:
<add> *
<add> * $this->request->allowMethod('post');
<add> * or
<add> * $this->request->allowMethod(['post', 'delete']);
<add> *
<add> * If the request would be GET, response header "Allow: POST, DELETE" will be set
<add> * and a 405 error will be returned.
<add> *
<add> * @param string|array $methods Allowed HTTP request methods.
<add> * @return bool true
<add> * @throws \Cake\Network\Exception\MethodNotAllowedException
<add> */
<add> public function allowMethod($methods)
<add> {
<add> $methods = (array)$methods;
<add> foreach ($methods as $method) {
<add> if ($this->is($method)) {
<add> return true;
<add> }
<add> }
<add> $allowed = strtoupper(implode(', ', $methods));
<add> $e = new MethodNotAllowedException();
<add> $e->responseHeader('Allow', $allowed);
<add> throw $e;
<add> }
<add>
<add> /**
<add> * Read data from php://input, mocked in tests.
<add> *
<add> * @return string contents of php://input
<add> */
<add> protected function _readInput()
<add> {
<add> if (empty($this->_input)) {
<add> $fh = fopen('php://input', 'r');
<add> $content = stream_get_contents($fh);
<add> fclose($fh);
<add> $this->_input = $content;
<add> }
<add>
<add> return $this->_input;
<add> }
<add>
<add> /**
<add> * Modify data originally from `php://input`. Useful for altering json/xml data
<add> * in middleware or DispatcherFilters before it gets to RequestHandlerComponent
<add> *
<add> * @param string $input A string to replace original parsed data from input()
<add> * @return void
<add> * @deprecated 3.4.0 This method will be removed in 4.0.0. Use withBody() instead.
<add> */
<add> public function setInput($input)
<add> {
<add> $stream = new Stream('php://memory', 'rw');
<add> $stream->write($input);
<add> $stream->rewind();
<add> $this->stream = $stream;
<add> }
<add>
<add> /**
<add> * Update the request with a new request data element.
<add> *
<add> * Returns an updated request object. This method returns
<add> * a *new* request object and does not mutate the request in-place.
<add> *
<add> * @param string $name The dot separated path to insert $value at.
<add> * @param mixed $value The value to insert into the request data.
<add> * @return static
<add> */
<add> public function withData($name, $value)
<add> {
<add> $copy = clone $this;
<add> $copy->data = Hash::insert($copy->data, $name, $value);
<add>
<add> return $copy;
<add> }
<add>
<add> /**
<add> * Update the request with a new routing parameter
<add> *
<add> * Returns an updated request object. This method returns
<add> * a *new* request object and does not mutate the request in-place.
<add> *
<add> * @param string $name The dot separated path to insert $value at.
<add> * @param mixed $value The value to insert into the the request parameters.
<add> * @return static
<add> */
<add> public function withParam($name, $value)
<add> {
<add> $copy = clone $this;
<add> $copy->params = Hash::insert($copy->params, $name, $value);
<add>
<add> return $copy;
<add> }
<add>
<add> /**
<add> * Return an instance with the specified request attribute.
<add> *
<add> * @param string $name The attribute name.
<add> * @param mixed $value The value of the attribute.
<add> * @return static
<add> */
<add> public function withAttribute($name, $value)
<add> {
<add> $new = clone $this;
<add> if (in_array($name, $this->emulatedAttributes, true)) {
<add> $new->{$name} = $value;
<add> } else {
<add> $new->attributes[$name] = $value;
<add> }
<add>
<add> return $new;
<add> }
<add>
<add> /**
<add> * Return an instance without the specified request attribute.
<add> *
<add> * @param string $name The attribute name.
<add> * @return static
<add> * @throws InvalidArgumentException
<add> */
<add> public function withoutAttribute($name)
<add> {
<add> $new = clone $this;
<add> if (in_array($name, $this->emulatedAttributes, true)) {
<add> throw new InvalidArgumentException(
<add> "You cannot unset '$name'. It is a required CakePHP attribute."
<add> );
<add> }
<add> unset($new->attributes[$name]);
<add>
<add> return $new;
<add> }
<add>
<add> /**
<add> * Read an attribute from the request, or get the default
<add> *
<add> * @param string $name The attribute name.
<add> * @param mixed|null $default The default value if the attribute has not been set.
<add> * @return static
<add> */
<add> public function getAttribute($name, $default = null)
<add> {
<add> if (in_array($name, $this->emulatedAttributes, true)) {
<add> return $this->{$name};
<add> }
<add> if (array_key_exists($name, $this->attributes)) {
<add> return $this->attributes[$name];
<add> }
<add>
<add> return $default;
<add> }
<add>
<add> /**
<add> * Get all the attributes in the request.
<add> *
<add> * This will include the params, webroot, and base attributes that CakePHP
<add> * provides.
<add> *
<add> * @return array
<add> */
<add> public function getAttributes()
<add> {
<add> $emulated = [
<add> 'params' => $this->params,
<add> 'webroot' => $this->webroot,
<add> 'base' => $this->base
<add> ];
<add>
<add> return $this->attributes + $emulated;
<add> }
<add>
<add> /**
<add> * Get the uploaded file from a dotted path.
<add> *
<add> * @param string $path The dot separated path to the file you want.
<add> * @return null|Psr\Http\Message\UploadedFileInterface
<add> */
<add> public function getUploadedFile($path)
<add> {
<add> $file = Hash::get($this->uploadedFiles, $path);
<add> if (!$file instanceof UploadedFile) {
<add> return null;
<add> }
<add>
<add> return $file;
<add> }
<add>
<add> /**
<add> * Get the array of uploaded files from the request.
<add> *
<add> * @return array
<add> */
<add> public function getUploadedFiles()
<add> {
<add> return $this->uploadedFiles;
<add> }
<add>
<add> /**
<add> * Update the request replacing the files, and creating a new instance.
<add> *
<add> * @param array $files An array of uploaded file objects.
<add> * @return static
<add> * @throws InvalidArgumentException when $files contains an invalid object.
<add> */
<add> public function withUploadedFiles(array $files)
<add> {
<add> $this->validateUploadedFiles($files, '');
<add> $new = clone $this;
<add> $new->uploadedFiles = $files;
<add>
<add> return $new;
<add> }
<add>
<add> /**
<add> * Recursively validate uploaded file data.
<add> *
<add> * @param array $uploadedFiles The new files array to validate.
<add> * @param string $path The path thus far.
<add> * @return void
<add> * @throws InvalidArgumentException If any leaf elements are not valid files.
<add> */
<add> protected function validateUploadedFiles(array $uploadedFiles, $path)
<add> {
<add> foreach ($uploadedFiles as $key => $file) {
<add> if (is_array($file)) {
<add> $this->validateUploadedFiles($file, $key . '.');
<add> continue;
<add> }
<add>
<add> if (!$file instanceof UploadedFileInterface) {
<add> throw new InvalidArgumentException("Invalid file at '{$path}{$key}'");
<add> }
<add> }
<add> }
<add>
<add> /**
<add> * Gets the body of the message.
<add> *
<add> * @return \Psr\Http\Message\StreamInterface Returns the body as a stream.
<add> */
<add> public function getBody()
<add> {
<add> return $this->stream;
<add> }
<add>
<add> /**
<add> * Return an instance with the specified message body.
<add> *
<add> * @param \Psr\Http\Message\StreamInterface $body The new request body
<add> * @return static
<add> */
<add> public function withBody(StreamInterface $body)
<add> {
<add> $new = clone $this;
<add> $new->stream = $body;
<add>
<add> return $new;
<add> }
<add>
<add> /**
<add> * Retrieves the URI instance.
<add> *
<add> * @return \Psr\Http\Message\UriInterface Returns a UriInterface instance
<add> * representing the URI of the request.
<add> */
<add> public function getUri()
<add> {
<add> return $this->uri;
<add> }
<add>
<add> /**
<add> * Return an instance with the specified uri
<add> *
<add> * *Warning* Replacing the Uri will not update the `base`, `webroot`,
<add> * and `url` attributes.
<add> *
<add> * @param \Psr\Http\Message\UriInterface $uri The new request uri
<add> * @param bool $preserveHost Whether or not the host should be retained.
<add> * @return static
<add> */
<add> public function withUri(UriInterface $uri, $preserveHost = false)
<add> {
<add> $new = clone $this;
<add> $new->uri = $uri;
<add>
<add> if ($preserveHost && $this->hasHeader('Host')) {
<add> return $new;
<add> }
<add>
<add> $host = $uri->getHost();
<add> if (!$host) {
<add> return $new;
<add> }
<add> if ($uri->getPort()) {
<add> $host .= ':' . $uri->getPort();
<add> }
<add> $new->_environment['HTTP_HOST'] = $host;
<add>
<add> return $new;
<add> }
<add>
<add> /**
<add> * Create a new instance with a specific request-target.
<add> *
<add> * You can use this method to overwrite the request target that is
<add> * inferred from the request's Uri. This also lets you change the request
<add> * target's form to an absolute-form, authority-form or asterisk-form
<add> *
<add> * @link http://tools.ietf.org/html/rfc7230#section-2.7 (for the various
<add> * request-target forms allowed in request messages)
<add> * @param string $target The request target.
<add> * @return static
<add> */
<add> public function withRequestTarget($target)
<add> {
<add> $new = clone $this;
<add> $new->requestTarget = $target;
<add>
<add> return $new;
<add> }
<add>
<add> /**
<add> * Retrieves the request's target.
<add> *
<add> * Retrieves the message's request-target either as it was requested,
<add> * or as set with `withRequestTarget()`. By default this will return the
<add> * application relative path without base directory, and the query string
<add> * defined in the SERVER environment.
<add> *
<add> * @return string
<add> */
<add> public function getRequestTarget()
<add> {
<add> if ($this->requestTarget !== null) {
<add> return $this->requestTarget;
<add> }
<add>
<add> $target = $this->uri->getPath();
<add> if ($this->uri->getQuery()) {
<add> $target .= '?' . $this->uri->getQuery();
<add> }
<add>
<add> if (empty($target)) {
<add> $target = '/';
<add> }
<add>
<add> return $target;
<add> }
<add>
<add> /**
<add> * Array access read implementation
<add> *
<add> * @param string $name Name of the key being accessed.
<add> * @return mixed
<add> * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use param(), data() and query() instead.
<add> */
<add> public function offsetGet($name)
<add> {
<add> if (isset($this->params[$name])) {
<add> return $this->params[$name];
<add> }
<add> if ($name === 'url') {
<add> return $this->query;
<add> }
<add> if ($name === 'data') {
<add> return $this->data;
<add> }
<add>
<add> return null;
<add> }
<add>
<add> /**
<add> * Array access write implementation
<add> *
<add> * @param string $name Name of the key being written
<add> * @param mixed $value The value being written.
<add> * @return void
<add> * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use param(), data() and query() instead.
<add> */
<add> public function offsetSet($name, $value)
<add> {
<add> $this->params[$name] = $value;
<add> }
<add>
<add> /**
<add> * Array access isset() implementation
<add> *
<add> * @param string $name thing to check.
<add> * @return bool
<add> * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use param(), data() and query() instead.
<add> */
<add> public function offsetExists($name)
<add> {
<add> if ($name === 'url' || $name === 'data') {
<add> return true;
<add> }
<add>
<add> return isset($this->params[$name]);
<add> }
<add>
<add> /**
<add> * Array access unset() implementation
<add> *
<add> * @param string $name Name to unset.
<add> * @return void
<add> * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use param(), data() and query() instead.
<add> */
<add> public function offsetUnset($name)
<add> {
<add> unset($this->params[$name]);
<add> }
<add>}
<ide><path>src/Http/ServerRequestFactory.php
<ide> namespace Cake\Http;
<ide>
<ide> use Cake\Core\Configure;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Network\Session;
<ide> use Cake\Utility\Hash;
<ide> use Zend\Diactoros\ServerRequestFactory as BaseFactory;
<ide> public static function fromGlobals(
<ide> 'cookiePath' => $uri->webroot
<ide> ];
<ide> $session = Session::create($sessionConfig);
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'environment' => $server,
<ide> 'uri' => $uri,
<ide> 'files' => $files,
<ide><path>src/Network/Request.php
<ide> <?php
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://cakephp.org CakePHP(tm) Project
<del> * @since 2.0.0
<del> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\Network;
<del>
<del>use ArrayAccess;
<del>use BadMethodCallException;
<del>use Cake\Core\Configure;
<del>use Cake\Http\ServerRequestFactory;
<del>use Cake\Network\Exception\MethodNotAllowedException;
<del>use Cake\Utility\Hash;
<del>use InvalidArgumentException;
<del>use Psr\Http\Message\ServerRequestInterface;
<del>use Psr\Http\Message\StreamInterface;
<del>use Psr\Http\Message\UploadedFileInterface;
<del>use Psr\Http\Message\UriInterface;
<del>use Zend\Diactoros\PhpInputStream;
<del>use Zend\Diactoros\Stream;
<del>use Zend\Diactoros\UploadedFile;
<del>
<del>/**
<del> * A class that helps wrap Request information and particulars about a single request.
<del> * Provides methods commonly used to introspect on the request headers and request body.
<del> */
<del>class Request implements ArrayAccess, ServerRequestInterface
<del>{
<del>
<del> /**
<del> * Array of parameters parsed from the URL.
<del> *
<del> * @var array
<del> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use param() instead.
<del> */
<del> public $params = [
<del> 'plugin' => null,
<del> 'controller' => null,
<del> 'action' => null,
<del> '_ext' => null,
<del> 'pass' => []
<del> ];
<del>
<del> /**
<del> * Array of POST data. Will contain form data as well as uploaded files.
<del> * In PUT/PATCH/DELETE requests this property will contain the form-urlencoded
<del> * data.
<del> *
<del> * @var array
<del> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use data() instead.
<del> */
<del> public $data = [];
<del>
<del> /**
<del> * Array of querystring arguments
<del> *
<del> * @var array
<del> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use query() instead.
<del> */
<del> public $query = [];
<del>
<del> /**
<del> * Array of cookie data.
<del> *
<del> * @var array
<del> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use cookie() instead.
<del> */
<del> public $cookies = [];
<del>
<del> /**
<del> * Array of environment data.
<del> *
<del> * @var array
<del> */
<del> protected $_environment = [];
<del>
<del> /**
<del> * The URL string used for the request.
<del> *
<del> * @var string
<del> */
<del> public $url;
<del>
<del> /**
<del> * Base URL path.
<del> *
<del> * @var string
<del> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getAttribute('base') instead.
<del> */
<del> public $base;
<del>
<del> /**
<del> * webroot path segment for the request.
<del> *
<del> * @var string
<del> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getAttribute('webroot') instead.
<del> */
<del> public $webroot = '/';
<del>
<del> /**
<del> * The full address to the current request
<del> *
<del> * @var string
<del> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use here() instead.
<del> */
<del> public $here;
<del>
<del> /**
<del> * Whether or not to trust HTTP_X headers set by most load balancers.
<del> * Only set to true if your application runs behind load balancers/proxies
<del> * that you control.
<del> *
<del> * @var bool
<del> */
<del> public $trustProxy = false;
<del>
<del> /**
<del> * The built in detectors used with `is()` can be modified with `addDetector()`.
<del> *
<del> * There are several ways to specify a detector, see Cake\Network\Request::addDetector() for the
<del> * various formats and ways to define detectors.
<del> *
<del> * @var array
<del> */
<del> protected static $_detectors = [
<del> 'get' => ['env' => 'REQUEST_METHOD', 'value' => 'GET'],
<del> 'post' => ['env' => 'REQUEST_METHOD', 'value' => 'POST'],
<del> 'put' => ['env' => 'REQUEST_METHOD', 'value' => 'PUT'],
<del> 'patch' => ['env' => 'REQUEST_METHOD', 'value' => 'PATCH'],
<del> 'delete' => ['env' => 'REQUEST_METHOD', 'value' => 'DELETE'],
<del> 'head' => ['env' => 'REQUEST_METHOD', 'value' => 'HEAD'],
<del> 'options' => ['env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'],
<del> 'ssl' => ['env' => 'HTTPS', 'options' => [1, 'on']],
<del> 'ajax' => ['env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'],
<del> 'flash' => ['env' => 'HTTP_USER_AGENT', 'pattern' => '/^(Shockwave|Adobe) Flash/'],
<del> 'requested' => ['param' => 'requested', 'value' => 1],
<del> 'json' => ['accept' => ['application/json'], 'param' => '_ext', 'value' => 'json'],
<del> 'xml' => ['accept' => ['application/xml', 'text/xml'], 'param' => '_ext', 'value' => 'xml'],
<del> ];
<del>
<del> /**
<del> * Instance cache for results of is(something) calls
<del> *
<del> * @var array
<del> */
<del> protected $_detectorCache = [];
<del>
<del> /**
<del> * Request body stream. Contains php://input unless `input` constructor option is used.
<del> *
<del> * @var \Psr\Http\Message\StreamInterface
<del> */
<del> protected $stream;
<del>
<del> /**
<del> * Uri instance
<del> *
<del> * @var \Psr\Http\Message\UriInterface
<del> */
<del> protected $uri;
<del>
<del> /**
<del> * Instance of a Session object relative to this request
<del> *
<del> * @var \Cake\Network\Session
<del> */
<del> protected $session;
<del>
<del> /**
<del> * Store the additional attributes attached to the request.
<del> *
<del> * @var array
<del> */
<del> protected $attributes = [];
<del>
<del> /**
<del> * A list of propertes that emulated by the PSR7 attribute methods.
<del> *
<del> * @var array
<del> */
<del> protected $emulatedAttributes = ['session', 'webroot', 'base', 'params'];
<del>
<del> /**
<del> * Array of Psr\Http\Message\UploadedFileInterface objects.
<del> *
<del> * @var array
<del> */
<del> protected $uploadedFiles = [];
<del>
<del> /**
<del> * The HTTP protocol version used.
<del> *
<del> * @var string|null
<del> */
<del> protected $protocol;
<del>
<del> /**
<del> * The request target if overridden
<del> *
<del> * @var string|null
<del> */
<del> protected $requestTarget;
<del>
<del> /**
<del> * Wrapper method to create a new request from PHP superglobals.
<del> *
<del> * Uses the $_GET, $_POST, $_FILES, $_COOKIE, $_SERVER, $_ENV and php://input data to construct
<del> * the request.
<del> *
<del> * @return \Cake\Network\Request
<del> * @deprecated 3.4.0 Use `Cake\Http\ServerRequestFactory` instead.
<del> */
<del> public static function createFromGlobals()
<del> {
<del> return ServerRequestFactory::fromGlobals();
<del> }
<del>
<del> /**
<del> * Create a new request object.
<del> *
<del> * You can supply the data as either an array or as a string. If you use
<del> * a string you can only supply the URL for the request. Using an array will
<del> * let you provide the following keys:
<del> *
<del> * - `post` POST data or non query string data
<del> * - `query` Additional data from the query string.
<del> * - `files` Uploaded file data formatted like $_FILES.
<del> * - `cookies` Cookies for this request.
<del> * - `environment` $_SERVER and $_ENV data.
<del> * - ~~`url`~~ The URL without the base path for the request. This option is deprecated and will be removed in 4.0.0
<del> * - `uri` The PSR7 UriInterface object. If null, one will be created.
<del> * - `base` The base URL for the request.
<del> * - `webroot` The webroot directory for the request.
<del> * - `input` The data that would come from php://input this is useful for simulating
<del> * requests with put, patch or delete data.
<del> * - `session` An instance of a Session object
<del> *
<del> * @param string|array $config An array of request data to create a request with.
<del> * The string version of this argument is *deprecated* and will be removed in 4.0.0
<del> */
<del> public function __construct($config = [])
<del> {
<del> if (is_string($config)) {
<del> $config = ['url' => $config];
<del> }
<del> $config += [
<del> 'params' => $this->params,
<del> 'query' => [],
<del> 'post' => [],
<del> 'files' => [],
<del> 'cookies' => [],
<del> 'environment' => [],
<del> 'url' => '',
<del> 'uri' => null,
<del> 'base' => '',
<del> 'webroot' => '',
<del> 'input' => null,
<del> ];
<del>
<del> $this->_setConfig($config);
<del> }
<del>
<del> /**
<del> * Process the config/settings data into properties.
<del> *
<del> * @param array $config The config data to use.
<del> * @return void
<del> */
<del> protected function _setConfig($config)
<del> {
<del> if (!empty($config['url']) && $config['url'][0] === '/') {
<del> $config['url'] = substr($config['url'], 1);
<del> }
<del>
<del> if (empty($config['session'])) {
<del> $config['session'] = new Session([
<del> 'cookiePath' => $config['base']
<del> ]);
<del> }
<del>
<del> $this->_environment = $config['environment'];
<del> $this->cookies = $config['cookies'];
<del>
<del> if (isset($config['uri']) && $config['uri'] instanceof UriInterface) {
<del> $uri = $config['uri'];
<del> } else {
<del> $uri = ServerRequestFactory::createUri($config['environment']);
<del> }
<del>
<del> // Extract a query string from config[url] if present.
<del> // This is required for backwards compatbility and keeping
<del> // UriInterface implementations happy.
<del> $querystr = '';
<del> if (strpos($config['url'], '?') !== false) {
<del> list($config['url'], $querystr) = explode('?', $config['url']);
<del> }
<del> if ($config['url']) {
<del> $uri = $uri->withPath('/' . $config['url']);
<del> }
<del>
<del> $this->uri = $uri;
<del> $this->base = $config['base'];
<del> $this->webroot = $config['webroot'];
<del>
<del> $this->url = substr($uri->getPath(), 1);
<del> $this->here = $this->base . '/' . $this->url;
<del>
<del> if (isset($config['input'])) {
<del> $stream = new Stream('php://memory', 'rw');
<del> $stream->write($config['input']);
<del> $stream->rewind();
<del> } else {
<del> $stream = new PhpInputStream();
<del> }
<del> $this->stream = $stream;
<del>
<del> $config['post'] = $this->_processPost($config['post']);
<del> $this->data = $this->_processFiles($config['post'], $config['files']);
<del> $this->query = $this->_processGet($config['query'], $querystr);
<del> $this->params = $config['params'];
<del> $this->session = $config['session'];
<del> }
<del>
<del> /**
<del> * Sets the REQUEST_METHOD environment variable based on the simulated _method
<del> * HTTP override value. The 'ORIGINAL_REQUEST_METHOD' is also preserved, if you
<del> * want the read the non-simulated HTTP method the client used.
<del> *
<del> * @param array $data Array of post data.
<del> * @return array
<del> */
<del> protected function _processPost($data)
<del> {
<del> $method = $this->env('REQUEST_METHOD');
<del> $override = false;
<del>
<del> if (in_array($method, ['PUT', 'DELETE', 'PATCH']) &&
<del> strpos($this->contentType(), 'application/x-www-form-urlencoded') === 0
<del> ) {
<del> $data = $this->input();
<del> parse_str($data, $data);
<del> }
<del> if ($this->hasHeader('X-Http-Method-Override')) {
<del> $data['_method'] = $this->getHeaderLine('X-Http-Method-Override');
<del> $override = true;
<del> }
<del> $this->_environment['ORIGINAL_REQUEST_METHOD'] = $method;
<del> if (isset($data['_method'])) {
<del> $this->_environment['REQUEST_METHOD'] = $data['_method'];
<del> unset($data['_method']);
<del> $override = true;
<del> }
<del>
<del> if ($override && !in_array($this->_environment['REQUEST_METHOD'], ['PUT', 'POST', 'DELETE', 'PATCH'])) {
<del> $data = [];
<del> }
<del>
<del> return $data;
<del> }
<del>
<del> /**
<del> * Process the GET parameters and move things into the object.
<del> *
<del> * @param array $query The array to which the parsed keys/values are being added.
<del> * @param string $queryString A query string from the URL if provided
<del> * @return array An array containing the parsed querystring keys/values.
<del> */
<del> protected function _processGet($query, $queryString = '')
<del> {
<del> $unsetUrl = '/' . str_replace(['.', ' '], '_', urldecode($this->url));
<del> unset($query[$unsetUrl]);
<del> unset($query[$this->base . $unsetUrl]);
<del> if (strlen($queryString)) {
<del> parse_str($queryString, $queryArgs);
<del> $query += $queryArgs;
<del> }
<del>
<del> return $query;
<del> }
<del>
<del> /**
<del> * Process uploaded files and move things onto the post data.
<del> *
<del> * @param array $post Post data to merge files onto.
<del> * @param array $files Uploaded files to merge in.
<del> * @return array merged post + file data.
<del> */
<del> protected function _processFiles($post, $files)
<del> {
<del> if (!is_array($files)) {
<del> return $post;
<del> }
<del> $fileData = [];
<del> foreach ($files as $key => $value) {
<del> if ($value instanceof UploadedFileInterface) {
<del> $fileData[$key] = $value;
<del> continue;
<del> }
<del>
<del> if (is_array($value) && isset($value['tmp_name'])) {
<del> $fileData[$key] = $this->_createUploadedFile($value);
<del> continue;
<del> }
<del>
<del> throw new InvalidArgumentException(sprintf(
<del> 'Invalid value in FILES "%s"',
<del> json_encode($value)
<del> ));
<del> }
<del> $this->uploadedFiles = $fileData;
<del>
<del> // Make a flat map that can be inserted into $post for BC.
<del> $fileMap = Hash::flatten($fileData);
<del> foreach ($fileMap as $key => $file) {
<del> $error = $file->getError();
<del> $tmpName = '';
<del> if ($error === UPLOAD_ERR_OK) {
<del> $tmpName = $file->getStream()->getMetadata('uri');
<del> }
<del> $post = Hash::insert($post, $key, [
<del> 'tmp_name' => $tmpName,
<del> 'error' => $error,
<del> 'name' => $file->getClientFilename(),
<del> 'type' => $file->getClientMediaType(),
<del> 'size' => $file->getSize(),
<del> ]);
<del> }
<del>
<del> return $post;
<del> }
<del>
<del> /**
<del> * Create an UploadedFile instance from a $_FILES array.
<del> *
<del> * If the value represents an array of values, this method will
<del> * recursively process the data.
<del> *
<del> * @param array $value $_FILES struct
<del> * @return array|UploadedFileInterface
<del> */
<del> protected function _createUploadedFile(array $value)
<del> {
<del> if (is_array($value['tmp_name'])) {
<del> return $this->_normalizeNestedFiles($value);
<del> }
<del>
<del> return new UploadedFile(
<del> $value['tmp_name'],
<del> $value['size'],
<del> $value['error'],
<del> $value['name'],
<del> $value['type']
<del> );
<del> }
<del>
<del> /**
<del> * Normalize an array of file specifications.
<del> *
<del> * Loops through all nested files and returns a normalized array of
<del> * UploadedFileInterface instances.
<del> *
<del> * @param array $files The file data to normalize & convert.
<del> * @return array An array of UploadedFileInterface objects.
<del> */
<del> protected function _normalizeNestedFiles(array $files = [])
<del> {
<del> $normalizedFiles = [];
<del> foreach (array_keys($files['tmp_name']) as $key) {
<del> $spec = [
<del> 'tmp_name' => $files['tmp_name'][$key],
<del> 'size' => $files['size'][$key],
<del> 'error' => $files['error'][$key],
<del> 'name' => $files['name'][$key],
<del> 'type' => $files['type'][$key],
<del> ];
<del> $normalizedFiles[$key] = $this->_createUploadedFile($spec);
<del> }
<del>
<del> return $normalizedFiles;
<del> }
<del>
<del> /**
<del> * Get the content type used in this request.
<del> *
<del> * @return string
<del> */
<del> public function contentType()
<del> {
<del> $type = $this->env('CONTENT_TYPE');
<del> if ($type) {
<del> return $type;
<del> }
<del>
<del> return $this->env('HTTP_CONTENT_TYPE');
<del> }
<del>
<del> /**
<del> * Returns the instance of the Session object for this request
<del> *
<del> * If a session object is passed as first argument it will be set as
<del> * the session to use for this request
<del> *
<del> * @param \Cake\Network\Session|null $session the session object to use
<del> * @return \Cake\Network\Session
<del> */
<del> public function session(Session $session = null)
<del> {
<del> if ($session === null) {
<del> return $this->session;
<del> }
<del>
<del> return $this->session = $session;
<del> }
<del>
<del> /**
<del> * Get the IP the client is using, or says they are using.
<del> *
<del> * @return string The client IP.
<del> */
<del> public function clientIp()
<del> {
<del> if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_FOR')) {
<del> $ipaddr = preg_replace('/(?:,.*)/', '', $this->env('HTTP_X_FORWARDED_FOR'));
<del> } elseif ($this->trustProxy && $this->env('HTTP_CLIENT_IP')) {
<del> $ipaddr = $this->env('HTTP_CLIENT_IP');
<del> } else {
<del> $ipaddr = $this->env('REMOTE_ADDR');
<del> }
<del>
<del> return trim($ipaddr);
<del> }
<del>
<del> /**
<del> * Returns the referer that referred this request.
<del> *
<del> * @param bool $local Attempt to return a local address.
<del> * Local addresses do not contain hostnames.
<del> * @return string The referring address for this request.
<del> */
<del> public function referer($local = false)
<del> {
<del> $ref = $this->env('HTTP_REFERER');
<del>
<del> $base = Configure::read('App.fullBaseUrl') . $this->webroot;
<del> if (!empty($ref) && !empty($base)) {
<del> if ($local && strpos($ref, $base) === 0) {
<del> $ref = substr($ref, strlen($base));
<del> if (!strlen($ref)) {
<del> $ref = '/';
<del> }
<del> if ($ref[0] !== '/') {
<del> $ref = '/' . $ref;
<del> }
<del>
<del> return $ref;
<del> }
<del> if (!$local) {
<del> return $ref;
<del> }
<del> }
<del>
<del> return '/';
<del> }
<del>
<del> /**
<del> * Missing method handler, handles wrapping older style isAjax() type methods
<del> *
<del> * @param string $name The method called
<del> * @param array $params Array of parameters for the method call
<del> * @return mixed
<del> * @throws \BadMethodCallException when an invalid method is called.
<del> */
<del> public function __call($name, $params)
<del> {
<del> if (strpos($name, 'is') === 0) {
<del> $type = strtolower(substr($name, 2));
<del>
<del> array_unshift($params, $type);
<del>
<del> return call_user_func_array([$this, 'is'], $params);
<del> }
<del> throw new BadMethodCallException(sprintf('Method %s does not exist', $name));
<del> }
<del>
<del> /**
<del> * Magic get method allows access to parsed routing parameters directly on the object.
<del> *
<del> * Allows access to `$this->params['controller']` via `$this->controller`
<del> *
<del> * @param string $name The property being accessed.
<del> * @return mixed Either the value of the parameter or null.
<del> * @deprecated 3.4.0 Accessing routing parameters through __get will removed in 4.0.0.
<del> * Use param() instead.
<del> */
<del> public function __get($name)
<del> {
<del> if (isset($this->params[$name])) {
<del> return $this->params[$name];
<del> }
<del>
<del> return null;
<del> }
<del>
<del> /**
<del> * Magic isset method allows isset/empty checks
<del> * on routing parameters.
<del> *
<del> * @param string $name The property being accessed.
<del> * @return bool Existence
<del> * @deprecated 3.4.0 Accessing routing parameters through __isset will removed in 4.0.0.
<del> * Use param() instead.
<del> */
<del> public function __isset($name)
<del> {
<del> return isset($this->params[$name]);
<del> }
<del>
<del> /**
<del> * Check whether or not a Request is a certain type.
<del> *
<del> * Uses the built in detection rules as well as additional rules
<del> * defined with Cake\Network\CakeRequest::addDetector(). Any detector can be called
<del> * as `is($type)` or `is$Type()`.
<del> *
<del> * @param string|array $type The type of request you want to check. If an array
<del> * this method will return true if the request matches any type.
<del> * @return bool Whether or not the request is the type you are checking.
<del> */
<del> public function is($type)
<del> {
<del> if (is_array($type)) {
<del> $result = array_map([$this, 'is'], $type);
<del>
<del> return count(array_filter($result)) > 0;
<del> }
<del> $args = func_get_args();
<del> array_shift($args);
<del>
<del> $type = strtolower($type);
<del> if (!isset(static::$_detectors[$type])) {
<del> return false;
<del> }
<del> if ($args) {
<del> return $this->_is($type, $args);
<del> }
<del> if (!isset($this->_detectorCache[$type])) {
<del> $this->_detectorCache[$type] = $this->_is($type, $args);
<del> }
<del>
<del> return $this->_detectorCache[$type];
<del> }
<del>
<del> /**
<del> * Clears the instance detector cache, used by the is() function
<del> *
<del> * @return void
<del> */
<del> public function clearDetectorCache()
<del> {
<del> $this->_detectorCache = [];
<del> }
<del>
<del> /**
<del> * Worker for the public is() function
<del> *
<del> * @param string|array $type The type of request you want to check. If an array
<del> * this method will return true if the request matches any type.
<del> * @param array $args Array of custom detector arguments.
<del> * @return bool Whether or not the request is the type you are checking.
<del> */
<del> protected function _is($type, $args)
<del> {
<del> $detect = static::$_detectors[$type];
<del> if (is_callable($detect)) {
<del> array_unshift($args, $this);
<del>
<del> return call_user_func_array($detect, $args);
<del> }
<del> if (isset($detect['env']) && $this->_environmentDetector($detect)) {
<del> return true;
<del> }
<del> if (isset($detect['header']) && $this->_headerDetector($detect)) {
<del> return true;
<del> }
<del> if (isset($detect['accept']) && $this->_acceptHeaderDetector($detect)) {
<del> return true;
<del> }
<del> if (isset($detect['param']) && $this->_paramDetector($detect)) {
<del> return true;
<del> }
<del>
<del> return false;
<del> }
<del>
<del> /**
<del> * Detects if a specific accept header is present.
<del> *
<del> * @param array $detect Detector options array.
<del> * @return bool Whether or not the request is the type you are checking.
<del> */
<del> protected function _acceptHeaderDetector($detect)
<del> {
<del> $acceptHeaders = explode(',', $this->env('HTTP_ACCEPT'));
<del> foreach ($detect['accept'] as $header) {
<del> if (in_array($header, $acceptHeaders)) {
<del> return true;
<del> }
<del> }
<del>
<del> return false;
<del> }
<del>
<del> /**
<del> * Detects if a specific header is present.
<del> *
<del> * @param array $detect Detector options array.
<del> * @return bool Whether or not the request is the type you are checking.
<del> */
<del> protected function _headerDetector($detect)
<del> {
<del> foreach ($detect['header'] as $header => $value) {
<del> $header = $this->env('http_' . $header);
<del> if ($header !== null) {
<del> if (!is_string($value) && !is_bool($value) && is_callable($value)) {
<del> return call_user_func($value, $header);
<del> }
<del>
<del> return ($header === $value);
<del> }
<del> }
<del>
<del> return false;
<del> }
<del>
<del> /**
<del> * Detects if a specific request parameter is present.
<del> *
<del> * @param array $detect Detector options array.
<del> * @return bool Whether or not the request is the type you are checking.
<del> */
<del> protected function _paramDetector($detect)
<del> {
<del> $key = $detect['param'];
<del> if (isset($detect['value'])) {
<del> $value = $detect['value'];
<del>
<del> return isset($this->params[$key]) ? $this->params[$key] == $value : false;
<del> }
<del> if (isset($detect['options'])) {
<del> return isset($this->params[$key]) ? in_array($this->params[$key], $detect['options']) : false;
<del> }
<del>
<del> return false;
<del> }
<del>
<del> /**
<del> * Detects if a specific environment variable is present.
<del> *
<del> * @param array $detect Detector options array.
<del> * @return bool Whether or not the request is the type you are checking.
<del> */
<del> protected function _environmentDetector($detect)
<del> {
<del> if (isset($detect['env'])) {
<del> if (isset($detect['value'])) {
<del> return $this->env($detect['env']) == $detect['value'];
<del> }
<del> if (isset($detect['pattern'])) {
<del> return (bool)preg_match($detect['pattern'], $this->env($detect['env']));
<del> }
<del> if (isset($detect['options'])) {
<del> $pattern = '/' . implode('|', $detect['options']) . '/i';
<del>
<del> return (bool)preg_match($pattern, $this->env($detect['env']));
<del> }
<del> }
<del>
<del> return false;
<del> }
<del>
<del> /**
<del> * Check that a request matches all the given types.
<del> *
<del> * Allows you to test multiple types and union the results.
<del> * See Request::is() for how to add additional types and the
<del> * built-in types.
<del> *
<del> * @param array $types The types to check.
<del> * @return bool Success.
<del> * @see \Cake\Network\Request::is()
<del> */
<del> public function isAll(array $types)
<del> {
<del> $result = array_filter(array_map([$this, 'is'], $types));
<del>
<del> return count($result) === count($types);
<del> }
<del>
<del> /**
<del> * Add a new detector to the list of detectors that a request can use.
<del> * There are several different formats and types of detectors that can be set.
<del> *
<del> * ### Callback detectors
<del> *
<del> * Callback detectors allow you to provide a callable to handle the check.
<del> * The callback will receive the request object as its only parameter.
<del> *
<del> * ```
<del> * addDetector('custom', function ($request) { //Return a boolean });
<del> * addDetector('custom', ['SomeClass', 'somemethod']);
<del> * ```
<del> *
<del> * ### Environment value comparison
<del> *
<del> * An environment value comparison, compares a value fetched from `env()` to a known value
<del> * the environment value is equality checked against the provided value.
<del> *
<del> * e.g `addDetector('post', ['env' => 'REQUEST_METHOD', 'value' => 'POST'])`
<del> *
<del> * ### Pattern value comparison
<del> *
<del> * Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
<del> *
<del> * ```
<del> * addDetector('iphone', ['env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i']);
<del> * ```
<del> *
<del> * ### Option based comparison
<del> *
<del> * Option based comparisons use a list of options to create a regular expression. Subsequent calls
<del> * to add an already defined options detector will merge the options.
<del> *
<del> * ```
<del> * addDetector('mobile', ['env' => 'HTTP_USER_AGENT', 'options' => ['Fennec']]);
<del> * ```
<del> *
<del> * ### Request parameter detectors
<del> *
<del> * Allows for custom detectors on the request parameters.
<del> *
<del> * e.g `addDetector('requested', ['param' => 'requested', 'value' => 1]`
<del> *
<del> * You can also make parameter detectors that accept multiple values
<del> * using the `options` key. This is useful when you want to check
<del> * if a request parameter is in a list of options.
<del> *
<del> * `addDetector('extension', ['param' => 'ext', 'options' => ['pdf', 'csv']]`
<del> *
<del> * @param string $name The name of the detector.
<del> * @param callable|array $callable A callable or options array for the detector definition.
<del> * @return void
<del> */
<del> public static function addDetector($name, $callable)
<del> {
<del> $name = strtolower($name);
<del> if (is_callable($callable)) {
<del> static::$_detectors[$name] = $callable;
<del>
<del> return;
<del> }
<del> if (isset(static::$_detectors[$name], $callable['options'])) {
<del> $callable = Hash::merge(static::$_detectors[$name], $callable);
<del> }
<del> static::$_detectors[$name] = $callable;
<del> }
<del>
<del> /**
<del> * Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
<del> * This modifies the parameters available through `$request->params`.
<del> *
<del> * @param array $params Array of parameters to merge in
<del> * @return $this The current object, you can chain this method.
<del> */
<del> public function addParams(array $params)
<del> {
<del> $this->params = array_merge($this->params, $params);
<del>
<del> return $this;
<del> }
<del>
<del> /**
<del> * Add paths to the requests' paths vars. This will overwrite any existing paths.
<del> * Provides an easy way to modify, here, webroot and base.
<del> *
<del> * @param array $paths Array of paths to merge in
<del> * @return $this The current object, you can chain this method.
<del> */
<del> public function addPaths(array $paths)
<del> {
<del> foreach (['webroot', 'here', 'base'] as $element) {
<del> if (isset($paths[$element])) {
<del> $this->{$element} = $paths[$element];
<del> }
<del> }
<del>
<del> return $this;
<del> }
<del>
<del> /**
<del> * Get the value of the current requests URL. Will include querystring arguments.
<del> *
<del> * @param bool $base Include the base path, set to false to trim the base path off.
<del> * @return string The current request URL including query string args.
<del> * @deprecated 3.4.0 This method will be removed in 4.0.0. You should use getRequestTarget() instead.
<del> */
<del> public function here($base = true)
<del> {
<del> $url = $this->here;
<del> if (!empty($this->query)) {
<del> $url .= '?' . http_build_query($this->query, null, '&');
<del> }
<del> if (!$base) {
<del> $url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
<del> }
<del>
<del> return $url;
<del> }
<del>
<del> /**
<del> * Normalize a header name into the SERVER version.
<del> *
<del> * @param string $name The header name.
<del> * @return string The normalized header name.
<del> */
<del> protected function normalizeHeaderName($name)
<del> {
<del> $name = str_replace('-', '_', strtoupper($name));
<del> if (!in_array($name, ['CONTENT_LENGTH', 'CONTENT_TYPE'])) {
<del> $name = 'HTTP_' . $name;
<del> }
<del>
<del> return $name;
<del> }
<del>
<del> /**
<del> * Read an HTTP header from the Request information.
<del> *
<del> * If the header is not defined in the request, this method
<del> * will fallback to reading data from $_SERVER and $_ENV.
<del> * This fallback behavior is deprecated, and will be removed in 4.0.0
<del> *
<del> * @param string $name Name of the header you want.
<del> * @return string|null Either null on no header being set or the value of the header.
<del> * @deprecated 4.0.0 The automatic fallback to env() will be removed in 4.0.0
<del> */
<del> public function header($name)
<del> {
<del> $name = $this->normalizeHeaderName($name);
<del>
<del> return $this->env($name);
<del> }
<del>
<del> /**
<del> * Get all headers in the request.
<del> *
<del> * Returns an associative array where the header names are
<del> * the keys and the values are a list of header values.
<del> *
<del> * While header names are not case-sensitive, getHeaders() will normalize
<del> * the headers.
<del> *
<del> * @return array An associative array of headers and their values.
<del> */
<del> public function getHeaders()
<del> {
<del> $headers = [];
<del> foreach ($this->_environment as $key => $value) {
<del> $name = null;
<del> if (strpos($key, 'HTTP_') === 0) {
<del> $name = substr($key, 5);
<del> }
<del> if (strpos($key, 'CONTENT_') === 0) {
<del> $name = $key;
<del> }
<del> if ($name !== null) {
<del> $name = strtr(strtolower($name), '_', ' ');
<del> $name = strtr(ucwords($name), ' ', '-');
<del> $headers[$name] = (array)$value;
<del> }
<del> }
<del>
<del> return $headers;
<del> }
<del>
<del> /**
<del> * Check if a header is set in the request.
<del> *
<del> * @param string $name The header you want to get (case-insensitive)
<del> * @return bool Whether or not the header is defined.
<del> */
<del> public function hasHeader($name)
<del> {
<del> $name = $this->normalizeHeaderName($name);
<del>
<del> return isset($this->_environment[$name]);
<del> }
<del>
<del> /**
<del> * Get a single header from the request.
<del> *
<del> * Return the header value as an array. If the header
<del> * is not present an empty array will be returned.
<del> *
<del> * @param string $name The header you want to get (case-insensitive)
<del> * @return array An associative array of headers and their values.
<del> * If the header doesn't exist, an empty array will be returned.
<del> */
<del> public function getHeader($name)
<del> {
<del> $name = $this->normalizeHeaderName($name);
<del> if (isset($this->_environment[$name])) {
<del> return (array)$this->_environment[$name];
<del> }
<del>
<del> return [];
<del> }
<del>
<del> /**
<del> * Get a single header as a string from the request.
<del> *
<del> * Return an array of header values
<del> *
<del> * @param string $name The header you want to get (case-insensitive)
<del> * @return string Header values collapsed into a comma separated string.
<del> */
<del> public function getHeaderLine($name)
<del> {
<del> $value = $this->getHeader($name);
<del>
<del> return implode(', ', $value);
<del> }
<del>
<del> /**
<del> * Get a modified request with the provided header.
<del> *
<del> * @param string $name The header name.
<del> * @param string|array $value The header value
<del> * @return static
<del> */
<del> public function withHeader($name, $value)
<del> {
<del> $new = clone $this;
<del> $name = $this->normalizeHeaderName($name);
<del> $new->_environment[$name] = $value;
<del>
<del> return $new;
<del> }
<del>
<del> /**
<del> * Get a modified request with the provided header.
<del> *
<del> * Existing header values will be retained. The provided value
<del> * will be appended into the existing values.
<del> *
<del> * @param string $name The header name.
<del> * @param string|array $value The header value
<del> * @return static
<del> */
<del> public function withAddedHeader($name, $value)
<del> {
<del> $new = clone $this;
<del> $name = $this->normalizeHeaderName($name);
<del> $existing = [];
<del> if (isset($new->_environment[$name])) {
<del> $existing = (array)$new->_environment[$name];
<del> }
<del> $existing = array_merge($existing, (array)$value);
<del> $new->_environment[$name] = $existing;
<del>
<del> return $new;
<del> }
<del>
<del> /**
<del> * Get a modified request without a provided header.
<del> *
<del> * @param string $name The header name to remove.
<del> * @return static
<del> */
<del> public function withoutHeader($name)
<del> {
<del> $new = clone $this;
<del> $name = $this->normalizeHeaderName($name);
<del> unset($new->_environment[$name]);
<del>
<del> return $new;
<del> }
<del>
<del> /**
<del> * Get the HTTP method used for this request.
<del> *
<del> * @return string The name of the HTTP method used.
<del> * @deprecated 3.4.0 This method will be removed in 4.0.0. Use getMethod() instead.
<del> */
<del> public function method()
<del> {
<del> return $this->env('REQUEST_METHOD');
<del> }
<del>
<del> /**
<del> * Get the HTTP method used for this request.
<del> * There are a few ways to specify a method.
<del> *
<del> * - If your client supports it you can use native HTTP methods.
<del> * - You can set the HTTP-X-Method-Override header.
<del> * - You can submit an input with the name `_method`
<del> *
<del> * Any of these 3 approaches can be used to set the HTTP method used
<del> * by CakePHP internally, and will effect the result of this method.
<del> *
<del> * @return string The name of the HTTP method used.
<del> */
<del> public function getMethod()
<del> {
<del> return $this->env('REQUEST_METHOD');
<del> }
<del>
<del> /**
<del> * Update the request method and get a new instance.
<del> *
<del> * @param string $method The HTTP method to use.
<del> * @return static A new instance with the updated method.
<del> */
<del> public function withMethod($method)
<del> {
<del> $new = clone $this;
<del>
<del> if (!is_string($method) ||
<del> !preg_match('/^[!#$%&\'*+.^_`\|~0-9a-z-]+$/i', $method)
<del> ) {
<del> throw new InvalidArgumentException(sprintf(
<del> 'Unsupported HTTP method "%s" provided',
<del> $method
<del> ));
<del> }
<del> $new->_environment['REQUEST_METHOD'] = $method;
<del>
<del> return $new;
<del> }
<del>
<del> /**
<del> * Get all the server environment parameters.
<del> *
<del> * Read all of the 'environment' or 'server' data that was
<del> * used to create this request.
<del> *
<del> * @return array
<del> */
<del> public function getServerParams()
<del> {
<del> return $this->_environment;
<del> }
<del>
<del> /**
<del> * Get all the query parameters.
<del> *
<del> * @return array
<del> */
<del> public function getQueryParams()
<del> {
<del> return $this->query;
<del> }
<del>
<del> /**
<del> * Update the query string data and get a new instance.
<del> *
<del> * @param array $query The query string data to use
<del> * @return static A new instance with the updated query string data.
<del> */
<del> public function withQueryParams(array $query)
<del> {
<del> $new = clone $this;
<del> $new->query = $query;
<del>
<del> return $new;
<del> }
<del>
<del> /**
<del> * Get the host that the request was handled on.
<del> *
<del> * @return string
<del> */
<del> public function host()
<del> {
<del> if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_HOST')) {
<del> return $this->env('HTTP_X_FORWARDED_HOST');
<del> }
<del>
<del> return $this->env('HTTP_HOST');
<del> }
<del>
<del> /**
<del> * Get the port the request was handled on.
<del> *
<del> * @return string
<del> */
<del> public function port()
<del> {
<del> if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_PORT')) {
<del> return $this->env('HTTP_X_FORWARDED_PORT');
<del> }
<del>
<del> return $this->env('SERVER_PORT');
<del> }
<del>
<del> /**
<del> * Get the current url scheme used for the request.
<del> *
<del> * e.g. 'http', or 'https'
<del> *
<del> * @return string The scheme used for the request.
<del> */
<del> public function scheme()
<del> {
<del> if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_PROTO')) {
<del> return $this->env('HTTP_X_FORWARDED_PROTO');
<del> }
<del>
<del> return $this->env('HTTPS') ? 'https' : 'http';
<del> }
<del>
<del> /**
<del> * Get the domain name and include $tldLength segments of the tld.
<del> *
<del> * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
<del> * While `example.co.uk` contains 2.
<del> * @return string Domain name without subdomains.
<del> */
<del> public function domain($tldLength = 1)
<del> {
<del> $segments = explode('.', $this->host());
<del> $domain = array_slice($segments, -1 * ($tldLength + 1));
<del>
<del> return implode('.', $domain);
<del> }
<del>
<del> /**
<del> * Get the subdomains for a host.
<del> *
<del> * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
<del> * While `example.co.uk` contains 2.
<del> * @return array An array of subdomains.
<del> */
<del> public function subdomains($tldLength = 1)
<del> {
<del> $segments = explode('.', $this->host());
<del>
<del> return array_slice($segments, 0, -1 * ($tldLength + 1));
<del> }
<del>
<del> /**
<del> * Find out which content types the client accepts or check if they accept a
<del> * particular type of content.
<del> *
<del> * #### Get all types:
<del> *
<del> * ```
<del> * $this->request->accepts();
<del> * ```
<del> *
<del> * #### Check for a single type:
<del> *
<del> * ```
<del> * $this->request->accepts('application/json');
<del> * ```
<del> *
<del> * This method will order the returned content types by the preference values indicated
<del> * by the client.
<del> *
<del> * @param string|null $type The content type to check for. Leave null to get all types a client accepts.
<del> * @return array|bool Either an array of all the types the client accepts or a boolean if they accept the
<del> * provided type.
<del> */
<del> public function accepts($type = null)
<del> {
<del> $raw = $this->parseAccept();
<del> $accept = [];
<del> foreach ($raw as $types) {
<del> $accept = array_merge($accept, $types);
<del> }
<del> if ($type === null) {
<del> return $accept;
<del> }
<del>
<del> return in_array($type, $accept);
<del> }
<del>
<del> /**
<del> * Parse the HTTP_ACCEPT header and return a sorted array with content types
<del> * as the keys, and pref values as the values.
<del> *
<del> * Generally you want to use Cake\Network\Request::accept() to get a simple list
<del> * of the accepted content types.
<del> *
<del> * @return array An array of prefValue => [content/types]
<del> */
<del> public function parseAccept()
<del> {
<del> return $this->_parseAcceptWithQualifier($this->getHeaderLine('Accept'));
<del> }
<del>
<del> /**
<del> * Get the languages accepted by the client, or check if a specific language is accepted.
<del> *
<del> * Get the list of accepted languages:
<del> *
<del> * ``` \Cake\Network\Request::acceptLanguage(); ```
<del> *
<del> * Check if a specific language is accepted:
<del> *
<del> * ``` \Cake\Network\Request::acceptLanguage('es-es'); ```
<del> *
<del> * @param string|null $language The language to test.
<del> * @return array|bool If a $language is provided, a boolean. Otherwise the array of accepted languages.
<del> */
<del> public function acceptLanguage($language = null)
<del> {
<del> $raw = $this->_parseAcceptWithQualifier($this->getHeaderLine('Accept-Language'));
<del> $accept = [];
<del> foreach ($raw as $languages) {
<del> foreach ($languages as &$lang) {
<del> if (strpos($lang, '_')) {
<del> $lang = str_replace('_', '-', $lang);
<del> }
<del> $lang = strtolower($lang);
<del> }
<del> $accept = array_merge($accept, $languages);
<del> }
<del> if ($language === null) {
<del> return $accept;
<del> }
<del>
<del> return in_array(strtolower($language), $accept);
<del> }
<del>
<del> /**
<del> * Parse Accept* headers with qualifier options.
<del> *
<del> * Only qualifiers will be extracted, any other accept extensions will be
<del> * discarded as they are not frequently used.
<del> *
<del> * @param string $header Header to parse.
<del> * @return array
<del> */
<del> protected function _parseAcceptWithQualifier($header)
<del> {
<del> $accept = [];
<del> $header = explode(',', $header);
<del> foreach (array_filter($header) as $value) {
<del> $prefValue = '1.0';
<del> $value = trim($value);
<del>
<del> $semiPos = strpos($value, ';');
<del> if ($semiPos !== false) {
<del> $params = explode(';', $value);
<del> $value = trim($params[0]);
<del> foreach ($params as $param) {
<del> $qPos = strpos($param, 'q=');
<del> if ($qPos !== false) {
<del> $prefValue = substr($param, $qPos + 2);
<del> }
<del> }
<del> }
<del>
<del> if (!isset($accept[$prefValue])) {
<del> $accept[$prefValue] = [];
<del> }
<del> if ($prefValue) {
<del> $accept[$prefValue][] = $value;
<del> }
<del> }
<del> krsort($accept);
<del>
<del> return $accept;
<del> }
<del>
<del> /**
<del> * Provides a read accessor for `$this->query`. Allows you
<del> * to use a syntax similar to `CakeSession` for reading URL query data.
<del> *
<del> * @param string|null $name Query string variable name or null to read all.
<del> * @return string|array|null The value being read
<del> */
<del> public function query($name = null)
<del> {
<del> if ($name === null) {
<del> return $this->query;
<del> }
<del>
<del> return Hash::get($this->query, $name);
<del> }
<del>
<del> /**
<del> * Provides a read/write accessor for `$this->data`. Allows you
<del> * to use a syntax similar to `Cake\Model\Datasource\Session` for reading post data.
<del> *
<del> * ### Reading values.
<del> *
<del> * ```
<del> * $request->data('Post.title');
<del> * ```
<del> *
<del> * When reading values you will get `null` for keys/values that do not exist.
<del> *
<del> * ### Writing values
<del> *
<del> * ```
<del> * $request->data('Post.title', 'New post!');
<del> * ```
<del> *
<del> * As of 3.4.0, the setter mode of this method is *deprecated*.
<del> * Use `withData` instead.
<del> *
<del> * You can write to any value, even paths/keys that do not exist, and the arrays
<del> * will be created for you.
<del> *
<del> * @param string|null $name Dot separated name of the value to read/write
<del> * @param mixed ...$args The data to set (deprecated)
<del> * @return mixed|$this Either the value being read, or this so you can chain consecutive writes.
<del> */
<del> public function data($name = null, ...$args)
<del> {
<del> if (count($args) === 1) {
<del> $this->data = Hash::insert($this->data, $name, $args[0]);
<del>
<del> return $this;
<del> }
<del> if ($name !== null) {
<del> return Hash::get($this->data, $name);
<del> }
<del>
<del> return $this->data;
<del> }
<del>
<del> /**
<del> * Safely access the values in $this->params.
<del> *
<del> * As of 3.4.0, the setter mode of this method is *deprecated*.
<del> * Use `withParam` instead.
<del> *
<del> * @param string $name The name of the parameter to get.
<del> * @param mixed ...$args Value to set (deprecated).
<del> * @return mixed|$this The value of the provided parameter. Will
<del> * return false if the parameter doesn't exist or is falsey.
<del> */
<del> public function param($name, ...$args)
<del> {
<del> if (count($args) === 1) {
<del> $this->params = Hash::insert($this->params, $name, $args[0]);
<del>
<del> return $this;
<del> }
<del> if (!isset($this->params[$name])) {
<del> return Hash::get($this->params, $name, false);
<del> }
<del>
<del> return $this->params[$name];
<del> }
<del>
<del> /**
<del> * Read data from `php://input`. Useful when interacting with XML or JSON
<del> * request body content.
<del> *
<del> * Getting input with a decoding function:
<del> *
<del> * ```
<del> * $this->request->input('json_decode');
<del> * ```
<del> *
<del> * Getting input using a decoding function, and additional params:
<del> *
<del> * ```
<del> * $this->request->input('Xml::build', ['return' => 'DOMDocument']);
<del> * ```
<del> *
<del> * Any additional parameters are applied to the callback in the order they are given.
<del> *
<del> * @param string|null $callback A decoding callback that will convert the string data to another
<del> * representation. Leave empty to access the raw input data. You can also
<del> * supply additional parameters for the decoding callback using var args, see above.
<del> * @param array ...$args The additional arguments
<del> * @return string The decoded/processed request data.
<del> */
<del> public function input($callback = null, ...$args)
<del> {
<del> $input = $this->stream->getContents();
<del> if ($callback) {
<del> array_unshift($args, $input);
<del>
<del> return call_user_func_array($callback, $args);
<del> }
<del>
<del> return $input;
<del> }
<del>
<del> /**
<del> * Read cookie data from the request's cookie data.
<del> *
<del> * @param string $key The key you want to read.
<del> * @return null|string Either the cookie value, or null if the value doesn't exist.
<del> */
<del> public function cookie($key)
<del> {
<del> if (isset($this->cookies[$key])) {
<del> return $this->cookies[$key];
<del> }
<del>
<del> return null;
<del> }
<del>
<del> /**
<del> * Get all the cookie data from the request.
<del> *
<del> * @return array An array of cookie data.
<del> */
<del> public function getCookieParams()
<del> {
<del> return $this->cookies;
<del> }
<del>
<del> /**
<del> * Replace the cookies and get a new request instance.
<del> *
<del> * @param array $cookies The new cookie data to use.
<del> * @return static
<del> */
<del> public function withCookieParams(array $cookies)
<del> {
<del> $new = clone $this;
<del> $new->cookies = $cookies;
<del>
<del> return $new;
<del> }
<del>
<del> /**
<del> * Get the parsed request body data.
<del> *
<del> * If the request Content-Type is either application/x-www-form-urlencoded
<del> * or multipart/form-data, nd the request method is POST, this will be the
<del> * post data. For other content types, it may be the deserialized request
<del> * body.
<del> *
<del> * @return null|array|object The deserialized body parameters, if any.
<del> * These will typically be an array or object.
<del> */
<del> public function getParsedBody()
<del> {
<del> return $this->data;
<del> }
<del>
<del> /**
<del> * Update the parsed body and get a new instance.
<del> *
<del> * @param null|array|object $data The deserialized body data. This will
<del> * typically be in an array or object.
<del> * @return static
<del> */
<del> public function withParsedBody($data)
<del> {
<del> $new = clone $this;
<del> $new->data = $data;
<del>
<del> return $new;
<del> }
<del>
<del> /**
<del> * Retrieves the HTTP protocol version as a string.
<del> *
<del> * @return string HTTP protocol version.
<del> */
<del> public function getProtocolVersion()
<del> {
<del> if ($this->protocol) {
<del> return $this->protocol;
<del> }
<del>
<del> // Lazily populate this data as it is generally not used.
<del> preg_match('/^HTTP\/([\d.]+)$/', $this->env('SERVER_PROTOCOL'), $match);
<del> $protocol = '1.1';
<del> if (isset($match[1])) {
<del> $protocol = $match[1];
<del> }
<del> $this->protocol = $protocol;
<del>
<del> return $this->protocol;
<del> }
<del>
<del> /**
<del> * Return an instance with the specified HTTP protocol version.
<del> *
<del> * The version string MUST contain only the HTTP version number (e.g.,
<del> * "1.1", "1.0").
<del> *
<del> * @param string $version HTTP protocol version
<del> * @return static
<del> */
<del> public function withProtocolVersion($version)
<del> {
<del> if (!preg_match('/^(1\.[01]|2)$/', $version)) {
<del> throw new InvalidArgumentException("Unsupported protocol version '{$version}' provided");
<del> }
<del> $new = clone $this;
<del> $new->protocol = $version;
<del>
<del> return $new;
<del> }
<del>
<del> /**
<del> * Get/Set value from the request's environment data.
<del> * Fallback to using env() if key not set in $environment property.
<del> *
<del> * @param string $key The key you want to read/write from/to.
<del> * @param string|null $value Value to set. Default null.
<del> * @param string|null $default Default value when trying to retrieve an environment
<del> * variable's value that does not exist. The value parameter must be null.
<del> * @return $this|string|null This instance if used as setter,
<del> * if used as getter either the environment value, or null if the value doesn't exist.
<del> */
<del> public function env($key, $value = null, $default = null)
<del> {
<del> if ($value !== null) {
<del> $this->_environment[$key] = $value;
<del> $this->clearDetectorCache();
<del>
<del> return $this;
<del> }
<del>
<del> $key = strtoupper($key);
<del> if (!array_key_exists($key, $this->_environment)) {
<del> $this->_environment[$key] = env($key);
<del> }
<del>
<del> return $this->_environment[$key] !== null ? $this->_environment[$key] : $default;
<del> }
<del>
<del> /**
<del> * Allow only certain HTTP request methods, if the request method does not match
<del> * a 405 error will be shown and the required "Allow" response header will be set.
<del> *
<del> * Example:
<del> *
<del> * $this->request->allowMethod('post');
<del> * or
<del> * $this->request->allowMethod(['post', 'delete']);
<del> *
<del> * If the request would be GET, response header "Allow: POST, DELETE" will be set
<del> * and a 405 error will be returned.
<del> *
<del> * @param string|array $methods Allowed HTTP request methods.
<del> * @return bool true
<del> * @throws \Cake\Network\Exception\MethodNotAllowedException
<del> */
<del> public function allowMethod($methods)
<del> {
<del> $methods = (array)$methods;
<del> foreach ($methods as $method) {
<del> if ($this->is($method)) {
<del> return true;
<del> }
<del> }
<del> $allowed = strtoupper(implode(', ', $methods));
<del> $e = new MethodNotAllowedException();
<del> $e->responseHeader('Allow', $allowed);
<del> throw $e;
<del> }
<del>
<del> /**
<del> * Read data from php://input, mocked in tests.
<del> *
<del> * @return string contents of php://input
<del> */
<del> protected function _readInput()
<del> {
<del> if (empty($this->_input)) {
<del> $fh = fopen('php://input', 'r');
<del> $content = stream_get_contents($fh);
<del> fclose($fh);
<del> $this->_input = $content;
<del> }
<del>
<del> return $this->_input;
<del> }
<del>
<del> /**
<del> * Modify data originally from `php://input`. Useful for altering json/xml data
<del> * in middleware or DispatcherFilters before it gets to RequestHandlerComponent
<del> *
<del> * @param string $input A string to replace original parsed data from input()
<del> * @return void
<del> * @deprecated 3.4.0 This method will be removed in 4.0.0. Use withBody() instead.
<del> */
<del> public function setInput($input)
<del> {
<del> $stream = new Stream('php://memory', 'rw');
<del> $stream->write($input);
<del> $stream->rewind();
<del> $this->stream = $stream;
<del> }
<del>
<del> /**
<del> * Update the request with a new request data element.
<del> *
<del> * Returns an updated request object. This method returns
<del> * a *new* request object and does not mutate the request in-place.
<del> *
<del> * @param string $name The dot separated path to insert $value at.
<del> * @param mixed $value The value to insert into the request data.
<del> * @return static
<del> */
<del> public function withData($name, $value)
<del> {
<del> $copy = clone $this;
<del> $copy->data = Hash::insert($copy->data, $name, $value);
<del>
<del> return $copy;
<del> }
<del>
<del> /**
<del> * Update the request with a new routing parameter
<del> *
<del> * Returns an updated request object. This method returns
<del> * a *new* request object and does not mutate the request in-place.
<del> *
<del> * @param string $name The dot separated path to insert $value at.
<del> * @param mixed $value The value to insert into the the request parameters.
<del> * @return static
<del> */
<del> public function withParam($name, $value)
<del> {
<del> $copy = clone $this;
<del> $copy->params = Hash::insert($copy->params, $name, $value);
<del>
<del> return $copy;
<del> }
<del>
<del> /**
<del> * Return an instance with the specified request attribute.
<del> *
<del> * @param string $name The attribute name.
<del> * @param mixed $value The value of the attribute.
<del> * @return static
<del> */
<del> public function withAttribute($name, $value)
<del> {
<del> $new = clone $this;
<del> if (in_array($name, $this->emulatedAttributes, true)) {
<del> $new->{$name} = $value;
<del> } else {
<del> $new->attributes[$name] = $value;
<del> }
<del>
<del> return $new;
<del> }
<del>
<del> /**
<del> * Return an instance without the specified request attribute.
<del> *
<del> * @param string $name The attribute name.
<del> * @return static
<del> * @throws InvalidArgumentException
<del> */
<del> public function withoutAttribute($name)
<del> {
<del> $new = clone $this;
<del> if (in_array($name, $this->emulatedAttributes, true)) {
<del> throw new InvalidArgumentException(
<del> "You cannot unset '$name'. It is a required CakePHP attribute."
<del> );
<del> }
<del> unset($new->attributes[$name]);
<del>
<del> return $new;
<del> }
<del>
<del> /**
<del> * Read an attribute from the request, or get the default
<del> *
<del> * @param string $name The attribute name.
<del> * @param mixed|null $default The default value if the attribute has not been set.
<del> * @return static
<del> */
<del> public function getAttribute($name, $default = null)
<del> {
<del> if (in_array($name, $this->emulatedAttributes, true)) {
<del> return $this->{$name};
<del> }
<del> if (array_key_exists($name, $this->attributes)) {
<del> return $this->attributes[$name];
<del> }
<del>
<del> return $default;
<del> }
<del>
<del> /**
<del> * Get all the attributes in the request.
<del> *
<del> * This will include the params, webroot, and base attributes that CakePHP
<del> * provides.
<del> *
<del> * @return array
<del> */
<del> public function getAttributes()
<del> {
<del> $emulated = [
<del> 'params' => $this->params,
<del> 'webroot' => $this->webroot,
<del> 'base' => $this->base
<del> ];
<del>
<del> return $this->attributes + $emulated;
<del> }
<del>
<del> /**
<del> * Get the uploaded file from a dotted path.
<del> *
<del> * @param string $path The dot separated path to the file you want.
<del> * @return null|Psr\Http\Message\UploadedFileInterface
<del> */
<del> public function getUploadedFile($path)
<del> {
<del> $file = Hash::get($this->uploadedFiles, $path);
<del> if (!$file instanceof UploadedFile) {
<del> return null;
<del> }
<del>
<del> return $file;
<del> }
<del>
<del> /**
<del> * Get the array of uploaded files from the request.
<del> *
<del> * @return array
<del> */
<del> public function getUploadedFiles()
<del> {
<del> return $this->uploadedFiles;
<del> }
<del>
<del> /**
<del> * Update the request replacing the files, and creating a new instance.
<del> *
<del> * @param array $files An array of uploaded file objects.
<del> * @return static
<del> * @throws InvalidArgumentException when $files contains an invalid object.
<del> */
<del> public function withUploadedFiles(array $files)
<del> {
<del> $this->validateUploadedFiles($files, '');
<del> $new = clone $this;
<del> $new->uploadedFiles = $files;
<del>
<del> return $new;
<del> }
<del>
<del> /**
<del> * Recursively validate uploaded file data.
<del> *
<del> * @param array $uploadedFiles The new files array to validate.
<del> * @param string $path The path thus far.
<del> * @return void
<del> * @throws InvalidArgumentException If any leaf elements are not valid files.
<del> */
<del> protected function validateUploadedFiles(array $uploadedFiles, $path)
<del> {
<del> foreach ($uploadedFiles as $key => $file) {
<del> if (is_array($file)) {
<del> $this->validateUploadedFiles($file, $key . '.');
<del> continue;
<del> }
<del>
<del> if (!$file instanceof UploadedFileInterface) {
<del> throw new InvalidArgumentException("Invalid file at '{$path}{$key}'");
<del> }
<del> }
<del> }
<del>
<del> /**
<del> * Gets the body of the message.
<del> *
<del> * @return \Psr\Http\Message\StreamInterface Returns the body as a stream.
<del> */
<del> public function getBody()
<del> {
<del> return $this->stream;
<del> }
<del>
<del> /**
<del> * Return an instance with the specified message body.
<del> *
<del> * @param \Psr\Http\Message\StreamInterface $body The new request body
<del> * @return static
<del> */
<del> public function withBody(StreamInterface $body)
<del> {
<del> $new = clone $this;
<del> $new->stream = $body;
<del>
<del> return $new;
<del> }
<del>
<del> /**
<del> * Retrieves the URI instance.
<del> *
<del> * @return \Psr\Http\Message\UriInterface Returns a UriInterface instance
<del> * representing the URI of the request.
<del> */
<del> public function getUri()
<del> {
<del> return $this->uri;
<del> }
<del>
<del> /**
<del> * Return an instance with the specified uri
<del> *
<del> * *Warning* Replacing the Uri will not update the `base`, `webroot`,
<del> * and `url` attributes.
<del> *
<del> * @param \Psr\Http\Message\UriInterface $uri The new request uri
<del> * @param bool $preserveHost Whether or not the host should be retained.
<del> * @return static
<del> */
<del> public function withUri(UriInterface $uri, $preserveHost = false)
<del> {
<del> $new = clone $this;
<del> $new->uri = $uri;
<del>
<del> if ($preserveHost && $this->hasHeader('Host')) {
<del> return $new;
<del> }
<del>
<del> $host = $uri->getHost();
<del> if (!$host) {
<del> return $new;
<del> }
<del> if ($uri->getPort()) {
<del> $host .= ':' . $uri->getPort();
<del> }
<del> $new->_environment['HTTP_HOST'] = $host;
<del>
<del> return $new;
<del> }
<del>
<del> /**
<del> * Create a new instance with a specific request-target.
<del> *
<del> * You can use this method to overwrite the request target that is
<del> * inferred from the request's Uri. This also lets you change the request
<del> * target's form to an absolute-form, authority-form or asterisk-form
<del> *
<del> * @link http://tools.ietf.org/html/rfc7230#section-2.7 (for the various
<del> * request-target forms allowed in request messages)
<del> * @param string $target The request target.
<del> * @return static
<del> */
<del> public function withRequestTarget($target)
<del> {
<del> $new = clone $this;
<del> $new->requestTarget = $target;
<del>
<del> return $new;
<del> }
<del>
<del> /**
<del> * Retrieves the request's target.
<del> *
<del> * Retrieves the message's request-target either as it was requested,
<del> * or as set with `withRequestTarget()`. By default this will return the
<del> * application relative path without base directory, and the query string
<del> * defined in the SERVER environment.
<del> *
<del> * @return string
<del> */
<del> public function getRequestTarget()
<del> {
<del> if ($this->requestTarget !== null) {
<del> return $this->requestTarget;
<del> }
<del>
<del> $target = $this->uri->getPath();
<del> if ($this->uri->getQuery()) {
<del> $target .= '?' . $this->uri->getQuery();
<del> }
<del>
<del> if (empty($target)) {
<del> $target = '/';
<del> }
<del>
<del> return $target;
<del> }
<del>
<del> /**
<del> * Array access read implementation
<del> *
<del> * @param string $name Name of the key being accessed.
<del> * @return mixed
<del> * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use param(), data() and query() instead.
<del> */
<del> public function offsetGet($name)
<del> {
<del> if (isset($this->params[$name])) {
<del> return $this->params[$name];
<del> }
<del> if ($name === 'url') {
<del> return $this->query;
<del> }
<del> if ($name === 'data') {
<del> return $this->data;
<del> }
<del>
<del> return null;
<del> }
<del>
<del> /**
<del> * Array access write implementation
<del> *
<del> * @param string $name Name of the key being written
<del> * @param mixed $value The value being written.
<del> * @return void
<del> * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use param(), data() and query() instead.
<del> */
<del> public function offsetSet($name, $value)
<del> {
<del> $this->params[$name] = $value;
<del> }
<del>
<del> /**
<del> * Array access isset() implementation
<del> *
<del> * @param string $name thing to check.
<del> * @return bool
<del> * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use param(), data() and query() instead.
<del> */
<del> public function offsetExists($name)
<del> {
<del> if ($name === 'url' || $name === 'data') {
<del> return true;
<del> }
<del>
<del> return isset($this->params[$name]);
<del> }
<del>
<del> /**
<del> * Array access unset() implementation
<del> *
<del> * @param string $name Name to unset.
<del> * @return void
<del> * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use param(), data() and query() instead.
<del> */
<del> public function offsetUnset($name)
<del> {
<del> unset($this->params[$name]);
<del> }
<del>}
<add>// @deprecated Backwards compatibility with earler 3.x versions.
<add>class_alias('Cake\Http\ServerRequest', 'Cake\Network\Request'); | 3 |
Javascript | Javascript | push operations directly to the array | 02a3a2275307389474c11119cef1f13763cfca60 | <ide><path>src/backend/renderer.js
<ide> export function attach(
<ide> // children when Suspense flips to fallback. These Fibers won't have IDs.
<ide> let fibersUnmountedInThisCommitPhase: WeakSet<Fiber> = new WeakSet();
<ide>
<del> // TODO: we could make this layer DEV-only and write directly to pendingOperations.
<del> let nextOperation: Array<number> = [];
<del> function beginNextOperation(size: number): void {
<del> nextOperation.length = size;
<del> }
<del> function endNextOperation(): void {
<add> function pushOperation(op: number): void {
<ide> if (__DEV__) {
<del> for (let i = 0; i < nextOperation.length; i++) {
<del> if (!Number.isInteger(nextOperation[i])) {
<del> console.error(
<del> 'endNextOperation() was called but some values are not integers.',
<del> nextOperation
<del> );
<del> }
<add> if (!Number.isInteger(op)) {
<add> console.error(
<add> 'pushOperation() was called but the value is not an integer.',
<add> op
<add> );
<ide> }
<ide> }
<del> pendingOperations.push.apply(pendingOperations, nextOperation);
<del> nextOperation.length = 0;
<add> pendingOperations.push(op);
<ide> }
<ide>
<ide> function flushPendingEvents(root: Object): void {
<ide> export function attach(
<ide> const hasOwnerMetadata = fiber.hasOwnProperty('_debugOwner');
<ide>
<ide> if (isRoot) {
<del> beginNextOperation(5);
<del> nextOperation[0] = TREE_OPERATION_ADD;
<del> nextOperation[1] = id;
<del> nextOperation[2] = ElementTypeRoot;
<del> nextOperation[3] = isProfilingSupported ? 1 : 0;
<del> nextOperation[4] = hasOwnerMetadata ? 1 : 0;
<del> endNextOperation();
<add> pushOperation(TREE_OPERATION_ADD);
<add> pushOperation(id);
<add> pushOperation(ElementTypeRoot);
<add> pushOperation(isProfilingSupported ? 1 : 0);
<add> pushOperation(hasOwnerMetadata ? 1 : 0);
<ide> } else {
<ide> const { displayName, key, type } = getDataForFiber(fiber);
<ide> const { _debugOwner } = fiber;
<ide> export function attach(
<ide> displayName === null ? 0 : encodedDisplayName.length;
<ide> const encodedKeySize = key === null ? 0 : encodedKey.length;
<ide>
<del> beginNextOperation(7 + encodedDisplayNameSize + encodedKeySize);
<del> nextOperation[0] = TREE_OPERATION_ADD;
<del> nextOperation[1] = id;
<del> nextOperation[2] = type;
<del> nextOperation[3] = parentID;
<del> nextOperation[4] = ownerID;
<del> nextOperation[5] = encodedDisplayNameSize;
<add> pushOperation(TREE_OPERATION_ADD);
<add> pushOperation(id);
<add> pushOperation(type);
<add> pushOperation(parentID);
<add> pushOperation(ownerID);
<add> pushOperation(encodedDisplayNameSize);
<ide> if (displayName !== null) {
<ide> for (let i = 0; i < encodedDisplayName.length; i++) {
<del> nextOperation[6 + i] = encodedDisplayName[i];
<add> pushOperation(encodedDisplayName[i]);
<ide> }
<ide> }
<del> nextOperation[6 + encodedDisplayNameSize] = encodedKeySize;
<add> pushOperation(encodedKeySize);
<ide> if (key !== null) {
<ide> for (let i = 0; i < encodedKey.length; i++) {
<del> nextOperation[6 + encodedDisplayNameSize + 1 + i] = encodedKey[i];
<add> pushOperation(encodedKey[i]);
<ide> }
<ide> }
<del> endNextOperation();
<ide> }
<ide>
<ide> if (isProfiling) {
<ide> // Tree base duration updates are included in the operations typed array.
<ide> // So we have to convert them from milliseconds to microseconds so we can send them as ints.
<ide> const treeBaseDuration = Math.floor(fiber.treeBaseDuration * 1000);
<ide>
<del> beginNextOperation(3);
<del> nextOperation[0] = TREE_OPERATION_UPDATE_TREE_BASE_DURATION;
<del> nextOperation[1] = id;
<del> nextOperation[2] = treeBaseDuration;
<del> endNextOperation();
<add> pushOperation(TREE_OPERATION_UPDATE_TREE_BASE_DURATION);
<add> pushOperation(id);
<add> pushOperation(treeBaseDuration);
<ide>
<ide> const { actualDuration } = fiber;
<ide> if (actualDuration > 0) {
<ide> export function attach(
<ide> if (isRoot) {
<ide> // Removing a root needs to happen at the end
<ide> // so we don't batch it with other unmounts.
<del> beginNextOperation(3);
<del> nextOperation[0] = TREE_OPERATION_REMOVE;
<del> nextOperation[1] = 1; // Remove one item
<del> nextOperation[2] = id;
<del> endNextOperation();
<add> pushOperation(TREE_OPERATION_REMOVE);
<add> pushOperation(1); // Remove one item
<add> pushOperation(id);
<ide> } else if (!shouldFilterFiber(fiber)) {
<ide> // To maintain child-first ordering,
<ide> // we'll push it into one of these queues,
<ide> export function attach(
<ide> // Tree base duration updates are included in the operations typed array.
<ide> // So we have to convert them from milliseconds to microseconds so we can send them as ints.
<ide> const treeBaseDuration = Math.floor(fiber.treeBaseDuration * 1000);
<del>
<del> beginNextOperation(3);
<del> nextOperation[0] = TREE_OPERATION_UPDATE_TREE_BASE_DURATION;
<del> nextOperation[1] = getFiberID(getPrimaryFiber(fiber));
<del> nextOperation[2] = treeBaseDuration;
<del> endNextOperation();
<add> pushOperation(TREE_OPERATION_UPDATE_TREE_BASE_DURATION);
<add> pushOperation(getFiberID(getPrimaryFiber(fiber)));
<add> pushOperation(treeBaseDuration);
<ide> }
<ide>
<ide> if (haveProfilerTimesChanged(fiber.alternate, fiber)) {
<ide> export function attach(
<ide> // No need to reorder.
<ide> return;
<ide> }
<del> beginNextOperation(3 + numChildren);
<del> nextOperation[0] = TREE_OPERATION_REORDER_CHILDREN;
<del> nextOperation[1] = getFiberID(getPrimaryFiber(fiber));
<del> nextOperation[2] = numChildren;
<add> pushOperation(TREE_OPERATION_REORDER_CHILDREN);
<add> pushOperation(getFiberID(getPrimaryFiber(fiber)));
<add> pushOperation(numChildren);
<ide> for (let i = 0; i < nextChildren.length; i++) {
<del> nextOperation[3 + i] = nextChildren[i];
<add> pushOperation(nextChildren[i]);
<ide> }
<del> endNextOperation();
<ide> }
<ide>
<ide> function findReorderedChildrenRecursively( | 1 |
Text | Text | add apiversion to /version for remote api 1.12 | 92f46d233e69a2134ddeaa4843d4b99be00de096 | <ide><path>docs/sources/reference/api/docker_remote_api_v1.12.md
<ide> Show the docker version information
<ide> Content-Type: application/json
<ide>
<ide> {
<add> "ApiVersion":"1.12",
<ide> "Version":"0.2.2",
<ide> "GitCommit":"5a2a5cc+CHANGES",
<ide> "GoVersion":"go1.0.3" | 1 |
Python | Python | add separableconv2d layer (tf only) | 47c09d9557a9c4614270912cb39d55d7e7c01268 | <ide><path>keras/backend/tensorflow_backend.py
<ide> def separable_conv2d(x, depthwise_kernel, pointwise_kernel, strides=(1, 1),
<ide> padding = _preprocess_border_mode(border_mode)
<ide> strides = (1,) + strides + (1,)
<ide>
<del> tf.nn.separable_conv2d(x, depthwise_kernel, pointwise_kernel,
<del> strides, padding)
<add> x = tf.nn.separable_conv2d(x, depthwise_kernel, pointwise_kernel,
<add> strides, padding)
<ide> return _postprocess_conv2d_output(x, dim_ordering)
<ide>
<ide>
<ide><path>keras/layers/convolutional.py
<ide> class Convolution1D(Layer):
<ide> (eg. maxnorm, nonneg), applied to the main weights matrix.
<ide> b_constraint: instance of the [constraints](../constraints.md) module,
<ide> applied to the bias.
<del> bias: whether to include a bias (i.e. make the layer affine rather than linear).
<add> bias: whether to include a bias
<add> (i.e. make the layer affine rather than linear).
<ide> input_dim: Number of channels/dimensions in the input.
<ide> Either this argument or the keyword argument `input_shape`must be
<ide> provided when using this layer as the first layer in a model.
<ide> class Convolution2D(Layer):
<ide> It defaults to the `image_dim_ordering` value found in your
<ide> Keras config file at `~/.keras/keras.json`.
<ide> If you never set it, then it will be "th".
<del> bias: whether to include a bias (i.e. make the layer affine rather than linear).
<add> bias: whether to include a bias
<add> (i.e. make the layer affine rather than linear).
<ide>
<ide> # Input shape
<ide> 4D tensor with shape:
<ide> class AtrousConv2D(Convolution2D):
<ide> '''
<ide> def __init__(self, nb_filter, nb_row, nb_col,
<ide> init='glorot_uniform', activation='linear', weights=None,
<del> border_mode='valid', subsample=(1, 1), atrous_rate=(1, 1), dim_ordering=K.image_dim_ordering(),
<add> border_mode='valid', subsample=(1, 1),
<add> atrous_rate=(1, 1), dim_ordering=K.image_dim_ordering(),
<ide> W_regularizer=None, b_regularizer=None, activity_regularizer=None,
<ide> W_constraint=None, b_constraint=None,
<ide> bias=True, **kwargs):
<ide> def get_config(self):
<ide> return dict(list(base_config.items()) + list(config.items()))
<ide>
<ide>
<add>class SeparableConv2D(Layer):
<add> '''Separable convolution operator for 2D inputs.
<add>
<add> Separable convolutions consist in first performing
<add> a depthwise spatial convolution
<add> (which acts on each input channel separately)
<add> followed by a pointwise convolution which mixes together the resulting
<add> output channels. The `depth_multiplier` argument controls how many
<add> output channels are generated per input channel in the depthwise step.
<add>
<add> Intuitively, separable convolutions can be understood as
<add> a way to factorize a convolution kernel into two smaller kernels,
<add> or as an extreme version of an Inception block.
<add>
<add> When using this layer as the first layer in a model,
<add> provide the keyword argument `input_shape`
<add> (tuple of integers, does not include the sample axis),
<add> e.g. `input_shape=(3, 128, 128)` for 128x128 RGB pictures.
<add>
<add> # Arguments
<add> nb_filter: Number of convolution filters to use.
<add> nb_row: Number of rows in the convolution kernel.
<add> nb_col: Number of columns in the convolution kernel.
<add> init: name of initialization function for the weights of the layer
<add> (see [initializations](../initializations.md)), or alternatively,
<add> Theano function to use for weights initialization.
<add> This parameter is only relevant if you don't pass
<add> a `weights` argument.
<add> activation: name of activation function to use
<add> (see [activations](../activations.md)),
<add> or alternatively, elementwise Theano function.
<add> If you don't specify anything, no activation is applied
<add> (ie. "linear" activation: a(x) = x).
<add> weights: list of numpy arrays to set as initial weights.
<add> border_mode: 'valid' or 'same'.
<add> subsample: tuple of length 2. Factor by which to subsample output.
<add> Also called strides elsewhere.
<add> depth_multiplier: how many output channel to use per input channel
<add> for the depthwise convolution step.
<add> atrous_rate: tuple of length 2. Factor for kernel dilation.
<add> Also called filter_dilation elsewhere.
<add> depthwise_regularizer: instance of [WeightRegularizer](../regularizers.md)
<add> (eg. L1 or L2 regularization), applied to the depthwise weights matrix.
<add> pointwise_regularizer: instance of [WeightRegularizer](../regularizers.md)
<add> (eg. L1 or L2 regularization), applied to the pointwise weights matrix.
<add> b_regularizer: instance of [WeightRegularizer](../regularizers.md),
<add> applied to the bias.
<add> activity_regularizer: instance of [ActivityRegularizer](../regularizers.md),
<add> applied to the network output.
<add> depthwise_constraint: instance of the [constraints](../constraints.md) module
<add> (eg. maxnorm, nonneg), applied to the depthwise weights matrix.
<add> pointwise_constraint: instance of the [constraints](../constraints.md) module
<add> (eg. maxnorm, nonneg), applied to the pointwise weights matrix.
<add> b_constraint: instance of the [constraints](../constraints.md) module,
<add> applied to the bias.
<add> dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension
<add> (the depth) is at index 1, in 'tf' mode is it at index 3.
<add> It defaults to the `image_dim_ordering` value found in your
<add> Keras config file at `~/.keras/keras.json`.
<add> If you never set it, then it will be "th".
<add> bias: whether to include a bias
<add> (i.e. make the layer affine rather than linear).
<add>
<add> # Input shape
<add> 4D tensor with shape:
<add> `(samples, channels, rows, cols)` if dim_ordering='th'
<add> or 4D tensor with shape:
<add> `(samples, rows, cols, channels)` if dim_ordering='tf'.
<add>
<add> # Output shape
<add> 4D tensor with shape:
<add> `(samples, nb_filter, new_rows, new_cols)` if dim_ordering='th'
<add> or 4D tensor with shape:
<add> `(samples, new_rows, new_cols, nb_filter)` if dim_ordering='tf'.
<add> `rows` and `cols` values might have changed due to padding.
<add> '''
<add> def __init__(self, nb_filter, nb_row, nb_col,
<add> init='glorot_uniform', activation='linear', weights=None,
<add> border_mode='valid', subsample=(1, 1),
<add> depth_multiplier=1, dim_ordering=K.image_dim_ordering(),
<add> depthwise_regularizer=None, pointwise_regularizer=None,
<add> b_regularizer=None, activity_regularizer=None,
<add> depthwise_constraint=None, pointwise_constraint=None,
<add> b_constraint=None,
<add> bias=True, **kwargs):
<add>
<add> if K._BACKEND != 'tensorflow':
<add> raise Exception('SeparableConv2D is only available '
<add> 'with TensorFlow for the time being.')
<add>
<add> if border_mode not in {'valid', 'same'}:
<add> raise Exception('Invalid border mode for AtrousConv2D:', border_mode)
<add>
<add> if border_mode not in {'valid', 'same'}:
<add> raise Exception('Invalid border mode for Convolution2D:', border_mode)
<add> self.nb_filter = nb_filter
<add> self.nb_row = nb_row
<add> self.nb_col = nb_col
<add> self.init = initializations.get(init, dim_ordering=dim_ordering)
<add> self.activation = activations.get(activation)
<add> assert border_mode in {'valid', 'same'}, 'border_mode must be in {valid, same}'
<add> self.border_mode = border_mode
<add> self.subsample = tuple(subsample)
<add> self.depth_multiplier = depth_multiplier
<add> assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}'
<add> self.dim_ordering = dim_ordering
<add>
<add> self.depthwise_regularizer = regularizers.get(depthwise_regularizer)
<add> self.pointwise_regularizer = regularizers.get(pointwise_regularizer)
<add> self.b_regularizer = regularizers.get(b_regularizer)
<add> self.activity_regularizer = regularizers.get(activity_regularizer)
<add>
<add> self.depthwise_constraint = constraints.get(depthwise_constraint)
<add> self.pointwise_constraint = constraints.get(pointwise_constraint)
<add> self.b_constraint = constraints.get(b_constraint)
<add>
<add> self.bias = bias
<add> self.input_spec = [InputSpec(ndim=4)]
<add> self.initial_weights = weights
<add> super(SeparableConv2D, self).__init__(**kwargs)
<add>
<add> def build(self, input_shape):
<add> if self.dim_ordering == 'th':
<add> stack_size = input_shape[1]
<add> depthwise_shape = (self.depth_multiplier, stack_size, self.nb_row, self.nb_col)
<add> pointwise_shape = (self.nb_filter, self.depth_multiplier * stack_size, 1, 1)
<add> elif self.dim_ordering == 'tf':
<add> stack_size = input_shape[3]
<add> depthwise_shape = (self.nb_row, self.nb_col, stack_size, self.depth_multiplier)
<add> pointwise_shape = (1, 1, self.depth_multiplier * stack_size, self.nb_filter)
<add> else:
<add> raise Exception('Invalid dim_ordering: ' + self.dim_ordering)
<add> self.depthwise_kernel = self.init(depthwise_shape,
<add> name='{}_depthwise_kernel'.format(self.name))
<add> self.pointwise_kernel = self.init(pointwise_shape,
<add> name='{}_pointwise_kernel'.format(self.name))
<add> if self.bias:
<add> self.b = K.zeros((self.nb_filter,), name='{}_b'.format(self.name))
<add> self.trainable_weights = [self.depthwise_kernel,
<add> self.pointwise_kernel,
<add> self.b]
<add> else:
<add> self.trainable_weights = [self.depthwise_kernel,
<add> self.pointwise_kernel]
<add> self.regularizers = []
<add> if self.depthwise_regularizer:
<add> self.depthwise_regularizer.set_param(self.depthwise_kernel)
<add> self.regularizers.append(self.depthwise_regularizer)
<add> if self.pointwise_regularizer:
<add> self.pointwise_regularizer.set_param(self.pointwise_kernel)
<add> self.regularizers.append(self.pointwise_regularizer)
<add> if self.bias and self.b_regularizer:
<add> self.b_regularizer.set_param(self.b)
<add> self.regularizers.append(self.b_regularizer)
<add> if self.activity_regularizer:
<add> self.activity_regularizer.set_layer(self)
<add> self.regularizers.append(self.activity_regularizer)
<add>
<add> self.constraints = {}
<add> if self.depthwise_constraint:
<add> self.constraints[self.depthwise_kernel] = self.depthwise_constraint
<add> if self.pointwise_constraint:
<add> self.constraints[self.pointwise_kernel] = self.pointwise_constraint
<add> if self.bias and self.b_constraint:
<add> self.constraints[self.b] = self.b_constraint
<add>
<add> if self.initial_weights is not None:
<add> self.set_weights(self.initial_weights)
<add> del self.initial_weights
<add>
<add> def get_output_shape_for(self, input_shape):
<add> if self.dim_ordering == 'th':
<add> rows = input_shape[2]
<add> cols = input_shape[3]
<add> elif self.dim_ordering == 'tf':
<add> rows = input_shape[1]
<add> cols = input_shape[2]
<add> else:
<add> raise Exception('Invalid dim_ordering: ' + self.dim_ordering)
<add>
<add> rows = conv_output_length(rows, self.nb_row,
<add> self.border_mode, self.subsample[0])
<add> cols = conv_output_length(cols, self.nb_col,
<add> self.border_mode, self.subsample[1])
<add>
<add> if self.dim_ordering == 'th':
<add> return (input_shape[0], self.nb_filter, rows, cols)
<add> elif self.dim_ordering == 'tf':
<add> return (input_shape[0], rows, cols, self.nb_filter)
<add> else:
<add> raise Exception('Invalid dim_ordering: ' + self.dim_ordering)
<add>
<add> def call(self, x, mask=None):
<add> output = K.separable_conv2d(x, self.depthwise_kernel,
<add> self.pointwise_kernel,
<add> strides=self.subsample,
<add> border_mode=self.border_mode,
<add> dim_ordering=self.dim_ordering)
<add> if self.bias:
<add> if self.dim_ordering == 'th':
<add> output += K.reshape(self.b, (1, self.nb_filter, 1, 1))
<add> elif self.dim_ordering == 'tf':
<add> output += K.reshape(self.b, (1, 1, 1, self.nb_filter))
<add> else:
<add> raise Exception('Invalid dim_ordering: ' + self.dim_ordering)
<add> output = self.activation(output)
<add> return output
<add>
<add> def get_config(self):
<add> config = {'nb_filter': self.nb_filter,
<add> 'nb_row': self.nb_row,
<add> 'nb_col': self.nb_col,
<add> 'init': self.init.__name__,
<add> 'activation': self.activation.__name__,
<add> 'border_mode': self.border_mode,
<add> 'subsample': self.subsample,
<add> 'depth_multiplier': self.depth_multiplier,
<add> 'dim_ordering': self.dim_ordering,
<add> 'depthwise_regularizer': self.depthwise_regularizer.get_config() if self.depthwise_regularizer else None,
<add> 'pointwise_regularizer': self.depthwise_regularizer.get_config() if self.depthwise_regularizer else None,
<add> 'b_regularizer': self.b_regularizer.get_config() if self.b_regularizer else None,
<add> 'activity_regularizer': self.activity_regularizer.get_config() if self.activity_regularizer else None,
<add> 'depthwise_constraint': self.depthwise_constraint.get_config() if self.depthwise_constraint else None,
<add> 'pointwise_constraint': self.pointwise_constraint.get_config() if self.pointwise_constraint else None,
<add> 'b_constraint': self.b_constraint.get_config() if self.b_constraint else None,
<add> 'bias': self.bias}
<add> base_config = super(SeparableConv2D, self).get_config()
<add> return dict(list(base_config.items()) + list(config.items()))
<add>
<add>
<ide> class Convolution3D(Layer):
<ide> '''Convolution operator for filtering windows of three-dimensional inputs.
<ide> When using this layer as the first layer in a model,
<ide><path>tests/keras/layers/test_convolutional.py
<ide> def test_averagepooling_1d():
<ide>
<ide>
<ide> def test_convolution_2d():
<del> nb_samples = 8
<add> nb_samples = 2
<ide> nb_filter = 3
<ide> stack_size = 4
<ide> nb_row = 10
<ide> def test_convolution_2d():
<ide>
<ide>
<ide> def test_atrous_conv_2d():
<del> nb_samples = 8
<add> nb_samples = 2
<ide> nb_filter = 3
<ide> stack_size = 4
<ide> nb_row = 10
<ide> def test_atrous_conv_2d():
<ide> input_shape=(nb_samples, stack_size, nb_row, nb_col))
<ide>
<ide>
<add>@pytest.mark.skipif(K._BACKEND != 'tensorflow', reason="Requires TF backend")
<add>def test_separable_conv_2d():
<add> nb_samples = 2
<add> nb_filter = 8
<add> stack_size = 4
<add> nb_row = 10
<add> nb_col = 6
<add>
<add> for border_mode in ['valid', 'same']:
<add> for subsample in [(1, 1), (2, 2)]:
<add> for multiplier in [1, 2]:
<add> if border_mode == 'same' and subsample != (1, 1):
<add> continue
<add>
<add> layer_test(convolutional.SeparableConv2D,
<add> kwargs={'nb_filter': nb_filter,
<add> 'nb_row': 3,
<add> 'nb_col': 3,
<add> 'border_mode': border_mode,
<add> 'subsample': subsample,
<add> 'depth_multiplier': multiplier},
<add> input_shape=(nb_samples, stack_size, nb_row, nb_col))
<add>
<add> layer_test(convolutional.SeparableConv2D,
<add> kwargs={'nb_filter': nb_filter,
<add> 'nb_row': 3,
<add> 'nb_col': 3,
<add> 'border_mode': border_mode,
<add> 'depthwise_regularizer': 'l2',
<add> 'pointwise_regularizer': 'l2',
<add> 'b_regularizer': 'l2',
<add> 'activity_regularizer': 'activity_l2',
<add> 'pointwise_constraint': 'unitnorm',
<add> 'depthwise_constraint': 'unitnorm',
<add> 'subsample': subsample,
<add> 'depth_multiplier': multiplier},
<add> input_shape=(nb_samples, stack_size, nb_row, nb_col))
<add>
<add>
<ide> def test_maxpooling_2d():
<ide> pool_size = (3, 3)
<ide>
<ide> def test_averagepooling_3d():
<ide>
<ide>
<ide> def test_zero_padding_2d():
<del> nb_samples = 9
<add> nb_samples = 2
<ide> stack_size = 7
<ide> input_nb_row = 11
<ide> input_nb_col = 12
<ide> def test_zero_padding_2d():
<ide>
<ide> @pytest.mark.skipif(K._BACKEND != 'theano', reason="Requires Theano backend")
<ide> def test_zero_padding_3d():
<del> nb_samples = 9
<add> nb_samples = 2
<ide> stack_size = 7
<ide> input_len_dim1 = 10
<ide> input_len_dim2 = 11
<ide> def test_upsampling_1d():
<ide>
<ide>
<ide> def test_upsampling_2d():
<del> nb_samples = 9
<add> nb_samples = 2
<ide> stack_size = 7
<ide> input_nb_row = 11
<ide> input_nb_col = 12
<ide> def test_upsampling_2d():
<ide>
<ide> @pytest.mark.skipif(K._BACKEND != 'theano', reason="Requires Theano backend")
<ide> def test_upsampling_3d():
<del> nb_samples = 9
<add> nb_samples = 2
<ide> stack_size = 7
<ide> input_len_dim1 = 10
<ide> input_len_dim2 = 11 | 3 |
Python | Python | add bz2 support to loadtxt [patch by ryan may] | 00f70117aed4a20bfa8770560e1759f769ada527 | <ide><path>numpy/lib/io.py
<ide> def loadtxt(fname, dtype=float, comments='#', delimiter=None, converters=None,
<ide> Parameters
<ide> ----------
<ide> fname : file or string
<del> File or filename to read. If the filename extension is ``.gz``,
<del> the file is first decompressed.
<add> File or filename to read. If the filename extension is ``.gz`` or
<add> ``.bz2``, the file is first decompressed.
<ide> dtype : data-type
<ide> Data type of the resulting array. If this is a record data-type,
<ide> the resulting array will be 1-dimensional, and each row will be
<ide> def loadtxt(fname, dtype=float, comments='#', delimiter=None, converters=None,
<ide> if fname.endswith('.gz'):
<ide> import gzip
<ide> fh = gzip.open(fname)
<add> elif fname.endswith('.bz2'):
<add> import bz2
<add> fh = bz2.BZ2File(fname)
<ide> else:
<ide> fh = file(fname)
<ide> elif hasattr(fname, 'readline'): | 1 |
Javascript | Javascript | make template in documentation for {{each}} valid | 898d24d11d20bd802809dcee7cedfcbf78655dac | <ide><path>packages/ember-htmlbars/lib/helpers/each.js
<ide> import normalizeSelf from "ember-htmlbars/utils/normalize-self";
<ide> ```javascript
<ide> App.NoPeopleView = Ember.View.extend({
<ide> tagName: 'li',
<del> template: 'No person is available, sorry'
<add> template: '<p>No person is available, sorry</p>'
<ide> });
<ide> ```
<ide> | 1 |
PHP | PHP | update cache shell to commands | c751690b70b2c8b53b4ed331a6ebefba16130e60 | <ide><path>src/Command/CacheClearAllCommand.php
<add><?php
<add>declare(strict_types=1);
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.0.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Command;
<add>
<add>use Cake\Cache\Cache;
<add>use Cake\Console\Arguments;
<add>use Cake\Console\Command;
<add>use Cake\Console\ConsoleIo;
<add>use Cake\Console\ConsoleOptionParser;
<add>
<add>/**
<add> * CacheClearAll command.
<add> */
<add>class CacheClearAllCommand extends Command
<add>{
<add> /**
<add> * Hook method for defining this command's option parser.
<add> *
<add> * @see https://book.cakephp.org/3.0/en/console-and-shells/commands.html#defining-arguments-and-options
<add> *
<add> * @param \Cake\Console\ConsoleOptionParser $parser The parser to be defined
<add> * @return \Cake\Console\ConsoleOptionParser The built parser.
<add> */
<add> public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
<add> {
<add> $parser = parent::buildOptionParser($parser);
<add> $parser->setDescription('Clear all data in all configured cache engines.');
<add>
<add> return $parser;
<add> }
<add>
<add> /**
<add> * Implement this method with your command's logic.
<add> *
<add> * @param \Cake\Console\Arguments $args The command arguments.
<add> * @param \Cake\Console\ConsoleIo $io The console io
<add> * @return null|int The exit code or null for success
<add> */
<add> public function execute(Arguments $args, ConsoleIo $io): ?int
<add> {
<add> $engines = Cache::configured();
<add> foreach ($engines as $engine) {
<add> $this->executeCommand(CacheClearCommand::class, [$engine], $io);
<add> }
<add>
<add> return static::CODE_SUCCESS;
<add> }
<add>}
<ide><path>src/Command/CacheClearCommand.php
<add><?php
<add>declare(strict_types=1);
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.0.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Command;
<add>
<add>use Cake\Cache\Cache;
<add>use Cake\Cache\Engine\ApcuEngine;
<add>use Cake\Cache\Engine\WincacheEngine;
<add>use Cake\Cache\InvalidArgumentException;
<add>use Cake\Console\Arguments;
<add>use Cake\Console\Command;
<add>use Cake\Console\ConsoleIo;
<add>use Cake\Console\ConsoleOptionParser;
<add>
<add>/**
<add> * CacheClear command.
<add> */
<add>class CacheClearCommand extends Command
<add>{
<add> /**
<add> * Hook method for defining this command's option parser.
<add> *
<add> * @see https://book.cakephp.org/3.0/en/console-and-shells/commands.html#defining-arguments-and-options
<add> *
<add> * @param \Cake\Console\ConsoleOptionParser $parser The parser to be defined
<add> * @return \Cake\Console\ConsoleOptionParser The built parser.
<add> */
<add> public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
<add> {
<add> $parser = parent::buildOptionParser($parser);
<add> $parser
<add> ->setDescription('Clear all data in a single cache engine')
<add> ->addArgument('engine', [
<add> 'help' => 'The cache engine to clear.' .
<add> 'For example, `cake cache clear _cake_model_` will clear the model cache' .
<add> 'Use `cake cache list_engines` to list available engines',
<add> 'required' => true,
<add> ]);
<add>
<add> return $parser;
<add> }
<add>
<add> /**
<add> * Implement this method with your command's logic.
<add> *
<add> * @param \Cake\Console\Arguments $args The command arguments.
<add> * @param \Cake\Console\ConsoleIo $io The console io
<add> * @return null|int The exit code or null for success
<add> */
<add> public function execute(Arguments $args, ConsoleIo $io): ?int
<add> {
<add> $name = $args->getArgument('engine');
<add> try {
<add> $io->out("Clearing {$name}");
<add>
<add> $engine = Cache::pool($name);
<add> Cache::clear($name);
<add> if ($engine instanceof ApcuEngine) {
<add> $io->warn("ApcuEngine detected: Cleared {$name} CLI cache successfully " .
<add> "but {$name} web cache must be cleared separately.");
<add> } elseif ($engine instanceof WincacheEngine) {
<add> $io->warn("WincacheEngine detected: Cleared {$name} CLI cache successfully " .
<add> "but {$name} web cache must be cleared separately.");
<add> } else {
<add> $io->out("<success>Cleared {$name} cache</success>");
<add> }
<add> } catch (InvalidArgumentException $e) {
<add> $io->error($e->getMessage());
<add> $this->abort();
<add> }
<add>
<add> return static::CODE_SUCCESS;
<add> }
<add>}
<ide><path>src/Command/CacheListCommand.php
<add><?php
<add>declare(strict_types=1);
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.0.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Command;
<add>
<add>use Cake\Cache\Cache;
<add>use Cake\Console\Arguments;
<add>use Cake\Console\Command;
<add>use Cake\Console\ConsoleIo;
<add>use Cake\Console\ConsoleOptionParser;
<add>
<add>/**
<add> * CacheList command.
<add> */
<add>class CacheListCommand extends Command
<add>{
<add> /**
<add> * Hook method for defining this command's option parser.
<add> *
<add> * @see https://book.cakephp.org/3.0/en/console-and-shells/commands.html#defining-arguments-and-options
<add> *
<add> * @param \Cake\Console\ConsoleOptionParser $parser The parser to be defined
<add> * @return \Cake\Console\ConsoleOptionParser The built parser.
<add> */
<add> public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
<add> {
<add> $parser = parent::buildOptionParser($parser);
<add> $parser->setDescription('Show a list of configured caches.');
<add>
<add> return $parser;
<add> }
<add>
<add> /**
<add> * Get the list of cache prefixes
<add> *
<add> * @param \Cake\Console\Arguments $args The command arguments.
<add> * @param \Cake\Console\ConsoleIo $io The console io
<add> * @return null|int The exit code or null for success
<add> */
<add> public function execute(Arguments $args, ConsoleIo $io): ?int
<add> {
<add> $engines = Cache::configured();
<add> foreach ($engines as $engine) {
<add> $io->out("- $engine");
<add> }
<add>
<add> return static::CODE_SUCCESS;
<add> }
<add>}
<ide><path>src/Console/CommandScanner.php
<ide> */
<ide> namespace Cake\Console;
<ide>
<add>use Cake\Command\CacheClearAllCommand;
<add>use Cake\Command\CacheClearCommand;
<add>use Cake\Command\CacheListCommand;
<add>use Cake\Command\HelpCommand;
<add>use Cake\Command\UpgradeCommand;
<add>use Cake\Command\VersionCommand;
<ide> use Cake\Core\App;
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<ide> public function scanCore(): array
<ide> '',
<ide> ['command_list']
<ide> );
<del> $coreCommands = $this->scanDir(
<del> dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Command' . DIRECTORY_SEPARATOR,
<del> 'Cake\Command\\',
<del> '',
<del> ['command_list']
<del> );
<add>
<add> $coreCommands = [
<add> [
<add> 'name' => 'cache clear',
<add> 'fullName' => 'cache clear',
<add> 'class' => CacheClearCommand::class,
<add> ],
<add> [
<add> 'name' => 'cache clear_all',
<add> 'fullName' => 'cache clear_all',
<add> 'class' => CacheClearAllCommand::class,
<add> ],
<add> [
<add> 'name' => 'cache list',
<add> 'fullName' => 'cache list',
<add> 'class' => CacheListCommand::class,
<add> ],
<add> [
<add> 'name' => 'help',
<add> 'fullName' => 'help',
<add> 'class' => HelpCommand::class,
<add> ],
<add> [
<add> 'name' => 'upgrade',
<add> 'fullName' => 'upgrade',
<add> 'class' => UpgradeCommand::class,
<add> ],
<add> [
<add> 'name' => 'version',
<add> 'fullName' => 'version',
<add> 'class' => VersionCommand::class,
<add> ],
<add> ];
<ide>
<ide> return array_merge($coreShells, $coreCommands);
<ide> }
<ide><path>src/Shell/CacheShell.php
<del><?php
<del>declare(strict_types=1);
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> * @link https://cakephp.org CakePHP(tm) Project
<del> * @since 3.3.0
<del> * @license https://opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\Shell;
<del>
<del>use Cake\Cache\Cache;
<del>use Cake\Cache\Engine\ApcuEngine;
<del>use Cake\Cache\Engine\WincacheEngine;
<del>use Cake\Cache\InvalidArgumentException;
<del>use Cake\Console\ConsoleOptionParser;
<del>use Cake\Console\Shell;
<del>
<del>/**
<del> * Cache Shell.
<del> *
<del> * Provides a CLI interface to clear caches.
<del> * This tool can be used in development or by deployment scripts when changes
<del> * are made that require cached data to be removed.
<del> */
<del>class CacheShell extends Shell
<del>{
<del> /**
<del> * Get the option parser for this shell.
<del> *
<del> * @return \Cake\Console\ConsoleOptionParser
<del> */
<del> public function getOptionParser(): ConsoleOptionParser
<del> {
<del> $parser = parent::getOptionParser();
<del> $parser->addSubcommand('list_prefixes', [
<del> 'help' => 'Show a list of all defined cache prefixes.',
<del> ]);
<del> $parser->addSubcommand('clear_all', [
<del> 'help' => 'Clear all caches.',
<del> ]);
<del> $parser->addSubcommand('clear', [
<del> 'help' => 'Clear the cache for a specified prefix.',
<del> 'parser' => [
<del> 'description' => [
<del> 'Clear the cache for a particular prefix.',
<del> 'For example, `cake cache clear _cake_model_` will clear the model cache',
<del> 'Use `cake cache list_prefixes` to list available prefixes',
<del> ],
<del> 'arguments' => [
<del> 'prefix' => [
<del> 'help' => 'The cache prefix to be cleared.',
<del> 'required' => true,
<del> ],
<del> ],
<del> ],
<del> ]);
<del>
<del> return $parser;
<del> }
<del>
<del> /**
<del> * Clear metadata.
<del> *
<del> * @param string|null $prefix The cache prefix to be cleared.
<del> * @throws \Cake\Console\Exception\StopException
<del> * @return void
<del> */
<del> public function clear(?string $prefix = null): void
<del> {
<del> try {
<del> $engine = Cache::pool($prefix);
<del> Cache::clear($prefix);
<del> if ($engine instanceof ApcuEngine) {
<del> $this->warn("ApcuEngine detected: Cleared $prefix CLI cache successfully " .
<del> "but $prefix web cache must be cleared separately.");
<del> } elseif ($engine instanceof WincacheEngine) {
<del> $this->warn("WincacheEngine detected: Cleared $prefix CLI cache successfully " .
<del> "but $prefix web cache must be cleared separately.");
<del> } else {
<del> $this->out("<success>Cleared $prefix cache</success>");
<del> }
<del> } catch (InvalidArgumentException $e) {
<del> $this->abort($e->getMessage());
<del> }
<del> }
<del>
<del> /**
<del> * Clear metadata.
<del> *
<del> * @return void
<del> */
<del> public function clearAll(): void
<del> {
<del> $prefixes = Cache::configured();
<del> foreach ($prefixes as $prefix) {
<del> $this->clear($prefix);
<del> }
<del> }
<del>
<del> /**
<del> * Show a list of all defined cache prefixes.
<del> *
<del> * @return void
<del> */
<del> public function listPrefixes(): void
<del> {
<del> $prefixes = Cache::configured();
<del> foreach ($prefixes as $prefix) {
<del> $this->out($prefix);
<del> }
<del> }
<del>}
<add><path>tests/TestCase/Command/CacheCommandsTest.php
<del><path>tests/TestCase/Shell/CacheShellTest.php
<ide> * @since 3.3.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\Test\TestCase\Shell;
<add>namespace Cake\Test\TestCase\Command;
<ide>
<ide> use Cake\Cache\Cache;
<ide> use Cake\Console\Shell;
<ide> use Cake\TestSuite\ConsoleIntegrationTestCase;
<ide>
<ide> /**
<del> * CacheShell tests.
<add> * Cache Commands tests.
<ide> */
<del>class CacheShellTest extends ConsoleIntegrationTestCase
<add>class CacheCommandsTest extends ConsoleIntegrationTestCase
<ide> {
<ide> /**
<ide> * setup method
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<ide> Cache::setConfig('test', ['engine' => 'File', 'path' => CACHE]);
<add> $this->setAppNamespace();
<add> $this->useCommandRunner();
<ide> }
<ide>
<ide> /**
<ide> public function tearDown()
<ide> }
<ide>
<ide> /**
<del> * Test that getOptionParser() returns an instance of \Cake\Console\ConsoleOptionParser
<add> * Test help output
<ide> *
<ide> * @return void
<ide> */
<del> public function testGetOptionParser()
<add> public function testClearHelp()
<ide> {
<del> $this->exec('cache -h');
<add> $this->exec('cache clear -h');
<ide>
<ide> $this->assertExitCode(Shell::CODE_SUCCESS);
<del> $this->assertOutputContains('list_prefixes');
<del> $this->assertOutputContains('clear_all');
<add> $this->assertOutputContains('engine to clear');
<add> }
<add>
<add> /**
<add> * Test help output
<add> *
<add> * @return void
<add> */
<add> public function testClearAllHelp()
<add> {
<add> $this->exec('cache clear_all -h');
<add>
<add> $this->assertExitCode(Shell::CODE_SUCCESS);
<add> $this->assertOutputContains('Clear all');
<add> }
<add>
<add> /**
<add> * Test help output
<add> *
<add> * @return void
<add> */
<add> public function testListHelp()
<add> {
<add> $this->exec('cache list -h');
<add>
<add> $this->assertExitCode(Shell::CODE_SUCCESS);
<add> $this->assertOutputContains('Show a list');
<ide> }
<ide>
<ide> /** | 6 |
Ruby | Ruby | use match? where we don't need matchdata | d1ffe59ab5fd6e811833c127d43b32e87b5d7131 | <ide><path>actionpack/lib/action_dispatch/http/mime_negotiation.rb
<ide> def params_readable? # :doc:
<ide>
<ide> def valid_accept_header # :doc:
<ide> (xhr? && (accept.present? || content_mime_type)) ||
<del> (accept.present? && accept !~ BROWSER_LIKE_ACCEPTS)
<add> (accept.present? && !accept.match?(BROWSER_LIKE_ACCEPTS))
<ide> end
<ide>
<ide> def use_accept_header # :doc:
<ide><path>actionpack/lib/action_dispatch/http/url.rb
<ide> def build_host_url(host, port, protocol, options, path)
<ide> end
<ide>
<ide> def named_host?(host)
<del> IP_HOST_REGEXP !~ host
<add> !IP_HOST_REGEXP.match?(host)
<ide> end
<ide>
<ide> def normalize_protocol(protocol)
<ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb
<ide> def handle_options(options)
<ide>
<ide> # If host is not ip and matches domain regexp.
<ide> # (ip confirms to domain regexp so we explicitly check for ip)
<del> options[:domain] = if (request.host !~ /^[\d.]+$/) && (request.host =~ domain_regexp)
<add> options[:domain] = if !request.host.match?(/^[\d.]+$/) && (request.host =~ domain_regexp)
<ide> ".#{$&}"
<ide> end
<ide> elsif options[:domain].is_a? Array
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def self.normalize_path(path, format)
<ide> end
<ide>
<ide> def self.optional_format?(path, format)
<del> format != false && path !~ OPTIONAL_FORMAT_REGEX
<add> format != false && !path.match?(OPTIONAL_FORMAT_REGEX)
<ide> end
<ide>
<ide> def initialize(set:, ast:, controller:, default_action:, to:, formatted:, via:, options_constraints:, anchor:, scope_params:, options:)
<ide> def name_for_action(as, action)
<ide> # and return nil in case it isn't. Otherwise, we pass the invalid name
<ide> # forward so the underlying router engine treats it and raises an exception.
<ide> if as.nil?
<del> candidate unless candidate !~ /\A[_a-z]/i || has_named_route?(candidate)
<add> candidate unless !candidate.match?(/\A[_a-z]/i) || has_named_route?(candidate)
<ide> else
<ide> candidate
<ide> end
<ide><path>actionpack/test/dispatch/debug_exceptions_test.rb
<ide> def call(env)
<ide> @app = DevelopmentApp
<ide> Rails.stub :root, Pathname.new(".") do
<ide> cleaner = ActiveSupport::BacktraceCleaner.new.tap do |bc|
<del> bc.add_silencer { |line| line =~ /method_that_raises/ }
<del> bc.add_silencer { |line| line !~ %r{test/dispatch/debug_exceptions_test.rb} }
<add> bc.add_silencer { |line| line.match?(/method_that_raises/) }
<add> bc.add_silencer { |line| !line.match?(%r{test/dispatch/debug_exceptions_test.rb}) }
<ide> end
<ide>
<ide> get "/framework_raises", headers: { "action_dispatch.backtrace_cleaner" => cleaner }
<ide> def call(env)
<ide> @app = DevelopmentApp
<ide> Rails.stub :root, Pathname.new(".") do
<ide> cleaner = ActiveSupport::BacktraceCleaner.new.tap do |bc|
<del> bc.add_silencer { |line| line !~ %r{test/dispatch/debug_exceptions_test.rb} }
<add> bc.add_silencer { |line| !line.match?(%r{test/dispatch/debug_exceptions_test.rb}) }
<ide> end
<ide>
<ide> get "/nested_exceptions", headers: { "action_dispatch.backtrace_cleaner" => cleaner }
<ide> def call(env)
<ide> @app = DevelopmentApp
<ide> Rails.stub :root, Pathname.new(".") do
<ide> cleaner = ActiveSupport::BacktraceCleaner.new.tap do |bc|
<del> bc.add_silencer { |line| line !~ %r{test/dispatch/debug_exceptions_test.rb} }
<add> bc.add_silencer { |line| !line.match?(%r{test/dispatch/debug_exceptions_test.rb}) }
<ide> end
<ide>
<ide> get "/actionable_error", headers: { "action_dispatch.backtrace_cleaner" => cleaner }
<ide><path>actionpack/test/dispatch/exception_wrapper_test.rb
<ide> def backtrace
<ide> setup do
<ide> @cleaner = ActiveSupport::BacktraceCleaner.new
<ide> @cleaner.remove_filters!
<del> @cleaner.add_silencer { |line| line !~ /^lib/ }
<add> @cleaner.add_silencer { |line| !line.match?(/^lib/) }
<ide> end
<ide>
<ide> test "#source_extracts fetches source fragments for every backtrace entry" do
<ide><path>actionview/lib/action_view/helpers/url_helper.rb
<ide> def link_to_remote_options?(options)
<ide> end
<ide>
<ide> def add_method_to_attributes!(html_options, method)
<del> if method_not_get_method?(method) && html_options["rel"] !~ /nofollow/
<add> if method_not_get_method?(method) && !html_options["rel"]&.match?(/nofollow/)
<ide> if html_options["rel"].blank?
<ide> html_options["rel"] = "nofollow"
<ide> else
<ide><path>actionview/lib/action_view/layouts.rb
<ide> def _layout_for_option(name)
<ide> end
<ide>
<ide> def _normalize_layout(value)
<del> value.is_a?(String) && value !~ /\blayouts/ ? "layouts/#{value}" : value
<add> value.is_a?(String) && !value.match?(/\blayouts/) ? "layouts/#{value}" : value
<ide> end
<ide>
<ide> # Returns the default layout for this controller.
<ide><path>activemodel/lib/active_model/validations/format.rb
<ide> class FormatValidator < EachValidator # :nodoc:
<ide> def validate_each(record, attribute, value)
<ide> if options[:with]
<ide> regexp = option_call(record, :with)
<del> record_error(record, attribute, :with, value) if value.to_s !~ regexp
<add> record_error(record, attribute, :with, value) unless regexp.match?(value.to_s)
<ide> elsif options[:without]
<ide> regexp = option_call(record, :without)
<ide> record_error(record, attribute, :without, value) if regexp.match?(value.to_s)
<ide><path>activerecord/lib/active_record/attribute_methods/query.rb
<ide> def query_attribute(attr_name)
<ide> when false, nil then false
<ide> else
<ide> if !type_for_attribute(attr_name) { false }
<del> if Numeric === value || value !~ /[^0-9]/
<add> if Numeric === value || !value.match?(/[^0-9]/)
<ide> !value.to_i.zero?
<ide> else
<ide> return false if ActiveModel::Type::Boolean::FALSE_VALUES.include?(value)
<ide><path>activerecord/lib/active_record/connection_adapters/connection_specification.rb
<ide> def build_configuration_sentence # :nodoc:
<ide> # hash and merges with the rest of the hash.
<ide> # Connection details inside of the "url" key win any merge conflicts
<ide> def resolve_hash_connection(spec)
<del> if spec["url"] && spec["url"] !~ /^jdbc:/
<add> if spec["url"] && !spec["url"].match?(/^jdbc:/)
<ide> connection_hash = resolve_url_connection(spec.delete("url"))
<ide> spec.merge!(connection_hash)
<ide> end
<ide><path>activerecord/lib/active_record/explain_subscriber.rb
<ide> def ignore_payload?(payload)
<ide> payload[:exception] ||
<ide> payload[:cached] ||
<ide> IGNORED_PAYLOADS.include?(payload[:name]) ||
<del> payload[:sql] !~ EXPLAINED_SQLS
<add> !payload[:sql].match?(EXPLAINED_SQLS)
<ide> end
<ide>
<ide> ActiveSupport::Notifications.subscribe("sql.active_record", new)
<ide><path>activerecord/lib/arel/visitors/oracle.rb
<ide> def visit_Arel_Nodes_SelectStatement(o, collector)
<ide>
<ide> # if need to select first records without ORDER BY and GROUP BY and without DISTINCT
<ide> # then can use simple ROWNUM in WHERE clause
<del> if o.limit && o.orders.empty? && o.cores.first.groups.empty? && !o.offset && o.cores.first.set_quantifier.class.to_s !~ /Distinct/
<add> if o.limit && o.orders.empty? && o.cores.first.groups.empty? && !o.offset && !o.cores.first.set_quantifier.class.to_s.match?(/Distinct/)
<ide> o.cores.last.wheres.push Nodes::LessThanOrEqual.new(
<ide> Nodes::SqlLiteral.new("ROWNUM"), o.limit.expr
<ide> )
<ide><path>activerecord/test/cases/associations/belongs_to_associations_test.rb
<ide> def test_belongs_to_does_not_use_order_by
<ide> Client.find(3).firm
<ide> ensure
<ide> sql_log = ActiveRecord::SQLCounter.log
<del> assert sql_log.all? { |sql| /order by/i !~ sql }, "ORDER BY was used in the query: #{sql_log}"
<add> assert sql_log.all? { |sql| !/order by/i.match?(sql) }, "ORDER BY was used in the query: #{sql_log}"
<ide> end
<ide>
<ide> def test_belongs_to_with_primary_key
<ide><path>activerecord/test/cases/associations/has_one_associations_test.rb
<ide> def test_has_one_does_not_use_order_by
<ide> companies(:first_firm).account
<ide> ensure
<ide> sql_log = ActiveRecord::SQLCounter.log
<del> assert sql_log.all? { |sql| /order by/i !~ sql }, "ORDER BY was used in the query: #{sql_log}"
<add> assert sql_log.all? { |sql| !/order by/i.match?(sql) }, "ORDER BY was used in the query: #{sql_log}"
<ide> end
<ide>
<ide> def test_has_one_cache_nils
<ide><path>activesupport/lib/active_support/core_ext/name_error.rb
<ide> def missing_name
<ide> # We should use original_message message instead.
<ide> message = respond_to?(:original_message) ? original_message : self.message
<ide>
<del> if /undefined local variable or method/ !~ message
<add> unless /undefined local variable or method/.match?(message)
<ide> $1 if /((::)?([A-Z]\w*)(::[A-Z]\w*)*)$/ =~ message
<ide> end
<ide> end
<ide><path>activesupport/lib/active_support/option_merger.rb
<ide> module ActiveSupport
<ide> class OptionMerger #:nodoc:
<ide> instance_methods.each do |method|
<del> undef_method(method) if method !~ /^(__|instance_eval|class|object_id)/
<add> undef_method(method) unless method.match?(/^(__|instance_eval|class|object_id)/)
<ide> end
<ide>
<ide> def initialize(context, options)
<ide><path>activesupport/test/message_encryptor_test.rb
<ide> def test_on_rotation_is_called_and_returns_modified_messages
<ide> def test_on_rotation_can_be_passed_at_the_constructor_level
<ide> older_message = ActiveSupport::MessageEncryptor.new(secrets[:older], "older sign").encrypt_and_sign(encoded: "message")
<ide>
<del> rotated = false
<add> rotated = rotated = false # double assigning to suppress "assigned but unused variable" warning
<ide> encryptor = ActiveSupport::MessageEncryptor.new(@secret, on_rotation: proc { rotated = true })
<ide> encryptor.rotate secrets[:older], "older sign"
<ide>
<ide> def test_on_rotation_can_be_passed_at_the_constructor_level
<ide> def test_on_rotation_option_takes_precedence_over_the_one_given_in_constructor
<ide> older_message = ActiveSupport::MessageEncryptor.new(secrets[:older], "older sign").encrypt_and_sign(encoded: "message")
<ide>
<del> rotated = false
<add> rotated = rotated = false # double assigning to suppress "assigned but unused variable" warning
<ide> encryptor = ActiveSupport::MessageEncryptor.new(@secret, on_rotation: proc { rotated = true })
<ide> encryptor.rotate secrets[:older], "older sign"
<ide>
<ide><path>railties/lib/rails/code_statistics.rb
<ide> def calculate_directory_statistics(directory, pattern = /^(?!\.).*?\.(rb|js|coff
<ide> Dir.foreach(directory) do |file_name|
<ide> path = "#{directory}/#{file_name}"
<ide>
<del> if File.directory?(path) && (/^\./ !~ file_name)
<add> if File.directory?(path) && !(/^\./.match?(file_name))
<ide> stats.add(calculate_directory_statistics(path, pattern))
<ide> elsif file_name&.match?(pattern)
<ide> stats.add_by_file_path(path)
<ide><path>railties/lib/rails/code_statistics_calculator.rb
<ide> def add_by_io(io, file_type)
<ide>
<ide> @classes += 1 if patterns[:class] && line =~ patterns[:class]
<ide> @methods += 1 if patterns[:method] && line =~ patterns[:method]
<del> if line !~ /^\s*$/ && (patterns[:line_comment].nil? || line !~ patterns[:line_comment])
<add> if !line.match?(/^\s*$/) && (patterns[:line_comment].nil? || !line.match?(patterns[:line_comment]))
<ide> @code_lines += 1
<ide> end
<ide> end
<ide><path>railties/lib/rails/command/base.rb
<ide> def hide_command!
<ide> def inherited(base) #:nodoc:
<ide> super
<ide>
<del> if base.name && base.name !~ /Base$/
<add> if base.name && !base.name.match?(/Base$/)
<ide> Rails::Command.subclasses << base
<ide> end
<ide> end
<ide><path>railties/lib/rails/engine.rb
<ide> def inherited(base)
<ide> base.called_from = begin
<ide> call_stack = caller_locations.map { |l| l.absolute_path || l.path }
<ide>
<del> File.dirname(call_stack.detect { |p| p !~ %r[railties[\w.-]*/lib/rails|rack[\w.-]*/lib/rack] })
<add> File.dirname(call_stack.detect { |p| !p.match?(%r[railties[\w.-]*/lib/rails|rack[\w.-]*/lib/rack]) })
<ide> end
<ide> end
<ide>
<ide><path>railties/lib/rails/generators/base.rb
<ide> def self.inherited(base) #:nodoc:
<ide> # Invoke source_root so the default_source_root is set.
<ide> base.source_root
<ide>
<del> if base.name && base.name !~ /Base$/
<add> if base.name && !base.name.match?(/Base$/)
<ide> Rails::Generators.subclasses << base
<ide>
<ide> Rails::Generators.templates_path.each do |path| | 23 |
Javascript | Javascript | remove unnecessary comments | 56dcecfd09231b18c7cafeb3d2e2c17222d87cb8 | <ide><path>packages/ember/tests/routing/query_params_test/model_dependent_state_with_query_params_test.js
<ide> class ModelDependentQPTestCase extends QueryParamTestCase {
<ide> assert.equal(this.controller.get('q'), 'lol');
<ide> assert.equal(this.controller.get('z'), 0);
<ide> assert.equal(this.$link1.attr('href'), `${urlPrefix}/a-1?q=lol`);
<del> assert.equal(this.$link2.attr('href'), `${urlPrefix}/a-2?q=lol`); // fail
<add> assert.equal(this.$link2.attr('href'), `${urlPrefix}/a-2?q=lol`);
<ide> assert.equal(this.$link3.attr('href'), `${urlPrefix}/a-3`);
<ide>
<ide> this.expectedModelHookParams = { id: 'a-3', q: 'lol', z: 123 };
<ide> moduleFor('Query Params - model-dependent state (nested & more than 1 dynamic se
<ide> }
<ide>
<ide> ['@test query params have \'model\' stickiness by default'](assert) {
<del> assert.expect(59); // Insane.
<add> assert.expect(59);
<ide>
<ide> return this.boot().then(() => {
<ide> run(this.links['s-1-a-1'], 'click');
<ide> moduleFor('Query Params - model-dependent state (nested & more than 1 dynamic se
<ide> }
<ide>
<ide> ['@test query params have \'model\' stickiness by default (url changes)'](assert) {
<del> assert.expect(88); // INSANE.
<add> assert.expect(88);
<ide>
<ide> return this.boot().then(() => {
<ide> this.expectedSiteModelHookParams = { site_id: 's-1', country: 'au' };
<ide> moduleFor('Query Params - model-dependent state (nested & more than 1 dynamic se
<ide> }
<ide>
<ide> ['@test query params have \'model\' stickiness by default (params-based transitions)'](assert) {
<del> assert.expect(118); // <-- INSANE! Like why is this even a thing?
<add> assert.expect(118);
<ide>
<ide> return this.boot().then(() => {
<ide> this.expectedSiteModelHookParams = { site_id: 's-1', country: 'au' }; | 1 |
Javascript | Javascript | add friendly tips about how to exit repl" | 4dbfb096f04c49aaa8349626296193ecff6bf2f6 | <ide><path>lib/repl.js
<ide> function REPLServer(prompt,
<ide>
<ide> function defaultEval(code, context, file, cb) {
<ide> var err, result, script, wrappedErr;
<del> var isExitCommand = false;
<ide> var wrappedCmd = false;
<ide> var awaitPromise = false;
<ide> var input = code;
<del> var trimmedCommand = code.trim();
<del>
<del> if (trimmedCommand === 'exit' || trimmedCommand === 'quit') {
<del> isExitCommand = true;
<del> }
<ide>
<ide> if (/^\s*\{/.test(code) && /\}\s*$/.test(code)) {
<ide> // It's confusing for `{ a : 1 }` to be interpreted as a block
<ide> function REPLServer(prompt,
<ide> breakOnSigint: self.breakEvalOnSigint
<ide> };
<ide>
<del> const localContext = self.useGlobal ? global : self.context;
<del> if (isExitCommand && !localContext.hasOwnProperty(trimmedCommand)) {
<del> self.outputStream.write('(To exit, press ^D or type .exit)\n');
<del> return self.displayPrompt();
<del> }
<del>
<ide> if (self.useGlobal) {
<ide> result = script.runInThisContext(scriptOptions);
<ide> } else {
<del> result = script.runInContext(localContext, scriptOptions);
<add> result = script.runInContext(context, scriptOptions);
<ide> }
<ide> } finally {
<ide> if (self.breakEvalOnSigint) {
<ide> function REPLServer(prompt,
<ide> }
<ide> } catch (e) {
<ide> err = e;
<add>
<ide> if (err && err.code === 'ERR_SCRIPT_EXECUTION_INTERRUPTED') {
<del> // The stack trace for this case is not very useful anyway.
<add> // The stack trace for this case is not very useful anyway.
<ide> Object.defineProperty(err, 'stack', { value: '' });
<ide> }
<add>
<ide> if (process.domain) {
<ide> debug('not recoverable, send to domain');
<ide> process.domain.emit('error', err);
<ide><path>test/parallel/test-repl.js
<ide> const strictModeTests = [
<ide> }
<ide> ];
<ide>
<del>const friendlyExitTests = [
<del> {
<del> send: 'exit',
<del> expect: '(To exit, press ^D or type .exit)'
<del> },
<del> {
<del> send: 'quit',
<del> expect: '(To exit, press ^D or type .exit)'
<del> },
<del> {
<del> send: 'quit = 1',
<del> expect: '1'
<del> },
<del> {
<del> send: 'quit',
<del> expect: '1'
<del> },
<del> {
<del> send: 'exit',
<del> expect: '(To exit, press ^D or type .exit)'
<del> },
<del>];
<del>
<ide> const errorTests = [
<ide> // Uncaught error throws and prints out
<ide> {
<ide> const tcpTests = [
<ide> const [ socket, replServer ] = await startUnixRepl();
<ide>
<ide> await runReplTests(socket, prompt_unix, unixTests);
<del> await runReplTests(socket, prompt_unix, friendlyExitTests);
<ide> await runReplTests(socket, prompt_unix, errorTests);
<ide> replServer.replMode = repl.REPL_MODE_STRICT;
<ide> await runReplTests(socket, prompt_unix, strictModeTests); | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.