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 node.js version to bug template | 7d6fbe7fd62a3d1f7a918b40f6c9c777ca8730af | <ide><path>.github/ISSUE_TEMPLATE/1.Bug_report.md
<ide> If applicable, add screenshots to help explain your problem.
<ide> - OS: [e.g. macOS, Windows]
<ide> - Browser (if applies) [e.g. chrome, safari]
<ide> - Version of Next.js: [e.g. 6.0.2]
<add>- Version of Node.js: [e.g. 10.10.0]
<ide>
<ide> ## Additional context
<ide> | 1 |
Text | Text | use https in documentation links where possible | 3a29b99e3b24e4d7dbfcb22df5e1f98ba9a0be4b | <ide><path>docs/README.md
<ide> var myChart = new Chart(ctx, {
<ide>
<ide> Before submitting an issue or a pull request to the project, please take a moment to look over the [contributing guidelines](https://github.com/chartjs/Chart.js/blob/master/docs/developers/contributing.md) first.
<ide>
<del>For support using Chart.js, please post questions with the [`chartjs` tag on Stack Overflow](http://stackoverflow.com/questions/tagged/chartjs).
<add>For support using Chart.js, please post questions with the [`chartjs` tag on Stack Overflow](https://stackoverflow.com/questions/tagged/chartjs).
<ide>
<ide> ## License
<ide>
<del>Chart.js is available under the [MIT license](http://opensource.org/licenses/MIT).
<add>Chart.js is available under the [MIT license](https://opensource.org/licenses/MIT).
<ide><path>docs/axes/cartesian/time.md
<ide> The x-axis data points may additionally be specified via the `t` or `x` attribut
<ide>
<ide> ### Date Formats
<ide>
<del>When providing data for the time scale, Chart.js supports all of the formats that Moment.js accepts. See [Moment.js docs](http://momentjs.com/docs/#/parsing/) for details.
<add>When providing data for the time scale, Chart.js supports all of the formats that Moment.js accepts. See [Moment.js docs](https://momentjs.com/docs/#/parsing/) for details.
<ide>
<ide> ## Configuration Options
<ide>
<ide> var chart = new Chart(ctx, {
<ide> ```
<ide>
<ide> ### Display Formats
<del>The following display formats are used to configure how different time units are formed into strings for the axis tick marks. See [moment.js](http://momentjs.com/docs/#/displaying/format/) for the allowable format strings.
<add>The following display formats are used to configure how different time units are formed into strings for the axis tick marks. See [moment.js](https://momentjs.com/docs/#/displaying/format/) for the allowable format strings.
<ide>
<ide> Name | Default | Example
<ide> --- | --- | ---
<ide><path>docs/charts/line.md
<ide> When charting a lot of data, the chart render time may start to get quite large.
<ide>
<ide> Decimating your data will achieve the best results. When there is a lot of data to display on the graph, it doesn't make sense to show tens of thousands of data points on a graph that is only a few hundred pixels wide.
<ide>
<del>There are many approaches to data decimation and selection of an algorithm will depend on your data and the results you want to achieve. For instance, [min/max](http://digital.ni.com/public.nsf/allkb/F694FFEEA0ACF282862576020075F784) decimation will preserve peaks in your data but could require up to 4 points for each pixel. This type of decimation would work well for a very noisy signal where you need to see data peaks.
<add>There are many approaches to data decimation and selection of an algorithm will depend on your data and the results you want to achieve. For instance, [min/max](https://digital.ni.com/public.nsf/allkb/F694FFEEA0ACF282862576020075F784) decimation will preserve peaks in your data but could require up to 4 points for each pixel. This type of decimation would work well for a very noisy signal where you need to see data peaks.
<ide>
<ide> ## Disable Bezier Curves
<ide>
<ide><path>docs/configuration/tooltip.md
<ide> var myPieChart = new Chart(ctx, {
<ide> });
<ide> ```
<ide>
<del>See [samples](http://www.chartjs.org/samples/) for examples on how to get started with custom tooltips.
<add>See [samples](https://www.chartjs.org/samples/) for examples on how to get started with custom tooltips.
<ide>
<ide> ## Tooltip Model
<ide> The tooltip model contains parameters that can be used to render the tooltip.
<ide><path>docs/developers/README.md
<ide> Developer features allow extending and enhancing Chart.js in many different ways
<ide>
<ide> Latest documentation and samples, including unreleased features, are available at:
<ide>
<del> - http://www.chartjs.org/docs/master/
<del> - http://www.chartjs.org/samples/master/
<add> - https://www.chartjs.org/docs/master/
<add> - https://www.chartjs.org/samples/master/
<ide>
<ide> # Development releases
<ide>
<ide> Latest builds are available for testing at:
<ide>
<del> - http://www.chartjs.org/dist/master/Chart.min.js
<del> - http://www.chartjs.org/dist/master/Chart.bundle.min.js
<add> - https://www.chartjs.org/dist/master/Chart.min.js
<add> - https://www.chartjs.org/dist/master/Chart.bundle.min.js
<ide>
<ide> > Note: Development builds are currently only available via HTTP, so in order to include them in [JSFiddle](http://jsfiddle.net) or [CodePen](http://codepen.io), you need to access these tools via HTTP as well.
<ide>
<ide> Chart.js offers support for the following browsers:
<ide> * Edge 14+
<ide> * Safari 9+
<ide>
<del>Browser support for the canvas element is available in all modern & major mobile browsers. [CanIUse](http://caniuse.com/#feat=canvas)
<add>Browser support for the canvas element is available in all modern & major mobile browsers. [CanIUse](https://caniuse.com/#feat=canvas)
<ide>
<ide> Thanks to [BrowserStack](https://browserstack.com) for allowing our team to test on thousands of browsers.
<ide>
<ide> Version 2 has a completely different API than earlier versions.
<ide>
<ide> Most earlier version options have current equivalents or are the same.
<ide>
<del>Please use the documentation that is available on [chartjs.org](http://www.chartjs.org/docs/) for the current version of Chart.js.
<add>Please use the documentation that is available on [chartjs.org](https://www.chartjs.org/docs/) for the current version of Chart.js.
<ide>
<ide> Please note - documentation for previous versions are available on the GitHub repo.
<ide>
<ide><path>docs/developers/contributing.md
<ide> New contributions to the library are welcome, but we ask that you please follow
<ide>
<ide> # Building and Testing
<ide>
<del>Chart.js uses <a href="http://gulpjs.com/" target="_blank">gulp</a> to build the library into a single JavaScript file.
<add>Chart.js uses <a href="https://gulpjs.com/" target="_blank">gulp</a> to build the library into a single JavaScript file.
<ide>
<ide> Firstly, we need to ensure development dependencies are installed. With node and npm installed, after cloning the Chart.js repo to a local directory, and navigating to that directory in the command line, we can run the following:
<ide>
<ide> Firstly, we need to ensure development dependencies are installed. With node and
<ide> > npm install -g gulp
<ide> ```
<ide>
<del>This will install the local development dependencies for Chart.js, along with a CLI for the JavaScript task runner <a href="http://gulpjs.com/" target="_blank">gulp</a>.
<add>This will install the local development dependencies for Chart.js, along with a CLI for the JavaScript task runner <a href="https://gulpjs.com/" target="_blank">gulp</a>.
<ide>
<ide> The following commands are now available from the repository root:
<ide>
<ide> More information can be found in [gulpfile.js](https://github.com/chartjs/Chart.
<ide>
<ide> # Bugs and Issues
<ide>
<del>Please report these on the GitHub page - at <a href="https://github.com/chartjs/Chart.js" target="_blank">github.com/chartjs/Chart.js</a>. Please do not use issues for support requests. For help using Chart.js, please take a look at the [`chartjs`](http://stackoverflow.com/questions/tagged/chartjs) tag on Stack Overflow.
<add>Please report these on the GitHub page - at <a href="https://github.com/chartjs/Chart.js" target="_blank">github.com/chartjs/Chart.js</a>. Please do not use issues for support requests. For help using Chart.js, please take a look at the [`chartjs`](https://stackoverflow.com/questions/tagged/chartjs) tag on Stack Overflow.
<ide>
<ide> Well structured, detailed bug reports are hugely valuable for the project.
<ide>
<ide> Guidelines for reporting bugs:
<ide>
<ide> - Check the issue search to see if it has already been reported
<ide> - Isolate the problem to a simple test case
<del> - Please include a demonstration of the bug on a website such as [JS Bin](http://jsbin.com/), [JS Fiddle](http://jsfiddle.net/), or [Codepen](http://codepen.io/pen/). ([Template](http://codepen.io/pen?template=JXVYzq))
<add> - Please include a demonstration of the bug on a website such as [JS Bin](https://jsbin.com/), [JS Fiddle](https://jsfiddle.net/), or [Codepen](https://codepen.io/pen/). ([Template](https://codepen.io/pen?template=JXVYzq))
<ide>
<ide> Please provide any additional details associated with the bug, if it's browser or screen density specific, or only happens with a certain configuration or data.
<ide><path>docs/getting-started/installation.md
<ide> https://cdnjs.com/libraries/Chart.js
<ide> ### jsDelivr
<ide> [](https://cdn.jsdelivr.net/npm/chart.js@latest/dist/) [](https://www.jsdelivr.com/package/npm/chart.js)
<ide>
<del>Chart.js built files are also available through [jsDelivr](http://www.jsdelivr.com/):
<add>Chart.js built files are also available through [jsDelivr](https://www.jsdelivr.com/):
<ide>
<ide> https://www.jsdelivr.com/package/npm/chart.js?path=dist
<ide>
<ide> Files:
<ide> * `dist/Chart.js`
<ide> * `dist/Chart.min.js`
<ide>
<del>The stand-alone build includes Chart.js as well as the color parsing library. If this version is used, you are required to include [Moment.js](http://momentjs.com/) before Chart.js for the functionality of the time axis.
<add>The stand-alone build includes Chart.js as well as the color parsing library. If this version is used, you are required to include [Moment.js](https://momentjs.com/) before Chart.js for the functionality of the time axis.
<ide>
<ide> ## Bundled Build
<ide> Files:
<ide><path>docs/notes/license.md
<ide> # License
<ide>
<del>Chart.js is <a href="https://github.com/chartjs/Chart.js" target="_blank">open source</a> and available under the <a href="http://opensource.org/licenses/MIT" target="_blank">MIT license</a>.
<ide>\ No newline at end of file
<add>Chart.js is <a href="https://github.com/chartjs/Chart.js" target="_blank">open source</a> and available under the <a href="https://opensource.org/licenses/MIT" target="_blank">MIT license</a>.
<ide>\ No newline at end of file | 8 |
Text | Text | update the sponsor name | 3cec2c477f64d069994556f834fdf963763af7cb | <ide><path>PATRONS.md
<ide> The work on Redux was [funded by the community](https://www.patreon.com/reactdx)
<ide> Meet some of the outstanding companies and individuals that made it possible:
<ide>
<ide> * [Webflow](https://github.com/webflow)
<del>* [Chess iX](http://www.chess-ix.com/)
<add>* [Ximedes](https://www.ximedes.com/)
<ide> * [Herman J. Radtke III](http://hermanradtke.com)
<ide> * [Ken Wheeler](http://kenwheeler.github.io/)
<ide> * [Chung Yen Li](https://www.facebook.com/prototocal.lee) | 1 |
PHP | PHP | getpdo() docblock | 5e5bad00d1fa3fb51666e44b77c593422660e85f | <ide><path>src/Illuminate/Support/Facades/DB.php
<ide> namespace Illuminate\Support\Facades;
<ide>
<ide> /**
<del> * @method static \Doctrine\DBAL\Driver\PDOConnection getPdo()
<add> * @method static \PDO getPdo()
<ide> * @method static \Illuminate\Database\ConnectionInterface connection(string $name = null)
<ide> * @method static \Illuminate\Database\Query\Builder table(string $table, string $as = null)
<ide> * @method static \Illuminate\Database\Query\Builder query() | 1 |
Text | Text | remove roadmap to 2.0 | 2103e0541b8e2149a8b2e1e53d6a0ea8a66efb46 | <ide><path>readme.md
<ide> Next.js is a minimalistic framework for server-rendered React applications.
<ide> - [Customizing babel config](#customizing-babel-config)
<ide> - [Production deployment](#production-deployment)
<ide> - [FAQ](#faq)
<del>- [Roadmap](#roadmap)
<ide> - [Contributing](#contributing)
<ide> - [Authors](#authors)
<ide>
<ide> As we were researching options for server-rendering React that didn’t involve
<ide>
<ide> </details>
<ide>
<del>## Roadmap
<del>
<del>Our Roadmap towards 2.0.0 [is public](https://github.com/zeit/next.js/wiki/Roadmap#nextjs-200).
<del>
<ide> ## Contributing
<ide>
<ide> Please see our [contributing.md](./contributing.md) | 1 |
Javascript | Javascript | convert passive unmount phase to tree traversal | 1cf59f34b89728f8ef2bc17158c438ab17f063bd | <ide><path>packages/react-reconciler/src/ReactFiber.new.js
<ide> export function resetWorkInProgress(workInProgress: Fiber, renderLanes: Lanes) {
<ide> // We assume pendingProps, index, key, ref, return are still untouched to
<ide> // avoid doing another reconciliation.
<ide>
<del> // Reset the effect tag but keep any Placement tags, since that's something
<add> // Reset the effect flags but keep any Placement tags, since that's something
<ide> // that child fiber is setting, not the reconciliation.
<ide> workInProgress.flags &= Placement;
<ide>
<ide><path>packages/react-reconciler/src/ReactFiber.old.js
<ide> export function resetWorkInProgress(workInProgress: Fiber, renderLanes: Lanes) {
<ide> // We assume pendingProps, index, key, ref, return are still untouched to
<ide> // avoid doing another reconciliation.
<ide>
<del> // Reset the effect tag but keep any Placement tags, since that's something
<add> // Reset the effect flags but keep any Placement tags, since that's something
<ide> // that child fiber is setting, not the reconciliation.
<ide> workInProgress.flags &= Placement;
<ide>
<ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js
<ide> import type {FunctionComponentUpdateQueue} from './ReactFiberHooks.new';
<ide> import type {Wakeable} from 'shared/ReactTypes';
<ide> import type {ReactPriorityLevel} from './ReactInternalTypes';
<ide> import type {OffscreenState} from './ReactFiberOffscreenComponent';
<add>import type {HookFlags} from './ReactHookEffectTags';
<ide>
<ide> import {unstable_wrap as Schedule_tracing_wrap} from 'scheduler/tracing';
<ide> import {
<ide> import {
<ide> NoFlags,
<ide> ContentReset,
<ide> Placement,
<add> ChildDeletion,
<ide> Snapshot,
<ide> Update,
<ide> Passive,
<add> PassiveStatic,
<ide> PassiveMask,
<add> PassiveUnmountPendingDev,
<ide> } from './ReactFiberFlags';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import invariant from 'shared/invariant';
<ide> function commitBeforeMutationLifeCycles(
<ide> );
<ide> }
<ide>
<del>function commitHookEffectListUnmount(tag: number, finishedWork: Fiber) {
<add>function commitHookEffectListUnmount(flags: HookFlags, finishedWork: Fiber) {
<ide> const updateQueue: FunctionComponentUpdateQueue | null = (finishedWork.updateQueue: any);
<ide> const lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
<ide> if (lastEffect !== null) {
<ide> const firstEffect = lastEffect.next;
<ide> let effect = firstEffect;
<ide> do {
<del> if ((effect.tag & tag) === tag) {
<add> if ((effect.tag & flags) === flags) {
<ide> // Unmount
<ide> const destroy = effect.destroy;
<ide> effect.destroy = undefined;
<ide> if (destroy !== undefined) {
<del> destroy();
<add> safelyCallDestroy(finishedWork, destroy);
<ide> }
<ide> }
<ide> effect = effect.next;
<ide> function commitPassiveMountOnFiber(
<ide> }
<ide> }
<ide>
<add>export function commitPassiveUnmountEffects(firstChild: Fiber): void {
<add> nextEffect = firstChild;
<add> commitPassiveUnmountEffects_begin();
<add>}
<add>
<add>function commitPassiveUnmountEffects_begin() {
<add> while (nextEffect !== null) {
<add> const fiber = nextEffect;
<add> const child = fiber.child;
<add>
<add> if ((nextEffect.flags & ChildDeletion) !== NoFlags) {
<add> const deletions = fiber.deletions;
<add> if (deletions !== null) {
<add> for (let i = 0; i < deletions.length; i++) {
<add> const fiberToDelete = deletions[i];
<add> nextEffect = fiberToDelete;
<add> commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete);
<add>
<add> // Now that passive effects have been processed, it's safe to detach lingering pointers.
<add> detachFiberAfterEffects(fiberToDelete);
<add> }
<add> nextEffect = fiber;
<add> }
<add> }
<add>
<add> if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) {
<add> ensureCorrectReturnPointer(child, fiber);
<add> nextEffect = child;
<add> } else {
<add> commitPassiveUnmountEffects_complete();
<add> }
<add> }
<add>}
<add>
<add>function commitPassiveUnmountEffects_complete() {
<add> while (nextEffect !== null) {
<add> const fiber = nextEffect;
<add> if ((fiber.flags & Passive) !== NoFlags) {
<add> setCurrentDebugFiberInDEV(fiber);
<add> commitPassiveUnmountOnFiber(fiber);
<add> resetCurrentDebugFiberInDEV();
<add> }
<add>
<add> const sibling = fiber.sibling;
<add> if (sibling !== null) {
<add> ensureCorrectReturnPointer(sibling, fiber.return);
<add> nextEffect = sibling;
<add> return;
<add> }
<add>
<add> nextEffect = fiber.return;
<add> }
<add>}
<add>
<add>function commitPassiveUnmountOnFiber(finishedWork: Fiber): void {
<add> if (__DEV__) {
<add> finishedWork.flags &= ~PassiveUnmountPendingDev;
<add> const alternate = finishedWork.alternate;
<add> if (alternate !== null) {
<add> alternate.flags &= ~PassiveUnmountPendingDev;
<add> }
<add> }
<add>
<add> switch (finishedWork.tag) {
<add> case FunctionComponent:
<add> case ForwardRef:
<add> case SimpleMemoComponent: {
<add> if (
<add> enableProfilerTimer &&
<add> enableProfilerCommitHooks &&
<add> finishedWork.mode & ProfileMode
<add> ) {
<add> startPassiveEffectTimer();
<add> commitHookEffectListUnmount(HookPassive | HookHasEffect, finishedWork);
<add> recordPassiveEffectDuration(finishedWork);
<add> } else {
<add> commitHookEffectListUnmount(HookPassive | HookHasEffect, finishedWork);
<add> }
<add> break;
<add> }
<add> }
<add>}
<add>
<add>function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
<add> deletedSubtreeRoot: Fiber,
<add>) {
<add> while (nextEffect !== null) {
<add> const fiber = nextEffect;
<add> const child = fiber.child;
<add> if ((fiber.subtreeFlags & PassiveStatic) !== NoFlags && child !== null) {
<add> ensureCorrectReturnPointer(child, fiber);
<add> nextEffect = child;
<add> } else {
<add> commitPassiveUnmountEffectsInsideOfDeletedTree_complete(
<add> deletedSubtreeRoot,
<add> );
<add> }
<add> }
<add>}
<add>
<add>function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(
<add> deletedSubtreeRoot: Fiber,
<add>) {
<add> while (nextEffect !== null) {
<add> const fiber = nextEffect;
<add> if ((fiber.flags & PassiveStatic) !== NoFlags) {
<add> setCurrentDebugFiberInDEV(fiber);
<add> commitPassiveUnmountInsideDeletedTreeOnFiber(fiber);
<add> resetCurrentDebugFiberInDEV();
<add> }
<add>
<add> if (fiber === deletedSubtreeRoot) {
<add> nextEffect = null;
<add> return;
<add> }
<add>
<add> const sibling = fiber.sibling;
<add> if (sibling !== null) {
<add> ensureCorrectReturnPointer(sibling, fiber.return);
<add> nextEffect = sibling;
<add> return;
<add> }
<add>
<add> nextEffect = fiber.return;
<add> }
<add>}
<add>
<add>function commitPassiveUnmountInsideDeletedTreeOnFiber(current: Fiber): void {
<add> switch (current.tag) {
<add> case FunctionComponent:
<add> case ForwardRef:
<add> case SimpleMemoComponent: {
<add> if (
<add> enableProfilerTimer &&
<add> enableProfilerCommitHooks &&
<add> current.mode & ProfileMode
<add> ) {
<add> startPassiveEffectTimer();
<add> commitHookEffectListUnmount(HookPassive, current);
<add> recordPassiveEffectDuration(current);
<add> } else {
<add> commitHookEffectListUnmount(HookPassive, current);
<add> }
<add> break;
<add> }
<add> }
<add>}
<add>
<ide> let didWarnWrongReturnPointer = false;
<ide> function ensureCorrectReturnPointer(fiber, expectedReturnFiber) {
<ide> if (__DEV__) {
<ide><path>packages/react-reconciler/src/ReactFiberCommitWork.old.js
<ide> import type {FunctionComponentUpdateQueue} from './ReactFiberHooks.old';
<ide> import type {Wakeable} from 'shared/ReactTypes';
<ide> import type {ReactPriorityLevel} from './ReactInternalTypes';
<ide> import type {OffscreenState} from './ReactFiberOffscreenComponent';
<add>import type {HookFlags} from './ReactHookEffectTags';
<ide>
<ide> import {unstable_wrap as Schedule_tracing_wrap} from 'scheduler/tracing';
<ide> import {
<ide> import {
<ide> NoFlags,
<ide> ContentReset,
<ide> Placement,
<add> ChildDeletion,
<ide> Snapshot,
<ide> Update,
<ide> Passive,
<add> PassiveStatic,
<ide> PassiveMask,
<add> PassiveUnmountPendingDev,
<ide> } from './ReactFiberFlags';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import invariant from 'shared/invariant';
<ide> function commitBeforeMutationLifeCycles(
<ide> );
<ide> }
<ide>
<del>function commitHookEffectListUnmount(tag: number, finishedWork: Fiber) {
<add>function commitHookEffectListUnmount(flags: HookFlags, finishedWork: Fiber) {
<ide> const updateQueue: FunctionComponentUpdateQueue | null = (finishedWork.updateQueue: any);
<ide> const lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
<ide> if (lastEffect !== null) {
<ide> const firstEffect = lastEffect.next;
<ide> let effect = firstEffect;
<ide> do {
<del> if ((effect.tag & tag) === tag) {
<add> if ((effect.tag & flags) === flags) {
<ide> // Unmount
<ide> const destroy = effect.destroy;
<ide> effect.destroy = undefined;
<ide> if (destroy !== undefined) {
<del> destroy();
<add> safelyCallDestroy(finishedWork, destroy);
<ide> }
<ide> }
<ide> effect = effect.next;
<ide> function commitPassiveMountOnFiber(
<ide> }
<ide> }
<ide>
<add>export function commitPassiveUnmountEffects(firstChild: Fiber): void {
<add> nextEffect = firstChild;
<add> commitPassiveUnmountEffects_begin();
<add>}
<add>
<add>function commitPassiveUnmountEffects_begin() {
<add> while (nextEffect !== null) {
<add> const fiber = nextEffect;
<add> const child = fiber.child;
<add>
<add> if ((nextEffect.flags & ChildDeletion) !== NoFlags) {
<add> const deletions = fiber.deletions;
<add> if (deletions !== null) {
<add> for (let i = 0; i < deletions.length; i++) {
<add> const fiberToDelete = deletions[i];
<add> nextEffect = fiberToDelete;
<add> commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete);
<add>
<add> // Now that passive effects have been processed, it's safe to detach lingering pointers.
<add> detachFiberAfterEffects(fiberToDelete);
<add> }
<add> nextEffect = fiber;
<add> }
<add> }
<add>
<add> if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) {
<add> ensureCorrectReturnPointer(child, fiber);
<add> nextEffect = child;
<add> } else {
<add> commitPassiveUnmountEffects_complete();
<add> }
<add> }
<add>}
<add>
<add>function commitPassiveUnmountEffects_complete() {
<add> while (nextEffect !== null) {
<add> const fiber = nextEffect;
<add> if ((fiber.flags & Passive) !== NoFlags) {
<add> setCurrentDebugFiberInDEV(fiber);
<add> commitPassiveUnmountOnFiber(fiber);
<add> resetCurrentDebugFiberInDEV();
<add> }
<add>
<add> const sibling = fiber.sibling;
<add> if (sibling !== null) {
<add> ensureCorrectReturnPointer(sibling, fiber.return);
<add> nextEffect = sibling;
<add> return;
<add> }
<add>
<add> nextEffect = fiber.return;
<add> }
<add>}
<add>
<add>function commitPassiveUnmountOnFiber(finishedWork: Fiber): void {
<add> if (__DEV__) {
<add> finishedWork.flags &= ~PassiveUnmountPendingDev;
<add> const alternate = finishedWork.alternate;
<add> if (alternate !== null) {
<add> alternate.flags &= ~PassiveUnmountPendingDev;
<add> }
<add> }
<add>
<add> switch (finishedWork.tag) {
<add> case FunctionComponent:
<add> case ForwardRef:
<add> case SimpleMemoComponent: {
<add> if (
<add> enableProfilerTimer &&
<add> enableProfilerCommitHooks &&
<add> finishedWork.mode & ProfileMode
<add> ) {
<add> startPassiveEffectTimer();
<add> commitHookEffectListUnmount(HookPassive | HookHasEffect, finishedWork);
<add> recordPassiveEffectDuration(finishedWork);
<add> } else {
<add> commitHookEffectListUnmount(HookPassive | HookHasEffect, finishedWork);
<add> }
<add> break;
<add> }
<add> }
<add>}
<add>
<add>function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
<add> deletedSubtreeRoot: Fiber,
<add>) {
<add> while (nextEffect !== null) {
<add> const fiber = nextEffect;
<add> const child = fiber.child;
<add> if ((fiber.subtreeFlags & PassiveStatic) !== NoFlags && child !== null) {
<add> ensureCorrectReturnPointer(child, fiber);
<add> nextEffect = child;
<add> } else {
<add> commitPassiveUnmountEffectsInsideOfDeletedTree_complete(
<add> deletedSubtreeRoot,
<add> );
<add> }
<add> }
<add>}
<add>
<add>function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(
<add> deletedSubtreeRoot: Fiber,
<add>) {
<add> while (nextEffect !== null) {
<add> const fiber = nextEffect;
<add> if ((fiber.flags & PassiveStatic) !== NoFlags) {
<add> setCurrentDebugFiberInDEV(fiber);
<add> commitPassiveUnmountInsideDeletedTreeOnFiber(fiber);
<add> resetCurrentDebugFiberInDEV();
<add> }
<add>
<add> if (fiber === deletedSubtreeRoot) {
<add> nextEffect = null;
<add> return;
<add> }
<add>
<add> const sibling = fiber.sibling;
<add> if (sibling !== null) {
<add> ensureCorrectReturnPointer(sibling, fiber.return);
<add> nextEffect = sibling;
<add> return;
<add> }
<add>
<add> nextEffect = fiber.return;
<add> }
<add>}
<add>
<add>function commitPassiveUnmountInsideDeletedTreeOnFiber(current: Fiber): void {
<add> switch (current.tag) {
<add> case FunctionComponent:
<add> case ForwardRef:
<add> case SimpleMemoComponent: {
<add> if (
<add> enableProfilerTimer &&
<add> enableProfilerCommitHooks &&
<add> current.mode & ProfileMode
<add> ) {
<add> startPassiveEffectTimer();
<add> commitHookEffectListUnmount(HookPassive, current);
<add> recordPassiveEffectDuration(current);
<add> } else {
<add> commitHookEffectListUnmount(HookPassive, current);
<add> }
<add> break;
<add> }
<add> }
<add>}
<add>
<ide> let didWarnWrongReturnPointer = false;
<ide> function ensureCorrectReturnPointer(fiber, expectedReturnFiber) {
<ide> if (__DEV__) {
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> import type {Interaction} from 'scheduler/src/Tracing';
<ide> import type {SuspenseState} from './ReactFiberSuspenseComponent.new';
<ide> import type {Effect as HookEffect} from './ReactFiberHooks.new';
<ide> import type {StackCursor} from './ReactFiberStack.new';
<add>import type {FunctionComponentUpdateQueue} from './ReactFiberHooks.new';
<ide>
<ide> import {
<ide> warnAboutDeprecatedLifecycles,
<ide> import {
<ide> flushSyncCallbackQueue,
<ide> scheduleSyncCallback,
<ide> } from './SchedulerWithReactIntegration.new';
<add>import {
<add> NoFlags as NoHookEffect,
<add> Passive as HookPassive,
<add>} from './ReactHookEffectTags';
<ide> import {
<ide> logCommitStarted,
<ide> logCommitStopped,
<ide> import {
<ide> Snapshot,
<ide> Callback,
<ide> Passive,
<del> PassiveUnmountPendingDev,
<add> PassiveStatic,
<ide> Incomplete,
<ide> HostEffectMask,
<ide> Hydrating,
<ide> import {
<ide> commitResetTextContent,
<ide> isSuspenseBoundaryBeingHidden,
<ide> commitPassiveMountEffects,
<add> commitPassiveUnmountEffects,
<ide> detachFiberAfterEffects,
<ide> } from './ReactFiberCommitWork.new';
<ide> import {enqueueUpdate} from './ReactUpdateQueue.new';
<ide> import {
<ide> import {
<ide> markNestedUpdateScheduled,
<ide> recordCommitTime,
<del> recordPassiveEffectDuration,
<ide> resetNestedUpdateFlag,
<del> startPassiveEffectTimer,
<ide> startProfilerTimer,
<ide> stopProfilerTimerIfRunningAndRecordDelta,
<ide> syncNestedUpdateFlag,
<ide> let rootDoesHavePassiveEffects: boolean = false;
<ide> let rootWithPendingPassiveEffects: FiberRoot | null = null;
<ide> let pendingPassiveEffectsRenderPriority: ReactPriorityLevel = NoSchedulerPriority;
<ide> let pendingPassiveEffectsLanes: Lanes = NoLanes;
<del>let pendingPassiveHookEffectsUnmount: Array<HookEffect | Fiber> = [];
<ide> let pendingPassiveProfilerEffects: Array<Fiber> = [];
<ide>
<ide> let rootsWithPendingDiscreteUpdates: Set<FiberRoot> | null = null;
<ide> export function enqueuePendingPassiveHookEffectUnmount(
<ide> fiber: Fiber,
<ide> effect: HookEffect,
<ide> ): void {
<del> pendingPassiveHookEffectsUnmount.push(effect, fiber);
<del> if (__DEV__) {
<del> fiber.flags |= PassiveUnmountPendingDev;
<del> const alternate = fiber.alternate;
<del> if (alternate !== null) {
<del> alternate.flags |= PassiveUnmountPendingDev;
<del> }
<del> }
<ide> if (!rootDoesHavePassiveEffects) {
<ide> rootDoesHavePassiveEffects = true;
<ide> scheduleCallback(NormalSchedulerPriority, () => {
<ide> function flushPassiveEffectsImpl() {
<ide> executionContext |= CommitContext;
<ide> const prevInteractions = pushInteractions(root);
<ide>
<del> // It's important that ALL pending passive effect destroy functions are called
<del> // before ANY passive effect create functions are called.
<del> // Otherwise effects in sibling components might interfere with each other.
<del> // e.g. a destroy function in one component may unintentionally override a ref
<del> // value set by a create function in another component.
<del> // Layout effects have the same constraint.
<del>
<del> // First pass: Destroy stale passive effects.
<del> const unmountEffects = pendingPassiveHookEffectsUnmount;
<del> pendingPassiveHookEffectsUnmount = [];
<del> for (let i = 0; i < unmountEffects.length; i += 2) {
<del> const effect = ((unmountEffects[i]: any): HookEffect);
<del> const fiber = ((unmountEffects[i + 1]: any): Fiber);
<del> const destroy = effect.destroy;
<del> effect.destroy = undefined;
<del>
<del> if (__DEV__) {
<del> fiber.flags &= ~PassiveUnmountPendingDev;
<del> const alternate = fiber.alternate;
<del> if (alternate !== null) {
<del> alternate.flags &= ~PassiveUnmountPendingDev;
<del> }
<del> }
<del>
<del> if (typeof destroy === 'function') {
<del> if (__DEV__) {
<del> setCurrentDebugFiberInDEV(fiber);
<del> if (
<del> enableProfilerTimer &&
<del> enableProfilerCommitHooks &&
<del> fiber.mode & ProfileMode
<del> ) {
<del> startPassiveEffectTimer();
<del> invokeGuardedCallback(null, destroy, null);
<del> recordPassiveEffectDuration(fiber);
<del> } else {
<del> invokeGuardedCallback(null, destroy, null);
<del> }
<del> if (hasCaughtError()) {
<del> invariant(fiber !== null, 'Should be working on an effect.');
<del> const error = clearCaughtError();
<del> captureCommitPhaseError(fiber, error);
<del> }
<del> resetCurrentDebugFiberInDEV();
<del> } else {
<del> try {
<del> if (
<del> enableProfilerTimer &&
<del> enableProfilerCommitHooks &&
<del> fiber.mode & ProfileMode
<del> ) {
<del> try {
<del> startPassiveEffectTimer();
<del> destroy();
<del> } finally {
<del> recordPassiveEffectDuration(fiber);
<del> }
<del> } else {
<del> destroy();
<del> }
<del> } catch (error) {
<del> invariant(fiber !== null, 'Should be working on an effect.');
<del> captureCommitPhaseError(fiber, error);
<del> }
<del> }
<del> }
<del> }
<del> // Second pass: Create new passive effects.
<add> commitPassiveUnmountEffects(root.current);
<ide> commitPassiveMountEffects(root, root.current);
<ide>
<ide> // TODO: Move to commitPassiveMountEffects
<ide> function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
<ide> return;
<ide> }
<ide>
<del> // If there are pending passive effects unmounts for this Fiber,
<del> // we can assume that they would have prevented this update.
<del> if ((fiber.flags & PassiveUnmountPendingDev) !== NoFlags) {
<del> return;
<del> }
<add> if ((fiber.flags & PassiveStatic) !== NoFlags) {
<add> const updateQueue: FunctionComponentUpdateQueue | null = (fiber.updateQueue: any);
<add> if (updateQueue !== null) {
<add> const lastEffect = updateQueue.lastEffect;
<add> if (lastEffect !== null) {
<add> const firstEffect = lastEffect.next;
<ide>
<add> let effect = firstEffect;
<add> do {
<add> if (effect.destroy !== undefined) {
<add> if ((effect.tag & HookPassive) !== NoHookEffect) {
<add> return;
<add> }
<add> }
<add> effect = effect.next;
<add> } while (effect !== firstEffect);
<add> }
<add> }
<add> }
<ide> // We show the whole stack but dedupe on the top component's name because
<ide> // the problematic code almost always lies inside that component.
<ide> const componentName = getComponentName(fiber.type) || 'ReactComponent';
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> import type {Interaction} from 'scheduler/src/Tracing';
<ide> import type {SuspenseState} from './ReactFiberSuspenseComponent.old';
<ide> import type {Effect as HookEffect} from './ReactFiberHooks.old';
<ide> import type {StackCursor} from './ReactFiberStack.old';
<add>import type {FunctionComponentUpdateQueue} from './ReactFiberHooks.old';
<ide>
<ide> import {
<ide> warnAboutDeprecatedLifecycles,
<ide> import {
<ide> flushSyncCallbackQueue,
<ide> scheduleSyncCallback,
<ide> } from './SchedulerWithReactIntegration.old';
<add>import {
<add> NoFlags as NoHookEffect,
<add> Passive as HookPassive,
<add>} from './ReactHookEffectTags';
<ide> import {
<ide> logCommitStarted,
<ide> logCommitStopped,
<ide> import {
<ide> Snapshot,
<ide> Callback,
<ide> Passive,
<del> PassiveUnmountPendingDev,
<add> PassiveStatic,
<ide> Incomplete,
<ide> HostEffectMask,
<ide> Hydrating,
<ide> import {
<ide> commitResetTextContent,
<ide> isSuspenseBoundaryBeingHidden,
<ide> commitPassiveMountEffects,
<add> commitPassiveUnmountEffects,
<ide> detachFiberAfterEffects,
<ide> } from './ReactFiberCommitWork.old';
<ide> import {enqueueUpdate} from './ReactUpdateQueue.old';
<ide> import {
<ide> import {
<ide> markNestedUpdateScheduled,
<ide> recordCommitTime,
<del> recordPassiveEffectDuration,
<ide> resetNestedUpdateFlag,
<del> startPassiveEffectTimer,
<ide> startProfilerTimer,
<ide> stopProfilerTimerIfRunningAndRecordDelta,
<ide> syncNestedUpdateFlag,
<ide> let rootDoesHavePassiveEffects: boolean = false;
<ide> let rootWithPendingPassiveEffects: FiberRoot | null = null;
<ide> let pendingPassiveEffectsRenderPriority: ReactPriorityLevel = NoSchedulerPriority;
<ide> let pendingPassiveEffectsLanes: Lanes = NoLanes;
<del>let pendingPassiveHookEffectsUnmount: Array<HookEffect | Fiber> = [];
<ide> let pendingPassiveProfilerEffects: Array<Fiber> = [];
<ide>
<ide> let rootsWithPendingDiscreteUpdates: Set<FiberRoot> | null = null;
<ide> export function enqueuePendingPassiveHookEffectUnmount(
<ide> fiber: Fiber,
<ide> effect: HookEffect,
<ide> ): void {
<del> pendingPassiveHookEffectsUnmount.push(effect, fiber);
<del> if (__DEV__) {
<del> fiber.flags |= PassiveUnmountPendingDev;
<del> const alternate = fiber.alternate;
<del> if (alternate !== null) {
<del> alternate.flags |= PassiveUnmountPendingDev;
<del> }
<del> }
<ide> if (!rootDoesHavePassiveEffects) {
<ide> rootDoesHavePassiveEffects = true;
<ide> scheduleCallback(NormalSchedulerPriority, () => {
<ide> function flushPassiveEffectsImpl() {
<ide> executionContext |= CommitContext;
<ide> const prevInteractions = pushInteractions(root);
<ide>
<del> // It's important that ALL pending passive effect destroy functions are called
<del> // before ANY passive effect create functions are called.
<del> // Otherwise effects in sibling components might interfere with each other.
<del> // e.g. a destroy function in one component may unintentionally override a ref
<del> // value set by a create function in another component.
<del> // Layout effects have the same constraint.
<del>
<del> // First pass: Destroy stale passive effects.
<del> const unmountEffects = pendingPassiveHookEffectsUnmount;
<del> pendingPassiveHookEffectsUnmount = [];
<del> for (let i = 0; i < unmountEffects.length; i += 2) {
<del> const effect = ((unmountEffects[i]: any): HookEffect);
<del> const fiber = ((unmountEffects[i + 1]: any): Fiber);
<del> const destroy = effect.destroy;
<del> effect.destroy = undefined;
<del>
<del> if (__DEV__) {
<del> fiber.flags &= ~PassiveUnmountPendingDev;
<del> const alternate = fiber.alternate;
<del> if (alternate !== null) {
<del> alternate.flags &= ~PassiveUnmountPendingDev;
<del> }
<del> }
<del>
<del> if (typeof destroy === 'function') {
<del> if (__DEV__) {
<del> setCurrentDebugFiberInDEV(fiber);
<del> if (
<del> enableProfilerTimer &&
<del> enableProfilerCommitHooks &&
<del> fiber.mode & ProfileMode
<del> ) {
<del> startPassiveEffectTimer();
<del> invokeGuardedCallback(null, destroy, null);
<del> recordPassiveEffectDuration(fiber);
<del> } else {
<del> invokeGuardedCallback(null, destroy, null);
<del> }
<del> if (hasCaughtError()) {
<del> invariant(fiber !== null, 'Should be working on an effect.');
<del> const error = clearCaughtError();
<del> captureCommitPhaseError(fiber, error);
<del> }
<del> resetCurrentDebugFiberInDEV();
<del> } else {
<del> try {
<del> if (
<del> enableProfilerTimer &&
<del> enableProfilerCommitHooks &&
<del> fiber.mode & ProfileMode
<del> ) {
<del> try {
<del> startPassiveEffectTimer();
<del> destroy();
<del> } finally {
<del> recordPassiveEffectDuration(fiber);
<del> }
<del> } else {
<del> destroy();
<del> }
<del> } catch (error) {
<del> invariant(fiber !== null, 'Should be working on an effect.');
<del> captureCommitPhaseError(fiber, error);
<del> }
<del> }
<del> }
<del> }
<del> // Second pass: Create new passive effects.
<add> commitPassiveUnmountEffects(root.current);
<ide> commitPassiveMountEffects(root, root.current);
<ide>
<ide> // TODO: Move to commitPassiveMountEffects
<ide> function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
<ide> return;
<ide> }
<ide>
<del> // If there are pending passive effects unmounts for this Fiber,
<del> // we can assume that they would have prevented this update.
<del> if ((fiber.flags & PassiveUnmountPendingDev) !== NoFlags) {
<del> return;
<del> }
<add> if ((fiber.flags & PassiveStatic) !== NoFlags) {
<add> const updateQueue: FunctionComponentUpdateQueue | null = (fiber.updateQueue: any);
<add> if (updateQueue !== null) {
<add> const lastEffect = updateQueue.lastEffect;
<add> if (lastEffect !== null) {
<add> const firstEffect = lastEffect.next;
<ide>
<add> let effect = firstEffect;
<add> do {
<add> if (effect.destroy !== undefined) {
<add> if ((effect.tag & HookPassive) !== NoHookEffect) {
<add> return;
<add> }
<add> }
<add> effect = effect.next;
<add> } while (effect !== firstEffect);
<add> }
<add> }
<add> }
<ide> // We show the whole stack but dedupe on the top component's name because
<ide> // the problematic code almost always lies inside that component.
<ide> const componentName = getComponentName(fiber.type) || 'ReactComponent'; | 6 |
Python | Python | add support for axis lists in element wise ops | 160196137fde3fd57c5051aea75ea9830eb25d62 | <ide><path>keras/backend/tensorflow_backend.py
<ide> def gather(reference, indices):
<ide>
<ide> # ELEMENT-WISE OPERATIONS
<ide>
<add>def normalize_axis(axis, ndim):
<add> if type(axis) is tuple:
<add> axis = list(axis)
<add> if type(axis) is list:
<add> for i, a in enumerate(axis):
<add> if a is not None and a < 0:
<add> axis[i] = a % ndim
<add> else:
<add> if axis is not None and axis < 0:
<add> axis = axis % ndim
<add> return axis
<add>
<add>
<ide> def max(x, axis=None, keepdims=False):
<del> if axis is not None and axis < 0:
<del> axis = axis % len(x.get_shape())
<add> axis = normalize_axis(axis, ndim(x))
<ide> return tf.reduce_max(x, reduction_indices=axis, keep_dims=keepdims)
<ide>
<ide>
<ide> def min(x, axis=None, keepdims=False):
<del> if axis is not None and axis < 0:
<del> axis = axis % len(x.get_shape())
<add> axis = normalize_axis(axis, ndim(x))
<ide> return tf.reduce_min(x, reduction_indices=axis, keep_dims=keepdims)
<ide>
<ide>
<ide> def sum(x, axis=None, keepdims=False):
<ide> '''Sum of the values in a tensor, alongside the specified axis.
<ide> '''
<del> if axis is not None and axis < 0:
<del> axis = axis % len(x.get_shape())
<add> axis = normalize_axis(axis, ndim(x))
<ide> return tf.reduce_sum(x, reduction_indices=axis, keep_dims=keepdims)
<ide>
<ide>
<ide> def prod(x, axis=None, keepdims=False):
<ide> '''Multiply the values in a tensor, alongside the specified axis.
<ide> '''
<add> axis = normalize_axis(axis, ndim(x))
<ide> return tf.reduce_prod(x, reduction_indices=axis, keep_dims=keepdims)
<ide>
<ide>
<ide> def std(x, axis=None, keepdims=False):
<del> if axis is not None and axis < 0:
<del> axis = axis % len(x.get_shape())
<add> axis = normalize_axis(axis, ndim(x))
<ide> if x.dtype.base_dtype == tf.bool:
<ide> x = tf.cast(x, _FLOATX)
<del> m = tf.reduce_mean(x, reduction_indices=axis, keep_dims=keepdims)
<add> m = tf.reduce_mean(x, reduction_indices=axis, keep_dims=True)
<ide> devs_squared = tf.square(x - m)
<ide> return tf.sqrt(tf.reduce_mean(devs_squared,
<ide> reduction_indices=axis,
<ide> keep_dims=keepdims))
<ide>
<ide>
<ide> def mean(x, axis=None, keepdims=False):
<del> if axis is not None and axis < 0:
<del> axis = axis % len(x.get_shape())
<add> axis = normalize_axis(axis, ndim(x))
<ide> if x.dtype.base_dtype == tf.bool:
<ide> x = tf.cast(x, _FLOATX)
<ide> return tf.reduce_mean(x, reduction_indices=axis, keep_dims=keepdims)
<ide> def any(x, axis=None, keepdims=False):
<ide>
<ide> Return array of int8 (0s and 1s).
<ide> '''
<del> if axis is not None and axis < 0:
<del> axis = axis % len(x.get_shape())
<add> axis = normalize_axis(axis, ndim(x))
<ide> x = tf.cast(x, tf.bool)
<ide> x = tf.reduce_any(x, reduction_indices=axis, keep_dims=keepdims)
<ide> return tf.cast(x, tf.int8) | 1 |
PHP | PHP | fix method separation | ae6f1b0b7b616315ff99b25a790b991509d9b2ed | <ide><path>tests/Routing/RoutingRouteTest.php
<ide> public function testModelBindingWithCustomNullReturn()
<ide> $this->assertEquals('missing', $router->dispatch(Request::create('foo/taylor', 'GET'))->getContent());
<ide> }
<ide>
<add>
<ide> public function testModelBindingWithBindingClosure()
<ide> {
<ide> $router = $this->getRouter(); | 1 |
Text | Text | add note about autocrlf required for tests | 3654cd4cdaf2ab84d0e6a190c3b9e89e86726a88 | <ide><path>test/README.md
<ide> directory, see [the guide on writing tests](../doc/guides/writing-tests.md).
<ide> On how to run tests in this directory, see
<ide> [the contributing guide](../doc/guides/contributing/pull-requests.md#step-6-test).
<ide>
<add>For the tests to successfully run on Windows, Node.js has to be checked out from
<add>GitHub with the `autocrlf` git config flag set to true.
<add>
<ide> ## Test Directories
<ide>
<ide> |Directory |Runs on CI |Purpose | | 1 |
Text | Text | improve redundant variable name | fa94f836979516abea5743c0be2715c14c5ebb47 | <ide><path>website/docs/usage/rule-based-matching.md
<ide> from spacy.matcher import PhraseMatcher
<ide>
<ide> nlp = spacy.load('en_core_web_sm')
<ide> matcher = PhraseMatcher(nlp.vocab)
<del>terminology_list = [u"Barack Obama", u"Angela Merkel", u"Washington, D.C."]
<add>terms = [u"Barack Obama", u"Angela Merkel", u"Washington, D.C."]
<ide> # Only run nlp.make_doc to speed things up
<del>patterns = [nlp.make_doc(text) for text in terminology_list]
<add>patterns = [nlp.make_doc(text) for text in terms]
<ide> matcher.add("TerminologyList", None, *patterns)
<ide>
<ide> doc = nlp(u"German Chancellor Angela Merkel and US President Barack Obama " | 1 |
Python | Python | fix example test and test_fetcher for examples | b62ac4d240fb4d6d1b4040faf0ec168577b9f093 | <ide><path>examples/pytorch/text-classification/run_glue.py
<ide> def compute_metrics(p: EvalPrediction):
<ide>
<ide> if task == "mnli-mm":
<ide> metrics = {k + "_mm": v for k, v in metrics.items()}
<del> if "mnli" in task:
<add> if task is not None and "mnli" in task:
<ide> combined.update(metrics)
<ide>
<ide> trainer.log_metrics("eval", metrics)
<del> trainer.save_metrics("eval", combined if "mnli" in task else metrics)
<add> trainer.save_metrics("eval", combined if task is not None and "mnli" in task else metrics)
<ide>
<ide> if training_args.do_predict:
<ide> logger.info("*** Predict ***")
<ide><path>utils/tests_fetcher.py
<ide> def infer_tests_to_run(output_file, diff_with_last_commit=False, filters=None):
<ide> test_files_to_run.append(f)
<ide> # Example files are tested separately
<ide> elif f.startswith("examples/pytorch"):
<del> test_files_to_run.append("examples/pytorch/test_examples.py")
<add> test_files_to_run.append("examples/pytorch/test_pytorch_examples.py")
<ide> elif f.startswith("examples/flax"):
<del> test_files_to_run.append("examples/flax/test_examples.py")
<add> test_files_to_run.append("examples/flax/test_flax_examples.py")
<ide> else:
<ide> new_tests = module_to_test_file(f)
<ide> if new_tests is not None: | 2 |
Javascript | Javascript | replace var with let/const | ee81bce9091684129416205acd67c07b7a08d3ac | <ide><path>lib/timers.js
<ide> function setTimeout(callback, after, arg1, arg2, arg3) {
<ide> throw new ERR_INVALID_CALLBACK(callback);
<ide> }
<ide>
<del> var i, args;
<add> let i, args;
<ide> switch (arguments.length) {
<ide> // fast cases
<ide> case 1:
<ide> function setInterval(callback, repeat, arg1, arg2, arg3) {
<ide> throw new ERR_INVALID_CALLBACK(callback);
<ide> }
<ide>
<del> var i, args;
<add> let i, args;
<ide> switch (arguments.length) {
<ide> // fast cases
<ide> case 1:
<ide> function setImmediate(callback, arg1, arg2, arg3) {
<ide> throw new ERR_INVALID_CALLBACK(callback);
<ide> }
<ide>
<del> var i, args;
<add> let i, args;
<ide> switch (arguments.length) {
<ide> // fast cases
<ide> case 1: | 1 |
Python | Python | fix broken func directives in docstrings | 2fab8a31ae2639b3eacdd3935d58203b09650f29 | <ide><path>src/flask/json/__init__.py
<ide> def dumps(obj, app=None, **kwargs):
<ide> :param obj: Object to serialize to JSON.
<ide> :param app: Use this app's config instead of the active app context
<ide> or defaults.
<del> :param kwargs: Extra arguments passed to func:`json.dumps`.
<add> :param kwargs: Extra arguments passed to :func:`json.dumps`.
<ide>
<ide> .. versionchanged:: 2.0
<ide> ``encoding`` is deprecated and will be removed in 2.1.
<ide> def dump(obj, fp, app=None, **kwargs):
<ide> :param fp: File object to write JSON to.
<ide> :param app: Use this app's config instead of the active app context
<ide> or defaults.
<del> :param kwargs: Extra arguments passed to func:`json.dump`.
<add> :param kwargs: Extra arguments passed to :func:`json.dump`.
<ide>
<ide> .. versionchanged:: 2.0
<ide> Writing to a binary file, and the ``encoding`` argument, is
<ide> def load(fp, app=None, **kwargs):
<ide> :param fp: File object to read JSON from.
<ide> :param app: Use this app's config instead of the active app context
<ide> or defaults.
<del> :param kwargs: Extra arguments passed to func:`json.load`.
<add> :param kwargs: Extra arguments passed to :func:`json.load`.
<ide>
<ide> .. versionchanged:: 2.0
<ide> ``encoding`` is deprecated and will be removed in 2.1. The file | 1 |
Javascript | Javascript | add cut, copy, paste | 5388d70bb12cb93885f23d695f476cc2e1971b18 | <ide><path>src/core/ReactEventEmitter.js
<ide> var ReactEventEmitter = merge(ReactEventEmitterMixin, {
<ide> trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt);
<ide> trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt);
<ide> }
<add>
<add> if (isEventSupported('copy')) {
<add> trapBubbledEvent(topLevelTypes.topCopy, 'copy', mountAt);
<add> trapBubbledEvent(topLevelTypes.topCut, 'cut', mountAt);
<add> trapBubbledEvent(topLevelTypes.topPaste, 'paste', mountAt);
<add> }
<ide> },
<ide>
<ide> registrationNames: EventPluginHub.registrationNames,
<ide><path>src/event/EventConstants.js
<ide> var topLevelTypes = keyMirror({
<ide> topBlur: null,
<ide> topChange: null,
<ide> topClick: null,
<add> topCopy: null,
<add> topCut: null,
<ide> topDOMCharacterDataModified: null,
<ide> topDoubleClick: null,
<ide> topDrag: null,
<ide> var topLevelTypes = keyMirror({
<ide> topMouseOut: null,
<ide> topMouseOver: null,
<ide> topMouseUp: null,
<add> topPaste: null,
<ide> topScroll: null,
<ide> topSelectionChange: null,
<ide> topSubmit: null,
<ide><path>src/event/synthetic/SyntheticClipboardEvent.js
<add>/**
<add> * Copyright 2013 Facebook, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> *
<add> * @providesModule SyntheticClipboardEvent
<add> * @typechecks static-only
<add> */
<add>
<add>"use strict";
<add>
<add>var SyntheticEvent = require('SyntheticEvent');
<add>
<add>/**
<add> * @interface Event
<add> * @see http://www.w3.org/TR/clipboard-apis/
<add> */
<add>var ClipboardEventInterface = {
<add> clipboardData: null
<add>};
<add>
<add>/**
<add> * @param {object} dispatchConfig Configuration used to dispatch this event.
<add> * @param {string} dispatchMarker Marker identifying the event target.
<add> * @param {object} nativeEvent Native browser event.
<add> * @extends {SyntheticUIEvent}
<add> */
<add>function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent) {
<add> SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
<add>}
<add>
<add>SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface);
<add>
<add>module.exports = SyntheticClipboardEvent;
<add>
<ide><path>src/eventPlugins/SimpleEventPlugin.js
<ide>
<ide> var EventConstants = require('EventConstants');
<ide> var EventPropagators = require('EventPropagators');
<add>var SyntheticClipboardEvent = require('SyntheticClipboardEvent');
<ide> var SyntheticEvent = require('SyntheticEvent');
<ide> var SyntheticFocusEvent = require('SyntheticFocusEvent');
<ide> var SyntheticKeyboardEvent = require('SyntheticKeyboardEvent');
<ide> var eventTypes = {
<ide> captured: keyOf({onClickCapture: true})
<ide> }
<ide> },
<add> copy: {
<add> phasedRegistrationNames: {
<add> bubbled: keyOf({onCopy: true}),
<add> captured: keyOf({onCopyCapture: true})
<add> }
<add> },
<add> cut: {
<add> phasedRegistrationNames: {
<add> bubbled: keyOf({onCut: true}),
<add> captured: keyOf({onCutCapture: true})
<add> }
<add> },
<ide> doubleClick: {
<ide> phasedRegistrationNames: {
<ide> bubbled: keyOf({onDoubleClick: true}),
<ide> var eventTypes = {
<ide> captured: keyOf({onMouseUpCapture: true})
<ide> }
<ide> },
<add> paste: {
<add> phasedRegistrationNames: {
<add> bubbled: keyOf({onPaste: true}),
<add> captured: keyOf({onPasteCapture: true})
<add> }
<add> },
<ide> scroll: {
<ide> phasedRegistrationNames: {
<ide> bubbled: keyOf({onScroll: true}),
<ide> var eventTypes = {
<ide> var topLevelEventsToDispatchConfig = {
<ide> topBlur: eventTypes.blur,
<ide> topClick: eventTypes.click,
<add> topCopy: eventTypes.copy,
<add> topCut: eventTypes.cut,
<ide> topDoubleClick: eventTypes.doubleClick,
<ide> topDOMCharacterDataModified: eventTypes.DOMCharacterDataModified,
<ide> topDrag: eventTypes.drag,
<ide> var topLevelEventsToDispatchConfig = {
<ide> topMouseDown: eventTypes.mouseDown,
<ide> topMouseMove: eventTypes.mouseMove,
<ide> topMouseUp: eventTypes.mouseUp,
<add> topPaste: eventTypes.paste,
<ide> topScroll: eventTypes.scroll,
<ide> topSubmit: eventTypes.submit,
<ide> topTouchCancel: eventTypes.touchCancel,
<ide> var SimpleEventPlugin = {
<ide> case topLevelTypes.topWheel:
<ide> EventConstructor = SyntheticWheelEvent;
<ide> break;
<add> case topLevelTypes.topCopy:
<add> case topLevelTypes.topCut:
<add> case topLevelTypes.topPaste:
<add> EventConstructor = SyntheticClipboardEvent;
<add> break;
<ide> }
<ide> invariant(
<ide> EventConstructor, | 4 |
Javascript | Javascript | fix the order of the element test arguments | 97cbd76695a69a973760560689d90d98e550ad7b | <ide><path>test/unit/selector.js
<ide> test("element", function() {
<ide> ok( jQuery("#lengthtest input").length, '<input name="length"> cannot be found under IE, see #945' );
<ide>
<ide> // Check for unique-ness and sort order
<del> same( jQuery("*").get(), jQuery("*, *").get(), "Check for duplicates: *, *" );
<del> same( jQuery("p").get(), jQuery("p, div p").get(), "Check for duplicates: p, div p" );
<add> same( jQuery("*, *").get(), jQuery("*").get(), "Check for duplicates: *, *" );
<add> same( jQuery("p, div p").get(), jQuery("p").get(), "Check for duplicates: p, div p" );
<ide>
<ide> t( "Checking sort order", "h2, h1", ["qunit-header", "qunit-banner", "qunit-userAgent"] );
<ide> t( "Checking sort order", "h2:first, h1:first", ["qunit-header", "qunit-banner"] ); | 1 |
Go | Go | fix race in testlogssince | 2fe2f7a1864068e7d268833bb40536064f69b8aa | <ide><path>integration-cli/docker_cli_logs_test.go
<ide> func (s *DockerSuite) TestLogsFollowStopped(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestLogsSince(c *check.C) {
<ide> name := "testlogssince"
<del> runCmd := exec.Command(dockerBinary, "run", "--name="+name, "busybox", "/bin/sh", "-c", `date +%s; for i in $(seq 1 5); do sleep 1; echo log$i; done`)
<add> runCmd := exec.Command(dockerBinary, "run", "--name="+name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do sleep 2; echo `date +%s` log$i; done")
<ide> out, _, err := runCommandWithOutput(runCmd)
<ide> if err != nil {
<ide> c.Fatalf("run failed with errors: %s, %v", out, err)
<ide> }
<ide>
<del> outLines := strings.Split(out, "\n")
<del> startUnix, _ := strconv.ParseInt(outLines[0], 10, 64)
<del> since := startUnix + 3
<add> log2Line := strings.Split(strings.Split(out, "\n")[1], " ")
<add> t, err := strconv.ParseInt(log2Line[0], 10, 64) // the timestamp log2 is writen
<add> c.Assert(err, check.IsNil)
<add> since := t + 1 // add 1s so log1 & log2 doesn't show up
<ide> logsCmd := exec.Command(dockerBinary, "logs", "-t", fmt.Sprintf("--since=%v", since), name)
<ide>
<ide> out, _, err = runCommandWithOutput(logsCmd)
<ide> func (s *DockerSuite) TestLogsSince(c *check.C) {
<ide> }
<ide>
<ide> // Test with default value specified and parameter omitted
<del> expected := []string{"log1", "log2", "log3", "log4", "log5"}
<add> expected := []string{"log1", "log2", "log3"}
<ide> for _, cmd := range []*exec.Cmd{
<ide> exec.Command(dockerBinary, "logs", "-t", name),
<ide> exec.Command(dockerBinary, "logs", "-t", "--since=0", name), | 1 |
Javascript | Javascript | eliminate all overhead for hidden calls | 656ce920a33272dbf24c5a5beccf57f637e7e832 | <ide><path>benchmark/misc/hidestackframes.js
<add>'use strict';
<add>
<add>const common = require('../common.js');
<add>
<add>const bench = common.createBenchmark(main, {
<add> type: ['hide-stackframes-throw', 'direct-call-throw',
<add> 'hide-stackframes-noerr', 'direct-call-noerr'],
<add> n: [10e4]
<add>}, {
<add> flags: ['--expose-internals']
<add>});
<add>
<add>function main({ n, type }) {
<add> const {
<add> hideStackFrames,
<add> codes: {
<add> ERR_INVALID_ARG_TYPE,
<add> },
<add> } = require('internal/errors');
<add>
<add> const testfn = (value) => {
<add> if (typeof value !== 'number') {
<add> throw new ERR_INVALID_ARG_TYPE('Benchmark', 'number', value);
<add> }
<add> };
<add>
<add> let fn = testfn;
<add> if (type.startsWith('hide-stackframe'))
<add> fn = hideStackFrames(testfn);
<add> let value = 42;
<add> if (type.endsWith('-throw'))
<add> value = 'err';
<add>
<add> bench.start();
<add>
<add> for (let i = 0; i < n; i++) {
<add> try {
<add> fn(value);
<add> } catch {
<add> // No-op
<add> }
<add> }
<add>
<add> bench.end(n);
<add>}
<ide><path>lib/internal/errors.js
<ide> const kTypes = [
<ide> const MainContextError = Error;
<ide> const overrideStackTrace = new SafeWeakMap();
<ide> const kNoOverride = Symbol('kNoOverride');
<add>let userStackTraceLimit;
<add>const nodeInternalPrefix = '__node_internal_';
<ide> const prepareStackTrace = (globalThis, error, trace) => {
<ide> // API for node internals to override error stack formatting
<ide> // without interfering with userland code.
<ide> const prepareStackTrace = (globalThis, error, trace) => {
<ide> return f(error, trace);
<ide> }
<ide>
<add> const firstFrame = trace[0]?.getFunctionName();
<add> if (firstFrame && StringPrototypeStartsWith(firstFrame, nodeInternalPrefix)) {
<add> for (let l = trace.length - 1; l >= 0; l--) {
<add> const fn = trace[l]?.getFunctionName();
<add> if (fn && StringPrototypeStartsWith(fn, nodeInternalPrefix)) {
<add> ArrayPrototypeSplice(trace, 0, l + 1);
<add> break;
<add> }
<add> }
<add> // `userStackTraceLimit` is the user value for `Error.stackTraceLimit`,
<add> // it is updated at every new exception in `captureLargerStackTrace`.
<add> if (trace.length > userStackTraceLimit)
<add> ArrayPrototypeSplice(trace, userStackTraceLimit);
<add> }
<add>
<ide> const globalOverride =
<ide> maybeOverridePrepareStackTrace(globalThis, error, trace);
<ide> if (globalOverride !== kNoOverride) return globalOverride;
<ide> const maybeOverridePrepareStackTrace = (globalThis, error, trace) => {
<ide> return kNoOverride;
<ide> };
<ide>
<del>let excludedStackFn;
<del>
<ide> // Lazily loaded
<ide> let util;
<ide> let assert;
<ide> function lazyBuffer() {
<ide> return buffer;
<ide> }
<ide>
<add>const addCodeToName = hideStackFrames(function addCodeToName(err, name, code) {
<add> // Set the stack
<add> err = captureLargerStackTrace(err);
<add> // Add the error code to the name to include it in the stack trace.
<add> err.name = `${name} [${code}]`;
<add> // Access the stack to generate the error message including the error code
<add> // from the name.
<add> err.stack; // eslint-disable-line no-unused-expressions
<add> // Reset the name to the actual name.
<add> if (name === 'SystemError') {
<add> ObjectDefineProperty(err, 'name', {
<add> value: name,
<add> enumerable: false,
<add> writable: true,
<add> configurable: true
<add> });
<add> } else {
<add> delete err.name;
<add> }
<add>});
<add>
<ide> // A specialized Error that includes an additional info property with
<ide> // additional information about the error condition.
<ide> // It has the properties present in a UVException but with a custom error
<ide> function lazyBuffer() {
<ide> // and may have .path and .dest.
<ide> class SystemError extends Error {
<ide> constructor(key, context) {
<del> if (excludedStackFn === undefined) {
<del> super();
<del> } else {
<del> const limit = Error.stackTraceLimit;
<del> Error.stackTraceLimit = 0;
<del> super();
<del> // Reset the limit and setting the name property.
<del> Error.stackTraceLimit = limit;
<del> }
<add> const limit = Error.stackTraceLimit;
<add> Error.stackTraceLimit = 0;
<add> super();
<add> // Reset the limit and setting the name property.
<add> Error.stackTraceLimit = limit;
<ide> const prefix = getMessage(key, [], this);
<ide> let message = `${prefix}: ${context.syscall} returned ` +
<ide> `${context.code} (${context.message})`;
<ide> function makeSystemErrorWithCode(key) {
<ide>
<ide> function makeNodeErrorWithCode(Base, key) {
<ide> return function NodeError(...args) {
<del> let error;
<del> if (excludedStackFn === undefined) {
<del> error = new Base();
<del> } else {
<del> const limit = Error.stackTraceLimit;
<del> Error.stackTraceLimit = 0;
<del> error = new Base();
<del> // Reset the limit and setting the name property.
<del> Error.stackTraceLimit = limit;
<del> }
<add> const limit = Error.stackTraceLimit;
<add> Error.stackTraceLimit = 0;
<add> const error = new Base();
<add> // Reset the limit and setting the name property.
<add> Error.stackTraceLimit = limit;
<ide> const message = getMessage(key, args, error);
<ide> ObjectDefineProperty(error, 'message', {
<ide> value: message,
<ide> function makeNodeErrorWithCode(Base, key) {
<ide>
<ide> // This function removes unnecessary frames from Node.js core errors.
<ide> function hideStackFrames(fn) {
<del> return function hidden(...args) {
<del> // Make sure the most outer `hideStackFrames()` function is used.
<del> let setStackFn = false;
<del> if (excludedStackFn === undefined) {
<del> excludedStackFn = hidden;
<del> setStackFn = true;
<del> }
<del> try {
<del> return fn(...args);
<del> } finally {
<del> if (setStackFn === true) {
<del> excludedStackFn = undefined;
<del> }
<del> }
<del> };
<del>}
<del>
<del>function addCodeToName(err, name, code) {
<del> // Set the stack
<del> if (excludedStackFn !== undefined) {
<del> ErrorCaptureStackTrace(err, excludedStackFn);
<del> }
<del> // Add the error code to the name to include it in the stack trace.
<del> err.name = `${name} [${code}]`;
<del> // Access the stack to generate the error message including the error code
<del> // from the name.
<del> err.stack; // eslint-disable-line no-unused-expressions
<del> // Reset the name to the actual name.
<del> if (name === 'SystemError') {
<del> ObjectDefineProperty(err, 'name', {
<del> value: name,
<del> enumerable: false,
<del> writable: true,
<del> configurable: true
<del> });
<del> } else {
<del> delete err.name;
<del> }
<add> // We rename the functions that will be hidden to cut off the stacktrace
<add> // at the outermost one
<add> const hidden = nodeInternalPrefix + fn.name;
<add> ObjectDefineProperty(fn, 'name', { value: hidden });
<add> return fn;
<ide> }
<ide>
<ide> // Utility function for registering the error codes. Only used here. Exported
<ide> function uvErrmapGet(name) {
<ide> return uvBinding.errmap.get(name);
<ide> }
<ide>
<add>const captureLargerStackTrace = hideStackFrames(
<add> function captureLargerStackTrace(err) {
<add> userStackTraceLimit = Error.stackTraceLimit;
<add> Error.stackTraceLimit = Infinity;
<add> ErrorCaptureStackTrace(err);
<add> // Reset the limit
<add> Error.stackTraceLimit = userStackTraceLimit;
<add>
<add> return err;
<add> });
<ide>
<ide> /**
<ide> * This creates an error compatible with errors produced in the C++
<ide> function uvErrmapGet(name) {
<ide> * @param {Object} ctx
<ide> * @returns {Error}
<ide> */
<del>function uvException(ctx) {
<del> const [ code, uvmsg ] = uvErrmapGet(ctx.errno) || uvUnmappedError;
<add>const uvException = hideStackFrames(function uvException(ctx) {
<add> const [code, uvmsg] = uvErrmapGet(ctx.errno) || uvUnmappedError;
<ide> let message = `${code}: ${ctx.message || uvmsg}, ${ctx.syscall}`;
<ide>
<ide> let path;
<ide> function uvException(ctx) {
<ide> if (dest) {
<ide> err.dest = dest;
<ide> }
<del> ErrorCaptureStackTrace(err, excludedStackFn || uvException);
<del> return err;
<del>}
<add>
<add> return captureLargerStackTrace(err);
<add>});
<ide>
<ide> /**
<ide> * This creates an error compatible with errors produced in the C++
<ide> function uvException(ctx) {
<ide> * @param {number} [port]
<ide> * @returns {Error}
<ide> */
<del>function uvExceptionWithHostPort(err, syscall, address, port) {
<del> const [ code, uvmsg ] = uvErrmapGet(err) || uvUnmappedError;
<del> const message = `${syscall} ${code}: ${uvmsg}`;
<del> let details = '';
<del>
<del> if (port && port > 0) {
<del> details = ` ${address}:${port}`;
<del> } else if (address) {
<del> details = ` ${address}`;
<del> }
<add>const uvExceptionWithHostPort = hideStackFrames(
<add> function uvExceptionWithHostPort(err, syscall, address, port) {
<add> const [code, uvmsg] = uvErrmapGet(err) || uvUnmappedError;
<add> const message = `${syscall} ${code}: ${uvmsg}`;
<add> let details = '';
<add>
<add> if (port && port > 0) {
<add> details = ` ${address}:${port}`;
<add> } else if (address) {
<add> details = ` ${address}`;
<add> }
<ide>
<del> // Reducing the limit improves the performance significantly. We do not lose
<del> // the stack frames due to the `captureStackTrace()` function that is called
<del> // later.
<del> const tmpLimit = Error.stackTraceLimit;
<del> Error.stackTraceLimit = 0;
<del> // eslint-disable-next-line no-restricted-syntax
<del> const ex = new Error(`${message}${details}`);
<del> Error.stackTraceLimit = tmpLimit;
<del> ex.code = code;
<del> ex.errno = err;
<del> ex.syscall = syscall;
<del> ex.address = address;
<del> if (port) {
<del> ex.port = port;
<del> }
<del> ErrorCaptureStackTrace(ex, excludedStackFn || uvExceptionWithHostPort);
<del> return ex;
<del>}
<add> // Reducing the limit improves the performance significantly. We do not
<add> // lose the stack frames due to the `captureStackTrace()` function that
<add> // is called later.
<add> const tmpLimit = Error.stackTraceLimit;
<add> Error.stackTraceLimit = 0;
<add> // eslint-disable-next-line no-restricted-syntax
<add> const ex = new Error(`${message}${details}`);
<add> Error.stackTraceLimit = tmpLimit;
<add> ex.code = code;
<add> ex.errno = err;
<add> ex.syscall = syscall;
<add> ex.address = address;
<add> if (port) {
<add> ex.port = port;
<add> }
<add>
<add> return captureLargerStackTrace(ex);
<add> });
<ide>
<ide> /**
<ide> * This used to be util._errnoException().
<ide> function uvExceptionWithHostPort(err, syscall, address, port) {
<ide> * @param {string} [original]
<ide> * @returns {Error}
<ide> */
<del>function errnoException(err, syscall, original) {
<del> // TODO(joyeecheung): We have to use the type-checked
<del> // getSystemErrorName(err) to guard against invalid arguments from users.
<del> // This can be replaced with [ code ] = errmap.get(err) when this method
<del> // is no longer exposed to user land.
<del> if (util === undefined) util = require('util');
<del> const code = util.getSystemErrorName(err);
<del> const message = original ?
<del> `${syscall} ${code} ${original}` : `${syscall} ${code}`;
<del>
<del> // eslint-disable-next-line no-restricted-syntax
<del> const ex = new Error(message);
<del> ex.errno = err;
<del> ex.code = code;
<del> ex.syscall = syscall;
<del> ErrorCaptureStackTrace(ex, excludedStackFn || errnoException);
<del> return ex;
<del>}
<add>const errnoException = hideStackFrames(
<add> function errnoException(err, syscall, original) {
<add> // TODO(joyeecheung): We have to use the type-checked
<add> // getSystemErrorName(err) to guard against invalid arguments from users.
<add> // This can be replaced with [ code ] = errmap.get(err) when this method
<add> // is no longer exposed to user land.
<add> if (util === undefined) util = require('util');
<add> const code = util.getSystemErrorName(err);
<add> const message = original ?
<add> `${syscall} ${code} ${original}` : `${syscall} ${code}`;
<add>
<add> const tmpLimit = Error.stackTraceLimit;
<add> Error.stackTraceLimit = 0;
<add> // eslint-disable-next-line no-restricted-syntax
<add> const ex = new Error(message);
<add> Error.stackTraceLimit = tmpLimit;
<add> ex.errno = err;
<add> ex.code = code;
<add> ex.syscall = syscall;
<add>
<add> return captureLargerStackTrace(ex);
<add> });
<ide>
<ide> /**
<ide> * Deprecated, new function is `uvExceptionWithHostPort()`
<ide> function errnoException(err, syscall, original) {
<ide> * @param {string} [additional]
<ide> * @returns {Error}
<ide> */
<del>function exceptionWithHostPort(err, syscall, address, port, additional) {
<del> // TODO(joyeecheung): We have to use the type-checked
<del> // getSystemErrorName(err) to guard against invalid arguments from users.
<del> // This can be replaced with [ code ] = errmap.get(err) when this method
<del> // is no longer exposed to user land.
<del> if (util === undefined) util = require('util');
<del> const code = util.getSystemErrorName(err);
<del> let details = '';
<del> if (port && port > 0) {
<del> details = ` ${address}:${port}`;
<del> } else if (address) {
<del> details = ` ${address}`;
<del> }
<del> if (additional) {
<del> details += ` - Local (${additional})`;
<del> }
<add>const exceptionWithHostPort = hideStackFrames(
<add> function exceptionWithHostPort(err, syscall, address, port, additional) {
<add> // TODO(joyeecheung): We have to use the type-checked
<add> // getSystemErrorName(err) to guard against invalid arguments from users.
<add> // This can be replaced with [ code ] = errmap.get(err) when this method
<add> // is no longer exposed to user land.
<add> if (util === undefined) util = require('util');
<add> const code = util.getSystemErrorName(err);
<add> let details = '';
<add> if (port && port > 0) {
<add> details = ` ${address}:${port}`;
<add> } else if (address) {
<add> details = ` ${address}`;
<add> }
<add> if (additional) {
<add> details += ` - Local (${additional})`;
<add> }
<ide>
<del> // Reducing the limit improves the performance significantly. We do not lose
<del> // the stack frames due to the `captureStackTrace()` function that is called
<del> // later.
<del> const tmpLimit = Error.stackTraceLimit;
<del> Error.stackTraceLimit = 0;
<del> // eslint-disable-next-line no-restricted-syntax
<del> const ex = new Error(`${syscall} ${code}${details}`);
<del> Error.stackTraceLimit = tmpLimit;
<del> ex.errno = err;
<del> ex.code = code;
<del> ex.syscall = syscall;
<del> ex.address = address;
<del> if (port) {
<del> ex.port = port;
<del> }
<del> ErrorCaptureStackTrace(ex, excludedStackFn || exceptionWithHostPort);
<del> return ex;
<del>}
<add> // Reducing the limit improves the performance significantly. We do not
<add> // lose the stack frames due to the `captureStackTrace()` function that
<add> // is called later.
<add> const tmpLimit = Error.stackTraceLimit;
<add> Error.stackTraceLimit = 0;
<add> // eslint-disable-next-line no-restricted-syntax
<add> const ex = new Error(`${syscall} ${code}${details}`);
<add> Error.stackTraceLimit = tmpLimit;
<add> ex.errno = err;
<add> ex.code = code;
<add> ex.syscall = syscall;
<add> ex.address = address;
<add> if (port) {
<add> ex.port = port;
<add> }
<add>
<add> return captureLargerStackTrace(ex);
<add> });
<ide>
<ide> /**
<ide> * @param {number|string} code - A libuv error number or a c-ares error code
<ide> * @param {string} syscall
<ide> * @param {string} [hostname]
<ide> * @returns {Error}
<ide> */
<del>function dnsException(code, syscall, hostname) {
<add>const dnsException = hideStackFrames(function(code, syscall, hostname) {
<ide> let errno;
<ide> // If `code` is of type number, it is a libuv error number, else it is a
<ide> // c-ares error code.
<ide> function dnsException(code, syscall, hostname) {
<ide> if (hostname) {
<ide> ex.hostname = hostname;
<ide> }
<del> ErrorCaptureStackTrace(ex, excludedStackFn || dnsException);
<del> return ex;
<del>}
<add>
<add> return captureLargerStackTrace(ex);
<add>});
<ide>
<ide> function connResetException(msg) {
<ide> // eslint-disable-next-line no-restricted-syntax
<ide><path>lib/internal/fs/promises.js
<ide> async function writeFileHandle(filehandle, data, signal) {
<ide> if (remaining === 0) return;
<ide> do {
<ide> if (signal?.aborted) {
<del> throw new lazyDOMException('The operation was aborted', 'AbortError');
<add> throw lazyDOMException('The operation was aborted', 'AbortError');
<ide> }
<ide> const { bytesWritten } =
<ide> await write(filehandle, data, 0,
<ide> async function writeFile(path, data, options) {
<ide>
<ide> const fd = await open(path, flag, options.mode);
<ide> if (options.signal?.aborted) {
<del> throw new lazyDOMException('The operation was aborted', 'AbortError');
<add> throw lazyDOMException('The operation was aborted', 'AbortError');
<ide> }
<ide> return PromisePrototypeFinally(writeFileHandle(fd, data), fd.close);
<ide> } | 3 |
PHP | PHP | simplify method and remove param weirdness | 95325a6599cda02f84ba8efa38b3e6deb2d1363f | <ide><path>src/View/Helper/FormHelper.php
<ide> public function label($fieldName, $text = null, $options = array()) {
<ide> }
<ide>
<ide> /**
<del> * Generate a set of inputs for `$fields`. If $fields is null the fields of current model
<add> * Generate a set of inputs for `$fields`. If $fields is empty the fields of current model
<ide> * will be used.
<ide> *
<ide> * You can customize individual inputs through `$fields`.
<ide> public function label($fieldName, $text = null, $options = array()) {
<ide> * You can exclude fields using the `$blacklist` parameter:
<ide> *
<ide> * {{{
<del> * $this->Form->inputs(null, ['title']);
<add> * $this->Form->inputs([], ['title']);
<ide> * }}}
<ide> *
<ide> * In the above example, no field would be generated for the title field.
<ide> *
<del> * In addition to controller fields output, `$fields` can be used to control legend
<del> * and fieldset rendering.
<del> * `$this->Form->inputs('My legend');` Would generate an input set with a custom legend.
<del> *
<del> * @param mixed $fields An array of customizations for the fields that will be
<add> * @param array $fields An array of customizations for the fields that will be
<ide> * generated. This array allows you to set custom types, labels, or other options.
<ide> * @param array $blacklist A list of fields to not create inputs for.
<ide> * @param array $options Options array. Valid keys are:
<ide> public function label($fieldName, $text = null, $options = array()) {
<ide> * @return string Completed form inputs.
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::inputs
<ide> */
<del> public function inputs($fields = null, array $blacklist = [], array $options = []) {
<add> public function inputs(array $fields = [], array $blacklist = [], array $options = []) {
<ide> $fieldset = $legend = true;
<ide> $context = $this->_getContext();
<ide>
<ide> $modelFields = $context->fieldNames();
<ide>
<del> if (is_string($fields)) {
<del> $legend = $fields;
<del> $fields = [];
<del> } elseif (is_bool($fields)) {
<del> $fieldset = $legend = $fields;
<del> $fields = [];
<del> }
<del>
<ide> $fields = array_merge(
<ide> Hash::normalize($modelFields),
<ide> Hash::normalize((array)$fields)
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testInputMagicSelectChangeToRadio() {
<ide> */
<ide> public function testFormInputsLegendFieldset() {
<ide> $this->Form->create($this->article);
<del> $result = $this->Form->inputs('The Legend');
<add> $result = $this->Form->inputs([], [], array('legend' => 'The Legend'));
<ide> $expected = array(
<ide> '<fieldset',
<ide> '<legend',
<ide> public function testFormInputsLegendFieldset() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $result = $this->Form->inputs(null, array(), array('legend' => 'Field of Dreams', 'fieldset' => true));
<add> $result = $this->Form->inputs([], [], array('fieldset' => true, 'legend' => 'Field of Dreams'));
<ide> $this->assertContains('<legend>Field of Dreams</legend>', $result);
<ide> $this->assertContains('<fieldset>', $result);
<ide>
<del> $result = $this->Form->inputs('Field of Dreams', array(), array('fieldset' => true));
<del> $this->assertContains('<legend>Field of Dreams</legend>', $result);
<del> $this->assertContains('<fieldset>', $result);
<del>
<del> $result = $this->Form->inputs(null, array(), array('fieldset' => false, 'legend' => false));
<add> $result = $this->Form->inputs([], [], array('fieldset' => false, 'legend' => false));
<ide> $this->assertNotContains('<legend>', $result);
<ide> $this->assertNotContains('<fieldset>', $result);
<ide>
<del> $result = $this->Form->inputs(null, array(), array('fieldset' => false, 'legend' => 'Hello'));
<add> $result = $this->Form->inputs([], [], array('fieldset' => false, 'legend' => 'Hello'));
<ide> $this->assertNotContains('<legend>', $result);
<ide> $this->assertNotContains('<fieldset>', $result);
<ide>
<ide> public function testFormInputs() {
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $this->Form->create($this->article);
<del> $result = $this->Form->inputs('Hello');
<add> $result = $this->Form->inputs([], [], ['legend' => 'Hello']);
<ide> $expected = array(
<ide> 'fieldset' => array(),
<ide> 'legend' => array(), | 2 |
Python | Python | decorelate dependencies + fix bug | 98f5c7864f9796dc5baf44cf6973dbb3e6836261 | <ide><path>hubconf.py
<del>dependencies = ['torch', 'tqdm', 'boto3', 'requests', 'regex', 'ftfy', 'spacy']
<add>dependencies = ['torch', 'tqdm', 'boto3', 'requests', 'regex']
<ide>
<ide> from hubconfs.bert_hubconf import (
<ide> bertTokenizer,
<ide><path>hubconfs/gpt_hubconf.py
<ide> OpenAIGPTDoubleHeadsModel
<ide> )
<ide>
<add># Dependecies that are not specified in global hubconf.py
<add>specific_dependencies = ['spacy', 'ftfy']
<add>
<ide> # A lot of models share the same param doc. Use a decorator
<ide> # to save typing
<ide> gpt_docstring = """
<ide> def openAIGPTTokenizer(*args, **kwargs):
<ide> Instantiate a BPE tokenizer for OpenAI GPT from a pre-trained/customized vocab file.
<ide> Peculiarities:
<ide> - lower case all inputs
<del> - uses SpaCy tokenizer and ftfy for pre-BPE tokenization if they are installed, fallback to BERT's BasicTokenizer if not.
<add> - uses SpaCy tokenizer ('en' model) and ftfy for pre-BPE tokenization if they are installed, fallback to BERT's BasicTokenizer if not.
<ide> - argument special_tokens and function set_special_tokens:
<ide> can be used to add additional symbols (ex: "__classify__") to a vocabulary.
<ide>
<ide> def openAIGPTTokenizer(*args, **kwargs):
<ide> >>> text = "Who was Jim Henson ? Jim Henson was a puppeteer"
<ide> >>> tokenized_text = tokenizer.tokenize(text)
<ide> >>> indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)
<add> [763, 509, 4265, 2298, 945, 257, 4265, 2298, 945, 509, 246, 10148, 39041, 483]
<ide> """
<ide> tokenizer = OpenAIGPTTokenizer.from_pretrained(*args, **kwargs)
<ide> return tokenizer
<ide> def openAIGPTLMHeadModel(*args, **kwargs):
<ide> >>> predicted_index = torch.argmax(predictions[0, -1, :]).item()
<ide> >>> predicted_token = tokenizer.convert_ids_to_tokens([predicted_index])[0]
<ide> """
<del> model = OpenAIGPTDoubleHeadsModel.from_pretrained(*args, **kwargs)
<add> model = OpenAIGPTLMHeadModel.from_pretrained(*args, **kwargs)
<ide> return model
<ide>
<ide> | 2 |
Ruby | Ruby | remove bottle blocks | 8f96ba3c1ebe789cbffab207e058ec21001cb4ca | <ide><path>Library/Homebrew/dev-cmd/extract.rb
<ide> module Homebrew
<ide>
<ide> module_function
<ide>
<add> BOTTLE_BLOCK_REGEX = / bottle do.+?end\n\n/m.freeze
<add>
<ide> sig { returns(CLI::Parser) }
<ide> def extract_args
<ide> Homebrew::CLI::Parser.new do
<ide> def extract
<ide> result.sub!("class #{class_name} < Formula", "class #{versioned_name} < Formula")
<ide>
<ide> # Remove bottle blocks, they won't work.
<del> result.sub!(/ bottle do.+?end\n\n/m, "") if destination_tap != source_tap
<add> result.sub!(BOTTLE_BLOCK_REGEX, "")
<ide>
<ide> path = destination_tap.path/"Formula/#{name}@#{version.to_s.downcase}.rb"
<ide> if path.exist?
<ide> def formula_at_revision(repo, name, file, rev)
<ide> contents = Utils::Git.last_revision_of_file(repo, file, before_commit: rev)
<ide> contents.gsub!("@url=", "url ")
<ide> contents.gsub!("require 'brewkit'", "require 'formula'")
<add> contents.sub!(BOTTLE_BLOCK_REGEX, "")
<ide> with_monkey_patch { Formulary.from_contents(name, file, contents, ignore_errors: true) }
<ide> end
<ide> end | 1 |
Python | Python | pass initial_state as a keyword argument | 16343b3261da08a8aa52f209a8609ce4b51c7fdf | <ide><path>keras/layers/recurrent.py
<ide> class Recurrent(Layer):
<ide> a specific layer, or on your entire model.
<ide>
<ide> # Note on specifying initial states in RNNs
<del> Most RNN layers can be called with either a single tensor, or a list
<del> of tensors.
<del> If the an RNN layer is called with a single tensor, that tensor is
<del> treated as the input, and the initial states are assigned an
<del> appropriate default value.
<del> If an RNN layer is called with a list of tensors, the first element is
<del> treated as the input, and the remaining tensors are treated as the
<del> initial states.
<add> You can specify the initial state of RNN layers by calling theme with
<add> the keyword argument `initial_state`. The value of `initial_state`
<add> should be a tensor or list of tensors representing the initial state
<add> of the RNN layer.
<ide> """
<ide>
<ide> def __init__(self, return_sequences=False,
<ide> def __init__(self, return_sequences=False,
<ide> self.unroll = unroll
<ide> self.implementation = 0
<ide> self.supports_masking = True
<del> self.input_spec = None
<add> self.input_spec = InputSpec(ndim=3)
<add> self.state_spec = None
<ide> self.dropout = 0
<ide> self.recurrent_dropout = 0
<ide>
<ide> def get_initial_states(self, inputs):
<ide> def preprocess_input(self, inputs, training=None):
<ide> return inputs
<ide>
<add> def __call__(self, inputs, **kwargs):
<add> with K.name_scope(self.name):
<add> # Handle laying building (weight creating, input spec locking,
<add> # state spec locking)
<add> if not self.built:
<add> # Raise exceptions in case the input is not compatible
<add> # with the input_spec specified in the layer constructor.
<add> self.assert_input_compatibility(inputs)
<add>
<add> if hasattr(inputs, '_keras_shape'):
<add> input_shape = inputs._keras_shape
<add> elif hasattr(K, 'int_shape'):
<add> input_shape = K.int_shape(inputs)
<add> else:
<add> raise ValueError('You tried to call layer "' + self.name +
<add> '". This layer has no information'
<add> ' about its expected input shape, '
<add> 'and thus cannot be built. '
<add> 'You can build it manually via: '
<add> '`layer.build(batch_input_shape)`')
<add> self.build(input_shape)
<add> self.built = True
<add>
<add> # If initial_state is specified, add it to the inputs and temporarily
<add> # modify the input spec to include the state
<add> if 'initial_state' in kwargs:
<add> # Compute the full input spec, including state
<add> input_spec = self.input_spec
<add> state_spec = self.state_spec
<add> if not isinstance(state_spec, list):
<add> state_spec = [state_spec]
<add> self.input_spec = [input_spec] + state_spec
<add>
<add> # Compute the full inputs, including state
<add> initial_state = kwargs.pop('initial_state')
<add> if not isinstance(initial_state, list):
<add> initial_state = [initial_state]
<add> inputs = [inputs] + initial_state
<add>
<add> # Perform the call
<add> output = super(Recurrent, self).__call__(inputs, **kwargs)
<add>
<add> # Restore original input spec
<add> self.input_spec = input_spec
<add> return output
<add>
<add> return super(Recurrent, self).__call__(inputs, **kwargs)
<add>
<ide> def call(self, inputs, mask=None, training=None):
<ide> # input shape: (nbias_samples, time (padded with zeros), input_dim)
<ide> # note that the .build() method of subclasses MUST define
<del> # self.input_spec with a complete input shape.
<add> # self.input_spec and self.state_spec with complete input shapes.
<ide> if isinstance(inputs, list):
<ide> initial_states = inputs[1:]
<ide> inputs = inputs[0]
<ide> def call(self, inputs, mask=None, training=None):
<ide> def reset_states(self):
<ide> if not self.stateful:
<ide> raise AttributeError('Layer must be stateful.')
<del> if not self.batch_size:
<add> batch_size = self.input_spec.shape[0]
<add> if not batch_size:
<ide> raise ValueError('If a RNN is stateful, it needs to know '
<ide> 'its batch size. Specify the batch size '
<ide> 'of your input tensors: \n'
<ide> def reset_states(self):
<ide> '`batch_shape` argument to your Input layer.')
<ide> if self.states[0] is not None:
<ide> for state in self.states:
<del> K.set_value(state, np.zeros((self.batch_size, self.units)))
<add> K.set_value(state, np.zeros((batch_size, self.units)))
<ide> else:
<del> self.states = [K.zeros((self.batch_size, self.units))
<add> self.states = [K.zeros((batch_size, self.units))
<ide> for _ in self.states]
<ide>
<ide> def get_config(self):
<ide> def build(self, input_shape):
<ide> if isinstance(input_shape, list):
<ide> input_shape = input_shape[0]
<ide>
<del> self.batch_size = input_shape[0]
<add> batch_size = input_shape[0] if self.stateful else None
<ide> self.input_dim = input_shape[2]
<add> self.input_spec = InputSpec(shape=(batch_size, None, self.input_dim))
<add> self.state_spec = InputSpec(shape=(batch_size, self.units))
<ide>
<ide> self.states = [None]
<ide> if self.stateful:
<ide> def build(self, input_shape):
<ide> if isinstance(input_shape, list):
<ide> input_shape = input_shape[0]
<ide>
<del> self.batch_size = input_shape[0]
<add> batch_size = input_shape[0] if self.stateful else None
<ide> self.input_dim = input_shape[2]
<add> self.input_spec = InputSpec(shape=(batch_size, None, self.input_dim))
<add> self.state_spec = InputSpec(shape=(batch_size, self.units))
<ide>
<ide> self.states = [None]
<ide> if self.stateful:
<ide> def build(self, input_shape):
<ide> if isinstance(input_shape, list):
<ide> input_shape = input_shape[0]
<ide>
<del> self.batch_size = input_shape[0]
<add> batch_size = input_shape[0] if self.stateful else None
<ide> self.input_dim = input_shape[2]
<add> self.input_spec = InputSpec(shape=(batch_size, None, self.input_dim))
<add> self.state_spec = [InputSpec(shape=(batch_size, self.units)),
<add> InputSpec(shape=(batch_size, self.units))]
<ide>
<ide> self.states = [None, None]
<ide> if self.stateful:
<ide><path>tests/keras/layers/recurrent_test.py
<ide> def test_from_config(layer_class):
<ide> def test_specify_state(layer_class):
<ide> states = 2 if layer_class is recurrent.LSTM else 1
<ide> inputs = Input((timesteps, embedding_dim))
<del> initial_states = [Input((units,)) for _ in range(states)]
<add> initial_state = [Input((units,)) for _ in range(states)]
<ide> layer = layer_class(units)
<del> output = layer([inputs] + initial_states)
<del> model = Model([inputs] + initial_states, output)
<add> output = layer(inputs, initial_state=initial_state)
<add> model = Model([inputs] + initial_state, output)
<ide> model.compile(loss='categorical_crossentropy', optimizer='adam')
<ide>
<ide> inputs = np.random.random((num_samples, timesteps, embedding_dim)) | 2 |
Text | Text | add headers to payload list [ci skip] | 0c85ff33b1b84ee68cad47f5c294051fecccf115 | <ide><path>guides/source/active_support_instrumentation.md
<ide> Action Controller
<ide> | `:controller` | The controller name |
<ide> | `:action` | The action |
<ide> | `:params` | Hash of request parameters without any filtered parameter |
<add>| `:headers` | Request headers |
<ide> | `:format` | html/js/json/xml etc |
<ide> | `:method` | HTTP request verb |
<ide> | `:path` | Request path |
<ide> Action Controller
<ide> controller: "PostsController",
<ide> action: "new",
<ide> params: { "action" => "new", "controller" => "posts" },
<add> headers: #<ActionDispatch::Http::Headers:0x0055a67a519b88>,
<ide> format: :html,
<ide> method: "GET",
<ide> path: "/posts/new"
<ide> Action Controller
<ide> | `:controller` | The controller name |
<ide> | `:action` | The action |
<ide> | `:params` | Hash of request parameters without any filtered parameter |
<add>| `:headers` | Request headers |
<ide> | `:format` | html/js/json/xml etc |
<ide> | `:method` | HTTP request verb |
<ide> | `:path` | Request path |
<ide> Action Controller
<ide> controller: "PostsController",
<ide> action: "index",
<ide> params: {"action" => "index", "controller" => "posts"},
<add> headers: #<ActionDispatch::Http::Headers:0x0055a67a519b88>,
<ide> format: :html,
<ide> method: "GET",
<ide> path: "/posts", | 1 |
Mixed | Ruby | avoid duplicate clauses when using #or | 110e0e1fcceab68716e0c75d87baffb14403b288 | <ide><path>activerecord/CHANGELOG.md
<add>* When using #or, extract the common conditions and put them before the OR condition.
<add>
<add> *Maxime Handfield Lapointe*
<add>
<ide> * `Relation#or` now accepts two relations who have different values for
<ide> `references` only, as `references` can be implicitly called by `where`.
<ide>
<ide><path>activerecord/lib/active_record/relation/where_clause.rb
<ide> def +(other)
<ide> )
<ide> end
<ide>
<add> def -(other)
<add> WhereClause.new(
<add> predicates - other.predicates,
<add> )
<add> end
<add>
<ide> def merge(other)
<ide> WhereClause.new(
<ide> predicates_unreferenced_by(other) + other.predicates,
<ide> def except(*columns)
<ide> end
<ide>
<ide> def or(other)
<del> if empty?
<del> self
<del> elsif other.empty?
<del> other
<del> else
<del> WhereClause.new(
<del> [ast.or(other.ast)],
<del> )
<del> end
<add> left = self - other
<add> common = self - left
<add> right = other - common
<add>
<add> return common if left.empty? || right.empty?
<add>
<add> or_clause = WhereClause.new(
<add> [left.ast.or(right.ast)]
<add> )
<add> common + or_clause
<ide> end
<ide>
<ide> def to_h(table_name = nil)
<ide><path>activerecord/test/cases/relation/where_clause_test.rb
<ide> class WhereClauseTest < ActiveRecord::TestCase
<ide> assert_equal WhereClause.empty, WhereClause.empty.or(where_clause)
<ide> end
<ide>
<add> test "or places common conditions before the OR" do
<add> wcs = (0..6).map do |i|
<add> WhereClause.new([table["col_#{i}"].eq(bind_param(i))])
<add> end
<add>
<add> actual = wcs[0]
<add> expected = wcs[0]
<add>
<add> actual = (actual + wcs[1]).or(actual + wcs[2])
<add> expected = expected + wcs[1].or(wcs[2])
<add>
<add> actual = (actual + wcs[3] + wcs[4]).or(actual + wcs[5] + wcs[6])
<add> expected = expected + (wcs[3] + wcs[4]).or(wcs[5] + wcs[6])
<add>
<add> assert_equal expected, actual
<add> end
<add>
<add> test "or will use common conditions only if one side only has common conditions" do
<add> common = WhereClause.new(
<add> [table["id"].eq(bind_param(1)), "foo = bar"]
<add> )
<add>
<add> extra = WhereClause.new([table["extra"].eq(bind_param("pluto"))])
<add>
<add> actual_extra_only_on_left = (common + extra).or(common)
<add> actual_extra_only_on_right = (common).or(common + extra)
<add>
<add> expected = common
<add>
<add> assert_equal expected, actual_extra_only_on_left
<add> assert_equal expected, actual_extra_only_on_right
<add> end
<add>
<ide> private
<ide>
<ide> def table | 3 |
Text | Text | remove whitespace before testing | a294021d537abdc7e1582d72be2592727a0f8dec | <ide><path>curriculum/challenges/english/03-front-end-libraries/react/render-state-in-the-user-interface.english.md
<ide> tests:
<ide> - text: <code>MyComponent</code> should render an <code>h1</code> header enclosed in a single <code>div</code>.
<ide> testString: assert(/<div><h1>.*<\/h1><\/div>/.test(Enzyme.mount(React.createElement(MyComponent)).html()));
<ide> - text: The rendered <code>h1</code> header should contain text rendered from the component's state.
<del> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: ''TestName'' }); return waitForIt(() => mockedComponent.html()) }; const firstValue = await first(); assert(firstValue === ''<div><h1>TestName</h1></div>'');};'
<add> testString: |
<add> async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: 'TestName' }); return waitForIt(() => mockedComponent.html()) }; const firstValue = await first(); const getValue = firstValue.replace(/\s/g, ''); assert(getValue === '<div><h1>TestName</h1></div>'); };
<ide>
<ide> ```
<ide> | 1 |
Python | Python | terminate pool at systemexit | 22491d70625ca9890d8c47f50ffacca89c34bd3c | <ide><path>celery/bin/celeryd.py
<ide> def run_worker(concurrency=DAEMON_CONCURRENCY, daemon=False,
<ide> except Exception, e:
<ide> emergency_error(logfile, "celeryd raised exception %s: %s\n%s" % (
<ide> e.__class__, e, traceback.format_exc()))
<add> except:
<add> context.close()
<add> raise
<ide>
<ide>
<ide> OPTION_LIST = (
<ide><path>celery/pool.py
<ide> def _start(self):
<ide> self._processes = {}
<ide> self._pool = multiprocessing.Pool(processes=self.limit)
<ide>
<add> def terminate(self):
<add> """Terminate the pool."""
<add> self._pool.terminate()
<add>
<ide> def _terminate_and_restart(self):
<ide> """INTERNAL: Terminate and restart the pool."""
<ide> try:
<del> self._pool.terminate()
<add> self.terminate()
<ide> except OSError:
<ide> pass
<ide> self._start()
<ide> def on_ready(self, ret_value, callbacks, errbacks, meta):
<ide> been collected."""
<ide>
<ide> if isinstance(ret_value, ExceptionInfo):
<add> if isinstance(ret_value.exception, KeyboardInterrupt) or \
<add> isinstance(ret_value.exception, SystemExit):
<add> self.terminate()
<add> raise ret_value.exception
<ide> for errback in errbacks:
<ide> errback(ret_value, meta)
<ide> else:
<ide><path>celery/worker.py
<ide> def jail(task_id, func, args, kwargs):
<ide> for k, v in kwargs.items()])
<ide> try:
<ide> result = func(*args, **kwargs)
<add> except (SystemExit, KeyboardInterrupt):
<add> raise
<ide> except Exception, exc:
<ide> default_backend.mark_as_failure(task_id, exc)
<ide> return ExceptionInfo(sys.exc_info())
<ide> def run(self):
<ide> self.logger.critical("Message queue raised %s: %s\n%s" % (
<ide> exc.__class__, exc, traceback.format_exc()))
<ide> continue
<add> except:
<add> self.pool.terminate()
<add> raise
<add> | 3 |
Python | Python | add fixture for cli tests requiring sample dags | 3cd4df16d4f383c27f7fc6bd932bca1f83ab9977 | <ide><path>airflow/models/dagbag.py
<ide> from airflow.utils.retries import MAX_DB_RETRIES, run_with_db_retries
<ide> from airflow.utils.session import provide_session
<ide> from airflow.utils.timeout import timeout
<add>from airflow.utils.types import NOTSET, ArgNotSet
<ide>
<ide> if TYPE_CHECKING:
<ide> import pathlib
<ide> class DagBag(LoggingMixin):
<ide> def __init__(
<ide> self,
<ide> dag_folder: str | pathlib.Path | None = None,
<del> include_examples: bool = conf.getboolean('core', 'LOAD_EXAMPLES'),
<del> safe_mode: bool = conf.getboolean('core', 'DAG_DISCOVERY_SAFE_MODE'),
<add> include_examples: bool | ArgNotSet = NOTSET,
<add> safe_mode: bool | ArgNotSet = NOTSET,
<ide> read_dags_from_db: bool = False,
<ide> store_serialized_dags: bool | None = None,
<ide> load_op_links: bool = True,
<ide> def __init__(
<ide>
<ide> super().__init__()
<ide>
<add> include_examples = (
<add> include_examples
<add> if isinstance(include_examples, bool)
<add> else conf.getboolean('core', 'LOAD_EXAMPLES')
<add> )
<add> safe_mode = (
<add> safe_mode if isinstance(safe_mode, bool) else conf.getboolean('core', 'DAG_DISCOVERY_SAFE_MODE')
<add> )
<add>
<ide> if store_serialized_dags:
<ide> warnings.warn(
<ide> "The store_serialized_dags parameter has been deprecated. "
<ide><path>tests/cli/conftest.py
<ide> from airflow import models
<ide> from airflow.cli import cli_parser
<ide> from airflow.executors import celery_executor, celery_kubernetes_executor
<add>from tests.test_utils.config import conf_vars
<ide>
<ide> # Create custom executors here because conftest is imported first
<ide> custom_executor_module = type(sys)('custom_executor')
<ide> sys.modules['custom_executor'] = custom_executor_module
<ide>
<ide>
<add>@pytest.fixture(autouse=True)
<add>def load_examples():
<add> with conf_vars({('core', 'load_examples'): 'True'}):
<add> yield
<add>
<add>
<ide> @pytest.fixture(scope="session")
<ide> def dagbag():
<ide> return models.DagBag(include_examples=True)
<ide><path>tests/jobs/test_scheduler_job.py
<ide> def dagbag():
<ide> return DagBag(read_dags_from_db=True)
<ide>
<ide>
<add>@pytest.fixture
<add>def load_examples():
<add> with conf_vars({('core', 'load_examples'): 'True'}):
<add> yield
<add>
<add>
<ide> @pytest.mark.usefixtures("disable_load_example")
<ide> @pytest.mark.need_serialized_dag
<ide> class TestSchedulerJob:
<ide> def test_find_zombies_nothing(self):
<ide>
<ide> self.scheduler_job.executor.callback_sink.send.assert_not_called()
<ide>
<del> def test_find_zombies(self):
<add> def test_find_zombies(self, load_examples):
<ide> dagbag = DagBag(TEST_DAG_FOLDER, read_dags_from_db=False)
<ide> with create_session() as session:
<ide> session.query(LocalTaskJob).delete()
<ide> def test_find_zombies(self):
<ide> session.query(TaskInstance).delete()
<ide> session.query(LocalTaskJob).delete()
<ide>
<del> def test_zombie_message(self):
<add> def test_zombie_message(self, load_examples):
<ide> """
<ide> Check that the zombie message comes out as expected
<ide> """ | 3 |
Text | Text | fix minor typo in testing guide | 0e2cc9bc0debe893a8d151dfb4a3694b6b93505f | <ide><path>guides/source/testing.md
<ide> Finally we can assert that our response was successful, template was rendered, a
<ide>
<ide> #### Taking it further
<ide>
<del>We were able to successfully test a very small workflow for visiting our blog and creating a new article. If we wanted to take this further we could add tests for commenting, removing articles, or editting comments. Integration tests are a great place to experiment with all kinds of use-cases for our applications.
<add>We were able to successfully test a very small workflow for visiting our blog and creating a new article. If we wanted to take this further we could add tests for commenting, removing articles, or editing comments. Integration tests are a great place to experiment with all kinds of use-cases for our applications.
<ide>
<ide> Testing Your Mailers
<ide> -------------------- | 1 |
Javascript | Javascript | update test-dns.js after a60a9b0 | 7b72e156655afb6b998e8fb731cc65f4facb19ee | <ide><path>test/internet/test-dns.js
<ide> var assert = require('assert'),
<ide> isIP = net.isIP,
<ide> isIPv4 = net.isIPv4,
<ide> isIPv6 = net.isIPv6;
<add>var util = require('util');
<ide>
<ide> var expected = 0,
<ide> completed = 0,
<ide> TEST(function test_resolveTxt(done) {
<ide> var req = dns.resolveTxt('google.com', function(err, records) {
<ide> if (err) throw err;
<ide> assert.equal(records.length, 1);
<del> assert.equal(records[0].indexOf('v=spf1'), 0);
<add> assert.ok(util.isArray(records[0]));
<add> assert.equal(records[0][0].indexOf('v=spf1'), 0);
<ide> done();
<ide> });
<ide> | 1 |
Python | Python | avoid tensorflow import in trainer | b8697bc62216b9e2ca60811626c6a6ca992b0d34 | <ide><path>src/transformers/modelcard.py
<ide> is_tokenizers_available,
<ide> is_torch_available,
<ide> )
<del>from .models.auto.configuration_auto import ALL_PRETRAINED_CONFIG_ARCHIVE_MAP
<ide> from .training_args import ParallelMode
<ide> from .utils import logging
<ide>
<ide> def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
<ide> modelcard = ModelCard.from_pretrained('bert-base-uncased', output_attentions=True, foo=False)
<ide>
<ide> """
<add> # This imports every model so let's do it dynamically here.
<add> from transformers.models.auto.configuration_auto import ALL_PRETRAINED_CONFIG_ARCHIVE_MAP
<add>
<ide> cache_dir = kwargs.pop("cache_dir", None)
<ide> proxies = kwargs.pop("proxies", None)
<ide> find_from_standard_name = kwargs.pop("find_from_standard_name", True) | 1 |
Javascript | Javascript | add support for missing xhr response types | fcc89e9d923893229dae11edb59bd3df082fafad | <ide><path>Libraries/Network/XMLHttpRequestBase.js
<ide>
<ide> var RCTNetworking = require('RCTNetworking');
<ide> var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
<del>var invariant = require('fbjs/lib/invariant');
<add>const invariant = require('fbjs/lib/invariant');
<add>const utf8 = require('utf8');
<add>const warning = require('fbjs/lib/warning');
<add>
<add>type ResponseType = '' | 'arraybuffer' | 'blob' | 'document' | 'json' | 'text';
<add>type Response = ?Object | string;
<ide>
<ide> const UNSENT = 0;
<ide> const OPENED = 1;
<ide> const HEADERS_RECEIVED = 2;
<ide> const LOADING = 3;
<ide> const DONE = 4;
<ide>
<add>const SUPPORTED_RESPONSE_TYPES = {
<add> arraybuffer: typeof global.ArrayBuffer === 'function',
<add> blob: typeof global.Blob === 'function',
<add> document: false,
<add> json: true,
<add> text: true,
<add> '': true,
<add>};
<add>
<ide> /**
<ide> * Shared base for platform-specific XMLHttpRequest implementations.
<ide> */
<ide> class XMLHttpRequestBase {
<ide> upload: any;
<ide> readyState: number;
<ide> responseHeaders: ?Object;
<del> responseText: ?string;
<del> response: ?string;
<del> responseType: '' | 'text';
<add> responseText: string;
<ide> status: number;
<ide> timeout: number;
<ide> responseURL: ?string;
<ide> class XMLHttpRequestBase {
<ide> _requestId: ?number;
<ide> _subscriptions: [any];
<ide>
<del> _method: ?string;
<del> _url: ?string;
<del> _headers: Object;
<del> _sent: boolean;
<ide> _aborted: boolean;
<add> _cachedResponse: Response;
<add> _hasError: boolean;
<add> _headers: Object;
<ide> _lowerCaseResponseHeaders: Object;
<add> _method: ?string;
<add> _response: string | ?Object;
<add> _responseType: ResponseType;
<add> _sent: boolean;
<add> _url: ?string;
<ide>
<ide> constructor() {
<ide> this.UNSENT = UNSENT;
<ide> class XMLHttpRequestBase {
<ide> this._aborted = false;
<ide> }
<ide>
<del> _reset() {
<add> _reset(): void {
<ide> this.readyState = this.UNSENT;
<ide> this.responseHeaders = undefined;
<ide> this.responseText = '';
<del> this.response = null;
<del> this.responseType = '';
<ide> this.status = 0;
<ide> delete this.responseURL;
<ide>
<ide> this._requestId = null;
<ide>
<add> this._cachedResponse = undefined;
<add> this._hasError = false;
<ide> this._headers = {};
<add> this._responseType = '';
<ide> this._sent = false;
<ide> this._lowerCaseResponseHeaders = {};
<ide>
<ide> this._clearSubscriptions();
<ide> }
<ide>
<add> // $FlowIssue #10784535
<add> get responseType(): ResponseType {
<add> return this._responseType;
<add> }
<add>
<add> // $FlowIssue #10784535
<add> set responseType(responseType: ResponseType): void {
<add> if (this.readyState > HEADERS_RECEIVED) {
<add> throw new Error(
<add> "Failed to set the 'responseType' property on 'XMLHttpRequest': The " +
<add> "response type cannot be set if the object's state is LOADING or DONE"
<add> );
<add> }
<add> if (!SUPPORTED_RESPONSE_TYPES.hasOwnProperty(responseType)) {
<add> warning(
<add> `The provided value '${responseType}' is not a valid 'responseType'.`);
<add> return;
<add> }
<add>
<add> // redboxes early, e.g. for 'arraybuffer' on ios 7
<add> invariant(
<add> SUPPORTED_RESPONSE_TYPES[responseType] || responseType === 'document',
<add> `The provided value '${responseType}' is unsupported in this environment.`
<add> );
<add> this._responseType = responseType;
<add> }
<add>
<add> // $FlowIssue #10784535
<add> get response(): Response {
<add> const {responseType} = this;
<add> if (responseType === '' || responseType === 'text') {
<add> return this.readyState < LOADING || this._hasError
<add> ? ''
<add> : this.responseText;
<add> }
<add>
<add> if (this.readyState !== DONE) {
<add> return null;
<add> }
<add>
<add> if (this._cachedResponse !== undefined) {
<add> return this._cachedResponse;
<add> }
<add>
<add> switch (this.responseType) {
<add> case 'document':
<add> this._cachedResponse = null;
<add> break;
<add>
<add> case 'arraybuffer':
<add> this._cachedResponse = toArrayBuffer(
<add> this.responseText, this.getResponseHeader('content-type') || '');
<add> break;
<add>
<add> case 'blob':
<add> this._cachedResponse = new global.Blob(
<add> [this.responseText],
<add> {type: this.getResponseHeader('content-type') || ''}
<add> );
<add> break;
<add>
<add> case 'json':
<add> try {
<add> this._cachedResponse = JSON.parse(this.responseText);
<add> } catch (_) {
<add> this._cachedResponse = null;
<add> }
<add> break;
<add>
<add> default:
<add> this._cachedResponse = null;
<add> }
<add>
<add> return this._cachedResponse;
<add> }
<add>
<ide> didCreateRequest(requestId: number): void {
<ide> this._requestId = requestId;
<ide> this._subscriptions.push(RCTDeviceEventEmitter.addListener(
<ide> class XMLHttpRequestBase {
<ide> } else {
<ide> this.responseText += responseText;
<ide> }
<del> switch(this.responseType) {
<del> case '':
<del> case 'text':
<del> this.response = this.responseText;
<del> break;
<del> case 'blob': // whatwg-fetch sets this in Chrome
<del> /* global Blob: true */
<del> invariant(
<del> typeof Blob === 'function',
<del> `responseType "blob" is only supported on platforms with native Blob support`
<del> );
<del> this.response = new Blob([this.responseText]);
<del> break;
<del> default: //TODO: Support other types, eg: document, arraybuffer, json
<del> invariant(false, `responseType "${this.responseType}" is unsupported`);
<del> }
<add> this._cachedResponse = undefined; // force lazy recomputation
<ide> this.setReadyState(this.LOADING);
<ide> }
<ide> }
<ide> class XMLHttpRequestBase {
<ide> if (requestId === this._requestId) {
<ide> if (error) {
<ide> this.responseText = error;
<add> this._hasError = true;
<ide> }
<ide> this._clearSubscriptions();
<ide> this._requestId = null;
<ide> XMLHttpRequestBase.HEADERS_RECEIVED = HEADERS_RECEIVED;
<ide> XMLHttpRequestBase.LOADING = LOADING;
<ide> XMLHttpRequestBase.DONE = DONE;
<ide>
<add>function toArrayBuffer(text: string, contentType: string): ArrayBuffer {
<add> const {length} = text;
<add> if (length === 0) {
<add> return new ArrayBuffer(0);
<add> }
<add>
<add> const charsetMatch = contentType.match(/;\s*charset=([^;]*)/i);
<add> const charset = charsetMatch ? charsetMatch[1].trim() : 'utf-8';
<add>
<add> if (/^utf-?8$/i.test(charset)) {
<add> return utf8.encode(text);
<add> } else { //TODO: utf16 / ucs2 / utf32
<add> const array = new Uint8Array(length);
<add> for (let i = 0; i < length; i++) {
<add> array[i] = text.charCodeAt(i); // Uint8Array automatically masks with 0xff
<add> }
<add> return array.buffer;
<add> }
<add>}
<add>
<ide> module.exports = XMLHttpRequestBase;
<ide><path>Libraries/Utilities/__tests__/utf8-test.js
<add>/**
<add> * Copyright (c) 2016-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add> 'use strict';
<add>
<add> jest.autoMockOff();
<add>
<add> const {encode} = require('../utf8');
<add>
<add> describe('UTF-8 encoding:', () => {
<add> it('can encode code points < U+80', () => {
<add> const arrayBuffer = encode('\u0000abcDEF\u007f');
<add> expect(new Uint8Array(arrayBuffer)).toEqual(
<add> new Uint8Array([0x00, 0x61, 0x62, 0x63, 0x44, 0x45, 0x46, 0x7f]));
<add> });
<add>
<add> it('can encode code points < U+800', () => {
<add> const arrayBuffer = encode('\u0080\u0548\u07ff');
<add> expect(new Uint8Array(arrayBuffer)).toEqual(
<add> new Uint8Array([0xc2, 0x80, 0xd5, 0x88, 0xdf, 0xbf]));
<add> });
<add>
<add> it('can encode code points < U+10000', () => {
<add> const arrayBuffer = encode('\u0800\uac48\uffff');
<add> expect(new Uint8Array(arrayBuffer)).toEqual(
<add> new Uint8Array([0xe0, 0xa0, 0x80, 0xea, 0xb1, 0x88, 0xef, 0xbf, 0xbf]));
<add> });
<add>
<add> it('can encode code points in the Supplementary Planes (surrogate pairs)', () => {
<add> const arrayBuffer = encode([
<add> '\ud800\udc00',
<add> '\ud800\ude89',
<add> '\ud83d\ude3b',
<add> '\udbff\udfff'
<add> ].join(''));
<add> expect(new Uint8Array(arrayBuffer)).toEqual(
<add> new Uint8Array([
<add> 0xf0, 0x90, 0x80, 0x80,
<add> 0xf0, 0x90, 0x8a, 0x89,
<add> 0xf0, 0x9f, 0x98, 0xbb,
<add> 0xf4, 0x8f, 0xbf, 0xbf,
<add> ])
<add> );
<add> });
<add>
<add> it('allows for stray high surrogates', () => {
<add> const arrayBuffer = encode('a\ud8c6b');
<add> expect(new Uint8Array(arrayBuffer)).toEqual(
<add> new Uint8Array([0x61, 0xed, 0xa3, 0x86, 0x62]));
<add> });
<add>
<add> it('allows for stray low surrogates', () => {
<add> const arrayBuffer = encode('a\ude19b');
<add> expect(new Uint8Array(arrayBuffer)).toEqual(
<add> new Uint8Array([0x61, 0xed, 0xb8, 0x99, 0x62]));
<add> });
<add> });
<ide><path>Libraries/Utilities/utf8.js
<add>/**
<add> * Copyright (c) 2016-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule utf8
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>class ByteVector {
<add> _storage: Uint8Array;
<add> _sizeWritten: number;
<add>
<add> constructor(size) {
<add> this._storage = new Uint8Array(size);
<add> this._sizeWritten = 0;
<add> }
<add>
<add> push(value: number): ByteVector {
<add> const i = this._sizeWritten;
<add> if (i === this._storage.length) {
<add> this._realloc();
<add> }
<add> this._storage[i] = value;
<add> this._sizeWritten = i + 1;
<add> return this;
<add> }
<add>
<add> getBuffer(): ArrayBuffer {
<add> return this._storage.buffer.slice(0, this._sizeWritten);
<add> }
<add>
<add> _realloc() {
<add> const storage = this._storage;
<add> this._storage = new Uint8Array(align(storage.length * 1.5));
<add> this._storage.set(storage);
<add> }
<add>}
<add>
<add>/*eslint-disable no-bitwise */
<add>exports.encode = (string: string): ArrayBuffer => {
<add> const {length} = string;
<add> const bytes = new ByteVector(length);
<add>
<add> // each character / char code is assumed to represent an UTF-16 wchar.
<add> // With the notable exception of surrogate pairs, each wchar represents the
<add> // corresponding unicode code point.
<add> // For an explanation of UTF-8 encoding, read [1]
<add> // For an explanation of UTF-16 surrogate pairs, read [2]
<add> //
<add> // [1] https://en.wikipedia.org/wiki/UTF-8#Description
<add> // [2] https://en.wikipedia.org/wiki/UTF-16#U.2B10000_to_U.2B10FFFF
<add> let nextCodePoint = string.charCodeAt(0);
<add> for (let i = 0; i < length; i++) {
<add> let codePoint = nextCodePoint;
<add> nextCodePoint = string.charCodeAt(i + 1);
<add>
<add> if (codePoint < 0x80) {
<add> bytes.push(codePoint);
<add> } else if (codePoint < 0x800) {
<add> bytes
<add> .push(0xc0 | codePoint >>> 6)
<add> .push(0x80 | codePoint & 0x3f);
<add> } else if (codePoint >>> 10 === 0x36 && nextCodePoint >>> 10 === 0x37) { // high surrogate & low surrogate
<add> codePoint = 0x10000 + (((codePoint & 0x3ff) << 10) | (nextCodePoint & 0x3ff));
<add> bytes
<add> .push(0xf0 | codePoint >>> 18 & 0x7)
<add> .push(0x80 | codePoint >>> 12 & 0x3f)
<add> .push(0x80 | codePoint >>> 6 & 0x3f)
<add> .push(0x80 | codePoint & 0x3f);
<add>
<add> i += 1;
<add> nextCodePoint = string.charCodeAt(i + 1);
<add> } else {
<add> bytes
<add> .push(0xe0 | codePoint >>> 12)
<add> .push(0x80 | codePoint >>> 6 & 0x3f)
<add> .push(0x80 | codePoint & 0x3f);
<add> }
<add> }
<add> return bytes.getBuffer();
<add>};
<add>
<add>// align to multiples of 8 bytes
<add>function align(size: number): number {
<add> return size % 8 ? (Math.floor(size / 8) + 1) << 3 : size;
<add>} | 3 |
Javascript | Javascript | remove extra spacing | 11ab454d020cc4dbc1b589e77c865be7a7274911 | <ide><path>test/createStore.spec.js
<ide> describe('createStore', () => {
<ide> expect(listenerB.calls.length).toBe(1);
<ide> });
<ide>
<del>
<ide> it('should support removing a subscription within a subscription', () => {
<ide> const store = createStore(reducers.todos);
<ide> const listenerA = expect.createSpy(() => {}); | 1 |
Javascript | Javascript | make isnumeric limited to strings and numbers | 15ac848868e993dfe5ccd7751a94f5c8edc288bc | <ide><path>src/core.js
<ide> jQuery.extend( {
<ide>
<ide> isNumeric: function( obj ) {
<ide>
<del> // parseFloat NaNs numeric-cast false positives (null|true|false|"")
<del> // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
<del> // subtraction forces infinities to NaN
<del> // adding 1 corrects loss of precision from parseFloat (#15100)
<del> var realStringObj = obj && obj.toString();
<del> return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0;
<add> // As of jQuery 3.0, isNumeric is limited to
<add> // strings and numbers (primitives or objects)
<add> // that can be coerced to finite numbers (gh-2662)
<add> var type = jQuery.type( obj );
<add> return ( type === "number" || type === "string" ) &&
<add> ( obj - parseFloat( obj ) + 1 ) >= 0;
<ide> },
<ide>
<ide> isPlainObject: function( obj ) {
<ide><path>test/unit/core.js
<ide> QUnit.test( "isNumeric", function( assert ) {
<ide> assert.ok( t( 1.5999999999999999 ), "Very precise floating point number" );
<ide> assert.ok( t( 8e5 ), "Exponential notation" );
<ide> assert.ok( t( "123e-2" ), "Exponential notation string" );
<del> assert.ok( t( new ToString( "42" ) ), "Custom .toString returning number" );
<ide>
<add> assert.equal( t( new ToString( "42" ) ), false, "Custom .toString returning number" );
<ide> assert.equal( t( "" ), false, "Empty string" );
<ide> assert.equal( t( " " ), false, "Whitespace characters string" );
<ide> assert.equal( t( "\t\t" ), false, "Tab characters string" ); | 2 |
Mixed | Python | allow customizing operation name. | 5b16a1724202d6f4ef58d22caa492893ee5f3aa8 | <ide><path>docs/api-guide/schemas.md
<ide> class MyView(APIView):
<ide> ...
<ide> ```
<ide>
<add>### OperationId
<add>
<add>The schema generator generates an [operationid](openapi-operationid) for each operation. This `operationId` is deduced from the model name, serializer name or view name. The operationId may looks like "ListItems", "RetrieveItem", "UpdateItem", etc..
<add>
<add>If you have several views with the same model, the generator may generate duplicate operationId.
<add>In order to work around this, you can override the second part of the operationId: operation name.
<add>
<add>```python
<add>from rest_framework.schemas.openapi import AutoSchema
<add>
<add>class ExampleView(APIView):
<add> """APIView subclass with custom schema introspection."""
<add> schema = AutoSchema(operation_id_base="Custom")
<add>```
<add>
<add>The previous example will generate the following operationId: "ListCustoms", "RetrieveCustom", "UpdateCustom", "PartialUpdateCustom", "DestroyCustom".
<add>You need to provide the singular form of he operation name. For the list operation, a "s" will be appended at the end of the operation.
<add>
<add>If you need more configuration over the `operationId` field, you can override the `get_operation_id_base` and `get_operation_id` methods from the `AutoSchema` class:
<add>
<add>```python
<add>class CustomSchema(AutoSchema):
<add> def get_operation_id_base(self, path, method, action):
<add> pass
<add>
<add> def get_operation_id(self, path, method):
<add> pass
<add>
<add>class CustomView(APIView):
<add> """APIView subclass with custom schema introspection."""
<add> schema = CustomSchema()
<add>```
<ide>
<ide> [openapi]: https://github.com/OAI/OpenAPI-Specification
<ide> [openapi-specification-extensions]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions
<ide> [openapi-operation]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#operationObject
<ide> [openapi-tags]: https://swagger.io/specification/#tagObject
<add>[openapi-operationid]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#fixed-fields-17
<ide><path>rest_framework/schemas/openapi.py
<ide> def get_schema(self, request=None, public=False):
<ide>
<ide> class AutoSchema(ViewInspector):
<ide>
<del> def __init__(self, tags=None):
<add> def __init__(self, operation_id_base=None, tags=None):
<add> """
<add> :param operation_id_base: user-defined name in operationId. If empty, it will be deducted from the Model/Serializer/View name.
<add> """
<ide> if tags and not all(isinstance(tag, str) for tag in tags):
<ide> raise ValueError('tags must be a list or tuple of string.')
<ide> self._tags = tags
<add> self.operation_id_base = operation_id_base
<ide> super().__init__()
<ide>
<ide> request_media_types = []
<ide> def __init__(self, tags=None):
<ide> def get_operation(self, path, method):
<ide> operation = {}
<ide>
<del> operation['operationId'] = self._get_operation_id(path, method)
<add> operation['operationId'] = self.get_operation_id(path, method)
<ide> operation['description'] = self.get_description(path, method)
<ide>
<ide> parameters = []
<ide> def get_operation(self, path, method):
<ide>
<ide> return operation
<ide>
<del> def _get_operation_id(self, path, method):
<add> def get_operation_id_base(self, path, method, action):
<ide> """
<del> Compute an operation ID from the model, serializer or view name.
<add> Compute the base part for operation ID from the model, serializer or view name.
<ide> """
<del> method_name = getattr(self.view, 'action', method.lower())
<del> if is_list_view(path, method, self.view):
<del> action = 'list'
<del> elif method_name not in self.method_mapping:
<del> action = method_name
<del> else:
<del> action = self.method_mapping[method.lower()]
<add> model = getattr(getattr(self.view, 'queryset', None), 'model', None)
<add>
<add> if self.operation_id_base is not None:
<add> name = self.operation_id_base
<ide>
<ide> # Try to deduce the ID from the view's model
<del> model = getattr(getattr(self.view, 'queryset', None), 'model', None)
<del> if model is not None:
<add> elif model is not None:
<ide> name = model.__name__
<ide>
<ide> # Try with the serializer class name
<ide> def _get_operation_id(self, path, method):
<ide> if action == 'list' and not name.endswith('s'): # listThings instead of listThing
<ide> name += 's'
<ide>
<add> return name
<add>
<add> def get_operation_id(self, path, method):
<add> """
<add> Compute an operation ID from the view type and get_operation_id_base method.
<add> """
<add> method_name = getattr(self.view, 'action', method.lower())
<add> if is_list_view(path, method, self.view):
<add> action = 'list'
<add> elif method_name not in self.method_mapping:
<add> action = method_name
<add> else:
<add> action = self.method_mapping[method.lower()]
<add>
<add> name = self.get_operation_id_base(path, method, action)
<add>
<ide> return action + name
<ide>
<ide> def _get_path_parameters(self, path, method):
<ide><path>tests/schemas/test_openapi.py
<ide> def test_operation_id_generation(self):
<ide> inspector = AutoSchema()
<ide> inspector.view = view
<ide>
<del> operationId = inspector._get_operation_id(path, method)
<add> operationId = inspector.get_operation_id(path, method)
<ide> assert operationId == 'listExamples'
<ide>
<add> def test_operation_id_custom_operation_id_base(self):
<add> path = '/'
<add> method = 'GET'
<add>
<add> view = create_view(
<add> views.ExampleGenericAPIView,
<add> method,
<add> create_request(path),
<add> )
<add> inspector = AutoSchema(operation_id_base="Ulysse")
<add> inspector.view = view
<add>
<add> operationId = inspector.get_operation_id(path, method)
<add> assert operationId == 'listUlysses'
<add>
<add> def test_operation_id_custom_name(self):
<add> path = '/'
<add> method = 'GET'
<add>
<add> view = create_view(
<add> views.ExampleGenericAPIView,
<add> method,
<add> create_request(path),
<add> )
<add> inspector = AutoSchema(operation_id_base='Ulysse')
<add> inspector.view = view
<add>
<add> operationId = inspector.get_operation_id(path, method)
<add> assert operationId == 'listUlysses'
<add>
<add> def test_operation_id_override_get(self):
<add> class CustomSchema(AutoSchema):
<add> def get_operation_id(self, path, method):
<add> return 'myCustomOperationId'
<add>
<add> path = '/'
<add> method = 'GET'
<add> view = create_view(
<add> views.ExampleGenericAPIView,
<add> method,
<add> create_request(path),
<add> )
<add> inspector = CustomSchema()
<add> inspector.view = view
<add>
<add> operationId = inspector.get_operation_id(path, method)
<add> assert operationId == 'myCustomOperationId'
<add>
<add> def test_operation_id_override_base(self):
<add> class CustomSchema(AutoSchema):
<add> def get_operation_id_base(self, path, method, action):
<add> return 'Item'
<add>
<add> path = '/'
<add> method = 'GET'
<add> view = create_view(
<add> views.ExampleGenericAPIView,
<add> method,
<add> create_request(path),
<add> )
<add> inspector = CustomSchema()
<add> inspector.view = view
<add>
<add> operationId = inspector.get_operation_id(path, method)
<add> assert operationId == 'listItem'
<add>
<ide> def test_repeat_operation_ids(self):
<ide> router = routers.SimpleRouter()
<ide> router.register('account', views.ExampleGenericViewSet, basename="account") | 3 |
Javascript | Javascript | add react-dom to bower when releasing | 353a01cf5e7dc59581298160e566e7ec8e6e73cd | <ide><path>grunt/tasks/release.js
<ide> var BOWER_GLOB = [BOWER_PATH + '*.{js}'];
<ide> var BOWER_FILES = [
<ide> 'react.js', 'react.min.js', 'JSXTransformer.js',
<ide> 'react-with-addons.js', 'react-with-addons.min.js',
<add> 'react-dom.js', 'react-dom.min.js',
<ide> ];
<ide> var GH_PAGES_PATH = '../react-gh-pages/';
<ide> var GH_PAGES_GLOB = [GH_PAGES_PATH + '*']; | 1 |
Ruby | Ruby | add some implementation docs. closes . closes | 2cb2ca68b1973ddd202b094599521e4adc39a217 | <ide><path>actionpack/lib/action_dispatch/middleware/flash.rb
<ide> def notice=(message)
<ide> end
<ide> end
<ide>
<add> # Implementation detail: please do not change the signature of the
<add> # FlashHash class. Doing that will likely affect all Rails apps in
<add> # production as the FlashHash currently stored in their sessions will
<add> # become invalid.
<ide> class FlashHash
<ide> include Enumerable
<ide> | 1 |
Ruby | Ruby | fix string#last example | 39c483fec56b98b0cdb11b705cd7e63b43d60a64 | <ide><path>activesupport/lib/active_support/core_ext/string/access.rb
<ide> def first(limit = 1)
<ide> #
<ide> # str = "hello"
<ide> # str.last #=> "o"
<del> # str.last(1) #=> "h"
<add> # str.last(1) #=> "o"
<ide> # str.last(2) #=> "lo"
<ide> # str.last(0) #=> ""
<ide> # str.last(6) #=> "hello" | 1 |
PHP | PHP | remove getfromjson from translator | 697b898a1c89881c91af83ecc4493fa681e2aa38 | <ide><path>src/Illuminate/Auth/Notifications/ResetPassword.php
<ide> public function toMail($notifiable)
<ide> }
<ide>
<ide> return (new MailMessage)
<del> ->subject(Lang::getFromJson('Reset Password Notification'))
<del> ->line(Lang::getFromJson('You are receiving this email because we received a password reset request for your account.'))
<del> ->action(Lang::getFromJson('Reset Password'), url(config('app.url').route('password.reset', ['token' => $this->token, 'email' => $notifiable->getEmailForPasswordReset()], false)))
<del> ->line(Lang::getFromJson('This password reset link will expire in :count minutes.', ['count' => config('auth.passwords.users.expire')]))
<del> ->line(Lang::getFromJson('If you did not request a password reset, no further action is required.'));
<add> ->subject(Lang::get('Reset Password Notification'))
<add> ->line(Lang::get('You are receiving this email because we received a password reset request for your account.'))
<add> ->action(Lang::get('Reset Password'), url(config('app.url').route('password.reset', ['token' => $this->token, 'email' => $notifiable->getEmailForPasswordReset()], false)))
<add> ->line(Lang::get('This password reset link will expire in :count minutes.', ['count' => config('auth.passwords.users.expire')]))
<add> ->line(Lang::get('If you did not request a password reset, no further action is required.'));
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Auth/Notifications/VerifyEmail.php
<ide> public function toMail($notifiable)
<ide> }
<ide>
<ide> return (new MailMessage)
<del> ->subject(Lang::getFromJson('Verify Email Address'))
<del> ->line(Lang::getFromJson('Please click the button below to verify your email address.'))
<del> ->action(Lang::getFromJson('Verify Email Address'), $verificationUrl)
<del> ->line(Lang::getFromJson('If you did not create an account, no further action is required.'));
<add> ->subject(Lang::get('Verify Email Address'))
<add> ->line(Lang::get('Please click the button below to verify your email address.'))
<add> ->action(Lang::get('Verify Email Address'), $verificationUrl)
<add> ->line(Lang::get('If you did not create an account, no further action is required.'));
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Foundation/helpers.php
<ide> function trans_choice($key, $number, array $replace = [], $locale = null)
<ide> /**
<ide> * Translate the given message.
<ide> *
<del> * @param string $key
<add> * @param string|null $key
<ide> * @param array $replace
<ide> * @param string|null $locale
<del> * @return string|array|null
<add> * @return \Illuminate\Contracts\Translation\Translator|string|array|null
<ide> */
<del> function __($key, $replace = [], $locale = null)
<add> function __($key = null, $replace = [], $locale = null)
<ide> {
<del> return app('translator')->getFromJson($key, $replace, $locale);
<add> return trans($key, $replace, $locale);
<ide> }
<ide> }
<ide>
<ide><path>src/Illuminate/Translation/Translator.php
<ide> public function trans($key, array $replace = [], $locale = null)
<ide> * @return string|array
<ide> */
<ide> public function get($key, array $replace = [], $locale = null, $fallback = true)
<del> {
<del> [$namespace, $group, $item] = $this->parseKey($key);
<del>
<del> // Here we will get the locale that should be used for the language line. If one
<del> // was not passed, we will use the default locales which was given to us when
<del> // the translator was instantiated. Then, we can load the lines and return.
<del> $locales = $fallback ? $this->localeArray($locale)
<del> : [$locale ?: $this->locale];
<del>
<del> foreach ($locales as $locale) {
<del> if (! is_null($line = $this->getLine(
<del> $namespace, $group, $locale, $item, $replace
<del> ))) {
<del> break;
<del> }
<del> }
<del>
<del> // If the line doesn't exist, we will return back the key which was requested as
<del> // that will be quick to spot in the UI if language keys are wrong or missing
<del> // from the application's language files. Otherwise we can return the line.
<del> return $line ?? $key;
<del> }
<del>
<del> /**
<del> * Get the translation for a given key from the JSON translation files.
<del> *
<del> * @param string $key
<del> * @param array $replace
<del> * @param string|null $locale
<del> * @return string|array
<del> */
<del> public function getFromJson($key, array $replace = [], $locale = null)
<ide> {
<ide> $locale = $locale ?: $this->locale;
<ide>
<ide> public function getFromJson($key, array $replace = [], $locale = null)
<ide> // using the typical translation file. This way developers can always just use a
<ide> // helper such as __ instead of having to pick between trans or __ with views.
<ide> if (! isset($line)) {
<del> $fallback = $this->get($key, $replace, $locale);
<del>
<del> if ($fallback !== $key) {
<del> return $fallback;
<add> [$namespace, $group, $item] = $this->parseKey($key);
<add>
<add> // Here we will get the locale that should be used for the language line. If one
<add> // was not passed, we will use the default locales which was given to us when
<add> // the translator was instantiated. Then, we can load the lines and return.
<add> $locales = $fallback ? $this->localeArray($locale) : [$locale];
<add>
<add> foreach ($locales as $locale) {
<add> if (! is_null($line = $this->getLine(
<add> $namespace, $group, $locale, $item, $replace
<add> ))) {
<add> break;
<add> }
<ide> }
<ide> }
<ide>
<add> // If the line doesn't exist, we will return back the key which was requested as
<add> // that will be quick to spot in the UI if language keys are wrong or missing
<add> // from the application's language files. Otherwise we can return the line.
<ide> return $this->makeReplacements($line ?: $key, $replace);
<ide> }
<ide>
<ide><path>src/Illuminate/View/Compilers/Concerns/CompilesTranslations.php
<ide> protected function compileLang($expression)
<ide> return "<?php \$__env->startTranslation{$expression}; ?>";
<ide> }
<ide>
<del> return "<?php echo app('translator')->getFromJson{$expression}; ?>";
<add> return "<?php echo app('translator')->get{$expression}; ?>";
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/View/Concerns/ManagesTranslations.php
<ide> public function startTranslation($replacements = [])
<ide> */
<ide> public function renderTranslation()
<ide> {
<del> return $this->container->make('translator')->getFromJson(
<add> return $this->container->make('translator')->get(
<ide> trim(ob_get_clean()), $this->translationReplacements
<ide> );
<ide> }
<ide><path>tests/Translation/TranslationTranslatorTest.php
<ide> public function testHasMethodReturnsFalseWhenReturnedTranslationIsNull()
<ide> $t->expects($this->once())->method('get')->with($this->equalTo('foo'), $this->equalTo([]), $this->equalTo('bar'), false)->will($this->returnValue('foo'));
<ide> $this->assertFalse($t->hasForLocale('foo', 'bar'));
<ide>
<del> $t = $this->getMockBuilder(Translator::class)->setMethods(['load', 'getLine'])->setConstructorArgs([$this->getLoader(), 'en'])->getMock();
<del> $t->expects($this->any())->method('load')->with($this->equalTo('*'), $this->equalTo('foo'), $this->equalTo('en'))->will($this->returnValue(null));
<del> $t->expects($this->once())->method('getLine')->with($this->equalTo('*'), $this->equalTo('foo'), $this->equalTo('en'), null, $this->equalTo([]))->will($this->returnValue('bar'));
<add> $t = new Translator($this->getLoader(), 'en');
<add> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]);
<add> $t->getLoader()->shouldReceive('load')->once()->with('en', 'foo', '*')->andReturn(['foo' => 'bar']);
<ide> $this->assertTrue($t->hasForLocale('foo'));
<ide>
<del> $t = $this->getMockBuilder(Translator::class)->setMethods(['load', 'getLine'])->setConstructorArgs([$this->getLoader(), 'en'])->getMock();
<del> $t->expects($this->any())->method('load')->with($this->equalTo('*'), $this->equalTo('foo'), $this->equalTo('en'))->will($this->returnValue(null));
<del> $t->expects($this->once())->method('getLine')->with($this->equalTo('*'), $this->equalTo('foo'), $this->equalTo('en'), null, $this->equalTo([]))->will($this->returnValue('foo'));
<add> $t = new Translator($this->getLoader(), 'en');
<add> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]);
<add> $t->getLoader()->shouldReceive('load')->once()->with('en', 'foo', '*')->andReturn([]);
<ide> $this->assertFalse($t->hasForLocale('foo'));
<ide> }
<ide>
<ide> public function testGetMethodProperlyLoadsAndRetrievesItem()
<ide> {
<ide> $t = new Translator($this->getLoader(), 'en');
<add> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]);
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', 'bar', 'foo')->andReturn(['foo' => 'foo', 'baz' => 'breeze :foo', 'qux' => ['tree :foo', 'breeze :foo']]);
<ide> $this->assertEquals(['tree bar', 'breeze bar'], $t->get('foo::bar.qux', ['foo' => 'bar'], 'en'));
<ide> $this->assertEquals('breeze bar', $t->get('foo::bar.baz', ['foo' => 'bar'], 'en'));
<ide> $this->assertEquals('foo', $t->get('foo::bar.foo'));
<ide> }
<ide>
<add> public function testGetMethodForNonExistingReturnsSameKey()
<add> {
<add> $t = new Translator($this->getLoader(), 'en');
<add> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]);
<add> $t->getLoader()->shouldReceive('load')->once()->with('en', 'bar', 'foo')->andReturn(['foo' => 'foo', 'baz' => 'breeze :foo', 'qux' => ['tree :foo', 'breeze :foo']]);
<add> $t->getLoader()->shouldReceive('load')->once()->with('en', 'unknown', 'foo')->andReturn([]);
<add> $this->assertEquals('foo::unknown', $t->get('foo::unknown', ['foo' => 'bar'], 'en'));
<add> $this->assertEquals('foo::bar.unknown', $t->get('foo::bar.unknown', ['foo' => 'bar'], 'en'));
<add> $this->assertEquals('foo::unknown.bar', $t->get('foo::unknown.bar'));
<add> }
<add>
<ide> public function testTransMethodProperlyLoadsAndRetrievesItemWithHTMLInTheMessage()
<ide> {
<ide> $t = new Translator($this->getLoader(), 'en');
<add> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]);
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', 'foo', '*')->andReturn(['bar' => 'breeze <p>test</p>']);
<ide> $this->assertSame('breeze <p>test</p>', $t->trans('foo.bar', [], 'en'));
<ide> }
<ide>
<ide> public function testGetMethodProperlyLoadsAndRetrievesItemWithCapitalization()
<ide> {
<ide> $t = $this->getMockBuilder(Translator::class)->setMethods(null)->setConstructorArgs([$this->getLoader(), 'en'])->getMock();
<add> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]);
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', 'bar', 'foo')->andReturn(['foo' => 'foo', 'baz' => 'breeze :Foo :BAR']);
<ide> $this->assertEquals('breeze Bar FOO', $t->get('foo::bar.baz', ['foo' => 'bar', 'bar' => 'foo'], 'en'));
<ide> $this->assertEquals('foo', $t->get('foo::bar.foo'));
<ide> public function testGetMethodProperlyLoadsAndRetrievesItemWithCapitalization()
<ide> public function testGetMethodProperlyLoadsAndRetrievesItemWithLongestReplacementsFirst()
<ide> {
<ide> $t = new Translator($this->getLoader(), 'en');
<add> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]);
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', 'bar', 'foo')->andReturn(['foo' => 'foo', 'baz' => 'breeze :foo :foobar']);
<ide> $this->assertEquals('breeze bar taylor', $t->get('foo::bar.baz', ['foo' => 'bar', 'foobar' => 'taylor'], 'en'));
<ide> $this->assertEquals('breeze foo bar baz taylor', $t->get('foo::bar.baz', ['foo' => 'foo bar baz', 'foobar' => 'taylor'], 'en'));
<ide> public function testGetMethodProperlyLoadsAndRetrievesItemForFallback()
<ide> {
<ide> $t = new Translator($this->getLoader(), 'en');
<ide> $t->setFallback('lv');
<add> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]);
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', 'bar', 'foo')->andReturn([]);
<ide> $t->getLoader()->shouldReceive('load')->once()->with('lv', 'bar', 'foo')->andReturn(['foo' => 'foo', 'baz' => 'breeze :foo']);
<ide> $this->assertEquals('breeze bar', $t->get('foo::bar.baz', ['foo' => 'bar'], 'en'));
<ide> public function testGetMethodProperlyLoadsAndRetrievesItemForFallback()
<ide> public function testGetMethodProperlyLoadsAndRetrievesItemForGlobalNamespace()
<ide> {
<ide> $t = new Translator($this->getLoader(), 'en');
<add> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]);
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', 'foo', '*')->andReturn(['bar' => 'breeze :foo']);
<ide> $this->assertEquals('breeze bar', $t->get('foo.bar', ['foo' => 'bar']));
<ide> }
<ide> public function testChoiceMethodProperlyCountsCollectionsAndLoadsAndRetrievesIte
<ide> $t->choice('foo', $values, ['replace']);
<ide> }
<ide>
<del> public function testGetJsonMethod()
<add> public function testGetJson()
<ide> {
<ide> $t = new Translator($this->getLoader(), 'en');
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn(['foo' => 'one']);
<del> $this->assertEquals('one', $t->getFromJson('foo'));
<add> $this->assertEquals('one', $t->get('foo'));
<ide> }
<ide>
<ide> public function testGetJsonReplaces()
<ide> {
<ide> $t = new Translator($this->getLoader(), 'en');
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn(['foo :i:c :u' => 'bar :i:c :u']);
<del> $this->assertEquals('bar onetwo three', $t->getFromJson('foo :i:c :u', ['i' => 'one', 'c' => 'two', 'u' => 'three']));
<add> $this->assertEquals('bar onetwo three', $t->get('foo :i:c :u', ['i' => 'one', 'c' => 'two', 'u' => 'three']));
<ide> }
<ide>
<ide> public function testGetJsonReplacesForAssociativeInput()
<ide> {
<ide> $t = new Translator($this->getLoader(), 'en');
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn(['foo :i :c' => 'bar :i :c']);
<del> $this->assertEquals('bar eye see', $t->getFromJson('foo :i :c', ['i' => 'eye', 'c' => 'see']));
<add> $this->assertEquals('bar eye see', $t->get('foo :i :c', ['i' => 'eye', 'c' => 'see']));
<ide> }
<ide>
<ide> public function testGetJsonPreservesOrder()
<ide> {
<ide> $t = new Translator($this->getLoader(), 'en');
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn(['to :name I give :greeting' => ':greeting :name']);
<del> $this->assertEquals('Greetings David', $t->getFromJson('to :name I give :greeting', ['name' => 'David', 'greeting' => 'Greetings']));
<add> $this->assertEquals('Greetings David', $t->get('to :name I give :greeting', ['name' => 'David', 'greeting' => 'Greetings']));
<ide> }
<ide>
<ide> public function testGetJsonForNonExistingJsonKeyLooksForRegularKeys()
<ide> {
<ide> $t = new Translator($this->getLoader(), 'en');
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]);
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', 'foo', '*')->andReturn(['bar' => 'one']);
<del> $this->assertEquals('one', $t->getFromJson('foo.bar'));
<add> $this->assertEquals('one', $t->get('foo.bar'));
<ide> }
<ide>
<ide> public function testGetJsonForNonExistingJsonKeyLooksForRegularKeysAndReplace()
<ide> {
<ide> $t = new Translator($this->getLoader(), 'en');
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]);
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', 'foo', '*')->andReturn(['bar' => 'one :message']);
<del> $this->assertEquals('one two', $t->getFromJson('foo.bar', ['message' => 'two']));
<add> $this->assertEquals('one two', $t->get('foo.bar', ['message' => 'two']));
<ide> }
<ide>
<ide> public function testGetJsonForNonExistingReturnsSameKey()
<ide> {
<ide> $t = new Translator($this->getLoader(), 'en');
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]);
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', 'Foo that bar', '*')->andReturn([]);
<del> $this->assertEquals('Foo that bar', $t->getFromJson('Foo that bar'));
<add> $this->assertEquals('Foo that bar', $t->get('Foo that bar'));
<ide> }
<ide>
<ide> public function testGetJsonForNonExistingReturnsSameKeyAndReplaces()
<ide> {
<ide> $t = new Translator($this->getLoader(), 'en');
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]);
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', 'foo :message', '*')->andReturn([]);
<del> $this->assertEquals('foo baz', $t->getFromJson('foo :message', ['message' => 'baz']));
<add> $this->assertEquals('foo baz', $t->get('foo :message', ['message' => 'baz']));
<ide> }
<ide>
<ide> protected function getLoader()
<ide><path>tests/View/Blade/BladeExpressionTest.php
<ide> class BladeExpressionTest extends AbstractBladeTestCase
<ide> {
<ide> public function testExpressionsOnTheSameLine()
<ide> {
<del> $this->assertEquals('<?php echo app(\'translator\')->getFromJson(foo(bar(baz(qux(breeze()))))); ?> space () <?php echo app(\'translator\')->getFromJson(foo(bar)); ?>', $this->compiler->compileString('@lang(foo(bar(baz(qux(breeze()))))) space () @lang(foo(bar))'));
<add> $this->assertEquals('<?php echo app(\'translator\')->get(foo(bar(baz(qux(breeze()))))); ?> space () <?php echo app(\'translator\')->get(foo(bar)); ?>', $this->compiler->compileString('@lang(foo(bar(baz(qux(breeze()))))) space () @lang(foo(bar))'));
<ide> }
<ide>
<ide> public function testExpressionWithinHTML()
<ide> {
<ide> $this->assertEquals('<html <?php echo e($foo); ?>>', $this->compiler->compileString('<html {{ $foo }}>'));
<ide> $this->assertEquals('<html<?php echo e($foo); ?>>', $this->compiler->compileString('<html{{ $foo }}>'));
<del> $this->assertEquals('<html <?php echo e($foo); ?> <?php echo app(\'translator\')->getFromJson(\'foo\'); ?>>', $this->compiler->compileString('<html {{ $foo }} @lang(\'foo\')>'));
<add> $this->assertEquals('<html <?php echo e($foo); ?> <?php echo app(\'translator\')->get(\'foo\'); ?>>', $this->compiler->compileString('<html {{ $foo }} @lang(\'foo\')>'));
<ide> }
<ide> }
<ide><path>tests/View/Blade/BladeLangTest.php
<ide> class BladeLangTest extends AbstractBladeTestCase
<ide> public function testStatementThatContainsNonConsecutiveParenthesisAreCompiled()
<ide> {
<ide> $string = "Foo @lang(function_call('foo(blah)')) bar";
<del> $expected = "Foo <?php echo app('translator')->getFromJson(function_call('foo(blah)')); ?> bar";
<add> $expected = "Foo <?php echo app('translator')->get(function_call('foo(blah)')); ?> bar";
<ide> $this->assertEquals($expected, $this->compiler->compileString($string));
<ide> }
<ide>
<ide> public function testLanguageAndChoicesAreCompiled()
<ide> {
<del> $this->assertEquals('<?php echo app(\'translator\')->getFromJson(\'foo\'); ?>', $this->compiler->compileString("@lang('foo')"));
<add> $this->assertEquals('<?php echo app(\'translator\')->get(\'foo\'); ?>', $this->compiler->compileString("@lang('foo')"));
<ide> $this->assertEquals('<?php echo app(\'translator\')->choice(\'foo\', 1); ?>', $this->compiler->compileString("@choice('foo', 1)"));
<ide> }
<ide> }
<ide><path>tests/View/ViewFactoryTest.php
<ide> public function testTranslation()
<ide> {
<ide> $container = new Container;
<ide> $container->instance('translator', $translator = m::mock(stdClass::class));
<del> $translator->shouldReceive('getFromJson')->with('Foo', ['name' => 'taylor'])->andReturn('Bar');
<add> $translator->shouldReceive('get')->with('Foo', ['name' => 'taylor'])->andReturn('Bar');
<ide> $factory = $this->getFactory();
<ide> $factory->setContainer($container);
<ide> $factory->startTranslation(['name' => 'taylor']); | 10 |
PHP | PHP | remove route dependency from url generator api | 3d4cfbcfc0f1f06b3127504761ddd5b418f0d29a | <ide><path>src/Illuminate/Contracts/Routing/UrlGenerator.php
<ide> public function asset($path, $secure = null);
<ide> * @param string $name
<ide> * @param mixed $parameters
<ide> * @param bool $absolute
<del> * @param \Illuminate\Routing\Route $route
<ide> * @return string
<ide> *
<ide> * @throws \InvalidArgumentException
<ide> */
<del> public function route($name, $parameters = array(), $absolute = true, $route = null);
<add> public function route($name, $parameters = array(), $absolute = true);
<ide>
<ide> /**
<ide> * Get the URL to a controller action.
<ide> *
<ide> * @param string $action
<del> * @param mixed $parameters
<del> * @param bool $absolute
<add> * @param mixed $parameters
<add> * @param bool $absolute
<ide> * @return string
<ide> */
<ide> public function action($action, $parameters = array(), $absolute = true);
<ide><path>src/Illuminate/Routing/UrlGenerator.php
<ide> public function forceSchema($schema)
<ide> * @param string $name
<ide> * @param mixed $parameters
<ide> * @param bool $absolute
<del> * @param \Illuminate\Routing\Route $route
<ide> * @return string
<ide> *
<ide> * @throws \InvalidArgumentException
<ide> */
<del> public function route($name, $parameters = array(), $absolute = true, $route = null)
<add> public function route($name, $parameters = array(), $absolute = true)
<ide> {
<del> $route = $route ?: $this->routes->getByName($name);
<del>
<del> $parameters = $this->formatParameters($parameters);
<del>
<del> if ( ! is_null($route))
<add> if ( ! is_null($route = $this->routes->getByName($name)))
<ide> {
<ide> return $this->toRoute($route, $parameters, $absolute);
<ide> }
<ide> public function route($name, $parameters = array(), $absolute = true, $route = n
<ide> */
<ide> protected function toRoute($route, array $parameters, $absolute)
<ide> {
<add> $parameters = $this->formatParameters($parameters);
<add>
<ide> $domain = $this->getRouteDomain($route, $parameters);
<ide>
<ide> $uri = strtr(rawurlencode($this->trimUrl(
<ide> public function action($action, $parameters = array(), $absolute = true)
<ide> $action = trim($action, '\\');
<ide> }
<ide>
<del> return $this->route($action, $parameters, $absolute, $this->routes->getByAction($action));
<add> return $this->toRoute($this->routes->getByAction($action), $parameters, $absolute);
<ide> }
<ide>
<ide> /** | 2 |
Python | Python | fix incorrect module name | e46ca53e175ec800f1f2267f5d769dc38e9d31be | <ide><path>keras/optimizers/schedules/__init__.py
<ide> # ==============================================================================
<ide> """Learning rate schedule API."""
<ide>
<del>from keras.optimizers.schedules.learning_rate_schedules import ExponentialDecay
<del>from keras.optimizers.schedules.learning_rate_schedules import InverseTimeDecay
<del>from keras.optimizers.schedules.learning_rate_schedules import (
<add>from keras.optimizers.schedules.learning_rate_schedule import ExponentialDecay
<add>from keras.optimizers.schedules.learning_rate_schedule import InverseTimeDecay
<add>from keras.optimizers.schedules.learning_rate_schedule import (
<ide> PiecewiseConstantDecay,
<ide> )
<del>from keras.optimizers.schedules.learning_rate_schedules import PolynomialDecay
<add>from keras.optimizers.schedules.learning_rate_schedule import PolynomialDecay | 1 |
Text | Text | fix typos (docs/animations) | 7c36138caa0b550ac9471d0a7b555923ce63f69a | <ide><path>docs/Animations.md
<ide> use this.
<ide>
<ide>  Screenshot from
<ide> [react-native-scrollable-tab-view](https://github.com/brentvatne/react-native-scrollable-tab-view).
<del>You can run a simlar example [here](https://rnplay.org/apps/qHU_5w).
<add>You can run a similar example [here](https://rnplay.org/apps/qHU_5w).
<ide>
<ide> #### A sidenote about setNativeProps
<ide>
<ide> var CustomLeftToRightGesture = Object.assign({}, BaseConfig.gestures.pop, {
<ide> });
<ide>
<ide> var CustomSceneConfig = Object.assign({}, BaseConfig, {
<del> // A very tighly wound spring will make this transition fast
<add> // A very tightly wound spring will make this transition fast
<ide> springTension: 100,
<ide> springFriction: 1,
<ide> | 1 |
Python | Python | fix merge issue #480 | 8d553d3fcb5f00e78e77236d47013b55c818d498 | <ide><path>glances/plugins/glances_help.py
<ide> def generate_view_data(self):
<ide> self.view_data['psutil_version'] = ' with PSutil {0}'.format(psutil_version)
<ide>
<ide> try:
<del> self.view_data['configuration_file'] = '{0}: {1}'.format('Configuration file', self.config.get_loaded_config_file())
<add> self.view_data['configuration_file'] = 'Configuration file: {0}'.format(self.config.loaded_config_file)
<ide> except AttributeError:
<ide> pass
<ide> | 1 |
Python | Python | fix logic order for use_tf/use_torch | faef6f6191a8d319b541396a0f850c3d6f15f5d4 | <ide><path>transformers/file_utils.py
<ide> try:
<ide> os.environ.setdefault('USE_TF', 'YES')
<ide> if os.environ['USE_TF'].upper() in ('1', 'ON', 'YES'):
<del> logger.info("USE_TF override through env variable, disabling Tensorflow")
<del> _tf_available = False
<del> else:
<ide> import tensorflow as tf
<ide> assert hasattr(tf, '__version__') and int(tf.__version__[0]) >= 2
<ide> _tf_available = True # pylint: disable=invalid-name
<ide> logger.info("TensorFlow version {} available.".format(tf.__version__))
<add> else:
<add> logger.info("USE_TF override through env variable, disabling Tensorflow")
<add> _tf_available = False
<add>
<ide> except (ImportError, AssertionError):
<ide> _tf_available = False # pylint: disable=invalid-name
<ide>
<ide> try:
<ide> os.environ.setdefault('USE_TORCH', 'YES')
<ide> if os.environ['USE_TORCH'].upper() in ('1', 'ON', 'YES'):
<del> logger.info("USE_TORCH override through env variable, disabling PyTorch")
<del> _torch_available = False
<del> else:
<ide> import torch
<ide> _torch_available = True # pylint: disable=invalid-name
<ide> logger.info("PyTorch version {} available.".format(torch.__version__))
<add>
<add> else:
<add> logger.info("USE_TORCH override through env variable, disabling PyTorch")
<add> _torch_available = False
<ide> except ImportError:
<ide> _torch_available = False # pylint: disable=invalid-name
<ide> | 1 |
Java | Java | add @reactmodule annotation | 0561336ae4f2e9bd9d418c18b30bc32951f2c2ac | <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/BaseJavaModule.java
<ide>
<ide> package com.facebook.react.bridge;
<ide>
<add>import com.facebook.common.logging.FLog;
<ide> import com.facebook.infer.annotation.Assertions;
<add>import com.facebook.react.bridge.annotations.ReactModule;
<add>import com.facebook.react.common.ReactConstants;
<ide> import com.facebook.systrace.Systrace;
<ide> import com.facebook.systrace.SystraceMessage;
<ide>
<ide> public final void writeConstantsField(JsonWriter writer, String fieldName) throw
<ide> writer.endObject();
<ide> }
<ide>
<add> @Override
<add> public String getName() {
<add> ReactModule module = getClass().getAnnotation(ReactModule.class);
<add> if (module == null) {
<add> throw new IllegalStateException(
<add> getClass().getSimpleName() +
<add> "module must have @ReactModule annotation or override getName()");
<add> }
<add> return module.name();
<add> }
<add>
<ide> @Override
<ide> public void initialize() {
<ide> // do nothing
<ide> }
<ide>
<ide> @Override
<ide> public boolean canOverrideExistingModule() {
<add> // TODO(t11394819): Make this final and use annotation
<ide> return false;
<ide> }
<ide>
<ide> public void onCatalystInstanceDestroy() {
<ide>
<ide> @Override
<ide> public boolean supportsWebWorkers() {
<del> return false;
<add> ReactModule module = getClass().getAnnotation(ReactModule.class);
<add> if (module == null) {
<add> FLog.w(
<add> ReactConstants.TAG,
<add> "Module " + getName() +
<add> " lacks @ReactModule annotation, assuming false for supportsWebWorkers()");
<add> return false;
<add> }
<add> return module.supportsWebWorkers();
<ide> }
<ide>
<ide> private static char paramTypeToChar(Class paramClass) {
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/annotations/ReactModule.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.bridge.annotations;
<add>
<add>import java.lang.annotation.Retention;
<add>import java.lang.annotation.Target;
<add>
<add>import com.facebook.react.bridge.BaseJavaModule;
<add>import com.facebook.react.bridge.ExecutorToken;
<add>import com.facebook.react.bridge.ReactContext;
<add>
<add>import static java.lang.annotation.ElementType.TYPE;
<add>import static java.lang.annotation.RetentionPolicy.RUNTIME;
<add>
<add>/**
<add> * Annotation for use on {@link BaseJavaModule}s to describe properties for that module.
<add> */
<add>@Retention(RUNTIME)
<add>@Target(TYPE)
<add>public @interface ReactModule {
<add> /**
<add> * Name used to {@code require()} this module from JavaScript.
<add> */
<add> String name();
<add>
<add> /**
<add> * True if you intend to override some other native module that was registered e.g. as part
<add> * of a different package (such as the core one). Trying to override without returning true from
<add> * this method is considered an error and will throw an exception during initialization. By
<add> * default all modules return false.
<add> */
<add> boolean canOverrideExistingModule() default false;
<add>
<add> /**
<add> * In order to support web workers, a module must be aware that it can be invoked from multiple
<add> * different JS VMs. Supporting web workers means recognizing things like:
<add> *
<add> * 1) ids (e.g. timer ids, request ids, etc.) may only unique on a per-VM basis
<add> * 2) the module needs to make sure to enqueue callbacks and JS module calls to the correct VM
<add> *
<add> * In order to facilitate this, modules that support web workers will have all their @ReactMethod-
<add> * annotated methods passed a {@link ExecutorToken} as the first parameter before any arguments
<add> * from JS. This ExecutorToken internally maps to a specific JS VM and can be used by the
<add> * framework to route calls appropriately. In order to make JS module calls correctly, start using
<add> * the version of {@link ReactContext#getJSModule(ExecutorToken, Class)} that takes an
<add> * ExecutorToken. It will ensure that any calls you dispatch to the returned object will go to
<add> * the right VM. For Callbacks, you don't have to do anything special -- the framework
<add> * automatically tags them with the correct ExecutorToken when the are created.
<add> *
<add> * Note: even though calls can come from multiple JS VMs on multiple threads, calls to this module
<add> * will still only occur on a single thread.
<add> *
<add> * @return whether this module supports web workers.
<add> */
<add> boolean supportsWebWorkers() default false;
<add>
<add> /**
<add> * Whether this module needs to be loaded immediately.
<add> */
<add> boolean needsEagerInit() default false;
<add>} | 2 |
Java | Java | add databufferutils.matcher and split | f747ba282aea2f7c542e4a59ef6b30f9016325c5 | <ide><path>spring-core/src/main/java/org/springframework/core/io/buffer/DataBufferUtils.java
<ide> import java.nio.channels.ReadableByteChannel;
<ide> import java.nio.channels.WritableByteChannel;
<ide> import java.nio.file.StandardOpenOption;
<add>import java.util.ArrayList;
<add>import java.util.Arrays;
<add>import java.util.List;
<ide> import java.util.concurrent.Callable;
<ide> import java.util.concurrent.atomic.AtomicBoolean;
<ide> import java.util.concurrent.atomic.AtomicLong;
<ide> public abstract class DataBufferUtils {
<ide>
<ide> private static final Consumer<DataBuffer> RELEASE_CONSUMER = DataBufferUtils::release;
<ide>
<add> private static final DataBuffer END_FRAME = new DefaultDataBufferFactory().wrap(new byte[0]);
<add>
<ide>
<ide> //---------------------------------------------------------------------
<ide> // Reading
<ide> public static Mono<DataBuffer> join(Publisher<DataBuffer> dataBuffers) {
<ide> .filter(list -> !list.isEmpty())
<ide> .map(list -> list.get(0).factory().join(list))
<ide> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
<add> }
<add>
<add> /**
<add> * Return a {@link Matcher} for the given delimiters. The matcher can be used to find the
<add> * delimiters in data buffers.
<add> * @param delimiter the delimiter bytes to find
<add> * @return the matcher
<add> * @since 5.2
<add> */
<add> public static Matcher matcher(byte[] delimiter) {
<add> Assert.isTrue(delimiter.length > 0, "Delimiter must not be empty");
<add> return new KnuthMorrisPrattMatcher(delimiter);
<add> }
<add>
<add> /**
<add> * Splits the given stream of data buffers around the given delimiter.
<add> * The returned flux contains data buffers that are terminated by the given delimiter,
<add> * though the delimiter itself is removed.
<add> * @param dataBuffers the input stream of data buffers
<add> * @param delimiter the delimiting byte array
<add> * @return the flux of data buffers created by splitting the given data buffers around the
<add> * given delimiter
<add> * @since 5.2
<add> */
<add> public static Flux<DataBuffer> split(Publisher<DataBuffer> dataBuffers, byte[] delimiter) {
<add> return split(dataBuffers, delimiter, true);
<add> }
<add>
<add> /**
<add> * Splits the given stream of data buffers around the given delimiter.
<add> * The returned flux contains data buffers that are terminated by the given delimiter,
<add> * which is included when {@code stripDelimiter} is {@code true}, or stripped off when
<add> * {@code false}.
<add> * @param dataBuffers the input stream of data buffers
<add> * @param delimiter the delimiting byte array
<add> * @param stripDelimiter whether to include the delimiter at the end of each resulting buffer
<add> * @return the flux of data buffers created by splitting the given data buffers around the
<add> * given delimiter
<add> * @since 5.2
<add> */
<add> public static Flux<DataBuffer> split(Publisher<DataBuffer> dataBuffers, byte[] delimiter,
<add> boolean stripDelimiter) {
<add> Assert.notNull(dataBuffers, "DataBuffers must not be null");
<add> Assert.isTrue(delimiter.length > 0, "Delimiter must not be empty");
<add>
<add> Matcher matcher = matcher(delimiter);
<add> return Flux.from(dataBuffers)
<add> .flatMap(buffer -> endFrameOnDelimiter(buffer, matcher))
<add> .bufferUntil(buffer -> buffer == END_FRAME)
<add> .map(buffers -> joinAndStrip(buffers, delimiter, stripDelimiter))
<add> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
<add> }
<add>
<add> // Return Flux, because returning List (w/ flatMapIterable) results in memory leaks because
<add> // of pre-fetching.
<add> private static Flux<DataBuffer> endFrameOnDelimiter(DataBuffer dataBuffer, Matcher matcher) {
<add> List<DataBuffer> result = new ArrayList<>();
<add> do {
<add> int endIdx = matcher.match(dataBuffer);
<add> int readPosition = dataBuffer.readPosition();
<add> if (endIdx != -1) {
<add> int length = endIdx + 1 - readPosition ;
<add> result.add(dataBuffer.retainedSlice(readPosition, length));
<add> result.add(END_FRAME);
<add> dataBuffer.readPosition(endIdx + 1);
<add> }
<add> else {
<add> result.add(retain(dataBuffer));
<add> break;
<add> }
<add> }
<add> while (dataBuffer.readableByteCount() > 0);
<add>
<add> DataBufferUtils.release(dataBuffer);
<add> return Flux.fromIterable(result);
<add> }
<add>
<add> private static DataBuffer joinAndStrip(List<DataBuffer> dataBuffers, byte[] delimiter,
<add> boolean stripDelimiter) {
<add>
<add> Assert.state(!dataBuffers.isEmpty(), "DataBuffers should not be empty");
<add>
<add> boolean endFrameFound = false;
<add> int lastIdx = dataBuffers.size() - 1;
<add> if (dataBuffers.get(lastIdx) == END_FRAME) {
<add> endFrameFound = true;
<add> dataBuffers.remove(lastIdx);
<add> }
<add>
<add> DataBuffer result = dataBuffers.get(0).factory().join(dataBuffers);
<add> if (stripDelimiter && endFrameFound) {
<add> result.writePosition(result.writePosition() - delimiter.length);
<add> }
<add> return result;
<add> }
<add>
<add>
<add> /**
<add> * Defines an object that matches a data buffer against a delimiter.
<add> * @since 5.2
<add> * @see #match(DataBuffer)
<add> */
<add> public interface Matcher {
<add>
<add> /**
<add> * Returns the position of the final matching delimiter byte that matches the given buffer,
<add> * or {@code -1} if not found.
<add> * @param dataBuffer the buffer in which to search for the delimiter
<add> * @return the position of the final matching delimiter, or {@code -1} if not found.
<add> */
<add> int match(DataBuffer dataBuffer);
<add>
<add> /**
<add> * Return the delimiter used for this matcher.
<add> * @return the delimiter
<add> */
<add> byte[] delimiter();
<ide>
<ide> }
<ide>
<ide> private void sinkDataBuffer() {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Implementation of {@link Matcher} that uses the Knuth-Morris-Pratt algorithm.
<add> *
<add> * @see <a href="https://www.nayuki.io/page/knuth-morris-pratt-string-matching">Knuth-Morris-Pratt string matching</a>
<add> */
<add> private static class KnuthMorrisPrattMatcher implements Matcher {
<add>
<add> private final byte[] delimiter;
<add>
<add> private final int[] table;
<add>
<add> private int matches = 0;
<add>
<add>
<add> public KnuthMorrisPrattMatcher(byte[] delimiter) {
<add> this.delimiter = Arrays.copyOf(delimiter, delimiter.length);
<add> this.table = longestSuffixPrefixTable(delimiter);
<add> }
<add>
<add> private static int[] longestSuffixPrefixTable(byte[] delimiter) {
<add> int[] result = new int[delimiter.length];
<add> result[0] = 0;
<add> for (int i = 1; i < delimiter.length; i++) {
<add> int j = result[i - 1];
<add> while (j > 0 && delimiter[i] != delimiter[j]) {
<add> j = result[j - 1];
<add> }
<add> if (delimiter[i] == delimiter[j]) {
<add> j++;
<add> }
<add> result[i] = j;
<add> }
<add> return result;
<add> }
<add>
<add> @Override
<add> public int match(DataBuffer dataBuffer) {
<add> for (int i = dataBuffer.readPosition(); i < dataBuffer.writePosition(); i++) {
<add> byte b = dataBuffer.getByte(i);
<add>
<add> while (this.matches > 0 && b != this.delimiter[this.matches]) {
<add> this.matches = this.table[this.matches - 1];
<add> }
<add>
<add> if (b == this.delimiter[this.matches]) {
<add> this.matches++;
<add> if (this.matches == this.delimiter.length) {
<add> this.matches = 0;
<add> return i;
<add> }
<add> }
<add> }
<add> return -1;
<add> }
<add>
<add> public void reset() {
<add> this.matches = 0;
<add> }
<add>
<add> @Override
<add> public byte[] delimiter() {
<add> return Arrays.copyOf(this.delimiter, this.delimiter.length);
<add> }
<add> }
<add>
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java
<ide> import org.springframework.core.io.buffer.support.DataBufferTestUtils;
<ide>
<ide> import static org.junit.Assert.*;
<del>import static org.mockito.ArgumentMatchers.*;
<del>import static org.mockito.Mockito.anyLong;
<del>import static org.mockito.Mockito.isA;
<add>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> /**
<ide> public void joinCanceled() {
<ide> .verify();
<ide> }
<ide>
<add> @Test
<add> public void matcher() {
<add> DataBuffer foo = stringBuffer("foo");
<add> DataBuffer bar = stringBuffer("bar");
<add>
<add> byte[] delims = "ooba".getBytes(StandardCharsets.UTF_8);
<add> DataBufferUtils.Matcher matcher = DataBufferUtils.matcher(delims);
<add> int result = matcher.match(foo);
<add> assertEquals(-1, result);
<add> result = matcher.match(bar);
<add> assertEquals(1, result);
<add>
<add>
<add> release(foo, bar);
<add> }
<add>
<add> @Test
<add> public void matcher2() {
<add> DataBuffer foo = stringBuffer("fooobar");
<add>
<add> byte[] delims = "oo".getBytes(StandardCharsets.UTF_8);
<add> DataBufferUtils.Matcher matcher = DataBufferUtils.matcher(delims);
<add> int result = matcher.match(foo);
<add> assertEquals(2, result);
<add> foo.readPosition(2);
<add> result = matcher.match(foo);
<add> assertEquals(3, result);
<add> foo.readPosition(3);
<add> result = matcher.match(foo);
<add> assertEquals(-1, result);
<add>
<add> release(foo);
<add> }
<add>
<add> @Test
<add> public void split() {
<add> Mono<DataBuffer> source =
<add> deferStringBuffer("--foo--bar--baz--");
<add>
<add> byte[] delimiter = "--".getBytes(StandardCharsets.UTF_8);
<add>
<add> Flux<DataBuffer> result = DataBufferUtils.split(source, delimiter);
<add>
<add> StepVerifier.create(result)
<add> .consumeNextWith(stringConsumer(""))
<add> .consumeNextWith(stringConsumer("foo"))
<add> .consumeNextWith(stringConsumer("bar"))
<add> .consumeNextWith(stringConsumer("baz"))
<add> .verifyComplete();
<add> }
<add>
<add> @Test
<add> public void splitIncludeDelimiter() {
<add> Mono<DataBuffer> source =
<add> deferStringBuffer("--foo--bar--baz--");
<add>
<add> byte[] delimiter = "--".getBytes(StandardCharsets.UTF_8);
<add>
<add> Flux<DataBuffer> result = DataBufferUtils.split(source, delimiter, false);
<add>
<add> StepVerifier.create(result)
<add> .consumeNextWith(stringConsumer("--"))
<add> .consumeNextWith(stringConsumer("foo--"))
<add> .consumeNextWith(stringConsumer("bar--"))
<add> .consumeNextWith(stringConsumer("baz--"))
<add> .verifyComplete();
<add> }
<add>
<add> @Test
<add> public void splitErrors() {
<add> Flux<DataBuffer> source = Flux.concat(
<add> deferStringBuffer("foo--"),
<add> deferStringBuffer("bar--"),
<add> Mono.error(new RuntimeException())
<add> );
<add> byte[] delimiter = "--".getBytes(StandardCharsets.UTF_8);
<add>
<add> Flux<DataBuffer> result = DataBufferUtils.split(source, delimiter);
<add>
<add> StepVerifier.create(result)
<add> .consumeNextWith(stringConsumer("foo"))
<add> .consumeNextWith(stringConsumer("bar"))
<add> .expectError(RuntimeException.class)
<add> .verify();
<add> }
<add>
<add> @Test
<add> public void splitCanceled() {
<add> Flux<DataBuffer> source = Flux.concat(
<add> deferStringBuffer("foo--"),
<add> deferStringBuffer("bar--"),
<add> deferStringBuffer("baz")
<add> );
<add> byte[] delimiter = "--".getBytes(StandardCharsets.UTF_8);
<add>
<add> Flux<DataBuffer> result = DataBufferUtils.split(source, delimiter);
<add>
<add> StepVerifier.create(result)
<add> .thenCancel()
<add> .verify();
<add> }
<add>
<add>
<add> @Test
<add> public void splitWithoutDemand() {
<add> Flux<DataBuffer> source = Flux.concat(
<add> deferStringBuffer("foo--"),
<add> deferStringBuffer("bar--")
<add> );
<add> byte[] delimiter = "--".getBytes(StandardCharsets.UTF_8);
<add>
<add> Flux<DataBuffer> result = DataBufferUtils.split(source, delimiter);
<add>
<add> BaseSubscriber<DataBuffer> subscriber = new ZeroDemandSubscriber();
<add> result.subscribe(subscriber);
<add> subscriber.cancel();
<add> }
<add>
<add> @Test
<add> public void splitAcrossBuffer() {
<add> Flux<DataBuffer> source = Flux.concat(
<add> deferStringBuffer("foo-"),
<add> deferStringBuffer("-bar-"),
<add> deferStringBuffer("-baz"));
<add>
<add> byte[] delimiter = "--".getBytes(StandardCharsets.UTF_8);
<add>
<add> Flux<DataBuffer> result = DataBufferUtils.split(source, delimiter);
<add>
<add> StepVerifier.create(result)
<add> .consumeNextWith(stringConsumer("foo"))
<add> .consumeNextWith(stringConsumer("bar"))
<add> .consumeNextWith(stringConsumer("baz"))
<add> .verifyComplete();
<add> }
<add>
<ide>
<ide> private static class ZeroDemandSubscriber extends BaseSubscriber<DataBuffer> {
<ide> | 2 |
Text | Text | add google drawings as an svg tool | 847a561fbdc1f7d44527a0dcf2caeed3c7ebc9ad | <ide><path>guide/english/svg/index.md
<ide> There are a few tools available to create SVG in the form of a drawing program.
<ide>
<ide> - <a href='https://www.inkscape.org/' target='_blank' rel='nofollow'>Inkscape</a> - It is an open source tool for state-of-the-art vector drawing with an easy to use graphical interface.
<ide> - <a href='https://www.adobe.com/products/illustrator/' target='_blank' rel='nofollow'>Adobe Illustrator</a> - Adobe Illustrator is a commercial tool for Vector Imagery.
<add>- <a href='https://docs.google.com/drawings' target='_blank' rel='nofollow'>Google Drawings</a> - Google Drawings is a simple web based software allowing you to export your vectors as SVGs.
<ide>
<ide> For more tools, refer to <a href='https://www.w3.org/Graphics/SVG/WG/wiki/Implementations' target='_blank' rel='nofollow'>W3C list of tools that supports SVG</a>
<ide> | 1 |
Javascript | Javascript | move initialization of uniqueprefix higher | 13b88a07e08fffbfb8fc1184a793d313917db65e | <ide><path>src/evaluator.js
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> var self = this;
<ide> var xref = this.xref;
<ide> var handler = this.handler;
<del> var uniquePrefix = this.uniquePrefix;
<add> var uniquePrefix = this.uniquePrefix || '';
<ide>
<ide> function insertDependency(depList) {
<ide> fnArray.push('dependency');
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> }, handler, xref, resources, image, inline);
<ide> }
<ide>
<del> uniquePrefix = uniquePrefix || '';
<ide> if (!queue.argsArray) {
<ide> queue.argsArray = [];
<ide> } | 1 |
Javascript | Javascript | handle `error` events with `_tlserror` | d33c4bf97b68dbae83a1d456f7b34a91b1583666 | <ide><path>lib/_tls_wrap.js
<ide> function TLSSocket(socket, options) {
<ide> // Proxy for API compatibility
<ide> this.ssl = this._handle;
<ide>
<del> this.on('error', this._emitTLSError);
<add> this.on('error', this._tlsError);
<ide>
<ide> this._init(socket, wrap);
<ide>
<ide> TLSSocket.prototype._releaseControl = function() {
<ide> if (this._controlReleased)
<ide> return false;
<ide> this._controlReleased = true;
<del> this.removeListener('error', this._emitTLSError);
<add> this.removeListener('error', this._tlsError);
<ide> return true;
<ide> };
<ide> | 1 |
Javascript | Javascript | read compiler.context instead of this.context | c204cdd91e62e91ecdb14cd6bc4588335ccf5a4e | <ide><path>server/on-demand-entry-handler.js
<ide> export default function onDemandEntryHandler (devMiddleware, compilers, {
<ide> const allEntries = Object.keys(entries).map((page) => {
<ide> const { name, entry } = entries[page]
<ide> entries[page].status = BUILDING
<del> return addEntry(compilation, this.context, name, entry)
<add> return addEntry(compilation, compiler.context, name, entry)
<ide> })
<ide>
<ide> Promise.all(allEntries) | 1 |
Ruby | Ruby | add brew linkapps --system | cda83428a64e89862c4da1265ed0e185829186b6 | <ide><path>Library/Contributions/cmd/brew-linkapps.rb
<ide> # Links any Applications (.app) found in installed prefixes to ~/Applications
<ide> require "formula"
<ide>
<del>HOME_APPS = File.expand_path("~/Applications")
<add>TARGET_DIR = ARGV.include?("--system") ? "/Applications" : File.expand_path("~/Applications")
<ide>
<del>unless File.exist? HOME_APPS
<del> opoo "#{HOME_APPS} does not exist, stopping."
<del> puts "Run `mkdir ~/Applications` first."
<add>unless File.exist? TARGET_DIR
<add> opoo "#{TARGET_DIR} does not exist, stopping."
<add> puts "Run `mkdir #{TARGET_DIR}` first."
<ide> exit 1
<ide> end
<ide>
<ide> Dir["#{f.installed_prefix}/*.app", "#{f.installed_prefix}/bin/*.app", "#{f.installed_prefix}/libexec/*.app"].each do |p|
<ide> puts "Linking #{p}"
<ide> appname = File.basename(p)
<del> target = HOME_APPS+"/"+appname
<add> target = TARGET_DIR+"/"+appname
<ide> if File.exist? target
<ide> if File.symlink? target
<ide> system "rm", target
<ide> else
<ide> onoe "#{target} already exists, skipping."
<ide> end
<ide> end
<del> system "ln", "-s", p, HOME_APPS
<add> system "ln", "-s", p, TARGET_DIR
<ide> end
<ide> end
<ide> end
<ide>
<del>puts "Finished linking. Find the links under ~/Applications."
<add>puts "Finished linking. Find the links under #{TARGET_DIR}." | 1 |
Javascript | Javascript | remove prism from app chunk | 06294afdd3894ea4a8582288018e14950485f294 | <ide><path>client/src/components/profile/components/TimeLine.js
<ide> import { withTranslation } from 'react-i18next';
<ide> import './timeline.css';
<ide> import TimelinePagination from './TimelinePagination';
<ide> import { FullWidthRow, Link } from '../../helpers';
<del>import SolutionViewer from '../../SolutionViewer/SolutionViewer';
<add>import Loadable from '@loadable/component';
<add>
<ide> import {
<ide> getCertIds,
<ide> getPathFromID,
<ide> import CertificationIcon from '../../../assets/icons/CertificationIcon';
<ide> import { langCodes } from '../../../../../config/i18n/all-langs';
<ide> import envData from '../../../../../config/env.json';
<ide>
<add>const SolutionViewer = Loadable(() =>
<add> import('../../SolutionViewer/SolutionViewer')
<add>);
<add>
<ide> const { clientLocale } = envData;
<ide>
<ide> const localeCode = langCodes[clientLocale]; | 1 |
Mixed | Ruby | fix explicit names on multiple file fields | 48dc5192eff45fce5ce39c41cdc3188be97ca614 | <ide><path>actionpack/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Fix explicit names on multiple file fields. If a file field tag is passed
<add> the multiple option, it is turned into an array field (appending `[]`),
<add> but if the file field is passed an explicit name as an option, leave the
<add> name alone (do not append `[]`). Fixes #9830
<add>
<add> *Ryan McGeary*
<add>
<ide> * Add block support for the `mail_to` helper, similar to the `link_to` helper.
<ide>
<ide> *Sam Pohlenz*
<ide><path>actionpack/lib/action_view/helpers/tags/base.rb
<ide> def add_default_name_and_id_for_value(tag_value, options)
<ide>
<ide> def add_default_name_and_id(options)
<ide> if options.has_key?("index")
<del> options["name"] ||= options.fetch("name"){ tag_name_with_index(options["index"]) }
<add> options["name"] ||= options.fetch("name"){ tag_name_with_index(options["index"], options["multiple"]) }
<ide> options["id"] = options.fetch("id"){ tag_id_with_index(options["index"]) }
<ide> options.delete("index")
<ide> elsif defined?(@auto_index)
<del> options["name"] ||= options.fetch("name"){ tag_name_with_index(@auto_index) }
<add> options["name"] ||= options.fetch("name"){ tag_name_with_index(@auto_index, options["multiple"]) }
<ide> options["id"] = options.fetch("id"){ tag_id_with_index(@auto_index) }
<ide> else
<del> options["name"] ||= options.fetch("name"){ tag_name }
<add> options["name"] ||= options.fetch("name"){ tag_name(options["multiple"]) }
<ide> options["id"] = options.fetch("id"){ tag_id }
<ide> end
<ide>
<del> options["name"] += "[]" if options["multiple"] && !options["name"].ends_with?("[]")
<ide> options["id"] = [options.delete('namespace'), options["id"]].compact.join("_").presence
<ide> end
<ide>
<del> def tag_name
<del> "#{@object_name}[#{sanitized_method_name}]"
<add> def tag_name(multiple = false)
<add> "#{@object_name}[#{sanitized_method_name}]#{"[]" if multiple}"
<ide> end
<ide>
<del> def tag_name_with_index(index)
<del> "#{@object_name}[#{index}][#{sanitized_method_name}]"
<add> def tag_name_with_index(index, multiple = false)
<add> "#{@object_name}[#{index}][#{sanitized_method_name}]#{"[]" if multiple}"
<ide> end
<ide>
<ide> def tag_id
<ide><path>actionpack/test/template/form_helper_test.rb
<ide> def test_file_field_has_no_size
<ide> assert_dom_equal expected, file_field("user", "avatar")
<ide> end
<ide>
<add> def test_file_field_with_multiple_behavior
<add> expected = '<input id="import_file" multiple="multiple" name="import[file][]" type="file" />'
<add> assert_dom_equal expected, file_field("import", "file", :multiple => true)
<add> end
<add>
<add> def test_file_field_with_multiple_behavior_and_explicit_name
<add> expected = '<input id="import_file" multiple="multiple" name="custom" type="file" />'
<add> assert_dom_equal expected, file_field("import", "file", :multiple => true, :name => "custom")
<add> end
<add>
<ide> def test_hidden_field
<ide> assert_dom_equal(
<ide> '<input id="post_title" name="post[title]" type="hidden" value="Hello World" />', | 3 |
Text | Text | add area/daemon and area/docs labels | 851bf81603183b6493facb3bf3479d2936473073 | <ide><path>project/ISSUE-TRIAGE.md
<ide> An issue can have multiple of the following labels.
<ide> | Kind | Description |
<ide> |------------------|---------------------------------------------------------------------------------------------------------------------------------|
<ide> | kind/bug | Bugs are bugs. The cause may or may not be known at triage time so debugging should be taken account into the time estimate. |
<del>| kind/docs | Writing documentation, man pages, articles, blogs, or other significant word-driven task. |
<ide> | kind/enhancement | Enhancement are not bugs or new features but can drastically improve usability or performance of a project component. |
<ide> | kind/feature | Functionality or other elements that the project does not currently support. Features are new and shiny. |
<ide> | kind/question | Contains a user or contributor question requiring a response. |
<ide> An issue can have multiple of the following labels.
<ide> | area/api |
<ide> | area/builder |
<ide> | area/cli |
<add>| area/daemon |
<ide> | area/distribution |
<add>| area/docs |
<ide> | area/kernel |
<ide> | area/logging |
<ide> | area/networking | | 1 |
Python | Python | fix mt5 config | 36b60ce9e88656e10d1dbef2762a0b3540c37a5f | <ide><path>src/transformers/models/mt5/configuration_mt5.py
<ide> class MT5Config(PretrainedConfig):
<ide> testing).
<ide> feed_forward_proj (:obj:`string`, `optional`, defaults to :obj:`"gated-gelu"`):
<ide> Type of feed forward layer to be used. Should be one of :obj:`"relu"` or :obj:`"gated-gelu"`.
<add> use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`):
<add> Whether or not the model should return the last key/values attentions (not used by all models).
<ide> """
<ide> model_type = "mt5"
<ide> keys_to_ignore_at_inference = ["past_key_values"]
<ide> def __init__(
<ide> initializer_factor=1.0,
<ide> feed_forward_proj="gated-gelu",
<ide> is_encoder_decoder=True,
<add> use_cache=True,
<ide> tokenizer_class="T5Tokenizer",
<ide> tie_word_embeddings=False,
<ide> pad_token_id=0,
<ide> def __init__(
<ide> self.layer_norm_epsilon = layer_norm_epsilon
<ide> self.initializer_factor = initializer_factor
<ide> self.feed_forward_proj = feed_forward_proj
<add> self.use_cache = use_cache
<ide>
<ide> @property
<ide> def hidden_size(self): | 1 |
Java | Java | fix typos in @eventlistener | 14e168f2dc530c67d98f40974dd903810a0420a3 | <ide><path>spring-context/src/main/java/org/springframework/context/event/EventListener.java
<ide> import org.springframework.core.annotation.AliasFor;
<ide>
<ide> /**
<del> * Annotation that marks a method to listen for application events. The
<del> * method may have one (and only one) parameter that reflects the event
<del> * type to listen to. Or this annotation may refer to the event type(s)
<del> * using the {@link #classes} attribute. Events can be {@link ApplicationEvent}
<del> * instances as well as arbitrary objects.
<add> * Annotation that marks a method as a listener for application events.
<ide> *
<del> * <p>Processing of {@code @EventListener} annotations is performed via
<add> * <p>The method must declare one (and only one) parameter that reflects the
<add> * event type to listen to. Alternatively, this annotation may refer to the
<add> * event type(s) using the {@link #classes} attribute. Events can be
<add> * {@link ApplicationEvent} instances as well as arbitrary objects.
<add> *
<add> * <p>Processing of {@code @EventListener} annotations is performed via the
<ide> * {@link EventListenerMethodProcessor} that is registered automatically
<ide> * when using Java config or via the {@code <context:annotation-driven/>}
<ide> * XML element.
<ide> *
<ide> * <p>Annotated methods may have a non-{@code void} return type. When they
<ide> * do, the result of the method invocation is sent as a new event. It is
<del> * also possible to defined the order in which listeners for a certain
<del> * event are invoked. To do so, add a regular {code @Order} annotation
<add> * also possible to define the order in which listeners for a certain event
<add> * are invoked. To do so, add a regular
<add> * {@link org.springframework.core.annotation.Order @Order} annotation
<ide> * alongside this annotation.
<ide> *
<ide> * <p>While it is possible to define any arbitrary exception types, checked
<ide> * exceptions will be wrapped in a {@link java.lang.reflect.UndeclaredThrowableException}
<del> * as the caller only handles runtime exceptions.
<add> * so that the caller only handles runtime exceptions.
<ide> *
<ide> * @author Stephane Nicoll
<ide> * @since 4.2 | 1 |
Ruby | Ruby | remove redeclared method | b7dd6f1f7eb803923b52e96ae663f05f6b4676ae | <ide><path>Library/Homebrew/extend/ARGV.rb
<ide> def build_from_source?
<ide> flag? '--build-from-source' or ENV['HOMEBREW_BUILD_FROM_SOURCE']
<ide> end
<ide>
<del> def one?
<del> flag? "--1"
<del> end
<del>
<ide> def flag? flag
<ide> options_only.each do |arg|
<ide> return true if arg == flag | 1 |
Text | Text | fix illogical code in tutorial.md | 284a96b9a668325cc0b6a0b8c2b64ecacc437b3f | <ide><path>docs/tutorial/tutorial.md
<ide> const moves = history.map((step, move) => {
<ide> 'Move #' + move :
<ide> 'Game start';
<ide> return (
<del> <li key={move}>
<add> <li>
<ide> <a href="#" onClick={() => this.jumpTo(move)}>{desc}</a>
<ide> </li>
<ide> ); | 1 |
Python | Python | add tests for `np.floating.is_integer` | 5d86d8c9cc70f87b4aab10682d101acd8c4fb781 | <ide><path>numpy/core/tests/test_scalar_methods.py
<ide> def test_roundtrip(self, ftype, frac_vals, exp_vals):
<ide> pytest.skip("longdouble too small on this platform")
<ide>
<ide> assert_equal(nf / df, f, "{}/{}".format(n, d))
<add>
<add>
<add>@pytest.mark.parametrize("code", np.typecodes["Float"])
<add>class TestIsInteger:
<add> @pytest.mark.parametrize("str_value", ["inf", "nan"])
<add> def test_special(self, code: str, str_value: str) -> None:
<add> cls = np.dtype(code).type
<add> value = cls(str_value)
<add> assert not value.is_integer()
<add>
<add> def test_true(self, code: str) -> None:
<add> float_array = np.arange(-5, 5).astype(code)
<add> for value in float_array:
<add> assert value.is_integer()
<add>
<add> def test_false(self, code: str) -> None:
<add> float_array = np.arange(-5, 5).astype(code)
<add> float_array *= 1.1
<add> for value in float_array:
<add> if value == 0:
<add> continue
<add> assert not value.is_integer()
<ide><path>numpy/typing/tests/data/fail/scalars.py
<ide> def func(a: np.float32) -> None: ...
<ide>
<ide> c8.__getnewargs__() # E: Invalid self argument
<ide> f2.__getnewargs__() # E: Invalid self argument
<del>f2.is_integer() # E: Invalid self argument
<ide> f2.hex() # E: Invalid self argument
<ide> np.float16.fromhex("0x0.0p+0") # E: Invalid self argument
<ide> f2.__trunc__() # E: Invalid self argument | 2 |
PHP | PHP | remove unneeded calls to with | fcb9642d475f08d462a0522eb0111d0e6963bf54 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function morphTo($name = null, $type = null, $id = null)
<ide> $instance = new $class;
<ide>
<ide> return new MorphTo(
<del> with($instance)->newQuery(), $this, $id, $instance->getKeyName(), $type, $name
<add> $instance->newQuery(), $this, $id, $instance->getKeyName(), $type, $name
<ide> );
<ide> }
<ide> }
<ide> public function hasManyThrough($related, $through, $firstKey = null, $secondKey
<ide>
<ide> $secondKey = $secondKey ?: $through->getForeignKey();
<ide>
<del> return new HasManyThrough(with(new $related)->newQuery(), $this, $through, $firstKey, $secondKey);
<add> return new HasManyThrough((new $related)->newQuery(), $this, $through, $firstKey, $secondKey);
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Foundation/Console/TailCommand.php
<ide> protected function tailLocalLogs($path)
<ide>
<ide> $lines = $this->option('lines');
<ide>
<del> with(new Process('tail -f -n '.$lines.' '.escapeshellarg($path)))->setTimeout(null)->run(function($type, $line) use ($output)
<add> (new Process('tail -f -n '.$lines.' '.escapeshellarg($path)))->setTimeout(null)->run(function($type, $line) use ($output)
<ide> {
<ide> $output->write($line);
<ide> });
<ide><path>src/Illuminate/Foundation/Console/TinkerCommand.php
<ide> protected function runBorisShell()
<ide> {
<ide> $this->setupBorisErrorHandling();
<ide>
<del> with(new \Boris\Boris('> '))->start();
<add> (new \Boris\Boris('> '))->start();
<ide> }
<ide>
<ide> /** | 3 |
Javascript | Javascript | add feature flag to disable yielding | 4162f6026c2f560f286e7853f4929cd5e0135bdd | <ide><path>packages/react-dom/src/__tests__/ReactDOMFiberAsync-test.internal.js
<ide> 'use strict';
<ide>
<ide> const React = require('react');
<add>const Fragment = React.Fragment;
<ide> let ReactFeatureFlags = require('shared/ReactFeatureFlags');
<ide>
<ide> let ReactDOM;
<ide> describe('ReactDOMFiberAsync', () => {
<ide> expect(formSubmitted).toBe(true);
<ide> });
<ide> });
<add>
<add> describe('Disable yielding', () => {
<add> beforeEach(() => {
<add> jest.resetModules();
<add> ReactFeatureFlags = require('shared/ReactFeatureFlags');
<add> ReactFeatureFlags.disableYielding = true;
<add> ReactFeatureFlags.debugRenderPhaseSideEffectsForStrictMode = false;
<add> ReactDOM = require('react-dom');
<add> Scheduler = require('scheduler');
<add> });
<add>
<add> it('wont yield during a render if yielding is disabled', () => {
<add> class A extends React.Component {
<add> render() {
<add> Scheduler.yieldValue('A');
<add> return <div>{this.props.children}</div>;
<add> }
<add> }
<add>
<add> class B extends React.Component {
<add> render() {
<add> Scheduler.yieldValue('B');
<add> return <div>{this.props.children}</div>;
<add> }
<add> }
<add>
<add> class C extends React.Component {
<add> render() {
<add> Scheduler.yieldValue('C');
<add> return <div>{this.props.children}</div>;
<add> }
<add> }
<add>
<add> let root = ReactDOM.unstable_createRoot(container);
<add>
<add> root.render(
<add> <Fragment>
<add> <A />
<add> <B />
<add> <C />
<add> </Fragment>,
<add> );
<add>
<add> expect(Scheduler).toHaveYielded([]);
<add>
<add> Scheduler.unstable_flushNumberOfYields(2);
<add> // Even though we just flushed two yields, we should have rendered
<add> // everything without yielding when the flag is on.
<add> expect(Scheduler).toHaveYielded(['A', 'B', 'C']);
<add> });
<add> });
<ide> });
<ide><path>packages/react-reconciler/src/ReactFiberScheduler.js
<ide> import {
<ide> replayFailedUnitOfWorkWithInvokeGuardedCallback,
<ide> warnAboutDeprecatedLifecycles,
<ide> enableSuspenseServerRenderer,
<add> disableYielding,
<ide> } from 'shared/ReactFeatureFlags';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import invariant from 'shared/invariant';
<ide> function onSuspend(
<ide> msUntilTimeout: number,
<ide> ): void {
<ide> root.expirationTime = rootExpirationTime;
<del> if (msUntilTimeout === 0 && !shouldYield()) {
<add> if (msUntilTimeout === 0 && (disableYielding || !shouldYield())) {
<ide> // Don't wait an additional tick. Commit the tree immediately.
<ide> root.pendingCommitExpirationTime = suspendedExpirationTime;
<ide> root.finishedWork = finishedWork;
<ide> function performAsyncWork(didTimeout) {
<ide> } while (root !== firstScheduledRoot);
<ide> }
<ide> }
<del> performWork(NoWork, true);
<add> let isYieldy = true;
<add> if (disableYielding) {
<add> isYieldy = false;
<add> }
<add> performWork(NoWork, isYieldy);
<ide> }
<ide>
<ide> function performSyncWork() {
<ide><path>packages/shared/ReactFeatureFlags.js
<ide> export function addUserTimingListener() {
<ide> // Disable javascript: URL strings in href for XSS protection.
<ide> export const disableJavaScriptURLs = false;
<ide>
<add>// Disables yielding during render in Concurrent Mode. Used for debugging only.
<add>export const disableYielding = false;
<add>
<ide> // React Fire: prevent the value and checked attributes from syncing
<ide> // with their related DOM properties
<ide> export const disableInputAttributeSyncing = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.native-fb.js
<ide> export const warnAboutShorthandPropertyCollision = false;
<ide> export const enableSchedulerDebugging = false;
<ide> export const debugRenderPhaseSideEffectsForStrictMode = true;
<ide> export const disableJavaScriptURLs = false;
<add>export const disableYielding = false;
<ide> export const disableInputAttributeSyncing = false;
<ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = __DEV__;
<ide> export const warnAboutDeprecatedLifecycles = true;
<ide><path>packages/shared/forks/ReactFeatureFlags.native-oss.js
<ide> export const enableProfilerTimer = __PROFILE__;
<ide> export const enableSchedulerTracing = __PROFILE__;
<ide> export const enableSuspenseServerRenderer = false;
<ide> export const disableJavaScriptURLs = false;
<add>export const disableYielding = false;
<ide> export const disableInputAttributeSyncing = false;
<ide> export const enableStableConcurrentModeAPIs = false;
<ide> export const warnAboutShorthandPropertyCollision = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.persistent.js
<ide> export const enableProfilerTimer = __PROFILE__;
<ide> export const enableSchedulerTracing = __PROFILE__;
<ide> export const enableSuspenseServerRenderer = false;
<ide> export const disableJavaScriptURLs = false;
<add>export const disableYielding = false;
<ide> export const disableInputAttributeSyncing = false;
<ide> export const enableStableConcurrentModeAPIs = false;
<ide> export const warnAboutShorthandPropertyCollision = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.js
<ide> export const enableProfilerTimer = false;
<ide> export const enableSchedulerTracing = false;
<ide> export const enableSuspenseServerRenderer = false;
<ide> export const disableJavaScriptURLs = false;
<add>export const disableYielding = false;
<ide> export const disableInputAttributeSyncing = false;
<ide> export const enableStableConcurrentModeAPIs = false;
<ide> export const warnAboutShorthandPropertyCollision = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.www.js
<ide> export const enableStableConcurrentModeAPIs = false;
<ide> export const enableSchedulerDebugging = false;
<ide> export const warnAboutDeprecatedSetNativeProps = false;
<ide> export const disableJavaScriptURLs = false;
<add>export const disableYielding = false;
<ide> export const enableEventAPI = true;
<ide>
<ide> // Only used in www builds.
<ide><path>packages/shared/forks/ReactFeatureFlags.www.js
<ide> export const {
<ide> replayFailedUnitOfWorkWithInvokeGuardedCallback,
<ide> warnAboutDeprecatedLifecycles,
<ide> disableJavaScriptURLs,
<add> disableYielding,
<ide> disableInputAttributeSyncing,
<ide> warnAboutShorthandPropertyCollision,
<ide> warnAboutDeprecatedSetNativeProps, | 9 |
Javascript | Javascript | fix bug in hmr runtime | 54a90430a22cc8688ec38a2975119409b7463154 | <ide><path>lib/hmr/JavascriptHotModuleReplacement.runtime.js
<ide> module.exports = function () {
<ide> moduleOutdatedDependencies =
<ide> outdatedDependencies[outdatedModuleId];
<ide> var callbacks = [];
<add> var dependenciesForCallbacks = [];
<ide> for (var j = 0; j < moduleOutdatedDependencies.length; j++) {
<ide> var dependency = moduleOutdatedDependencies[j];
<ide> var acceptCallback =
<ide> module.hot._acceptedDependencies[dependency];
<ide> if (acceptCallback) {
<ide> if (callbacks.indexOf(acceptCallback) !== -1) continue;
<ide> callbacks.push(acceptCallback);
<add> dependenciesForCallbacks.push(dependency);
<ide> }
<ide> }
<ide> for (var k = 0; k < callbacks.length; k++) {
<ide> module.exports = function () {
<ide> options.onErrored({
<ide> type: "accept-errored",
<ide> moduleId: outdatedModuleId,
<del> dependencyId: moduleOutdatedDependencies[i],
<add> dependencyId: dependenciesForCallbacks[k],
<ide> error: err
<ide> });
<ide> } | 1 |
Javascript | Javascript | remove unused `mozcentralcheck` target | 6d374f15c05bdd782fbea563a50f5f3a3f1af377 | <ide><path>make.js
<ide> target.mozcentraldiff = function() {
<ide> echo('Result diff can be found at ' + MOZCENTRAL_DIFF);
<ide> };
<ide>
<del>target.mozcentralcheck = function() {
<del> cd(ROOT_DIR);
<del>
<del> echo();
<del> echo('### Checking mozcentral changes');
<del>
<del> var mcPath = env['MC_PATH'];
<del> if (!mcPath) {
<del> echo('mozilla-central path is not provided.');
<del> echo('Please specify MC_PATH variable');
<del> exit(1);
<del> }
<del> if ((mcPath[0] !== '/' && mcPath[0] !== '~' && mcPath[1] !== ':') ||
<del> !test('-d', mcPath)) {
<del> echo('mozilla-central path is not in absolute form or does not exist.');
<del> exit(1);
<del> }
<del>
<del> var MOZCENTRAL_DIFF = BUILD_DIR + 'mozcentral_changes.diff';
<del> if (test('-f', MOZCENTRAL_DIFF)) {
<del> rm(MOZCENTRAL_DIFF);
<del> }
<del>
<del> var MOZCENTRAL_BASELINE_DIR = BUILD_DIR + 'mozcentral.baseline';
<del> if (!test('-d', MOZCENTRAL_BASELINE_DIR)) {
<del> echo('mozcentral baseline was not found');
<del> echo('Please build one using "gulp mozcentralbaseline"');
<del> exit(1);
<del> }
<del> cd(MOZCENTRAL_BASELINE_DIR);
<del> exec('git reset --hard');
<del> cd(ROOT_DIR); rm('-rf', MOZCENTRAL_BASELINE_DIR + '/*'); // trying to be safe
<del> cd(MOZCENTRAL_BASELINE_DIR);
<del> mkdir('browser');
<del> cd('browser');
<del> mkdir('-p', 'extensions/pdfjs');
<del> cp('-Rf', mcPath + '/browser/extensions/pdfjs/*', 'extensions/pdfjs');
<del> mkdir('-p', 'locales/en-US/pdfviewer');
<del> cp('-Rf', mcPath + '/browser/locales/en-US/pdfviewer/*',
<del> 'locales/en-US/pdfviewer');
<del> // Remove '.DS_Store' and other hidden files
<del> find('.').forEach(function(file) {
<del> if (file.match(/^\.\w|~$/)) {
<del> rm('-f', file);
<del> }
<del> });
<del>
<del> cd('..');
<del> exec('git add -A');
<del> var diff = exec('git diff --binary --cached --unified=8',
<del> {silent: true}).output;
<del>
<del> if (diff) {
<del> echo('There were changes found at mozilla-central.');
<del> diff.to('../mozcentral_changes.diff');
<del> echo('Result diff can be found at ' + MOZCENTRAL_DIFF);
<del> exit(1);
<del> }
<del>
<del> echo('Success: there are no changes at mozilla-central');
<del>};
<del>
<del>
<ide> ////////////////////////////////////////////////////////////////////////////////
<ide> //
<ide> // Other | 1 |
Java | Java | improve diagnostics for invalid testgroup values | 55caf7bdb0b418d64967f057832eba40de7ff825 | <ide><path>spring-core/src/test/java/org/springframework/tests/TestGroup.java
<ide> import java.util.HashSet;
<ide> import java.util.Set;
<ide>
<add>import org.springframework.util.StringUtils;
<add>
<add>import static java.lang.String.*;
<add>
<ide> /**
<ide> * A test group used to limit when certain tests are run.
<ide> *
<ide> public static Set<TestGroup> parse(String value) {
<ide> try {
<ide> groups.add(valueOf(group.trim().toUpperCase()));
<ide> } catch (IllegalArgumentException e) {
<del> throw new IllegalArgumentException("Unable to find test group '" + group.trim()
<del> + "' when parsing '" + value + "'");
<add> throw new IllegalArgumentException(format(
<add> "Unable to find test group '%s' when parsing testGroups value: '%s'. " +
<add> "Available groups include: [%s]", group.trim(), value,
<add> StringUtils.arrayToCommaDelimitedString(TestGroup.values())));
<ide> }
<ide> }
<ide> return groups;
<ide><path>spring-core/src/test/java/org/springframework/tests/TestGroupTests.java
<ide> public void parseInMixedCase() throws Exception {
<ide> @Test
<ide> public void parseMissing() throws Exception {
<ide> thrown.expect(IllegalArgumentException.class);
<del> thrown.expectMessage("Unable to find test group 'missing' when parsing 'performance, missing'");
<add> thrown.expectMessage("Unable to find test group 'missing' when parsing " +
<add> "testGroups value: 'performance, missing'. Available groups include: " +
<add> "[LONG_RUNNING,PERFORMANCE,JMXMP]");
<ide> TestGroup.parse("performance, missing");
<ide> }
<ide> | 2 |
PHP | PHP | add additional unit tests for error middleware | 6c2dbd5872bfc309da535f284bd7e79debb0d9a3 | <ide><path>tests/TestCase/Error/Middleware/ErrorHandlerMiddlewareTest.php
<ide> public function testHandleException()
<ide> $this->assertContains('was not found', '' . $result->getBody());
<ide> }
<ide>
<add> /**
<add> * Test rendering an error page holds onto the original request.
<add> *
<add> * @return void
<add> */
<add> public function testHandleExceptionPreserveRequest()
<add> {
<add> $request = ServerRequestFactory::fromGlobals();
<add> $request = $request->withHeader('Accept', 'application/json');
<add>
<add> $response = new Response();
<add> $middleware = new ErrorHandlerMiddleware();
<add> $next = function ($req, $res) {
<add> throw new \Cake\Http\Exception\NotFoundException('whoops');
<add> };
<add> $result = $middleware($request, $response, $next);
<add> $this->assertInstanceOf('Cake\Http\Response', $result);
<add> $this->assertNotSame($result, $response);
<add> $this->assertEquals(404, $result->getStatusCode());
<add> $this->assertContains('"message": "whoops"', '' . $result->getBody());
<add> $this->assertEquals('application/json; charset=UTF-8', $result->getHeaderLine('Content-type'));
<add> }
<add>
<ide> /**
<ide> * Test handling PHP 7's Error instance.
<ide> * | 1 |
Text | Text | use sentence case in readme.md headers | b10349a246349fcffb60212d17bc6d765282a617 | <ide><path>README.md
<ide> The Node.js project uses an [open governance model](./GOVERNANCE.md). The
<ide> # Table of contents
<ide>
<ide> * [Support](#support)
<del>* [Release Types](#release-types)
<add>* [Release types](#release-types)
<ide> * [Download](#download)
<del> * [Current and LTS Releases](#current-and-lts-releases)
<del> * [Nightly Releases](#nightly-releases)
<del> * [API Documentation](#api-documentation)
<del> * [Verifying Binaries](#verifying-binaries)
<add> * [Current and LTS releases](#current-and-lts-releases)
<add> * [Nightly releases](#nightly-releases)
<add> * [API documentation](#api-documentation)
<add> * [Verifying binaries](#verifying-binaries)
<ide> * [Building Node.js](#building-nodejs)
<ide> * [Security](#security)
<ide> * [Contributing to Node.js](#contributing-to-nodejs)
<del>* [Current Project Team Members](#current-project-team-members)
<add>* [Current project team members](#current-project-team-members)
<ide> * [TSC (Technical Steering Committee)](#tsc-technical-steering-committee)
<ide> * [Collaborators](#collaborators)
<del> * [Release Keys](#release-keys)
<add> * [Release keys](#release-keys)
<ide> * [License](#license)
<ide>
<ide> ## Support | 1 |
Python | Python | remove type restriction for ordering | 174682bf07edab6f814fd35dd3caca1e981ac6db | <ide><path>airflow/models.py
<ide> def __neq__(self, other):
<ide> return not self == other
<ide>
<ide> def __lt__(self, other):
<del> return (type(self) == type(other) and self.task_id < other.task_id)
<add> return self.task_id < other.task_id
<ide>
<ide> def __hash__(self):
<ide> return hash(tuple(getattr(self, c, None) for c in self._comps))
<ide> def __neq__(self, other):
<ide> return not self == other
<ide>
<ide> def __lt__(self, other):
<del> return (type(self) == type(other) and self.dag_id < other.dag_id)
<add> return self.dag_id < other.dag_id
<ide>
<ide> def __hash__(self):
<ide> return hash(tuple(getattr(self, c, None) for c in self._comps)) | 1 |
Javascript | Javascript | handle case when weights are zero | 578013ac202aa3b28d25c4378018acd077ce5ed8 | <ide><path>src/objects/SkinnedMesh.js
<ide> THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
<ide>
<ide> } else {
<ide>
<del> // do nothing
<add> sw.set( 1, 0, 0, 0 ); // do something reasonable
<ide>
<ide> }
<ide>
<ide> THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
<ide>
<ide> } else {
<ide>
<del> // do nothing
<add> vec.set( 1, 0, 0, 0 ); // do something reasonable
<ide>
<ide> }
<ide> | 1 |
Python | Python | fix typos in hive transfer operator docstrings | f50f677514b562ac83a00cde2bfd0efdfbe171e4 | <ide><path>airflow/providers/apache/hive/transfers/hive_to_mysql.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide>
<del>"""This module contains operator to move data from Hive to MySQL."""
<add>"""This module contains an operator to move data from Hive to MySQL."""
<ide> from tempfile import NamedTemporaryFile
<ide> from typing import Dict, Optional
<ide>
<ide><path>airflow/providers/apache/hive/transfers/hive_to_samba.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide>
<del>"""This module contains operator to move data from Hive to Samba."""
<add>"""This module contains an operator to move data from Hive to Samba."""
<ide>
<ide> from tempfile import NamedTemporaryFile
<ide>
<ide><path>airflow/providers/apache/hive/transfers/mssql_to_hive.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide>
<del>"""This module contains operator to move data from MSSQL to Hive."""
<add>"""This module contains an operator to move data from MSSQL to Hive."""
<ide>
<ide> from collections import OrderedDict
<ide> from tempfile import NamedTemporaryFile
<ide><path>airflow/providers/apache/hive/transfers/mysql_to_hive.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide>
<del>"""This module contains operator to move data from MySQL to Druid."""
<add>"""This module contains an operator to move data from MySQL to Hive."""
<ide>
<ide> from collections import OrderedDict
<ide> from tempfile import NamedTemporaryFile
<ide><path>airflow/providers/apache/hive/transfers/s3_to_hive.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide>
<del>"""This module contains operator to move data from Hive to S3 bucket."""
<add>"""This module contains an operator to move data from an S3 bucket to Hive."""
<ide>
<ide> import bz2
<ide> import gzip
<ide><path>airflow/providers/apache/hive/transfers/vertica_to_hive.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide>
<del>"""This module contains operator to move data from Vertica to Hive."""
<add>"""This module contains an operator to move data from Vertica to Hive."""
<ide>
<ide> from collections import OrderedDict
<ide> from tempfile import NamedTemporaryFile | 6 |
Java | Java | add support for setting the "vary" response header | 7a5e93ff16622cbffeac31f514fad11a7102c2cd | <ide><path>spring-web/src/main/java/org/springframework/http/HttpHeaders.java
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.LinkedCaseInsensitiveMap;
<ide> import org.springframework.util.MultiValueMap;
<add>import org.springframework.util.ObjectUtils;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> /**
<ide> public String getUpgrade() {
<ide> return getFirst(UPGRADE);
<ide> }
<ide>
<add> /**
<add> * Set the request header names (e.g. "Accept-Language") for which the
<add> * response is subject to content negotiation and variances based on the
<add> * value of those request headers.
<add> * @param requestHeaders the request header names
<add> * @since 4.3
<add> */
<add> public void setVary(List<String> requestHeaders) {
<add> set(VARY, toCommaDelimitedString(requestHeaders));
<add> }
<add>
<add> /**
<add> * Return the request header names subject to content negotiation.
<add> */
<add> public List<String> getVary() {
<add> return getFirstValueAsList(VARY);
<add> }
<add>
<ide> /**
<ide> * Parse the first header value for the given header name as a date,
<ide> * return -1 if there is no value, or raise {@link IllegalArgumentException}
<ide><path>spring-web/src/main/java/org/springframework/http/ResponseEntity.java
<ide> public static BodyBuilder unprocessableEntity() {
<ide> */
<ide> B cacheControl(CacheControl cacheControl);
<ide>
<add> /**
<add> * Configure one or more request header names (e.g. "Accept-Language") to
<add> * add to the "Vary" response header to inform clients that the response is
<add> * subject to content negotiation and variances based on the value of the
<add> * given request headers. The configured request header names are added only
<add> * if not already present in the response "Vary" header.
<add> * @param requestHeaders request header names
<add> * @since 4.3
<add> */
<add> B varyBy(String... requestHeaders);
<add>
<ide> /**
<ide> * Build the response entity with no body.
<ide> * @return the response entity
<ide> public BodyBuilder cacheControl(CacheControl cacheControl) {
<ide> return this;
<ide> }
<ide>
<add> @Override
<add> public BodyBuilder varyBy(String... requestHeaders) {
<add> this.headers.setVary(Arrays.asList(requestHeaders));
<add> return this;
<add> }
<add>
<ide> @Override
<ide> public ResponseEntity<Void> build() {
<ide> return new ResponseEntity<Void>(null, this.headers, this.status);
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessor.java
<ide> import java.io.IOException;
<ide> import java.lang.reflect.ParameterizedType;
<ide> import java.lang.reflect.Type;
<add>import java.util.ArrayList;
<add>import java.util.Collections;
<ide> import java.util.List;
<add>import java.util.Map;
<ide>
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.web.context.request.NativeWebRequest;
<ide> import org.springframework.web.method.support.ModelAndViewContainer;
<ide>
<add>import static org.springframework.http.HttpHeaders.VARY;
<add>
<ide> /**
<ide> * Resolves {@link HttpEntity} and {@link RequestEntity} method argument values
<ide> * and also handles {@link HttpEntity} and {@link ResponseEntity} return values.
<ide> public void handleReturnValue(Object returnValue, MethodParameter returnType,
<ide> Assert.isInstanceOf(HttpEntity.class, returnValue);
<ide> HttpEntity<?> responseEntity = (HttpEntity<?>) returnValue;
<ide>
<add> HttpHeaders outputHeaders = outputMessage.getHeaders();
<ide> HttpHeaders entityHeaders = responseEntity.getHeaders();
<add> if (outputHeaders.containsKey(VARY) && entityHeaders.containsKey(VARY)) {
<add> List<String> values = getVaryRequestHeadersToAdd(outputHeaders, entityHeaders);
<add> if (!values.isEmpty()) {
<add> outputHeaders.setVary(values);
<add> }
<add> }
<ide> if (!entityHeaders.isEmpty()) {
<del> outputMessage.getHeaders().putAll(entityHeaders);
<add> for (Map.Entry<String, List<String>> entry : entityHeaders.entrySet()) {
<add> outputHeaders.putIfAbsent(entry.getKey(), entry.getValue());
<add> }
<ide> }
<ide>
<ide> Object body = responseEntity.getBody();
<ide> public void handleReturnValue(Object returnValue, MethodParameter returnType,
<ide> outputMessage.flush();
<ide> }
<ide>
<add> private List<String> getVaryRequestHeadersToAdd(HttpHeaders responseHeaders, HttpHeaders entityHeaders) {
<add> if (!responseHeaders.containsKey(HttpHeaders.VARY)) {
<add> return entityHeaders.getVary();
<add> }
<add> List<String> entityHeadersVary = entityHeaders.getVary();
<add> List<String> result = new ArrayList<String>(entityHeadersVary);
<add> for (String header : responseHeaders.get(HttpHeaders.VARY)) {
<add> for (String existing : StringUtils.tokenizeToStringArray(header, ",")) {
<add> if ("*".equals(existing)) {
<add> return Collections.emptyList();
<add> }
<add> for (String value : entityHeadersVary) {
<add> if (value.equalsIgnoreCase(existing)) {
<add> result.remove(value);
<add> }
<add> }
<add> }
<add> }
<add> return result;
<add> }
<add>
<ide> private boolean isResourceNotModified(ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage) {
<ide> List<String> ifNoneMatch = inputMessage.getHeaders().getIfNoneMatch();
<ide> long ifModifiedSince = inputMessage.getHeaders().getIfModifiedSince();
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.java
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.Collection;
<add>import java.util.Collections;
<ide> import java.util.LinkedHashSet;
<ide> import java.util.Set;
<ide> import java.util.concurrent.TimeUnit;
<ide> import javax.servlet.http.HttpServletResponse;
<ide>
<ide> import org.springframework.http.CacheControl;
<add>import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<add>import org.springframework.util.ClassUtils;
<ide> import org.springframework.util.ObjectUtils;
<ide> import org.springframework.util.StringUtils;
<ide> import org.springframework.web.HttpRequestMethodNotSupportedException;
<ide> public abstract class WebContentGenerator extends WebApplicationObjectSupport {
<ide>
<ide> protected static final String HEADER_CACHE_CONTROL = "Cache-Control";
<ide>
<add> /** Checking for Servlet 3.0+ HttpServletResponse.getHeaders(String) */
<add> private static final boolean servlet3Present =
<add> ClassUtils.hasMethod(HttpServletResponse.class, "getHeaders", String.class);
<add>
<ide>
<ide> /** Set of supported HTTP methods */
<ide> private Set<String> supportedMethods;
<ide> public abstract class WebContentGenerator extends WebApplicationObjectSupport {
<ide>
<ide> private int cacheSeconds = -1;
<ide>
<add> private String[] varyByRequestHeaders;
<add>
<add>
<add> // deprecated fields
<add>
<ide> /** Use HTTP 1.0 expires header? */
<ide> private boolean useExpiresHeader = false;
<ide>
<ide> public final int getCacheSeconds() {
<ide> return this.cacheSeconds;
<ide> }
<ide>
<add> /**
<add> * Configure one or more request header names (e.g. "Accept-Language") to
<add> * add to the "Vary" response header to inform clients that the response is
<add> * subject to content negotiation and variances based on the value of the
<add> * given request headers. The configured request header names are added only
<add> * if not already present in the response "Vary" header.
<add> *
<add> * <p><strong>Note:</strong> this property is only supported on Servlet 3.0+
<add> * which allows checking existing response header values.
<add> * @param varyByRequestHeaders one or more request header names
<add> * @since 4.3
<add> */
<add> public void setVaryByRequestHeaders(String... varyByRequestHeaders) {
<add> this.varyByRequestHeaders = varyByRequestHeaders;
<add> }
<add>
<add> /**
<add> * Return the configured request header names for the "Vary" response header.
<add> */
<add> public String[] getVaryByRequestHeaders() {
<add> return this.varyByRequestHeaders;
<add> }
<add>
<ide> /**
<ide> * Set whether to use the HTTP 1.0 expires header. Default is "false",
<ide> * as of 4.2.
<ide> protected final void prepareResponse(HttpServletResponse response) {
<ide> else {
<ide> applyCacheSeconds(response, this.cacheSeconds);
<ide> }
<add> if (servlet3Present && this.varyByRequestHeaders != null) {
<add> for (String value : getVaryRequestHeadersToAdd(response)) {
<add> response.addHeader("Vary", value);
<add> }
<add> }
<ide> }
<ide>
<ide> /**
<ide> protected final void preventCaching(HttpServletResponse response) {
<ide> }
<ide> }
<ide>
<add> private Collection<String> getVaryRequestHeadersToAdd(HttpServletResponse response) {
<add> if (!response.containsHeader(HttpHeaders.VARY)) {
<add> return Arrays.asList(getVaryByRequestHeaders());
<add> }
<add> Collection<String> result = new ArrayList<String>(getVaryByRequestHeaders().length);
<add> Collections.addAll(result, getVaryByRequestHeaders());
<add> for (String header : response.getHeaders(HttpHeaders.VARY)) {
<add> for (String existing : StringUtils.tokenizeToStringArray(header, ",")) {
<add> if ("*".equals(existing)) {
<add> return Collections.emptyList();
<add> }
<add> for (String value : getVaryByRequestHeaders()) {
<add> if (value.equalsIgnoreCase(existing)) {
<add> result.remove(value);
<add> }
<add> }
<add> }
<add> }
<add> return result;
<add> }
<add>
<ide> }
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.java
<ide> import java.nio.charset.Charset;
<ide> import java.text.SimpleDateFormat;
<ide> import java.util.ArrayList;
<add>import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import java.util.Date;
<ide> import java.util.List;
<ide> public void handleReturnValueIfNoneMatchIfUnmodifiedSince() throws Exception {
<ide> assertEquals(etagValue, servletResponse.getHeader(HttpHeaders.ETAG));
<ide> }
<ide>
<add> @Test
<add> public void varyHeader() throws Exception {
<add> String[] entityValues = {"Accept-Language", "User-Agent"};
<add> String[] existingValues = {};
<add> String[] expected = {"Accept-Language, User-Agent"};
<add> testVaryHeader(entityValues, existingValues, expected);
<add> }
<add>
<add> @Test
<add> public void varyHeaderWithExistingWildcard() throws Exception {
<add> String[] entityValues = {"Accept-Language"};
<add> String[] existingValues = {"*"};
<add> String[] expected = {"*"};
<add> testVaryHeader(entityValues, existingValues, expected);
<add> }
<add>
<add> @Test
<add> public void varyHeaderWithExistingCommaValues() throws Exception {
<add> String[] entityValues = {"Accept-Language", "User-Agent"};
<add> String[] existingValues = {"Accept-Encoding", "Accept-Language"};
<add> String[] expected = {"Accept-Encoding", "Accept-Language", "User-Agent"};
<add> testVaryHeader(entityValues, existingValues, expected);
<add> }
<add>
<add> @Test
<add> public void varyHeaderWithExistingCommaSeparatedValues() throws Exception {
<add> String[] entityValues = {"Accept-Language", "User-Agent"};
<add> String[] existingValues = {"Accept-Encoding, Accept-Language"};
<add> String[] expected = {"Accept-Encoding, Accept-Language", "User-Agent"};
<add> testVaryHeader(entityValues, existingValues, expected);
<add> }
<add>
<add> @Test
<add> public void handleReturnValueVaryHeader() throws Exception {
<add> String[] entityValues = {"Accept-Language", "User-Agent"};
<add> String[] existingValues = {"Accept-Encoding, Accept-Language"};
<add> String[] expected = {"Accept-Encoding, Accept-Language", "User-Agent"};
<add> testVaryHeader(entityValues, existingValues, expected);
<add> }
<add>
<add>
<ide> private void initStringMessageConversion(MediaType accepted) {
<ide> given(messageConverter.canWrite(String.class, null)).willReturn(true);
<ide> given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
<ide> private void assertResponseOkWithBody(String body) throws Exception {
<ide> verify(messageConverter).write(eq(body), eq(MediaType.TEXT_PLAIN), outputMessage.capture());
<ide> }
<ide>
<add> private void testVaryHeader(String[] entityValues, String[] existingValues, String[] expected) throws Exception {
<add> ResponseEntity<String> returnValue = ResponseEntity.ok().varyBy(entityValues).body("Foo");
<add> for (String value : existingValues) {
<add> servletResponse.addHeader("Vary", value);
<add> }
<add> initStringMessageConversion(MediaType.TEXT_PLAIN);
<add> processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
<add>
<add> assertTrue(mavContainer.isRequestHandled());
<add> assertEquals(Arrays.asList(expected), servletResponse.getHeaders("Vary"));
<add> verify(messageConverter).write(eq("Foo"), eq(MediaType.TEXT_PLAIN), isA(HttpOutputMessage.class));
<add> }
<add>
<add>
<ide> @SuppressWarnings("unused")
<ide> public ResponseEntity<String> handle1(HttpEntity<String> httpEntity, ResponseEntity<String> entity,
<ide> int i, RequestEntity<String> requestEntity) {
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/support/WebContentGeneratorTests.java
<ide> */
<ide> package org.springframework.web.servlet.support;
<ide>
<add>import java.util.Arrays;
<add>
<ide> import org.junit.Test;
<ide>
<add>import org.springframework.mock.web.test.MockHttpServletResponse;
<add>
<ide> import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertNull;
<ide>
<ide> /**
<ide> * Unit tests for {@link WebContentGenerator}.
<ide> * @author Rossen Stoyanchev
<ide> */
<ide> public class WebContentGeneratorTests {
<ide>
<del>
<ide> @Test
<ide> public void getAllowHeaderWithConstructorTrue() throws Exception {
<ide> WebContentGenerator generator = new TestWebContentGenerator(true);
<ide> public void getAllowHeaderWithSupportedMethodsSetterEmpty() throws Exception {
<ide> "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS", generator.getAllowHeader());
<ide> }
<ide>
<add> @Test
<add> public void varyHeaderNone() throws Exception {
<add> WebContentGenerator generator = new TestWebContentGenerator();
<add> MockHttpServletResponse response = new MockHttpServletResponse();
<add> generator.prepareResponse(response);
<add>
<add> assertNull(response.getHeader("Vary"));
<add> }
<add>
<add> @Test
<add> public void varyHeader() throws Exception {
<add> String[] configuredValues = {"Accept-Language", "User-Agent"};
<add> String[] responseValues = {};
<add> String[] expected = {"Accept-Language", "User-Agent"};
<add> testVaryHeader(configuredValues, responseValues, expected);
<add> }
<add>
<add> @Test
<add> public void varyHeaderWithExistingWildcard() throws Exception {
<add> String[] configuredValues = {"Accept-Language"};
<add> String[] responseValues = {"*"};
<add> String[] expected = {"*"};
<add> testVaryHeader(configuredValues, responseValues, expected);
<add> }
<add>
<add> @Test
<add> public void varyHeaderWithExistingCommaValues() throws Exception {
<add> String[] configuredValues = {"Accept-Language", "User-Agent"};
<add> String[] responseValues = {"Accept-Encoding", "Accept-Language"};
<add> String[] expected = {"Accept-Encoding", "Accept-Language", "User-Agent"};
<add> testVaryHeader(configuredValues, responseValues, expected);
<add> }
<add>
<add> @Test
<add> public void varyHeaderWithExistingCommaSeparatedValues() throws Exception {
<add> String[] configuredValues = {"Accept-Language", "User-Agent"};
<add> String[] responseValues = {"Accept-Encoding, Accept-Language"};
<add> String[] expected = {"Accept-Encoding, Accept-Language", "User-Agent"};
<add> testVaryHeader(configuredValues, responseValues, expected);
<add> }
<add>
<add> private void testVaryHeader(String[] configuredValues, String[] responseValues, String[] expected) {
<add> WebContentGenerator generator = new TestWebContentGenerator();
<add> generator.setVaryByRequestHeaders(configuredValues);
<add> MockHttpServletResponse response = new MockHttpServletResponse();
<add> for (String value : responseValues) {
<add> response.addHeader("Vary", value);
<add> }
<add> generator.prepareResponse(response);
<add> assertEquals(Arrays.asList(expected), response.getHeaderValues("Vary"));
<add> }
<add>
<ide>
<ide> private static class TestWebContentGenerator extends WebContentGenerator {
<ide> | 6 |
Java | Java | drop support for jetty 9.3 and okhttp 2.x | 47c4cf7abf231018e102bf51d83dd92c656f8996 | <ide><path>spring-web/src/main/java/org/springframework/http/client/OkHttpAsyncClientHttpRequest.java
<del>/*
<del> * Copyright 2002-2016 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.http.client;
<del>
<del>import java.io.IOException;
<del>import java.net.URI;
<del>
<del>import com.squareup.okhttp.Call;
<del>import com.squareup.okhttp.Callback;
<del>import com.squareup.okhttp.OkHttpClient;
<del>import com.squareup.okhttp.Request;
<del>import com.squareup.okhttp.Response;
<del>
<del>import org.springframework.http.HttpHeaders;
<del>import org.springframework.http.HttpMethod;
<del>import org.springframework.util.concurrent.ListenableFuture;
<del>import org.springframework.util.concurrent.SettableListenableFuture;
<del>
<del>/**
<del> * {@link AsyncClientHttpRequest} implementation based on OkHttp 2.x.
<del> *
<del> * <p>Created via the {@link OkHttpClientHttpRequestFactory}.
<del> *
<del> * @author Luciano Leggieri
<del> * @author Arjen Poutsma
<del> * @since 4.3
<del> * @see org.springframework.http.client.OkHttp3AsyncClientHttpRequest
<del> * @deprecated as of Spring 5.0, in favor of OkHttp 3.x
<del> */
<del>@Deprecated
<del>class OkHttpAsyncClientHttpRequest extends AbstractBufferingAsyncClientHttpRequest {
<del>
<del> private final OkHttpClient client;
<del>
<del> private final URI uri;
<del>
<del> private final HttpMethod method;
<del>
<del>
<del> public OkHttpAsyncClientHttpRequest(OkHttpClient client, URI uri, HttpMethod method) {
<del> this.client = client;
<del> this.uri = uri;
<del> this.method = method;
<del> }
<del>
<del>
<del> @Override
<del> public HttpMethod getMethod() {
<del> return this.method;
<del> }
<del>
<del> @Override
<del> public URI getURI() {
<del> return this.uri;
<del> }
<del>
<del> @Override
<del> protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers, byte[] content)
<del> throws IOException {
<del>
<del> Request request = OkHttpClientHttpRequestFactory.buildRequest(headers, content, this.uri, this.method);
<del> return new OkHttpListenableFuture(this.client.newCall(request));
<del> }
<del>
<del>
<del> @Deprecated
<del> private static class OkHttpListenableFuture extends SettableListenableFuture<ClientHttpResponse> {
<del>
<del> private final Call call;
<del>
<del> public OkHttpListenableFuture(Call call) {
<del> this.call = call;
<del> this.call.enqueue(new Callback() {
<del> @Override
<del> public void onResponse(Response response) {
<del> set(new OkHttpClientHttpResponse(response));
<del> }
<del> @Override
<del> public void onFailure(Request request, IOException ex) {
<del> setException(ex);
<del> }
<del> });
<del> }
<del>
<del> @Override
<del> protected void interruptTask() {
<del> this.call.cancel();
<del> }
<del> }
<del>
<del>}
<ide><path>spring-web/src/main/java/org/springframework/http/client/OkHttpClientHttpRequest.java
<del>/*
<del> * Copyright 2002-2016 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.http.client;
<del>
<del>import java.io.IOException;
<del>import java.net.URI;
<del>
<del>import com.squareup.okhttp.OkHttpClient;
<del>import com.squareup.okhttp.Request;
<del>
<del>import org.springframework.http.HttpHeaders;
<del>import org.springframework.http.HttpMethod;
<del>
<del>/**
<del> * {@link ClientHttpRequest} implementation based on OkHttp 2.x.
<del> *
<del> * <p>Created via the {@link OkHttpClientHttpRequestFactory}.
<del> *
<del> * @author Luciano Leggieri
<del> * @author Arjen Poutsma
<del> * @since 4.2
<del> * @see org.springframework.http.client.OkHttp3ClientHttpRequest
<del> * @deprecated as of Spring 5.0, in favor of OkHttp 3.x
<del> */
<del>@Deprecated
<del>class OkHttpClientHttpRequest extends AbstractBufferingClientHttpRequest {
<del>
<del> private final OkHttpClient client;
<del>
<del> private final URI uri;
<del>
<del> private final HttpMethod method;
<del>
<del>
<del> public OkHttpClientHttpRequest(OkHttpClient client, URI uri, HttpMethod method) {
<del> this.client = client;
<del> this.uri = uri;
<del> this.method = method;
<del> }
<del>
<del>
<del> @Override
<del> public HttpMethod getMethod() {
<del> return this.method;
<del> }
<del>
<del> @Override
<del> public URI getURI() {
<del> return this.uri;
<del> }
<del>
<del>
<del> @Override
<del> protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] content) throws IOException {
<del> Request request = OkHttpClientHttpRequestFactory.buildRequest(headers, content, this.uri, this.method);
<del> return new OkHttpClientHttpResponse(this.client.newCall(request).execute());
<del> }
<del>
<del>}
<ide><path>spring-web/src/main/java/org/springframework/http/client/OkHttpClientHttpRequestFactory.java
<del>/*
<del> * Copyright 2002-2016 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.http.client;
<del>
<del>import java.io.IOException;
<del>import java.net.MalformedURLException;
<del>import java.net.URI;
<del>import java.util.List;
<del>import java.util.Map;
<del>import java.util.concurrent.TimeUnit;
<del>
<del>import com.squareup.okhttp.OkHttpClient;
<del>import com.squareup.okhttp.Request;
<del>import com.squareup.okhttp.RequestBody;
<del>
<del>import org.springframework.beans.factory.DisposableBean;
<del>import org.springframework.http.HttpHeaders;
<del>import org.springframework.http.HttpMethod;
<del>import org.springframework.util.Assert;
<del>import org.springframework.util.StringUtils;
<del>
<del>/**
<del> * {@link ClientHttpRequestFactory} implementation that uses
<del> * <a href="http://square.github.io/okhttp/">OkHttp</a> 2.x to create requests.
<del> *
<del> * @author Luciano Leggieri
<del> * @author Arjen Poutsma
<del> * @since 4.2
<del> * @see org.springframework.http.client.OkHttp3ClientHttpRequestFactory
<del> * @deprecated as of Spring 5.0, in favor of OkHttp 3.x
<del> */
<del>@Deprecated
<del>public class OkHttpClientHttpRequestFactory
<del> implements ClientHttpRequestFactory, AsyncClientHttpRequestFactory, DisposableBean {
<del>
<del> private final OkHttpClient client;
<del>
<del> private final boolean defaultClient;
<del>
<del>
<del> /**
<del> * Create a factory with a default {@link OkHttpClient} instance.
<del> */
<del> public OkHttpClientHttpRequestFactory() {
<del> this.client = new OkHttpClient();
<del> this.defaultClient = true;
<del> }
<del>
<del> /**
<del> * Create a factory with the given {@link OkHttpClient} instance.
<del> * @param client the client to use
<del> */
<del> public OkHttpClientHttpRequestFactory(OkHttpClient client) {
<del> Assert.notNull(client, "OkHttpClient must not be null");
<del> this.client = client;
<del> this.defaultClient = false;
<del> }
<del>
<del>
<del> /**
<del> * Sets the underlying read timeout in milliseconds.
<del> * A value of 0 specifies an infinite timeout.
<del> * @see OkHttpClient#setReadTimeout(long, TimeUnit)
<del> */
<del> public void setReadTimeout(int readTimeout) {
<del> this.client.setReadTimeout(readTimeout, TimeUnit.MILLISECONDS);
<del> }
<del>
<del> /**
<del> * Sets the underlying write timeout in milliseconds.
<del> * A value of 0 specifies an infinite timeout.
<del> * @see OkHttpClient#setWriteTimeout(long, TimeUnit)
<del> */
<del> public void setWriteTimeout(int writeTimeout) {
<del> this.client.setWriteTimeout(writeTimeout, TimeUnit.MILLISECONDS);
<del> }
<del>
<del> /**
<del> * Sets the underlying connect timeout in milliseconds.
<del> * A value of 0 specifies an infinite timeout.
<del> * @see OkHttpClient#setConnectTimeout(long, TimeUnit)
<del> */
<del> public void setConnectTimeout(int connectTimeout) {
<del> this.client.setConnectTimeout(connectTimeout, TimeUnit.MILLISECONDS);
<del> }
<del>
<del>
<del> @Override
<del> public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) {
<del> return new OkHttpClientHttpRequest(this.client, uri, httpMethod);
<del> }
<del>
<del> @Override
<del> public AsyncClientHttpRequest createAsyncRequest(URI uri, HttpMethod httpMethod) {
<del> return new OkHttpAsyncClientHttpRequest(this.client, uri, httpMethod);
<del> }
<del>
<del>
<del> @Override
<del> public void destroy() throws IOException {
<del> if (this.defaultClient) {
<del> // Clean up the client if we created it in the constructor
<del> if (this.client.getCache() != null) {
<del> this.client.getCache().close();
<del> }
<del> this.client.getDispatcher().getExecutorService().shutdown();
<del> }
<del> }
<del>
<del>
<del> static Request buildRequest(HttpHeaders headers, byte[] content, URI uri, HttpMethod method)
<del> throws MalformedURLException {
<del>
<del> com.squareup.okhttp.MediaType contentType = getContentType(headers);
<del> RequestBody body = (content.length > 0 ||
<del> com.squareup.okhttp.internal.http.HttpMethod.requiresRequestBody(method.name()) ?
<del> RequestBody.create(contentType, content) : null);
<del>
<del> Request.Builder builder = new Request.Builder().url(uri.toURL()).method(method.name(), body);
<del> for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
<del> String headerName = entry.getKey();
<del> for (String headerValue : entry.getValue()) {
<del> builder.addHeader(headerName, headerValue);
<del> }
<del> }
<del> return builder.build();
<del> }
<del>
<del> private static com.squareup.okhttp.MediaType getContentType(HttpHeaders headers) {
<del> String rawContentType = headers.getFirst(HttpHeaders.CONTENT_TYPE);
<del> return (StringUtils.hasText(rawContentType) ?
<del> com.squareup.okhttp.MediaType.parse(rawContentType) : null);
<del> }
<del>
<del>}
<ide><path>spring-web/src/main/java/org/springframework/http/client/OkHttpClientHttpResponse.java
<del>/*
<del> * Copyright 2002-2016 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.http.client;
<del>
<del>import java.io.IOException;
<del>import java.io.InputStream;
<del>
<del>import com.squareup.okhttp.Response;
<del>
<del>import org.springframework.http.HttpHeaders;
<del>import org.springframework.util.Assert;
<del>
<del>/**
<del> * {@link ClientHttpResponse} implementation based on OkHttp 2.x.
<del> *
<del> * @author Luciano Leggieri
<del> * @author Arjen Poutsma
<del> * @since 4.2
<del> * @see org.springframework.http.client.OkHttp3ClientHttpResponse
<del> * @deprecated as of Spring 5.0, in favor of OkHttp 3.x
<del> */
<del>@Deprecated
<del>class OkHttpClientHttpResponse extends AbstractClientHttpResponse {
<del>
<del> private final Response response;
<del>
<del> private HttpHeaders headers;
<del>
<del>
<del> public OkHttpClientHttpResponse(Response response) {
<del> Assert.notNull(response, "Response must not be null");
<del> this.response = response;
<del> }
<del>
<del>
<del> @Override
<del> public int getRawStatusCode() {
<del> return this.response.code();
<del> }
<del>
<del> @Override
<del> public String getStatusText() {
<del> return this.response.message();
<del> }
<del>
<del> @Override
<del> public InputStream getBody() throws IOException {
<del> return this.response.body().byteStream();
<del> }
<del>
<del> @Override
<del> public HttpHeaders getHeaders() {
<del> if (this.headers == null) {
<del> HttpHeaders headers = new HttpHeaders();
<del> for (String headerName : this.response.headers().names()) {
<del> for (String headerValue : this.response.headers(headerName)) {
<del> headers.add(headerName, headerValue);
<del> }
<del> }
<del> this.headers = headers;
<del> }
<del> return this.headers;
<del> }
<del>
<del> @Override
<del> public void close() {
<del> try {
<del> this.response.body().close();
<del> }
<del> catch (IOException ex) {
<del> // ignore
<del> }
<del> }
<del>
<del>}
<ide><path>spring-web/src/test/java/org/springframework/http/client/OkHttpAsyncClientHttpRequestFactoryTests.java
<del>/*
<del> * Copyright 2002-2016 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.http.client;
<del>
<del>import org.junit.Test;
<del>
<del>import org.springframework.http.HttpMethod;
<del>
<del>/**
<del> * @author Luciano Leggieri
<del> */
<del>public class OkHttpAsyncClientHttpRequestFactoryTests extends AbstractAsyncHttpRequestFactoryTestCase {
<del>
<del> @Override
<del> @SuppressWarnings("deprecation")
<del> protected AsyncClientHttpRequestFactory createRequestFactory() {
<del> return new OkHttpClientHttpRequestFactory();
<del> }
<del>
<del> @Override
<del> @Test
<del> public void httpMethods() throws Exception {
<del> super.httpMethods();
<del> assertHttpMethod("patch", HttpMethod.PATCH);
<del> }
<del>
<del>}
<ide><path>spring-web/src/test/java/org/springframework/http/client/OkHttpClientHttpRequestFactoryTests.java
<del>/*
<del> * Copyright 2002-2016 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.http.client;
<del>
<del>import org.junit.Test;
<del>
<del>import org.springframework.http.HttpMethod;
<del>
<del>/**
<del> * @author Luciano Leggieri
<del> */
<del>public class OkHttpClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase {
<del>
<del> @Override
<del> @SuppressWarnings("deprecation")
<del> protected ClientHttpRequestFactory createRequestFactory() {
<del> return new OkHttpClientHttpRequestFactory();
<del> }
<del>
<del> @Override
<del> @Test
<del> public void httpMethods() throws Exception {
<del> super.httpMethods();
<del> assertHttpMethod("patch", HttpMethod.PATCH);
<del> }
<del>
<del>}
<ide><path>spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java
<ide> public static Iterable<? extends ClientHttpRequestFactory> data() {
<ide> new SimpleClientHttpRequestFactory(),
<ide> new HttpComponentsClientHttpRequestFactory(),
<ide> new Netty4ClientHttpRequestFactory(),
<del> new OkHttp3ClientHttpRequestFactory(),
<del> new org.springframework.http.client.OkHttpClientHttpRequestFactory()
<add> new OkHttp3ClientHttpRequestFactory()
<ide> );
<ide> }
<ide>
<add>
<ide> @Before
<del> public void setUpClient() {
<add> public void setupClient() {
<ide> this.template = new RestTemplate(this.clientHttpRequestFactory);
<ide> }
<ide>
<add>
<ide> @Test
<ide> public void getString() {
<ide> String s = template.getForObject(baseUrl + "/{method}", String.class, "get");
<ide><path>spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java
<ide> import org.springframework.http.converter.HttpMessageConverter;
<ide> import org.springframework.web.util.DefaultUriBuilderFactory;
<ide>
<del>import static org.junit.Assert.assertEquals;
<del>import static org.junit.Assert.assertFalse;
<del>import static org.junit.Assert.assertNull;
<del>import static org.junit.Assert.assertSame;
<del>import static org.junit.Assert.fail;
<del>import static org.mockito.BDDMockito.any;
<del>import static org.mockito.BDDMockito.eq;
<del>import static org.mockito.BDDMockito.given;
<del>import static org.mockito.BDDMockito.mock;
<del>import static org.mockito.BDDMockito.verify;
<del>import static org.mockito.BDDMockito.willThrow;
<add>import static org.junit.Assert.*;
<add>import static org.mockito.BDDMockito.*;
<ide>
<ide> /**
<ide> * @author Arjen Poutsma
<ide> public class RestTemplateTests {
<ide> @SuppressWarnings("rawtypes")
<ide> private HttpMessageConverter converter;
<ide>
<add>
<ide> @Before
<del> public void setUp() {
<add> public void setup() {
<ide> requestFactory = mock(ClientHttpRequestFactory.class);
<ide> request = mock(ClientHttpRequest.class);
<ide> response = mock(ClientHttpResponse.class);
<ide> public void setUp() {
<ide> template.setErrorHandler(errorHandler);
<ide> }
<ide>
<add>
<ide> @Test
<ide> public void varArgsTemplateVariables() throws Exception {
<ide> given(requestFactory.createRequest(new URI("http://example.com/hotels/42/bookings/21"), HttpMethod.GET))
<ide> public void exchangeParameterizedType() throws Exception {
<ide>
<ide> verify(response).close();
<ide> }
<add>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/adapter/jetty/JettyWebSocketSession.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 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> package org.springframework.web.socket.adapter.jetty;
<ide>
<ide> import java.io.IOException;
<del>import java.lang.reflect.Method;
<ide> import java.net.InetSocketAddress;
<ide> import java.net.URI;
<ide> import java.security.Principal;
<ide>
<ide> import org.eclipse.jetty.websocket.api.RemoteEndpoint;
<ide> import org.eclipse.jetty.websocket.api.Session;
<del>import org.eclipse.jetty.websocket.api.UpgradeRequest;
<del>import org.eclipse.jetty.websocket.api.UpgradeResponse;
<ide> import org.eclipse.jetty.websocket.api.WebSocketException;
<ide> import org.eclipse.jetty.websocket.api.extensions.ExtensionConfig;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.util.CollectionUtils;
<ide> import org.springframework.util.ObjectUtils;
<del>import org.springframework.util.ReflectionUtils;
<ide> import org.springframework.web.socket.BinaryMessage;
<ide> import org.springframework.web.socket.CloseStatus;
<ide> import org.springframework.web.socket.PingMessage;
<ide> import org.springframework.web.socket.adapter.AbstractWebSocketSession;
<ide>
<ide> /**
<del> * A {@link WebSocketSession} for use with the Jetty 9.3/9.4 WebSocket API.
<add> * A {@link WebSocketSession} for use with the Jetty 9.4 WebSocket API.
<ide> *
<ide> * @author Phillip Webb
<ide> * @author Rossen Stoyanchev
<ide> */
<ide> public class JettyWebSocketSession extends AbstractWebSocketSession<Session> {
<ide>
<del> // As of Jetty 9.4, UpgradeRequest and UpgradeResponse are interfaces instead of classes
<del> private static final boolean directInterfaceCalls;
<del>
<del> private static Method getUpgradeRequest;
<del> private static Method getUpgradeResponse;
<del> private static Method getRequestURI;
<del> private static Method getHeaders;
<del> private static Method getUserPrincipal;
<del> private static Method getAcceptedSubProtocol;
<del> private static Method getExtensions;
<del>
<del> static {
<del> directInterfaceCalls = UpgradeRequest.class.isInterface();
<del> if (!directInterfaceCalls) {
<del> try {
<del> getUpgradeRequest = Session.class.getMethod("getUpgradeRequest");
<del> getUpgradeResponse = Session.class.getMethod("getUpgradeResponse");
<del> getRequestURI = UpgradeRequest.class.getMethod("getRequestURI");
<del> getHeaders = UpgradeRequest.class.getMethod("getHeaders");
<del> getUserPrincipal = UpgradeRequest.class.getMethod("getUserPrincipal");
<del> getAcceptedSubProtocol = UpgradeResponse.class.getMethod("getAcceptedSubProtocol");
<del> getExtensions = UpgradeResponse.class.getMethod("getExtensions");
<del> }
<del> catch (NoSuchMethodException ex) {
<del> throw new IllegalStateException("Incompatible Jetty API", ex);
<del> }
<del> }
<del> }
<del>
<del>
<ide> private String id;
<ide>
<ide> private URI uri;
<ide> public boolean isOpen() {
<ide> @Override
<ide> public void initializeNativeSession(Session session) {
<ide> super.initializeNativeSession(session);
<del> if (directInterfaceCalls) {
<del> initializeJettySessionDirectly(session);
<del> }
<del> else {
<del> initializeJettySessionReflectively(session);
<del> }
<del> }
<ide>
<del> private void initializeJettySessionDirectly(Session session) {
<ide> this.id = ObjectUtils.getIdentityHexString(getNativeSession());
<ide> this.uri = session.getUpgradeRequest().getRequestURI();
<ide>
<del> this.headers = new HttpHeaders();
<del> this.headers.putAll(session.getUpgradeRequest().getHeaders());
<del> this.headers = HttpHeaders.readOnlyHttpHeaders(this.headers);
<add> HttpHeaders headers = new HttpHeaders();
<add> headers.putAll(session.getUpgradeRequest().getHeaders());
<add> this.headers = HttpHeaders.readOnlyHttpHeaders(headers);
<ide>
<ide> this.acceptedProtocol = session.getUpgradeResponse().getAcceptedSubProtocol();
<ide>
<ide> List<ExtensionConfig> jettyExtensions = session.getUpgradeResponse().getExtensions();
<ide> if (!CollectionUtils.isEmpty(jettyExtensions)) {
<del> this.extensions = new ArrayList<>(jettyExtensions.size());
<add> List<WebSocketExtension> extensions = new ArrayList<>(jettyExtensions.size());
<ide> for (ExtensionConfig jettyExtension : jettyExtensions) {
<del> this.extensions.add(new WebSocketExtension(jettyExtension.getName(), jettyExtension.getParameters()));
<add> extensions.add(new WebSocketExtension(jettyExtension.getName(), jettyExtension.getParameters()));
<ide> }
<del> this.extensions = Collections.unmodifiableList(this.extensions);
<add> this.extensions = Collections.unmodifiableList(extensions);
<ide> }
<ide> else {
<ide> this.extensions = Collections.emptyList();
<ide> private void initializeJettySessionDirectly(Session session) {
<ide> }
<ide> }
<ide>
<del> @SuppressWarnings("unchecked")
<del> private void initializeJettySessionReflectively(Session session) {
<del> Object request = ReflectionUtils.invokeMethod(getUpgradeRequest, session);
<del> Object response = ReflectionUtils.invokeMethod(getUpgradeResponse, session);
<del>
<del> this.id = ObjectUtils.getIdentityHexString(getNativeSession());
<del> this.uri = (URI) ReflectionUtils.invokeMethod(getRequestURI, request);
<del>
<del> this.headers = new HttpHeaders();
<del> this.headers.putAll((Map<String, List<String>>) ReflectionUtils.invokeMethod(getHeaders, request));
<del> this.headers = HttpHeaders.readOnlyHttpHeaders(this.headers);
<del>
<del> this.acceptedProtocol = (String) ReflectionUtils.invokeMethod(getAcceptedSubProtocol, response);
<del>
<del> List<ExtensionConfig> extensions = (List<ExtensionConfig>) ReflectionUtils.invokeMethod(getExtensions, response);
<del> if (!CollectionUtils.isEmpty(extensions)) {
<del> this.extensions = new ArrayList<>(extensions.size());
<del> for (ExtensionConfig extension : extensions) {
<del> this.extensions.add(new WebSocketExtension(extension.getName(), extension.getParameters()));
<del> }
<del> this.extensions = Collections.unmodifiableList(this.extensions);
<del> }
<del> else {
<del> this.extensions = Collections.emptyList();
<del> }
<del>
<del> if (this.user == null) {
<del> this.user = (Principal) ReflectionUtils.invokeMethod(getUserPrincipal, request);
<del> }
<del> }
<del>
<ide>
<ide> @Override
<ide> protected void sendTextMessage(TextMessage message) throws IOException {
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/jetty/JettyRequestUpgradeStrategy.java
<ide> import org.springframework.http.server.ServletServerHttpRequest;
<ide> import org.springframework.http.server.ServletServerHttpResponse;
<ide> import org.springframework.util.Assert;
<del>import org.springframework.util.ClassUtils;
<ide> import org.springframework.util.CollectionUtils;
<ide> import org.springframework.web.context.ServletContextAware;
<ide> import org.springframework.web.socket.WebSocketExtension;
<ide> import org.springframework.web.socket.server.RequestUpgradeStrategy;
<ide>
<ide> /**
<del> * A {@link RequestUpgradeStrategy} for use with Jetty 9.3 and 9.4. Based on
<del> * Jetty's internal {@code org.eclipse.jetty.websocket.server.WebSocketHandler} class.
<add> * A {@link RequestUpgradeStrategy} for use with Jetty 9.4. Based on Jetty's
<add> * internal {@code org.eclipse.jetty.websocket.server.WebSocketHandler} class.
<ide> *
<ide> * @author Phillip Webb
<ide> * @author Rossen Stoyanchev
<ide> public class JettyRequestUpgradeStrategy implements RequestUpgradeStrategy, Serv
<ide> new NamedThreadLocal<>("WebSocketHandlerContainer");
<ide>
<ide>
<del> // Configurable factory adapter due to Jetty 9.3.15+ API differences:
<del> // using WebSocketServerFactory(ServletContext) as a version indicator
<del> private final WebSocketServerFactoryAdapter factoryAdapter =
<del> (ClassUtils.hasConstructor(WebSocketServerFactory.class, ServletContext.class) ?
<del> new ModernJettyWebSocketServerFactoryAdapter() : new LegacyJettyWebSocketServerFactoryAdapter());
<add> private WebSocketPolicy policy;
<add>
<add> private WebSocketServerFactory factory;
<ide>
<ide> private ServletContext servletContext;
<ide>
<ide> public class JettyRequestUpgradeStrategy implements RequestUpgradeStrategy, Serv
<ide> * its default constructor thus using a default {@link WebSocketPolicy}.
<ide> */
<ide> public JettyRequestUpgradeStrategy() {
<del> this.factoryAdapter.setPolicy(WebSocketPolicy.newServerPolicy());
<add> this.policy = WebSocketPolicy.newServerPolicy();
<ide> }
<ide>
<ide> /**
<ide> public JettyRequestUpgradeStrategy() {
<ide> */
<ide> public JettyRequestUpgradeStrategy(WebSocketPolicy policy) {
<ide> Assert.notNull(policy, "WebSocketPolicy must not be null");
<del> this.factoryAdapter.setPolicy(policy);
<add> this.policy = policy;
<ide> }
<ide>
<ide> /**
<ide> public JettyRequestUpgradeStrategy(WebSocketPolicy policy) {
<ide> */
<ide> public JettyRequestUpgradeStrategy(WebSocketServerFactory factory) {
<ide> Assert.notNull(factory, "WebSocketServerFactory must not be null");
<del> this.factoryAdapter.setFactory(factory);
<add> this.factory = factory;
<ide> }
<ide>
<ide>
<ide> public void start() {
<ide> if (!isRunning()) {
<ide> this.running = true;
<ide> try {
<del> this.factoryAdapter.start();
<add> if (this.factory == null) {
<add> this.factory = new WebSocketServerFactory(servletContext, this.policy);
<add> }
<add> this.factory.setCreator(new WebSocketCreator() {
<add> @Override
<add> public Object createWebSocket(ServletUpgradeRequest request, ServletUpgradeResponse response) {
<add> WebSocketHandlerContainer container = containerHolder.get();
<add> Assert.state(container != null, "Expected WebSocketHandlerContainer");
<add> response.setAcceptedSubProtocol(container.getSelectedProtocol());
<add> response.setExtensions(container.getExtensionConfigs());
<add> return container.getHandler();
<add> }
<add> });
<add> this.factory.start();
<ide> }
<ide> catch (Throwable ex) {
<ide> throw new IllegalStateException("Unable to start Jetty WebSocketServerFactory", ex);
<ide> public void start() {
<ide> public void stop() {
<ide> if (isRunning()) {
<ide> this.running = false;
<del> try {
<del> this.factoryAdapter.stop();
<del> }
<del> catch (Throwable ex) {
<del> throw new IllegalStateException("Unable to stop Jetty WebSocketServerFactory", ex);
<add> if (this.factory != null) {
<add> try {
<add> this.factory.stop();
<add> }
<add> catch (Throwable ex) {
<add> throw new IllegalStateException("Unable to stop Jetty WebSocketServerFactory", ex);
<add> }
<ide> }
<ide> }
<ide> }
<ide> public List<WebSocketExtension> getSupportedExtensions(ServerHttpRequest request
<ide> }
<ide>
<ide> private List<WebSocketExtension> buildWebSocketExtensions() {
<del> Set<String> names = this.factoryAdapter.getFactory().getExtensionFactory().getExtensionNames();
<add> Set<String> names = this.factory.getExtensionFactory().getExtensionNames();
<ide> List<WebSocketExtension> result = new ArrayList<>(names.size());
<ide> for (String name : names) {
<ide> result.add(new WebSocketExtension(name));
<ide> public void upgrade(ServerHttpRequest request, ServerHttpResponse response,
<ide> Assert.isInstanceOf(ServletServerHttpResponse.class, response, "ServletServerHttpResponse required");
<ide> HttpServletResponse servletResponse = ((ServletServerHttpResponse) response).getServletResponse();
<ide>
<del> Assert.isTrue(this.factoryAdapter.getFactory().isUpgradeRequest(servletRequest, servletResponse),
<del> "Not a WebSocket handshake");
<add> Assert.isTrue(this.factory.isUpgradeRequest(servletRequest, servletResponse), "Not a WebSocket handshake");
<ide>
<ide> JettyWebSocketSession session = new JettyWebSocketSession(attributes, user);
<ide> JettyWebSocketHandlerAdapter handlerAdapter = new JettyWebSocketHandlerAdapter(wsHandler, session);
<ide> public void upgrade(ServerHttpRequest request, ServerHttpResponse response,
<ide>
<ide> try {
<ide> containerHolder.set(container);
<del> this.factoryAdapter.getFactory().acceptWebSocket(servletRequest, servletResponse);
<add> this.factory.acceptWebSocket(servletRequest, servletResponse);
<ide> }
<ide> catch (IOException ex) {
<ide> throw new HandshakeFailureException(
<ide> public List<ExtensionConfig> getExtensionConfigs() {
<ide> }
<ide> }
<ide>
<del>
<del> private static abstract class WebSocketServerFactoryAdapter {
<del>
<del> private WebSocketPolicy policy;
<del>
<del> private WebSocketServerFactory factory;
<del>
<del> public void setPolicy(WebSocketPolicy policy) {
<del> this.policy = policy;
<del> }
<del>
<del> public void setFactory(WebSocketServerFactory factory) {
<del> this.factory = factory;
<del> }
<del>
<del> public WebSocketServerFactory getFactory() {
<del> return this.factory;
<del> }
<del>
<del> public void start() throws Exception {
<del> if (this.factory == null) {
<del> this.factory = createFactory(this.policy);
<del> }
<del> this.factory.setCreator(new WebSocketCreator() {
<del> @Override
<del> public Object createWebSocket(ServletUpgradeRequest request, ServletUpgradeResponse response) {
<del> WebSocketHandlerContainer container = containerHolder.get();
<del> Assert.state(container != null, "Expected WebSocketHandlerContainer");
<del> response.setAcceptedSubProtocol(container.getSelectedProtocol());
<del> response.setExtensions(container.getExtensionConfigs());
<del> return container.getHandler();
<del> }
<del> });
<del> startFactory(this.factory);
<del> }
<del>
<del> public void stop() throws Exception {
<del> if (this.factory != null) {
<del> stopFactory(this.factory);
<del> }
<del> }
<del>
<del> protected abstract WebSocketServerFactory createFactory(WebSocketPolicy policy) throws Exception;
<del>
<del> protected abstract void startFactory(WebSocketServerFactory factory) throws Exception;
<del>
<del> protected abstract void stopFactory(WebSocketServerFactory factory) throws Exception;
<del> }
<del>
<del>
<del> // Jetty 9.3.15+
<del> private class ModernJettyWebSocketServerFactoryAdapter extends WebSocketServerFactoryAdapter {
<del>
<del> @Override
<del> protected WebSocketServerFactory createFactory(WebSocketPolicy policy) throws Exception {
<del> return new WebSocketServerFactory(servletContext, policy);
<del> }
<del>
<del> @Override
<del> protected void startFactory(WebSocketServerFactory factory) throws Exception {
<del> factory.start();
<del> }
<del>
<del> @Override
<del> protected void stopFactory(WebSocketServerFactory factory) throws Exception {
<del> factory.stop();
<del> }
<del> }
<del>
<del>
<del> // Jetty <9.3.15
<del> private class LegacyJettyWebSocketServerFactoryAdapter extends WebSocketServerFactoryAdapter {
<del>
<del> @Override
<del> protected WebSocketServerFactory createFactory(WebSocketPolicy policy) throws Exception {
<del> return WebSocketServerFactory.class.getConstructor(WebSocketPolicy.class).newInstance(policy);
<del> }
<del>
<del> @Override
<del> protected void startFactory(WebSocketServerFactory factory) throws Exception {
<del> WebSocketServerFactory.class.getMethod("init", ServletContext.class).invoke(factory, servletContext);
<del> }
<del>
<del> @Override
<del> protected void stopFactory(WebSocketServerFactory factory) throws Exception {
<del> WebSocketServerFactory.class.getMethod("cleanup").invoke(factory);
<del> }
<del> }
<del>
<ide> } | 10 |
Ruby | Ruby | perf caching engine, converting to an attr_reader | 53bfaedaca5387bbc27a4ce04ea47367aaf4401a | <ide><path>lib/arel/algebra/relations/utilities/compound.rb
<ide> module Arel
<ide> class Compound
<ide> include Relation
<ide>
<del> attr_reader :relation
<add> attr_reader :relation, :engine
<ide> delegate :joins, :join?, :inserts, :taken, :skipped, :name, :externalizable?,
<ide> :column_for, :sources, :locked, :table_alias, :array,
<ide> :to => :relation
<ide>
<ide> def initialize relation
<ide> @relation = relation
<add> @engine = relation.engine
<ide> @attributes = nil
<ide> @wheres = nil
<ide> @groupings = nil
<ide> def attributes
<ide> def unoperated_rows
<ide> relation.call.collect { |row| row.bind(self) }
<ide> end
<del>
<del> def engine
<del> relation.engine
<del> end
<ide> end
<ide> end | 1 |
PHP | PHP | add sqlite decimal length/precision | ca07ce15a8feafbc02af15f98c2208cea70a60e8 | <ide><path>src/Core/StaticConfigTrait.php
<ide> public static function parseDsn(string $dsn): array
<ide> $parsed['className'] = $classMap[$parsed['scheme']];
<ide> }
<ide> }
<del>
<add>
<ide> return $parsed;
<ide> }
<ide>
<ide><path>src/Database/Schema/SqliteSchema.php
<ide> protected function _convertColumn(string $column): array
<ide> }
<ide>
<ide> $col = strtolower($matches[2]);
<del> $length = null;
<add> $length = $precision = null;
<ide> if (isset($matches[3])) {
<del> $length = (int)$matches[3];
<add> $length = $matches[3];
<add> if (strpos($length, ',') !== false) {
<add> [$length, $precision] = explode(',', $length);
<add> }
<add> $length = (int)$length;
<add> $precision = (int)$precision;
<ide> }
<ide>
<ide> if ($col === 'bigint') {
<ide> protected function _convertColumn(string $column): array
<ide> return ['type' => TableSchema::TYPE_INTEGER, 'length' => $length, 'unsigned' => $unsigned];
<ide> }
<ide> if (strpos($col, 'decimal') !== false) {
<del> return ['type' => TableSchema::TYPE_DECIMAL, 'length' => null, 'unsigned' => $unsigned];
<add> return ['type' => TableSchema::TYPE_DECIMAL, 'length' => $length, 'precision' => $precision, 'unsigned' => $unsigned];
<ide> }
<ide> if (in_array($col, ['float', 'real', 'double'])) {
<del> return ['type' => TableSchema::TYPE_FLOAT, 'length' => null, 'unsigned' => $unsigned];
<add> return ['type' => TableSchema::TYPE_FLOAT, 'length' => $length, 'precision' => $precision, 'unsigned' => $unsigned];
<ide> }
<ide>
<ide> if (strpos($col, 'boolean') !== false) { | 2 |
Ruby | Ruby | fix app and actions generators tests | f8294cb8bac6357727e7d5df5623349105c6f996 | <ide><path>railties/test/generators/actions_test.rb
<ide> class ActionsTest < Rails::Generators::TestCase
<ide> arguments [destination_root]
<ide>
<ide> def setup
<add> Rails.application = TestApp::Application
<ide> super
<ide> @git_plugin_uri = 'git://github.com/technoweenie/restful-authentication.git'
<ide> @svn_plugin_uri = 'svn://svnhub.com/technoweenie/restful-authentication/trunk'
<ide> end
<ide>
<add> def teardown
<add> Rails.application = TestApp::Application.instance
<add> end
<add>
<ide> def test_invoke_other_generator_with_shortcut
<ide> action :invoke, 'model', ['my_model']
<ide> assert_file 'app/models/my_model.rb', /MyModel/
<ide><path>railties/test/generators/app_generator_test.rb
<ide> class AppGeneratorTest < Rails::Generators::TestCase
<ide> arguments [destination_root]
<ide>
<ide> def setup
<add> Rails.application = TestApp::Application
<ide> super
<ide> Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
<ide> @bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle')
<ide> def setup
<ide> def teardown
<ide> super
<ide> Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
<add> Rails.application = TestApp::Application.instance
<ide> end
<ide>
<ide> def test_application_skeleton_is_created
<ide> class CustomAppGeneratorTest < Rails::Generators::TestCase
<ide> arguments [destination_root]
<ide>
<ide> def setup
<add> Rails.application = TestApp::Application
<ide> super
<ide> Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
<ide> @bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle')
<ide> def teardown
<ide> super
<ide> Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
<ide> Object.class_eval { remove_const :AppBuilder if const_defined?(:AppBuilder) }
<add> Rails.application = TestApp::Application.instance
<ide> end
<ide>
<ide> def test_builder_option_with_empty_app_builder | 2 |
Javascript | Javascript | keep chunk ids | c5b52b547c8c2c683217a9ea175398a2e4922c4d | <ide><path>lib/Compilation.js
<ide> Compilation.prototype.applyModuleIds = function applyModuleIds() {
<ide> };
<ide>
<ide> Compilation.prototype.applyChunkIds = function applyChunkIds() {
<del> var i = 0;
<add> var i = this.cache && this.cache["nextChunkId"] || 1;
<add> var usedIds = {0:true};
<add> if(this.cache) {
<add> if(!this.cache.chunks)
<add> this.cache.chunks = {};
<add> var keys = Object.keys(this.cache.chunks).slice();
<add> var cacheChunks = this.cache.chunks;
<add> this.cache.chunks = {};
<add> }
<ide> this.chunks.forEach(function(chunk) {
<del> if(chunk.id === null)
<del> chunk.id = ++i;
<add> if(chunk.id === null) {
<add> if(this.cache) {
<add> for(var j = 0; j < keys.length; j++) {
<add> var chunkId = keys[j];
<add> var cacheChunk = cacheChunks[chunkId];
<add> if(usedIds[cacheChunk.id]) continue;
<add> if(chunk.blocks.some(function(block) {
<add> return cacheChunk.blocks.indexOf(block) >= 0;
<add> })) {
<add> usedIds[cacheChunk.id] = true;
<add> chunk.id = cacheChunk.id;
<add> break;
<add> }
<add> }
<add> }
<add> if(chunk.id === null)
<add> chunk.id = i++;
<add> if(this.cache) {
<add> this.cache.chunks["c"+chunk.id] = {
<add> id: chunk.id,
<add> blocks: chunk.blocks
<add> };
<add> }
<add> }
<ide> if(!chunk.ids)
<ide> chunk.ids = [chunk.id];
<del> });
<add> }, this);
<add> if(this.cache) this.cache["nextChunkId"] = i;
<ide> };
<ide>
<ide> Compilation.prototype.sortItems = function sortItems() { | 1 |
Go | Go | correct command annotation | b642282990fe19f1dd7add0313c05cd139c52819 | <ide><path>api/client/image/history.go
<ide> type historyOptions struct {
<ide> noTrunc bool
<ide> }
<ide>
<del>// NewHistoryCommand create a new `docker history` command
<add>// NewHistoryCommand creates a new `docker history` command
<ide> func NewHistoryCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide> var opts historyOptions
<ide>
<ide><path>api/client/image/images.go
<ide> type imagesOptions struct {
<ide> filter []string
<ide> }
<ide>
<del>// NewImagesCommand create a new `docker images` command
<add>// NewImagesCommand creates a new `docker images` command
<ide> func NewImagesCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide> var opts imagesOptions
<ide>
<ide><path>api/client/image/remove.go
<ide> type removeOptions struct {
<ide> noPrune bool
<ide> }
<ide>
<del>// NewRemoveCommand create a new `docker remove` command
<add>// NewRemoveCommand creates a new `docker remove` command
<ide> func NewRemoveCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide> var opts removeOptions
<ide>
<ide><path>api/client/image/search.go
<ide> type searchOptions struct {
<ide> automated bool
<ide> }
<ide>
<del>// NewSearchCommand create a new `docker search` command
<add>// NewSearchCommand creates a new `docker search` command
<ide> func NewSearchCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide> var opts searchOptions
<ide>
<ide><path>api/client/image/tag.go
<ide> type tagOptions struct {
<ide> name string
<ide> }
<ide>
<del>// NewTagCommand create a new `docker tag` command
<add>// NewTagCommand creates a new `docker tag` command
<ide> func NewTagCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide> var opts tagOptions
<ide> | 5 |
PHP | PHP | update controller tests | 72bf1ca460104c1b70f0cdd11aa8baaf70814af0 | <ide><path>lib/Cake/Controller/Controller.php
<ide> public function __isset($name) {
<ide> */
<ide> public function __get($name) {
<ide> switch ($name) {
<del> case 'base':
<del> case 'here':
<del> case 'webroot':
<del> case 'data':
<del> return $this->request->{$name};
<del> case 'action':
<del> return isset($this->request->params['action']) ? $this->request->params['action'] : '';
<del> case 'params':
<del> return $this->request;
<ide> case 'paginate':
<ide> return $this->Components->load('Paginator')->settings;
<ide> }
<ide> public function __get($name) {
<ide> */
<ide> public function __set($name, $value) {
<ide> switch ($name) {
<del> case 'base':
<del> case 'here':
<del> case 'webroot':
<del> case 'data':
<del> return $this->request->{$name} = $value;
<del> case 'action':
<del> return $this->request->params['action'] = $value;
<del> case 'params':
<del> return $this->request->params = $value;
<ide> case 'paginate':
<ide> return $this->Components->load('Paginator')->settings = $value;
<ide> }
<ide> public function render($view = null, $layout = null) {
<ide> $models = ClassRegistry::keys();
<ide> foreach ($models as $currentModel) {
<ide> $currentObject = ClassRegistry::getObject($currentModel);
<del> if (is_a($currentObject, 'Model')) {
<add> if ($currentObject instanceof \Cake\Model\Model) {
<ide> $className = get_class($currentObject);
<del> list($plugin) = pluginSplit(App::location($className));
<del> $this->request->params['models'][$currentObject->alias] = compact('plugin', 'className');
<add> $this->request->params['models'][$currentObject->alias] = compact('className');
<ide> $View->validationErrors[$currentObject->alias] =& $currentObject->validationErrors;
<ide> }
<ide> }
<ide> public function flash($message, $url, $pause = 1, $layout = 'flash') {
<ide> $this->render(false, $layout);
<ide> }
<ide>
<del>/**
<del> * Converts POST'ed form data to a model conditions array, suitable for use in a Model::find() call.
<del> *
<del> * @param array $data POST'ed data organized by model and field
<del> * @param string|array $op A string containing an SQL comparison operator, or an array matching operators
<del> * to fields
<del> * @param string $bool SQL boolean operator: AND, OR, XOR, etc.
<del> * @param boolean $exclusive If true, and $op is an array, fields not included in $op will not be
<del> * included in the returned conditions
<del> * @return array An array of model conditions
<del> * @deprecated
<del> */
<del> public function postConditions($data = array(), $op = null, $bool = 'AND', $exclusive = false) {
<del> if (!is_array($data) || empty($data)) {
<del> if (!empty($this->request->data)) {
<del> $data = $this->request->data;
<del> } else {
<del> return null;
<del> }
<del> }
<del> $cond = array();
<del>
<del> if ($op === null) {
<del> $op = '';
<del> }
<del>
<del> $arrayOp = is_array($op);
<del> foreach ($data as $model => $fields) {
<del> foreach ($fields as $field => $value) {
<del> $key = $model . '.' . $field;
<del> $fieldOp = $op;
<del> if ($arrayOp) {
<del> if (array_key_exists($key, $op)) {
<del> $fieldOp = $op[$key];
<del> } elseif (array_key_exists($field, $op)) {
<del> $fieldOp = $op[$field];
<del> } else {
<del> $fieldOp = false;
<del> }
<del> }
<del> if ($exclusive && $fieldOp === false) {
<del> continue;
<del> }
<del> $fieldOp = strtoupper(trim($fieldOp));
<del> if ($fieldOp === 'LIKE') {
<del> $key = $key . ' LIKE';
<del> $value = '%' . $value . '%';
<del> } elseif ($fieldOp && $fieldOp != '=') {
<del> $key = $key . ' ' . $fieldOp;
<del> }
<del> $cond[$key] = $value;
<del> }
<del> }
<del> if ($bool != null && strtoupper($bool) != 'AND') {
<del> $cond = array($bool => $cond);
<del> }
<del> return $cond;
<del> }
<del>
<ide> /**
<ide> * Handles automatic pagination of model records.
<ide> *
<ide><path>lib/Cake/Test/TestApp/Controller/AppController.php
<ide> <?php
<ide> /**
<del> * Application level Controller
<del> *
<del> * This file is application-wide controller file. You can put all
<del> * application-wide controller-related methods here.
<del> *
<del> * PHP 5
<del> *
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<ide> *
<ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> * @link http://cakephp.org CakePHP(tm) Project
<del> * @package Cake.Controller
<ide> * @since CakePHP(tm) v 0.2.9
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> * will inherit them.
<ide> *
<ide> * @package Cake.Controller
<del> * @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
<ide> */
<ide> class AppController extends Controller {
<ide> }
<ide><path>lib/Cake/Test/TestApp/Controller/CommentsController.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP Project
<add> * @package Cake.Test.TestApp.Controller
<add> * @since CakePHP(tm) v 3.0.0
<add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<add> */
<add>namespace TestApp\Controller;
<add>
<add>use TestApp\Controller\AppController;
<add>
<add>/**
<add> * ControllerPostsController class
<add> *
<add> * @package Cake.Test.Case.Controller
<add> */
<add>class CommentsController extends AppController {
<add>
<add> protected $_mergeParent = 'ControllerTestAppController';
<add>}
<ide><path>lib/Cake/Test/TestCase/Controller/Component/Acl/DbAclTest.php
<ide> <?php
<ide> /**
<del> * DbAclTest file.
<del> *
<del> * PHP 5
<del> *
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<ide> *
<ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> * @link http://cakephp.org CakePHP(tm) Project
<del> * @package Cake.Test.Case.Controller.Component.Acl
<ide> * @since CakePHP(tm) v 2.0
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<del>
<ide> namespace Cake\Test\TestCase\Controller\Component\Acl;
<add>
<ide> use Cake\Controller\ComponentCollection;
<ide> use Cake\Controller\Component\AclComponent;
<ide> use Cake\Controller\Component\Acl\DbAcl;
<ide> class DbAclTest extends TestCase {
<ide> */
<ide> public function setUp() {
<ide> parent::setUp();
<add> $this->markTestIncomplete('DbAcl will not work until models do.');
<ide> Configure::write('Acl.classname', __NAMESPACE__ . '\DbAclTwoTest');
<ide> Configure::write('Acl.database', 'test');
<ide> $Collection = new ComponentCollection();
<ide><path>lib/Cake/Test/TestCase/Controller/ControllerTest.php
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> namespace Cake\Test\TestCase\Controller;
<add>
<ide> use Cake\Controller\Controller;
<ide> use Cake\Core\App;
<add>use Cake\Core\Configure;
<ide> use Cake\Core\Object;
<ide> use Cake\Core\Plugin;
<ide> use Cake\Network\Request;
<ide> public function find($type = 'first', $options = array()) {
<ide>
<ide> }
<ide>
<del>/**
<del> * ControllerPostsController class
<del> *
<del> * @package Cake.Test.Case.Controller
<del> */
<del>class ControllerCommentsController extends ControllerTestAppController {
<del>
<del>/**
<del> * name property
<del> *
<del> * @var string 'ControllerPost'
<del> */
<del> public $name = 'ControllerComments';
<del>
<del> protected $_mergeParent = 'ControllerTestAppController';
<del>}
<del>
<del>/**
<del> * ControllerComment class
<del> *
<del> * @package Cake.Test.Case.Controller
<del> */
<del>class ControllerComment extends TestModel {
<del>
<del>/**
<del> * name property
<del> *
<del> * @var string 'ControllerComment'
<del> */
<del> public $name = 'Comment';
<del>
<del>/**
<del> * useTable property
<del> *
<del> * @var string 'comments'
<del> */
<del> public $useTable = 'comments';
<del>
<del>/**
<del> * data property
<del> *
<del> * @var array
<del> */
<del> public $data = array('name' => 'Some Name');
<del>
<del>/**
<del> * alias property
<del> *
<del> * @var string 'ControllerComment'
<del> */
<del> public $alias = 'ControllerComment';
<del>}
<del>
<del>/**
<del> * ControllerAlias class
<del> *
<del> * @package Cake.Test.Case.Controller
<del> */
<del>class ControllerAlias extends TestModel {
<del>
<del>/**
<del> * name property
<del> *
<del> * @var string 'ControllerAlias'
<del> */
<del> public $name = 'ControllerAlias';
<del>
<del>/**
<del> * alias property
<del> *
<del> * @var string 'ControllerSomeAlias'
<del> */
<del> public $alias = 'ControllerSomeAlias';
<del>
<del>/**
<del> * useTable property
<del> *
<del> * @var string 'posts'
<del> */
<del> public $useTable = 'posts';
<del>}
<del>
<del>/**
<del> * NameTest class
<del> *
<del> * @package Cake.Test.Case.Controller
<del> */
<del>class NameTest extends TestModel {
<del>
<del>/**
<del> * name property
<del> * @var string 'Name'
<del> */
<del> public $name = 'Name';
<del>
<del>/**
<del> * useTable property
<del> * @var string 'names'
<del> */
<del> public $useTable = 'comments';
<del>
<del>/**
<del> * alias property
<del> *
<del> * @var string 'ControllerComment'
<del> */
<del> public $alias = 'Name';
<del>}
<del>
<ide> /**
<ide> * TestController class
<ide> *
<ide> class TestController extends ControllerTestAppController {
<ide> *
<ide> * @var array
<ide> */
<del> public $uses = array('ControllerComment', 'ControllerAlias');
<add> public $uses = array('Comment');
<ide>
<ide> protected $_mergeParent = 'ControllerTestAppController';
<ide>
<ide> class TestController extends ControllerTestAppController {
<ide> * @return void
<ide> */
<ide> public function index($testId, $testTwoId) {
<del> $this->data = array(
<add> $this->request->data = array(
<ide> 'testId' => $testId,
<ide> 'test2Id' => $testTwoId
<ide> );
<ide> public function index($testId, $testTwoId) {
<ide> * @return void
<ide> */
<ide> public function view($testId, $testTwoId) {
<del> $this->data = array(
<add> $this->request->data = array(
<ide> 'testId' => $testId,
<ide> 'test2Id' => $testTwoId
<ide> );
<ide> public function admin_add() {
<ide>
<ide> }
<ide>
<del>/**
<del> * TestComponent class
<del> *
<del> * @package Cake.Test.Case.Controller
<del> */
<del>class TestComponent extends Object {
<del>
<del>/**
<del> * beforeRedirect method
<del> *
<del> * @return void
<del> */
<del> public function beforeRedirect() {
<del> }
<del>
<del>/**
<del> * initialize method
<del> *
<del> * @return void
<del> */
<del> public function initialize(Controller $controller) {
<del> }
<del>
<del>/**
<del> * startup method
<del> *
<del> * @return void
<del> */
<del> public function startup(Controller $controller) {
<del> }
<del>
<del>/**
<del> * shutdown method
<del> *
<del> * @return void
<del> */
<del> public function shutdown(Controller $controller) {
<del> }
<del>
<del>/**
<del> * beforeRender callback
<del> *
<del> * @return void
<del> */
<del> public function beforeRender(Controller $controller) {
<del> if ($this->viewclass) {
<del> $controller->viewClass = $this->viewclass;
<del> }
<del> }
<del>
<del>}
<del>
<del>class Test2Component extends TestComponent {
<del>
<del> public function beforeRender(Controller $controller) {
<del> return false;
<del> }
<del>
<del>}
<del>
<ide> /**
<ide> * AnotherTestController class
<ide> *
<ide> public function tearDown() {
<ide> * @return void
<ide> */
<ide> public function testLoadModel() {
<add> Configure::write('App.namespace', 'TestApp');
<ide> $request = new Request('controller_posts/index');
<ide> $response = $this->getMock('Cake\Network\Response');
<ide> $Controller = new Controller($request, $response);
<ide>
<del> $this->assertFalse(isset($Controller->ControllerPost));
<add> $this->assertFalse(isset($Controller->Post));
<ide>
<del> $result = $Controller->loadModel('ControllerPost');
<add> $result = $Controller->loadModel('Post');
<ide> $this->assertTrue($result);
<del> $this->assertTrue(is_a($Controller->ControllerPost, 'ControllerPost'));
<del> $this->assertTrue(in_array('ControllerPost', $Controller->uses));
<add> $this->assertInstanceOf('TestApp\Model\Post', $Controller->Post);
<add> $this->assertTrue(in_array('Post', $Controller->uses));
<ide>
<ide> ClassRegistry::flush();
<ide> unset($Controller);
<ide> public function testLoadModel() {
<ide> * @return void
<ide> */
<ide> public function testLoadModelInPlugins() {
<del> App::build(array(
<del> 'Plugin' => array(CAKE . 'Test/TestApp/Plugin/'),
<del> 'Controller' => array(CAKE . 'Test/TestApp/Controller/'),
<del> 'Model' => array(CAKE . 'Test/TestApp/Model/')
<del> ));
<add> Configure::write('App.namespace', 'TestApp');
<add> App::build([
<add> 'Plugin' => [CAKE . 'Test/TestApp/Plugin/'],
<add> 'Controller' => [CAKE . 'Test/TestApp/Controller/'],
<add> 'Model' => [CAKE . 'Test/TestApp/Model/']
<add> ]);
<ide> Plugin::load('TestPlugin');
<ide>
<ide> $Controller = new TestPluginController();
<ide> public function testLoadModelInPlugins() {
<ide> * @return void
<ide> */
<ide> public function testConstructClasses() {
<add> Configure::write('App.namespace', 'TestApp');
<ide> $request = new Request('controller_posts/index');
<ide>
<ide> $Controller = new Controller($request);
<del> $Controller->uses = array('ControllerPost', 'ControllerComment');
<add> $Controller->uses = ['Post', 'Comment'];
<ide> $Controller->constructClasses();
<del> $this->assertTrue(is_a($Controller->ControllerPost, 'ControllerPost'));
<del> $this->assertTrue(is_a($Controller->ControllerComment, 'ControllerComment'));
<add> $this->assertInstanceOf('TestApp\Model\Post', $Controller->Post);
<add> $this->assertInstanceOf('TestApp\Model\Comment', $Controller->Comment);
<ide>
<del> $this->assertEquals('Comment', $Controller->ControllerComment->name);
<add> $this->assertEquals('Comment', $Controller->Comment->name);
<ide>
<ide> unset($Controller);
<ide>
<del> App::build(array('Plugin' => array(CAKE . 'Test/TestApp/Plugin/')));
<add> App::build(['Plugin' => [CAKE . 'Test/TestApp/Plugin/']]);
<ide> Plugin::load('TestPlugin');
<ide>
<ide> $Controller = new Controller($request);
<ide> $Controller->uses = array('TestPlugin.TestPluginPost');
<ide> $Controller->constructClasses();
<ide>
<ide> $this->assertTrue(isset($Controller->TestPluginPost));
<del> $this->assertTrue(is_a($Controller->TestPluginPost, 'TestPluginPost'));
<del> }
<del>
<del>/**
<del> * testAliasName method
<del> *
<del> * @return void
<del> */
<del> public function testAliasName() {
<del> $request = new Request('controller_posts/index');
<del> $Controller = new Controller($request);
<del> $Controller->uses = array('NameTest');
<del> $Controller->constructClasses();
<del>
<del> $this->assertEquals('Name', $Controller->NameTest->name);
<del> $this->assertEquals('Name', $Controller->NameTest->alias);
<del>
<del> unset($Controller);
<add> $this->assertInstanceOf('TestPlugin\Model\TestPluginPost', $Controller->TestPluginPost);
<ide> }
<ide>
<ide> /**
<ide> public function testControllerSet() {
<ide> * @return void
<ide> */
<ide> public function testRender() {
<del> App::build(array(
<del> 'View' => array(CAKE . 'Test/TestApp/View/')
<del> ), App::RESET);
<add> Configure::write('App.namespace', 'TestApp');
<add> App::build([
<add> 'Plugin' => [CAKE . 'Test/TestApp/Plugin/'],
<add> 'View' => [CAKE . 'Test/TestApp/View/']
<add> ], App::RESET);
<ide> ClassRegistry::flush();
<add> Plugin::load('TestPlugin');
<add>
<ide> $request = new Request('controller_posts/index');
<ide> $request->params['action'] = 'index';
<ide>
<ide> public function testRender() {
<ide> $Controller->view = null;
<ide>
<ide> $Controller = new TestController($request, new Response());
<del> $Controller->uses = array('ControllerAlias', 'TestPlugin.ControllerComment', 'ControllerPost');
<add> $Controller->uses = ['TestPlugin.TestPluginComment'];
<ide> $Controller->helpers = array('Html');
<ide> $Controller->constructClasses();
<del> $Controller->ControllerComment->validationErrors = array('title' => 'tooShort');
<del> $expected = $Controller->ControllerComment->validationErrors;
<add> $expected = ['title' => 'tooShort'];
<add> $Controller->TestPluginComment->validationErrors = $expected;
<ide>
<ide> $Controller->viewPath = 'Posts';
<ide> $result = $Controller->render('index');
<ide> $View = $Controller->View;
<del> $this->assertTrue(isset($View->validationErrors['ControllerComment']));
<del> $this->assertEquals($expected, $View->validationErrors['ControllerComment']);
<del>
<del> $expectedModels = array(
<del> 'ControllerAlias' => array('plugin' => null, 'className' => 'ControllerAlias'),
<del> 'ControllerComment' => array('plugin' => 'TestPlugin', 'className' => 'ControllerComment'),
<del> 'ControllerPost' => array('plugin' => null, 'className' => 'ControllerPost')
<del> );
<add> $this->assertTrue(isset($View->validationErrors['TestPluginComment']));
<add> $this->assertEquals($expected, $View->validationErrors['TestPluginComment']);
<add>
<add> $expectedModels = [
<add> 'TestPluginComment' => [
<add> 'className' => 'TestPlugin\Model\TestPluginComment'
<add> ],
<add> ];
<ide> $this->assertEquals($expectedModels, $Controller->request->params['models']);
<del>
<del> ClassRegistry::flush();
<del> App::build();
<ide> }
<ide>
<ide> /**
<ide> public function testRender() {
<ide> * @return void
<ide> */
<ide> public function testComponentBeforeRenderChangingViewClass() {
<del> App::build(array(
<del> 'View' => array(
<add> Configure::write('App.namespace', 'TestApp');
<add> App::build([
<add> 'View' => [
<ide> CAKE . 'Test/TestApp/View/'
<del> )
<del> ), true);
<add> ]
<add> ], true);
<ide> $Controller = new Controller($this->getMock('Cake\Network\Request'), new Response());
<del> $Controller->uses = array();
<del> $Controller->components = array('Test');
<ide> $Controller->constructClasses();
<del> $Controller->Test->viewclass = 'Theme';
<del> $Controller->viewPath = 'Posts';
<del> $Controller->theme = 'TestTheme';
<add> $Controller->uses = $Controller->components = [];
<add>
<add> $mock = $this->getMock('Cake\Controller\Component', ['beforeRender'], [$Controller->Components]);
<add> $mock->expects($this->once())
<add> ->method('beforeRender')
<add> ->will($this->returnCallback(function ($controller) {
<add> $controller->viewClass = 'Json';
<add> }));
<add> $Controller->Components->set('Test', $mock);
<add> $Controller->Components->enable('Test');
<add>
<add> $Controller->set([
<add> 'test' => 'value',
<add> '_serialize' => ['test']
<add> ]);
<ide> $result = $Controller->render('index');
<del> $this->assertRegExp('/default test_theme layout/', (string)$result);
<del> App::build();
<add> $this->assertEquals('{"test":"value"}', $result);
<ide> }
<ide>
<ide> /**
<ide> public function testComponentBeforeRenderChangingViewClass() {
<ide> */
<ide> public function testComponentCancelRender() {
<ide> $Controller = new Controller($this->getMock('Cake\Network\Request'), new Response());
<del> $Controller->uses = array();
<del> $Controller->components = array('Test2');
<ide> $Controller->constructClasses();
<add> $mock = $this->getMock('Cake\Controller\Component', ['beforeRender'], [$Controller->Components]);
<add> $mock->expects($this->once())
<add> ->method('beforeRender')
<add> ->will($this->returnValue(false));
<add> $Controller->Components->set('Test', $mock);
<add> $Controller->Components->enable('Test');
<add>
<ide> $result = $Controller->render('index');
<ide> $this->assertInstanceOf('Cake\Network\Response', $result);
<ide> }
<ide> public function testMergeVars() {
<ide> $this->assertEquals(0, count(array_diff($TestController->uses, $uses)));
<ide> $this->assertEquals(count(array_diff_assoc(Hash::normalize($TestController->components), Hash::normalize($components))), 0);
<ide>
<del> $expected = array('ControllerComment', 'ControllerAlias', 'ControllerPost');
<add> $expected = array('Comment', 'ControllerPost');
<ide> $this->assertEquals($expected, $TestController->uses, '$uses was merged incorrectly, ControllerTestAppController models should be last.');
<ide>
<ide> $TestController = new AnotherTestController($request);
<ide> public function testValidateErrors() {
<ide> $this->assertFalse($TestController->validateErrors());
<ide> $this->assertEquals(0, $TestController->validate());
<ide>
<del> $TestController->ControllerComment->invalidate('some_field', 'error_message');
<del> $TestController->ControllerComment->invalidate('some_field2', 'error_message2');
<add> $TestController->Comment->invalidate('some_field', 'error_message');
<add> $TestController->Comment->invalidate('some_field2', 'error_message2');
<ide>
<del> $comment = new ControllerComment($request);
<add> $comment = new \TestApp\Model\Comment($request);
<ide> $comment->set('someVar', 'data');
<ide> $result = $TestController->validateErrors($comment);
<ide> $expected = array('some_field' => array('error_message'), 'some_field2' => array('error_message2'));
<ide> public function testValidateErrorsOnArbitraryModels() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<del>/**
<del> * testPostConditions method
<del> *
<del> * @return void
<del> */
<del> public function testPostConditions() {
<del> $request = new Request('controller_posts/index');
<del>
<del> $Controller = new Controller($request);
<del>
<del> $data = array(
<del> 'Model1' => array('field1' => '23'),
<del> 'Model2' => array('field2' => 'string'),
<del> 'Model3' => array('field3' => '23'),
<del> );
<del> $expected = array(
<del> 'Model1.field1' => '23',
<del> 'Model2.field2' => 'string',
<del> 'Model3.field3' => '23',
<del> );
<del> $result = $Controller->postConditions($data);
<del> $this->assertSame($expected, $result);
<del>
<del> $data = array();
<del> $Controller->data = array(
<del> 'Model1' => array('field1' => '23'),
<del> 'Model2' => array('field2' => 'string'),
<del> 'Model3' => array('field3' => '23'),
<del> );
<del> $expected = array(
<del> 'Model1.field1' => '23',
<del> 'Model2.field2' => 'string',
<del> 'Model3.field3' => '23',
<del> );
<del> $result = $Controller->postConditions($data);
<del> $this->assertSame($expected, $result);
<del>
<del> $data = array();
<del> $Controller->data = array();
<del> $result = $Controller->postConditions($data);
<del> $this->assertNull($result);
<del>
<del> $data = array();
<del> $Controller->data = array(
<del> 'Model1' => array('field1' => '23'),
<del> 'Model2' => array('field2' => 'string'),
<del> 'Model3' => array('field3' => '23'),
<del> );
<del> $ops = array(
<del> 'Model1.field1' => '>',
<del> 'Model2.field2' => 'LIKE',
<del> 'Model3.field3' => '<=',
<del> );
<del> $expected = array(
<del> 'Model1.field1 >' => '23',
<del> 'Model2.field2 LIKE' => "%string%",
<del> 'Model3.field3 <=' => '23',
<del> );
<del> $result = $Controller->postConditions($data, $ops);
<del> $this->assertSame($expected, $result);
<del> }
<del>
<ide> /**
<ide> * testControllerHttpCodes method
<ide> *
<ide> public function testShutdownProcessIndirect() {
<ide> $Controller->shutdownProcess();
<ide> }
<ide>
<del>/**
<del> * test that BC works for attributes on the request object.
<del> *
<del> * @return void
<del> */
<del> public function testPropertyBackwardsCompatibility() {
<del> $request = new Request('posts/index');
<del> $request->addParams(array('controller' => 'posts', 'action' => 'index'));
<del> $request->data = array('Post' => array('id' => 1));
<del> $request->here = '/posts/index';
<del> $request->webroot = '/';
<del>
<del> $Controller = new TestController($request);
<del> $this->assertEquals($request->data, $Controller->data);
<del> $this->assertEquals($request->webroot, $Controller->webroot);
<del> $this->assertEquals($request->here, $Controller->here);
<del> $this->assertEquals($request->action, $Controller->action);
<del>
<del> $this->assertFalse(empty($Controller->data));
<del> $this->assertTrue(isset($Controller->data));
<del> $this->assertTrue(empty($Controller->something));
<del> $this->assertFalse(isset($Controller->something));
<del>
<del> $this->assertEquals($request, $Controller->params);
<del> $this->assertEquals($request->params['controller'], $Controller->params['controller']);
<del> }
<del>
<del>/**
<del> * test that the BC wrapper doesn't interfere with models and components.
<del> *
<del> * @return void
<del> */
<del> public function testPropertyCompatibilityAndModelsComponents() {
<del> $request = new Request('controller_posts/index');
<del>
<del> $Controller = new TestController($request);
<del> $Controller->constructClasses();
<del> $this->assertInstanceOf('Cake\Controller\Component\SecurityComponent', $Controller->Security);
<del> $this->assertInstanceOf('ControllerComment', $Controller->ControllerComment);
<del> }
<del>
<ide> /**
<ide> * test that using Controller::paginate() falls back to PaginatorComponent
<ide> *
<ide> public function testPropertyCompatibilityAndModelsComponents() {
<ide> public function testPaginateBackwardsCompatibility() {
<ide> $request = new Request('controller_posts/index');
<ide> $request->params['pass'] = array();
<del> $response = $this->getMock('Cake\Network\Response', array('httpCodes'));
<add> $response = $this->getMock('Cake\Network\Response', ['httpCodes']);
<ide>
<ide> $Controller = new Controller($request, $response);
<del> $Controller->uses = array('ControllerPost', 'ControllerComment');
<add> $Controller->uses = ['Post', 'Comment'];
<ide> $Controller->passedArgs[] = '1';
<del> $Controller->params['url'] = array();
<add> $Controller->request->query['url'] = [];
<ide> $Controller->constructClasses();
<del> $expected = array('page' => 1, 'limit' => 20, 'maxLimit' => 100);
<add> $expected = ['page' => 1, 'limit' => 20, 'maxLimit' => 100];
<ide> $this->assertEquals($expected, $Controller->paginate);
<ide>
<del> $results = Hash::extract($Controller->paginate('ControllerPost'), '{n}.ControllerPost.id');
<del> $this->assertEquals(array(1, 2, 3), $results);
<add> $results = Hash::extract($Controller->paginate('Post'), '{n}.Post.id');
<add> $this->assertEquals([1, 2, 3], $results);
<ide>
<ide> $Controller->passedArgs = array();
<ide> $Controller->paginate = array('limit' => '-1');
<ide> $this->assertEquals(array('limit' => '-1'), $Controller->paginate);
<del> $Controller->paginate('ControllerPost');
<del> $this->assertSame($Controller->params['paging']['ControllerPost']['page'], 1);
<del> $this->assertSame($Controller->params['paging']['ControllerPost']['pageCount'], 3);
<del> $this->assertSame($Controller->params['paging']['ControllerPost']['prevPage'], false);
<del> $this->assertSame($Controller->params['paging']['ControllerPost']['nextPage'], true);
<add> $Controller->paginate('Post');
<add> $this->assertSame($Controller->request->params['paging']['Post']['page'], 1);
<add> $this->assertSame($Controller->request->params['paging']['Post']['pageCount'], 3);
<add> $this->assertSame($Controller->request->params['paging']['Post']['prevPage'], false);
<add> $this->assertSame($Controller->request->params['paging']['Post']['nextPage'], true);
<ide> }
<ide>
<ide> /** | 5 |
PHP | PHP | use interfaces instead of classes for typehinting | ca1db1dce91dd6e11b749d7393b20cafb6423b66 | <ide><path>src/ORM/Behavior/Translate/EavStrategy.php
<ide> use Cake\Core\InstanceConfigTrait;
<ide> use Cake\Datasource\EntityInterface;
<ide> use Cake\Datasource\QueryInterface;
<del>use Cake\Event\Event;
<add>use Cake\Event\EventInterface;
<ide> use Cake\ORM\Behavior\Translate\TranslateStrategyInterface;
<ide> use Cake\ORM\Entity;
<ide> use Cake\ORM\Locator\LocatorAwareTrait;
<del>use Cake\ORM\Query;
<ide> use Cake\ORM\Table;
<ide>
<ide> /**
<ide> protected function setupAssociations()
<ide> * table. It modifies the passed query by eager loading the translated fields
<ide> * and adding a formatter to copy the values into the main table records.
<ide> *
<del> * @param \Cake\Event\Event $event The beforeFind event that was fired.
<del> * @param \Cake\ORM\Query $query Query
<add> * @param \Cake\Event\EventInterface $event The beforeFind event that was fired.
<add> * @param \Cake\Datasource\QueryInterface $query Query
<ide> * @param \ArrayObject $options The options for the query
<ide> * @return void
<ide> */
<del> public function beforeFind(Event $event, Query $query, ArrayObject $options): void
<add> public function beforeFind(EventInterface $event, QueryInterface $query, ArrayObject $options): void
<ide> {
<ide> $locale = $this->getLocale();
<ide>
<ide> public function beforeFind(Event $event, Query $query, ArrayObject $options): vo
<ide> * Modifies the entity before it is saved so that translated fields are persisted
<ide> * in the database too.
<ide> *
<del> * @param \Cake\Event\Event $event The beforeSave event that was fired
<add> * @param \Cake\Event\EventInterface $event The beforeSave event that was fired
<ide> * @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
<ide> * @param \ArrayObject $options the options passed to the save method
<ide> * @return void
<ide> */
<del> public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options): void
<add> public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): void
<ide> {
<ide> $locale = $entity->get('_locale') ?: $this->getLocale();
<ide> $newOptions = [$this->translationTable->getAlias() => ['validate' => false]];
<ide><path>src/ORM/Behavior/Translate/ShadowTableStrategy.php
<ide> use Cake\Core\InstanceConfigTrait;
<ide> use Cake\Database\Expression\FieldInterface;
<ide> use Cake\Datasource\EntityInterface;
<del>use Cake\Event\Event;
<add>use Cake\Datasource\QueryInterface;
<add>use Cake\Event\EventInterface;
<ide> use Cake\ORM\Behavior\Translate\TranslateStrategyInterface;
<ide> use Cake\ORM\Locator\LocatorAwareTrait;
<del>use Cake\ORM\Query;
<ide> use Cake\ORM\Table;
<ide>
<ide> /**
<ide> protected function setupAssociations()
<ide> * table. It modifies the passed query by eager loading the translated fields
<ide> * and adding a formatter to copy the values into the main table records.
<ide> *
<del> * @param \Cake\Event\Event $event The beforeFind event that was fired.
<del> * @param \Cake\ORM\Query $query Query.
<add> * @param \Cake\Event\EventInterface $event The beforeFind event that was fired.
<add> * @param \Cake\Datasource\QueryInterface $query Query.
<ide> * @param \ArrayObject $options The options for the query.
<ide> * @return void
<ide> */
<del> public function beforeFind(Event $event, Query $query, ArrayObject $options): void
<add> public function beforeFind(EventInterface $event, QueryInterface $query, ArrayObject $options): void
<ide> {
<ide> $locale = $this->getLocale();
<ide>
<ide> public function beforeFind(Event $event, Query $query, ArrayObject $options): vo
<ide> * Only add translations for fields that are in the main table, always
<ide> * add the locale field though.
<ide> *
<del> * @param \Cake\ORM\Query $query The query to check.
<add> * @param \Cake\Datasource\QueryInterface $query The query to check.
<ide> * @param array $config The config to use for adding fields.
<ide> * @return bool Whether a join to the translation table is required.
<ide> */
<del> protected function addFieldsToQuery(Query $query, array $config)
<add> protected function addFieldsToQuery(QueryInterface $query, array $config)
<ide> {
<ide> if ($query->isAutoFieldsEnabled()) {
<ide> return true;
<ide> protected function addFieldsToQuery(Query $query, array $config)
<ide> * prefixing fields with the appropriate table alias. This method currently
<ide> * expects to receive an order clause only.
<ide> *
<del> * @param \Cake\ORM\Query $query the query to check.
<add> * @param \Cake\Datasource\QueryInterface $query the query to check.
<ide> * @param string $name The clause name.
<ide> * @param array $config The config to use for adding fields.
<ide> * @return bool Whether a join to the translation table is required.
<ide> */
<del> protected function iterateClause(Query $query, $name = '', $config = [])
<add> protected function iterateClause(QueryInterface $query, $name = '', $config = [])
<ide> {
<ide> $clause = $query->clause($name);
<ide> if (!$clause || !$clause->count()) {
<ide> protected function iterateClause(Query $query, $name = '', $config = [])
<ide> * prefixing fields with the appropriate table alias. This method currently
<ide> * expects to receive a where clause only.
<ide> *
<del> * @param \Cake\ORM\Query $query the query to check.
<add> * @param \Cake\Datasource\QueryInterface $query the query to check.
<ide> * @param string $name The clause name.
<ide> * @param array $config The config to use for adding fields.
<ide> * @return bool Whether a join to the translation table is required.
<ide> */
<del> protected function traverseClause(Query $query, $name = '', $config = [])
<add> protected function traverseClause(QueryInterface $query, $name = '', $config = [])
<ide> {
<ide> $clause = $query->clause($name);
<ide> if (!$clause || !$clause->count()) {
<ide> protected function traverseClause(Query $query, $name = '', $config = [])
<ide> * Modifies the entity before it is saved so that translated fields are persisted
<ide> * in the database too.
<ide> *
<del> * @param \Cake\Event\Event $event The beforeSave event that was fired.
<add> * @param \Cake\Event\EventInterface $event The beforeSave event that was fired.
<ide> * @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved.
<ide> * @param \ArrayObject $options the options passed to the save method.
<ide> * @return void
<ide> */
<del> public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options): void
<add> public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): void
<ide> {
<ide> $locale = $entity->get('_locale') ?: $this->getLocale();
<ide> $newOptions = [$this->translationTable->getAlias() => ['validate' => false]];
<ide><path>src/ORM/Behavior/Translate/TranslateStrategyInterface.php
<ide> use ArrayObject;
<ide> use Cake\Collection\CollectionInterface;
<ide> use Cake\Datasource\EntityInterface;
<del>use Cake\Event\Event;
<add>use Cake\Datasource\QueryInterface;
<add>use Cake\Event\EventInterface;
<ide> use Cake\ORM\PropertyMarshalInterface;
<del>use Cake\ORM\Query;
<ide> use Cake\ORM\Table;
<ide>
<ide> /**
<ide> public function groupTranslations($results): CollectionInterface;
<ide> * table. It modifies the passed query by eager loading the translated fields
<ide> * and adding a formatter to copy the values into the main table records.
<ide> *
<del> * @param \Cake\Event\Event $event The beforeFind event that was fired.
<add> * @param \Cake\Event\EventInterface $event The beforeFind event that was fired.
<ide> * @param \Cake\ORM\Query $query Query
<ide> * @param \ArrayObject $options The options for the query
<ide> * @return void
<ide> */
<del> public function beforeFind(Event $event, Query $query, ArrayObject $options): void;
<add> public function beforeFind(EventInterface $event, QueryInterface $query, ArrayObject $options): void;
<ide>
<ide> /**
<ide> * Modifies the entity before it is saved so that translated fields are persisted
<ide> * in the database too.
<ide> *
<del> * @param \Cake\Event\Event $event The beforeSave event that was fired
<add> * @param \Cake\Event\EntityInterface $event The beforeSave event that was fired
<ide> * @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
<ide> * @param \ArrayObject $options the options passed to the save method
<ide> * @return void
<ide> */
<del> public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options): void;
<add> public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): void;
<ide>
<ide> /**
<ide> * Unsets the temporary `_i18n` property after the entity has been saved
<ide> *
<del> * @param \Cake\Event\Event $event The beforeSave event that was fired
<add> * @param \Cake\Event\EventInterface $event The beforeSave event that was fired
<ide> * @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
<ide> * @return void
<ide> */
<del> public function afterSave(Event $event, EntityInterface $entity): void;
<add> public function afterSave(EventInterface $event, EntityInterface $entity): void;
<ide> }
<ide><path>src/ORM/Behavior/Translate/TranslateStrategyTrait.php
<ide> namespace Cake\ORM\Behavior\Translate;
<ide>
<ide> use Cake\Datasource\EntityInterface;
<del>use Cake\Event\Event;
<add>use Cake\Event\EventInterface;
<ide> use Cake\I18n\I18n;
<ide> use Cake\ORM\Table;
<ide>
<ide> public function buildMarshalMap($marshaller, $map, $options)
<ide> /**
<ide> * Unsets the temporary `_i18n` property after the entity has been saved
<ide> *
<del> * @param \Cake\Event\Event $event The beforeSave event that was fired
<add> * @param \Cake\Event\EventInterface $event The beforeSave event that was fired
<ide> * @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
<ide> * @return void
<ide> */
<del> public function afterSave(Event $event, EntityInterface $entity): void
<add> public function afterSave(EventInterface $event, EntityInterface $entity): void
<ide> {
<ide> $entity->unsetProperty('_i18n');
<ide> } | 4 |
Javascript | Javascript | simplify tracking of edgesgeometry coordinates | 669eb6dd6191978e2f6b280bc50f976453f3d654 | <ide><path>src/extras/geometries/EdgesGeometry.js
<ide> THREE.EdgesGeometry = function ( geometry, thresholdAngle ) {
<ide>
<ide> var vertices = geometry2.vertices;
<ide> var faces = geometry2.faces;
<del> var numEdges = 0;
<ide>
<ide> for ( var i = 0, l = faces.length; i < l; i ++ ) {
<ide>
<ide> THREE.EdgesGeometry = function ( geometry, thresholdAngle ) {
<ide> if ( hash[ key ] === undefined ) {
<ide>
<ide> hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
<del> numEdges ++;
<ide>
<ide> } else {
<ide>
<ide> THREE.EdgesGeometry = function ( geometry, thresholdAngle ) {
<ide>
<ide> }
<ide>
<del> var coords = new Float32Array( numEdges * 2 * 3 );
<del>
<del> var index = 0;
<add> var coords = [];
<ide>
<ide> for ( var key in hash ) {
<ide>
<ide> THREE.EdgesGeometry = function ( geometry, thresholdAngle ) {
<ide> if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
<ide>
<ide> var vertex = vertices[ h.vert1 ];
<del> coords[ index ++ ] = vertex.x;
<del> coords[ index ++ ] = vertex.y;
<del> coords[ index ++ ] = vertex.z;
<add> coords.push( vertex.x );
<add> coords.push( vertex.y );
<add> coords.push( vertex.z );
<ide>
<ide> vertex = vertices[ h.vert2 ];
<del> coords[ index ++ ] = vertex.x;
<del> coords[ index ++ ] = vertex.y;
<del> coords[ index ++ ] = vertex.z;
<add> coords.push( vertex.x );
<add> coords.push( vertex.y );
<add> coords.push( vertex.z );
<ide>
<ide> }
<ide>
<ide> }
<ide>
<del> coords = coords.subarray( 0, index );
<del>
<del> this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
<add> this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( coords ), 3 ) );
<ide>
<ide> };
<ide> | 1 |
Javascript | Javascript | check thenable instead of thenablestate | 6b4c0314e82e3e56a8af84f3af3c0822a950ad1f | <ide><path>packages/react-reconciler/src/ReactFiberThenable.new.js
<ide> export function getThenableStateAfterSuspending(): ThenableState | null {
<ide> return state;
<ide> }
<ide>
<del>export function isThenableStateResolved(thenables: ThenableState): boolean {
<del> const lastThenable = thenables[thenables.length - 1];
<del> if (lastThenable !== undefined) {
<del> const status = lastThenable.status;
<del> return status === 'fulfilled' || status === 'rejected';
<del> }
<del> return true;
<add>export function isThenableResolved(thenable: Thenable<mixed>): boolean {
<add> const status = thenable.status;
<add> return status === 'fulfilled' || status === 'rejected';
<ide> }
<ide>
<ide> function noop(): void {}
<ide><path>packages/react-reconciler/src/ReactFiberThenable.old.js
<ide> export function getThenableStateAfterSuspending(): ThenableState | null {
<ide> return state;
<ide> }
<ide>
<del>export function isThenableStateResolved(thenables: ThenableState): boolean {
<del> const lastThenable = thenables[thenables.length - 1];
<del> if (lastThenable !== undefined) {
<del> const status = lastThenable.status;
<del> return status === 'fulfilled' || status === 'rejected';
<del> }
<del> return true;
<add>export function isThenableResolved(thenable: Thenable<mixed>): boolean {
<add> const status = thenable.status;
<add> return status === 'fulfilled' || status === 'rejected';
<ide> }
<ide>
<ide> function noop(): void {}
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> import {
<ide> SuspenseException,
<ide> getSuspendedThenable,
<ide> getThenableStateAfterSuspending,
<del> isThenableStateResolved,
<add> isThenableResolved,
<ide> } from './ReactFiberThenable.new';
<ide> import {schedulePostPaintCallback} from './ReactPostPaintCallback';
<ide> import {
<ide> function renderRootConcurrent(root: FiberRoot, lanes: Lanes) {
<ide> break;
<ide> }
<ide> case SuspendedOnData: {
<add> const thenable: Thenable<mixed> = (thrownValue: any);
<ide> if (workInProgressSuspendedThenableState !== null) {
<ide> const thenableState = workInProgressSuspendedThenableState;
<del> if (isThenableStateResolved(thenableState)) {
<add> if (isThenableResolved(thenable)) {
<ide> // The data resolved. Try rendering the component again.
<ide> workInProgressSuspendedReason = NotSuspended;
<ide> workInProgressThrownValue = null;
<del> replaySuspendedUnitOfWork(
<del> unitOfWork,
<del> thrownValue,
<del> thenableState,
<del> );
<add> replaySuspendedUnitOfWork(unitOfWork, thenable, thenableState);
<ide> break;
<ide> }
<ide> }
<ide>
<ide> // The work loop is suspended on data. We should wait for it to
<ide> // resolve before continuing to render.
<del> const thenable: Thenable<mixed> = (workInProgressThrownValue: any);
<ide> const onResolution = () => {
<ide> ensureRootIsScheduled(root, now());
<ide> };
<ide> function renderRootConcurrent(root: FiberRoot, lanes: Lanes) {
<ide> default: {
<ide> if (workInProgressSuspendedThenableState !== null) {
<ide> const thenableState = workInProgressSuspendedThenableState;
<del> if (isThenableStateResolved(thenableState)) {
<add> const thenable: Thenable<mixed> = (thrownValue: any);
<add> if (isThenableResolved(thenable)) {
<ide> // The data resolved. Try rendering the component again.
<ide> workInProgressSuspendedReason = NotSuspended;
<ide> workInProgressThrownValue = null;
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> import {
<ide> SuspenseException,
<ide> getSuspendedThenable,
<ide> getThenableStateAfterSuspending,
<del> isThenableStateResolved,
<add> isThenableResolved,
<ide> } from './ReactFiberThenable.old';
<ide> import {schedulePostPaintCallback} from './ReactPostPaintCallback';
<ide> import {
<ide> function renderRootConcurrent(root: FiberRoot, lanes: Lanes) {
<ide> break;
<ide> }
<ide> case SuspendedOnData: {
<add> const thenable: Thenable<mixed> = (thrownValue: any);
<ide> if (workInProgressSuspendedThenableState !== null) {
<ide> const thenableState = workInProgressSuspendedThenableState;
<del> if (isThenableStateResolved(thenableState)) {
<add> if (isThenableResolved(thenable)) {
<ide> // The data resolved. Try rendering the component again.
<ide> workInProgressSuspendedReason = NotSuspended;
<ide> workInProgressThrownValue = null;
<del> replaySuspendedUnitOfWork(
<del> unitOfWork,
<del> thrownValue,
<del> thenableState,
<del> );
<add> replaySuspendedUnitOfWork(unitOfWork, thenable, thenableState);
<ide> break;
<ide> }
<ide> }
<ide>
<ide> // The work loop is suspended on data. We should wait for it to
<ide> // resolve before continuing to render.
<del> const thenable: Thenable<mixed> = (workInProgressThrownValue: any);
<ide> const onResolution = () => {
<ide> ensureRootIsScheduled(root, now());
<ide> };
<ide> function renderRootConcurrent(root: FiberRoot, lanes: Lanes) {
<ide> default: {
<ide> if (workInProgressSuspendedThenableState !== null) {
<ide> const thenableState = workInProgressSuspendedThenableState;
<del> if (isThenableStateResolved(thenableState)) {
<add> const thenable: Thenable<mixed> = (thrownValue: any);
<add> if (isThenableResolved(thenable)) {
<ide> // The data resolved. Try rendering the component again.
<ide> workInProgressSuspendedReason = NotSuspended;
<ide> workInProgressThrownValue = null; | 4 |
Javascript | Javascript | replace object.assign with object spread | 35ec01097b2a397ad0a22aac536fe07514876e21 | <ide><path>test/parallel/test-trace-events-async-hooks-dynamic.js
<ide> const proc = cp.spawnSync(
<ide> ['-e', enable + code ],
<ide> {
<ide> cwd: tmpdir.path,
<del> env: Object.assign({}, process.env, {
<del> 'NODE_DEBUG_NATIVE': 'tracing',
<del> 'NODE_DEBUG': 'tracing'
<del> })
<add> env: { ...process.env,
<add> 'NODE_DEBUG_NATIVE': 'tracing',
<add> 'NODE_DEBUG': 'tracing'
<add> }
<ide> });
<ide>
<ide> console.log('process exit with signal:', proc.signal);
<ide><path>test/parallel/test-trace-events-async-hooks-worker.js
<ide> const proc = cp.spawnSync(
<ide> [ '--trace-event-categories', 'node.async_hooks', '-e', worker ],
<ide> {
<ide> cwd: tmpdir.path,
<del> env: Object.assign({}, process.env, {
<del> 'NODE_DEBUG_NATIVE': 'tracing',
<del> 'NODE_DEBUG': 'tracing'
<del> })
<add> env: { ...process.env,
<add> 'NODE_DEBUG_NATIVE': 'tracing',
<add> 'NODE_DEBUG': 'tracing'
<add> }
<ide> });
<ide>
<ide> console.log('process exit with signal:', proc.signal);
<ide><path>test/parallel/test-util-inspect.js
<ide> if (typeof Symbol !== 'undefined') {
<ide> const arr = new Array(101).fill();
<ide> const obj = { a: { a: { a: { a: 1 } } } };
<ide>
<del> const oldOptions = Object.assign({}, util.inspect.defaultOptions);
<add> const oldOptions = { ...util.inspect.defaultOptions };
<ide>
<ide> // Set single option through property assignment.
<ide> util.inspect.defaultOptions.maxArrayLength = null;
<ide><path>test/parallel/test-whatwg-url-custom-properties.js
<ide> assert.strictEqual(url.searchParams, oldParams);
<ide> // contains the Symbols that Node uses for brand checking, but not the data
<ide> // properties, which are getters. Verify that urlToOptions() can handle such
<ide> // a case.
<del> const copiedUrlObj = Object.assign({}, urlObj);
<add> const copiedUrlObj = { ...urlObj };
<ide> const copiedOpts = urlToOptions(copiedUrlObj);
<ide> assert.strictEqual(copiedOpts instanceof URL, false);
<ide> assert.strictEqual(copiedOpts.protocol, undefined);
<ide><path>test/sequential/test-async-wrap-getasyncid.js
<ide> const fs = require('fs');
<ide> const v8 = require('v8');
<ide> const fsPromises = fs.promises;
<ide> const net = require('net');
<del>const providers = Object.assign({}, internalBinding('async_wrap').Providers);
<add>const providers = { ...internalBinding('async_wrap').Providers };
<ide> const fixtures = require('../common/fixtures');
<ide> const tmpdir = require('../common/tmpdir');
<ide> const { getSystemErrorName } = require('util');
<ide><path>test/sequential/test-inspector-open.js
<ide> if (process.env.BE_CHILD)
<ide> return beChild();
<ide>
<ide> const child = fork(__filename,
<del> { env: Object.assign({}, process.env, { BE_CHILD: 1 }) });
<add> { env: { ...process.env, BE_CHILD: 1 } });
<ide>
<ide> child.once('message', common.mustCall((msg) => {
<ide> assert.strictEqual(msg.cmd, 'started');
<ide><path>test/sequential/test-inspector-port-cluster.js
<ide> function workerProcessMain() {
<ide> function spawnMaster({ execArgv, workers, clusterSettings = {} }) {
<ide> return new Promise((resolve) => {
<ide> childProcess.fork(__filename, {
<del> env: Object.assign({}, process.env, {
<del> workers: JSON.stringify(workers),
<del> clusterSettings: JSON.stringify(clusterSettings),
<del> testProcess: true
<del> }),
<add> env: { ...process.env,
<add> workers: JSON.stringify(workers),
<add> clusterSettings: JSON.stringify(clusterSettings),
<add> testProcess: true
<add> },
<ide> execArgv: execArgv.concat(['--expose-internals'])
<ide> }).on('exit', common.mustCall((code, signal) => {
<ide> checkExitCode(code, signal); | 7 |
Python | Python | fix rst syntax warnings | 20caa1bd2a5087dc08f5a34fdb1e019a197f3522 | <ide><path>celery/backends/__init__.py
<ide> def get_backend_cls(backend):
<ide> """
<ide> .. function:: get_default_backend_cls()
<ide>
<del> Get the backend class specified in :settings:`CELERY_BACKEND`.
<add> Get the backend class specified in :setting:`CELERY_BACKEND`.
<ide>
<ide> """
<ide> get_default_backend_cls = partial(get_backend_cls, CELERY_BACKEND)
<ide> def get_backend_cls(backend):
<ide> .. function:: get_default_periodicstatus_backend_cls()
<ide>
<ide> Get the backend class specified in
<del> :settings:`CELERY_PERIODIC_STATUS_BACKEND`.
<add> :setting:`CELERY_PERIODIC_STATUS_BACKEND`.
<ide>
<ide> """
<ide> get_default_periodicstatus_backend_cls = partial(get_backend_cls,
<ide><path>celery/conf.py
<ide> route e.g. some tasks to one server, and others to the rest.
<ide> See `Exchange types and the effect of bindings`_.
<ide>
<del>.. _`Exchange types and the effect of bindings:
<del> http://en.wikipedia.org/wiki/Advanced_Message_Queuing_Protocol
<del> #Exchange_types_and_the_effect_of_bindings
<add>.. _`Exchange types and the effect of bindings`: http://bit.ly/wpamqpexchanges
<ide>
<ide> """
<ide> AMQP_EXCHANGE_TYPE = getattr(settings, "CELERY_AMQP_EXCHANGE_TYPE",
<ide><path>celery/result.py
<ide> def __init__(self, task_id):
<ide> class TaskSetResult(object):
<ide> """Working with :class:`celery.task.TaskSet` results.
<ide>
<del> An instance of this class is returned by :meth:`celery.task.TaskSet.run().
<add> An instance of this class is returned by :meth:`celery.task.TaskSet.run()`.
<ide> It lets you inspect the status and return values of a taskset as a
<ide> single entity.
<ide>
<ide> def __init__(self, taskset_id, subtask_ids):
<ide> self.subtasks = map(AsyncResult, self.subtask_ids)
<ide>
<ide> def itersubtasks(self):
<del> """:returns: an iterator for iterating over the tasksets
<del> :class:`AsyncResult` objects."""
<add> """Taskset subtask iterator.
<add>
<add> :returns: an iterator for iterating over the tasksets
<add> :class:`AsyncResult` objects.
<add>
<add> """
<ide> return (subtask for subtask in self.subtasks)
<ide>
<ide> def successful(self):
<del> """:returns: ``True`` if all of the tasks in the taskset finished
<del> successfully (i.e. did not raise an exception)."""
<add> """Was the taskset successful?
<add>
<add> :returns: ``True`` if all of the tasks in the taskset finished
<add> successfully (i.e. did not raise an exception).
<add>
<add> """
<ide> return all((subtask.successful()
<ide> for subtask in self.itersubtasks()))
<ide>
<ide> def failed(self):
<del> """:returns: ``True`` if any of the tasks in the taskset failed.
<del> (i.e., raised an exception)"""
<add> """Did the taskset fail?
<add>
<add> :returns: ``True`` if any of the tasks in the taskset failed.
<add> (i.e., raised an exception)
<add>
<add> """
<ide> return any((not subtask.successful()
<ide> for subtask in self.itersubtasks()))
<ide>
<ide> def waiting(self):
<del> """:returns: ``True`` if any of the tasks in the taskset is still
<del> waiting for execution."""
<add> """Is the taskset waiting?
<add>
<add> :returns: ``True`` if any of the tasks in the taskset is still
<add> waiting for execution.
<add>
<add> """
<ide> return any((not subtask.ready()
<ide> for subtask in self.itersubtasks()))
<ide>
<ide> def ready(self):
<del> """:returns: ``True`` if all of the tasks in the taskset has been
<del> executed."""
<add> """Is the task readyu?
<add>
<add> :returns: ``True`` if all of the tasks in the taskset has been
<add> executed.
<add>
<add> """
<ide> return all((subtask.ready()
<ide> for subtask in self.itersubtasks()))
<ide>
<ide> def completed_count(self):
<del> """:returns: the number of tasks completed."""
<add> """Task completion count.
<add>
<add> :returns: the number of tasks completed.
<add>
<add> """
<ide> return sum(imap(int, (subtask.successful()
<ide> for subtask in self.itersubtasks())))
<ide> | 3 |
Java | Java | remove a redundant word | c8fd4cb5840f02881a6e201767c9609642c08c86 | <ide><path>spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 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> public class ServletTestExecutionListener extends AbstractTestExecutionListener
<ide> ServletTestExecutionListener.class, "createdByTheTestContextFramework");
<ide>
<ide> /**
<del> * Attribute name for a {@link TestContext} attribute which indicates that that
<del> * the {@code ServletTestExecutionListener} should be activated. When not set to
<add> * Attribute name for a {@link TestContext} attribute which indicates that the
<add> * {@code ServletTestExecutionListener} should be activated. When not set to
<ide> * {@code true}, activation occurs when the {@linkplain TestContext#getTestClass()
<ide> * test class} is annotated with {@link WebAppConfiguration @WebAppConfiguration}.
<ide> * <p>Permissible values include {@link Boolean#TRUE} and {@link Boolean#FALSE}. | 1 |
Javascript | Javascript | fix tests after merge | 4dde417214fa48185246cddade518c57f6de32af | <ide><path>src/browser/ui/__tests__/ReactDOMComponent-test.js
<ide> describe('ReactDOMComponent', function() {
<ide> });
<ide>
<ide> it('warns on invalid nesting', () => {
<del> spyOn(console, 'warn');
<add> spyOn(console, 'error');
<ide> ReactTestUtils.renderIntoDocument(<div><tr /></div>);
<ide>
<del> expect(console.warn.calls.length).toBe(1);
<del> expect(console.warn.calls[0].args[0]).toBe(
<add> expect(console.error.calls.length).toBe(1);
<add> expect(console.error.calls[0].args[0]).toBe(
<ide> 'Warning: validateDOMNesting(...): <div> cannot contain a <tr> node.'
<ide> );
<ide> });
<ide>
<ide> it('warns on invalid nesting at root', () => {
<del> spyOn(console, 'warn');
<add> spyOn(console, 'error');
<ide> var p = document.createElement('p');
<ide> React.render(<tr />, p);
<ide>
<del> expect(console.warn.calls.length).toBe(1);
<del> expect(console.warn.calls[0].args[0]).toBe(
<add> expect(console.error.calls.length).toBe(1);
<add> expect(console.error.calls[0].args[0]).toBe(
<ide> 'Warning: validateDOMNesting(...): <p> cannot contain a <tr> node.'
<ide> );
<ide> });
<ide>
<ide> it('warns nicely for table rows', () => {
<del> spyOn(console, 'warn');
<add> spyOn(console, 'error');
<ide> var Foo = React.createClass({
<ide> render: function() {
<ide> return <table><tr /></table>;
<ide> }
<ide> });
<ide> ReactTestUtils.renderIntoDocument(<Foo />);
<ide>
<del> expect(console.warn.calls.length).toBe(1);
<del> expect(console.warn.calls[0].args[0]).toBe(
<add> expect(console.error.calls.length).toBe(1);
<add> expect(console.error.calls[0].args[0]).toBe(
<ide> 'Warning: validateDOMNesting(...): <table> cannot contain a <tr> ' +
<ide> 'node. Add a <tbody> to your code to match the DOM tree generated by ' +
<ide> 'the browser. Check the render method of `Foo`.'
<ide><path>src/classic/class/__tests__/ReactClass-test.js
<ide> describe('ReactClass-spec', function() {
<ide>
<ide> instance.getDOMNode();
<ide>
<del> expect(console.warn.calls.length).toBe(1);
<del> expect(console.warn.calls[0].args[0]).toContain(
<add> expect(console.error.calls.length).toBe(1);
<add> expect(console.error.calls[0].args[0]).toContain(
<ide> 'MyComponent.getDOMNode(...) is deprecated. Please use ' +
<ide> 'React.findDOMNode(instance) instead.'
<ide> );
<ide><path>src/core/__tests__/ReactComponent-test.js
<ide> describe('ReactComponent', function() {
<ide> });
<ide>
<ide> it('warns when calling getDOMNode', function() {
<del> spyOn(console, 'warn');
<add> spyOn(console, 'error');
<ide>
<ide> var container = document.createElement('div');
<ide> var instance = React.render(<div />, container);
<ide>
<ide> instance.getDOMNode();
<ide>
<del> expect(console.warn.calls.length).toBe(1);
<del> expect(console.warn.calls[0].args[0]).toContain(
<add> expect(console.error.calls.length).toBe(1);
<add> expect(console.error.calls[0].args[0]).toContain(
<ide> 'DIV.getDOMNode(...) is deprecated. Please use ' +
<ide> 'React.findDOMNode(instance) instead.'
<ide> ); | 3 |
Javascript | Javascript | remove old curriculum bundler | edb936ce35b498e9c593df418f10389b4bbd2643 | <ide><path>curriculum/create-challenge-bundle.js
<del>var fs = require('fs');
<del>var getChallenges = require('./getChallenges');
<del>
<del>var challengeSpecs = getChallenges();
<del>
<del>fs.writeFileSync('seed/challenge-bundle.json', JSON.stringify(challengeSpecs));
<ide><path>curriculum/package-entry.js
<del>export { default as getChallenges } from './getChallenges'; | 2 |
Python | Python | decorate non-regression tests | 91dec2c76e9affbaafb62cc6a95b317db583c569 | <ide><path>spacy/tests/lang/en/test_prefix_suffix_infix.py
<ide> def test_en_tokenizer_splits_period_abbr(en_tokenizer):
<ide> assert tokens[4].text == "Mr."
<ide>
<ide>
<add>@pytest.mark.issue(225)
<ide> @pytest.mark.xfail(reason="Issue #225 - not yet implemented")
<ide> def test_en_tokenizer_splits_em_dash_infix(en_tokenizer):
<ide> tokens = en_tokenizer(
<ide><path>spacy/tests/lang/fr/test_prefix_suffix_infix.py
<ide> from spacy.lang.char_classes import ALPHA
<ide>
<ide>
<add>@pytest.mark.issue(768)
<ide> @pytest.mark.parametrize(
<ide> "text,expected_tokens", [("l'avion", ["l'", "avion"]), ("j'ai", ["j'", "ai"])]
<ide> )
<ide><path>spacy/tests/matcher/test_dependency_matcher.py
<ide> def test_dependency_matcher_span_user_data(en_tokenizer):
<ide> assert doc_t_i == span_t_i + offset
<ide>
<ide>
<add>@pytest.mark.issue(9263)
<ide> def test_dependency_matcher_order_issue(en_tokenizer):
<ide> # issue from #9263
<ide> doc = en_tokenizer("I like text")
<ide> def test_dependency_matcher_order_issue(en_tokenizer):
<ide> assert matches == []
<ide>
<ide>
<add>@pytest.mark.issue(9263)
<ide> def test_dependency_matcher_remove(en_tokenizer):
<ide> # issue from #9263
<ide> doc = en_tokenizer("The red book")
<ide><path>spacy/tests/matcher/test_matcher_logic.py
<ide> def test_operator_combos(en_vocab):
<ide> assert not matches, (string, pattern_str)
<ide>
<ide>
<add>@pytest.mark.issue(1450)
<ide> def test_matcher_end_zero_plus(en_vocab):
<ide> """Test matcher works when patterns end with * operator. (issue 1450)"""
<ide> matcher = Matcher(en_vocab)
<ide><path>spacy/tests/serialize/test_serialize_pipeline.py
<ide> def test_serialize_tagger_strings(en_vocab, de_vocab, taggers):
<ide> assert label in tagger2.vocab.strings
<ide>
<ide>
<add>@pytest.mark.issue(1105)
<ide> def test_serialize_textcat_empty(en_vocab):
<ide> # See issue #1105
<ide> cfg = {"model": DEFAULT_SINGLE_TEXTCAT_MODEL} | 5 |
Ruby | Ruby | add helper methods for pth detection | b584689afa5683592371458f7d9383d0fea4e8e1 | <ide><path>Library/Homebrew/language/python.rb
<ide> def self.major_minor_version python
<ide> Version.new(version.to_s)
<ide> end
<ide>
<add> def self.homebrew_site_packages(version="2.7")
<add> HOMEBREW_PREFIX/"lib/python#{version}/site-packages"
<add> end
<add>
<ide> def self.each_python build, &block
<ide> original_pythonpath = ENV["PYTHONPATH"]
<ide> ["python", "python3"].each do |python|
<ide> def self.each_python build, &block
<ide> ENV["PYTHONPATH"] = if Formulary.factory(python).installed?
<ide> nil
<ide> else
<del> "#{HOMEBREW_PREFIX}/lib/python#{version}/site-packages"
<add> homebrew_site_packages(version)
<ide> end
<ide> block.call python, version if block
<ide> end
<ide> ENV["PYTHONPATH"] = original_pythonpath
<ide> end
<add>
<add> def self.reads_brewed_pth_files? python
<add> version = major_minor_version python
<add> return unless homebrew_site_packages(version).directory?
<add> probe_file = homebrew_site_packages(version)/"homebrew-pth-probe.pth"
<add> probe_file.atomic_write("import site; site.homebrew_was_here = True")
<add> result = quiet_system python, "-c", "import site; assert(site.homebrew_was_here)"
<add> probe_file.unlink
<add> result
<add> end
<add>
<add> def self.user_site_packages python
<add> Pathname.new(`#{python} -c "import site; print(site.getusersitepackages())"`.chomp)
<add> end
<add>
<add> def self.in_sys_path? python, path
<add> script = <<-EOS.undent
<add> import os, sys
<add> [os.path.realpath(p) for p in sys.path].index(os.path.realpath("#{path}"))
<add> EOS
<add> quiet_system python, "-c", script
<add> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | fix version typo in grunt task | 52164602466e6d9fe3787c522977c7a112d2ee21 | <ide><path>grunt/tasks/version-check.js
<ide> module.exports = function() {
<ide> }
<ide> if (npmReactVersion !== reactToolsVersion) {
<ide> grunt.log.error(
<del> 'npm-react version does not match react-tools veersion. Expected %s, saw %s',
<add> 'npm-react version does not match react-tools version. Expected %s, saw %s',
<ide> reactToolsVersion,
<ide> npmReactVersion
<ide> ); | 1 |
PHP | PHP | add more proxy methods to deferred value | 08c40123a438e40ad82582fee7ddaa1ff056bb83 | <ide><path>src/Illuminate/View/Component.php
<ide>
<ide> namespace Illuminate\View;
<ide>
<add>use ArrayIterator;
<ide> use Closure;
<ide> use Illuminate\Container\Container;
<ide> use Illuminate\Contracts\Support\DeferringDisplayableValue;
<add>use Illuminate\Support\Enumerable;
<ide> use Illuminate\Support\Str;
<add>use IteratorAggregate;
<ide> use ReflectionClass;
<ide> use ReflectionMethod;
<ide> use ReflectionProperty;
<ide> protected function createInvokableVariable(string $method)
<ide> {
<ide> return new class(function () use ($method) {
<ide> return $this->{$method}();
<del> }) implements DeferringDisplayableValue {
<add> }) implements DeferringDisplayableValue, IteratorAggregate {
<ide> protected $callable;
<ide>
<ide> public function __construct(Closure $callable)
<ide> public function resolveDisplayableValue()
<ide> return $this->__invoke();
<ide> }
<ide>
<add> public function getIterator()
<add> {
<add> $result = $this->__invoke();
<add>
<add> return new ArrayIterator($result instanceof Enumerable ? $result->all() : $result);
<add> }
<add>
<add> public function __get($key)
<add> {
<add> return $this->__invoke()->{$key};
<add> }
<add>
<add> public function __call($method, $parameters)
<add> {
<add> return $this->__invoke()->{$method}(...$parameters);
<add> }
<add>
<ide> public function __invoke()
<ide> {
<ide> return call_user_func($this->callable);
<ide> public function __toString()
<ide> {
<ide> return (string) $this->__invoke();
<ide> }
<del>
<ide> };
<ide> }
<ide> | 1 |
Javascript | Javascript | remove disableschedulertimeoutinworkloop flag | ba82eea3837e4aaeb5a30b7827b664a8c2128d2e | <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> import {
<ide> enableSchedulingProfiler,
<ide> enableScopeAPI,
<ide> skipUnmountedBoundaries,
<del> disableSchedulerTimeoutInWorkLoop,
<ide> enableDoubleInvokingEffects,
<ide> } from 'shared/ReactFeatureFlags';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
<ide>
<ide> // This is the entry point for every concurrent task, i.e. anything that
<ide> // goes through Scheduler.
<del>function performConcurrentWorkOnRoot(root, didTimeout) {
<add>function performConcurrentWorkOnRoot(root) {
<ide> // Since we know we're in a React event, we can clear the current
<ide> // event time. The next update will compute a new event time.
<ide> currentEventTime = NoTimestamp;
<ide> function performConcurrentWorkOnRoot(root, didTimeout) {
<ide> return null;
<ide> }
<ide>
<del> // TODO: We only check `didTimeout` defensively, to account for a Scheduler
<del> // bug we're still investigating. Once the bug in Scheduler is fixed,
<del> // we can remove this, since we track expiration ourselves.
<del> if (!disableSchedulerTimeoutInWorkLoop && didTimeout) {
<del> // Something expired. Flush synchronously until there's no expired
<del> // work left.
<del> markRootExpired(root, lanes);
<del> // This will schedule a synchronous callback.
<del> ensureRootIsScheduled(root, now());
<del> return null;
<del> }
<del>
<ide> let exitStatus = renderRootConcurrent(root, lanes);
<ide>
<ide> if (
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> import {
<ide> enableSchedulingProfiler,
<ide> enableScopeAPI,
<ide> skipUnmountedBoundaries,
<del> disableSchedulerTimeoutInWorkLoop,
<ide> } from 'shared/ReactFeatureFlags';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> import invariant from 'shared/invariant';
<ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
<ide>
<ide> // This is the entry point for every concurrent task, i.e. anything that
<ide> // goes through Scheduler.
<del>function performConcurrentWorkOnRoot(root, didTimeout) {
<add>function performConcurrentWorkOnRoot(root) {
<ide> // Since we know we're in a React event, we can clear the current
<ide> // event time. The next update will compute a new event time.
<ide> currentEventTime = NoTimestamp;
<ide> function performConcurrentWorkOnRoot(root, didTimeout) {
<ide> return null;
<ide> }
<ide>
<del> // TODO: We only check `didTimeout` defensively, to account for a Scheduler
<del> // bug we're still investigating. Once the bug in Scheduler is fixed,
<del> // we can remove this, since we track expiration ourselves.
<del> if (!disableSchedulerTimeoutInWorkLoop && didTimeout) {
<del> // Something expired. Flush synchronously until there's no expired
<del> // work left.
<del> markRootExpired(root, lanes);
<del> // This will schedule a synchronous callback.
<del> ensureRootIsScheduled(root, now());
<del> return null;
<del> }
<del>
<ide> let exitStatus = renderRootConcurrent(root, lanes);
<ide>
<ide> if (
<ide><path>packages/shared/ReactFeatureFlags.js
<ide> export const enableDiscreteEventFlushingChange = false;
<ide>
<ide> export const enableEagerRootListeners = true;
<ide>
<del>export const disableSchedulerTimeoutInWorkLoop = false;
<del>
<ide> export const enableDoubleInvokingEffects = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.native-fb.js
<ide> export const deferRenderPhaseUpdateToNextBatch = true;
<ide> export const decoupleUpdatePriorityFromScheduler = false;
<ide> export const enableDiscreteEventFlushingChange = false;
<ide> export const enableEagerRootListeners = true;
<del>export const disableSchedulerTimeoutInWorkLoop = false;
<ide>
<ide> export const enableDoubleInvokingEffects = false;
<ide>
<ide><path>packages/shared/forks/ReactFeatureFlags.native-oss.js
<ide> export const deferRenderPhaseUpdateToNextBatch = true;
<ide> export const decoupleUpdatePriorityFromScheduler = false;
<ide> export const enableDiscreteEventFlushingChange = false;
<ide> export const enableEagerRootListeners = true;
<del>export const disableSchedulerTimeoutInWorkLoop = false;
<ide>
<ide> export const enableDoubleInvokingEffects = false;
<ide>
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.js
<ide> export const deferRenderPhaseUpdateToNextBatch = true;
<ide> export const decoupleUpdatePriorityFromScheduler = false;
<ide> export const enableDiscreteEventFlushingChange = false;
<ide> export const enableEagerRootListeners = true;
<del>export const disableSchedulerTimeoutInWorkLoop = false;
<ide>
<ide> export const enableDoubleInvokingEffects = false;
<ide>
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.native.js
<ide> export const deferRenderPhaseUpdateToNextBatch = true;
<ide> export const decoupleUpdatePriorityFromScheduler = false;
<ide> export const enableDiscreteEventFlushingChange = false;
<ide> export const enableEagerRootListeners = true;
<del>export const disableSchedulerTimeoutInWorkLoop = false;
<ide>
<ide> export const enableDoubleInvokingEffects = false;
<ide>
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.www.js
<ide> export const deferRenderPhaseUpdateToNextBatch = true;
<ide> export const decoupleUpdatePriorityFromScheduler = false;
<ide> export const enableDiscreteEventFlushingChange = false;
<ide> export const enableEagerRootListeners = true;
<del>export const disableSchedulerTimeoutInWorkLoop = false;
<ide>
<ide> export const enableDoubleInvokingEffects = false;
<ide>
<ide><path>packages/shared/forks/ReactFeatureFlags.testing.js
<ide> export const deferRenderPhaseUpdateToNextBatch = true;
<ide> export const decoupleUpdatePriorityFromScheduler = false;
<ide> export const enableDiscreteEventFlushingChange = false;
<ide> export const enableEagerRootListeners = true;
<del>export const disableSchedulerTimeoutInWorkLoop = false;
<ide>
<ide> export const enableDoubleInvokingEffects = false;
<ide>
<ide><path>packages/shared/forks/ReactFeatureFlags.testing.www.js
<ide> export const deferRenderPhaseUpdateToNextBatch = true;
<ide> export const decoupleUpdatePriorityFromScheduler = false;
<ide> export const enableDiscreteEventFlushingChange = true;
<ide> export const enableEagerRootListeners = true;
<del>export const disableSchedulerTimeoutInWorkLoop = false;
<ide>
<ide> export const enableDoubleInvokingEffects = false;
<ide>
<ide><path>packages/shared/forks/ReactFeatureFlags.www-dynamic.js
<ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = __DEV__;
<ide> // to __VARIANT__.
<ide> export const enableTrustedTypesIntegration = false;
<ide> export const disableSchedulerTimeoutBasedOnReactExpirationTime = false;
<del>export const disableSchedulerTimeoutInWorkLoop = __VARIANT__;
<ide>
<ide> export const enableDoubleInvokingEffects = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.www.js
<ide> export const {
<ide> enableDebugTracing,
<ide> skipUnmountedBoundaries,
<ide> enableEagerRootListeners,
<del> disableSchedulerTimeoutInWorkLoop,
<ide> enableDoubleInvokingEffects,
<ide> } = dynamicFeatureFlags;
<ide> | 12 |
Ruby | Ruby | remove stale construct_* methods | 21ce8eac9b9bd8e14e3396caf2e30751889e26cb | <ide><path>activerecord/lib/active_record/base.rb
<ide> def construct_join(joins, scope)
<ide> end
<ide> end
<ide>
<del> def construct_order(order, scope)
<del> orders = []
<del>
<del> scoped_order = scope[:order] if scope
<del> if order
<del> orders << order
<del> orders << scoped_order if scoped_order && scoped_order != order
<del> elsif scoped_order
<del> orders << scoped_order
<del> end
<del>
<del> orders.reject {|o| o.blank?}
<del> end
<del>
<del> def construct_limit(limit, scope)
<del> limit ||= scope[:limit] if scope
<del> limit
<del> end
<del>
<del> def construct_offset(offset, scope)
<del> offset ||= scope[:offset] if scope
<del> offset
<del> end
<del>
<ide> # Merges includes so that the result is a valid +include+
<ide> def merge_includes(first, second)
<ide> (Array.wrap(first) + Array.wrap(second)).uniq | 1 |
Text | Text | fix usage in middleware errors | c984281f900811cff43e136362709dbafca3711b | <ide><path>docs/advanced-features/middleware.md
<ide> export function middleware(req: NextRequest) {
<ide> if (areCredentialsValid(req.headers.get('authorization')) {
<ide> return NextResponse.next()
<ide> }
<del> return NextResponse.redirect(`/login?from=${req.nextUrl.pathname}`)
<add> return NextResponse.redirect(new URL(`/login?from=${req.nextUrl.pathname}`, req.url))
<ide> }
<ide> ```
<ide>
<ide><path>errors/returning-response-body-in-middleware.md
<ide>
<ide> Your [`middleware`](https://nextjs.org/docs/advanced-features/middleware) function returns a response body, which is not supported.
<ide>
<del>Letting middleware respond to incoming requests would bypass Next.js routing mechanism, creating an unecessary escape hatch.
<add>Letting middleware respond to incoming requests would bypass Next.js routing mechanism, creating an unnecessary escape hatch.
<ide>
<ide> #### Possible Ways to Fix It
<ide>
<ide> It is intended for use cases like:
<ide> }
<ide> }
<ide>
<del> return NextResponse.redirect(`/login?from=${req.nextUrl.pathname}`)
<add> return NextResponse.redirect(
<add> new URL(`/login?from=${req.nextUrl.pathname}`, req.url)
<add> )
<ide> }
<ide> ```
<ide>
<ide> It is intended for use cases like:
<ide> headers: { 'response-greetings': 'Hej!' },
<ide> })
<ide> // configures cookies
<del> response.cookies.set('hello', 'world')
<add> res.cookies.set('hello', 'world')
<ide> return res
<ide> }
<ide> ``` | 2 |
Javascript | Javascript | add mocha rfc 232 service test blueprint | 4f51ebd5c47ec3e8089eadc2bdbfeca5f11f7581 | <ide><path>blueprints/service-test/mocha-rfc-232-files/__root__/__testType__/__path__/__test__.js
<add>import { expect } from 'chai';
<add>import { describe, it } from 'mocha';
<add>import { setupTest } from 'ember-mocha';
<add>
<add>describe('<%= friendlyTestDescription %>', function() {
<add> setupTest();
<add>
<add> // Replace this with your real tests.
<add> it('exists', function() {
<add> let service = this.owner.lookup('service:<%= dasherizedModuleName %>');
<add> expect(service).to.be.ok;
<add> });
<add>});
<ide><path>node-tests/blueprints/service-test-test.js
<ide> describe('Blueprint: service-test', function() {
<ide> });
<ide> });
<ide>
<add> describe('with [email protected]', function() {
<add> beforeEach(function() {
<add> modifyPackages([
<add> { name: 'ember-cli-qunit', delete: true },
<add> { name: 'ember-mocha', dev: true },
<add> ]);
<add> generateFakePackageManifest('ember-mocha', '0.14.0');
<add> });
<add>
<add> it('service-test foo', function() {
<add> return emberGenerateDestroy(['service-test', 'foo'], _file => {
<add> expect(_file('tests/unit/services/foo-test.js')).to.equal(
<add> fixture('service-test/mocha-rfc232.js')
<add> );
<add> });
<add> });
<add> });
<add>
<ide> describe('with [email protected]', function() {
<ide> beforeEach(function() {
<ide> generateFakePackageManifest('ember-cli-qunit', '4.2.0');
<ide><path>node-tests/fixtures/service-test/mocha-rfc232.js
<add>import { expect } from 'chai';
<add>import { describe, it } from 'mocha';
<add>import { setupTest } from 'ember-mocha';
<add>
<add>describe('Unit | Service | foo', function() {
<add> setupTest();
<add>
<add> // Replace this with your real tests.
<add> it('exists', function() {
<add> let service = this.owner.lookup('service:foo');
<add> expect(service).to.be.ok;
<add> });
<add>}); | 3 |
Javascript | Javascript | add smoke tests for styles (including ssr) | 44c74c7b124056649ca9d9887bb73f28d9bc7685 | <ide><path>src/renderers/dom/__tests__/ReactDOMProduction-test.js
<ide> describe('ReactDOMProduction', () => {
<ide>
<ide> var React;
<ide> var ReactDOM;
<add> var ReactDOMServer;
<ide> var oldProcess;
<ide>
<ide> beforeEach(() => {
<ide> describe('ReactDOMProduction', () => {
<ide> jest.resetModules();
<ide> React = require('react');
<ide> ReactDOM = require('react-dom');
<add> ReactDOMServer = require('react-dom/server');
<ide> });
<ide>
<ide> afterEach(() => {
<ide> describe('ReactDOMProduction', () => {
<ide>
<ide> var container = document.createElement('div');
<ide> var inst = ReactDOM.render(
<del> <div className="blue">
<add> <div className="blue" style={{fontFamily: 'Helvetica'}}>
<ide> <Component key={1}>A</Component>
<ide> <Component key={2}>B</Component>
<ide> <Component key={3}>C</Component>
<ide> describe('ReactDOMProduction', () => {
<ide>
<ide> expect(container.firstChild).toBe(inst);
<ide> expect(inst.className).toBe('blue');
<add> expect(inst.style.fontFamily).toBe('Helvetica');
<ide> expect(inst.textContent).toBe('ABC');
<ide>
<ide> ReactDOM.render(
<del> <div className="red">
<add> <div className="red" style={{fontFamily: 'Comic Sans MS'}}>
<ide> <Component key={2}>B</Component>
<ide> <Component key={1}>A</Component>
<ide> <Component key={3}>C</Component>
<ide> describe('ReactDOMProduction', () => {
<ide> );
<ide>
<ide> expect(inst.className).toBe('red');
<add> expect(inst.style.fontFamily).toBe('Comic Sans MS');
<ide> expect(inst.textContent).toBe('BAC');
<ide>
<ide> ReactDOM.unmountComponentAtNode(container);
<ide>
<ide> expect(container.childNodes.length).toBe(0);
<ide> });
<ide>
<add> it('should handle a simple flow (ssr)', () => {
<add> class Component extends React.Component {
<add> render() {
<add> return <span>{this.props.children}</span>;
<add> }
<add> }
<add>
<add> var container = document.createElement('div');
<add> var markup = ReactDOMServer.renderToString(
<add> <div className="blue" style={{fontFamily: 'Helvetica'}}>
<add> <Component key={1}>A</Component>
<add> <Component key={2}>B</Component>
<add> <Component key={3}>C</Component>
<add> </div>,
<add> container,
<add> );
<add> container.innerHTML = markup;
<add> var inst = container.firstChild;
<add>
<add> expect(inst.className).toBe('blue');
<add> expect(inst.style.fontFamily).toBe('Helvetica');
<add> expect(inst.textContent).toBe('ABC');
<add> });
<add>
<ide> it('should call lifecycle methods', () => {
<ide> var log = [];
<ide> class Component extends React.Component { | 1 |
Python | Python | fix misleading error when coercing to array | 99f605c4545597e9a3bdf66f97b98da30f78ae33 | <ide><path>numpy/lib/histograms.py
<ide> def _get_outer_edges(a, range):
<ide> if first_edge > last_edge:
<ide> raise ValueError(
<ide> 'max must be larger than min in range parameter.')
<del> if not np.all(np.isfinite([first_edge, last_edge])):
<add> if not (np.isfinite(first_edge) and np.isfinite(last_edge)):
<ide> raise ValueError(
<ide> 'range parameter must be finite.')
<ide> if first_edge == last_edge:
<ide><path>numpy/lib/tests/test_histograms.py
<ide> def test_unsigned_monotonicity_check(self):
<ide> with assert_raises(ValueError):
<ide> hist, edges = np.histogram(arr, bins=bins)
<ide>
<add> def test_object_array_of_0d(self):
<add> # gh-7864
<add> assert_raises(ValueError,
<add> histogram, [np.array([0.4]) for i in range(10)] + [-np.inf])
<add> assert_raises(ValueError,
<add> histogram, [np.array([0.4]) for i in range(10)] + [np.inf])
<add>
<add> # these should not crash
<add> np.histogram([np.array([0.5]) for i in range(10)] + [.500000000000001])
<add> np.histogram([np.array([0.5]) for i in range(10)] + [.5])
<add>
<ide>
<ide> class TestHistogramOptimBinNums(object):
<ide> """ | 2 |
Javascript | Javascript | fix timeout with null handle | cecbb595d5c4ea97264092abf2ade16b54a945fd | <ide><path>lib/net.js
<ide> Socket.prototype.setTimeout = function(msecs, callback) {
<ide>
<ide>
<ide> Socket.prototype._onTimeout = function() {
<del> // `.prevWriteQueueSize` !== `.updateWriteQueueSize()` means there is
<del> // an active write in progress, so we suppress the timeout.
<del> const prevWriteQueueSize = this._handle.writeQueueSize;
<del> if (prevWriteQueueSize > 0 &&
<del> prevWriteQueueSize !== this._handle.updateWriteQueueSize()) {
<del> this._unrefTimer();
<del> return;
<add> if (this._handle) {
<add> // `.prevWriteQueueSize` !== `.updateWriteQueueSize()` means there is
<add> // an active write in progress, so we suppress the timeout.
<add> const prevWriteQueueSize = this._handle.writeQueueSize;
<add> if (prevWriteQueueSize > 0 &&
<add> prevWriteQueueSize !== this._handle.updateWriteQueueSize()) {
<add> this._unrefTimer();
<add> return;
<add> }
<ide> }
<ide> debug('_onTimeout');
<ide> this.emit('timeout');
<ide><path>test/parallel/test-net-timeout-no-handle.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const net = require('net');
<add>const assert = require('assert');
<add>
<add>const socket = new net.Socket();
<add>socket.setTimeout(common.platformTimeout(50));
<add>
<add>socket.on('timeout', common.mustCall(() => {
<add> assert.strictEqual(socket._handle, null);
<add>}));
<add>
<add>socket.on('connect', common.mustNotCall());
<add>
<add>// since the timeout is unrefed, the code will exit without this
<add>setTimeout(() => {}, common.platformTimeout(200)); | 2 |
Text | Text | add docs for server.address() for pipe case | 13487c437cea783a91db775dd003b24a147b112e | <ide><path>doc/api/net.md
<ide> added: v0.1.90
<ide> -->
<ide>
<ide> Returns the bound address, the address family name, and port of the server
<del>as reported by the operating system.
<add>as reported by the operating system if listening on an IP socket.
<ide> Useful to find which port was assigned when getting an OS-assigned address.
<ide> Returns an object with `port`, `family`, and `address` properties:
<ide> `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
<ide>
<add>For a server listening on a pipe or UNIX domain socket, the name is returned
<add>as a string.
<add>
<ide> Example:
<ide>
<ide> ```js | 1 |
Javascript | Javascript | add .rocks to csp | 94622cc3d67fd8435fb6350931848c1597a9edb1 | <ide><path>server/middlewares/csp.js
<ide> import helmet from 'helmet';
<ide> let trusted = [
<ide> "'self'",
<ide> 'https://search.freecodecamp.org',
<add> 'https://www.freecodecamp.rocks',
<add> 'https://api.freecodecamp.rocks',
<ide> 'https://*.algolianet.com',
<ide> 'https://' + process.env.AUTH0_DOMAIN
<ide> ]; | 1 |
Python | Python | add tip for dotenv | 08e61ea200d04326f8f40a3130ef613f84cd854d | <ide><path>flask/cli.py
<ide> def load_dotenv(path=None):
<ide> """
<ide>
<ide> if dotenv is None:
<add> if path or os.path.exists('.env') or os.path.exists('.flaskenv'):
<add> click.secho(
<add> ' * Tip: There are .env files present.'
<add> ' Do "pip install python-dotenv" to use them',
<add> fg='yellow')
<ide> return
<ide>
<ide> if path is not None: | 1 |
Text | Text | use regex to filter tests in sudoku solver | f89c6806a3807361232275f344814713a5e20379 | <ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/sudoku-solver.md
<ide> async (getUserInput) => {
<ide> try {
<ide> const getTests = await $.get(getUserInput('url') + '/_api/get-tests');
<ide> assert.isArray(getTests);
<del> const units = getTests.filter((el) => el.context.includes('UnitTests'));
<del> assert.isAtLeast(units.length, 12, 'At least 12 tests passed');
<del> units.forEach((test) => {
<add> const unitTests = getTests.filter((test) => {
<add> return !!test.context.match(/Unit\s*Tests/gi);
<add> });
<add> assert.isAtLeast(unitTests.length, 12, 'At least 12 tests passed');
<add> unitTests.forEach((test) => {
<ide> assert.equal(test.state, 'passed', 'Test in Passed State');
<ide> assert.isAtLeast(
<ide> test.assertions.length,
<ide> async (getUserInput) => {
<ide> try {
<ide> const getTests = await $.get(getUserInput('url') + '/_api/get-tests');
<ide> assert.isArray(getTests);
<del> const funcs = getTests.filter((el) =>
<del> el.context.includes('Functional Tests')
<del> );
<del> assert.isAtLeast(funcs.length, 14, 'At least 14 tests passed');
<del> funcs.forEach((test) => {
<add> const functTests = getTests.filter((test) => {
<add> return !!test.context.match(/Functional\s*Tests/gi);
<add> });
<add> assert.isAtLeast(functTests.length, 14, 'At least 14 tests passed');
<add> functTests.forEach((test) => {
<ide> assert.equal(test.state, 'passed', 'Test in Passed State');
<ide> assert.isAtLeast(
<ide> test.assertions.length, | 1 |
Text | Text | add example with forwardref to readme | 144eecd185f7083a112d7bbc178c6f59e4e34252 | <ide><path>packages/next/README.md
<ide> export default About
<ide>
<ide> Note: if passing a functional component as a child of `<Link>` you will need to wrap it in [`React.forwardRef`](https://reactjs.org/docs/react-api.html#reactforwardref)
<ide>
<add>**Example with `React.forwardRef`**
<add>
<add>```jsx
<add>import React from 'react'
<add>import Link from 'next/link'
<add>
<add>// `onClick`, `href`, and `ref` need to be passed to the DOM element
<add>// for proper handling
<add>const MyButton = React.forwardRef(({ onClick, href }, ref) => (
<add> <a href={href} onClick={onClick} ref={ref}>
<add> Click Me
<add> </a>
<add>))
<add>
<add>export default () => (
<add> <>
<add> <Link href='/another'>
<add> <MyButton />
<add> </Link>
<add> </>
<add>)
<add>```
<add>
<ide> **Custom routes (using props from URL)**
<ide>
<ide> If you find that your use case is not covered by [Dynamic Routing](#dynamic-routing) then you can create a custom server and manually add dynamic routes. | 1 |
Python | Python | fix transformer loss | 0344c5503ee55e24f0de7f37336a6e08f10976fd | <ide><path>official/transformer/transformer_main.py
<ide> def model_fn(features, labels, mode, params):
<ide> logits = output
<ide>
<ide> # Calculate model loss.
<add> # xentropy contains the cross entropy loss of every nonpadding token in the
<add> # targets.
<ide> xentropy, weights = metrics.padded_cross_entropy_loss(
<ide> logits, targets, params.label_smoothing, params.vocab_size)
<del> loss = tf.reduce_sum(xentropy * weights) / tf.reduce_sum(weights)
<add> # Compute the weighted mean of the cross entropy losses
<add> loss = tf.reduce_sum(xentropy) / tf.reduce_sum(weights)
<ide>
<ide> # Save loss as named tensor that will be logged with the logging hook.
<ide> tf.identity(loss, "cross_entropy")
<ide><path>official/transformer/utils/metrics.py
<ide> def padded_cross_entropy_loss(logits, labels, smoothing, vocab_size):
<ide> smoothing: Label smoothing constant, used to determine the on and off values
<ide> vocab_size: int size of the vocabulary
<ide> Returns:
<del> Returns a float32 tensor with shape
<del> [batch_size, max(length_logits, length_labels)]
<add> Returns the cross entropy loss and weight tensors: float32 tensors with
<add> shape [batch_size, max(length_logits, length_labels)]
<ide> """
<ide> with tf.name_scope("loss", [logits, labels]):
<ide> logits, labels = _pad_tensors_to_same_length(logits, labels) | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.