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
|
---|---|---|---|---|---|
Javascript | Javascript | update gpgpu example | 3c4ec1d1bdc1f04f02d00244a7b44611c67de61d | <ide><path>examples/js/SimulatorRenderer.js
<ide> function SimulatorRenderer(WIDTH, renderer) {
<ide> var dtPosition = generatePositionTexture();
<ide> var dtVelocity = generateVelocityTexture();
<ide>
<del> rtPosition1 = getRenderTarget();
<add> rtPosition1 = getRenderTarget( THREE.RGBAFormat );
<ide> rtPosition2 = rtPosition1.clone();
<del> rtVelocity1 = rtPosition1.clone();
<del> rtVelocity2 = rtPosition1.clone();
<add> rtVelocity1 = getRenderTarget( THREE.RGBFormat );
<add> rtVelocity2 = rtVelocity1.clone();
<ide>
<ide> simulator.renderTexture(dtPosition, rtPosition1);
<ide> simulator.renderTexture(rtPosition1, rtPosition2);
<ide> function SimulatorRenderer(WIDTH, renderer) {
<ide>
<ide> this.init = init;
<ide>
<del> function getRenderTarget() {
<add> function getRenderTarget( type ) {
<ide> var renderTarget = new THREE.WebGLRenderTarget(WIDTH, WIDTH, {
<ide> wrapS: THREE.RepeatWrapping,
<ide> wrapT: THREE.RepeatWrapping,
<ide> minFilter: THREE.NearestFilter,
<ide> magFilter: THREE.NearestFilter,
<del> format: THREE.RGBAFormat,
<add> format: type,
<ide> type: THREE.FloatType,
<ide> stencilBuffer: false
<ide> });
<ide> function SimulatorRenderer(WIDTH, renderer) {
<ide>
<ide> function generatePositionTexture() {
<ide>
<del> var a = new Float32Array( PARTICLES * 3 );
<add> var a = new Float32Array( PARTICLES * 4 );
<ide>
<del> for ( var k = 0; k < PARTICLES; k += 3 ) {
<add> for ( var k = 0; k < PARTICLES; k += 4 ) {
<ide>
<ide> var x = Math.random() * BOUNDS - BOUNDS_HALF;
<ide> var y = Math.random() * BOUNDS - BOUNDS_HALF;
<ide> function SimulatorRenderer(WIDTH, renderer) {
<ide> a[ k + 0 ] = x;
<ide> a[ k + 1 ] = y;
<ide> a[ k + 2 ] = z;
<add> a[ k + 3 ] = 1;
<ide>
<ide> }
<ide>
<del> var texture = new THREE.DataTexture( a, WIDTH, WIDTH, THREE.RGBFormat, THREE.FloatType );
<add> var texture = new THREE.DataTexture( a, WIDTH, WIDTH, THREE.RGBAFormat, THREE.FloatType );
<ide> texture.minFilter = THREE.NearestFilter;
<ide> texture.magFilter = THREE.NearestFilter;
<ide> texture.needsUpdate = true; | 1 |
Javascript | Javascript | avoid unecessary nexttick | 033037cec99b3b20cfec25fcebd5ee68fbb30ad4 | <ide><path>lib/internal/streams/destroy.js
<ide> function destroy(err, cb) {
<ide> }
<ide>
<ide> this._destroy(err || null, (err) => {
<add> const emitClose = (w && w.emitClose) || (r && r.emitClose);
<ide> if (cb) {
<del> process.nextTick(emitCloseNT, this);
<add> if (emitClose) {
<add> process.nextTick(emitCloseNT, this);
<add> }
<ide> cb(err);
<ide> } else if (needError(this, err)) {
<del> process.nextTick(emitErrorAndCloseNT, this, err);
<del> } else {
<add> process.nextTick(emitClose ? emitErrorCloseNT : emitErrorNT, this, err);
<add> } else if (emitClose) {
<ide> process.nextTick(emitCloseNT, this);
<ide> }
<ide> });
<ide>
<ide> return this;
<ide> }
<ide>
<del>function emitErrorAndCloseNT(self, err) {
<del> emitErrorNT(self, err);
<del> emitCloseNT(self);
<add>function emitErrorCloseNT(self, err) {
<add> self.emit('error', err);
<add> self.emit('close');
<ide> }
<ide>
<ide> function emitCloseNT(self) {
<del> const r = self._readableState;
<del> const w = self._writableState;
<del>
<del> if (w && !w.emitClose)
<del> return;
<del> if (r && !r.emitClose)
<del> return;
<ide> self.emit('close');
<ide> }
<ide>
<add>function emitErrorNT(self, err) {
<add> self.emit('error', err);
<add>}
<add>
<ide> function undestroy() {
<ide> const r = this._readableState;
<ide> const w = this._writableState;
<ide> function undestroy() {
<ide> }
<ide> }
<ide>
<del>function emitErrorNT(self, err) {
<del> self.emit('error', err);
<del>}
<del>
<ide> function errorOrDestroy(stream, err) {
<ide> // We have tests that rely on errors being emitted
<ide> // in the same tick, so changing this is semver major. | 1 |
Text | Text | use correct status code | a4d500ba107466e8d44a82ed8ca632a3ea81a016 | <ide><path>docs/api-guide/authentication.md
<ide> If successfully authenticated, `BasicAuthentication` provides the following cred
<ide> * `request.user` will be a `django.contrib.auth.models.User` instance.
<ide> * `request.auth` will be `None`.
<ide>
<del>Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthenticated` response with an appropriate WWW-Authenticate header. For example:
<add>Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example:
<ide>
<ide> WWW-Authenticate: Basic realm="api"
<ide>
<ide> If successfully authenticated, `TokenAuthentication` provides the following cred
<ide> * `request.user` will be a `django.contrib.auth.models.User` instance.
<ide> * `request.auth` will be a `rest_framework.tokenauth.models.BasicToken` instance.
<ide>
<del>Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthenticated` response with an appropriate WWW-Authenticate header. For example:
<add>Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example:
<ide>
<ide> WWW-Authenticate: Token
<ide>
<ide> Typically the approach you should take is:
<ide> * If authentication is not attempted, return `None`. Any other authentication schemes also in use will still be checked.
<ide> * If authentication is attempted but fails, raise an `Unauthenticated` exception. An error response will be returned immediately, without checking any other authentication schemes.
<ide>
<del>You *may* also override the `.authentication_header(self, request)` method. If implemented, it should return a string that will be used as the value of the `WWW-Authenticate` header in a `HTTP 401 Unauthenticated` response.
<add>You *may* also override the `.authentication_header(self, request)` method. If implemented, it should return a string that will be used as the value of the `WWW-Authenticate` header in a `HTTP 401 Unauthorized` response.
<ide>
<ide> If the `.authentication_header()` method is not overridden, the authentication scheme will return `HTTP 403 Forbidden` responses when an unauthenticated request is denied access.
<ide> | 1 |
Ruby | Ruby | remove superfluous test | 116fae6ef994dcc46d334a2dd652c1d7e977468e | <ide><path>activestorage/test/jobs/purge_job_test.rb
<ide> class ActiveStorage::PurgeJobTest < ActiveJob::TestCase
<ide> end
<ide> end
<ide> end
<del>
<del> test "ignores attached blob" do
<del> User.create! name: "DHH", avatar: @blob
<del>
<del> perform_enqueued_jobs do
<del> assert_nothing_raised do
<del> ActiveStorage::PurgeJob.perform_later @blob
<del> end
<del> end
<del> end
<ide> end | 1 |
Text | Text | add chinese translation for 01-why-react.md | c3948483d975f57af4e2fedb426969f7c8d61563 | <ide><path>docs/docs/01-why-react.zh-CN.md
<add>---
<add>id: why-react-zh-CN
<add>title: 为什么使用 React?
<add>layout: docs
<add>permalink: why-react-zh-CN.html
<add>next: displaying-data.html
<add>---
<add>
<add>React 是一个 Facebook 和 Instagram 用来创建用户界面的 JavaScript 库。很人多认为 React 是 **[MVC](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)** 中的 **V**(视图)。
<add>
<add>我们创造 React 是为了解决一个问题:**构建随着时间数据不断变化的大规模应用程序**。为了达到这个目标,React 采用下面两个主要的思想。
<add>
<add>### 简单
<add>
<add>仅仅只要表达出你的应用程序在任一个时间点应该长的样子,然后当底层的数据变了,React 会自动更新所有UI的变化。
<add>
<add>### 表达能力(Declarative)
<add>
<add>当数据变化了,React 概念上是类似点击了更新的按钮,但仅会更新变化的部分。
<add>
<add>## 构建可组合的组件
<add>
<add>React is all about building reusable components. In fact, with React the *only* thing you do is build components. Since they're so encapsulated, components make code reuse, testing, and separation of concerns easy.
<add>
<add>React 是所有关于创建可以复用的组件。事实上,通过 React 你*唯一*要做的事情就是构建组件。得益于其良好的封装性,组件使代码复用、测试和关注分离(separation of concerns)更加简单。
<add>
<add>## 给它5分钟的时间
<add>
<add>React挑战了很多传统的知识,第一眼看上去可能很多想法有点疯狂。当你阅读这篇指南,请[给它5分钟的时间](http://37signals.com/svn/posts/3124-give-it-five-minutes);那些疯狂的想法已经帮助 Facebook 和 Instagram 从里到外创建了上千的组件了。
<add>
<add>## 了解更多
<add>
<add>你可以从这篇[博客](http://facebook.github.io/react/blog/2013/06/05/why-react.html)了解更多我们创造 React 的动机。
<add>
<add> | 1 |
Python | Python | add is_done=true to get_all_expired filter | 52ffc2b264cbacaee56017cd4a67df4511d60392 | <ide><path>celery/managers.py
<ide> def is_done(self, task_id):
<ide> return self.get_task(task_id).is_done
<ide>
<ide> def get_all_expired(self):
<del> return self.filter(date_done__lt=datetime.now() - timedelta(days=5))
<add> return self.filter(date_done__lt=datetime.now() - timedelta(days=5),
<add> is_done=True)
<ide>
<ide> def delete_expired(self):
<ide> self.get_all_expired().delete() | 1 |
Javascript | Javascript | add missing variables | 6e8878041958373b4d5db25c4206d82a59d7af24 | <ide><path>examples/with-external-scoped-css/pages/_document.js
<ide> import Document, { Head, Main, NextScript } from 'next/document'
<ide>
<ide> export default class MyDocument extends Document {
<ide> static getInitialProps ({ renderPage }) {
<del> const {html, head} = renderPage()
<del> return { html, head }
<add> const { html, head, errorHtml, chunks } = renderPage()
<add> return { html, head, errorHtml, chunks }
<ide> }
<ide>
<ide> render () { | 1 |
Javascript | Javascript | extract layout effects to separate functions | 679eea3282967742473910aed1209ac8c21f2a67 | <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js
<ide> export function commitPassiveEffectDurations(
<ide> }
<ide> }
<ide>
<add>function commitHookLayoutEffects(finishedWork: Fiber) {
<add> // At this point layout effects have already been destroyed (during mutation phase).
<add> // This is done to prevent sibling component effects from interfering with each other,
<add> // e.g. a destroy function in one component should never override a ref set
<add> // by a create function in another component during the same commit.
<add> if (
<add> enableProfilerTimer &&
<add> enableProfilerCommitHooks &&
<add> finishedWork.mode & ProfileMode
<add> ) {
<add> try {
<add> startLayoutEffectTimer();
<add> commitHookEffectListMount(HookLayout | HookHasEffect, finishedWork);
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add> recordLayoutEffectDuration(finishedWork);
<add> } else {
<add> try {
<add> commitHookEffectListMount(HookLayout | HookHasEffect, finishedWork);
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add> }
<add>}
<add>
<add>function commitClassLayoutLifecycles(
<add> finishedWork: Fiber,
<add> current: Fiber | null,
<add>) {
<add> const instance = finishedWork.stateNode;
<add> if (current === null) {
<add> // We could update instance props and state here,
<add> // but instead we rely on them being set during last render.
<add> // TODO: revisit this when we implement resuming.
<add> if (__DEV__) {
<add> if (
<add> finishedWork.type === finishedWork.elementType &&
<add> !didWarnAboutReassigningProps
<add> ) {
<add> if (instance.props !== finishedWork.memoizedProps) {
<add> console.error(
<add> 'Expected %s props to match memoized props before ' +
<add> 'componentDidMount. ' +
<add> 'This might either be because of a bug in React, or because ' +
<add> 'a component reassigns its own `this.props`. ' +
<add> 'Please file an issue.',
<add> getComponentNameFromFiber(finishedWork) || 'instance',
<add> );
<add> }
<add> if (instance.state !== finishedWork.memoizedState) {
<add> console.error(
<add> 'Expected %s state to match memoized state before ' +
<add> 'componentDidMount. ' +
<add> 'This might either be because of a bug in React, or because ' +
<add> 'a component reassigns its own `this.state`. ' +
<add> 'Please file an issue.',
<add> getComponentNameFromFiber(finishedWork) || 'instance',
<add> );
<add> }
<add> }
<add> }
<add> if (
<add> enableProfilerTimer &&
<add> enableProfilerCommitHooks &&
<add> finishedWork.mode & ProfileMode
<add> ) {
<add> try {
<add> startLayoutEffectTimer();
<add> instance.componentDidMount();
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add> recordLayoutEffectDuration(finishedWork);
<add> } else {
<add> try {
<add> instance.componentDidMount();
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add> }
<add> } else {
<add> const prevProps =
<add> finishedWork.elementType === finishedWork.type
<add> ? current.memoizedProps
<add> : resolveDefaultProps(finishedWork.type, current.memoizedProps);
<add> const prevState = current.memoizedState;
<add> // We could update instance props and state here,
<add> // but instead we rely on them being set during last render.
<add> // TODO: revisit this when we implement resuming.
<add> if (__DEV__) {
<add> if (
<add> finishedWork.type === finishedWork.elementType &&
<add> !didWarnAboutReassigningProps
<add> ) {
<add> if (instance.props !== finishedWork.memoizedProps) {
<add> console.error(
<add> 'Expected %s props to match memoized props before ' +
<add> 'componentDidUpdate. ' +
<add> 'This might either be because of a bug in React, or because ' +
<add> 'a component reassigns its own `this.props`. ' +
<add> 'Please file an issue.',
<add> getComponentNameFromFiber(finishedWork) || 'instance',
<add> );
<add> }
<add> if (instance.state !== finishedWork.memoizedState) {
<add> console.error(
<add> 'Expected %s state to match memoized state before ' +
<add> 'componentDidUpdate. ' +
<add> 'This might either be because of a bug in React, or because ' +
<add> 'a component reassigns its own `this.state`. ' +
<add> 'Please file an issue.',
<add> getComponentNameFromFiber(finishedWork) || 'instance',
<add> );
<add> }
<add> }
<add> }
<add> if (
<add> enableProfilerTimer &&
<add> enableProfilerCommitHooks &&
<add> finishedWork.mode & ProfileMode
<add> ) {
<add> try {
<add> startLayoutEffectTimer();
<add> instance.componentDidUpdate(
<add> prevProps,
<add> prevState,
<add> instance.__reactInternalSnapshotBeforeUpdate,
<add> );
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add> recordLayoutEffectDuration(finishedWork);
<add> } else {
<add> try {
<add> instance.componentDidUpdate(
<add> prevProps,
<add> prevState,
<add> instance.__reactInternalSnapshotBeforeUpdate,
<add> );
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add> }
<add> }
<add>}
<add>
<add>function commitClassCallbacks(finishedWork: Fiber, current: Fiber | null) {
<add> // TODO: I think this is now always non-null by the time it reaches the
<add> // commit phase. Consider removing the type check.
<add> const updateQueue: UpdateQueue<*> | null = (finishedWork.updateQueue: any);
<add> if (updateQueue !== null) {
<add> const instance = finishedWork.stateNode;
<add> if (__DEV__) {
<add> if (
<add> finishedWork.type === finishedWork.elementType &&
<add> !didWarnAboutReassigningProps
<add> ) {
<add> if (instance.props !== finishedWork.memoizedProps) {
<add> console.error(
<add> 'Expected %s props to match memoized props before ' +
<add> 'processing the update queue. ' +
<add> 'This might either be because of a bug in React, or because ' +
<add> 'a component reassigns its own `this.props`. ' +
<add> 'Please file an issue.',
<add> getComponentNameFromFiber(finishedWork) || 'instance',
<add> );
<add> }
<add> if (instance.state !== finishedWork.memoizedState) {
<add> console.error(
<add> 'Expected %s state to match memoized state before ' +
<add> 'processing the update queue. ' +
<add> 'This might either be because of a bug in React, or because ' +
<add> 'a component reassigns its own `this.state`. ' +
<add> 'Please file an issue.',
<add> getComponentNameFromFiber(finishedWork) || 'instance',
<add> );
<add> }
<add> }
<add> }
<add> // We could update instance props and state here,
<add> // but instead we rely on them being set during last render.
<add> // TODO: revisit this when we implement resuming.
<add> try {
<add> commitCallbacks(updateQueue, instance);
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add> }
<add>}
<add>
<add>function commitHostComponentMount(finishedWork: Fiber, current: Fiber | null) {
<add> const type = finishedWork.type;
<add> const props = finishedWork.memoizedProps;
<add> const instance: Instance = finishedWork.stateNode;
<add> try {
<add> commitMount(instance, type, props, finishedWork);
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add>}
<add>
<add>function commitProfilerUpdate(finishedWork: Fiber, current: Fiber | null) {
<add> if (enableProfilerTimer) {
<add> try {
<add> const {onCommit, onRender} = finishedWork.memoizedProps;
<add> const {effectDuration} = finishedWork.stateNode;
<add>
<add> const commitTime = getCommitTime();
<add>
<add> let phase = current === null ? 'mount' : 'update';
<add> if (enableProfilerNestedUpdatePhase) {
<add> if (isCurrentUpdateNested()) {
<add> phase = 'nested-update';
<add> }
<add> }
<add>
<add> if (typeof onRender === 'function') {
<add> onRender(
<add> finishedWork.memoizedProps.id,
<add> phase,
<add> finishedWork.actualDuration,
<add> finishedWork.treeBaseDuration,
<add> finishedWork.actualStartTime,
<add> commitTime,
<add> );
<add> }
<add>
<add> if (enableProfilerCommitHooks) {
<add> if (typeof onCommit === 'function') {
<add> onCommit(
<add> finishedWork.memoizedProps.id,
<add> phase,
<add> effectDuration,
<add> commitTime,
<add> );
<add> }
<add>
<add> // Schedule a passive effect for this Profiler to call onPostCommit hooks.
<add> // This effect should be scheduled even if there is no onPostCommit callback for this Profiler,
<add> // because the effect is also where times bubble to parent Profilers.
<add> enqueuePendingPassiveProfilerEffect(finishedWork);
<add>
<add> // Propagate layout effect durations to the next nearest Profiler ancestor.
<add> // Do not reset these values until the next render so DevTools has a chance to read them first.
<add> let parentFiber = finishedWork.return;
<add> outer: while (parentFiber !== null) {
<add> switch (parentFiber.tag) {
<add> case HostRoot:
<add> const root = parentFiber.stateNode;
<add> root.effectDuration += effectDuration;
<add> break outer;
<add> case Profiler:
<add> const parentStateNode = parentFiber.stateNode;
<add> parentStateNode.effectDuration += effectDuration;
<add> break outer;
<add> }
<add> parentFiber = parentFiber.return;
<add> }
<add> }
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add> }
<add>}
<add>
<ide> function commitLayoutEffectOnFiber(
<ide> finishedRoot: FiberRoot,
<ide> current: Fiber | null,
<ide> function commitLayoutEffectOnFiber(
<ide> );
<ide> if (flags & Update) {
<ide> if (!offscreenSubtreeWasHidden) {
<del> // At this point layout effects have already been destroyed (during mutation phase).
<del> // This is done to prevent sibling component effects from interfering with each other,
<del> // e.g. a destroy function in one component should never override a ref set
<del> // by a create function in another component during the same commit.
<del> if (
<del> enableProfilerTimer &&
<del> enableProfilerCommitHooks &&
<del> finishedWork.mode & ProfileMode
<del> ) {
<del> try {
<del> startLayoutEffectTimer();
<del> commitHookEffectListMount(
<del> HookLayout | HookHasEffect,
<del> finishedWork,
<del> );
<del> } catch (error) {
<del> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<del> }
<del> recordLayoutEffectDuration(finishedWork);
<del> } else {
<del> try {
<del> commitHookEffectListMount(
<del> HookLayout | HookHasEffect,
<del> finishedWork,
<del> );
<del> } catch (error) {
<del> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<del> }
<del> }
<add> commitHookLayoutEffects(finishedWork);
<ide> }
<ide> }
<ide> break;
<ide> function commitLayoutEffectOnFiber(
<ide> );
<ide> if (flags & Update) {
<ide> if (!offscreenSubtreeWasHidden) {
<del> const instance = finishedWork.stateNode;
<del> if (current === null) {
<del> // We could update instance props and state here,
<del> // but instead we rely on them being set during last render.
<del> // TODO: revisit this when we implement resuming.
<del> if (__DEV__) {
<del> if (
<del> finishedWork.type === finishedWork.elementType &&
<del> !didWarnAboutReassigningProps
<del> ) {
<del> if (instance.props !== finishedWork.memoizedProps) {
<del> console.error(
<del> 'Expected %s props to match memoized props before ' +
<del> 'componentDidMount. ' +
<del> 'This might either be because of a bug in React, or because ' +
<del> 'a component reassigns its own `this.props`. ' +
<del> 'Please file an issue.',
<del> getComponentNameFromFiber(finishedWork) || 'instance',
<del> );
<del> }
<del> if (instance.state !== finishedWork.memoizedState) {
<del> console.error(
<del> 'Expected %s state to match memoized state before ' +
<del> 'componentDidMount. ' +
<del> 'This might either be because of a bug in React, or because ' +
<del> 'a component reassigns its own `this.state`. ' +
<del> 'Please file an issue.',
<del> getComponentNameFromFiber(finishedWork) || 'instance',
<del> );
<del> }
<del> }
<del> }
<del> if (
<del> enableProfilerTimer &&
<del> enableProfilerCommitHooks &&
<del> finishedWork.mode & ProfileMode
<del> ) {
<del> try {
<del> startLayoutEffectTimer();
<del> instance.componentDidMount();
<del> } catch (error) {
<del> captureCommitPhaseError(
<del> finishedWork,
<del> finishedWork.return,
<del> error,
<del> );
<del> }
<del> recordLayoutEffectDuration(finishedWork);
<del> } else {
<del> try {
<del> instance.componentDidMount();
<del> } catch (error) {
<del> captureCommitPhaseError(
<del> finishedWork,
<del> finishedWork.return,
<del> error,
<del> );
<del> }
<del> }
<del> } else {
<del> const prevProps =
<del> finishedWork.elementType === finishedWork.type
<del> ? current.memoizedProps
<del> : resolveDefaultProps(finishedWork.type, current.memoizedProps);
<del> const prevState = current.memoizedState;
<del> // We could update instance props and state here,
<del> // but instead we rely on them being set during last render.
<del> // TODO: revisit this when we implement resuming.
<del> if (__DEV__) {
<del> if (
<del> finishedWork.type === finishedWork.elementType &&
<del> !didWarnAboutReassigningProps
<del> ) {
<del> if (instance.props !== finishedWork.memoizedProps) {
<del> console.error(
<del> 'Expected %s props to match memoized props before ' +
<del> 'componentDidUpdate. ' +
<del> 'This might either be because of a bug in React, or because ' +
<del> 'a component reassigns its own `this.props`. ' +
<del> 'Please file an issue.',
<del> getComponentNameFromFiber(finishedWork) || 'instance',
<del> );
<del> }
<del> if (instance.state !== finishedWork.memoizedState) {
<del> console.error(
<del> 'Expected %s state to match memoized state before ' +
<del> 'componentDidUpdate. ' +
<del> 'This might either be because of a bug in React, or because ' +
<del> 'a component reassigns its own `this.state`. ' +
<del> 'Please file an issue.',
<del> getComponentNameFromFiber(finishedWork) || 'instance',
<del> );
<del> }
<del> }
<del> }
<del> if (
<del> enableProfilerTimer &&
<del> enableProfilerCommitHooks &&
<del> finishedWork.mode & ProfileMode
<del> ) {
<del> try {
<del> startLayoutEffectTimer();
<del> instance.componentDidUpdate(
<del> prevProps,
<del> prevState,
<del> instance.__reactInternalSnapshotBeforeUpdate,
<del> );
<del> } catch (error) {
<del> captureCommitPhaseError(
<del> finishedWork,
<del> finishedWork.return,
<del> error,
<del> );
<del> }
<del> recordLayoutEffectDuration(finishedWork);
<del> } else {
<del> try {
<del> instance.componentDidUpdate(
<del> prevProps,
<del> prevState,
<del> instance.__reactInternalSnapshotBeforeUpdate,
<del> );
<del> } catch (error) {
<del> captureCommitPhaseError(
<del> finishedWork,
<del> finishedWork.return,
<del> error,
<del> );
<del> }
<del> }
<del> }
<add> commitClassLayoutLifecycles(finishedWork, current);
<ide> }
<ide> }
<ide>
<ide> if (flags & Callback) {
<del> // TODO: I think this is now always non-null by the time it reaches the
<del> // commit phase. Consider removing the type check.
<del> const updateQueue: UpdateQueue<
<del> *,
<del> > | null = (finishedWork.updateQueue: any);
<del> if (updateQueue !== null) {
<del> const instance = finishedWork.stateNode;
<del> if (__DEV__) {
<del> if (
<del> finishedWork.type === finishedWork.elementType &&
<del> !didWarnAboutReassigningProps
<del> ) {
<del> if (instance.props !== finishedWork.memoizedProps) {
<del> console.error(
<del> 'Expected %s props to match memoized props before ' +
<del> 'processing the update queue. ' +
<del> 'This might either be because of a bug in React, or because ' +
<del> 'a component reassigns its own `this.props`. ' +
<del> 'Please file an issue.',
<del> getComponentNameFromFiber(finishedWork) || 'instance',
<del> );
<del> }
<del> if (instance.state !== finishedWork.memoizedState) {
<del> console.error(
<del> 'Expected %s state to match memoized state before ' +
<del> 'processing the update queue. ' +
<del> 'This might either be because of a bug in React, or because ' +
<del> 'a component reassigns its own `this.state`. ' +
<del> 'Please file an issue.',
<del> getComponentNameFromFiber(finishedWork) || 'instance',
<del> );
<del> }
<del> }
<del> }
<del> // We could update instance props and state here,
<del> // but instead we rely on them being set during last render.
<del> // TODO: revisit this when we implement resuming.
<del> try {
<del> commitCallbacks(updateQueue, instance);
<del> } catch (error) {
<del> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<del> }
<del> }
<add> commitClassCallbacks(finishedWork, current);
<ide> }
<ide>
<ide> if (flags & Ref) {
<ide> if (!offscreenSubtreeWasHidden) {
<del> try {
<del> commitAttachRef(finishedWork);
<del> } catch (error) {
<del> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<del> }
<add> safelyAttachRef(finishedWork, finishedWork.return);
<ide> }
<ide> }
<ide> break;
<ide> function commitLayoutEffectOnFiber(
<ide> finishedWork,
<ide> committedLanes,
<ide> );
<del> if (flags & Update) {
<del> const instance: Instance = finishedWork.stateNode;
<del>
<del> // Renderers may schedule work to be done after host components are mounted
<del> // (eg DOM renderer may schedule auto-focus for inputs and form controls).
<del> // These effects should only be committed when components are first mounted,
<del> // aka when there is no current/alternate.
<del> if (current === null && finishedWork.flags & Update) {
<del> const type = finishedWork.type;
<del> const props = finishedWork.memoizedProps;
<del> try {
<del> commitMount(instance, type, props, finishedWork);
<del> } catch (error) {
<del> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<del> }
<del> }
<add>
<add> // Renderers may schedule work to be done after host components are mounted
<add> // (eg DOM renderer may schedule auto-focus for inputs and form controls).
<add> // These effects should only be committed when components are first mounted,
<add> // aka when there is no current/alternate.
<add> if (current === null && flags & Update) {
<add> commitHostComponentMount(finishedWork, current);
<ide> }
<ide>
<ide> if (flags & Ref) {
<ide> if (!offscreenSubtreeWasHidden) {
<del> try {
<del> commitAttachRef(finishedWork);
<del> } catch (error) {
<del> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<del> }
<add> safelyAttachRef(finishedWork, finishedWork.return);
<ide> }
<ide> }
<ide> break;
<ide> function commitLayoutEffectOnFiber(
<ide> finishedWork,
<ide> committedLanes,
<ide> );
<del> if (enableProfilerTimer) {
<del> if (flags & Update) {
<del> try {
<del> const {onCommit, onRender} = finishedWork.memoizedProps;
<del> const {effectDuration} = finishedWork.stateNode;
<del>
<del> const commitTime = getCommitTime();
<del>
<del> let phase = current === null ? 'mount' : 'update';
<del> if (enableProfilerNestedUpdatePhase) {
<del> if (isCurrentUpdateNested()) {
<del> phase = 'nested-update';
<del> }
<del> }
<del>
<del> if (typeof onRender === 'function') {
<del> onRender(
<del> finishedWork.memoizedProps.id,
<del> phase,
<del> finishedWork.actualDuration,
<del> finishedWork.treeBaseDuration,
<del> finishedWork.actualStartTime,
<del> commitTime,
<del> );
<del> }
<del>
<del> if (enableProfilerCommitHooks) {
<del> if (typeof onCommit === 'function') {
<del> onCommit(
<del> finishedWork.memoizedProps.id,
<del> phase,
<del> effectDuration,
<del> commitTime,
<del> );
<del> }
<del>
<del> // Schedule a passive effect for this Profiler to call onPostCommit hooks.
<del> // This effect should be scheduled even if there is no onPostCommit callback for this Profiler,
<del> // because the effect is also where times bubble to parent Profilers.
<del> enqueuePendingPassiveProfilerEffect(finishedWork);
<del>
<del> // Propagate layout effect durations to the next nearest Profiler ancestor.
<del> // Do not reset these values until the next render so DevTools has a chance to read them first.
<del> let parentFiber = finishedWork.return;
<del> outer: while (parentFiber !== null) {
<del> switch (parentFiber.tag) {
<del> case HostRoot:
<del> const root = parentFiber.stateNode;
<del> root.effectDuration += effectDuration;
<del> break outer;
<del> case Profiler:
<del> const parentStateNode = parentFiber.stateNode;
<del> parentStateNode.effectDuration += effectDuration;
<del> break outer;
<del> }
<del> parentFiber = parentFiber.return;
<del> }
<del> }
<del> } catch (error) {
<del> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<del> }
<del> }
<add> // TODO: Should this fire inside an offscreen tree? Or should it wait to
<add> // fire when the tree becomes visible again.
<add> if (flags & Update) {
<add> commitProfilerUpdate(finishedWork, current);
<ide> }
<ide> break;
<ide> }
<ide> function commitLayoutEffectOnFiber(
<ide> committedLanes,
<ide> );
<ide> if (flags & Update) {
<del> try {
<del> commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
<del> } catch (error) {
<del> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<del> }
<add> commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
<ide> }
<ide> break;
<ide> }
<ide> function commitSuspenseHydrationCallbacks(
<ide> if (prevState !== null) {
<ide> const suspenseInstance = prevState.dehydrated;
<ide> if (suspenseInstance !== null) {
<del> commitHydratedSuspenseInstance(suspenseInstance);
<del> if (enableSuspenseCallback) {
<del> const hydrationCallbacks = finishedRoot.hydrationCallbacks;
<del> if (hydrationCallbacks !== null) {
<del> const onHydrated = hydrationCallbacks.onHydrated;
<del> if (onHydrated) {
<del> onHydrated(suspenseInstance);
<add> try {
<add> commitHydratedSuspenseInstance(suspenseInstance);
<add> if (enableSuspenseCallback) {
<add> const hydrationCallbacks = finishedRoot.hydrationCallbacks;
<add> if (hydrationCallbacks !== null) {
<add> const onHydrated = hydrationCallbacks.onHydrated;
<add> if (onHydrated) {
<add> onHydrated(suspenseInstance);
<add> }
<ide> }
<ide> }
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<ide> }
<ide> }
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberCommitWork.old.js
<ide> export function commitPassiveEffectDurations(
<ide> }
<ide> }
<ide>
<add>function commitHookLayoutEffects(finishedWork: Fiber) {
<add> // At this point layout effects have already been destroyed (during mutation phase).
<add> // This is done to prevent sibling component effects from interfering with each other,
<add> // e.g. a destroy function in one component should never override a ref set
<add> // by a create function in another component during the same commit.
<add> if (
<add> enableProfilerTimer &&
<add> enableProfilerCommitHooks &&
<add> finishedWork.mode & ProfileMode
<add> ) {
<add> try {
<add> startLayoutEffectTimer();
<add> commitHookEffectListMount(HookLayout | HookHasEffect, finishedWork);
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add> recordLayoutEffectDuration(finishedWork);
<add> } else {
<add> try {
<add> commitHookEffectListMount(HookLayout | HookHasEffect, finishedWork);
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add> }
<add>}
<add>
<add>function commitClassLayoutLifecycles(
<add> finishedWork: Fiber,
<add> current: Fiber | null,
<add>) {
<add> const instance = finishedWork.stateNode;
<add> if (current === null) {
<add> // We could update instance props and state here,
<add> // but instead we rely on them being set during last render.
<add> // TODO: revisit this when we implement resuming.
<add> if (__DEV__) {
<add> if (
<add> finishedWork.type === finishedWork.elementType &&
<add> !didWarnAboutReassigningProps
<add> ) {
<add> if (instance.props !== finishedWork.memoizedProps) {
<add> console.error(
<add> 'Expected %s props to match memoized props before ' +
<add> 'componentDidMount. ' +
<add> 'This might either be because of a bug in React, or because ' +
<add> 'a component reassigns its own `this.props`. ' +
<add> 'Please file an issue.',
<add> getComponentNameFromFiber(finishedWork) || 'instance',
<add> );
<add> }
<add> if (instance.state !== finishedWork.memoizedState) {
<add> console.error(
<add> 'Expected %s state to match memoized state before ' +
<add> 'componentDidMount. ' +
<add> 'This might either be because of a bug in React, or because ' +
<add> 'a component reassigns its own `this.state`. ' +
<add> 'Please file an issue.',
<add> getComponentNameFromFiber(finishedWork) || 'instance',
<add> );
<add> }
<add> }
<add> }
<add> if (
<add> enableProfilerTimer &&
<add> enableProfilerCommitHooks &&
<add> finishedWork.mode & ProfileMode
<add> ) {
<add> try {
<add> startLayoutEffectTimer();
<add> instance.componentDidMount();
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add> recordLayoutEffectDuration(finishedWork);
<add> } else {
<add> try {
<add> instance.componentDidMount();
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add> }
<add> } else {
<add> const prevProps =
<add> finishedWork.elementType === finishedWork.type
<add> ? current.memoizedProps
<add> : resolveDefaultProps(finishedWork.type, current.memoizedProps);
<add> const prevState = current.memoizedState;
<add> // We could update instance props and state here,
<add> // but instead we rely on them being set during last render.
<add> // TODO: revisit this when we implement resuming.
<add> if (__DEV__) {
<add> if (
<add> finishedWork.type === finishedWork.elementType &&
<add> !didWarnAboutReassigningProps
<add> ) {
<add> if (instance.props !== finishedWork.memoizedProps) {
<add> console.error(
<add> 'Expected %s props to match memoized props before ' +
<add> 'componentDidUpdate. ' +
<add> 'This might either be because of a bug in React, or because ' +
<add> 'a component reassigns its own `this.props`. ' +
<add> 'Please file an issue.',
<add> getComponentNameFromFiber(finishedWork) || 'instance',
<add> );
<add> }
<add> if (instance.state !== finishedWork.memoizedState) {
<add> console.error(
<add> 'Expected %s state to match memoized state before ' +
<add> 'componentDidUpdate. ' +
<add> 'This might either be because of a bug in React, or because ' +
<add> 'a component reassigns its own `this.state`. ' +
<add> 'Please file an issue.',
<add> getComponentNameFromFiber(finishedWork) || 'instance',
<add> );
<add> }
<add> }
<add> }
<add> if (
<add> enableProfilerTimer &&
<add> enableProfilerCommitHooks &&
<add> finishedWork.mode & ProfileMode
<add> ) {
<add> try {
<add> startLayoutEffectTimer();
<add> instance.componentDidUpdate(
<add> prevProps,
<add> prevState,
<add> instance.__reactInternalSnapshotBeforeUpdate,
<add> );
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add> recordLayoutEffectDuration(finishedWork);
<add> } else {
<add> try {
<add> instance.componentDidUpdate(
<add> prevProps,
<add> prevState,
<add> instance.__reactInternalSnapshotBeforeUpdate,
<add> );
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add> }
<add> }
<add>}
<add>
<add>function commitClassCallbacks(finishedWork: Fiber, current: Fiber | null) {
<add> // TODO: I think this is now always non-null by the time it reaches the
<add> // commit phase. Consider removing the type check.
<add> const updateQueue: UpdateQueue<*> | null = (finishedWork.updateQueue: any);
<add> if (updateQueue !== null) {
<add> const instance = finishedWork.stateNode;
<add> if (__DEV__) {
<add> if (
<add> finishedWork.type === finishedWork.elementType &&
<add> !didWarnAboutReassigningProps
<add> ) {
<add> if (instance.props !== finishedWork.memoizedProps) {
<add> console.error(
<add> 'Expected %s props to match memoized props before ' +
<add> 'processing the update queue. ' +
<add> 'This might either be because of a bug in React, or because ' +
<add> 'a component reassigns its own `this.props`. ' +
<add> 'Please file an issue.',
<add> getComponentNameFromFiber(finishedWork) || 'instance',
<add> );
<add> }
<add> if (instance.state !== finishedWork.memoizedState) {
<add> console.error(
<add> 'Expected %s state to match memoized state before ' +
<add> 'processing the update queue. ' +
<add> 'This might either be because of a bug in React, or because ' +
<add> 'a component reassigns its own `this.state`. ' +
<add> 'Please file an issue.',
<add> getComponentNameFromFiber(finishedWork) || 'instance',
<add> );
<add> }
<add> }
<add> }
<add> // We could update instance props and state here,
<add> // but instead we rely on them being set during last render.
<add> // TODO: revisit this when we implement resuming.
<add> try {
<add> commitCallbacks(updateQueue, instance);
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add> }
<add>}
<add>
<add>function commitHostComponentMount(finishedWork: Fiber, current: Fiber | null) {
<add> const type = finishedWork.type;
<add> const props = finishedWork.memoizedProps;
<add> const instance: Instance = finishedWork.stateNode;
<add> try {
<add> commitMount(instance, type, props, finishedWork);
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add>}
<add>
<add>function commitProfilerUpdate(finishedWork: Fiber, current: Fiber | null) {
<add> if (enableProfilerTimer) {
<add> try {
<add> const {onCommit, onRender} = finishedWork.memoizedProps;
<add> const {effectDuration} = finishedWork.stateNode;
<add>
<add> const commitTime = getCommitTime();
<add>
<add> let phase = current === null ? 'mount' : 'update';
<add> if (enableProfilerNestedUpdatePhase) {
<add> if (isCurrentUpdateNested()) {
<add> phase = 'nested-update';
<add> }
<add> }
<add>
<add> if (typeof onRender === 'function') {
<add> onRender(
<add> finishedWork.memoizedProps.id,
<add> phase,
<add> finishedWork.actualDuration,
<add> finishedWork.treeBaseDuration,
<add> finishedWork.actualStartTime,
<add> commitTime,
<add> );
<add> }
<add>
<add> if (enableProfilerCommitHooks) {
<add> if (typeof onCommit === 'function') {
<add> onCommit(
<add> finishedWork.memoizedProps.id,
<add> phase,
<add> effectDuration,
<add> commitTime,
<add> );
<add> }
<add>
<add> // Schedule a passive effect for this Profiler to call onPostCommit hooks.
<add> // This effect should be scheduled even if there is no onPostCommit callback for this Profiler,
<add> // because the effect is also where times bubble to parent Profilers.
<add> enqueuePendingPassiveProfilerEffect(finishedWork);
<add>
<add> // Propagate layout effect durations to the next nearest Profiler ancestor.
<add> // Do not reset these values until the next render so DevTools has a chance to read them first.
<add> let parentFiber = finishedWork.return;
<add> outer: while (parentFiber !== null) {
<add> switch (parentFiber.tag) {
<add> case HostRoot:
<add> const root = parentFiber.stateNode;
<add> root.effectDuration += effectDuration;
<add> break outer;
<add> case Profiler:
<add> const parentStateNode = parentFiber.stateNode;
<add> parentStateNode.effectDuration += effectDuration;
<add> break outer;
<add> }
<add> parentFiber = parentFiber.return;
<add> }
<add> }
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<add> }
<add> }
<add>}
<add>
<ide> function commitLayoutEffectOnFiber(
<ide> finishedRoot: FiberRoot,
<ide> current: Fiber | null,
<ide> function commitLayoutEffectOnFiber(
<ide> );
<ide> if (flags & Update) {
<ide> if (!offscreenSubtreeWasHidden) {
<del> // At this point layout effects have already been destroyed (during mutation phase).
<del> // This is done to prevent sibling component effects from interfering with each other,
<del> // e.g. a destroy function in one component should never override a ref set
<del> // by a create function in another component during the same commit.
<del> if (
<del> enableProfilerTimer &&
<del> enableProfilerCommitHooks &&
<del> finishedWork.mode & ProfileMode
<del> ) {
<del> try {
<del> startLayoutEffectTimer();
<del> commitHookEffectListMount(
<del> HookLayout | HookHasEffect,
<del> finishedWork,
<del> );
<del> } catch (error) {
<del> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<del> }
<del> recordLayoutEffectDuration(finishedWork);
<del> } else {
<del> try {
<del> commitHookEffectListMount(
<del> HookLayout | HookHasEffect,
<del> finishedWork,
<del> );
<del> } catch (error) {
<del> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<del> }
<del> }
<add> commitHookLayoutEffects(finishedWork);
<ide> }
<ide> }
<ide> break;
<ide> function commitLayoutEffectOnFiber(
<ide> );
<ide> if (flags & Update) {
<ide> if (!offscreenSubtreeWasHidden) {
<del> const instance = finishedWork.stateNode;
<del> if (current === null) {
<del> // We could update instance props and state here,
<del> // but instead we rely on them being set during last render.
<del> // TODO: revisit this when we implement resuming.
<del> if (__DEV__) {
<del> if (
<del> finishedWork.type === finishedWork.elementType &&
<del> !didWarnAboutReassigningProps
<del> ) {
<del> if (instance.props !== finishedWork.memoizedProps) {
<del> console.error(
<del> 'Expected %s props to match memoized props before ' +
<del> 'componentDidMount. ' +
<del> 'This might either be because of a bug in React, or because ' +
<del> 'a component reassigns its own `this.props`. ' +
<del> 'Please file an issue.',
<del> getComponentNameFromFiber(finishedWork) || 'instance',
<del> );
<del> }
<del> if (instance.state !== finishedWork.memoizedState) {
<del> console.error(
<del> 'Expected %s state to match memoized state before ' +
<del> 'componentDidMount. ' +
<del> 'This might either be because of a bug in React, or because ' +
<del> 'a component reassigns its own `this.state`. ' +
<del> 'Please file an issue.',
<del> getComponentNameFromFiber(finishedWork) || 'instance',
<del> );
<del> }
<del> }
<del> }
<del> if (
<del> enableProfilerTimer &&
<del> enableProfilerCommitHooks &&
<del> finishedWork.mode & ProfileMode
<del> ) {
<del> try {
<del> startLayoutEffectTimer();
<del> instance.componentDidMount();
<del> } catch (error) {
<del> captureCommitPhaseError(
<del> finishedWork,
<del> finishedWork.return,
<del> error,
<del> );
<del> }
<del> recordLayoutEffectDuration(finishedWork);
<del> } else {
<del> try {
<del> instance.componentDidMount();
<del> } catch (error) {
<del> captureCommitPhaseError(
<del> finishedWork,
<del> finishedWork.return,
<del> error,
<del> );
<del> }
<del> }
<del> } else {
<del> const prevProps =
<del> finishedWork.elementType === finishedWork.type
<del> ? current.memoizedProps
<del> : resolveDefaultProps(finishedWork.type, current.memoizedProps);
<del> const prevState = current.memoizedState;
<del> // We could update instance props and state here,
<del> // but instead we rely on them being set during last render.
<del> // TODO: revisit this when we implement resuming.
<del> if (__DEV__) {
<del> if (
<del> finishedWork.type === finishedWork.elementType &&
<del> !didWarnAboutReassigningProps
<del> ) {
<del> if (instance.props !== finishedWork.memoizedProps) {
<del> console.error(
<del> 'Expected %s props to match memoized props before ' +
<del> 'componentDidUpdate. ' +
<del> 'This might either be because of a bug in React, or because ' +
<del> 'a component reassigns its own `this.props`. ' +
<del> 'Please file an issue.',
<del> getComponentNameFromFiber(finishedWork) || 'instance',
<del> );
<del> }
<del> if (instance.state !== finishedWork.memoizedState) {
<del> console.error(
<del> 'Expected %s state to match memoized state before ' +
<del> 'componentDidUpdate. ' +
<del> 'This might either be because of a bug in React, or because ' +
<del> 'a component reassigns its own `this.state`. ' +
<del> 'Please file an issue.',
<del> getComponentNameFromFiber(finishedWork) || 'instance',
<del> );
<del> }
<del> }
<del> }
<del> if (
<del> enableProfilerTimer &&
<del> enableProfilerCommitHooks &&
<del> finishedWork.mode & ProfileMode
<del> ) {
<del> try {
<del> startLayoutEffectTimer();
<del> instance.componentDidUpdate(
<del> prevProps,
<del> prevState,
<del> instance.__reactInternalSnapshotBeforeUpdate,
<del> );
<del> } catch (error) {
<del> captureCommitPhaseError(
<del> finishedWork,
<del> finishedWork.return,
<del> error,
<del> );
<del> }
<del> recordLayoutEffectDuration(finishedWork);
<del> } else {
<del> try {
<del> instance.componentDidUpdate(
<del> prevProps,
<del> prevState,
<del> instance.__reactInternalSnapshotBeforeUpdate,
<del> );
<del> } catch (error) {
<del> captureCommitPhaseError(
<del> finishedWork,
<del> finishedWork.return,
<del> error,
<del> );
<del> }
<del> }
<del> }
<add> commitClassLayoutLifecycles(finishedWork, current);
<ide> }
<ide> }
<ide>
<ide> if (flags & Callback) {
<del> // TODO: I think this is now always non-null by the time it reaches the
<del> // commit phase. Consider removing the type check.
<del> const updateQueue: UpdateQueue<
<del> *,
<del> > | null = (finishedWork.updateQueue: any);
<del> if (updateQueue !== null) {
<del> const instance = finishedWork.stateNode;
<del> if (__DEV__) {
<del> if (
<del> finishedWork.type === finishedWork.elementType &&
<del> !didWarnAboutReassigningProps
<del> ) {
<del> if (instance.props !== finishedWork.memoizedProps) {
<del> console.error(
<del> 'Expected %s props to match memoized props before ' +
<del> 'processing the update queue. ' +
<del> 'This might either be because of a bug in React, or because ' +
<del> 'a component reassigns its own `this.props`. ' +
<del> 'Please file an issue.',
<del> getComponentNameFromFiber(finishedWork) || 'instance',
<del> );
<del> }
<del> if (instance.state !== finishedWork.memoizedState) {
<del> console.error(
<del> 'Expected %s state to match memoized state before ' +
<del> 'processing the update queue. ' +
<del> 'This might either be because of a bug in React, or because ' +
<del> 'a component reassigns its own `this.state`. ' +
<del> 'Please file an issue.',
<del> getComponentNameFromFiber(finishedWork) || 'instance',
<del> );
<del> }
<del> }
<del> }
<del> // We could update instance props and state here,
<del> // but instead we rely on them being set during last render.
<del> // TODO: revisit this when we implement resuming.
<del> try {
<del> commitCallbacks(updateQueue, instance);
<del> } catch (error) {
<del> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<del> }
<del> }
<add> commitClassCallbacks(finishedWork, current);
<ide> }
<ide>
<ide> if (flags & Ref) {
<ide> if (!offscreenSubtreeWasHidden) {
<del> try {
<del> commitAttachRef(finishedWork);
<del> } catch (error) {
<del> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<del> }
<add> safelyAttachRef(finishedWork, finishedWork.return);
<ide> }
<ide> }
<ide> break;
<ide> function commitLayoutEffectOnFiber(
<ide> finishedWork,
<ide> committedLanes,
<ide> );
<del> if (flags & Update) {
<del> const instance: Instance = finishedWork.stateNode;
<del>
<del> // Renderers may schedule work to be done after host components are mounted
<del> // (eg DOM renderer may schedule auto-focus for inputs and form controls).
<del> // These effects should only be committed when components are first mounted,
<del> // aka when there is no current/alternate.
<del> if (current === null && finishedWork.flags & Update) {
<del> const type = finishedWork.type;
<del> const props = finishedWork.memoizedProps;
<del> try {
<del> commitMount(instance, type, props, finishedWork);
<del> } catch (error) {
<del> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<del> }
<del> }
<add>
<add> // Renderers may schedule work to be done after host components are mounted
<add> // (eg DOM renderer may schedule auto-focus for inputs and form controls).
<add> // These effects should only be committed when components are first mounted,
<add> // aka when there is no current/alternate.
<add> if (current === null && flags & Update) {
<add> commitHostComponentMount(finishedWork, current);
<ide> }
<ide>
<ide> if (flags & Ref) {
<ide> if (!offscreenSubtreeWasHidden) {
<del> try {
<del> commitAttachRef(finishedWork);
<del> } catch (error) {
<del> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<del> }
<add> safelyAttachRef(finishedWork, finishedWork.return);
<ide> }
<ide> }
<ide> break;
<ide> function commitLayoutEffectOnFiber(
<ide> finishedWork,
<ide> committedLanes,
<ide> );
<del> if (enableProfilerTimer) {
<del> if (flags & Update) {
<del> try {
<del> const {onCommit, onRender} = finishedWork.memoizedProps;
<del> const {effectDuration} = finishedWork.stateNode;
<del>
<del> const commitTime = getCommitTime();
<del>
<del> let phase = current === null ? 'mount' : 'update';
<del> if (enableProfilerNestedUpdatePhase) {
<del> if (isCurrentUpdateNested()) {
<del> phase = 'nested-update';
<del> }
<del> }
<del>
<del> if (typeof onRender === 'function') {
<del> onRender(
<del> finishedWork.memoizedProps.id,
<del> phase,
<del> finishedWork.actualDuration,
<del> finishedWork.treeBaseDuration,
<del> finishedWork.actualStartTime,
<del> commitTime,
<del> );
<del> }
<del>
<del> if (enableProfilerCommitHooks) {
<del> if (typeof onCommit === 'function') {
<del> onCommit(
<del> finishedWork.memoizedProps.id,
<del> phase,
<del> effectDuration,
<del> commitTime,
<del> );
<del> }
<del>
<del> // Schedule a passive effect for this Profiler to call onPostCommit hooks.
<del> // This effect should be scheduled even if there is no onPostCommit callback for this Profiler,
<del> // because the effect is also where times bubble to parent Profilers.
<del> enqueuePendingPassiveProfilerEffect(finishedWork);
<del>
<del> // Propagate layout effect durations to the next nearest Profiler ancestor.
<del> // Do not reset these values until the next render so DevTools has a chance to read them first.
<del> let parentFiber = finishedWork.return;
<del> outer: while (parentFiber !== null) {
<del> switch (parentFiber.tag) {
<del> case HostRoot:
<del> const root = parentFiber.stateNode;
<del> root.effectDuration += effectDuration;
<del> break outer;
<del> case Profiler:
<del> const parentStateNode = parentFiber.stateNode;
<del> parentStateNode.effectDuration += effectDuration;
<del> break outer;
<del> }
<del> parentFiber = parentFiber.return;
<del> }
<del> }
<del> } catch (error) {
<del> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<del> }
<del> }
<add> // TODO: Should this fire inside an offscreen tree? Or should it wait to
<add> // fire when the tree becomes visible again.
<add> if (flags & Update) {
<add> commitProfilerUpdate(finishedWork, current);
<ide> }
<ide> break;
<ide> }
<ide> function commitLayoutEffectOnFiber(
<ide> committedLanes,
<ide> );
<ide> if (flags & Update) {
<del> try {
<del> commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
<del> } catch (error) {
<del> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<del> }
<add> commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
<ide> }
<ide> break;
<ide> }
<ide> function commitSuspenseHydrationCallbacks(
<ide> if (prevState !== null) {
<ide> const suspenseInstance = prevState.dehydrated;
<ide> if (suspenseInstance !== null) {
<del> commitHydratedSuspenseInstance(suspenseInstance);
<del> if (enableSuspenseCallback) {
<del> const hydrationCallbacks = finishedRoot.hydrationCallbacks;
<del> if (hydrationCallbacks !== null) {
<del> const onHydrated = hydrationCallbacks.onHydrated;
<del> if (onHydrated) {
<del> onHydrated(suspenseInstance);
<add> try {
<add> commitHydratedSuspenseInstance(suspenseInstance);
<add> if (enableSuspenseCallback) {
<add> const hydrationCallbacks = finishedRoot.hydrationCallbacks;
<add> if (hydrationCallbacks !== null) {
<add> const onHydrated = hydrationCallbacks.onHydrated;
<add> if (onHydrated) {
<add> onHydrated(suspenseInstance);
<add> }
<ide> }
<ide> }
<add> } catch (error) {
<add> captureCommitPhaseError(finishedWork, finishedWork.return, error);
<ide> }
<ide> }
<ide> } | 2 |
Javascript | Javascript | flow type touchablebounce | 8454a36b0bc54cb1e267bc264657cc693607da71 | <ide><path>Libraries/Components/Touchable/TouchableBounce.js
<ide> const React = require('React');
<ide> const createReactClass = require('create-react-class');
<ide> const PropTypes = require('prop-types');
<ide> const Touchable = require('Touchable');
<add>const TouchableWithoutFeedback = require('TouchableWithoutFeedback');
<add>const ViewPropTypes = require('ViewPropTypes');
<add>
<add>import type {EdgeInsetsProp} from 'EdgeInsetsPropType';
<add>import type {Props as TouchableWithoutFeedbackProps} from 'TouchableWithoutFeedback';
<add>import type {ViewStyleProp} from 'StyleSheet';
<ide>
<ide> type Event = Object;
<ide>
<ide> type State = {
<ide>
<ide> const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
<ide>
<add>type Props = $ReadOnly<{|
<add> ...TouchableWithoutFeedbackProps,
<add>
<add> onPressWithCompletion?: ?Function,
<add> onPressAnimationComplete?: ?Function,
<add> pressRetentionOffset?: ?EdgeInsetsProp,
<add> releaseVelocity?: ?number,
<add> releaseBounciness?: ?number,
<add> style?: ?ViewStyleProp,
<add>|}>;
<add>
<ide> /**
<ide> * Example of using the `TouchableMixin` to play well with other responder
<ide> * locking views including `ScrollView`. `TouchableMixin` provides touchable
<ide> * hooks (`this.touchableHandle*`) that we forward events to. In turn,
<ide> * `TouchableMixin` expects us to implement some abstract methods to handle
<ide> * interesting interactions such as `handleTouchablePress`.
<ide> */
<del>const TouchableBounce = createReactClass({
<add>const TouchableBounce = ((createReactClass({
<ide> displayName: 'TouchableBounce',
<ide> mixins: [Touchable.Mixin, NativeMethodsMixin],
<ide>
<ide> propTypes: {
<del> /**
<del> * When true, indicates that the view is an accessibility element. By default,
<del> * all the touchable elements are accessible.
<del> */
<del> accessible: PropTypes.bool,
<add> ...TouchableWithoutFeedback.propTypes,
<ide>
<del> onPress: PropTypes.func,
<del> onPressIn: PropTypes.func,
<del> onPressOut: PropTypes.func,
<ide> // The function passed takes a callback to start the animation which should
<ide> // be run after this onPress handler is done. You can use this (for example)
<ide> // to update UI before starting the animation.
<ide> const TouchableBounce = createReactClass({
<ide> * is disabled. Ensure you pass in a constant to reduce memory allocations.
<ide> */
<ide> pressRetentionOffset: EdgeInsetsPropType,
<del> /**
<del> * This defines how far your touch can start away from the button. This is
<del> * added to `pressRetentionOffset` when moving off of the button.
<del> * ** NOTE **
<del> * The touch area never extends past the parent view bounds and the Z-index
<del> * of sibling views always takes precedence if a touch hits two overlapping
<del> * views.
<del> */
<del> hitSlop: EdgeInsetsPropType,
<ide> releaseVelocity: PropTypes.number.isRequired,
<ide> releaseBounciness: PropTypes.number.isRequired,
<add> /**
<add> * Style to apply to the container/underlay. Most commonly used to make sure
<add> * rounded corners match the wrapped component.
<add> */
<add> style: ViewPropTypes.style,
<ide> },
<ide>
<ide> getDefaultProps: function() {
<ide> const TouchableBounce = createReactClass({
<ide> },
<ide>
<ide> touchableGetPressRectOffset: function(): typeof PRESS_RETENTION_OFFSET {
<del> // $FlowFixMe Invalid prop usage
<ide> return this.props.pressRetentionOffset || PRESS_RETENTION_OFFSET;
<ide> },
<ide>
<ide> const TouchableBounce = createReactClass({
<ide> render: function(): React.Element<any> {
<ide> return (
<ide> <Animated.View
<del> /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
<del> * comment suppresses an error when upgrading Flow's support for React.
<del> * To see the error delete this comment and run Flow. */
<ide> style={[{transform: [{scale: this.state.scale}]}, this.props.style]}
<ide> accessible={this.props.accessible !== false}
<del> /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
<del> * comment suppresses an error when upgrading Flow's support for React.
<del> * To see the error delete this comment and run Flow. */
<ide> accessibilityLabel={this.props.accessibilityLabel}
<del> /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
<del> * comment suppresses an error when upgrading Flow's support for React.
<del> * To see the error delete this comment and run Flow. */
<ide> accessibilityComponentType={this.props.accessibilityComponentType}
<del> /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
<del> * comment suppresses an error when upgrading Flow's support for React.
<del> * To see the error delete this comment and run Flow. */
<ide> accessibilityTraits={this.props.accessibilityTraits}
<del> /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
<del> * comment suppresses an error when upgrading Flow's support for React.
<del> * To see the error delete this comment and run Flow. */
<ide> nativeID={this.props.nativeID}
<del> /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
<del> * comment suppresses an error when upgrading Flow's support for React.
<del> * To see the error delete this comment and run Flow. */
<ide> testID={this.props.testID}
<ide> hitSlop={this.props.hitSlop}
<ide> onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder}
<ide> const TouchableBounce = createReactClass({
<ide> </Animated.View>
<ide> );
<ide> },
<del>});
<add>}): any): React.ComponentType<Props>);
<ide>
<ide> module.exports = TouchableBounce; | 1 |
Javascript | Javascript | move chain alias from indexedsequence to sequence | 0afefc9aebfe5d82750528712f599c038a3e7f27 | <ide><path>src/Sequence.js
<ide> SequencePrototype.toJSON = SequencePrototype.toJS;
<ide> SequencePrototype.__toJS = SequencePrototype.toObject;
<ide> SequencePrototype.inspect =
<ide> SequencePrototype.toSource = function() { return this.toString(); };
<add>SequencePrototype.chain = SequencePrototype.flatMap;
<ide>
<ide>
<ide> class IndexedSequence extends Sequence {
<ide> var IndexedSequencePrototype = IndexedSequence.prototype;
<ide> IndexedSequencePrototype[ITERATOR_SYMBOL] = IndexedSequencePrototype.values;
<ide> IndexedSequencePrototype.__toJS = IndexedSequencePrototype.toArray;
<ide> IndexedSequencePrototype.__toStringMapper = quoteString;
<del>IndexedSequencePrototype.chain = IndexedSequencePrototype.flatMap;
<ide>
<ide>
<ide> class ValuesSequence extends IndexedSequence { | 1 |
Ruby | Ruby | fix failure in reporter_test.rb | d0060f12061bf2b8962964abd67b413c601101b5 | <ide><path>railties/lib/rails/test_unit/reporter.rb
<ide> def record(result)
<ide> end
<ide>
<ide> if output_inline? && result.failure && (!result.skipped? || options[:verbose])
<add> result.failures.each { |f| f.backtrace.clear } if result.error?
<add>
<ide> io.puts
<ide> io.puts
<ide> io.puts color_output(result, by: result) | 1 |
Ruby | Ruby | remove rescue as it was clobbering the real error | ae13cb1523b97e860e7a8eeec905528a273d843a | <ide><path>load_paths.rb
<del>begin
<del> require File.expand_path('../.bundle/environment', __FILE__)
<del>rescue LoadError
<del> begin
<del> # bust gem prelude
<del> if defined? Gem
<del> Gem.source_index
<del> gem 'bundler'
<del> else
<del> require 'rubygems'
<del> end
<del> require 'bundler'
<del> Bundler.setup
<del> rescue LoadError
<del> module Bundler
<del> def self.require(*args, &block); end
<del> def self.method_missing(*args, &block); end
<del> end
<del>
<del> %w(
<del> actionmailer
<del> actionpack
<del> activemodel
<del> activerecord
<del> activeresource
<del> activesupport
<del> railties
<del> ).each do |framework|
<del> $:.unshift File.expand_path("../#{framework}/lib", __FILE__)
<del> end
<del> end
<add># bust gem prelude
<add>if defined? Gem
<add> Gem.source_index
<add> gem 'bundler'
<add>else
<add> require 'rubygems'
<ide> end
<add>require 'bundler'
<add>Bundler.setup
<ide>\ No newline at end of file | 1 |
Java | Java | fix cancellation order in throttlefirst | d6d8869c9f4d3bf6fb7b4b2126a4ee25cc3d0b49 | <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableThrottleFirstTimed.java
<ide> public void onNext(T t) {
<ide> downstream.onNext(t);
<ide> BackpressureHelper.produced(this, 1);
<ide> } else {
<add> upstream.cancel();
<ide> done = true;
<del> cancel();
<ide> downstream.onError(MissingBackpressureException.createDefault());
<add> worker.dispose();
<ide> return;
<ide> }
<ide>
<ide> public void onNext(T t) {
<ide> onDropped.accept(t);
<ide> } catch (Throwable ex) {
<ide> Exceptions.throwIfFatal(ex);
<del> downstream.onError(ex);
<del> worker.dispose();
<ide> upstream.cancel();
<ide> done = true;
<add> downstream.onError(ex);
<add> worker.dispose();
<ide> }
<ide> }
<ide> }
<ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableThrottleFirstTimed.java
<ide>
<ide> public ObservableThrottleFirstTimed(
<ide> ObservableSource<T> source,
<del> long timeout,
<add> long timeout,
<ide> TimeUnit unit,
<ide> Scheduler scheduler,
<ide> Consumer<? super T> onDropped) {
<ide> public void onNext(T t) {
<ide> onDropped.accept(t);
<ide> } catch (Throwable ex) {
<ide> Exceptions.throwIfFatal(ex);
<add> upstream.dispose();
<ide> downstream.onError(ex);
<ide> worker.dispose();
<del> upstream.dispose();
<ide> }
<ide> }
<ide> } | 2 |
Ruby | Ruby | convert `dependency_expansion` test to spec | 7393485b7b2f15b84506d1c7f7d157db545aa18f | <ide><path>Library/Homebrew/test/dependency_expansion_spec.rb
<add>require "dependency"
<add>
<add>describe Dependency do
<add> def build_dep(name, tags = [], deps = [])
<add> dep = described_class.new(name.to_s, tags)
<add> allow(dep).to receive(:to_formula).and_return(double(deps: deps, name: name))
<add> dep
<add> end
<add>
<add> let(:foo) { build_dep(:foo) }
<add> let(:bar) { build_dep(:bar) }
<add> let(:baz) { build_dep(:baz) }
<add> let(:qux) { build_dep(:qux) }
<add> let(:deps) { [foo, bar, baz, qux] }
<add> let(:formula) { double(deps: deps, name: "f") }
<add>
<add> describe "::expand" do
<add> it "yields dependent and dependency pairs" do
<add> i = 0
<add> described_class.expand(formula) do |dependent, dep|
<add> expect(dependent).to eq(formula)
<add> expect(deps[i]).to eq(dep)
<add> i += 1
<add> end
<add> end
<add>
<add> it "returns the dependencies" do
<add> expect(described_class.expand(formula)).to eq(deps)
<add> end
<add>
<add> it "prunes all when given a block with ::prune" do
<add> expect(described_class.expand(formula) { described_class.prune }).to be_empty
<add> end
<add>
<add> it "can prune selectively" do
<add> deps = described_class.expand(formula) do |_, dep|
<add> described_class.prune if dep.name == "foo"
<add> end
<add>
<add> expect(deps).to eq([bar, baz, qux])
<add> end
<add>
<add> it "preserves dependency order" do
<add> allow(foo).to receive(:to_formula).and_return(double(name: "f", deps: [qux, baz]))
<add> expect(described_class.expand(formula)).to eq([qux, baz, foo, bar])
<add> end
<add> end
<add>
<add> it "skips optionals by default" do
<add> deps = [build_dep(:foo, [:optional]), bar, baz, qux]
<add> f = double(deps: deps, build: double(with?: false), name: "f")
<add> expect(described_class.expand(f)).to eq([bar, baz, qux])
<add> end
<add>
<add> it "keeps recommended dependencies by default" do
<add> deps = [build_dep(:foo, [:recommended]), bar, baz, qux]
<add> f = double(deps: deps, build: double(with?: true), name: "f")
<add> expect(described_class.expand(f)).to eq(deps)
<add> end
<add>
<add> it "merges repeated dependencies with differing options" do
<add> foo2 = build_dep(:foo, ["option"])
<add> baz2 = build_dep(:baz, ["option"])
<add> deps << foo2 << baz2
<add> deps = [foo2, bar, baz2, qux]
<add> deps.zip(described_class.expand(formula)) do |expected, actual|
<add> expect(expected.tags).to eq(actual.tags)
<add> expect(expected).to eq(actual)
<add> end
<add> end
<add>
<add> it "merges dependencies and perserves env_proc" do
<add> env_proc = double
<add> dep = described_class.new("foo", [], env_proc)
<add> allow(dep).to receive(:to_formula).and_return(double(deps: [], name: "foo"))
<add> deps.replace([dep])
<add> expect(described_class.expand(formula).first.env_proc).to eq(env_proc)
<add> end
<add>
<add> it "merges tags without duplicating them" do
<add> foo2 = build_dep(:foo, ["option"])
<add> foo3 = build_dep(:foo, ["option"])
<add> deps << foo2 << foo3
<add>
<add> expect(described_class.expand(formula).first.tags).to eq(%w[option])
<add> end
<add>
<add> it "skips parent but yields children with ::skip" do
<add> f = double(
<add> name: "f",
<add> deps: [
<add> build_dep(:foo, [], [bar, baz]),
<add> build_dep(:foo, [], [baz]),
<add> ],
<add> )
<add>
<add> deps = described_class.expand(f) do |_dependent, dep|
<add> described_class.skip if %w[foo qux].include? dep.name
<add> end
<add>
<add> expect(deps).to eq([bar, baz])
<add> end
<add>
<add> it "keeps dependency but prunes recursive dependencies with ::keep_but_prune_recursive_deps" do
<add> foo = build_dep(:foo, [:build], bar)
<add> baz = build_dep(:baz, [:build])
<add> f = double(name: "f", deps: [foo, baz])
<add>
<add> deps = described_class.expand(f) do |_dependent, dep|
<add> described_class.keep_but_prune_recursive_deps if dep.build?
<add> end
<add>
<add> expect(deps).to eq([foo, baz])
<add> end
<add>
<add> it "returns only the dependencies given as a collection as second argument" do
<add> expect(formula.deps).to eq([foo, bar, baz, qux])
<add> expect(described_class.expand(formula, [bar, baz])).to eq([bar, baz])
<add> end
<add>
<add> it "doesn't raise an error when a dependency is cyclic" do
<add> foo = build_dep(:foo)
<add> bar = build_dep(:bar, [], [foo])
<add> allow(foo).to receive(:to_formula).and_return(double(deps: [bar], name: foo.name))
<add> f = double(name: "f", deps: [foo, bar])
<add> expect { described_class.expand(f) }.not_to raise_error
<add> end
<add>
<add> it "cleans the expand stack" do
<add> foo = build_dep(:foo)
<add> allow(foo).to receive(:to_formula).and_raise(FormulaUnavailableError, foo.name)
<add> f = double(name: "f", deps: [foo])
<add> expect { described_class.expand(f) }.to raise_error(FormulaUnavailableError)
<add> expect(described_class.instance_variable_get(:@expand_stack)).to be_empty
<add> end
<add>end
<ide><path>Library/Homebrew/test/dependency_expansion_test.rb
<del>require "testing_env"
<del>require "dependency"
<del>
<del>class DependencyExpansionTests < Homebrew::TestCase
<del> def build_dep(name, tags = [], deps = [])
<del> dep = Dependency.new(name.to_s, tags)
<del> dep.stubs(:to_formula).returns(stub(deps: deps, name: name))
<del> dep
<del> end
<del>
<del> def setup
<del> super
<del> @foo = build_dep(:foo)
<del> @bar = build_dep(:bar)
<del> @baz = build_dep(:baz)
<del> @qux = build_dep(:qux)
<del> @deps = [@foo, @bar, @baz, @qux]
<del> @f = stub(deps: @deps, name: "f")
<del> end
<del>
<del> def test_expand_yields_dependent_and_dep_pairs
<del> i = 0
<del> Dependency.expand(@f) do |dependent, dep|
<del> assert_equal @f, dependent
<del> assert_equal dep, @deps[i]
<del> i += 1
<del> end
<del> end
<del>
<del> def test_expand_no_block
<del> assert_equal @deps, Dependency.expand(@f)
<del> end
<del>
<del> def test_expand_prune_all
<del> assert_empty Dependency.expand(@f) { Dependency.prune }
<del> end
<del>
<del> def test_expand_selective_pruning
<del> deps = Dependency.expand(@f) do |_, dep|
<del> Dependency.prune if dep.name == "foo"
<del> end
<del>
<del> assert_equal [@bar, @baz, @qux], deps
<del> end
<del>
<del> def test_expand_preserves_dependency_order
<del> @foo.stubs(:to_formula).returns(stub(name: "f", deps: [@qux, @baz]))
<del> assert_equal [@qux, @baz, @foo, @bar], Dependency.expand(@f)
<del> end
<del>
<del> def test_expand_skips_optionals_by_default
<del> deps = [build_dep(:foo, [:optional]), @bar, @baz, @qux]
<del> f = stub(deps: deps, build: stub(with?: false), name: "f")
<del> assert_equal [@bar, @baz, @qux], Dependency.expand(f)
<del> end
<del>
<del> def test_expand_keeps_recommendeds_by_default
<del> deps = [build_dep(:foo, [:recommended]), @bar, @baz, @qux]
<del> f = stub(deps: deps, build: stub(with?: true), name: "f")
<del> assert_equal deps, Dependency.expand(f)
<del> end
<del>
<del> def test_merges_repeated_deps_with_differing_options
<del> @foo2 = build_dep(:foo, ["option"])
<del> @baz2 = build_dep(:baz, ["option"])
<del> @deps << @foo2 << @baz2
<del> deps = [@foo2, @bar, @baz2, @qux]
<del> deps.zip(Dependency.expand(@f)) do |expected, actual|
<del> assert_equal expected.tags, actual.tags
<del> assert_equal expected, actual
<del> end
<del> end
<del>
<del> def test_merger_preserves_env_proc
<del> env_proc = stub
<del> dep = Dependency.new("foo", [], env_proc)
<del> dep.stubs(:to_formula).returns(stub(deps: [], name: "foo"))
<del> @deps.replace [dep]
<del> assert_equal env_proc, Dependency.expand(@f).first.env_proc
<del> end
<del>
<del> def test_merged_tags_no_dupes
<del> @foo2 = build_dep(:foo, ["option"])
<del> @foo3 = build_dep(:foo, ["option"])
<del> @deps << @foo2 << @foo3
<del>
<del> assert_equal %w[option], Dependency.expand(@f).first.tags
<del> end
<del>
<del> def test_skip_skips_parent_but_yields_children
<del> f = stub(
<del> name: "f",
<del> deps: [
<del> build_dep(:foo, [], [@bar, @baz]),
<del> build_dep(:foo, [], [@baz]),
<del> ],
<del> )
<del>
<del> deps = Dependency.expand(f) do |_dependent, dep|
<del> Dependency.skip if %w[foo qux].include? dep.name
<del> end
<del>
<del> assert_equal [@bar, @baz], deps
<del> end
<del>
<del> def test_keep_dep_but_prune_recursive_deps
<del> foo = build_dep(:foo, [:build], @bar)
<del> baz = build_dep(:baz, [:build])
<del> f = stub(name: "f", deps: [foo, baz])
<del>
<del> deps = Dependency.expand(f) do |_dependent, dep|
<del> Dependency.keep_but_prune_recursive_deps if dep.build?
<del> end
<del>
<del> assert_equal [foo, baz], deps
<del> end
<del>
<del> def test_deps_with_collection_argument
<del> assert_equal [@foo, @bar, @baz, @qux], @f.deps
<del> assert_equal [@bar, @baz], Dependency.expand(@f, [@bar, @baz])
<del> end
<del>
<del> def test_cyclic_dependency
<del> foo = build_dep(:foo)
<del> bar = build_dep(:bar, [], [foo])
<del> foo.stubs(:to_formula).returns(stub(deps: [bar], name: "foo"))
<del> f = stub(name: "f", deps: [foo, bar])
<del> assert_nothing_raised { Dependency.expand(f) }
<del> end
<del>
<del> def test_clean_expand_stack
<del> foo = build_dep(:foo)
<del> foo.stubs(:to_formula).raises(FormulaUnavailableError, "foo")
<del> f = stub(name: "f", deps: [foo])
<del> assert_raises(FormulaUnavailableError) { Dependency.expand(f) }
<del> assert_empty Dependency.instance_variable_get(:@expand_stack)
<del> end
<del>end | 2 |
Python | Python | update deprecation message to be more clearer | 523f5e05fcce1ea77963be5760fbd22a330f89ab | <ide><path>official/nlp/bert/model_training_utils.py
<ide> def write_txt_summary(training_summary, summary_dir):
<ide>
<ide>
<ide> @deprecation.deprecated(
<del> None, 'This function is deprecated. Please use Keras compile/fit instead.')
<add> None, 'This function is deprecated and we do not expect adding new '
<add> 'functionalities. Please do not have your code depending '
<add> 'on this library.')
<ide> def run_customized_training_loop(
<ide> # pylint: disable=invalid-name
<ide> _sentinel=None, | 1 |
Javascript | Javascript | fix typo in regex tweak from previous commit | 0f6c7830ce5bdd31588dccdc40b6254fb4a9100f | <ide><path>src/core.js
<ide> var jQuery = function( selector, context ) {
<ide> rootjQuery,
<ide>
<ide> // A simple way to check for HTML strings
<del> quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$/,
<add> quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$/,
<ide>
<ide> // Check if a string has a non-whitespace character in it
<ide> rnotwhite = /\S/, | 1 |
Ruby | Ruby | use sidekiq.options to set initial wait | a22523abcd4281b1632c75771e87a55c141aa339 | <ide><path>activejob/test/support/integration/adapters/sidekiq.rb
<ide> def start_workers
<ide> timeout: 1,
<ide> })
<ide> Sidekiq.average_scheduled_poll_interval = 0.5
<del> Sidekiq::Scheduled.const_set :INITIAL_WAIT, 1
<add> Sidekiq.options[:poll_interval_average] = 1
<ide> begin
<ide> sidekiq.run
<ide> continue_write.puts "started" | 1 |
PHP | PHP | use null coalesce in a few more applicable places | 958512427cace7753ebd94a573bbad834b8b7508 | <ide><path>src/Http/Client.php
<ide> public function buildUrl(string $url, $query = [], array $options = []): string
<ide> */
<ide> protected function _createRequest(string $method, string $url, $data, $options): Request
<ide> {
<del> $headers = isset($options['headers']) ? (array)$options['headers'] : [];
<add> $headers = (array)($options['headers'] ?? []);
<ide> if (isset($options['type'])) {
<ide> $headers = array_merge($headers, $this->_typeHeaders($options['type']));
<ide> }
<ide><path>src/Mailer/Transport/MailTransport.php
<ide> protected function _mail(
<ide> // phpcs:disable
<ide> if (!@mail($to, $subject, $message, $headers, $params)) {
<ide> $error = error_get_last();
<del> $msg = 'Could not send email: ' . (isset($error['message']) ? $error['message'] : 'unknown');
<add> $msg = 'Could not send email: ' . ($error['message'] ?? 'unknown');
<ide> throw new SocketException($msg);
<ide> }
<ide> // phpcs:enable
<ide><path>src/View/Form/ArrayContext.php
<ide> public function primaryKey(): array
<ide> }
<ide> foreach ($this->_context['schema']['_constraints'] as $data) {
<ide> if (isset($data['type']) && $data['type'] === 'primary') {
<del> return isset($data['columns']) ? (array)$data['columns'] : [];
<add> return (array)($data['columns'] ?? []);
<ide> }
<ide> }
<ide> | 3 |
Python | Python | fix bin/init_model.py after refactoring | d310dc73efe209f50d50d08067b23dafa0dede67 | <ide><path>bin/init_model.py
<ide> def main(lang_id, lang_data_dir, corpora_dir, model_dir):
<ide>
<ide> tag_map = json.load((lang_data_dir / 'tag_map.json').open())
<ide> setup_tokenizer(lang_data_dir, model_dir / 'tokenizer')
<del> setup_vocab(get_lang_class(lang_id).default_lex_attrs(), tag_map, corpora_dir,
<add> setup_vocab(get_lang_class(lang_id).Defaults.lex_attr_getters, tag_map, corpora_dir,
<ide> model_dir / 'vocab')
<ide>
<ide> if (lang_data_dir / 'gazetteer.json').exists(): | 1 |
Python | Python | fix batch normalization as first layer | 97174dd298cf4b5be459e79b0181a124650d9148 | <ide><path>keras/layers/normalization.py
<ide> def __init__(self, input_shape, epsilon=1e-6, mode=0, momentum=0.9, weights=None
<ide> self.epsilon = epsilon
<ide> self.mode = mode
<ide> self.momentum = momentum
<del> self.input = ndim_tensor(len(self.input_shape))
<add> self.input = ndim_tensor(len(self.input_shape) + 1)
<ide>
<ide> self.gamma = self.init((self.input_shape))
<ide> self.beta = shared_zeros(self.input_shape) | 1 |
Ruby | Ruby | remove unnecessary blank line | a8ca47d294d1399393c4f066e0bebd356d500148 | <ide><path>Library/Homebrew/diagnostic.rb
<ide> def check_coretap_git_origin
<ide> branch = coretap_path.git_branch
<ide> return if branch.nil? || branch =~ /master/
<ide>
<del>
<ide> <<-EOS.undent
<ide> Homebrew/homebrew-core is not on the master branch
<ide> | 1 |
Mixed | Ruby | add params option for button_to | e6e0579defcfcf94ef1c4c1c7659f374a5335cdb | <ide><path>actionpack/CHANGELOG.md
<add>* Add `params` option to `button_to` form helper, which renders the given hash
<add> as hidden form fields.
<add>
<add> *Andy Waite*
<add>
<ide> * Development mode exceptions are rendered in text format in case of XHR request.
<ide>
<ide> *Kir Shatrov*
<ide><path>actionview/lib/action_view/helpers/url_helper.rb
<ide> def link_to(name = nil, options = nil, html_options = nil, &block)
<ide> # * <tt>:form</tt> - This hash will be form attributes
<ide> # * <tt>:form_class</tt> - This controls the class of the form within which the submit button will
<ide> # be placed
<add> # * <tt>:params</tt> - Hash of parameters to be rendered as hidden fields within the form.
<ide> #
<ide> # ==== Data attributes
<ide> #
<ide> def button_to(name = nil, options = nil, html_options = nil, &block)
<ide>
<ide> url = options.is_a?(String) ? options : url_for(options)
<ide> remote = html_options.delete('remote')
<add> params = html_options.delete('params')
<ide>
<ide> method = html_options.delete('method').to_s
<ide> method_tag = BUTTON_TAG_METHOD_VERBS.include?(method) ? method_tag(method) : ''.html_safe
<ide> def button_to(name = nil, options = nil, html_options = nil, &block)
<ide> end
<ide>
<ide> inner_tags = method_tag.safe_concat(button).safe_concat(request_token_tag)
<add> if params
<add> params.each do |name, value|
<add> inner_tags.safe_concat tag(:input, type: "hidden", name: name, value: value.to_param)
<add> end
<add> end
<ide> content_tag('form', content_tag('div', inner_tags), form_options)
<ide> end
<ide>
<ide><path>actionview/test/template/url_helper_test.rb
<ide> def test_button_to_with_block
<ide> )
<ide> end
<ide>
<add> def test_button_to_with_params
<add> assert_dom_equal(
<add> %{<form action="http://www.example.com" class="button_to" method="post"><div><input type="submit" value="Hello" /><input type="hidden" name="foo" value="bar" /><input type="hidden" name="baz" value="quux" /></div></form>},
<add> button_to("Hello", "http://www.example.com", params: {foo: :bar, baz: "quux"})
<add> )
<add> end
<add>
<ide> def test_link_tag_with_straight_url
<ide> assert_dom_equal %{<a href="http://www.example.com">Hello</a>}, link_to("Hello", "http://www.example.com")
<ide> end | 3 |
Ruby | Ruby | fix typo in deprecation warning | c9aac2a215d46d25556a6a0eaae1b9f85231a6b4 | <ide><path>activesupport/lib/active_support/message_encryptor.rb
<ide> class InvalidMessage < StandardError; end
<ide>
<ide> def initialize(secret, options = {})
<ide> unless options.is_a?(Hash)
<del> ActiveSupport::Deprecation.warn "The second parameter should be an options hash. Use :cipher => 'algorithm' to sepcify the cipher algorithm."
<add> ActiveSupport::Deprecation.warn "The second parameter should be an options hash. Use :cipher => 'algorithm' to specify the cipher algorithm."
<ide> options = { :cipher => options }
<ide> end
<ide> | 1 |
Text | Text | add extra note about canary branch in contributing | bb48a31d5474baf3cf4c8edefd8453c6406dce0c | <ide><path>contributing.md
<ide> Our Commitment to Open Source can be found [here](https://zeit.co/blog/oss)
<ide> 3. Install the dependencies: `yarn`
<ide> 4. Run `yarn dev` to build and watch for code changes
<ide> 5. In a new terminal, run `yarn types` to compile declaration files from TypeScript
<del>6. The development branch is `canary`. On a release, the relevant parts of the changes in the `canary` branch are rebased into `master`.
<add>6. The development branch is `canary` (this is the branch pull requests should be made against). On a release, the relevant parts of the changes in the `canary` branch are rebased into `master`.
<ide>
<ide> > You may need to run `yarn types` again if your types get outdated.
<ide> | 1 |
Ruby | Ruby | remove unused require | 728ef086d4079b1972090e23b0492ee88464394d | <ide><path>activesupport/lib/active_support/parameter_filter.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "active_support/core_ext/object/duplicable"
<del>require "active_support/core_ext/array/extract"
<ide>
<ide> module ActiveSupport
<ide> # +ParameterFilter+ allows you to specify keys for sensitive data from | 1 |
Python | Python | use getmask where possible | e54deb5e1996648c516f32c3be0159cb6dece5a2 | <ide><path>numpy/ma/core.py
<ide> def masked_values(x, value, rtol=1e-5, atol=1e-8, copy=True, shrink=True):
<ide> if issubclass(xnew.dtype.type, np.floating):
<ide> condition = umath.less_equal(
<ide> mabs(xnew - value), atol + rtol * mabs(value))
<del> mask = getattr(x, '_mask', nomask)
<add> mask = getmask(x)
<ide> else:
<ide> condition = umath.equal(xnew, value)
<ide> mask = nomask
<ide> def __array_finalize__(self, obj):
<ide> _mask = getattr(obj, '_mask',
<ide> make_mask_none(obj.shape, obj.dtype))
<ide> else:
<del> _mask = getattr(obj, '_mask', nomask)
<add> _mask = getmask(obj)
<ide>
<ide> # If self and obj point to exactly the same data, then probably
<ide> # self is a simple view of obj (e.g., self = obj[...]), so they
<ide> def view(self, dtype=None, type=None, fill_value=None):
<ide> # also make the mask be a view (so attr changes to the view's
<ide> # mask do no affect original object's mask)
<ide> # (especially important to avoid affecting np.masked singleton)
<del> if (getattr(output, '_mask', nomask) is not nomask):
<add> if (getmask(output) is not nomask):
<ide> output._mask = output._mask.view()
<ide>
<ide> # Make sure to reset the _fill_value if needed
<ide> def __setitem__(self, indx, value):
<ide> # Get the _data part of the new value
<ide> dval = value
<ide> # Get the _mask part of the new value
<del> mval = getattr(value, '_mask', nomask)
<add> mval = getmask(value)
<ide> if nbfields and mval is nomask:
<ide> mval = tuple([False] * nbfields)
<ide> if _mask is nomask:
<ide> def __eq__(self, other):
<ide> """
<ide> if self is masked:
<ide> return masked
<del> omask = getattr(other, '_mask', nomask)
<add> omask = getmask(other)
<ide> if omask is nomask:
<ide> check = self.filled(0).__eq__(other)
<ide> try:
<ide> def __ne__(self, other):
<ide> """
<ide> if self is masked:
<ide> return masked
<del> omask = getattr(other, '_mask', nomask)
<add> omask = getmask(other)
<ide> if omask is nomask:
<ide> check = self.filled(0).__ne__(other)
<ide> try:
<ide> def sum(self, axis=None, dtype=None, out=None, keepdims=np._NoValue):
<ide> # Explicit output
<ide> result = self.filled(0).sum(axis, dtype=dtype, out=out, **kwargs)
<ide> if isinstance(out, MaskedArray):
<del> outmask = getattr(out, '_mask', nomask)
<add> outmask = getmask(out)
<ide> if (outmask is nomask):
<ide> outmask = out._mask = make_mask_none(out.shape)
<ide> outmask.flat = newmask
<ide> def prod(self, axis=None, dtype=None, out=None, keepdims=np._NoValue):
<ide> # Explicit output
<ide> result = self.filled(1).prod(axis, dtype=dtype, out=out, **kwargs)
<ide> if isinstance(out, MaskedArray):
<del> outmask = getattr(out, '_mask', nomask)
<add> outmask = getmask(out)
<ide> if (outmask is nomask):
<ide> outmask = out._mask = make_mask_none(out.shape)
<ide> outmask.flat = newmask
<ide> def mean(self, axis=None, dtype=None, out=None, keepdims=np._NoValue):
<ide> if out is not None:
<ide> out.flat = result
<ide> if isinstance(out, MaskedArray):
<del> outmask = getattr(out, '_mask', nomask)
<add> outmask = getmask(out)
<ide> if (outmask is nomask):
<ide> outmask = out._mask = make_mask_none(out.shape)
<del> outmask.flat = getattr(result, '_mask', nomask)
<add> outmask.flat = getmask(result)
<ide> return out
<ide> return result
<ide>
<ide> def var(self, axis=None, dtype=None, out=None, ddof=0,
<ide> if dvar.ndim:
<ide> dvar._mask = mask_or(self._mask.all(axis, **kwargs), (cnt <= 0))
<ide> dvar._update_from(self)
<del> elif getattr(dvar, '_mask', False):
<add> elif getmask(dvar):
<ide> # Make sure that masked is returned when the scalar is masked.
<ide> dvar = masked
<ide> if out is not None:
<ide> def min(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue):
<ide> # Explicit output
<ide> result = self.filled(fill_value).min(axis=axis, out=out, **kwargs)
<ide> if isinstance(out, MaskedArray):
<del> outmask = getattr(out, '_mask', nomask)
<add> outmask = getmask(out)
<ide> if (outmask is nomask):
<ide> outmask = out._mask = make_mask_none(out.shape)
<ide> outmask.flat = newmask
<ide> def max(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue):
<ide> # Explicit output
<ide> result = self.filled(fill_value).max(axis=axis, out=out, **kwargs)
<ide> if isinstance(out, MaskedArray):
<del> outmask = getattr(out, '_mask', nomask)
<add> outmask = getmask(out)
<ide> if (outmask is nomask):
<ide> outmask = out._mask = make_mask_none(out.shape)
<ide> outmask.flat = newmask
<ide> def take(self, indices, axis=None, out=None, mode='raise'):
<ide> (_data, _mask) = (self._data, self._mask)
<ide> cls = type(self)
<ide> # Make sure the indices are not masked
<del> maskindices = getattr(indices, '_mask', nomask)
<add> maskindices = getmask(indices)
<ide> if maskindices is not nomask:
<ide> indices = indices.filled(0)
<ide> # Get the data, promoting scalars to 0d arrays with [...] so that | 1 |
Ruby | Ruby | add failing tests for issue | 024d3b9fcc684367b1a329c8b89c227b6470520e | <ide><path>actionpack/test/template/active_model_helper_test.rb
<ide> class ActiveModelHelperTest < ActionView::TestCase
<ide> tests ActionView::Helpers::ActiveModelHelper
<ide>
<ide> silence_warnings do
<del> class Post < Struct.new(:author_name, :body)
<add> class Post < Struct.new(:author_name, :body, :updated_at)
<ide> include ActiveModel::Conversion
<ide> include ActiveModel::Validations
<ide>
<ide> def setup
<ide> @post = Post.new
<ide> @post.errors[:author_name] << "can't be empty"
<ide> @post.errors[:body] << "foo"
<add> @post.errors[:updated_at] << "bar"
<ide>
<ide> @post.author_name = ""
<ide> @post.body = "Back to the hill and over it again!"
<add> @post.updated_at = Date.new(2004, 6, 15)
<ide> end
<ide>
<ide> def test_text_area_with_errors
<ide> def test_text_field_with_errors
<ide> )
<ide> end
<ide>
<add> def test_date_select_with_errors
<add> assert_dom_equal(
<add> %(<div class="field_with_errors"><select id="post_updated_at_1i" name="post[updated_at(1i)]">\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n</select>\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="15" />\n</div>),
<add> date_select("post", "updated_at", :discard_month => true, :discard_day => true, :start_year => 2004, :end_year => 2005)
<add> )
<add> end
<add>
<add> def test_datetime_select_with_errors
<add> assert_dom_equal(
<add> %(<div class="field_with_errors"><input id="post_updated_at_1i" name="post[updated_at(1i)]" type="hidden" value="2004" />\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="15" />\n<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n<option selected="selected" value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n</select>\n : <select id="post_updated_at_5i" name="post[updated_at(5i)]">\n<option selected="selected" value="00">00</option>\n</select>\n</div>),
<add> datetime_select("post", "updated_at", :discard_year => true, :discard_month => true, :discard_day => true, :minute_step => 60)
<add> )
<add> end
<add>
<add> def test_time_select_with_errors
<add> assert_dom_equal(
<add> %(<div class="field_with_errors"><input id="post_updated_at_1i" name="post[updated_at(1i)]" type="hidden" value="2004" />\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="15" />\n<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n<option selected="selected" value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n</select>\n : <select id="post_updated_at_5i" name="post[updated_at(5i)]">\n<option selected="selected" value="00">00</option>\n</select>\n</div>),
<add> time_select("post", "updated_at", :minute_step => 60)
<add> )
<add> end
<add>
<ide> def test_hidden_field_does_not_render_errors
<ide> assert_dom_equal(
<ide> %(<input id="post_author_name" name="post[author_name]" type="hidden" value="" />), | 1 |
Go | Go | add the testrunswaplessthanmemorylimit case | ab39a4c98110d9a16afd73ce2992ab3d4532201a | <ide><path>integration-cli/docker_cli_run_unix_test.go
<ide> func (s *DockerSuite) TestStopContainerSignal(c *check.C) {
<ide> c.Fatalf("Expected `exit trapped` in the log, got %v", out)
<ide> }
<ide> }
<add>
<add>func (s *DockerSuite) TestRunSwapLessThanMemoryLimit(c *check.C) {
<add> testRequires(c, memoryLimitSupport)
<add> testRequires(c, swapMemorySupport)
<add> out, _, err := dockerCmdWithError("run", "-m", "16m", "--memory-swap", "15m", "busybox", "echo", "test")
<add> expected := "Minimum memoryswap limit should be larger than memory limit"
<add> c.Assert(err, check.NotNil)
<add>
<add> if !strings.Contains(out, expected) {
<add> c.Fatalf("Expected output to contain %q, not %q", out, expected)
<add> }
<add>} | 1 |
Ruby | Ruby | remove a redundant default_scope tests | bad1a267f1740156729656c5fe4bfb7ba769a481 | <ide><path>activerecord/test/cases/relations_test.rb
<ide> def test_find_with_included_associations
<ide> end
<ide> end
<ide>
<del> def test_default_scope_with_conditions_string
<del> assert_equal Developer.where(name: "David").map(&:id).sort, DeveloperCalledDavid.all.map(&:id).sort
<del> assert_nil DeveloperCalledDavid.create!.name
<del> end
<del>
<del> def test_default_scope_with_conditions_hash
<del> assert_equal Developer.where(name: "Jamis").map(&:id).sort, DeveloperCalledJamis.all.map(&:id).sort
<del> assert_equal "Jamis", DeveloperCalledJamis.create!.name
<del> end
<del>
<ide> def test_default_scoping_finder_methods
<ide> developers = DeveloperCalledDavid.order("id").map(&:id).sort
<ide> assert_equal Developer.where(name: "David").map(&:id).sort, developers | 1 |
Mixed | Ruby | remove query params in diskservice | 2e15092942908ce6a240a2f10107e3b920d76abe | <ide><path>activestorage/CHANGELOG.md
<add>* Remove unused `disposition` and `content_type` query parameters for `DiskService`.
<add>
<add> *Peter Zhu*
<add>
<ide> * Use `DiskController` for both public and private files.
<ide>
<ide> `DiskController` is able to handle multiple services by adding a
<ide><path>activestorage/lib/active_storage/service/disk_service.rb
<ide> def generate_url(key, expires_in:, filename:, content_type:, disposition:)
<ide> protocol: current_uri.scheme,
<ide> host: current_uri.host,
<ide> port: current_uri.port,
<del> disposition: content_disposition,
<del> content_type: content_type,
<ide> filename: filename
<ide> )
<ide> end
<ide><path>activestorage/test/controllers/representations_controller_test.rb
<ide> class ActiveStorage::RepresentationsControllerWithVariantsTest < ActionDispatch:
<ide> signed_blob_id: @blob.signed_id,
<ide> variation_key: ActiveStorage::Variation.encode(resize: "100x100"))
<ide>
<del> assert_redirected_to(/racecar\.jpg\?.*disposition=inline/)
<add> assert_redirected_to(/racecar\.jpg/)
<add> follow_redirect!
<add> assert_match(/^inline/, response.headers["Content-Disposition"])
<ide>
<ide> image = read_image(@blob.variant(resize: "100x100"))
<ide> assert_equal 100, image.width
<ide> class ActiveStorage::RepresentationsControllerWithPreviewsTest < ActionDispatch:
<ide> variation_key: ActiveStorage::Variation.encode(resize: "100x100"))
<ide>
<ide> assert_predicate @blob.preview_image, :attached?
<del> assert_redirected_to(/report\.png\?.*disposition=inline/)
<add> assert_redirected_to(/report\.png/)
<add> follow_redirect!
<add> assert_match(/^inline/, response.headers["Content-Disposition"])
<ide>
<ide> image = read_image(@blob.preview_image.variant(resize: "100x100"))
<ide> assert_equal 77, image.width
<ide><path>activestorage/test/models/blob_test.rb
<ide> def expected_url_for(blob, disposition: :attachment, filename: nil, content_type
<ide> filename ||= blob.filename
<ide> content_type ||= blob.content_type
<ide>
<del> query = { disposition: ActionDispatch::Http::ContentDisposition.format(disposition: disposition, filename: filename.sanitized), content_type: content_type }
<del> key_params = { key: blob.key }.merge(query).merge(service_name: service_name)
<add> key_params = { key: blob.key, disposition: ActionDispatch::Http::ContentDisposition.format(disposition: disposition, filename: filename.sanitized), content_type: content_type, service_name: service_name }
<ide>
<del> "https://example.com/rails/active_storage/disk/#{ActiveStorage.verifier.generate(key_params, expires_in: 5.minutes, purpose: :blob_key)}/#{filename}?#{query.to_param}"
<add> "https://example.com/rails/active_storage/disk/#{ActiveStorage.verifier.generate(key_params, expires_in: 5.minutes, purpose: :blob_key)}/#{filename}"
<ide> end
<ide> end
<ide><path>activestorage/test/service/disk_public_service_test.rb
<ide> class ActiveStorage::Service::DiskPublicServiceTest < ActiveSupport::TestCase
<ide> test "public URL generation" do
<ide> url = @service.url(@key, disposition: :inline, filename: ActiveStorage::Filename.new("avatar.png"), content_type: "image/png")
<ide>
<del> assert_match(/^https:\/\/example.com\/rails\/active_storage\/disk\/.*\/avatar\.png\?content_type=image%2Fpng&disposition=inline.*/, url)
<add> assert_match(/^https:\/\/example.com\/rails\/active_storage\/disk\/.*\/avatar\.png/, url)
<ide> end
<ide> end
<ide><path>activestorage/test/service/disk_service_test.rb
<ide> class ActiveStorage::Service::DiskServiceTest < ActiveSupport::TestCase
<ide> original_url_options = Rails.application.routes.default_url_options.dup
<ide> Rails.application.routes.default_url_options.merge!(protocol: "http", host: "test.example.com", port: 3001)
<ide> begin
<del> assert_match(/^https:\/\/example.com\/rails\/active_storage\/disk\/.*\/avatar\.png\?content_type=image%2Fpng&disposition=inline/,
<add> assert_match(/^https:\/\/example.com\/rails\/active_storage\/disk\/.*\/avatar\.png$/,
<ide> @service.url(@key, expires_in: 5.minutes, disposition: :inline, filename: ActiveStorage::Filename.new("avatar.png"), content_type: "image/png"))
<ide> ensure
<ide> Rails.application.routes.default_url_options = original_url_options | 6 |
Go | Go | fix wrong test and add log | e73152bf273418cbee3d5862dd2ccfbdf2d6e8fc | <ide><path>integration-cli/docker_cli_diff_test.go
<ide> func (s *DockerSuite) TestDiffEnsureInitLayerFilesAreIgnored(c *check.C) {
<ide> }
<ide> }
<ide>
<del>func (s *DockerSuite) TestDiffEnsureOnlyKmsgAndPtmx(c *check.C) {
<add>func (s *DockerSuite) TestDiffEnsureDefaultDevs(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide> out, _ := dockerCmd(c, "run", "-d", "busybox", "sleep", "0")
<ide>
<ide> func (s *DockerSuite) TestDiffEnsureOnlyKmsgAndPtmx(c *check.C) {
<ide> }
<ide>
<ide> for _, line := range strings.Split(out, "\n") {
<del> c.Assert(line == "" || expected[line], checker.True)
<add> c.Assert(line == "" || expected[line], checker.True, check.Commentf(line))
<ide> }
<ide> }
<ide> | 1 |
PHP | PHP | add droptablesql to sqlite | 0878b174e258c23acbdca673dfb04ec6d5381558 | <ide><path>lib/Cake/Database/Schema/SqliteSchema.php
<ide> public function createTableSql($table, $columns, $constraints, $indexes) {
<ide> }
<ide> return $out;
<ide> }
<add>
<add>/**
<add> * Generate the SQL to drop a table.
<add> *
<add> * @param Cake\Database\Schema\Table $table Table instance
<add> * @return string DROP TABLE sql
<add> */
<add> public function dropTableSql(Table $table) {
<add> return sprintf('DROP TABLE "%s"', $table->name());
<add> }
<add>
<ide> }
<ide><path>lib/Cake/Test/TestCase/Database/Schema/SqliteSchemaTest.php
<ide> public function testCreateTableSql() {
<ide> );
<ide> }
<ide>
<add>
<add>/**
<add> * test dropTableSql
<add> *
<add> * @return void
<add> */
<add> public function testDropTableSql() {
<add> $driver = $this->_getMockedDriver();
<add> $connection = $this->getMock('Cake\Database\Connection', array(), array(), '', false);
<add> $connection->expects($this->any())->method('driver')
<add> ->will($this->returnValue($driver));
<add>
<add> $table = new Table('articles');
<add> $result = $table->dropTableSql($connection);
<add> $this->assertEquals('DROP TABLE "articles"', $result);
<add> }
<add>
<ide> /**
<ide> * Get a schema instance with a mocked driver/pdo instances
<ide> * | 2 |
Python | Python | fix flake8 errors | b359d23880771f046080b64ffe71aa52b86b1088 | <ide><path>libcloud/pricing.py
<ide> def get_gce_image_price(image_name, size_name, cores=1):
<ide> elif 'g1' in size_name:
<ide> size_type = 'g1'
<ide>
<del>
<ide> price_dict_keys = price_dict.keys()
<ide>
<ide> # search keys to find the one we want
<ide> def download_pricing_file(
<ide> with open(file_path, "w") as file_handle:
<ide> file_handle.write(body)
<ide>
<add>
<ide> # helper function to get image family for gce images
<ide> def get_gce_image_family(image_name):
<ide> image_family = None
<ide>
<ide> # Decide if the image is a premium image
<ide> if "sql" in image_name:
<del> image_family='SQL Server'
<add> image_family = 'SQL Server'
<ide> elif 'windows' in image_name:
<ide> image_family = 'Windows Server'
<ide> elif "rhel" in image_name and "sap" in image_name:
<ide><path>libcloud/test/test_pricing.py
<ide> def test_get_pricing_data_caching_cache_all(self):
<ide> self.assertTrue("foo" in libcloud.pricing.PRICING_DATA["compute"])
<ide> self.assertTrue("bar" in libcloud.pricing.PRICING_DATA["compute"])
<ide> self.assertTrue("baz" in libcloud.pricing.PRICING_DATA["compute"])
<del>
<add>
<ide> def test_get_gce_image_price_non_premium_image(self):
<ide> image_name = "debian-10-buster-v20220519"
<ide> cores = 4 | 2 |
Javascript | Javascript | remove unnecessary parameter from validateoneof | 572d55645c0bd446e7f88e0f2120e5a115257234 | <ide><path>lib/dns.js
<ide> function lookup(hostname, options, callback) {
<ide> } else if (typeof options === 'number') {
<ide> validateFunction(callback, 'callback');
<ide>
<del> validateOneOf(options, 'family', validFamilies, true);
<add> validateOneOf(options, 'family', validFamilies);
<ide> family = options;
<ide> } else if (options !== undefined && typeof options !== 'object') {
<ide> validateFunction(arguments.length === 2 ? options : callback, 'callback');
<ide> function lookup(hostname, options, callback) {
<ide> family = 6;
<ide> break;
<ide> default:
<del> validateOneOf(options.family, 'options.family', validFamilies, true);
<add> validateOneOf(options.family, 'options.family', validFamilies);
<ide> family = options.family;
<ide> break;
<ide> }
<ide><path>lib/internal/dns/promises.js
<ide> function lookup(hostname, options) {
<ide> }
<ide>
<ide> if (typeof options === 'number') {
<del> validateOneOf(options, 'family', validFamilies, true);
<add> validateOneOf(options, 'family', validFamilies);
<ide> family = options;
<ide> } else if (options !== undefined && typeof options !== 'object') {
<ide> throw new ERR_INVALID_ARG_TYPE('options', ['integer', 'object'], options);
<ide> function lookup(hostname, options) {
<ide> validateHints(hints);
<ide> }
<ide> if (options?.family != null) {
<del> validateOneOf(options.family, 'options.family', validFamilies, true);
<add> validateOneOf(options.family, 'options.family', validFamilies);
<ide> family = options.family;
<ide> }
<ide> if (options?.all != null) { | 2 |
Javascript | Javascript | fix eslint errors in layout service test | a0ce74643f3d6f7ad6f2f4a8ac4343d6526b91a8 | <ide><path>gulpfile.js
<ide> function lintTask() {
<ide> 'it',
<ide> 'jasmine',
<ide> 'moment',
<del> 'spyOn'
<add> 'spyOn',
<add> 'xit'
<ide> ]
<ide> };
<ide>
<ide><path>test/core.layoutService.tests.js
<ide> // Tests of the scale service
<ide> describe('Test the layout service', function() {
<ide> // Disable tests which need to be rewritten based on changes introduced by
<del> // the following changes: https://github.com/chartjs/Chart.js/pull/2346
<del> // using xit marks the test as pending: http://jasmine.github.io/2.0/introduction.html#section-Pending_Specs
<add> // the following changes: https://github.com/chartjs/Chart.js/pull/2346
<add> // using xit marks the test as pending: http://jasmine.github.io/2.0/introduction.html#section-Pending_Specs
<ide> xit('should fit a simple chart with 2 scales', function() {
<ide> var chart = window.acquireChart({
<ide> type: 'bar',
<ide> describe('Test the layout service', function() {
<ide> type: 'bar',
<ide> data: {
<ide> datasets: [
<del> { data: [10, 5, 0, 25, 78, -10] }
<add> {
<add> data: [10, 5, 0, 25, 78, -10]
<add> }
<ide> ],
<ide> labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
<ide> },
<ide> describe('Test the layout service', function() {
<ide> type: 'bar',
<ide> data: {
<ide> datasets: [
<del> { data: [10, 5, 0, 25, 78, -10] }
<add> {
<add> data: [10, 5, 0, 25, 78, -10]
<add> }
<ide> ],
<ide> labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
<ide> },
<ide> describe('Test the layout service', function() {
<ide> type: 'bar',
<ide> data: {
<ide> datasets: [
<del> { data: [10, 5, 0, 25, 78, -10] }
<add> {
<add> data: [10, 5, 0, 25, 78, -10]
<add> }
<ide> ],
<ide> labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
<ide> }, | 2 |
Ruby | Ruby | remove a confusing comment | 4360ecf7df7220d0a074c6eec40735f5f4390a1b | <ide><path>activerecord/test/schema/schema.rb
<ide> create_table(t, force: true) {}
<ide> end
<ide>
<del> # NOTE - the following 4 tables are used by models that have :inverse_of options on the associations
<ide> create_table :men, force: true do |t|
<ide> t.string :name
<ide> end | 1 |
PHP | PHP | fix $withcount binding problems | cab365a85a0fa3e4f7113390de4a5b31f64748e2 | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function whereKeyNot($id)
<ide> public function where($column, $operator = null, $value = null, $boolean = 'and')
<ide> {
<ide> if ($column instanceof Closure) {
<del> $query = $this->model->newQueryWithoutScopes();
<del>
<del> $column($query);
<add> $column($query = $this->model->newModelQuery());
<ide>
<ide> $this->query->addNestedWhereQuery($query->getQuery(), $boolean);
<ide> } else {
<ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function push()
<ide> */
<ide> public function save(array $options = [])
<ide> {
<del> $query = $this->newQueryWithoutScopes();
<add> $query = $this->newModelQuery();
<ide>
<ide> // If the "saving" event returns false we'll bail out of the save and return
<ide> // false, indicating that the save failed. This provides a chance for any
<ide> public function forceDelete()
<ide> */
<ide> protected function performDeleteOnModel()
<ide> {
<del> $this->setKeysForSaveQuery($this->newQueryWithoutScopes())->delete();
<add> $this->setKeysForSaveQuery($this->newModelQuery())->delete();
<ide>
<ide> $this->exists = false;
<ide> }
<ide> public function newQuery()
<ide> return $this->registerGlobalScopes($this->newQueryWithoutScopes());
<ide> }
<ide>
<add> /**
<add> * Get a new query builder that doesn't have any global scopes or eager loading.
<add> *
<add> * @return \Illuminate\Database\Eloquent\Builder|static
<add> */
<add> public function newModelQuery()
<add> {
<add> return $this->newEloquentBuilder(
<add> $this->newBaseQueryBuilder()
<add> )->setModel($this);
<add> }
<add>
<ide> /**
<ide> * Get a new query builder with no relationships loaded.
<ide> *
<ide> public function registerGlobalScopes($builder)
<ide> */
<ide> public function newQueryWithoutScopes()
<ide> {
<del> $builder = $this->newEloquentBuilder($this->newBaseQueryBuilder());
<del>
<del> // Once we have the query builders, we will set the model instances so the
<del> // builder can easily access any information it may need from the model
<del> // while it is constructing and executing various queries against it.
<del> return $builder->setModel($this)
<add> return $this->newModelQuery()
<ide> ->with($this->with)
<ide> ->withCount($this->withCount);
<ide> }
<ide><path>src/Illuminate/Database/Eloquent/SoftDeletes.php
<ide> protected function performDeleteOnModel()
<ide> if ($this->forceDeleting) {
<ide> $this->exists = false;
<ide>
<del> return $this->newQueryWithoutScopes()->where($this->getKeyName(), $this->getKey())->forceDelete();
<add> return $this->newModelQuery()->where($this->getKeyName(), $this->getKey())->forceDelete();
<ide> }
<ide>
<ide> return $this->runSoftDelete();
<ide> protected function performDeleteOnModel()
<ide> */
<ide> protected function runSoftDelete()
<ide> {
<del> $query = $this->newQueryWithoutScopes()->where($this->getKeyName(), $this->getKey());
<add> $query = $this->newModelQuery()->where($this->getKeyName(), $this->getKey());
<ide>
<ide> $time = $this->freshTimestamp();
<ide>
<ide><path>tests/Database/DatabaseEloquentBuilderTest.php
<ide> public function testNestedWhere()
<ide> $nestedRawQuery = $this->getMockQueryBuilder();
<ide> $nestedQuery->shouldReceive('getQuery')->once()->andReturn($nestedRawQuery);
<ide> $model = $this->getMockModel()->makePartial();
<del> $model->shouldReceive('newQueryWithoutScopes')->once()->andReturn($nestedQuery);
<add> $model->shouldReceive('newModelQuery')->once()->andReturn($nestedQuery);
<ide> $builder = $this->getBuilder();
<ide> $builder->getQuery()->shouldReceive('from');
<ide> $builder->setModel($model);
<ide><path>tests/Database/DatabaseEloquentModelTest.php
<ide> public function testWithMethodCallsQueryBuilderCorrectlyWithArray()
<ide>
<ide> public function testUpdateProcess()
<ide> {
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery', 'updateTimestamps'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('where')->once()->with('id', '=', 1);
<ide> $query->shouldReceive('update')->once()->with(['name' => 'taylor'])->andReturn(1);
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $model->expects($this->once())->method('updateTimestamps');
<ide> $model->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<ide> $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(true);
<ide> public function testUpdateProcess()
<ide>
<ide> public function testUpdateProcessDoesntOverrideTimestamps()
<ide> {
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('where')->once()->with('id', '=', 1);
<ide> $query->shouldReceive('update')->once()->with(['created_at' => 'foo', 'updated_at' => 'bar'])->andReturn(1);
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $model->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<ide> $events->shouldReceive('until');
<ide> $events->shouldReceive('fire');
<ide> public function testUpdateProcessDoesntOverrideTimestamps()
<ide>
<ide> public function testSaveIsCancelledIfSavingEventReturnsFalse()
<ide> {
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $model->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<ide> $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(false);
<ide> $model->exists = true;
<ide> public function testSaveIsCancelledIfSavingEventReturnsFalse()
<ide>
<ide> public function testUpdateIsCancelledIfUpdatingEventReturnsFalse()
<ide> {
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $model->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<ide> $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(true);
<ide> $events->shouldReceive('until')->once()->with('eloquent.updating: '.get_class($model), $model)->andReturn(false);
<ide> public function testUpdateIsCancelledIfUpdatingEventReturnsFalse()
<ide>
<ide> public function testEventsCanBeFiredWithCustomEventObjects()
<ide> {
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelEventObjectStub')->setMethods(['newQueryWithoutScopes'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelEventObjectStub')->setMethods(['newModelQuery'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $model->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<ide> $events->shouldReceive('until')->once()->with(m::type(EloquentModelSavingEventStub::class))->andReturn(false);
<ide> $model->exists = true;
<ide> public function testEventsCanBeFiredWithCustomEventObjects()
<ide>
<ide> public function testUpdateProcessWithoutTimestamps()
<ide> {
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelEventObjectStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'fireModelEvent'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelEventObjectStub')->setMethods(['newModelQuery', 'updateTimestamps', 'fireModelEvent'])->getMock();
<ide> $model->timestamps = false;
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('where')->once()->with('id', '=', 1);
<ide> $query->shouldReceive('update')->once()->with(['name' => 'taylor'])->andReturn(1);
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $model->expects($this->never())->method('updateTimestamps');
<ide> $model->expects($this->any())->method('fireModelEvent')->will($this->returnValue(true));
<ide>
<ide> public function testUpdateProcessWithoutTimestamps()
<ide>
<ide> public function testUpdateUsesOldPrimaryKey()
<ide> {
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery', 'updateTimestamps'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('where')->once()->with('id', '=', 1);
<ide> $query->shouldReceive('update')->once()->with(['id' => 2, 'foo' => 'bar'])->andReturn(1);
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $model->expects($this->once())->method('updateTimestamps');
<ide> $model->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<ide> $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(true);
<ide> public function testFromDateTime()
<ide>
<ide> public function testInsertProcess()
<ide> {
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery', 'updateTimestamps', 'refresh'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'taylor'], 'id')->andReturn(1);
<ide> $query->shouldReceive('getConnection')->once();
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $model->expects($this->once())->method('updateTimestamps');
<ide>
<ide> $model->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<ide> public function testInsertProcess()
<ide> $this->assertEquals(1, $model->id);
<ide> $this->assertTrue($model->exists);
<ide>
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery', 'updateTimestamps', 'refresh'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('insert')->once()->with(['name' => 'taylor']);
<ide> $query->shouldReceive('getConnection')->once();
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $model->expects($this->once())->method('updateTimestamps');
<ide> $model->setIncrementing(false);
<ide>
<ide> public function testInsertProcess()
<ide>
<ide> public function testInsertIsCancelledIfCreatingEventReturnsFalse()
<ide> {
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('getConnection')->once();
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $model->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<ide> $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(true);
<ide> $events->shouldReceive('until')->once()->with('eloquent.creating: '.get_class($model), $model)->andReturn(false);
<ide> public function testInsertIsCancelledIfCreatingEventReturnsFalse()
<ide>
<ide> public function testDeleteProperlyDeletesModel()
<ide> {
<del> $model = $this->getMockBuilder('Illuminate\Database\Eloquent\Model')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'touchOwners'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Database\Eloquent\Model')->setMethods(['newModelQuery', 'updateTimestamps', 'touchOwners'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('where')->once()->with('id', '=', 1)->andReturn($query);
<ide> $query->shouldReceive('delete')->once();
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $model->expects($this->once())->method('touchOwners');
<ide> $model->exists = true;
<ide> $model->id = 1;
<ide> public function testDeleteProperlyDeletesModel()
<ide>
<ide> public function testPushNoRelations()
<ide> {
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery', 'updateTimestamps', 'refresh'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'taylor'], 'id')->andReturn(1);
<ide> $query->shouldReceive('getConnection')->once();
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $model->expects($this->once())->method('updateTimestamps');
<ide>
<ide> $model->name = 'taylor';
<ide> public function testPushNoRelations()
<ide>
<ide> public function testPushEmptyOneRelation()
<ide> {
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery', 'updateTimestamps', 'refresh'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'taylor'], 'id')->andReturn(1);
<ide> $query->shouldReceive('getConnection')->once();
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $model->expects($this->once())->method('updateTimestamps');
<ide>
<ide> $model->name = 'taylor';
<ide> public function testPushEmptyOneRelation()
<ide>
<ide> public function testPushOneRelation()
<ide> {
<del> $related1 = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock();
<add> $related1 = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery', 'updateTimestamps', 'refresh'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'related1'], 'id')->andReturn(2);
<ide> $query->shouldReceive('getConnection')->once();
<del> $related1->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $related1->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $related1->expects($this->once())->method('updateTimestamps');
<ide> $related1->name = 'related1';
<ide> $related1->exists = false;
<ide>
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery', 'updateTimestamps', 'refresh'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'taylor'], 'id')->andReturn(1);
<ide> $query->shouldReceive('getConnection')->once();
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $model->expects($this->once())->method('updateTimestamps');
<ide>
<ide> $model->name = 'taylor';
<ide> public function testPushOneRelation()
<ide>
<ide> public function testPushEmptyManyRelation()
<ide> {
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery', 'updateTimestamps', 'refresh'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'taylor'], 'id')->andReturn(1);
<ide> $query->shouldReceive('getConnection')->once();
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $model->expects($this->once())->method('updateTimestamps');
<ide>
<ide> $model->name = 'taylor';
<ide> public function testPushEmptyManyRelation()
<ide>
<ide> public function testPushManyRelation()
<ide> {
<del> $related1 = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock();
<add> $related1 = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery', 'updateTimestamps', 'refresh'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'related1'], 'id')->andReturn(2);
<ide> $query->shouldReceive('getConnection')->once();
<del> $related1->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $related1->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $related1->expects($this->once())->method('updateTimestamps');
<ide> $related1->name = 'related1';
<ide> $related1->exists = false;
<ide>
<del> $related2 = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock();
<add> $related2 = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery', 'updateTimestamps', 'refresh'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'related2'], 'id')->andReturn(3);
<ide> $query->shouldReceive('getConnection')->once();
<del> $related2->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $related2->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $related2->expects($this->once())->method('updateTimestamps');
<ide> $related2->name = 'related2';
<ide> $related2->exists = false;
<ide>
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery', 'updateTimestamps', 'refresh'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'taylor'], 'id')->andReturn(1);
<ide> $query->shouldReceive('getConnection')->once();
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide> $model->expects($this->once())->method('updateTimestamps');
<ide>
<ide> $model->name = 'taylor';
<ide> public function testNonExistingAttributeWithInternalMethodNameDoesntCallMethod()
<ide>
<ide> public function testIntKeyTypePreserved()
<ide> {
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newModelQuery', 'updateTimestamps', 'refresh'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('insertGetId')->once()->with([], 'id')->andReturn(1);
<ide> $query->shouldReceive('getConnection')->once();
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide>
<ide> $this->assertTrue($model->save());
<ide> $this->assertEquals(1, $model->id);
<ide> }
<ide>
<ide> public function testStringKeyTypePreserved()
<ide> {
<del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentKeyTypeModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock();
<add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentKeyTypeModelStub')->setMethods(['newModelQuery', 'updateTimestamps', 'refresh'])->getMock();
<ide> $query = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $query->shouldReceive('insertGetId')->once()->with([], 'id')->andReturn('string id');
<ide> $query->shouldReceive('getConnection')->once();
<del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query));
<add> $model->expects($this->once())->method('newModelQuery')->will($this->returnValue($query));
<ide>
<ide> $this->assertTrue($model->save());
<ide> $this->assertEquals('string id', $model->id);
<ide><path>tests/Database/DatabaseSoftDeletingTraitTest.php
<ide> public function testDeleteSetsSoftDeletedColumn()
<ide> $model = m::mock('Illuminate\Tests\Database\DatabaseSoftDeletingTraitStub');
<ide> $model->shouldDeferMissing();
<ide> // $model->shouldReceive('newQuery')->andReturn($query = m::mock('stdClass'));
<del> $model->shouldReceive('newQueryWithoutScopes')->andReturn($query = m::mock('stdClass'));
<add> $model->shouldReceive('newModelQuery')->andReturn($query = m::mock('stdClass'));
<ide> $query->shouldReceive('where')->once()->with('id', 1)->andReturn($query);
<ide> $query->shouldReceive('update')->once()->with([
<ide> 'deleted_at' => 'date-time', | 6 |
PHP | PHP | add missing docblock. | 327d5d6410b1c9c392393808428da003710f45f1 | <ide><path>src/Illuminate/Mail/Transport/MailgunTransport.php
<ide> class MailgunTransport extends Transport
<ide> * @param \GuzzleHttp\ClientInterface $client
<ide> * @param string $key
<ide> * @param string $domain
<add> * @param string|null $endpoint
<ide> * @return void
<ide> */
<ide> public function __construct(ClientInterface $client, $key, $domain, $endpoint = null) | 1 |
Javascript | Javascript | make argument of dependencytemplate an object | 831e71c7977c9805936a2698433d1da9ec29ee95 | <ide><path>lib/DependencyTemplate.js
<ide> /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
<ide>
<ide> /**
<del> * @typedef {Object} TemplateContext
<add> * @typedef {Object} DependencyTemplateContext
<ide> * @property {RuntimeTemplate} runtimeTemplate the runtime template
<ide> * @property {DependencyTemplates} dependencyTemplates the dependency templates
<ide> * @property {Module} module current module
<ide> class DependencyTemplate {
<ide> * @abstract
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, templateContext) {
<ide> throw new Error("DependencyTemplate.apply must be overriden");
<ide> }
<ide>
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<del> * @param {TemplateContext} templateContext the template context
<add> * @param {DependencyTemplateContext} templateContext the template context
<ide> * @returns {InitFragment[]|null} the init fragments
<ide> */
<ide> getInitFragments(dependency, templateContext) {
<ide><path>lib/JavascriptGenerator.js
<ide> class JavascriptGenerator extends Generator {
<ide>
<ide> /**
<ide> * @param {Module} module the current module
<del> * @param {TODO} dependency the dependency to generate
<add> * @param {Dependency} dependency the dependency to generate
<ide> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<ide> * @param {InitFragment[]} initFragments mutable list of init fragments
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<ide> class JavascriptGenerator extends Generator {
<ide> source,
<ide> runtimeTemplate
<ide> ) {
<del> const template = dependencyTemplates.get(dependency.constructor);
<add> const constructor =
<add> /** @type {new (...args: any[]) => Dependency} */ (dependency.constructor);
<add> const template = dependencyTemplates.get(constructor);
<ide> if (!template) {
<ide> throw new Error(
<ide> "No template for dependency: " + dependency.constructor.name
<ide> );
<ide> }
<ide>
<del> template.apply(dependency, source, runtimeTemplate, dependencyTemplates);
<add> template.apply(dependency, source, {
<add> module,
<add> runtimeTemplate,
<add> dependencyTemplates
<add> });
<ide>
<ide> const fragments = template.getInitFragments(dependency, {
<ide> runtimeTemplate,
<ide><path>lib/dependencies/AMDDefineDependency.js
<ide> const NullDependency = require("./NullDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class AMDDefineDependency extends NullDependency {
<ide> constructor(range, arrayRange, functionRange, objectRange, namedModule) {
<ide> AMDDefineDependency.Template = class AMDDefineDependencyTemplate extends NullDep
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, templateContext) {
<ide> const dep = /** @type {AMDDefineDependency} */ (dependency);
<ide> const branch = this.branch(dep);
<ide> const defAndText = this.definitions[branch];
<ide><path>lib/dependencies/AMDRequireArrayDependency.js
<ide> const Dependency = require("../Dependency");
<ide> const DependencyTemplate = require("../DependencyTemplate");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class AMDRequireArrayDependency extends Dependency {
<ide> constructor(depsArray, range) {
<ide> AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate ext
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate }) {
<ide> const dep = /** @type {AMDRequireArrayDependency} */ (dependency);
<ide> const content = this.getContent(dep, runtimeTemplate);
<ide> source.replace(dep.range[0], dep.range[1] - 1, content);
<ide><path>lib/dependencies/AMDRequireDependency.js
<ide> const NullDependency = require("./NullDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class AMDRequireDependency extends NullDependency {
<ide> constructor(block) {
<ide> AMDRequireDependency.Template = class AMDRequireDependencyTemplate extends NullD
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate }) {
<ide> const dep = /** @type {AMDRequireDependency} */ (dependency);
<ide> const depBlock = dep.block;
<ide> const promise = runtimeTemplate.blockPromise({
<ide><path>lib/dependencies/CachedConstDependency.js
<ide> const NullDependency = require("./NullDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplate").TemplateContext} TemplateContext */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */
<ide> /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<ide> CachedConstDependency.Template = class CachedConstDependencyTemplate extends Dep
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate, dependencyTemplates }) {
<ide> const dep = /** @type {CachedConstDependency} */ (dependency);
<ide> if (typeof dep.range === "number") {
<ide> source.insert(dep.range, dep.identifier);
<ide> CachedConstDependency.Template = class CachedConstDependencyTemplate extends Dep
<ide>
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<del> * @param {TemplateContext} templateContext the template context
<add> * @param {DependencyTemplateContext} templateContext the template context
<ide> * @returns {InitFragment[]|null} the init fragments
<ide> */
<ide> getInitFragments(dependency, { runtimeTemplate, dependencyTemplates }) {
<ide><path>lib/dependencies/ConstDependency.js
<ide> const NullDependency = require("./NullDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<ide> /** @typedef {import("../util/createHash").Hash} Hash */
<ide>
<ide> class ConstDependency extends NullDependency {
<ide> ConstDependency.Template = class ConstDependencyTemplate extends NullDependency.
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, templateContext) {
<ide> const dep = /** @type {ConstDependency} */ (dependency);
<ide> if (typeof dep.range === "number") {
<ide> source.insert(dep.range, dep.expression);
<ide><path>lib/dependencies/ContextDependencyTemplateAsId.js
<ide> const ContextDependency = require("./ContextDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class ContextDependencyTemplateAsId extends ContextDependency.Template {
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate }) {
<ide> const dep = /** @type {ContextDependency} */ (dependency);
<ide> const moduleExports = runtimeTemplate.moduleExports({
<ide> module: dep.module,
<ide><path>lib/dependencies/ContextDependencyTemplateAsRequireCall.js
<ide> const ContextDependency = require("./ContextDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class ContextDependencyTemplateAsRequireCall extends ContextDependency.Template {
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate }) {
<ide> const dep = /** @type {ContextDependency} */ (dependency);
<ide> const moduleExports = runtimeTemplate.moduleExports({
<ide> module: dep.module,
<ide><path>lib/dependencies/HarmonyAcceptDependency.js
<ide> const NullDependency = require("./NullDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class HarmonyAcceptDependency extends NullDependency {
<ide> constructor(range, dependencies, hasCallback) {
<ide> HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate extends
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate }) {
<ide> const dep = /** @type {HarmonyAcceptDependency} */ (dependency);
<ide> // TODO: remove this hack
<ide> const sourceAsAny = /** @type {any} */ (source);
<ide><path>lib/dependencies/HarmonyAcceptImportDependency.js
<ide> const HarmonyImportDependency = require("./HarmonyImportDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class HarmonyAcceptImportDependency extends HarmonyImportDependency {
<ide> constructor(request, originModule, parserScope) {
<ide> HarmonyAcceptImportDependency.Template = class HarmonyAcceptImportDependencyTemp
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, templateContext) {
<ide> // no-op
<ide> }
<ide> };
<ide><path>lib/dependencies/HarmonyCompatibilityDependency.js
<ide> const NullDependency = require("./NullDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplate").TemplateContext} TemplateContext */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class HarmonyCompatibilityDependency extends NullDependency {
<ide> constructor(originModule) {
<ide> HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, templateContext) {
<ide> // no-op
<ide> }
<ide>
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<del> * @param {TemplateContext} templateContext the template context
<add> * @param {DependencyTemplateContext} templateContext the template context
<ide> * @returns {InitFragment[]|null} the init fragments
<ide> */
<ide> getInitFragments(dependency, { runtimeTemplate, dependencyTemplates }) {
<ide><path>lib/dependencies/HarmonyExportExpressionDependency.js
<ide> const NullDependency = require("./NullDependency");
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<ide>
<ide> class HarmonyExportExpressionDependency extends NullDependency {
<ide> constructor(originModule, range, rangeStatement) {
<ide> HarmonyExportExpressionDependency.Template = class HarmonyExportDependencyTempla
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, templateContext) {
<ide> const dep = /** @type {HarmonyExportExpressionDependency} */ (dependency);
<ide> const used = dep.originModule.isUsed("default");
<ide> const content = this.getContent(dep.originModule, used);
<ide><path>lib/dependencies/HarmonyExportHeaderDependency.js
<ide> const NullDependency = require("./NullDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class HarmonyExportHeaderDependency extends NullDependency {
<ide> constructor(range, rangeStatement) {
<ide> HarmonyExportHeaderDependency.Template = class HarmonyExportDependencyTemplate e
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, templateContext) {
<ide> const dep = /** @type {HarmonyExportHeaderDependency} */ (dependency);
<ide> const content = "";
<ide> const replaceUntil = dep.range
<ide><path>lib/dependencies/HarmonyExportImportedSpecifierDependency.js
<ide> const HarmonyImportDependency = require("./HarmonyImportDependency");
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
<del>/** @typedef {import("../DependencyTemplate").TemplateContext} TemplateContext */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../Module")} Module */
<ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<ide> /** @typedef {import("../WebpackError")} WebpackError */
<ide> /** @typedef {import("../util/createHash").Hash} Hash */
<ide>
<ide> module.exports = HarmonyExportImportedSpecifierDependency;
<ide> HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedSpecifierDependencyTemplate extends HarmonyImportDependency.Template {
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<del> * @param {TemplateContext} templateContext the template context
<add> * @param {DependencyTemplateContext} templateContext the template context
<ide> * @returns {InitFragment[]|null} the init fragments
<ide> */
<ide> getInitFragments(dependency, templateContext) {
<ide><path>lib/dependencies/HarmonyExportSpecifierDependency.js
<ide> const NullDependency = require("./NullDependency");
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
<del>/** @typedef {import("../DependencyTemplate").TemplateContext} TemplateContext */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<ide>
<ide> class HarmonyExportSpecifierDependency extends NullDependency {
<ide> constructor(originModule, id, name) {
<ide> HarmonyExportSpecifierDependency.Template = class HarmonyExportSpecifierDependen
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, templateContext) {
<ide> // no-op
<ide> }
<ide>
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<del> * @param {TemplateContext} templateContext the template context
<add> * @param {DependencyTemplateContext} templateContext the template context
<ide> * @returns {InitFragment[]|null} the init fragments
<ide> */
<ide> getInitFragments(dependency, { runtimeTemplate, dependencyTemplates }) {
<ide><path>lib/dependencies/HarmonyImportDependency.js
<ide> const ModuleDependency = require("./ModuleDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplate").TemplateContext} TemplateContext */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../Module")} Module */
<ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<ide> /** @typedef {import("../util/createHash").Hash} Hash */
<ide>
<ide> class HarmonyImportDependency extends ModuleDependency {
<ide> HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, templateContext) {
<ide> // no-op
<ide> }
<ide>
<ide> HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends
<ide>
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<del> * @param {TemplateContext} templateContext the template context
<add> * @param {DependencyTemplateContext} templateContext the template context
<ide> * @returns {InitFragment[]|null} the init fragments
<ide> */
<ide> getInitFragments(dependency, { runtimeTemplate, module }) {
<ide><path>lib/dependencies/HarmonyImportSideEffectDependency.js
<ide> const HarmonyImportDependency = require("./HarmonyImportDependency");
<ide>
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplate").TemplateContext} TemplateContext */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../InitFragment")} InitFragment */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<ide> /** @typedef {import("../util/createHash").Hash} Hash */
<ide> /** @typedef {import("./DependencyReference")} DependencyReference */
<ide>
<ide> class HarmonyImportSideEffectDependency extends HarmonyImportDependency {
<ide> HarmonyImportSideEffectDependency.Template = class HarmonyImportSideEffectDependencyTemplate extends HarmonyImportDependency.Template {
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<del> * @param {TemplateContext} templateContext the template context
<add> * @param {DependencyTemplateContext} templateContext the template context
<ide> * @returns {InitFragment[]|null} the init fragments
<ide> */
<ide> getInitFragments(dependency, templateContext) {
<ide><path>lib/dependencies/HarmonyImportSpecifierDependency.js
<ide> const HarmonyImportDependency = require("./HarmonyImportDependency");
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<ide> /** @typedef {import("../WebpackError")} WebpackError */
<ide> /** @typedef {import("../util/createHash").Hash} Hash */
<ide>
<ide> HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependen
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, templateContext) {
<add> super.apply(dependency, source, templateContext);
<ide> const dep = /** @type {HarmonyImportSpecifierDependency} */ (dependency);
<del> super.apply(dep, source, runtimeTemplate, dependencyTemplates);
<del> const content = this.getContent(dep, runtimeTemplate);
<add> const content = this.getContent(dep, templateContext.runtimeTemplate);
<ide> source.replace(dep.range[0], dep.range[1] - 1, content);
<ide> }
<ide>
<ide><path>lib/dependencies/ImportDependency.js
<ide> const ModuleDependency = require("./ModuleDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class ImportDependency extends ModuleDependency {
<ide> constructor(request, originModule, block) {
<ide> ImportDependency.Template = class ImportDependencyTemplate extends ModuleDepende
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate }) {
<ide> const dep = /** @type {ImportDependency} */ (dependency);
<ide> const content = runtimeTemplate.moduleNamespacePromise({
<ide> block: dep.block,
<ide><path>lib/dependencies/ImportEagerDependency.js
<ide> const ModuleDependency = require("./ModuleDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class ImportEagerDependency extends ModuleDependency {
<ide> constructor(request, originModule, range) {
<ide> ImportEagerDependency.Template = class ImportEagerDependencyTemplate extends Mod
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate }) {
<ide> const dep = /** @type {ImportEagerDependency} */ (dependency);
<ide> const content = runtimeTemplate.moduleNamespacePromise({
<ide> module: dep.module,
<ide><path>lib/dependencies/ImportWeakDependency.js
<ide> const ModuleDependency = require("./ModuleDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class ImportWeakDependency extends ModuleDependency {
<ide> constructor(request, originModule, range) {
<ide> ImportWeakDependency.Template = class ImportDependencyTemplate extends ModuleDep
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate }) {
<ide> const dep = /** @type {ImportWeakDependency} */ (dependency);
<ide> const content = runtimeTemplate.moduleNamespacePromise({
<ide> module: dep.module,
<ide><path>lib/dependencies/LocalModuleDependency.js
<ide> const NullDependency = require("./NullDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class LocalModuleDependency extends NullDependency {
<ide> constructor(localModule, range, callNew) {
<ide> LocalModuleDependency.Template = class LocalModuleDependencyTemplate extends Nul
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, templateContext) {
<ide> const dep = /** @type {LocalModuleDependency} */ (dependency);
<ide> if (!dep.range) return;
<ide> const moduleInstance = dep.callNew
<ide><path>lib/dependencies/ModuleDecoratorDependency.js
<ide> const ModuleDependency = require("./ModuleDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplate").TemplateContext} TemplateContext */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */
<ide> /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<ide> ModuleDecoratorDependency.Template = class ModuleDecoratorDependencyTemplate ext
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {}
<add> apply(dependency, source, templateContext) {}
<ide>
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<del> * @param {TemplateContext} templateContext the template context
<add> * @param {DependencyTemplateContext} templateContext the template context
<ide> * @returns {InitFragment[]|null} the init fragments
<ide> */
<ide> getInitFragments(dependency, { runtimeTemplate, dependencyTemplates }) {
<ide><path>lib/dependencies/ModuleDependencyTemplateAsId.js
<ide> const ModuleDependency = require("./ModuleDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class ModuleDependencyTemplateAsId extends ModuleDependency.Template {
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate }) {
<ide> const dep = /** @type {ModuleDependency} */ (dependency);
<ide> if (!dep.range) return;
<ide> const content = runtimeTemplate.moduleId({
<ide><path>lib/dependencies/ModuleDependencyTemplateAsRequireId.js
<ide> const ModuleDependency = require("./ModuleDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class ModuleDependencyTemplateAsRequireId extends ModuleDependency.Template {
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate }) {
<ide> const dep = /** @type {ModuleDependency} */ (dependency);
<ide> if (!dep.range) return;
<ide> const content = runtimeTemplate.moduleExports({
<ide><path>lib/dependencies/NullDependency.js
<ide> const DependencyTemplate = require("../DependencyTemplate");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<ide> /** @typedef {import("../util/createHash").Hash} Hash */
<ide>
<ide> class NullDependency extends Dependency {
<ide> NullDependency.Template = class NullDependencyTemplate extends DependencyTemplat
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {}
<add> apply(dependency, source, templateContext) {}
<ide> };
<ide>
<ide> module.exports = NullDependency;
<ide><path>lib/dependencies/ProvidedDependency.js
<ide> const ModuleDependency = require("./ModuleDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplate").TemplateContext} TemplateContext */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */
<ide> /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<ide> class ProvidedDependencyTemplate extends ModuleDependency.Template {
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, templateContext) {
<ide> const dep = /** @type {ProvidedDependency} */ (dependency);
<ide> source.replace(dep.range[0], dep.range[1] - 1, dep.identifier);
<ide> }
<ide>
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<del> * @param {TemplateContext} templateContext the template context
<add> * @param {DependencyTemplateContext} templateContext the template context
<ide> * @returns {InitFragment[]|null} the init fragments
<ide> */
<ide> getInitFragments(dependency, { runtimeTemplate, dependencyTemplates }) {
<ide><path>lib/dependencies/RequireEnsureDependency.js
<ide> const NullDependency = require("./NullDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class RequireEnsureDependency extends NullDependency {
<ide> constructor(block) {
<ide> RequireEnsureDependency.Template = class RequireEnsureDependencyTemplate extends
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate }) {
<ide> const dep = /** @type {RequireEnsureDependency} */ (dependency);
<ide> const depBlock = dep.block;
<ide> const promise = runtimeTemplate.blockPromise({
<ide><path>lib/dependencies/RequireHeaderDependency.js
<ide> const NullDependency = require("./NullDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class RequireHeaderDependency extends NullDependency {
<ide> constructor(range) {
<ide> RequireHeaderDependency.Template = class RequireHeaderDependencyTemplate extends
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, templateContext) {
<ide> const dep = /** @type {RequireHeaderDependency} */ (dependency);
<ide> source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__");
<ide> }
<ide><path>lib/dependencies/RequireIncludeDependency.js
<ide> const ModuleDependency = require("./ModuleDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class RequireIncludeDependency extends ModuleDependency {
<ide> constructor(request, range) {
<ide> RequireIncludeDependency.Template = class RequireIncludeDependencyTemplate exten
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate }) {
<ide> const dep = /** @type {RequireIncludeDependency} */ (dependency);
<ide> const comment = runtimeTemplate.outputOptions.pathinfo
<ide> ? Template.toComment(
<ide><path>lib/dependencies/RequireResolveHeaderDependency.js
<ide> const NullDependency = require("./NullDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class RequireResolveHeaderDependency extends NullDependency {
<ide> constructor(range) {
<ide> RequireResolveHeaderDependency.Template = class RequireResolveHeaderDependencyTe
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, templateContext) {
<ide> const dep = /** @type {RequireResolveHeaderDependency} */ (dependency);
<ide> source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/");
<ide> }
<ide><path>lib/dependencies/UnsupportedDependency.js
<ide> const NullDependency = require("./NullDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<del>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide>
<ide> class UnsupportedDependency extends NullDependency {
<ide> constructor(request, range) {
<ide> UnsupportedDependency.Template = class UnsupportedDependencyTemplate extends Nul
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate }) {
<ide> const dep = /** @type {UnsupportedDependency} */ (dependency);
<ide> source.replace(
<ide> dep.range[0],
<ide><path>lib/optimize/ConcatenatedModule.js
<ide> const createHash = require("../util/createHash");
<ide> /** @typedef {import("webpack-sources").Source} Source */
<ide> /** @typedef {import("../Compilation")} Compilation */
<ide> /** @typedef {import("../Dependency")} Dependency */
<del>/** @typedef {import("../DependencyTemplate").TemplateContext} TemplateContext */
<add>/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<ide> /** @typedef {import("../InitFragment")} InitFragment */
<ide> /** @typedef {import("../Module").SourceContext} SourceContext */
<ide> class HarmonyImportSpecifierDependencyConcatenatedTemplate extends DependencyTem
<ide>
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<del> * @param {TemplateContext} templateContext the template context
<add> * @param {DependencyTemplateContext} templateContext the template context
<ide> * @returns {InitFragment[]|null} the init fragments
<ide> */
<ide> getInitFragments(dependency, templateContext) {
<ide> class HarmonyImportSpecifierDependencyConcatenatedTemplate extends DependencyTem
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate, dependencyTemplates }) {
<ide> const dep = /** @type {HarmonyImportSpecifierDependency} */ (dependency);
<ide> const module = dep._module;
<ide> const info = this.modulesMap.get(module);
<ide> if (!info) {
<del> this.originalTemplate.apply(
<del> dependency,
<del> source,
<add> this.originalTemplate.apply(dependency, source, {
<ide> runtimeTemplate,
<ide> dependencyTemplates
<del> );
<add> });
<ide> return;
<ide> }
<ide> let content;
<ide> class HarmonyImportSideEffectDependencyConcatenatedTemplate extends DependencyTe
<ide>
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<del> * @param {TemplateContext} templateContext the template context
<add> * @param {DependencyTemplateContext} templateContext the template context
<ide> * @returns {InitFragment[]|null} the init fragments
<ide> */
<ide> getInitFragments(dependency, templateContext) {
<ide> class HarmonyImportSideEffectDependencyConcatenatedTemplate extends DependencyTe
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate, dependencyTemplates }) {
<ide> const dep = /** @type {HarmonyImportSideEffectDependency} */ (dependency);
<ide> const module = dep._module;
<ide> const info = this.modulesMap.get(module);
<ide> if (!info) {
<del> this.originalTemplate.apply(
<del> dependency,
<del> source,
<add> this.originalTemplate.apply(dependency, source, {
<ide> runtimeTemplate,
<ide> dependencyTemplates
<del> );
<add> });
<ide> return;
<ide> }
<ide> }
<ide> class HarmonyExportSpecifierDependencyConcatenatedTemplate extends DependencyTem
<ide>
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<del> * @param {TemplateContext} templateContext the template context
<add> * @param {DependencyTemplateContext} templateContext the template context
<ide> * @returns {InitFragment[]|null} the init fragments
<ide> */
<ide> getInitFragments(dependency, templateContext) {
<ide> class HarmonyExportSpecifierDependencyConcatenatedTemplate extends DependencyTem
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate, dependencyTemplates }) {
<ide> const dep = /** @type {HarmonyExportSpecifierDependency} */ (dependency);
<ide> if (dep.originModule === this.rootModule) {
<del> this.originalTemplate.apply(
<del> dependency,
<del> source,
<add> this.originalTemplate.apply(dependency, source, {
<ide> runtimeTemplate,
<ide> dependencyTemplates
<del> );
<add> });
<ide> }
<ide> }
<ide> }
<ide> class HarmonyExportExpressionDependencyConcatenatedTemplate extends DependencyTe
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate, dependencyTemplates }) {
<ide> const dep = /** @type {HarmonyExportExpressionDependency} */ (dependency);
<ide> let content =
<ide> "/* harmony default export */ var __WEBPACK_MODULE_DEFAULT_EXPORT__ = ";
<ide> class HarmonyExportImportedSpecifierDependencyConcatenatedTemplate extends Depen
<ide>
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<del> * @param {TemplateContext} templateContext the template context
<add> * @param {DependencyTemplateContext} templateContext the template context
<ide> * @returns {InitFragment[]|null} the init fragments
<ide> */
<ide> getInitFragments(dependency, templateContext) {
<ide> class HarmonyExportImportedSpecifierDependencyConcatenatedTemplate extends Depen
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate, dependencyTemplates }) {
<ide> const dep = /** @type {HarmonyExportImportedSpecifierDependency} */ (dependency);
<ide> if (dep.originModule === this.rootModule) {
<ide> if (this.modulesMap.get(dep._module)) {
<ide> class HarmonyExportImportedSpecifierDependencyConcatenatedTemplate extends Depen
<ide> source.insert(-1, content);
<ide> }
<ide> } else {
<del> this.originalTemplate.apply(
<del> dependency,
<del> source,
<add> this.originalTemplate.apply(dependency, source, {
<ide> runtimeTemplate,
<ide> dependencyTemplates
<del> );
<add> });
<ide> }
<ide> }
<ide> }
<ide> class HarmonyCompatibilityDependencyConcatenatedTemplate extends DependencyTempl
<ide> /**
<ide> * @param {Dependency} dependency the dependency for which the template should be applied
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> apply(dependency, source, { runtimeTemplate, dependencyTemplates }) {
<ide> // do nothing
<ide> }
<ide> } | 34 |
PHP | PHP | remove unnecessary call to getdatasource() | fdb4b11d0b796caee0603f52492bfb9bfe8cebb5 | <ide><path>lib/Cake/Model/Datasource/DboSource.php
<ide> public function read(Model $model, $queryData = array(), $recursive = null) {
<ide> $linkModel = $model->{$assoc};
<ide> $external = isset($assocData['external']);
<ide>
<del> $linkModel->getDataSource();
<ide> if ($model->useDbConfig === $linkModel->useDbConfig) {
<ide> if ($bypass) {
<ide> $assocData['fields'] = false; | 1 |
Go | Go | add sys_chroot cap to unprivileged containers | 41f7cef2bd186d321fc4489691ba53ab41eb48e5 | <ide><path>daemon/execdriver/native/template/default_template.go
<ide> func New() *libcontainer.Container {
<ide> "SETFCAP",
<ide> "SETPCAP",
<ide> "NET_BIND_SERVICE",
<add> "SYS_CHROOT",
<ide> },
<ide> Namespaces: map[string]bool{
<ide> "NEWNS": true,
<ide><path>integration-cli/docker_cli_run_test.go
<ide> func TestThatCharacterDevicesActLikeCharacterDevices(t *testing.T) {
<ide>
<ide> logDone("run - test that character devices work.")
<ide> }
<add>
<add>func TestRunUnprivilegedWithChroot(t *testing.T) {
<add> cmd := exec.Command(dockerBinary, "run", "busybox", "chroot", "/", "true")
<add>
<add> if _, err := runCommand(cmd); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> deleteAllContainers()
<add>
<add> logDone("run - unprivileged with chroot")
<add>} | 2 |
Ruby | Ruby | fix warning in tests when using render_erb helper | a985309abc8993ddc33c7a604bc41868909f457c | <ide><path>actionpack/test/abstract_unit.rb
<ide> def view
<ide> end
<ide>
<ide> def render_erb(string)
<add> @virtual_path = nil
<add>
<ide> template = ActionView::Template.new(
<ide> string.strip,
<ide> "test template", | 1 |
Text | Text | update the issue template | 3394b43cb7c64f9a87db26077931c9c5ff8dad37 | <ide><path>.github/ISSUE_TEMPLATE.md
<ide> <!-- FreeCodeCamp Issue Template -->
<ide>
<del><!-- NOTE: ISSUES ARE NOT FOR CODE HELP - Ask for Help at https://gitter.im/FreeCodeCamp/Help -->
<ide> <!-- Please provide as much detail as possible for us to fix your issue -->
<ide> <!-- Remove any heading sections you did not fill out -->
<ide>
<ide> <!-- If relevant, paste all of your challenge code in here -->
<ide> ```js
<ide>
<add>
<add>
<ide> ```
<del>
<ide> #### Screenshot
<ide> <!-- Add a screenshot of your issue -->
<ide> | 1 |
Javascript | Javascript | add rfc 232 mocha controller tests | d73ca4c96abbebc8ff060593dcf5f48eaddcd16c | <ide><path>blueprints/controller-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 controller = this.owner.lookup('controller:<%= controllerPathName %>');
<add> expect(controller).to.be.ok;
<add> });
<add>});
<ide><path>node-tests/blueprints/controller-test-test.js
<ide> describe('Blueprint: controller-test', function() {
<ide> });
<ide> });
<ide> });
<add>
<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('controller-test foo', function() {
<add> return emberGenerateDestroy(['controller-test', 'foo'], _file => {
<add> expect(_file('tests/unit/controllers/foo-test.js')).to.equal(
<add> fixture('controller-test/mocha-rfc232.js')
<add> );
<add> });
<add> });
<add>
<add> it('controller-test foo/bar', function() {
<add> return emberGenerateDestroy(['controller-test', 'foo/bar'], _file => {
<add> expect(_file('tests/unit/controllers/foo/bar-test.js')).to.equal(
<add> fixture('controller-test/mocha-rfc232-nested.js')
<add> );
<add> });
<add> });
<add> });
<ide> });
<ide>
<ide> describe('in app - module unification', function() {
<ide> describe('Blueprint: controller-test', function() {
<ide> });
<ide> });
<ide> });
<add>
<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('controller-test foo', function() {
<add> return emberGenerateDestroy(['controller-test', 'foo'], _file => {
<add> expect(_file('src/ui/routes/foo/controller-test.js')).to.equal(
<add> fixture('controller-test/mocha-rfc232.js')
<add> );
<add> });
<add> });
<add>
<add> it('controller-test foo/bar', function() {
<add> return emberGenerateDestroy(['controller-test', 'foo/bar'], _file => {
<add> expect(_file('src/ui/routes/foo/bar/controller-test.js')).to.equal(
<add> fixture('controller-test/mocha-rfc232-nested.js')
<add> );
<add> });
<add> });
<add> });
<ide> });
<ide>
<ide> describe('in addon', function() {
<ide><path>node-tests/fixtures/controller-test/mocha-rfc232-nested.js
<add>import { expect } from 'chai';
<add>import { describe, it } from 'mocha';
<add>import { setupTest } from 'ember-mocha';
<add>
<add>describe('Unit | Controller | foo/bar', function() {
<add> setupTest();
<add>
<add> // Replace this with your real tests.
<add> it('exists', function() {
<add> let controller = this.owner.lookup('controller:foo/bar');
<add> expect(controller).to.be.ok;
<add> });
<add>});
<ide><path>node-tests/fixtures/controller-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 | Controller | foo', function() {
<add> setupTest();
<add>
<add> // Replace this with your real tests.
<add> it('exists', function() {
<add> let controller = this.owner.lookup('controller:foo');
<add> expect(controller).to.be.ok;
<add> });
<add>}); | 4 |
Javascript | Javascript | check eaddrinuse after binding localport | c419adff1d2cb8a71add8dc0027607715ae731ea | <ide><path>lib/net.js
<ide> function afterWrite(status, handle, req, err) {
<ide> }
<ide>
<ide>
<add>function checkBindError(err, port, handle) {
<add> // EADDRINUSE may not be reported until we call listen() or connect().
<add> // To complicate matters, a failed bind() followed by listen() or connect()
<add> // will implicitly bind to a random port. Ergo, check that the socket is
<add> // bound to the expected port before calling listen() or connect().
<add> //
<add> // FIXME(bnoordhuis) Doesn't work for pipe handles, they don't have a
<add> // getsockname() method. Non-issue for now, the cluster module doesn't
<add> // really support pipes anyway.
<add> if (err === 0 && port > 0 && handle.getsockname) {
<add> var out = {};
<add> err = handle.getsockname(out);
<add> if (err === 0 && port !== out.port) {
<add> debug(`checkBindError, bound to ${out.port} instead of ${port}`);
<add> err = UV_EADDRINUSE;
<add> }
<add> }
<add> return err;
<add>}
<add>
<add>
<ide> function internalConnect(
<ide> self, address, port, addressType, localAddress, localPort) {
<ide> // TODO return promise from Socket.prototype.connect which
<ide> function internalConnect(
<ide> debug('binding to localAddress: %s and localPort: %d (addressType: %d)',
<ide> localAddress, localPort, addressType);
<ide>
<add> err = checkBindError(err, localPort, self._handle);
<ide> if (err) {
<ide> const ex = exceptionWithHostPort(err, 'bind', localAddress, localPort);
<ide> self.destroy(ex);
<ide> function listenInCluster(server, address, port, addressType,
<ide> cluster._getServer(server, serverQuery, listenOnMasterHandle);
<ide>
<ide> function listenOnMasterHandle(err, handle) {
<del> // EADDRINUSE may not be reported until we call listen(). To complicate
<del> // matters, a failed bind() followed by listen() will implicitly bind to
<del> // a random port. Ergo, check that the socket is bound to the expected
<del> // port before calling listen().
<del> //
<del> // FIXME(bnoordhuis) Doesn't work for pipe handles, they don't have a
<del> // getsockname() method. Non-issue for now, the cluster module doesn't
<del> // really support pipes anyway.
<del> if (err === 0 && port > 0 && handle.getsockname) {
<del> var out = {};
<del> err = handle.getsockname(out);
<del> if (err === 0 && port !== out.port)
<del> err = UV_EADDRINUSE;
<del> }
<add> err = checkBindError(err, port, handle);
<ide>
<ide> if (err) {
<ide> var ex = exceptionWithHostPort(err, 'bind', address, port);
<ide><path>test/parallel/test-net-client-bind-twice.js
<add>'use strict';
<add>
<add>// This tests that net.connect() from a used local port throws EADDRINUSE.
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const net = require('net');
<add>
<add>const server1 = net.createServer(common.mustNotCall());
<add>server1.listen(0, common.localhostIPv4, common.mustCall(() => {
<add> const server2 = net.createServer(common.mustNotCall());
<add> server2.listen(0, common.localhostIPv4, common.mustCall(() => {
<add> const client = net.connect({
<add> host: common.localhostIPv4,
<add> port: server1.address().port,
<add> localAddress: common.localhostIPv4,
<add> localPort: server2.address().port
<add> }, common.mustNotCall());
<add>
<add> client.on('error', common.mustCall((err) => {
<add> assert.strictEqual(err.code, 'EADDRINUSE');
<add> server1.close();
<add> server2.close();
<add> }));
<add> }));
<add>})); | 2 |
Javascript | Javascript | add github check on login with github | 9196d1c48ececf281e767cfbcb566571e9b4653a | <ide><path>common/models/User-Identity.js
<del>var debug = require('debug')('freecc:models:userIdent');
<add>import debugFactory from 'debug';
<ide>
<del>var defaultProfileImage =
<del> require('../utils/constantStrings.json').defaultProfileImage;
<add>const debug = debugFactory('freecc:models:userIdent');
<add>
<add>const { defaultProfileImage } = require('../utils/constantStrings.json');
<ide>
<ide> function getFirstImageFromProfile(profile) {
<ide> return profile && profile.photos && profile.photos[0] ?
<ide> profile.photos[0].value :
<ide> null;
<ide> }
<del>module.exports = function(UserIdent) {
<add>
<add>export default function(UserIdent) {
<ide> UserIdent.observe('before save', function(ctx, next) {
<ide> var userIdent = ctx.currentInstance || ctx.instance;
<ide> if (!userIdent) {
<ide> debug('no user identity instance found');
<ide> return next();
<ide> }
<ide> userIdent.user(function(err, user) {
<add> let userChanged = false;
<ide> if (err) { return next(err); }
<ide> if (!user) {
<ide> debug('no user attached to identity!');
<ide> return next();
<ide> }
<ide>
<del> var picture = getFirstImageFromProfile(userIdent.profile);
<add> const picture = getFirstImageFromProfile(userIdent.profile);
<ide>
<ide> debug('picture', picture, user.picture);
<ide> // check if picture was found
<ide> module.exports = function(UserIdent) {
<ide> (!user.picture || user.picture === defaultProfileImage)
<ide> ) {
<ide> debug('setting user picture');
<del> user.picture = userIdent.profile.photos[0].value;
<add> user.picture = picture;
<add> userChanged = true;
<add> }
<add>
<add> // if user is not github cool
<add> // and user signed in with github
<add> // then make them github cool
<add> // and set their username from their github profile.
<add> if (!user.isGithubCool && userIdent.provider === 'github-login') {
<add> debug(`
<add> user isn't github cool yet but signed in with github
<add> lets make them cool!
<add> `);
<add> user.isGithubCool = true;
<add> user.username = userIdent.profile.username.toLowerCase();
<add> userChanged = true;
<add> }
<add>
<add> if (userChanged) {
<ide> return user.save(function(err) {
<ide> if (err) { return next(err); }
<ide> next();
<ide> });
<ide> }
<del>
<del> debug('exiting after user ident');
<add> debug('exiting after user identity before save');
<ide> next();
<ide> });
<ide> });
<del>};
<add>} | 1 |
Text | Text | update features [ci skip] | 3e058dee62a09dd61f788739a7f5f6218a095d61 | <ide><path>website/docs/usage/v3-1.md
<ide> vectors.
<ide> $ python -m spacy assemble config.cfg ./output
<ide> ```
<ide>
<add>### Pretty pipeline package READMEs {#package-readme}
<add>
<add>The [`spacy package`](/api/cli#package) command now auto-generates a pretty
<add>`README.md` based on the pipeline information defined in the `meta.json`. This
<add>includes a table with a general overview, as well as the label scheme and
<add>accuracy figures, if available. For an example, see the
<add>[model releases](https://github.com/explosion/spacy-models/releases).
<add>
<ide> ### Support for streaming large or infinite corpora {#streaming-corpora}
<ide>
<ide> > #### config.cfg (excerpt) | 1 |
Ruby | Ruby | change static root to /public | ce52c6f4a74f7cb9d9e321203bb47f0f3364bfb2 | <ide><path>railties/lib/rails/application.rb
<ide> def build_asset_environment
<ide>
<ide> env = Sprockets::Environment.new(root.to_s)
<ide> env.logger = Rails.logger
<del> env.static_root = Rails.root.join("public/assets")
<add> env.static_root = Rails.root.join("public")
<ide>
<ide> self.class.default_sprockets_paths.each do |pattern|
<ide> Dir[root.join(pattern)].each do |dir| | 1 |
Python | Python | clarify the examples for argmax and argmin | 7e0d3fe31ed6a31ff08fb1fc0c9e6c0e1f6a8568 | <ide><path>numpy/core/fromnumeric.py
<ide> def argmax(a, axis=None, out=None):
<ide>
<ide> Examples
<ide> --------
<del> >>> a = np.arange(6).reshape(2,3)
<add> >>> a = np.arange(6).reshape(2,3) + 10
<ide> >>> a
<del> array([[0, 1, 2],
<del> [3, 4, 5]])
<add> array([[10, 11, 12],
<add> [13, 14, 15]])
<ide> >>> np.argmax(a)
<ide> 5
<ide> >>> np.argmax(a, axis=0)
<ide> def argmax(a, axis=None, out=None):
<ide> >>> ind
<ide> (1, 2)
<ide> >>> a[ind]
<del> 5
<add> 15
<ide>
<ide> >>> b = np.arange(6)
<ide> >>> b[1] = 5
<ide> def argmin(a, axis=None, out=None):
<ide>
<ide> Examples
<ide> --------
<del> >>> a = np.arange(6).reshape(2,3)
<add> >>> a = np.arange(6).reshape(2,3) + 10
<ide> >>> a
<del> array([[0, 1, 2],
<del> [3, 4, 5]])
<add> array([[10, 11, 12],
<add> [13, 14, 15]])
<ide> >>> np.argmin(a)
<ide> 0
<ide> >>> np.argmin(a, axis=0)
<ide> def argmin(a, axis=None, out=None):
<ide> >>> ind
<ide> (0, 0)
<ide> >>> a[ind]
<del> 0
<add> 10
<ide>
<del> >>> b = np.arange(6)
<del> >>> b[4] = 0
<add> >>> b = np.arange(6) + 10
<add> >>> b[4] = 10
<ide> >>> b
<del> array([0, 1, 2, 3, 0, 5])
<add> array([10, 11, 12, 13, 10, 15])
<ide> >>> np.argmin(b) # Only the first occurrence is returned.
<ide> 0
<ide> | 1 |
Text | Text | fix pypi package name in install instructions | 2026d5f1d93da7c16a58590a561563cfea3b9ad1 | <ide><path>README.md
<ide> For more information, check out [the documentation][docs], in particular, the tu
<ide>
<ide> Install using `pip`...
<ide>
<del> pip install rest_framework
<add> pip install djangorestframework
<ide>
<ide> ...or clone the project from github.
<ide> | 1 |
Javascript | Javascript | fix nextseo example | 2ad0b5ba4aa7e66b71b616b94893609bc58e8160 | <ide><path>examples/with-next-seo/pages/index.js
<ide> export default function Home() {
<ide> return (
<ide> <div>
<ide> <NextSeo
<del> config={{
<del> title: 'Page Meta Title',
<del> description: 'This will be the page meta description',
<del> canonical: 'https://www.canonicalurl.ie/',
<del> openGraph: {
<del> url: 'https://www.canonicalurl.ie/',
<del> title: 'Open Graph Title',
<del> description: 'Open Graph Description',
<del> images: [
<del> {
<del> url: 'https://www.example.ie/og-image-01.jpg',
<del> width: 800,
<del> height: 600,
<del> alt: 'Og Image Alt',
<del> },
<del> {
<del> url: 'https://www.example.ie/og-image-02.jpg',
<del> width: 900,
<del> height: 800,
<del> alt: 'Og Image Alt Second',
<del> },
<del> { url: 'https://www.example.ie/og-image-03.jpg' },
<del> { url: 'https://www.example.ie/og-image-04.jpg' },
<del> ],
<del> },
<add> title="Page Meta Title"
<add> description="This will be the page meta description"
<add> canonical="https://www.canonicalurl.ie/"
<add> openGraph={{
<add> url: 'https://www.canonicalurl.ie/',
<add> title: 'Open Graph Title',
<add> description: 'Open Graph Description',
<add> images: [
<add> {
<add> url: 'https://www.example.ie/og-image-01.jpg',
<add> width: 800,
<add> height: 600,
<add> alt: 'Og Image Alt',
<add> },
<add> {
<add> url: 'https://www.example.ie/og-image-02.jpg',
<add> width: 900,
<add> height: 800,
<add> alt: 'Og Image Alt Second',
<add> },
<add> { url: 'https://www.example.ie/og-image-03.jpg' },
<add> { url: 'https://www.example.ie/og-image-04.jpg' },
<add> ],
<ide> }}
<ide> />
<ide> <h1>SEO Added to Page</h1> | 1 |
PHP | PHP | remove controller inspection from routing | 8c73439ee4b7be4ed63325a56f1551022b340867 | <ide><path>src/Illuminate/Routing/ControllerInspector.php
<del><?php
<del>
<del>namespace Illuminate\Routing;
<del>
<del>use ReflectionClass;
<del>use ReflectionMethod;
<del>use Illuminate\Support\Str;
<del>
<del>/**
<del> * @deprecated since version 5.1.
<del> */
<del>class ControllerInspector
<del>{
<del> /**
<del> * An array of HTTP verbs.
<del> *
<del> * @var array
<del> */
<del> protected $verbs = [
<del> 'any', 'get', 'post', 'put', 'patch',
<del> 'delete', 'head', 'options',
<del> ];
<del>
<del> /**
<del> * Get the routable methods for a controller.
<del> *
<del> * @param string $controller
<del> * @param string $prefix
<del> * @return array
<del> */
<del> public function getRoutable($controller, $prefix)
<del> {
<del> $routable = [];
<del>
<del> $reflection = new ReflectionClass($controller);
<del>
<del> $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC);
<del>
<del> // To get the routable methods, we will simply spin through all methods on the
<del> // controller instance checking to see if it belongs to the given class and
<del> // is a publicly routable method. If so, we will add it to this listings.
<del> foreach ($methods as $method) {
<del> if ($this->isRoutable($method)) {
<del> $data = $this->getMethodData($method, $prefix);
<del>
<del> $routable[$method->name][] = $data;
<del>
<del> // If the routable method is an index method, we will create a special index
<del> // route which is simply the prefix and the verb and does not contain any
<del> // the wildcard place-holders that each "typical" routes would contain.
<del> if ($data['plain'] == $prefix.'/index') {
<del> $routable[$method->name][] = $this->getIndexData($data, $prefix);
<del> }
<del> }
<del> }
<del>
<del> return $routable;
<del> }
<del>
<del> /**
<del> * Determine if the given controller method is routable.
<del> *
<del> * @param \ReflectionMethod $method
<del> * @return bool
<del> */
<del> public function isRoutable(ReflectionMethod $method)
<del> {
<del> if ($method->class == 'Illuminate\Routing\Controller') {
<del> return false;
<del> }
<del>
<del> return Str::startsWith($method->name, $this->verbs);
<del> }
<del>
<del> /**
<del> * Get the method data for a given method.
<del> *
<del> * @param \ReflectionMethod $method
<del> * @param string $prefix
<del> * @return array
<del> */
<del> public function getMethodData(ReflectionMethod $method, $prefix)
<del> {
<del> $verb = $this->getVerb($name = $method->name);
<del>
<del> $uri = $this->addUriWildcards($plain = $this->getPlainUri($name, $prefix));
<del>
<del> return compact('verb', 'plain', 'uri');
<del> }
<del>
<del> /**
<del> * Get the routable data for an index method.
<del> *
<del> * @param array $data
<del> * @param string $prefix
<del> * @return array
<del> */
<del> protected function getIndexData($data, $prefix)
<del> {
<del> return ['verb' => $data['verb'], 'plain' => $prefix, 'uri' => $prefix];
<del> }
<del>
<del> /**
<del> * Extract the verb from a controller action.
<del> *
<del> * @param string $name
<del> * @return string
<del> */
<del> public function getVerb($name)
<del> {
<del> return head(explode('_', Str::snake($name)));
<del> }
<del>
<del> /**
<del> * Determine the URI from the given method name.
<del> *
<del> * @param string $name
<del> * @param string $prefix
<del> * @return string
<del> */
<del> public function getPlainUri($name, $prefix)
<del> {
<del> return $prefix.'/'.implode('-', array_slice(explode('_', Str::snake($name)), 1));
<del> }
<del>
<del> /**
<del> * Add wildcards to the given URI.
<del> *
<del> * @param string $uri
<del> * @return string
<del> */
<del> public function addUriWildcards($uri)
<del> {
<del> return $uri.'/{one?}/{two?}/{three?}/{four?}/{five?}';
<del> }
<del>}
<ide><path>src/Illuminate/Routing/Router.php
<ide> namespace Illuminate\Routing;
<ide>
<ide> use Closure;
<del>use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Str;
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Http\Response;
<ide> public function match($methods, $uri, $action)
<ide> return $this->addRoute(array_map('strtoupper', (array) $methods), $uri, $action);
<ide> }
<ide>
<del> /**
<del> * Register an array of controllers with wildcard routing.
<del> *
<del> * @param array $controllers
<del> * @return void
<del> *
<del> * @deprecated since version 5.1.
<del> */
<del> public function controllers(array $controllers)
<del> {
<del> foreach ($controllers as $uri => $controller) {
<del> $this->controller($uri, $controller);
<del> }
<del> }
<del>
<del> /**
<del> * Route a controller to a URI with wildcard routing.
<del> *
<del> * @param string $uri
<del> * @param string $controller
<del> * @param array $names
<del> * @return void
<del> *
<del> * @deprecated since version 5.1.
<del> */
<del> public function controller($uri, $controller, $names = [])
<del> {
<del> $prepended = $controller;
<del>
<del> // First, we will check to see if a controller prefix has been registered in
<del> // the route group. If it has, we will need to prefix it before trying to
<del> // reflect into the class instance and pull out the method for routing.
<del> if (! empty($this->groupStack)) {
<del> $prepended = $this->prependGroupUses($controller);
<del> }
<del>
<del> $routable = (new ControllerInspector)
<del> ->getRoutable($prepended, $uri);
<del>
<del> // When a controller is routed using this method, we use Reflection to parse
<del> // out all of the routable methods for the controller, then register each
<del> // route explicitly for the developers, so reverse routing is possible.
<del> foreach ($routable as $method => $routes) {
<del> foreach ($routes as $route) {
<del> $this->registerInspected($route, $controller, $method, $names);
<del> }
<del> }
<del>
<del> $this->addFallthroughRoute($controller, $uri);
<del> }
<del>
<del> /**
<del> * Register an inspected controller route.
<del> *
<del> * @param array $route
<del> * @param string $controller
<del> * @param string $method
<del> * @param array $names
<del> * @return void
<del> *
<del> * @deprecated since version 5.1.
<del> */
<del> protected function registerInspected($route, $controller, $method, &$names)
<del> {
<del> $action = ['uses' => $controller.'@'.$method];
<del>
<del> // If a given controller method has been named, we will assign the name to the
<del> // controller action array, which provides for a short-cut to method naming
<del> // so you don't have to define an individual route for these controllers.
<del> $action['as'] = Arr::get($names, $method);
<del>
<del> $this->{$route['verb']}($route['uri'], $action);
<del> }
<del>
<del> /**
<del> * Add a fallthrough route for a controller.
<del> *
<del> * @param string $controller
<del> * @param string $uri
<del> * @return void
<del> *
<del> * @deprecated since version 5.1.
<del> */
<del> protected function addFallthroughRoute($controller, $uri)
<del> {
<del> $missing = $this->any($uri.'/{_missing}', $controller.'@missingMethod');
<del>
<del> $missing->where('_missing', '(.*)');
<del> }
<del>
<ide> /**
<ide> * Register an array of resource controllers.
<ide> *
<ide><path>tests/Routing/RoutingRouteTest.php
<ide> public function testControllerRouting()
<ide> $this->assertFalse(isset($_SERVER['route.test.controller.except.middleware']));
<ide> }
<ide>
<del> public function testControllerInspection()
<del> {
<del> $router = $this->getRouter();
<del> $router->controller('home', 'RouteTestInspectedControllerStub');
<del> $this->assertEquals('hello', $router->dispatch(Request::create('home/foo', 'GET'))->getContent());
<del> }
<del>
<ide> protected function getRouter()
<ide> {
<ide> return new Router(new Illuminate\Events\Dispatcher);
<ide> public function handle($request, $next, $parameter1, $parameter2)
<ide> }
<ide> }
<ide>
<del>class RouteTestInspectedControllerStub extends Illuminate\Routing\Controller
<del>{
<del> public function getFoo()
<del> {
<del> return 'hello';
<del> }
<del>}
<del>
<ide> class RouteTestControllerExceptMiddleware
<ide> {
<ide> public function handle($request, $next) | 3 |
Ruby | Ruby | move encryption helper code to the general helper | eb81a4ea3d2f0c9746e06a5fece9a44b46e92ee8 | <ide><path>activerecord/test/cases/encryption/helper.rb
<ide> require "cases/helper"
<ide> require "benchmark/ips"
<ide>
<del>ActiveRecord::Encryption.configure \
<del> master_key: "test master key",
<del> deterministic_key: "test deterministic key",
<del> key_derivation_salt: "testing key derivation salt"
<del>
<del>ActiveRecord::Encryption::ExtendedDeterministicQueries.install_support
<del>
<ide> class ActiveRecord::Fixture
<ide> prepend ActiveRecord::Encryption::EncryptedFixtures
<ide> end
<ide><path>activerecord/test/cases/helper.rb
<ide> def in_time_zone(zone)
<ide> ActiveRecord::Base.time_zone_aware_attributes = old_tz
<ide> end
<ide> end
<add>
<add># Encryption
<add>
<add>ActiveRecord::Encryption.configure \
<add> master_key: "test master key",
<add> deterministic_key: "test deterministic key",
<add> key_derivation_salt: "testing key derivation salt"
<add>
<add>ActiveRecord::Encryption::ExtendedDeterministicQueries.install_support
<ide>\ No newline at end of file | 2 |
Text | Text | leave pull requests open for 72 hours | 2f117e1cd83fb8c34e1ff135a15d472c2dab4f89 | <ide><path>COLLABORATOR_GUIDE.md
<ide> agenda.
<ide> ### Waiting for Approvals
<ide>
<ide> Before landing pull requests, sufficient time should be left for input
<del>from other Collaborators. In general, leave at least 48 hours during the
<del>week and 72 hours over weekends to account for international time
<del>differences and work schedules. However, certain types of pull requests
<del>can be fast-tracked and may be landed after a shorter delay. For example:
<add>from other Collaborators. In general, leave at least 72 hours to account for
<add>international time differences and work schedules. However, certain types of
<add>pull requests can be fast-tracked and may be landed after a shorter delay. For
<add>example:
<ide>
<ide> * Focused changes that affect only documentation and/or the test suite:
<ide> * `code-and-learn` tasks typically fall into this category.
<ide><path>doc/onboarding.md
<ide> onboarding session.
<ide> * There is a minimum waiting time which we try to respect for non-trivial
<ide> changes so that people who may have important input in such a distributed
<ide> project are able to respond.
<del> * For non-trivial changes, leave the pull request open for at least 48 hours
<del> (72 hours on a weekend).
<add> * For non-trivial changes, leave the pull request open for at least 72 hours.
<ide> * If a pull request is abandoned, check if they'd mind if you took it over
<ide> (especially if it just has nits left).
<ide> * Approving a change
<ide> needs to be pointed out separately during the onboarding.
<ide> * Run CI on the PR. Because the PR does not affect any code, use the
<ide> `node-test-pull-request-lite-pipeline` CI task.
<ide> * After one or two approvals, land the PR (PRs of this type do not need to wait
<del> for 48/72 hours to land).
<add> for 72 hours to land).
<ide> * Be sure to add the `PR-URL: <full-pr-url>` and appropriate `Reviewed-By:`
<ide> metadata.
<ide> * [`node-core-utils`][] automates the generation of metadata and the landing | 2 |
Javascript | Javascript | improve code in test-console-instance | 8e491a4f3f68930e9f17a0b41106c476b6e346e9 | <ide><path>test/parallel/test-console-instance.js
<ide> 'use strict';
<del>require('../common');
<add>const common = require('../common');
<ide> const assert = require('assert');
<ide> const Stream = require('stream');
<ide> const Console = require('console').Console;
<del>let called = false;
<ide>
<ide> const out = new Stream();
<ide> const err = new Stream();
<ide>
<ide> // ensure the Console instance doesn't write to the
<ide> // process' "stdout" or "stderr" streams
<del>process.stdout.write = process.stderr.write = function() {
<del> throw new Error('write() should not be called!');
<del>};
<add>process.stdout.write = process.stderr.write = common.fail;
<ide>
<ide> // make sure that the "Console" function exists
<ide> assert.strictEqual('function', typeof Console);
<ide>
<ide> // make sure that the Console constructor throws
<ide> // when not given a writable stream instance
<del>assert.throws(function() {
<add>assert.throws(() => {
<ide> new Console();
<del>}, /Console expects a writable stream/);
<add>}, /^TypeError: Console expects a writable stream instance$/);
<ide>
<ide> // Console constructor should throw if stderr exists but is not writable
<del>assert.throws(function() {
<del> out.write = function() {};
<add>assert.throws(() => {
<add> out.write = () => {};
<ide> err.write = undefined;
<ide> new Console(out, err);
<del>}, /Console expects writable stream instances/);
<add>}, /^TypeError: Console expects writable stream instances$/);
<ide>
<del>out.write = err.write = function(d) {};
<add>out.write = err.write = (d) => {};
<ide>
<ide> const c = new Console(out, err);
<ide>
<del>out.write = err.write = function(d) {
<add>out.write = err.write = common.mustCall((d) => {
<ide> assert.strictEqual(d, 'test\n');
<del> called = true;
<del>};
<add>}, 2);
<ide>
<del>assert(!called);
<ide> c.log('test');
<del>assert(called);
<del>
<del>called = false;
<ide> c.error('test');
<del>assert(called);
<ide>
<del>out.write = function(d) {
<add>out.write = common.mustCall((d) => {
<ide> assert.strictEqual('{ foo: 1 }\n', d);
<del> called = true;
<del>};
<add>});
<ide>
<del>called = false;
<ide> c.dir({ foo: 1 });
<del>assert(called);
<ide>
<ide> // ensure that the console functions are bound to the console instance
<del>called = 0;
<del>out.write = function(d) {
<add>let called = 0;
<add>out.write = common.mustCall((d) => {
<ide> called++;
<del> assert.strictEqual(d, called + ' ' + (called - 1) + ' [ 1, 2, 3 ]\n');
<del>};
<add> assert.strictEqual(d, `${called} ${called - 1} [ 1, 2, 3 ]\n`);
<add>}, 3);
<add>
<ide> [1, 2, 3].forEach(c.log);
<del>assert.strictEqual(3, called);
<ide>
<ide> // Console() detects if it is called without `new` keyword
<del>assert.doesNotThrow(function() {
<add>assert.doesNotThrow(() => {
<ide> Console(out, err);
<ide> }); | 1 |
Ruby | Ruby | fix a typo in the doc of forty_two ar findermethod | cd440c9ea716ebb78eb936cda9cf9389bc1359e8 | <ide><path>activerecord/lib/active_record/relation/finder_methods.rb
<ide> def fifth!
<ide> # If no order is defined it will order by primary key.
<ide> #
<ide> # Person.forty_two # returns the forty-second object fetched by SELECT * FROM people
<del> # Person.offset(3).forty_two # returns the fifth object from OFFSET 3 (which is OFFSET 44)
<add> # Person.offset(3).forty_two # returns the forty-second object from OFFSET 3 (which is OFFSET 44)
<ide> # Person.where(["user_name = :u", { u: user_name }]).forty_two
<ide> def forty_two
<ide> find_nth(41, offset_index) | 1 |
PHP | PHP | improve docs for aclshell | eee37bb04e582842d8c7bbdabd03680b6e31fe6b | <ide><path>lib/Cake/Console/Command/AclShell.php
<ide> public function getOptionParser() {
<ide> 'help' => __d('cake_console', 'Create a new ACL node'),
<ide> 'parser' => array(
<ide> 'description' => __d('cake_console', 'Creates a new ACL object <node> under the parent'),
<add> 'epilog' => __d('cake_console', 'You can use `root` as the parent when creating nodes to create top level nodes.'),
<ide> 'arguments' => array(
<ide> 'type' => $type,
<ide> 'parent' => array( | 1 |
Java | Java | update @since version after backport | 0134c9d608ab6cdef78c791e946a1a85aaacd476 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/HandlerMapping.java
<ide> public interface HandlerMapping {
<ide> /**
<ide> * Name of the {@link HttpServletRequest} attribute that contains the mapped
<ide> * handler for the best matching pattern.
<del> * @since 5.1.3
<add> * @since 4.3.21
<ide> */
<ide> String BEST_MATCHING_HANDLER_ATTRIBUTE = HandlerMapping.class.getName() + ".bestMatchingHandler";
<ide> | 1 |
Javascript | Javascript | add missing typings | 66dd4f992afd77fbe69ed62b654f8d819b13ddc8 | <ide><path>lib/RequestShortener.js
<ide> "use strict";
<ide>
<ide> const path = require("path");
<add>
<ide> const NORMALIZE_SLASH_DIRECTION_REGEXP = /\\/g;
<ide> const PATH_CHARS_REGEXP = /[-[\]{}()*+?.,\\^$|#\s]/g;
<ide> const SEPARATOR_REGEXP = /[/\\]$/;
<ide> const FRONT_OR_BACK_BANG_REGEXP = /^!|!$/g;
<ide> const INDEX_JS_REGEXP = /\/index.js(!|\?|\(query\))/g;
<ide> const MATCH_RESOURCE_REGEXP = /!=!/;
<ide>
<add>/**
<add> * @param {string} request the request
<add> * @returns {string} the normalized request
<add> */
<ide> const normalizeBackSlashDirection = request => {
<ide> return request.replace(NORMALIZE_SLASH_DIRECTION_REGEXP, "/");
<ide> };
<ide>
<add>/**
<add> * @param {string} path the path to match
<add> * @returns {RegExp} the path matcher
<add> */
<ide> const createRegExpForPath = path => {
<ide> const regexpTypePartial = path.replace(PATH_CHARS_REGEXP, "\\$&");
<ide> return new RegExp(`(^|!)${regexpTypePartial}`, "g");
<ide> };
<ide>
<ide> class RequestShortener {
<del> constructor(directory) {
<del> directory = normalizeBackSlashDirection(directory);
<add> /**
<add> * @param {string} dir the directory
<add> */
<add> constructor(dir) {
<add> /** @type {RegExp | null} */
<add> this.currentDirectoryRegExp = null;
<add> /** @type {RegExp | null} */
<add> this.parentDirectoryRegExp = null;
<add> /** @type {RegExp | null} */
<add> this.buildinsRegExp = null;
<add> /** @type {boolean} */
<add> this.buildinsAsModule = false;
<add>
<add> let directory = normalizeBackSlashDirection(dir);
<ide> if (SEPARATOR_REGEXP.test(directory)) {
<ide> directory = directory.substr(0, directory.length - 1);
<ide> }
<ide> class RequestShortener {
<ide> const parentDirectory = endsWithSeparator
<ide> ? dirname.substr(0, dirname.length - 1)
<ide> : dirname;
<add>
<ide> if (parentDirectory && parentDirectory !== directory) {
<ide> this.parentDirectoryRegExp = createRegExpForPath(parentDirectory);
<ide> }
<ide> class RequestShortener {
<ide> this.buildinsRegExp = createRegExpForPath(buildins);
<ide> }
<ide>
<add> /** @type {Map<string, string>} */
<ide> this.cache = new Map();
<ide> }
<ide>
<add> /**
<add> * @param {string | undefined | null} request the request to shorten
<add> * @returns {string | undefined | null} the shortened request
<add> */
<ide> shorten(request) {
<del> if (!request) return request;
<add> if (!request) {
<add> return request;
<add> }
<ide> const cacheEntry = this.cache.get(request);
<ide> if (cacheEntry !== undefined) {
<ide> return cacheEntry;
<ide><path>lib/ResolverFactory.js
<ide>
<ide> "use strict";
<ide>
<del>const Factory = require("enhanced-resolve").ResolverFactory;
<add>const { ResolverFactory: Factory } = require("enhanced-resolve");
<ide> const { HookMap, SyncHook, SyncWaterfallHook } = require("tapable");
<ide>
<ide> /** @typedef {import("enhanced-resolve/lib/Resolver")} Resolver */
<ide>
<add>/**
<add> * @typedef {Object} ResolverCache
<add> * @property {WeakMap<Object, Resolver>} direct
<add> * @property {Map<string, Resolver>} stringified
<add> */
<add>
<ide> module.exports = class ResolverFactory {
<ide> constructor() {
<ide> this.hooks = Object.freeze({
<add> /** @type {HookMap<Object>} */
<ide> resolveOptions: new HookMap(
<ide> () => new SyncWaterfallHook(["resolveOptions"])
<ide> ),
<add> /** @type {HookMap<Resolver, Object>} */
<ide> resolver: new HookMap(() => new SyncHook(["resolver", "resolveOptions"]))
<ide> });
<del> /** @type {Map<string, { direct: WeakMap<Object, Resolver>, stringified: Map<string, Resolver> }>} */
<add> /** @type {Map<string, ResolverCache>} */
<ide> this.cache = new Map();
<ide> }
<ide>
<ide> module.exports = class ResolverFactory {
<ide> this.cache.set(type, typedCaches);
<ide> }
<ide> const cachedResolver = typedCaches.direct.get(resolveOptions);
<del> if (cachedResolver) return cachedResolver;
<add> if (cachedResolver) {
<add> return cachedResolver;
<add> }
<ide> const ident = JSON.stringify(resolveOptions);
<ide> const resolver = typedCaches.stringified.get(ident);
<ide> if (resolver) { | 2 |
PHP | PHP | add getgrammar into passthru in eloquent builder | 0946c3eb93cfe70a895bcae67d47c341d990a781 | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> class Builder
<ide> */
<ide> protected $passthru = [
<ide> 'insert', 'insertOrIgnore', 'insertGetId', 'insertUsing', 'getBindings', 'toSql', 'dump', 'dd',
<del> 'exists', 'doesntExist', 'count', 'min', 'max', 'avg', 'average', 'sum', 'getConnection', 'raw',
<add> 'exists', 'doesntExist', 'count', 'min', 'max', 'avg', 'average', 'sum', 'getConnection', 'raw', 'getGrammar',
<ide> ];
<ide>
<ide> /**
<ide><path>tests/Database/DatabaseEloquentBuilderTest.php
<ide> public function testQueryPassThru()
<ide> $builder->getQuery()->shouldReceive('raw')->once()->with('bar')->andReturn('foo');
<ide>
<ide> $this->assertSame('foo', $builder->raw('bar'));
<add>
<add> $builder = $this->getBuilder();
<add> $grammar = new Grammar();
<add> $builder->getQuery()->shouldReceive('getGrammar')->once()->andReturn($grammar);
<add> $this->assertSame($grammar, $builder->getGrammar());
<ide> }
<ide>
<ide> public function testQueryScopes() | 2 |
PHP | PHP | add getter mode for logqueries | 2dc13efa6d5fcdc38f0fedf72924ad6b2ee6ddd6 | <ide><path>src/Database/Connection.php
<ide> public function quoteIdentifier($identifier) {
<ide> /**
<ide> * Enables or disables query logging for this connection.
<ide> *
<del> * @param bool $enable whether to turn logging on or disable it
<del> * @return void
<add> * @param bool $enable whether to turn logging on or disable it.
<add> * Use null to read current value.
<add> * @return bool
<ide> */
<del> public function logQueries($enable) {
<add> public function logQueries($enable = null) {
<add> if ($enable === null) {
<add> return $this->_logQueries;
<add> }
<ide> $this->_logQueries = $enable;
<ide> }
<ide>
<ide><path>tests/TestCase/Database/ConnectionTest.php
<ide> public function testLoggerDecorator() {
<ide> $this->assertNotInstanceOf('\Cake\Database\Log\LoggingStatement', $st);
<ide> }
<ide>
<add>/**
<add> * test logQueries method
<add> *
<add> * @return void
<add> */
<add> public function testLogQueries() {
<add> $this->connection->logQueries(true);
<add> $this->assertTrue($this->connection->logQueries());
<add>
<add> $this->connection->logQueries(false);
<add> $this->assertFalse($this->connection->logQueries());
<add> }
<add>
<ide> /**
<ide> * Tests that log() function logs to the configured query logger
<ide> * | 2 |
Ruby | Ruby | use typewriter in doc for action cable [ci skip] | 5eb831d3f25dafb1128dd45334fe8e918ef52004 | <ide><path>actioncable/lib/action_cable/server/base.rb
<ide> def call(env)
<ide> config.connection_class.call.new(self, env).process
<ide> end
<ide>
<del> # Disconnect all the connections identified by `identifiers` on this server or any others via RemoteConnections.
<add> # Disconnect all the connections identified by +identifiers+ on this server or any others via RemoteConnections.
<ide> def disconnect(identifiers)
<ide> remote_connections.where(identifiers).disconnect
<ide> end | 1 |
Python | Python | attempt #2 to fix encoding issues | 77083534df662443dcca199b9396f53b85188560 | <ide><path>celery/utils/term.py
<ide> def _fold_no_color(self, a, b):
<ide> except AttributeError:
<ide> B = string(b)
<ide>
<del> return safe_str(safe_str(A) + safe_str(B))
<add> return ''.join((string(A), string(B)))
<ide>
<ide> def no_color(self):
<ide> if self.s:
<del> return safe_str(reduce(self._fold_no_color, self.s))
<add> return string(reduce(self._fold_no_color, self.s))
<ide> return ''
<ide>
<ide> def embed(self):
<ide> prefix = ''
<ide> if self.enabled:
<ide> prefix = self.op
<del> return safe_str(prefix) + safe_str(reduce(self._add, self.s))
<add> return ''.join((string(prefix), string(reduce(self._add, self.s))))
<ide>
<ide> def __unicode__(self):
<ide> suffix = ''
<ide> if self.enabled:
<ide> suffix = RESET_SEQ
<del> return safe_str(self.embed() + safe_str(suffix))
<add> return string(''.join((self.embed(), string(suffix))))
<ide>
<ide> def __str__(self):
<ide> return safe_str(self.__unicode__()) | 1 |
Ruby | Ruby | fix code style in `audit` spec | d98c45b2d3e06385fd2026ed6f431b93a4614c46 | <ide><path>Library/Homebrew/test/dev-cmd/audit_spec.rb
<ide> module Count
<ide> def self.increment
<ide> @count ||= 0
<del> @count += 1
<add> @count += 1
<ide> end
<ide> end
<ide>
<ide> class Foo < Formula
<ide> end
<ide>
<ide> describe "#audit_revision_and_version_scheme" do
<del> subject do
<add> subject {
<ide> fa = described_class.new(Formulary.factory(formula_path))
<ide> fa.audit_revision_and_version_scheme
<ide> fa.problems.first
<del> end
<add> }
<ide>
<ide> let(:origin_tap_path) { Tap::TAP_DIRECTORY/"homebrew/homebrew-foo" }
<del> let(:formula_subpath) { "Formula/foo#{@foo_version}.rb" }
<add> let(:foo_version) { Count.increment }
<add> let(:formula_subpath) { "Formula/foo#{foo_version}.rb" }
<ide> let(:origin_formula_path) { origin_tap_path/formula_subpath }
<ide> let(:tap_path) { Tap::TAP_DIRECTORY/"homebrew/homebrew-bar" }
<ide> let(:formula_path) { tap_path/formula_subpath }
<ide>
<ide> before do
<del> @foo_version = Count.increment
<del>
<ide> origin_formula_path.write <<~EOS
<del> class Foo#{@foo_version} < Formula
<add> class Foo#{foo_version} < Formula
<ide> url "https://example.com/foo-1.0.tar.gz"
<ide> revision 2
<ide> version_scheme 1 | 1 |
Javascript | Javascript | upgrade compatibilityplugin to es6 | 2ed67f172e9656c9c95d23eab1975dbdd98e0697 | <ide><path>lib/CompatibilityPlugin.js
<ide> MIT License http://www.opensource.org/licenses/mit-license.php
<ide> Author Tobias Koppers @sokra
<ide> */
<del>var ConstDependency = require("./dependencies/ConstDependency");
<del>
<del>var NullFactory = require("./NullFactory");
<del>
<del>var jsonLoaderPath = require.resolve("json-loader");
<del>var matchJson = /\.json$/i;
<del>
<del>function CompatibilityPlugin() {}
<del>module.exports = CompatibilityPlugin;
<add>"use strict";
<add>
<add>const ConstDependency = require("./dependencies/ConstDependency");
<add>
<add>const NullFactory = require("./NullFactory");
<add>
<add>const jsonLoaderPath = require.resolve("json-loader");
<add>const matchJson = /\.json$/i;
<add>
<add>class CompatibilityPlugin {
<add>
<add> apply(compiler) {
<add> compiler.plugin("compilation", (compilation, params) => {
<add> compilation.dependencyFactories.set(ConstDependency, new NullFactory());
<add> compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
<add>
<add> params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
<add>
<add> if(typeof parserOptions.browserify !== "undefined" && !parserOptions.browserify)
<add> return;
<add>
<add> parser.plugin("call require", (expr) => {
<add> // support for browserify style require delegator: "require(o, !0)"
<add> if(expr.arguments.length !== 2) return;
<add> const second = parser.evaluateExpression(expr.arguments[1]);
<add> if(!second.isBoolean()) return;
<add> if(second.asBool() !== true) return;
<add> const dep = new ConstDependency("require", expr.callee.range);
<add> dep.loc = expr.loc;
<add> if(parser.state.current.dependencies.length > 1) {
<add> const last = parser.state.current.dependencies[parser.state.current.dependencies.length - 1];
<add> if(last.critical && last.request === "." && last.userRequest === "." && last.recursive)
<add> parser.state.current.dependencies.pop();
<add> }
<add> parser.state.current.addDependency(dep);
<add> return true;
<add> });
<add> });
<ide>
<del>CompatibilityPlugin.prototype.apply = function(compiler) {
<del> compiler.plugin("compilation", function(compilation, params) {
<del> compilation.dependencyFactories.set(ConstDependency, new NullFactory());
<del> compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
<del>
<del> params.normalModuleFactory.plugin("parser", function(parser, parserOptions) {
<del>
<del> if(typeof parserOptions.browserify !== "undefined" && !parserOptions.browserify)
<del> return;
<del>
<del> parser.plugin("call require", function(expr) {
<del> // support for browserify style require delegator: "require(o, !0)"
<del> if(expr.arguments.length !== 2) return;
<del> var second = this.evaluateExpression(expr.arguments[1]);
<del> if(!second.isBoolean()) return;
<del> if(second.asBool() !== true) return;
<del> var dep = new ConstDependency("require", expr.callee.range);
<del> dep.loc = expr.loc;
<del> if(this.state.current.dependencies.length > 1) {
<del> var last = this.state.current.dependencies[this.state.current.dependencies.length - 1];
<del> if(last.critical && last.request === "." && last.userRequest === "." && last.recursive)
<del> this.state.current.dependencies.pop();
<add> params.normalModuleFactory.plugin("after-resolve", (data, done) => {
<add> // if this is a json file and there are no loaders active, we use the json-loader in order to avoid parse errors
<add> // @see https://github.com/webpack/webpack/issues/3363
<add> if(matchJson.test(data.request) && data.loaders.length === 0) {
<add> data.loaders.push({
<add> loader: jsonLoaderPath
<add> });
<ide> }
<del> this.state.current.addDependency(dep);
<del> return true;
<add> done(null, data);
<ide> });
<ide> });
<del>
<del> params.normalModuleFactory.plugin("after-resolve", function(data, done) {
<del> // if this is a json file and there are no loaders active, we use the json-loader in order to avoid parse errors
<del> // @see https://github.com/webpack/webpack/issues/3363
<del> if(matchJson.test(data.request) && data.loaders.length === 0) {
<del> data.loaders.push({
<del> loader: jsonLoaderPath
<del> });
<del> }
<del> done(null, data);
<del> });
<del> });
<del>};
<add> }
<add>}
<add>module.exports = CompatibilityPlugin; | 1 |
Python | Python | use localhost rather than 0.0.0.0 | 4bf129f49eb608e34e46f60edb1d23303dd2ed27 | <ide><path>examples/__main__.py
<ide> })
<ide> http_server = tornado.httpserver.HTTPServer(application)
<ide> http_server.listen(tornado.options.options.port)
<del> print "http://0.0.0.0:%d/examples/index.html" % tornado.options.options.port
<add> print "http://localhost:%d/examples/index.html" % tornado.options.options.port
<ide> tornado.ioloop.IOLoop.instance().start() | 1 |
PHP | PHP | fix timeout and sleep | b44d34056e932898a295e7e58b8c48ce6057324d | <ide><path>src/Illuminate/Queue/Console/ListenCommand.php
<ide>
<ide> namespace Illuminate\Queue\Console;
<ide>
<add>use InvalidArgumentException;
<ide> use Illuminate\Queue\Listener;
<ide> use Illuminate\Console\Command;
<ide> use Symfony\Component\Console\Input\InputOption;
<ide> public function fire()
<ide>
<ide> $timeout = $this->input->getOption('timeout');
<ide>
<add> if ($timeout <= $this->input->getOption('sleep')) {
<add> throw new InvalidArgumentException(
<add> "Job timeout must be greater than 'sleep' option value."
<add> );
<add> }
<add>
<ide> // We need to get the right queue for the connection which is set in the queue
<ide> // configuration file for the application. We will pull it based on the set
<ide> // connection being run for the queue operation currently being executed. | 1 |
Go | Go | remove stdout from registry | 398a6317a09679b65a59d529e78f5e7480e8de0b | <ide><path>registry/registry.go
<ide> func (r *Registry) getImagesInRepository(repository string, authConfig *auth.Aut
<ide>
<ide> // Retrieve an image from the Registry.
<ide> // Returns the Image object as well as the layer as an Archive (io.Reader)
<del>func (r *Registry) GetRemoteImageJson(stdout io.Writer, imgId, registry string, token []string) ([]byte, error) {
<add>func (r *Registry) GetRemoteImageJson(imgId, registry string, token []string) ([]byte, error) {
<ide> client := r.getHttpClient()
<ide>
<del> fmt.Fprintf(stdout, "Pulling %s metadata\r\n", imgId)
<ide> // Get the Json
<ide> req, err := http.NewRequest("GET", registry+"/images/"+imgId+"/json", nil)
<ide> if err != nil {
<ide> func (r *Registry) GetRemoteImageJson(stdout io.Writer, imgId, registry string,
<ide> return jsonString, nil
<ide> }
<ide>
<del>func (r *Registry) GetRemoteImageLayer(stdout io.Writer, imgId, registry string, token []string) (io.Reader, error) {
<add>func (r *Registry) GetRemoteImageLayer(imgId, registry string, token []string) (io.ReadCloser, int, error) {
<ide> client := r.getHttpClient()
<ide>
<ide> req, err := http.NewRequest("GET", registry+"/images/"+imgId+"/layer", nil)
<ide> if err != nil {
<del> return nil, fmt.Errorf("Error while getting from the server: %s\n", err)
<add> return nil, -1, fmt.Errorf("Error while getting from the server: %s\n", err)
<ide> }
<ide> req.Header.Set("Authorization", "Token "+strings.Join(token, ", "))
<ide> res, err := client.Do(req)
<ide> if err != nil {
<del> return nil, err
<add> return nil, -1, err
<ide> }
<del> return utils.ProgressReader(res.Body, int(res.ContentLength), stdout, "Downloading %v/%v (%v)"), nil
<add> return res.Body, int(res.ContentLength), nil
<ide> }
<ide>
<del>func (r *Registry) GetRemoteTags(stdout io.Writer, registries []string, repository string, token []string) (map[string]string, error) {
<add>func (r *Registry) GetRemoteTags(registries []string, repository string, token []string) (map[string]string, error) {
<ide> client := r.getHttpClient()
<ide> if strings.Count(repository, "/") == 0 {
<ide> // This will be removed once the Registry supports auto-resolution on
<ide> func (r *Registry) GetRemoteTags(stdout io.Writer, registries []string, reposito
<ide> return nil, fmt.Errorf("Could not reach any registry endpoint")
<ide> }
<ide>
<del>func (r *Registry) getImageForTag(stdout io.Writer, tag, remote, registry string, token []string) (string, error) {
<add>func (r *Registry) getImageForTag(tag, remote, registry string, token []string) (string, error) {
<ide> client := r.getHttpClient()
<ide>
<ide> if !strings.Contains(remote, "/") {
<ide> func (r *Registry) PushImageJsonIndex(remote string, imgList []*ImgData, validat
<ide> }, nil
<ide> }
<ide>
<del>func (r *Registry) SearchRepositories(stdout io.Writer, term string) (*SearchResults, error) {
<add>func (r *Registry) SearchRepositories(term string) (*SearchResults, error) {
<ide> client := r.getHttpClient()
<ide> u := auth.IndexServerAddress() + "/search?q=" + url.QueryEscape(term)
<ide> req, err := http.NewRequest("GET", u, nil)
<ide><path>server.go
<ide> func (srv *Server) ContainerExport(name string, out io.Writer) error {
<ide> }
<ide>
<ide> func (srv *Server) ImagesSearch(term string) ([]ApiSearch, error) {
<del> results, err := srv.registry.SearchRepositories(nil, term)
<add> results, err := srv.registry.SearchRepositories(term)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func (srv *Server) ContainerTag(name, repo, tag string, force bool) error {
<ide> return nil
<ide> }
<ide>
<del>func (srv *Server) pullImage(stdout io.Writer, imgId, registry string, token []string) error {
<add>func (srv *Server) pullImage(out io.Writer, imgId, registry string, token []string) error {
<ide> history, err := srv.registry.GetRemoteHistory(imgId, registry, token)
<ide> if err != nil {
<ide> return err
<ide> func (srv *Server) pullImage(stdout io.Writer, imgId, registry string, token []s
<ide> // FIXME: Launch the getRemoteImage() in goroutines
<ide> for _, id := range history {
<ide> if !srv.runtime.graph.Exists(id) {
<del> imgJson, err := srv.registry.GetRemoteImageJson(stdout, id, registry, token)
<add> fmt.Fprintf(out, "Pulling %s metadata\r\n", id)
<add> imgJson, err := srv.registry.GetRemoteImageJson(id, registry, token)
<ide> if err != nil {
<ide> // FIXME: Keep goging in case of error?
<ide> return err
<ide> func (srv *Server) pullImage(stdout io.Writer, imgId, registry string, token []s
<ide> }
<ide>
<ide> // Get the layer
<del> fmt.Fprintf(stdout, "Pulling %s fs layer\r\n", img.Id)
<del> layer, err := srv.registry.GetRemoteImageLayer(stdout, img.Id, registry, token)
<add> fmt.Fprintf(out, "Pulling %s fs layer\r\n", img.Id)
<add> layer, contentLength, err := srv.registry.GetRemoteImageLayer(img.Id, registry, token)
<ide> if err != nil {
<ide> return err
<ide> }
<del>
<del> if err := srv.runtime.graph.Register(layer, false, img); err != nil {
<add> if err := srv.runtime.graph.Register(utils.ProgressReader(layer, contentLength, out, "Downloading %v/%v (%v)"), false, img); err != nil {
<ide> return err
<ide> }
<ide> }
<ide> func (srv *Server) pullRepository(stdout io.Writer, remote, askedTag string) err
<ide> }
<ide>
<ide> utils.Debugf("Retrieving the tag list")
<del> tagsList, err := srv.registry.GetRemoteTags(stdout, repoData.Endpoints, remote, repoData.Tokens)
<add> tagsList, err := srv.registry.GetRemoteTags(repoData.Endpoints, remote, repoData.Tokens)
<ide> if err != nil {
<ide> return err
<ide> } | 2 |
Javascript | Javascript | use cached intl.numberformat everywhere | 59000abd1d96c4e29c6687967f948b47a7db3948 | <ide><path>src/controllers/controller.doughnut.js
<ide> import DatasetController from '../core/core.datasetController';
<add>import {formatNumber} from '../core/core.intl';
<ide> import {isArray, valueOrDefault} from '../helpers/helpers.core';
<ide> import {toRadians, PI, TAU, HALF_PI} from '../helpers/helpers.math';
<ide>
<ide> export default class DoughnutController extends DatasetController {
<ide> const meta = me._cachedMeta;
<ide> const chart = me.chart;
<ide> const labels = chart.data.labels || [];
<del> const value = new Intl.NumberFormat(chart.options.locale).format(meta._parsed[index]);
<add> const value = formatNumber(meta._parsed[index], chart.options.locale);
<ide>
<ide> return {
<ide> label: labels[index] || '',
<ide><path>src/core/core.intl.js
<add>
<add>const intlCache = new Map();
<add>
<add>export function getNumberFormat(locale, options) {
<add> options = options || {};
<add> const cacheKey = locale + JSON.stringify(options);
<add> let formatter = intlCache.get(cacheKey);
<add> if (!formatter) {
<add> formatter = new Intl.NumberFormat(locale, options);
<add> intlCache.set(cacheKey, formatter);
<add> }
<add> return formatter;
<add>}
<add>
<add>export function formatNumber(num, locale, options) {
<add> return getNumberFormat(locale, options).format(num);
<add>}
<ide><path>src/core/core.ticks.js
<ide> import {isArray} from '../helpers/helpers.core';
<ide> import {log10} from '../helpers/helpers.math';
<add>import {formatNumber} from './core.intl';
<ide>
<del>const intlCache = new Map();
<ide> /**
<ide> * Namespace to hold formatters for different types of ticks
<ide> * @namespace Chart.Ticks.formatters
<ide> const formatters = {
<ide> const options = {notation, minimumFractionDigits: numDecimal, maximumFractionDigits: numDecimal};
<ide> Object.assign(options, this.options.ticks.format);
<ide>
<del> const cacheKey = locale + JSON.stringify(options);
<del> let formatter = intlCache.get(cacheKey);
<del> if (!formatter) {
<del> formatter = new Intl.NumberFormat(locale, options);
<del> intlCache.set(cacheKey, formatter);
<del> }
<del>
<del> return formatter.format(tickValue);
<add> return formatNumber(tickValue, locale, options);
<ide> }
<ide> };
<ide>
<ide><path>src/scales/scale.linearbase.js
<ide> import {isNullOrUndef, valueOrDefault} from '../helpers/helpers.core';
<ide> import {almostEquals, almostWhole, log10, _decimalPlaces, _setMinAndMaxByKey, sign} from '../helpers/helpers.math';
<ide> import Scale from '../core/core.scale';
<add>import {formatNumber} from '../core/core.intl';
<ide>
<ide> /**
<ide> * Implementation of the nice number algorithm used in determining where axis labels will go
<ide> export default class LinearScaleBase extends Scale {
<ide> }
<ide>
<ide> getLabelForValue(value) {
<del> return new Intl.NumberFormat(this.options.locale).format(value);
<add> return formatNumber(value, this.options.locale);
<ide> }
<ide> }
<ide><path>src/scales/scale.logarithmic.js
<ide> import {_setMinAndMaxByKey, log10} from '../helpers/helpers.math';
<ide> import Scale from '../core/core.scale';
<ide> import LinearScaleBase from './scale.linearbase';
<ide> import Ticks from '../core/core.ticks';
<add>import {formatNumber} from '../core/core.intl';
<ide>
<ide> function isMajor(tickVal) {
<ide> const remain = tickVal / (Math.pow(10, Math.floor(log10(tickVal))));
<ide> export default class LogarithmicScale extends Scale {
<ide> * @return {string}
<ide> */
<ide> getLabelForValue(value) {
<del> return value === undefined ? '0' : new Intl.NumberFormat(this.options.locale).format(value);
<add> return value === undefined ? '0' : formatNumber(value, this.options.locale);
<ide> }
<ide>
<ide> /** | 5 |
Mixed | Ruby | add include_seconds option to datetime_local_field | 2dea9aebf2ce2e0f37c821a8d88f3caef549de7a | <ide><path>actionview/CHANGELOG.md
<add>* Add `include_seconds` option for `datetime_local_field`
<add>
<add> This allows to omit seconds part in the input field, by passing `include_seconds: false`
<add>
<add> *Wojciech Wnętrzak*
<add>
<ide> * Guard against `ActionView::Helpers::FormTagHelper#field_name` calls with nil
<ide> `object_name` arguments. For example:
<ide>
<ide><path>actionview/lib/action_view/helpers/form_helper.rb
<ide> def time_field(object_name, method, options = {})
<ide> # datetime_field("user", "born_on", min: "2014-05-20T00:00:00")
<ide> # # => <input id="user_born_on" name="user[born_on]" type="datetime-local" min="2014-05-20T00:00:00.000" />
<ide> #
<add> # By default, provided datetimes will be formatted including seconds. You can render just the date, hour,
<add> # and minute by passing <tt>include_seconds: false</tt>.
<add> #
<add> # @user.born_on = Time.current
<add> # datetime_field("user", "born_on", include_seconds: false)
<add> # # => <input id="user_born_on" name="user[born_on]" type="datetime-local" value="2014-05-20T14:35" />
<ide> def datetime_field(object_name, method, options = {})
<ide> Tags::DatetimeLocalField.new(object_name, method, self, options).render
<ide> end
<ide><path>actionview/lib/action_view/helpers/form_tag_helper.rb
<ide> def time_field_tag(name, value = nil, options = {})
<ide> # * <tt>:min</tt> - The minimum acceptable value.
<ide> # * <tt>:max</tt> - The maximum acceptable value.
<ide> # * <tt>:step</tt> - The acceptable value granularity.
<add> # * <tt>:include_seconds</tt> - Include seconds in the output timestamp format (true by default).
<ide> # * Otherwise accepts the same options as text_field_tag.
<ide> def datetime_field_tag(name, value = nil, options = {})
<ide> text_field_tag(name, value, options.merge(type: "datetime-local"))
<ide><path>actionview/lib/action_view/helpers/tags/datetime_local_field.rb
<ide> module ActionView
<ide> module Helpers
<ide> module Tags # :nodoc:
<ide> class DatetimeLocalField < DatetimeField # :nodoc:
<add> def initialize(object_name, method_name, template_object, options = {})
<add> @include_seconds = options.delete(:include_seconds) { true }
<add> super
<add> end
<add>
<ide> class << self
<ide> def field_type
<ide> @field_type ||= "datetime-local"
<ide> def field_type
<ide>
<ide> private
<ide> def format_date(value)
<del> value&.strftime("%Y-%m-%dT%T")
<add> if @include_seconds
<add> value&.strftime("%Y-%m-%dT%T")
<add> else
<add> value&.strftime("%Y-%m-%dT%H:%M")
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>actionview/test/template/form_helper_test.rb
<ide> def test_datetime_local_field
<ide> assert_dom_equal(expected, datetime_local_field("post", "written_on"))
<ide> end
<ide>
<add> def test_datetime_local_field_without_seconds
<add> expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T00:00" />}
<add> assert_dom_equal(expected, datetime_local_field("post", "written_on", include_seconds: false))
<add> end
<add>
<ide> def test_month_field
<ide> expected = %{<input id="post_written_on" name="post[written_on]" type="month" value="2004-06" />}
<ide> assert_dom_equal(expected, month_field("post", "written_on")) | 5 |
Ruby | Ruby | remove array.wrap call in activemodel | 2a663dcf09b380279b22537db6a7caaefdf8b961 | <ide><path>activemodel/lib/active_model/callbacks.rb
<del>require 'active_support/core_ext/array/wrap'
<ide> require 'active_support/callbacks'
<ide>
<ide> module ActiveModel
<ide> def define_model_callbacks(*callbacks)
<ide> :only => [:before, :around, :after]
<ide> }.merge(options)
<ide>
<del> types = Array.wrap(options.delete(:only))
<add> types = Array(options.delete(:only))
<ide>
<ide> callbacks.each do |callback|
<ide> define_callbacks(callback, options)
<ide> def _define_after_model_callback(klass, callback) #:nodoc:
<ide> def self.after_#{callback}(*args, &block)
<ide> options = args.extract_options!
<ide> options[:prepend] = true
<del> options[:if] = Array.wrap(options[:if]) << "!halted && value != false"
<add> options[:if] = Array(options[:if]) << "!halted && value != false"
<ide> set_callback(:#{callback}, :after, *(args << options), &block)
<ide> end
<ide> CALLBACK
<ide><path>activemodel/lib/active_model/observing.rb
<ide> require 'singleton'
<ide> require 'active_model/observer_array'
<del>require 'active_support/core_ext/array/wrap'
<ide> require 'active_support/core_ext/module/aliasing'
<ide> require 'active_support/core_ext/module/remove_method'
<ide> require 'active_support/core_ext/string/inflections'
<ide> def observe(*models)
<ide> # end
<ide> # end
<ide> def observed_classes
<del> Array.wrap(observed_class)
<add> Array(observed_class)
<ide> end
<ide>
<ide> # The class observed by default is inferred from the observer's class name:
<ide><path>activemodel/lib/active_model/serialization.rb
<ide> def serializable_hash(options = nil)
<ide>
<ide> attribute_names = attributes.keys.sort
<ide> if only = options[:only]
<del> attribute_names &= Array.wrap(only).map(&:to_s)
<add> attribute_names &= Array(only).map(&:to_s)
<ide> elsif except = options[:except]
<del> attribute_names -= Array.wrap(except).map(&:to_s)
<add> attribute_names -= Array(except).map(&:to_s)
<ide> end
<ide>
<ide> hash = {}
<ide> attribute_names.each { |n| hash[n] = read_attribute_for_serialization(n) }
<ide>
<del> method_names = Array.wrap(options[:methods]).select { |n| respond_to?(n) }
<add> method_names = Array(options[:methods]).select { |n| respond_to?(n) }
<ide> method_names.each { |n| hash[n] = send(n) }
<ide>
<ide> serializable_add_includes(options) do |association, records, opts|
<ide><path>activemodel/lib/active_model/serializers/xml.rb
<del>require 'active_support/core_ext/array/wrap'
<ide> require 'active_support/core_ext/class/attribute_accessors'
<ide> require 'active_support/core_ext/array/conversions'
<ide> require 'active_support/core_ext/hash/conversions'
<ide> def serializable_hash
<ide> end
<ide>
<ide> def serializable_collection
<del> methods = Array.wrap(options[:methods]).map(&:to_s)
<add> methods = Array(options[:methods]).map(&:to_s)
<ide> serializable_hash.map do |name, value|
<ide> name = name.to_s
<ide> if methods.include?(name)
<ide> def add_associations(association, records, opts)
<ide>
<ide> def add_procs
<ide> if procs = options.delete(:procs)
<del> Array.wrap(procs).each do |proc|
<add> Array(procs).each do |proc|
<ide> if proc.arity == 1
<ide> proc.call(options)
<ide> else
<ide><path>activemodel/lib/active_model/validations.rb
<ide> require 'active_support/core_ext/array/extract_options'
<del>require 'active_support/core_ext/array/wrap'
<ide> require 'active_support/core_ext/class/attribute'
<ide> require 'active_support/core_ext/hash/keys'
<ide> require 'active_support/core_ext/hash/except'
<ide> def validate(*args, &block)
<ide> options = args.extract_options!
<ide> if options.key?(:on)
<ide> options = options.dup
<del> options[:if] = Array.wrap(options[:if])
<add> options[:if] = Array(options[:if])
<ide> options[:if].unshift("validation_context == :#{options[:on]}")
<ide> end
<ide> args << options
<ide><path>activemodel/lib/active_model/validations/callbacks.rb
<ide> module ClassMethods
<ide> def before_validation(*args, &block)
<ide> options = args.last
<ide> if options.is_a?(Hash) && options[:on]
<del> options[:if] = Array.wrap(options[:if])
<add> options[:if] = Array(options[:if])
<ide> options[:if].unshift("self.validation_context == :#{options[:on]}")
<ide> end
<ide> set_callback(:validation, :before, *args, &block)
<ide> def before_validation(*args, &block)
<ide> def after_validation(*args, &block)
<ide> options = args.extract_options!
<ide> options[:prepend] = true
<del> options[:if] = Array.wrap(options[:if])
<add> options[:if] = Array(options[:if])
<ide> options[:if] << "!halted"
<ide> options[:if].unshift("self.validation_context == :#{options[:on]}") if options[:on]
<ide> set_callback(:validation, :after, *(args << options), &block)
<ide><path>activemodel/lib/active_model/validator.rb
<del>require 'active_support/core_ext/array/wrap'
<ide> require "active_support/core_ext/module/anonymous"
<ide> require 'active_support/core_ext/object/blank'
<ide> require 'active_support/core_ext/object/inclusion'
<ide> class EachValidator < Validator
<ide> # +options+ reader, however the <tt>:attributes</tt> option will be removed
<ide> # and instead be made available through the +attributes+ reader.
<ide> def initialize(options)
<del> @attributes = Array.wrap(options.delete(:attributes))
<add> @attributes = Array(options.delete(:attributes))
<ide> raise ":attributes cannot be blank" if @attributes.empty?
<ide> super
<ide> check_validity! | 7 |
PHP | PHP | apply fixes from styleci | 4ffd790217432f8699d4beae891fca482c230de4 | <ide><path>src/Illuminate/Notifications/Channels/MailChannel.php
<ide> use Closure;
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Str;
<del>use Illuminate\Support\Collection;
<ide> use Illuminate\Contracts\Mail\Mailer;
<ide> use Illuminate\Contracts\Mail\Mailable;
<ide> use Illuminate\Notifications\Notification; | 1 |
Javascript | Javascript | allow dangerouslysetinnerhtml in <option> | 442eb21e0e6541460157782d18edea1383ed62fd | <ide><path>packages/react-dom/src/server/ReactDOMServerFormatConfig.js
<ide> function pushStartOption(
<ide> let children = null;
<ide> let value = null;
<ide> let selected = null;
<add> let innerHTML = null;
<ide> for (const propKey in props) {
<ide> if (hasOwnProperty.call(props, propKey)) {
<ide> const propValue = props[propKey];
<ide> function pushStartOption(
<ide> }
<ide> break;
<ide> case 'dangerouslySetInnerHTML':
<del> invariant(
<del> false,
<del> '`dangerouslySetInnerHTML` does not work on <option>.',
<del> );
<add> innerHTML = propValue;
<add> break;
<ide> // eslint-disable-next-line-no-fallthrough
<ide> case 'value':
<ide> value = propValue;
<ide> function pushStartOption(
<ide> }
<ide>
<ide> target.push(endOfStartTag);
<add> pushInnerHTML(target, innerHTML, children);
<ide> return children;
<ide> }
<ide> | 1 |
Go | Go | use dockercmd in integration-cli when possible | 012b67c3ea5bff539673deaa7058036126ac1046 | <ide><path>integration-cli/docker_cli_restart_test.go
<ide> func (s *DockerSuite) TestRestartStoppedContainer(c *check.C) {
<ide>
<ide> out, _ = dockerCmd(c, "logs", cleanedContainerID)
<ide> if out != "foobar\nfoobar\n" {
<del> c.Errorf("container should've printed 'foobar' twice")
<add> c.Errorf("container should've printed 'foobar' twice, got %v", out)
<ide> }
<ide> }
<ide>
<ide><path>integration-cli/docker_cli_save_load_test.go
<ide> import (
<ide> // save a repo using gz compression and try to load it using stdout
<ide> func (s *DockerSuite) TestSaveXzAndLoadRepoStdout(c *check.C) {
<ide> name := "test-save-xz-and-load-repo-stdout"
<del> runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "true")
<del> out, _, err := runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatalf("failed to create a container: %v %v", out, err)
<del> }
<add> dockerCmd(c, "run", "--name", name, "busybox", "true")
<ide>
<ide> repoName := "foobar-save-load-test-xz-gz"
<add> out, _ := dockerCmd(c, "commit", name, repoName)
<ide>
<del> commitCmd := exec.Command(dockerBinary, "commit", name, repoName)
<del> out, _, err = runCommandWithOutput(commitCmd)
<del> if err != nil {
<del> c.Fatalf("failed to commit container: %v %v", out, err)
<del> }
<del>
<del> inspectCmd := exec.Command(dockerBinary, "inspect", repoName)
<del> before, _, err := runCommandWithOutput(inspectCmd)
<del> if err != nil {
<del> c.Fatalf("the repo should exist before saving it: %v %v", before, err)
<del> }
<add> dockerCmd(c, "inspect", repoName)
<ide>
<ide> repoTarball, _, err := runCommandPipelineWithOutput(
<ide> exec.Command(dockerBinary, "save", repoName),
<ide> func (s *DockerSuite) TestSaveXzAndLoadRepoStdout(c *check.C) {
<ide> c.Fatalf("expected error, but succeeded with no error and output: %v", out)
<ide> }
<ide>
<del> inspectCmd = exec.Command(dockerBinary, "inspect", repoName)
<del> after, _, err := runCommandWithOutput(inspectCmd)
<add> after, _, err := dockerCmdWithError(c, "inspect", repoName)
<ide> if err == nil {
<ide> c.Fatalf("the repo should not exist: %v", after)
<ide> }
<ide> func (s *DockerSuite) TestSaveXzAndLoadRepoStdout(c *check.C) {
<ide> // save a repo using xz+gz compression and try to load it using stdout
<ide> func (s *DockerSuite) TestSaveXzGzAndLoadRepoStdout(c *check.C) {
<ide> name := "test-save-xz-gz-and-load-repo-stdout"
<del> runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "true")
<del> out, _, err := runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatalf("failed to create a container: %v %v", out, err)
<del> }
<add> dockerCmd(c, "run", "--name", name, "busybox", "true")
<ide>
<ide> repoName := "foobar-save-load-test-xz-gz"
<add> dockerCmd(c, "commit", name, repoName)
<ide>
<del> commitCmd := exec.Command(dockerBinary, "commit", name, repoName)
<del> out, _, err = runCommandWithOutput(commitCmd)
<del> if err != nil {
<del> c.Fatalf("failed to commit container: %v %v", out, err)
<del> }
<del>
<del> inspectCmd := exec.Command(dockerBinary, "inspect", repoName)
<del> before, _, err := runCommandWithOutput(inspectCmd)
<del> if err != nil {
<del> c.Fatalf("the repo should exist before saving it: %v %v", before, err)
<del> }
<add> dockerCmd(c, "inspect", repoName)
<ide>
<del> out, _, err = runCommandPipelineWithOutput(
<add> out, _, err := runCommandPipelineWithOutput(
<ide> exec.Command(dockerBinary, "save", repoName),
<ide> exec.Command("xz", "-c"),
<ide> exec.Command("gzip", "-c"))
<ide> func (s *DockerSuite) TestSaveXzGzAndLoadRepoStdout(c *check.C) {
<ide> c.Fatalf("expected error, but succeeded with no error and output: %v", out)
<ide> }
<ide>
<del> inspectCmd = exec.Command(dockerBinary, "inspect", repoName)
<del> after, _, err := runCommandWithOutput(inspectCmd)
<add> after, _, err := dockerCmdWithError(c, "inspect", repoName)
<ide> if err == nil {
<ide> c.Fatalf("the repo should not exist: %v", after)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestSaveSingleTag(c *check.C) {
<ide> repoName := "foobar-save-single-tag-test"
<add> dockerCmd(c, "tag", "busybox:latest", fmt.Sprintf("%v:latest", repoName))
<ide>
<del> tagCmd := exec.Command(dockerBinary, "tag", "busybox:latest", fmt.Sprintf("%v:latest", repoName))
<del> if out, _, err := runCommandWithOutput(tagCmd); err != nil {
<del> c.Fatalf("failed to tag repo: %s, %v", out, err)
<del> }
<del>
<del> idCmd := exec.Command(dockerBinary, "images", "-q", "--no-trunc", repoName)
<del> out, _, err := runCommandWithOutput(idCmd)
<del> if err != nil {
<del> c.Fatalf("failed to get repo ID: %s, %v", out, err)
<del> }
<add> out, _ := dockerCmd(c, "images", "-q", "--no-trunc", repoName)
<ide> cleanedImageID := strings.TrimSpace(out)
<ide>
<del> out, _, err = runCommandPipelineWithOutput(
<add> out, _, err := runCommandPipelineWithOutput(
<ide> exec.Command(dockerBinary, "save", fmt.Sprintf("%v:latest", repoName)),
<ide> exec.Command("tar", "t"),
<ide> exec.Command("grep", "-E", fmt.Sprintf("(^repositories$|%v)", cleanedImageID)))
<ide> if err != nil {
<ide> c.Fatalf("failed to save repo with image ID and 'repositories' file: %s, %v", out, err)
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestSaveImageId(c *check.C) {
<ide> repoName := "foobar-save-image-id-test"
<add> dockerCmd(c, "tag", "emptyfs:latest", fmt.Sprintf("%v:latest", repoName))
<ide>
<del> tagCmd := exec.Command(dockerBinary, "tag", "emptyfs:latest", fmt.Sprintf("%v:latest", repoName))
<del> if out, _, err := runCommandWithOutput(tagCmd); err != nil {
<del> c.Fatalf("failed to tag repo: %s, %v", out, err)
<del> }
<del>
<del> idLongCmd := exec.Command(dockerBinary, "images", "-q", "--no-trunc", repoName)
<del> out, _, err := runCommandWithOutput(idLongCmd)
<del> if err != nil {
<del> c.Fatalf("failed to get repo ID: %s, %v", out, err)
<del> }
<del>
<add> out, _ := dockerCmd(c, "images", "-q", "--no-trunc", repoName)
<ide> cleanedLongImageID := strings.TrimSpace(out)
<ide>
<del> idShortCmd := exec.Command(dockerBinary, "images", "-q", repoName)
<del> out, _, err = runCommandWithOutput(idShortCmd)
<del> if err != nil {
<del> c.Fatalf("failed to get repo short ID: %s, %v", out, err)
<del> }
<del>
<add> out, _ = dockerCmd(c, "images", "-q", repoName)
<ide> cleanedShortImageID := strings.TrimSpace(out)
<ide>
<ide> saveCmd := exec.Command(dockerBinary, "save", cleanedShortImageID)
<ide> tarCmd := exec.Command("tar", "t")
<add>
<add> var err error
<ide> tarCmd.Stdin, err = saveCmd.StdoutPipe()
<ide> if err != nil {
<ide> c.Fatalf("cannot set stdout pipe for tar: %v", err)
<ide> func (s *DockerSuite) TestSaveImageId(c *check.C) {
<ide> if err != nil {
<ide> c.Fatalf("failed to save repo with image ID: %s, %v", out, err)
<ide> }
<del>
<ide> }
<ide>
<ide> // save a repo and try to load it using flags
<ide> func (s *DockerSuite) TestSaveAndLoadRepoFlags(c *check.C) {
<ide> name := "test-save-and-load-repo-flags"
<del> runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "true")
<del> out, _, err := runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatalf("failed to create a container: %s, %v", out, err)
<del> }
<add> dockerCmd(c, "run", "--name", name, "busybox", "true")
<add>
<ide> repoName := "foobar-save-load-test"
<ide>
<del> commitCmd := exec.Command(dockerBinary, "commit", name, repoName)
<ide> deleteImages(repoName)
<del> if out, _, err = runCommandWithOutput(commitCmd); err != nil {
<del> c.Fatalf("failed to commit container: %s, %v", out, err)
<del> }
<del>
<del> inspectCmd := exec.Command(dockerBinary, "inspect", repoName)
<del> before, _, err := runCommandWithOutput(inspectCmd)
<del> if err != nil {
<del> c.Fatalf("the repo should exist before saving it: %s, %v", before, err)
<add> dockerCmd(c, "commit", name, repoName)
<ide>
<del> }
<add> before, _ := dockerCmd(c, "inspect", repoName)
<ide>
<del> out, _, err = runCommandPipelineWithOutput(
<add> out, _, err := runCommandPipelineWithOutput(
<ide> exec.Command(dockerBinary, "save", repoName),
<ide> exec.Command(dockerBinary, "load"))
<ide> if err != nil {
<ide> c.Fatalf("failed to save and load repo: %s, %v", out, err)
<ide> }
<ide>
<del> inspectCmd = exec.Command(dockerBinary, "inspect", repoName)
<del> after, _, err := runCommandWithOutput(inspectCmd)
<del> if err != nil {
<del> c.Fatalf("the repo should exist after loading it: %s, %v", after, err)
<del> }
<del>
<add> after, _ := dockerCmd(c, "inspect", repoName)
<ide> if before != after {
<ide> c.Fatalf("inspect is not the same after a save / load")
<ide> }
<ide> func (s *DockerSuite) TestSaveMultipleNames(c *check.C) {
<ide> repoName := "foobar-save-multi-name-test"
<ide>
<ide> // Make one image
<del> tagCmd := exec.Command(dockerBinary, "tag", "emptyfs:latest", fmt.Sprintf("%v-one:latest", repoName))
<del> if out, _, err := runCommandWithOutput(tagCmd); err != nil {
<del> c.Fatalf("failed to tag repo: %s, %v", out, err)
<del> }
<add> dockerCmd(c, "tag", "emptyfs:latest", fmt.Sprintf("%v-one:latest", repoName))
<ide>
<ide> // Make two images
<del> tagCmd = exec.Command(dockerBinary, "tag", "emptyfs:latest", fmt.Sprintf("%v-two:latest", repoName))
<del> out, _, err := runCommandWithOutput(tagCmd)
<del> if err != nil {
<del> c.Fatalf("failed to tag repo: %s, %v", out, err)
<del> }
<add> dockerCmd(c, "tag", "emptyfs:latest", fmt.Sprintf("%v-two:latest", repoName))
<ide>
<del> out, _, err = runCommandPipelineWithOutput(
<add> out, _, err := runCommandPipelineWithOutput(
<ide> exec.Command(dockerBinary, "save", fmt.Sprintf("%v-one", repoName), fmt.Sprintf("%v-two:latest", repoName)),
<ide> exec.Command("tar", "xO", "repositories"),
<ide> exec.Command("grep", "-q", "-E", "(-one|-two)"),
<ide> )
<ide> if err != nil {
<ide> c.Fatalf("failed to save multiple repos: %s, %v", out, err)
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestSaveRepoWithMultipleImages(c *check.C) {
<ide>
<ide> makeImage := func(from string, tag string) string {
<del> runCmd := exec.Command(dockerBinary, "run", "-d", from, "true")
<ide> var (
<ide> out string
<del> err error
<ide> )
<del> if out, _, err = runCommandWithOutput(runCmd); err != nil {
<del> c.Fatalf("failed to create a container: %v %v", out, err)
<del> }
<add> out, _ = dockerCmd(c, "run", "-d", from, "true")
<ide> cleanedContainerID := strings.TrimSpace(out)
<ide>
<del> commitCmd := exec.Command(dockerBinary, "commit", cleanedContainerID, tag)
<del> if out, _, err = runCommandWithOutput(commitCmd); err != nil {
<del> c.Fatalf("failed to commit container: %v %v", out, err)
<del> }
<add> out, _ = dockerCmd(c, "commit", cleanedContainerID, tag)
<ide> imageID := strings.TrimSpace(out)
<ide> return imageID
<ide> }
<ide> func (s *DockerSuite) TestSaveRepoWithMultipleImages(c *check.C) {
<ide> actual := strings.Split(strings.TrimSpace(out), "\n")
<ide>
<ide> // make the list of expected layers
<del> out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "history", "-q", "--no-trunc", "busybox:latest"))
<del> if err != nil {
<del> c.Fatalf("failed to get history: %s, %v", out, err)
<del> }
<del>
<add> out, _ = dockerCmd(c, "history", "-q", "--no-trunc", "busybox:latest")
<ide> expected := append(strings.Split(strings.TrimSpace(out), "\n"), idFoo, idBar)
<ide>
<ide> sort.Strings(actual)
<ide> sort.Strings(expected)
<ide> if !reflect.DeepEqual(expected, actual) {
<ide> c.Fatalf("archive does not contains the right layers: got %v, expected %v", actual, expected)
<ide> }
<del>
<ide> }
<ide>
<ide> // Issue #6722 #5892 ensure directories are included in changes
<ide><path>integration-cli/docker_cli_save_load_unix_test.go
<ide> import (
<ide> // save a repo and try to load it using stdout
<ide> func (s *DockerSuite) TestSaveAndLoadRepoStdout(c *check.C) {
<ide> name := "test-save-and-load-repo-stdout"
<del> runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "true")
<del> out, _, err := runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatalf("failed to create a container: %s, %v", out, err)
<del> }
<add> dockerCmd(c, "run", "--name", name, "busybox", "true")
<ide>
<ide> repoName := "foobar-save-load-test"
<add> out, _ := dockerCmd(c, "commit", name, repoName)
<ide>
<del> commitCmd := exec.Command(dockerBinary, "commit", name, repoName)
<del> if out, _, err = runCommandWithOutput(commitCmd); err != nil {
<del> c.Fatalf("failed to commit container: %s, %v", out, err)
<del> }
<del>
<del> inspectCmd := exec.Command(dockerBinary, "inspect", repoName)
<del> before, _, err := runCommandWithOutput(inspectCmd)
<del> if err != nil {
<del> c.Fatalf("the repo should exist before saving it: %s, %v", before, err)
<del> }
<add> before, _ := dockerCmd(c, "inspect", repoName)
<ide>
<ide> tmpFile, err := ioutil.TempFile("", "foobar-save-load-test.tar")
<ide> c.Assert(err, check.IsNil)
<ide> func (s *DockerSuite) TestSaveAndLoadRepoStdout(c *check.C) {
<ide> c.Fatalf("failed to load repo: %s, %v", out, err)
<ide> }
<ide>
<del> inspectCmd = exec.Command(dockerBinary, "inspect", repoName)
<del> after, _, err := runCommandWithOutput(inspectCmd)
<del> if err != nil {
<del> c.Fatalf("the repo should exist after loading it: %s %v", after, err)
<del> }
<add> after, _ := dockerCmd(c, "inspect", repoName)
<ide>
<ide> if before != after {
<ide> c.Fatalf("inspect is not the same after a save / load")
<ide> func (s *DockerSuite) TestSaveAndLoadRepoStdout(c *check.C) {
<ide> if !bytes.Contains(buf[:n], []byte("Cowardly refusing")) {
<ide> c.Fatal("help output is not being yielded", out)
<ide> }
<del>
<ide> }
<ide><path>integration-cli/docker_cli_search_test.go
<ide> package main
<ide>
<ide> import (
<del> "os/exec"
<ide> "strings"
<ide>
<ide> "github.com/go-check/check"
<ide> import (
<ide> // search for repos named "registry" on the central registry
<ide> func (s *DockerSuite) TestSearchOnCentralRegistry(c *check.C) {
<ide> testRequires(c, Network)
<del> searchCmd := exec.Command(dockerBinary, "search", "busybox")
<del> out, exitCode, err := runCommandWithOutput(searchCmd)
<del> if err != nil || exitCode != 0 {
<del> c.Fatalf("failed to search on the central registry: %s, %v", out, err)
<add>
<add> out, exitCode := dockerCmd(c, "search", "busybox")
<add> if exitCode != 0 {
<add> c.Fatalf("failed to search on the central registry: %s", out)
<ide> }
<ide>
<ide> if !strings.Contains(out, "Busybox base image.") {
<ide> c.Fatal("couldn't find any repository named (or containing) 'Busybox base image.'")
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestSearchStarsOptionWithWrongParameter(c *check.C) {
<del> searchCmdStarsChars := exec.Command(dockerBinary, "search", "--stars=a", "busybox")
<del> out, exitCode, err := runCommandWithOutput(searchCmdStarsChars)
<add> out, exitCode, err := dockerCmdWithError(c, "search", "--stars=a", "busybox")
<ide> if err == nil || exitCode == 0 {
<ide> c.Fatalf("Should not get right information: %s, %v", out, err)
<ide> }
<ide> func (s *DockerSuite) TestSearchStarsOptionWithWrongParameter(c *check.C) {
<ide> c.Fatal("couldn't find the invalid value warning")
<ide> }
<ide>
<del> searchCmdStarsNegativeNumber := exec.Command(dockerBinary, "search", "-s=-1", "busybox")
<del> out, exitCode, err = runCommandWithOutput(searchCmdStarsNegativeNumber)
<add> out, exitCode, err = dockerCmdWithError(c, "search", "-s=-1", "busybox")
<ide> if err == nil || exitCode == 0 {
<ide> c.Fatalf("Should not get right information: %s, %v", out, err)
<ide> }
<ide>
<ide> if !strings.Contains(out, "invalid value") {
<ide> c.Fatal("couldn't find the invalid value warning")
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestSearchCmdOptions(c *check.C) {
<ide> testRequires(c, Network)
<del> searchCmdhelp := exec.Command(dockerBinary, "search", "--help")
<del> out, exitCode, err := runCommandWithOutput(searchCmdhelp)
<del> if err != nil || exitCode != 0 {
<del> c.Fatalf("failed to get search help information: %s, %v", out, err)
<add>
<add> out, exitCode := dockerCmd(c, "search", "--help")
<add> if exitCode != 0 {
<add> c.Fatalf("failed to get search help information: %s", out)
<ide> }
<ide>
<ide> if !strings.Contains(out, "Usage:\tdocker search [OPTIONS] TERM") {
<del> c.Fatalf("failed to show docker search usage: %s, %v", out, err)
<add> c.Fatalf("failed to show docker search usage: %s", out)
<ide> }
<ide>
<del> searchCmd := exec.Command(dockerBinary, "search", "busybox")
<del> outSearchCmd, exitCode, err := runCommandWithOutput(searchCmd)
<del> if err != nil || exitCode != 0 {
<del> c.Fatalf("failed to search on the central registry: %s, %v", outSearchCmd, err)
<add> outSearchCmd, exitCode := dockerCmd(c, "search", "busybox")
<add> if exitCode != 0 {
<add> c.Fatalf("failed to search on the central registry: %s", outSearchCmd)
<ide> }
<ide>
<del> searchCmdNotrunc := exec.Command(dockerBinary, "search", "--no-trunc=true", "busybox")
<del> outSearchCmdNotrunc, _, err := runCommandWithOutput(searchCmdNotrunc)
<del> if err != nil {
<del> c.Fatalf("failed to search on the central registry: %s, %v", outSearchCmdNotrunc, err)
<del> }
<add> outSearchCmdNotrunc, _ := dockerCmd(c, "search", "--no-trunc=true", "busybox")
<ide>
<ide> if len(outSearchCmd) > len(outSearchCmdNotrunc) {
<ide> c.Fatalf("The no-trunc option can't take effect.")
<ide> }
<ide>
<del> searchCmdautomated := exec.Command(dockerBinary, "search", "--automated=true", "busybox")
<del> outSearchCmdautomated, exitCode, err := runCommandWithOutput(searchCmdautomated) //The busybox is a busybox base image, not an AUTOMATED image.
<del> if err != nil || exitCode != 0 {
<del> c.Fatalf("failed to search with automated=true on the central registry: %s, %v", outSearchCmdautomated, err)
<add> outSearchCmdautomated, exitCode := dockerCmd(c, "search", "--automated=true", "busybox") //The busybox is a busybox base image, not an AUTOMATED image.
<add> if exitCode != 0 {
<add> c.Fatalf("failed to search with automated=true on the central registry: %s", outSearchCmdautomated)
<ide> }
<ide>
<ide> outSearchCmdautomatedSlice := strings.Split(outSearchCmdautomated, "\n")
<ide> for i := range outSearchCmdautomatedSlice {
<ide> if strings.HasPrefix(outSearchCmdautomatedSlice[i], "busybox ") {
<del> c.Fatalf("The busybox is not an AUTOMATED image: %s, %v", out, err)
<add> c.Fatalf("The busybox is not an AUTOMATED image: %s", out)
<ide> }
<ide> }
<ide>
<del> searchCmdStars := exec.Command(dockerBinary, "search", "-s=2", "busybox")
<del> outSearchCmdStars, exitCode, err := runCommandWithOutput(searchCmdStars)
<del> if err != nil || exitCode != 0 {
<del> c.Fatalf("failed to search with stars=2 on the central registry: %s, %v", outSearchCmdStars, err)
<add> outSearchCmdStars, exitCode := dockerCmd(c, "search", "-s=2", "busybox")
<add> if exitCode != 0 {
<add> c.Fatalf("failed to search with stars=2 on the central registry: %s", outSearchCmdStars)
<ide> }
<ide>
<ide> if strings.Count(outSearchCmdStars, "[OK]") > strings.Count(outSearchCmd, "[OK]") {
<del> c.Fatalf("The quantity of images with stars should be less than that of all images: %s, %v", outSearchCmdStars, err)
<add> c.Fatalf("The quantity of images with stars should be less than that of all images: %s", outSearchCmdStars)
<ide> }
<ide>
<del> searchCmdOptions := exec.Command(dockerBinary, "search", "--stars=2", "--automated=true", "--no-trunc=true", "busybox")
<del> out, exitCode, err = runCommandWithOutput(searchCmdOptions)
<del> if err != nil || exitCode != 0 {
<del> c.Fatalf("failed to search with stars&automated&no-trunc options on the central registry: %s, %v", out, err)
<add> out, exitCode = dockerCmd(c, "search", "--stars=2", "--automated=true", "--no-trunc=true", "busybox")
<add> if exitCode != 0 {
<add> c.Fatalf("failed to search with stars&automated&no-trunc options on the central registry: %s", out)
<ide> }
<del>
<ide> }
<ide><path>integration-cli/docker_cli_service_test.go
<ide> package main
<ide>
<ide> import (
<ide> "fmt"
<del> "os/exec"
<ide> "strings"
<ide>
<ide> "github.com/go-check/check"
<ide> func assertSrvNotAvailable(c *check.C, sname, name string) {
<ide> }
<ide>
<ide> func isSrvPresent(c *check.C, sname, name string) bool {
<del> runCmd := exec.Command(dockerBinary, "service", "ls")
<del> out, _, _, err := runCommandWithStdoutStderr(runCmd)
<del> c.Assert(err, check.IsNil)
<add> out, _, _ := dockerCmdWithStdoutStderr(c, "service", "ls")
<ide> lines := strings.Split(out, "\n")
<ide> for i := 1; i < len(lines)-1; i++ {
<ide> if strings.Contains(lines[i], sname) && strings.Contains(lines[i], name) {
<ide> func isSrvPresent(c *check.C, sname, name string) bool {
<ide> }
<ide>
<ide> func isCntPresent(c *check.C, cname, sname, name string) bool {
<del> runCmd := exec.Command(dockerBinary, "service", "ls", "--no-trunc")
<del> out, _, _, err := runCommandWithStdoutStderr(runCmd)
<del> c.Assert(err, check.IsNil)
<add> out, _, _ := dockerCmdWithStdoutStderr(c, "service", "ls", "--no-trunc")
<ide> lines := strings.Split(out, "\n")
<ide> for i := 1; i < len(lines)-1; i++ {
<ide> fmt.Println(lines)
<ide> func isCntPresent(c *check.C, cname, sname, name string) bool {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestDockerServiceCreateDelete(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "network", "create", "test")
<del> _, _, _, err := runCommandWithStdoutStderr(runCmd)
<del> c.Assert(err, check.IsNil)
<add> dockerCmdWithStdoutStderr(c, "network", "create", "test")
<ide> assertNwIsAvailable(c, "test")
<ide>
<del> runCmd = exec.Command(dockerBinary, "service", "publish", "s1.test")
<del> _, _, _, err = runCommandWithStdoutStderr(runCmd)
<del> c.Assert(err, check.IsNil)
<add> dockerCmdWithStdoutStderr(c, "service", "publish", "s1.test")
<ide> assertSrvIsAvailable(c, "s1", "test")
<ide>
<del> runCmd = exec.Command(dockerBinary, "service", "unpublish", "s1.test")
<del> _, _, _, err = runCommandWithStdoutStderr(runCmd)
<del> c.Assert(err, check.IsNil)
<add> dockerCmdWithStdoutStderr(c, "service", "unpublish", "s1.test")
<ide> assertSrvNotAvailable(c, "s1", "test")
<ide>
<del> runCmd = exec.Command(dockerBinary, "network", "rm", "test")
<del> _, _, _, err = runCommandWithStdoutStderr(runCmd)
<del> c.Assert(err, check.IsNil)
<add> dockerCmdWithStdoutStderr(c, "network", "rm", "test")
<ide> assertNwNotAvailable(c, "test")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestDockerPublishServiceFlag(c *check.C) {
<ide> // Run saying the container is the backend for the specified service on the specified network
<del> runCmd := exec.Command(dockerBinary, "run", "-d", "--expose=23", "--publish-service", "telnet.production", "busybox", "top")
<del> out, _, err := runCommandWithOutput(runCmd)
<del> c.Assert(err, check.IsNil)
<add> out, _ := dockerCmd(c, "run", "-d", "--expose=23", "--publish-service", "telnet.production", "busybox", "top")
<ide> cid := strings.TrimSpace(out)
<ide>
<ide> // Verify container is attached in service ps o/p
<ide> assertSrvIsAvailable(c, "telnet", "production")
<del> runCmd = exec.Command(dockerBinary, "rm", "-f", cid)
<del> out, _, err = runCommandWithOutput(runCmd)
<del> c.Assert(err, check.IsNil)
<add> dockerCmd(c, "rm", "-f", cid)
<ide> }
<ide><path>integration-cli/docker_cli_start_test.go
<ide> package main
<ide>
<ide> import (
<ide> "fmt"
<del> "os/exec"
<ide> "strings"
<ide> "time"
<ide>
<ide> import (
<ide>
<ide> // Regression test for https://github.com/docker/docker/issues/7843
<ide> func (s *DockerSuite) TestStartAttachReturnsOnError(c *check.C) {
<del>
<ide> dockerCmd(c, "run", "-d", "--name", "test", "busybox")
<ide> dockerCmd(c, "wait", "test")
<ide>
<ide> // Expect this to fail because the above container is stopped, this is what we want
<del> if _, err := runCommand(exec.Command(dockerBinary, "run", "-d", "--name", "test2", "--link", "test:test", "busybox")); err == nil {
<add> if _, _, err := dockerCmdWithError(c, "run", "-d", "--name", "test2", "--link", "test:test", "busybox"); err == nil {
<ide> c.Fatal("Expected error but got none")
<ide> }
<ide>
<ide> ch := make(chan error)
<ide> go func() {
<ide> // Attempt to start attached to the container that won't start
<ide> // This should return an error immediately since the container can't be started
<del> if _, err := runCommand(exec.Command(dockerBinary, "start", "-a", "test2")); err == nil {
<add> if _, _, err := dockerCmdWithError(c, "start", "-a", "test2"); err == nil {
<ide> ch <- fmt.Errorf("Expected error but got none")
<ide> }
<ide> close(ch)
<ide> func (s *DockerSuite) TestStartAttachReturnsOnError(c *check.C) {
<ide> case <-time.After(time.Second):
<ide> c.Fatalf("Attach did not exit properly")
<ide> }
<del>
<ide> }
<ide>
<ide> // gh#8555: Exit code should be passed through when using start -a
<ide> func (s *DockerSuite) TestStartAttachCorrectExitCode(c *check.C) {
<del>
<del> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sh", "-c", "sleep 2; exit 1")
<del> out, _, _, err := runCommandWithStdoutStderr(runCmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<del>
<add> out, _, _ := dockerCmdWithStdoutStderr(c, "run", "-d", "busybox", "sh", "-c", "sleep 2; exit 1")
<ide> out = strings.TrimSpace(out)
<ide>
<ide> // make sure the container has exited before trying the "start -a"
<del> waitCmd := exec.Command(dockerBinary, "wait", out)
<del> if _, _, err = runCommandWithOutput(waitCmd); err != nil {
<del> c.Fatalf("Failed to wait on container: %v", err)
<del> }
<add> dockerCmd(c, "wait", out)
<ide>
<del> startCmd := exec.Command(dockerBinary, "start", "-a", out)
<del> startOut, exitCode, err := runCommandWithOutput(startCmd)
<add> startOut, exitCode, err := dockerCmdWithError(c, "start", "-a", out)
<ide> if err != nil && !strings.Contains("exit status 1", fmt.Sprintf("%s", err)) {
<ide> c.Fatalf("start command failed unexpectedly with error: %v, output: %q", err, startOut)
<ide> }
<ide> func (s *DockerSuite) TestStartAttachCorrectExitCode(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestStartAttachSilent(c *check.C) {
<del>
<ide> name := "teststartattachcorrectexitcode"
<del> runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "echo", "test")
<del> out, _, _, err := runCommandWithStdoutStderr(runCmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<add> dockerCmd(c, "run", "--name", name, "busybox", "echo", "test")
<ide>
<ide> // make sure the container has exited before trying the "start -a"
<del> waitCmd := exec.Command(dockerBinary, "wait", name)
<del> if _, _, err = runCommandWithOutput(waitCmd); err != nil {
<del> c.Fatalf("wait command failed with error: %v", err)
<del> }
<add> dockerCmd(c, "wait", name)
<ide>
<del> startCmd := exec.Command(dockerBinary, "start", "-a", name)
<del> startOut, _, err := runCommandWithOutput(startCmd)
<del> if err != nil {
<del> c.Fatalf("start command failed unexpectedly with error: %v, output: %q", err, startOut)
<del> }
<add> startOut, _ := dockerCmd(c, "start", "-a", name)
<ide> if expected := "test\n"; startOut != expected {
<ide> c.Fatalf("start -a produced unexpected output: expected %q, got %q", expected, startOut)
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestStartRecordError(c *check.C) {
<ide> func (s *DockerSuite) TestStartRecordError(c *check.C) {
<ide> }
<ide>
<ide> // Expect this to fail and records error because of ports conflict
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", "test2", "-p", "9999:9999", "busybox", "top"))
<add> out, _, err := dockerCmdWithError(c, "run", "-d", "--name", "test2", "-p", "9999:9999", "busybox", "top")
<ide> if err == nil {
<ide> c.Fatalf("Expected error but got none, output %q", out)
<ide> }
<add>
<ide> stateErr, err = inspectField("test2", "State.Error")
<ide> c.Assert(err, check.IsNil)
<ide> expected := "port is already allocated"
<ide> func (s *DockerSuite) TestStartRecordError(c *check.C) {
<ide> if stateErr != "" {
<ide> c.Fatalf("Expected to not have state error but got state.Error(%q)", stateErr)
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestStartPausedContainer(c *check.C) {
<ide> defer unpauseAllContainers()
<ide>
<del> runCmd := exec.Command(dockerBinary, "run", "-d", "--name", "testing", "busybox", "top")
<del> if out, _, err := runCommandWithOutput(runCmd); err != nil {
<del> c.Fatal(out, err)
<del> }
<add> dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top")
<ide>
<del> runCmd = exec.Command(dockerBinary, "pause", "testing")
<del> if out, _, err := runCommandWithOutput(runCmd); err != nil {
<del> c.Fatal(out, err)
<del> }
<add> dockerCmd(c, "pause", "testing")
<ide>
<del> runCmd = exec.Command(dockerBinary, "start", "testing")
<del> if out, _, err := runCommandWithOutput(runCmd); err == nil || !strings.Contains(out, "Cannot start a paused container, try unpause instead.") {
<add> if out, _, err := dockerCmdWithError(c, "start", "testing"); err == nil || !strings.Contains(out, "Cannot start a paused container, try unpause instead.") {
<ide> c.Fatalf("an error should have been shown that you cannot start paused container: %s\n%v", out, err)
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestStartMultipleContainers(c *check.C) {
<ide> // run a container named 'parent' and create two container link to `parent`
<del> cmd := exec.Command(dockerBinary, "run", "-d", "--name", "parent", "busybox", "top")
<del> if out, _, err := runCommandWithOutput(cmd); err != nil {
<del> c.Fatal(out, err)
<del> }
<add> dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top")
<add>
<ide> for _, container := range []string{"child_first", "child_second"} {
<del> cmd = exec.Command(dockerBinary, "create", "--name", container, "--link", "parent:parent", "busybox", "top")
<del> if out, _, err := runCommandWithOutput(cmd); err != nil {
<del> c.Fatal(out, err)
<del> }
<add> dockerCmd(c, "create", "--name", container, "--link", "parent:parent", "busybox", "top")
<ide> }
<ide>
<ide> // stop 'parent' container
<del> cmd = exec.Command(dockerBinary, "stop", "parent")
<del> if out, _, err := runCommandWithOutput(cmd); err != nil {
<del> c.Fatal(out, err)
<del> }
<add> dockerCmd(c, "stop", "parent")
<add>
<ide> out, err := inspectField("parent", "State.Running")
<ide> c.Assert(err, check.IsNil)
<ide> if out != "false" {
<ide> func (s *DockerSuite) TestStartMultipleContainers(c *check.C) {
<ide>
<ide> // start all the three containers, container `child_first` start first which should be failed
<ide> // container 'parent' start second and then start container 'child_second'
<del> cmd = exec.Command(dockerBinary, "start", "child_first", "parent", "child_second")
<del> out, _, err = runCommandWithOutput(cmd)
<add> out, _, err = dockerCmdWithError(c, "start", "child_first", "parent", "child_second")
<ide> if !strings.Contains(out, "Cannot start container child_first") || err == nil {
<ide> c.Fatal("Expected error but got none")
<ide> }
<ide> func (s *DockerSuite) TestStartMultipleContainers(c *check.C) {
<ide> }
<ide>
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestStartAttachMultipleContainers(c *check.C) {
<del>
<del> var cmd *exec.Cmd
<del>
<ide> // run multiple containers to test
<ide> for _, container := range []string{"test1", "test2", "test3"} {
<del> cmd = exec.Command(dockerBinary, "run", "-d", "--name", container, "busybox", "top")
<del> if out, _, err := runCommandWithOutput(cmd); err != nil {
<del> c.Fatal(out, err)
<del> }
<add> dockerCmd(c, "run", "-d", "--name", container, "busybox", "top")
<ide> }
<ide>
<ide> // stop all the containers
<ide> for _, container := range []string{"test1", "test2", "test3"} {
<del> cmd = exec.Command(dockerBinary, "stop", container)
<del> if out, _, err := runCommandWithOutput(cmd); err != nil {
<del> c.Fatal(out, err)
<del> }
<add> dockerCmd(c, "stop", container)
<ide> }
<ide>
<ide> // test start and attach multiple containers at once, expected error
<ide> for _, option := range []string{"-a", "-i", "-ai"} {
<del> cmd = exec.Command(dockerBinary, "start", option, "test1", "test2", "test3")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "start", option, "test1", "test2", "test3")
<ide> if !strings.Contains(out, "You cannot start and attach multiple containers at once.") || err == nil {
<ide> c.Fatal("Expected error but got none")
<ide> }
<ide> func (s *DockerSuite) TestStartAttachMultipleContainers(c *check.C) {
<ide> c.Fatal("Container running state wrong")
<ide> }
<ide> }
<del>
<ide> } | 6 |
Java | Java | add more test cases for simplealiasregistry | 345d8186d4a2153e20a2e13c21ea8686987a0031 | <ide><path>spring-core/src/test/java/org/springframework/core/SimpleAliasRegistryTests.java
<ide> void aliasChainingWithMultipleAliases() {
<ide> assertThat(registry.hasAlias("real_name", "alias_c")).isTrue();
<ide> }
<ide>
<add> @Test
<add> void removeAliasTest() {
<add> SimpleAliasRegistry registry = new SimpleAliasRegistry();
<add> registry.registerAlias("realname", "nickname");
<add> assertThat(registry.hasAlias("realname", "nickname")).isTrue();
<add>
<add> registry.removeAlias("nickname");
<add> assertThat(registry.hasAlias("realname", "nickname")).isFalse();
<add> }
<add>
<add> @Test
<add> void isAliasTest() {
<add> SimpleAliasRegistry registry = new SimpleAliasRegistry();
<add> registry.registerAlias("realname", "nickname");
<add> assertThat(registry.isAlias("nickname")).isTrue();
<add> assertThat(registry.isAlias("fake")).isFalse();
<add> }
<add>
<add> @Test
<add> void getAliasesTest() {
<add> SimpleAliasRegistry registry = new SimpleAliasRegistry();
<add> registry.registerAlias("realname", "nickname");
<add> assertThat(registry.getAliases("realname"));
<add> }
<ide> } | 1 |
Python | Python | add ticks to quantile interpolation/method error | 5bd71fb76c68f41debe3a15fbf316ce6ef7fd795 | <ide><path>numpy/lib/function_base.py
<ide> def _check_interpolation_as_method(method, interpolation, fname):
<ide> # sanity check, we assume this basically never happens
<ide> raise TypeError(
<ide> "You shall not pass both `method` and `interpolation`!\n"
<del> "(`interpolation` is Deprecated in favor of method)")
<add> "(`interpolation` is Deprecated in favor of `method`)")
<ide> return interpolation
<ide>
<ide> | 1 |
PHP | PHP | whitespace coding standards | c989624f8053f28d2ac37f5e84dc436965235177 | <ide><path>lib/Cake/Controller/Component/Auth/BlowfishAuthenticate.php
<ide> * For initial password hashing/creation see Security::hash(). Other than how the password is initially hashed,
<ide> * BlowfishAuthenticate works exactly the same way as FormAuthenticate.
<ide> *
<del> * @package Cake.Controller.Component.Auth
<del> * @since CakePHP(tm) v 2.3
<del> * @see AuthComponent::$authenticate
<add> * @package Cake.Controller.Component.Auth
<add> * @since CakePHP(tm) v 2.3
<add> * @see AuthComponent::$authenticate
<ide> */
<ide> class BlowfishAuthenticate extends FormAuthenticate {
<ide>
<ide><path>lib/Cake/Core/Object.php
<ide> public function requestAction($url, $extra = array()) {
<ide> *
<ide> * @param string $method Name of the method to call
<ide> * @param array $params Parameter list to use when calling $method
<del> * @return mixed Returns the result of the method call
<add> * @return mixed Returns the result of the method call
<ide> */
<ide> public function dispatchMethod($method, $params = array()) {
<ide> switch (count($params)) {
<ide><path>lib/Cake/Model/Behavior/ContainableBehavior.php
<ide> public function setup(Model $Model, $settings = array()) {
<ide> * )));
<ide> * }}}
<ide> *
<del> * @param Model $Model Model using the behavior
<add> * @param Model $Model Model using the behavior
<ide> * @param array $query Query parameters as set by cake
<ide> * @return array
<ide> */
<ide><path>lib/Cake/Model/Behavior/TreeBehavior.php
<ide> public function afterSave(Model $Model, $created) {
<ide> /**
<ide> * Runs before a find() operation
<ide> *
<del> * @param Model $Model Model using the behavior
<add> * @param Model $Model Model using the behavior
<ide> * @param array $query Query parameters as set by cake
<ide> * @return array
<ide> */
<ide><path>lib/Cake/Model/Datasource/Database/Postgres.php
<ide> public function resetSequence($table, $column) {
<ide> * @param string|Model $table A string or model class representing the table to be truncated
<ide> * @param boolean $reset true for resetting the sequence, false to leave it as is.
<ide> * and if 1, sequences are not modified
<del> * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
<add> * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
<ide> */
<ide> public function truncate($table, $reset = false) {
<ide> $table = $this->fullTableName($table, false, false);
<ide><path>lib/Cake/Model/Datasource/Database/Sqlite.php
<ide> public function update(Model $model, $fields = array(), $values = null, $conditi
<ide> * primary key, where applicable.
<ide> *
<ide> * @param string|Model $table A string or model class representing the table to be truncated
<del> * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
<add> * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
<ide> */
<ide> public function truncate($table) {
<ide> $this->_execute('DELETE FROM sqlite_sequence where name=' . $this->startQuote . $this->fullTableName($table, false, false) . $this->endQuote);
<ide><path>lib/Cake/Model/Datasource/DboSource.php
<ide> public function calculate(Model $model, $func, $params = array()) {
<ide> * primary key, where applicable.
<ide> *
<ide> * @param Model|string $table A string or model class representing the table to be truncated
<del> * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
<add> * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
<ide> */
<ide> public function truncate($table) {
<ide> return $this->execute('TRUNCATE TABLE ' . $this->fullTableName($table));
<ide><path>lib/Cake/TestSuite/CakeTestCase.php
<ide> abstract class CakeTestCase extends PHPUnit_Framework_TestCase {
<ide> * If no TestResult object is passed a new one will be created.
<ide> * This method is run for each test method in this class
<ide> *
<del> * @param PHPUnit_Framework_TestResult $result
<add> * @param PHPUnit_Framework_TestResult $result
<ide> * @return PHPUnit_Framework_TestResult
<ide> * @throws InvalidArgumentException
<ide> */
<ide><path>lib/Cake/TestSuite/Reporter/CakeHtmlReporter.php
<ide> protected function _getStackTrace(Exception $e) {
<ide> /**
<ide> * A test suite started.
<ide> *
<del> * @param PHPUnit_Framework_TestSuite $suite
<add> * @param PHPUnit_Framework_TestSuite $suite
<add> * @return void
<ide> */
<ide> public function startTestSuite(PHPUnit_Framework_TestSuite $suite) {
<ide> if (!$this->_headerSent) {
<ide><path>lib/Cake/Utility/CakeNumber.php
<ide> public static function addFormat($formatName, $options) {
<ide> /**
<ide> * Getter/setter for default currency
<ide> *
<del> * @param string $currency Default currency string used by currency() if $currency argument is not provided
<add> * @param string $currency Default currency string used by currency() if $currency argument is not provided
<ide> * @return string Currency
<ide> */
<ide> public static function defaultCurrency($currency = null) {
<ide><path>lib/Cake/Utility/ClassRegistry.php
<ide> public static function init($class, $strict = false) {
<ide> /**
<ide> * Add $object to the registry, associating it with the name $key.
<ide> *
<del> * @param string $key Key for the object in registry
<del> * @param object $object Object to store
<add> * @param string $key Key for the object in registry
<add> * @param object $object Object to store
<ide> * @return boolean True if the object was written, false if $key already exists
<ide> */
<ide> public static function addObject($key, $object) {
<ide> public static function addObject($key, $object) {
<ide> /**
<ide> * Remove object which corresponds to given key.
<ide> *
<del> * @param string $key Key of object to remove from registry
<add> * @param string $key Key of object to remove from registry
<ide> * @return void
<ide> */
<ide> public static function removeObject($key) {
<ide><path>lib/Cake/View/Helper.php
<ide> public function __set($name, $value) {
<ide> * an array of url parameters. Using an array for URLs will allow you to leverage
<ide> * the reverse routing features of CakePHP.
<ide> * @param boolean $full If true, the full base URL will be prepended to the result
<del> * @return string Full translated URL with base path.
<add> * @return string Full translated URL with base path.
<ide> * @link http://book.cakephp.org/2.0/en/views/helpers.html
<ide> */
<ide> public function url($url = null, $full = false) {
<ide><path>lib/Cake/View/Helper/FormHelper.php
<ide> public function isFieldError($field) {
<ide> *
<ide> * ### Options:
<ide> *
<del> * - `escape` bool Whether or not to html escape the contents of the error.
<del> * - `wrap` mixed Whether or not the error message should be wrapped in a div. If a
<add> * - `escape` bool - Whether or not to html escape the contents of the error.
<add> * - `wrap` mixed - Whether or not the error message should be wrapped in a div. If a
<ide> * string, will be used as the HTML tag to use.
<del> * - `class` string The classname for the error message
<add> * - `class` string - The classname for the error message
<ide> *
<ide> * @param string $field A field name, like "Modelname.fieldname"
<ide> * @param string|array $text Error message as string or array of messages.
<del> * If array contains `attributes` key it will be used as options for error container
<add> * If array contains `attributes` key it will be used as options for error container
<ide> * @param array $options Rendering options for <div /> wrapper tag
<ide> * @return string If there are errors this method returns an error message, otherwise null.
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::error
<ide><path>lib/Cake/View/Helper/NumberHelper.php
<ide> public function __call($method, $params) {
<ide> /**
<ide> * @see CakeNumber::precision()
<ide> *
<del> * @param float $number A floating point number.
<add> * @param float $number A floating point number.
<ide> * @param integer $precision The precision of the returned number.
<ide> * @return float Formatted float.
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::precision
<ide><path>lib/Cake/basics.php
<ide> function pluginSplit($name, $dotAppend = false, $plugin = null) {
<ide> * Print_r convenience function, which prints out <PRE> tags around
<ide> * the output of given array. Similar to debug().
<ide> *
<del> * @see debug()
<add> * @see debug()
<ide> * @param array $var Variable to print out
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#pr
<ide> */
<ide> function am() {
<ide> * IIS, or SCRIPT_NAME in CGI mode). Also exposes some additional custom
<ide> * environment information.
<ide> *
<del> * @param string $key Environment variable name.
<add> * @param string $key Environment variable name.
<ide> * @return string Environment variable setting.
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#env
<ide> */
<ide> function env($key) {
<ide> /**
<ide> * Reads/writes temporary data to cache files or session.
<ide> *
<del> * @param string $path File path within /tmp to save the file.
<del> * @param mixed $data The data to save to the temporary file.
<del> * @param mixed $expires A valid strtotime string when the data expires.
<del> * @param string $target The target of the cached data; either 'cache' or 'public'.
<del> * @return mixed The contents of the temporary file.
<add> * @param string $path File path within /tmp to save the file.
<add> * @param mixed $data The data to save to the temporary file.
<add> * @param mixed $expires A valid strtotime string when the data expires.
<add> * @param string $target The target of the cached data; either 'cache' or 'public'.
<add> * @return mixed The contents of the temporary file.
<ide> * @deprecated Please use Cache::write() instead
<ide> */
<ide> function cache($path, $data = null, $expires = '+1 day', $target = 'cache') { | 15 |
Ruby | Ruby | fix uses_from_macos_elements tests | 3e15023269326bb9c34ca63e360f3178983f7376 | <ide><path>Library/Homebrew/test/os/mac/formula_spec.rb
<ide>
<ide> expect(f.class.stable.deps.first.name).to eq("foo")
<ide> expect(f.class.head.deps.first.name).to eq("foo")
<del> expect(f.class.stable.uses_from_macos_elements).to be_empty
<del> expect(f.class.head.uses_from_macos_elements).to be_empty
<add> expect(f.class.stable.uses_from_macos_elements).to eq(["foo"])
<add> expect(f.class.head.uses_from_macos_elements).to eq(["foo"])
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/test/os/mac/software_spec_spec.rb
<ide> spec.uses_from_macos("foo", since: :high_sierra)
<ide>
<ide> expect(spec.deps.first.name).to eq("foo")
<del> expect(spec.uses_from_macos_elements).to be_empty
<add> expect(spec.uses_from_macos_elements).to eq(["foo"])
<ide> end
<ide>
<ide> it "works with tags" do | 2 |
Text | Text | provide password to volume create command | d9e5f7d8f7a749c36f8694852340aa136b9c29f5 | <ide><path>docs/extend/index.md
<ide> operation, such as creating a volume.
<ide> In the following example, you install the `sshfs` plugin, verify that it is
<ide> enabled, and use it to create a volume.
<ide>
<add>> **Note**: This example is intended for instructional purposes only. Once the volume is created, your SSH password to the remote host will be exposed as plaintext when inspecting the volume. You should delete the volume as soon as you are done with the example.
<add>
<ide> 1. Install the `sshfs` plugin.
<ide>
<ide> ```bash
<ide> enabled, and use it to create a volume.
<ide>
<ide> 3. Create a volume using the plugin.
<ide> This example mounts the `/remote` directory on host `1.2.3.4` into a
<del> volume named `sshvolume`. This volume can now be mounted into containers.
<add> volume named `sshvolume`.
<add>
<add> This volume can now be mounted into containers.
<ide>
<ide> ```bash
<ide> $ docker volume create \
<ide> -d vieux/sshfs \
<ide> --name sshvolume \
<del> -o [email protected]:/remote
<add> -o [email protected]:/remote \
<add> -o password=$(cat file_containing_password_for_remote_host)
<ide>
<ide> sshvolume
<ide> ```
<ide> enabled, and use it to create a volume.
<ide> 5. Start a container that uses the volume `sshvolume`.
<ide>
<ide> ```bash
<del> $ docker run -v sshvolume:/data busybox ls /data
<add> $ docker run --rm -v sshvolume:/data busybox ls /data
<ide>
<ide> <content of /remote on machine 1.2.3.4>
<ide> ```
<ide>
<add>6. Remove the volume `sshvolume`
<add> ```bash
<add> docker volume rm sshvolume
<add>
<add> sshvolume
<add> ```
<ide> To disable a plugin, use the `docker plugin disable` command. To completely
<ide> remove it, use the `docker plugin remove` command. For other available
<ide> commands and options, see the
<ide> in subdirectory `rootfs`.
<ide>
<ide> After that the plugin `<plugin-name>` will show up in `docker plugin ls`.
<ide> Plugins can be pushed to remote registries with
<del>`docker plugin push <plugin-name>`.
<ide>\ No newline at end of file
<add>`docker plugin push <plugin-name>`. | 1 |
Ruby | Ruby | remove usafe of respond_to in actionview tests | 2b0c602bc3dd2928b8a77465f305c765dbb447e5 | <ide><path>actionview/test/activerecord/controller_runtime_test.rb
<ide>
<ide> class ControllerRuntimeLogSubscriberTest < ActionController::TestCase
<ide> class LogSubscriberController < ActionController::Base
<del> respond_to :html
<del>
<ide> def show
<ide> render :inline => "<%= Project.all %>"
<ide> end
<ide> def zero
<ide> def create
<ide> ActiveRecord::LogSubscriber.runtime += 100
<ide> project = Project.last
<del> respond_with(project, location: url_for(action: :show))
<add> redirect_to "/"
<ide> end
<ide>
<ide> def redirect | 1 |
PHP | PHP | add `@componentfirst` directive | 8663082e67513d2ba1b7f0fbe868520d0bff67e8 | <ide><path>src/Illuminate/View/Compilers/Concerns/CompilesComponents.php
<ide> protected function compileEndSlot()
<ide> {
<ide> return '<?php $__env->endSlot(); ?>';
<ide> }
<add>
<add> /**
<add> * Compile the component-first statements into valid PHP.
<add> *
<add> * @param string $expression
<add> * @return string
<add> */
<add> protected function compileComponentFirst($expression)
<add> {
<add> return "<?php \$__env->startComponentFirst{$expression}; ?>";
<add> }
<ide> }
<ide><path>src/Illuminate/View/Concerns/ManagesComponents.php
<ide>
<ide> namespace Illuminate\View\Concerns;
<ide>
<add>use Illuminate\Support\Arr;
<ide> use Illuminate\Support\HtmlString;
<ide>
<ide> trait ManagesComponents
<ide> public function startComponent($name, array $data = [])
<ide> }
<ide> }
<ide>
<add> /**
<add> * Get the first view that actually exists from the given list, and start a component.
<add> *
<add> * @param array $names
<add> * @param array $data
<add> * @return void
<add> */
<add> public function startComponentFirst(array $names, array $data = [])
<add> {
<add> $name = Arr::first($names, function ($item) {
<add> return $this->exists($item);
<add> });
<add>
<add> $this->startComponent($name, $data);
<add> }
<add>
<ide> /**
<ide> * Render the current component.
<ide> *
<ide><path>tests/View/Blade/BladeComponentFirstTest.php
<add><?php
<add>
<add>namespace Illuminate\Tests\View\Blade;
<add>
<add>class BladeComponentFirstTest extends AbstractBladeTestCase
<add>{
<add> public function testComponentFirstsAreCompiled()
<add> {
<add> $this->assertEquals('<?php $__env->startComponentFirst(["one", "two"]); ?>', $this->compiler->compileString('@componentFirst(["one", "two"])'));
<add> $this->assertEquals('<?php $__env->startComponentFirst(["one", "two"], ["foo" => "bar"]); ?>', $this->compiler->compileString('@componentFirst(["one", "two"], ["foo" => "bar"])'));
<add> }
<add>} | 3 |
Javascript | Javascript | improve clarity and consistency | 8e2f7d37e492524696c9122fe1346bfe04ec0f24 | <ide><path>src/ng/rootScope.js
<ide> * exposed as $$____ properties
<ide> *
<ide> * Loop operations are optimized by using while(count--) { ... }
<del> * - this means that in order to keep the same order of execution as addition we have to add
<add> * - This means that in order to keep the same order of execution as addition we have to add
<ide> * items to the array at the beginning (unshift) instead of at the end (push)
<ide> *
<ide> * Child scopes are created and removed often
<del> * - Using an array would be slow since inserts in middle are expensive so we use linked list
<add> * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
<ide> *
<del> * There are few watches then a lot of observers. This is why you don't want the observer to be
<del> * implemented in the same way as watch. Watch requires return of initialization function which
<del> * are expensive to construct.
<add> * There are fewer watches than observers. This is why you don't want the observer to be implemented
<add> * in the same way as watch. Watch requires return of the initialization function which is expensive
<add> * to construct.
<ide> */
<ide>
<ide>
<ide> * Every application has a single root {@link ng.$rootScope.Scope scope}.
<ide> * All other scopes are descendant scopes of the root scope. Scopes provide separation
<ide> * between the model and the view, via a mechanism for watching the model for changes.
<del> * They also provide an event emission/broadcast and subscription facility. See the
<add> * They also provide event emission/broadcast and subscription facility. See the
<ide> * {@link guide/scope developer guide on scopes}.
<ide> */
<ide> function $RootScopeProvider() { | 1 |
Text | Text | add documentation for the 'timeout' event | 784cdad7407555bbffebc97e75866dc9a8a04106 | <ide><path>doc/api/http.md
<ide> added: v0.5.3
<ide>
<ide> Emitted after a socket is assigned to this request.
<ide>
<add>### Event: 'timeout'
<add><!-- YAML
<add>added: v0.7.8
<add>-->
<add>
<add>Emitted when the underlying socket times out from inactivity. This only notifies
<add>that the socket has been idle. The request must be aborted manually.
<add>
<add>See also: [`request.setTimeout()`][]
<add>
<ide> ### Event: 'upgrade'
<ide> <!-- YAML
<ide> added: v0.1.94
<ide> const req = http.request(options, (res) => {
<ide> [`net.createConnection()`]: net.html#net_net_createconnection_options_connectlistener
<ide> [`removeHeader(name)`]: #requestremoveheadername
<ide> [`request.end()`]: #http_request_end_data_encoding_callback
<add>[`request.setTimeout()`]: #http_request_settimeout_timeout_callback
<ide> [`request.socket`]: #http_request_socket
<ide> [`request.socket.getPeerCertificate()`]: tls.html#tls_tlssocket_getpeercertificate_detailed
<ide> [`request.write(data, encoding)`]: #http_request_write_chunk_encoding_callback | 1 |
Mixed | Javascript | use minimal object inspection with %s specifier | a9bf6652b5353f2098d4c0cd0eb77d17e02e164d | <ide><path>doc/api/util.md
<ide> as a `printf`-like format string which can contain zero or more format
<ide> specifiers. Each specifier is replaced with the converted value from the
<ide> corresponding argument. Supported specifiers are:
<ide>
<del>* `%s` - `String`.
<del>* `%d` - `Number` (integer or floating point value) or `BigInt`.
<del>* `%i` - Integer or `BigInt`.
<del>* `%f` - Floating point value.
<del>* `%j` - JSON. Replaced with the string `'[Circular]'` if the argument
<del>contains circular references.
<del>* `%o` - `Object`. A string representation of an object
<del> with generic JavaScript object formatting.
<del> Similar to `util.inspect()` with options
<add>* `%s` - `String` will be used to convert all values except `BigInt` and
<add> `Object`. `BigInt` values will be represented with an `n` and Objects are
<add> inspected using `util.inspect()` with options
<add> `{ depth: 0, colors: false, compact: 3 }`.
<add>* `%d` - `Number` will be used to convert all values except `BigInt`.
<add>* `%i` - `parseInt(value, 10)` is used for all values except `BigInt`.
<add>* `%f` - `parseFloat(value)` is used for all values.
<add>* `%j` - JSON. Replaced with the string `'[Circular]'` if the argument contains
<add> circular references.
<add>* `%o` - `Object`. A string representation of an object with generic JavaScript
<add> object formatting. Similar to `util.inspect()` with options
<ide> `{ showHidden: true, showProxy: true }`. This will show the full object
<ide> including non-enumerable properties and proxies.
<ide> * `%O` - `Object`. A string representation of an object with generic JavaScript
<ide><path>lib/internal/util/inspect.js
<ide> function formatWithOptions(inspectOptions, ...args) {
<ide> if (a + 1 !== args.length) {
<ide> switch (nextChar) {
<ide> case 115: // 's'
<del> tempStr = String(args[++a]);
<add> const tempArg = args[++a];
<add> if (typeof tempArg === 'object' && tempArg !== null) {
<add> tempStr = inspect(tempArg, {
<add> ...inspectOptions,
<add> compact: 3,
<add> colors: false,
<add> depth: 0
<add> });
<add> // eslint-disable-next-line valid-typeof
<add> } else if (typeof tempArg === 'bigint') {
<add> tempStr = `${tempArg}n`;
<add> } else {
<add> tempStr = String(tempArg);
<add> }
<ide> break;
<ide> case 106: // 'j'
<ide> tempStr = tryStringify(args[++a]);
<ide><path>test/parallel/test-http-response-statuscode.js
<ide> const server = http.Server(common.mustCall(function(req, res) {
<ide> test(res, NaN, 'NaN');
<ide> break;
<ide> case 3:
<del> test(res, {}, '[object Object]');
<add> test(res, {}, '{}');
<ide> break;
<ide> case 4:
<ide> test(res, 99, '99');
<ide> const server = http.Server(common.mustCall(function(req, res) {
<ide> test(res, true, 'true');
<ide> break;
<ide> case 9:
<del> test(res, [], '');
<add> test(res, [], '[]');
<ide> break;
<ide> case 10:
<ide> test(res, 'this is not valid', 'this is not valid');
<ide><path>test/parallel/test-stream-writable-change-default-encoding.js
<ide> common.expectsError(function changeDefaultEncodingToInvalidValue() {
<ide> }, {
<ide> type: TypeError,
<ide> code: 'ERR_UNKNOWN_ENCODING',
<del> message: 'Unknown encoding: [object Object]'
<add> message: 'Unknown encoding: {}'
<ide> });
<ide>
<ide> (function checkVairableCaseEncoding() {
<ide><path>test/parallel/test-util-format.js
<ide> assert.strictEqual(util.format('%f %f', 42), '42 %f');
<ide> // String format specifier
<ide> assert.strictEqual(util.format('%s'), '%s');
<ide> assert.strictEqual(util.format('%s', undefined), 'undefined');
<add>assert.strictEqual(util.format('%s', null), 'null');
<ide> assert.strictEqual(util.format('%s', 'foo'), 'foo');
<ide> assert.strictEqual(util.format('%s', 42), '42');
<ide> assert.strictEqual(util.format('%s', '42'), '42');
<ide> assert.strictEqual(util.format('%s %s', 42, 43), '42 43');
<ide> assert.strictEqual(util.format('%s %s', 42), '42 %s');
<add>assert.strictEqual(util.format('%s', 42n), '42n');
<add>assert.strictEqual(util.format('%s', Symbol('foo')), 'Symbol(foo)');
<add>assert.strictEqual(util.format('%s', true), 'true');
<add>assert.strictEqual(util.format('%s', { a: [1, 2, 3] }), '{ a: [Array] }');
<add>assert.strictEqual(util.format('%s', () => 5), '() => 5');
<ide>
<ide> // JSON format specifier
<ide> assert.strictEqual(util.format('%j'), '%j');
<ide> assert.strictEqual(
<ide> util.format(new SharedArrayBuffer(4)),
<ide> 'SharedArrayBuffer { [Uint8Contents]: <00 00 00 00>, byteLength: 4 }'
<ide> );
<add>
<add>assert.strictEqual(
<add> util.formatWithOptions(
<add> { colors: true, compact: 3 },
<add> '%s', [ 1, { a: true }]
<add> ),
<add> '[ 1, [Object] ]'
<add>); | 5 |
Ruby | Ruby | remove a redundant mutation tracker | c342d58446defad94f26c067b19003c9941f2470 | <ide><path>activerecord/lib/active_record/attribute_methods/dirty.rb
<ide> module Dirty
<ide> def reload(*)
<ide> super.tap do
<ide> @mutations_before_last_save = nil
<del> clear_mutation_trackers
<add> @mutations_from_database = nil
<ide> @changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
<ide> end
<ide> end
<ide> def initialize_dup(other) # :nodoc:
<ide> @attributes = self.class._default_attributes.map do |attr|
<ide> attr.with_value_from_user(@attributes.fetch_value(attr.name))
<ide> end
<del> clear_mutation_trackers
<add> @mutations_from_database = nil
<ide> end
<ide>
<ide> def changes_applied # :nodoc:
<del> @mutations_before_last_save = mutation_tracker
<del> @mutations_from_database = AttributeMutationTracker.new(@attributes)
<add> @mutations_before_last_save = mutations_from_database
<ide> @changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
<ide> forget_attribute_assignments
<del> clear_mutation_trackers
<add> @mutations_from_database = nil
<ide> end
<ide>
<ide> def clear_changes_information # :nodoc:
<ide> @mutations_before_last_save = nil
<ide> @changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
<ide> forget_attribute_assignments
<del> clear_mutation_trackers
<add> @mutations_from_database = nil
<ide> end
<ide>
<ide> def clear_attribute_changes(attr_names) # :nodoc:
<ide> def changed_attributes # :nodoc:
<ide> if defined?(@cached_changed_attributes)
<ide> @cached_changed_attributes
<ide> else
<del> super.reverse_merge(mutation_tracker.changed_values).freeze
<add> super.reverse_merge(mutations_from_database.changed_values).freeze
<ide> end
<ide> end
<ide>
<ide> def previous_changes # :nodoc:
<ide> end
<ide>
<ide> def attribute_changed_in_place?(attr_name) # :nodoc:
<del> mutation_tracker.changed_in_place?(attr_name)
<add> mutations_from_database.changed_in_place?(attr_name)
<ide> end
<ide>
<ide> # Did this attribute change when we last saved? This method can be invoked
<ide> def write_attribute_without_type_cast(attr_name, _)
<ide> result
<ide> end
<ide>
<del> def mutation_tracker
<del> unless defined?(@mutation_tracker)
<del> @mutation_tracker = nil
<del> end
<del> @mutation_tracker ||= AttributeMutationTracker.new(@attributes)
<del> end
<del>
<ide> def mutations_from_database
<ide> unless defined?(@mutations_from_database)
<ide> @mutations_from_database = nil
<ide> end
<del> @mutations_from_database ||= mutation_tracker
<add> @mutations_from_database ||= AttributeMutationTracker.new(@attributes)
<ide> end
<ide>
<ide> def changes_include?(attr_name)
<del> super || mutation_tracker.changed?(attr_name)
<add> super || mutations_from_database.changed?(attr_name)
<ide> end
<ide>
<ide> def clear_attribute_change(attr_name)
<del> mutation_tracker.forget_change(attr_name)
<ide> mutations_from_database.forget_change(attr_name)
<ide> end
<ide>
<ide> def forget_attribute_assignments
<ide> @attributes = @attributes.map(&:forgetting_assignment)
<ide> end
<ide>
<del> def clear_mutation_trackers
<del> @mutation_tracker = nil
<del> @mutations_from_database = nil
<del> end
<del>
<ide> def mutations_before_last_save
<ide> @mutations_before_last_save ||= NullMutationTracker.instance
<ide> end
<ide><path>activerecord/lib/active_record/persistence.rb
<ide> def destroy!
<ide> def becomes(klass)
<ide> became = klass.new
<ide> became.instance_variable_set("@attributes", @attributes)
<del> became.instance_variable_set("@mutation_tracker", @mutation_tracker) if defined?(@mutation_tracker)
<add> became.instance_variable_set("@mutations_from_database", @mutations_from_database) if defined?(@mutations_from_database)
<ide> became.instance_variable_set("@changed_attributes", attributes_changed_by_setter)
<ide> became.instance_variable_set("@new_record", new_record?)
<ide> became.instance_variable_set("@destroyed", destroyed?) | 2 |
Javascript | Javascript | remove legacy get helper test | 4c981bac1f040dc961d4c0b51f16ef337c39ae48 | <ide><path>packages/ember-htmlbars/tests/helpers/get_test.js
<del>import Ember from 'ember-metal/core';
<del>import EmberObject from 'ember-runtime/system/object';
<del>import run from 'ember-metal/run_loop';
<del>import compile from 'ember-template-compiler/system/compile';
<del>import { runAppend, runDestroy } from 'ember-runtime/tests/utils';
<del>import EmberView from 'ember-views/views/view';
<del>import ComponentLookup from 'ember-views/component_lookup';
<del>import TextField from 'ember-views/views/text_field';
<del>import buildOwner from 'container/tests/test-helpers/build-owner';
<del>import { OWNER } from 'container/owner';
<del>
<del>var view, owner;
<del>
<del>import isEnabled from 'ember-metal/features';
<del>if (!isEnabled('ember-glimmer')) {
<del> // jscs:disable
<del>
<del>QUnit.module('ember-htmlbars: {{get}} helper', {
<del> setup() {
<del> owner = buildOwner();
<del> owner.register('component:-text-field', TextField);
<del> owner.register('component-lookup:main', ComponentLookup);
<del> owner.registerOptionsForType('template', { instantiate: false });
<del> },
<del> teardown() {
<del> run(function() {
<del> Ember.TEMPLATES = {};
<del> });
<del> runDestroy(view);
<del> runDestroy(owner);
<del> owner = view = null;
<del> }
<del>});
<del>
<del>QUnit.test('get helper value should be updatable using {{input}} and (mut) - dynamic key', function() {
<del> var context = {
<del> source: EmberObject.create({
<del> banana: 'banana'
<del> }),
<del> key: 'banana'
<del> };
<del>
<del> view = EmberView.create({
<del> [OWNER]: owner,
<del> context: context,
<del> template: compile(`{{input type='text' value=(mut (get source key)) id='get-input'}}`)
<del> });
<del>
<del> runAppend(view);
<del>
<del> equal(view.$('#get-input').val(), 'banana');
<del>
<del> run(function() {
<del> view.set('context.source.banana', 'yellow');
<del> });
<del>
<del> equal(view.$('#get-input').val(), 'yellow');
<del>
<del> run(function() {
<del> view.$('#get-input').val('some value');
<del> view.childViews[0]._elementValueDidChange();
<del> });
<del>
<del> equal(view.$('#get-input').val(), 'some value');
<del> equal(view.get('context.source.banana'), 'some value');
<del>});
<del>
<del>QUnit.test('get helper value should be updatable using {{input}} and (mut) - dynamic nested key', function() {
<del> var context = {
<del> source: EmberObject.create({
<del> apple: {
<del> mcintosh: 'mcintosh'
<del> }
<del> }),
<del> key: 'apple.mcintosh'
<del> };
<del>
<del> view = EmberView.create({
<del> [OWNER]: owner,
<del> context: context,
<del> template: compile(`{{input type='text' value=(mut (get source key)) id='get-input'}}`)
<del> });
<del>
<del> runAppend(view);
<del>
<del> equal(view.$('#get-input').val(), 'mcintosh');
<del>
<del> run(function() {
<del> view.set('context.source.apple.mcintosh', 'red');
<del> });
<del>
<del> equal(view.$('#get-input').val(), 'red');
<del>
<del> run(function() {
<del> view.$('#get-input').val('some value');
<del> view.childViews[0]._elementValueDidChange();
<del> });
<del>
<del> equal(view.$('#get-input').val(), 'some value');
<del> equal(view.get('context.source.apple.mcintosh'), 'some value');
<del>});
<del>
<del>QUnit.test('get helper value should be updatable using {{input}} and (mut) - static key', function() {
<del> var context = {
<del> source: EmberObject.create({
<del> banana: 'banana'
<del> }),
<del> key: 'banana'
<del> };
<del>
<del> view = EmberView.create({
<del> [OWNER]: owner,
<del> context: context,
<del> template: compile(`{{input type='text' value=(mut (get source 'banana')) id='get-input'}}`)
<del> });
<del>
<del> runAppend(view);
<del>
<del> equal(view.$('#get-input').val(), 'banana');
<del>
<del> run(function() {
<del> view.set('context.source.banana', 'yellow');
<del> });
<del>
<del> equal(view.$('#get-input').val(), 'yellow');
<del>
<del> run(function() {
<del> view.$('#get-input').val('some value');
<del> view.childViews[0]._elementValueDidChange();
<del> });
<del>
<del> equal(view.$('#get-input').val(), 'some value');
<del> equal(view.get('context.source.banana'), 'some value');
<del>});
<del>
<del>} | 1 |
Javascript | Javascript | add test case and remove unused import | 48c7ca1e8142d0e388602999bfac00bbd9fcce1a | <ide><path>lib/dependencies/HarmonyExportImportedSpecifierDependency.js
<ide> "use strict";
<ide> const NullDependency = require("./NullDependency");
<ide> const HarmonyModulesHelpers = require("./HarmonyModulesHelpers");
<del>const WebpackMissingModule = require("./WebpackMissingModule");
<ide>
<ide> class HarmonyExportImportedSpecifierDependency extends NullDependency {
<ide> constructor(originModule, importDependency, importedVar, id, name) { | 1 |
Javascript | Javascript | fix small fonts | 645c9acb62313cab8e45ccdf4dc68b035ffffdd8 | <ide><path>pdf.js
<ide> function ScratchCanvas(width, height) {
<ide> }
<ide>
<ide> var CanvasGraphics = (function() {
<add> var kScalePrecision = 50;
<add> var kRasterizerMin = 14;
<add>
<ide> function constructor(canvasCtx, imageCanvas) {
<ide> this.ctx = canvasCtx;
<ide> this.current = new CanvasExtraState();
<ide> var CanvasGraphics = (function() {
<ide> if (this.ctx.$setFont) {
<ide> this.ctx.$setFont(fontName, size);
<ide> } else {
<del> this.ctx.font = size + 'px "' + fontName + '"';
<ide> FontMeasure.setActive(fontObj, size);
<add>
<add> size = (size <= kRasterizerMin) ? size * kScalePrecision : size;
<add> this.ctx.font = size + 'px"' + fontName + '"';
<ide> }
<ide> },
<ide> setTextRenderingMode: function(mode) {
<ide> var CanvasGraphics = (function() {
<ide> ctx.translate(current.x, -1 * current.y);
<ide> var font = this.current.font;
<ide> if (font) {
<add> if (this.current.fontSize < kRasterizerMin)
<add> ctx.transform(1 / kScalePrecision, 0, 0, 1 / kScalePrecision, 0, 0);
<ide> ctx.transform.apply(ctx, font.textMatrix);
<ide> text = font.charsToUnicode(text);
<ide> } | 1 |
Ruby | Ruby | improve generator name suggestions a bit | 7692a163fa836c7c66fe01a63215c1fd550f7b27 | <ide><path>railties/lib/rails/generators.rb
<ide> def self.invoke(namespace, args=ARGV, config={})
<ide> options = sorted_groups.map(&:last).flatten
<ide> suggestions = options.sort_by {|suggested| levenshtein_distance(namespace.to_s, suggested) }.first(3)
<ide> msg = "Could not find generator '#{namespace}'. "
<del> msg << "Maybe you meant #{ suggestions.map {|s| "'#{s}'"}.join(" or ") }\n"
<add> msg << "Maybe you meant #{ suggestions.map {|s| "'#{s}'"}.to_sentence(last_word_connector: " or ") }\n"
<ide> msg << "Run `rails generate --help` for more options."
<ide> puts msg
<ide> end
<ide> def self.levenshtein_distance str1, str2
<ide> t = str2
<ide> n = s.length
<ide> m = t.length
<del> max = n/2
<ide>
<ide> return m if (0 == n)
<ide> return n if (0 == m)
<del> return n if (n - m).abs > max
<ide>
<ide> d = (0..m).to_a
<ide> x = nil | 1 |
Text | Text | add missing option for child_process.spawnsync() | 1f32cca6f94838471b4053d591dd8e5499dff5a2 | <ide><path>doc/api/child_process.md
<ide> changes:
<ide> * `cwd` {string} Current working directory of the child process.
<ide> * `input` {string|Buffer|Uint8Array} The value which will be passed as stdin
<ide> to the spawned process. Supplying this value will override `stdio[0]`.
<add> * `argv0` {string} Explicitly set the value of `argv[0]` sent to the child
<add> process. This will be set to `command` if not specified.
<ide> * `stdio` {string|Array} Child's stdio configuration.
<ide> * `env` {Object} Environment key-value pairs.
<ide> * `uid` {number} Sets the user identity of the process (see setuid(2)). | 1 |
Python | Python | fix f90 detection in the tests | 733ebda112453f0dc51d326e230bc2613704195a | <ide><path>numpy/f2py/tests/util.py
<ide> def configuration(parent_name='',top_path=None):
<ide> out, err = p.communicate()
<ide> m = re.search(asbytes(r'COMPILERS:(\d+),(\d+),(\d+)'), out)
<ide> if m:
<del> _compiler_status = (bool(m.group(1)), bool(m.group(2)),
<del> bool(m.group(3)))
<add> _compiler_status = (bool(int(m.group(1))), bool(int(m.group(2))),
<add> bool(int(m.group(3))))
<ide> finally:
<ide> os.unlink(script)
<ide> | 1 |
Python | Python | add numbers and definitions | 229ecaf0ea69ad586587ea70b8a90d59e0e64005 | <ide><path>spacy/lang/vi/lex_attrs.py
<ide>
<ide>
<ide> _num_words = [
<del> "không",
<del> "một",
<del> "hai",
<del> "ba",
<del> "bốn",
<del> "năm",
<del> "sáu",
<del> "bảy",
<del> "bẩy",
<del> "tám",
<del> "chín",
<del> "mười",
<del> "chục",
<del> "trăm",
<del> "nghìn",
<del> "tỷ",
<add> "không", # Zero
<add> "một", # One
<add> "mốt", # Also one, irreplacable in niché cases for unit digit such as "51"="năm mươi mốt"
<add> "hai", # Two
<add> "ba", # Three
<add> "bốn", # Four
<add> "tư", # Also four, used in certain cases for unit digit such as "54"="năm mươi tư"
<add> "năm", # Five
<add> "lăm", # Also five, irreplacable in niché cases for unit digit such as "55"="năm mươi lăm"
<add> "sáu", # Six
<add> "bảy", # Seven
<add> "bẩy", # Also seven, old fashioned
<add> "tám", # Eight
<add> "chín", # Nine
<add> "mười", # Ten
<add> "chục", # Also ten, used for counting in tens such as "20 eggs"="hai chục trứng"
<add> "trăm", # Hundred
<add> "nghìn", # Thousand
<add> "ngàn", # Also thousand, used in the south
<add> "vạn", # Ten thousand
<add> "triệu", # Million
<add> "tỷ", # Billion
<add> "tỉ" # Also billion, used in combinatorics such as "tỉ_phú"="billionaire"
<ide> ]
<ide>
<ide> | 1 |
Text | Text | update morphanalysis.get and related examples | 8f44584bef4f41f5cbd72fd4292c1a727c6f33db | <ide><path>website/docs/api/morphanalysis.md
<ide> Iterate over the feature/value pairs in the analysis.
<ide> > #### Example
<ide> >
<ide> > ```python
<del>> feats = "Feat1=Val1|Feat2=Val2"
<add>> feats = "Feat1=Val1,Val3|Feat2=Val2"
<ide> > morph = MorphAnalysis(nlp.vocab, feats)
<del>> for feat in morph:
<del>> print(feat)
<add>> assert list(morph) == ["Feat1=Va1", "Feat1=Val3", "Feat2=Val2"]
<ide> > ```
<ide>
<ide> | Name | Type | Description |
<ide> Returns the morphological analysis in the UD FEATS string format.
<ide>
<ide> ## MorphAnalysis.get {#get tag="method"}
<ide>
<del>Retrieve a feature by field.
<add>Retrieve values for a feature by field.
<ide>
<ide> > #### Example
<ide> >
<ide> > ```python
<ide> > feats = "Feat1=Val1,Val2"
<ide> > morph = MorphAnalysis(nlp.vocab, feats)
<del>> assert morph.get("Feat1") == ['Feat1=Val1', 'Feat1=Val2']
<add>> assert morph.get("Feat1") == ["Val1", "Val2"]
<ide> > ```
<ide>
<ide> | Name | Type | Description |
<ide> map.
<ide> > ```python
<ide> > feats = "Feat1=Val1,Val2|Feat2=Val2"
<ide> > morph = MorphAnalysis(nlp.vocab, feats)
<del>> assert morph.to_dict() == {'Feat1': 'Val1,Val2', 'Feat2': 'Val2'}
<add>> assert morph.to_dict() == {"Feat1": "Val1,Val2", "Feat2": "Val2"}
<ide> > ```
<ide>
<ide> | Name | Type | Description | | 1 |
PHP | PHP | add trailing period in `seelink` & `dontseelink` | 9faca8e8e126222371314686729c05129d431420 | <ide><path>src/Illuminate/Foundation/Testing/CrawlerTrait.php
<ide> protected function dontSee($text)
<ide> */
<ide> public function seeLink($text, $url = null)
<ide> {
<del> $message = "No links were found with expected text [{$text}].";
<add> $message = "No links were found with expected text [{$text}]";
<ide>
<ide> if ($url) {
<ide> $message .= " and URL [{$url}]";
<ide> }
<ide>
<del> $this->assertTrue($this->hasLink($text, $url), $message);
<add> $this->assertTrue($this->hasLink($text, $url), "{$message}.");
<ide>
<ide> return $this;
<ide> }
<ide> public function dontSeeLink($text, $url = null)
<ide> $message .= " and URL [{$url}]";
<ide> }
<ide>
<del> $this->assertFalse($this->hasLink($text, $url), $message);
<add> $this->assertFalse($this->hasLink($text, $url), "{$message}.");
<ide>
<ide> return $this;
<ide> } | 1 |
Go | Go | fix events test so it doesnt need new daemon | 9aff77156b74cc248542601e146d87011819c10c | <ide><path>integration-cli/docker_cli_events_test.go
<ide> package main
<ide> import (
<ide> "fmt"
<ide> "os/exec"
<add> "regexp"
<ide> "strconv"
<ide> "strings"
<ide> "testing"
<ide> func TestEventsImageImport(t *testing.T) {
<ide> }
<ide>
<ide> func TestEventsFilters(t *testing.T) {
<del> // we need a new daemon here
<del> // otherwise events picks up the container from the previous
<del> // function as a die event (some sort of race)
<del> // I am not proud of this - jessfraz
<del> d := NewDaemon(t)
<del> if err := d.StartWithBusybox(); err != nil {
<del> t.Fatalf("Could not start daemon with busybox: %v", err)
<add> parseEvents := func(out, match string) {
<add> events := strings.Split(out, "\n")
<add> events = events[:len(events)-1]
<add> for _, event := range events {
<add> eventFields := strings.Fields(event)
<add> eventName := eventFields[len(eventFields)-1]
<add> if ok, err := regexp.MatchString(match, eventName); err != nil || !ok {
<add> t.Fatalf("event should match %s, got %#v, err: %v", match, eventFields, err)
<add> }
<add> }
<ide> }
<del> defer d.Stop()
<ide>
<ide> since := time.Now().Unix()
<del> out, err := d.Cmd("run", "--rm", "busybox", "true")
<add> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", "busybox", "true"))
<ide> if err != nil {
<ide> t.Fatal(out, err)
<ide> }
<del> out, err = d.Cmd("run", "--rm", "busybox", "true")
<add> out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", "busybox", "true"))
<ide> if err != nil {
<ide> t.Fatal(out, err)
<ide> }
<del> out, err = d.Cmd("events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", time.Now().Unix()), "--filter", "event=die")
<add> out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", time.Now().Unix()), "--filter", "event=die"))
<ide> if err != nil {
<ide> t.Fatalf("Failed to get events: %s", err)
<ide> }
<del> events := strings.Split(out, "\n")
<del> events = events[:len(events)-1]
<del> if len(events) != 2 {
<del> t.Fatalf("Expected 2 events, got %d: %v", len(events), events)
<del> }
<del> dieEvent := strings.Fields(events[len(events)-1])
<del> if dieEvent[len(dieEvent)-1] != "die" {
<del> t.Fatalf("event should be die, not %#v", dieEvent)
<del> }
<add> parseEvents(out, "die")
<ide>
<del> dieEvent = strings.Fields(events[len(events)-2])
<del> if dieEvent[len(dieEvent)-1] != "die" {
<del> t.Fatalf("event should be die, not %#v", dieEvent)
<del> }
<del>
<del> out, err = d.Cmd("events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", time.Now().Unix()), "--filter", "event=die", "--filter", "event=start")
<add> out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", time.Now().Unix()), "--filter", "event=die", "--filter", "event=start"))
<ide> if err != nil {
<ide> t.Fatalf("Failed to get events: %s", err)
<ide> }
<del> events = strings.Split(out, "\n")
<del> events = events[:len(events)-1]
<del> if len(events) != 4 {
<del> t.Fatalf("Expected 4 events, got %d: %v", len(events), events)
<del> }
<del> startEvent := strings.Fields(events[len(events)-4])
<del> if startEvent[len(startEvent)-1] != "start" {
<del> t.Fatalf("event should be start, not %#v", startEvent)
<del> }
<del> dieEvent = strings.Fields(events[len(events)-3])
<del> if dieEvent[len(dieEvent)-1] != "die" {
<del> t.Fatalf("event should be die, not %#v", dieEvent)
<del> }
<del> startEvent = strings.Fields(events[len(events)-2])
<del> if startEvent[len(startEvent)-1] != "start" {
<del> t.Fatalf("event should be start, not %#v", startEvent)
<del> }
<del> dieEvent = strings.Fields(events[len(events)-1])
<del> if dieEvent[len(dieEvent)-1] != "die" {
<del> t.Fatalf("event should be die, not %#v", dieEvent)
<add> parseEvents(out, "((die)|(start))")
<add>
<add> // make sure we at least got 2 start events
<add> count := strings.Count(out, "start")
<add> if count != 2 {
<add> t.Fatalf("should have had 2 start events but had %d, out: %s", count, out)
<ide> }
<ide>
<ide> logDone("events - filters") | 1 |
Python | Python | add deprecation warning and check warning in test | 8ca9221ec58e65dbf2ac9d669de216c0366088c1 | <ide><path>numpy/lib/function_base.py
<ide> def msort(a):
<ide> [3, 4]])
<ide>
<ide> """
<add> warnings.warn(
<add> "msort is deprecated, use np.sort(a, axis=0) instead",
<add> DeprecationWarning,
<add> stacklevel=3,
<add> )
<ide> b = array(a, subok=True, copy=True)
<ide> b.sort(0)
<ide> return b
<ide><path>numpy/lib/tests/test_function_base.py
<ide> def test_simple(self):
<ide> A = np.array([[0.44567325, 0.79115165, 0.54900530],
<ide> [0.36844147, 0.37325583, 0.96098397],
<ide> [0.64864341, 0.52929049, 0.39172155]])
<del> assert_almost_equal(
<del> msort(A),
<del> np.array([[0.36844147, 0.37325583, 0.39172155],
<del> [0.44567325, 0.52929049, 0.54900530],
<del> [0.64864341, 0.79115165, 0.96098397]]))
<add> with pytest.warns(DeprecationWarning, match="msort is deprecated"):
<add> assert_almost_equal(
<add> msort(A),
<add> np.array([[0.36844147, 0.37325583, 0.39172155],
<add> [0.44567325, 0.52929049, 0.54900530],
<add> [0.64864341, 0.79115165, 0.96098397]]))
<ide>
<ide>
<ide> class TestMeshgrid: | 2 |
Javascript | Javascript | add benchmarkcase for ast | 05fbec8eb2d0845fe4c13ecc1c01122ccad59715 | <ide><path>lib/Parser.js
<ide> Parser.prototype.walkMethodDefinition = function walkMethodDefinition(methodDefi
<ide> };
<ide>
<ide> Parser.prototype.walkStatements = function walkStatements(statements) {
<del> statements.forEach(function(statement) {
<del> if(this.isHoistedStatement(statement))
<del> this.walkStatement(statement);
<del> }, this);
<del> statements.forEach(function(statement) {
<del> if(!this.isHoistedStatement(statement))
<del> this.walkStatement(statement);
<del> }, this);
<add> for(var indexA = 0, lenA = statements.length; indexA < lenA; indexA++) {
<add> var statementA = statements[indexA];
<add> if(this.isHoistedStatement(statementA))
<add> this.walkStatement(statementA);
<add> }
<add> for(var indexB = 0, lenB = statements.length; indexB < lenB; indexB++) {
<add> var statementB = statements[indexB];
<add> if(!this.isHoistedStatement(statementB))
<add> this.walkStatement(statementB);
<add> }
<ide> };
<ide>
<ide> Parser.prototype.isHoistedStatement = function isHoistedStatement(statement) {
<ide> Parser.prototype.walkExportNamedDeclaration = function walkExportNamedDeclaratio
<ide> }
<ide> }
<ide> if(statement.specifiers) {
<del> for(var specifierIndex = 0; specifierIndex <= statement.specifiers.length - 1; specifierIndex++) {
<add> for(var specifierIndex = 0; specifierIndex < statement.specifiers.length; specifierIndex++) {
<ide> var specifier = statement.specifiers[specifierIndex];
<ide> switch(specifier.type) {
<ide> case "ExportSpecifier":
<ide> Parser.prototype.walkExportDefaultDeclaration = function walkExportDefaultDeclar
<ide> var pos = this.scope.definitions.length;
<ide> this.walkStatement(statement.declaration);
<ide> var newDefs = this.scope.definitions.slice(pos);
<del> for(var index = 0; index <= newDefs.length - 1; index++) {
<add> for(var index = 0, len = newDefs.length; index < len; index++) {
<ide> var def = newDefs[index];
<ide> this.applyPluginsBailResult("export specifier", statement, def, "default");
<ide> }
<ide> Parser.prototype.walkClassDeclaration = function walkClassDeclaration(statement)
<ide> };
<ide>
<ide> Parser.prototype.walkSwitchCases = function walkSwitchCases(switchCases) {
<del> for(var index = 0; index <= switchCases.length - 1; index++) {
<add> for(var index = 0, len = switchCases.length; index < len; index++) {
<ide> var switchCase = switchCases[index];
<ide>
<ide> if(switchCase.test) {
<ide> Parser.prototype.walkVariableDeclarators = function walkVariableDeclarators(decl
<ide> };
<ide>
<ide> Parser.prototype.walkExpressions = function walkExpressions(expressions) {
<del> for(var expressionsIndex = 0; expressionsIndex <= expressions.length - 1; expressionsIndex++) {
<add> for(var expressionsIndex = 0, len = expressions.length; expressionsIndex < len; expressionsIndex++) {
<ide> var expression = expressions[expressionsIndex];
<ide> if(expression)
<ide> this.walkExpression(expression);
<ide> Parser.prototype.walkSpreadElement = function walkSpreadElement(expression) {
<ide> };
<ide>
<ide> Parser.prototype.walkObjectExpression = function walkObjectExpression(expression) {
<del> for(var propIndex = 0; propIndex <= expression.properties.length - 1; propIndex++) {
<add> for(var propIndex = 0, len = expression.properties.length; propIndex < len; propIndex++) {
<ide> var prop = expression.properties[propIndex];
<ide> if(prop.computed)
<ide> this.walkExpression(prop.key);
<ide> Parser.prototype.inScope = function inScope(params, fn) {
<ide> definitions: oldScope.definitions.slice(),
<ide> renames: Object.create(oldScope.renames)
<ide> };
<del> params.forEach(function(param) {
<add>
<add> for(var paramIndex = 0, len = params.length; paramIndex < len; paramIndex++) {
<add> var param = params[paramIndex];
<add>
<ide> if(typeof param !== "string") {
<ide> param = _this.enterPattern(param, function(param) {
<ide> _this.scope.renames["$" + param] = undefined;
<ide> Parser.prototype.inScope = function inScope(params, fn) {
<ide> _this.scope.renames["$" + param] = undefined;
<ide> _this.scope.definitions.push(param);
<ide> }
<del> });
<add> }
<add>
<ide> fn();
<ide> _this.scope = oldScope;
<ide> };
<ide> Parser.prototype.enterIdentifier = function enterIdentifier(pattern, onIdent) {
<ide> };
<ide>
<ide> Parser.prototype.enterObjectPattern = function enterObjectPattern(pattern, onIdent) {
<del> for(var propIndex = 0; propIndex <= pattern.properties.length - 1; propIndex++) {
<add> for(var propIndex = 0, len = pattern.properties.length; propIndex < len; propIndex++) {
<ide> var prop = pattern.properties[propIndex];
<ide> this.enterPattern(prop.value, onIdent);
<ide> }
<ide> };
<ide>
<ide> Parser.prototype.enterArrayPattern = function enterArrayPattern(pattern, onIdent) {
<del> for(var elementIndex = 0; elementIndex <= pattern.elements.length - 1; elementIndex++) {
<add> for(var elementIndex = 0, len = pattern.properties.length; elementIndex < len; elementIndex++) {
<ide> var element = pattern.elements[elementIndex];
<ide> this.enterPattern(element, onIdent);
<ide> }
<ide> var POSSIBLE_AST_OPTIONS = [{
<ide>
<ide> Parser.prototype.parse = function parse(source, initialState) {
<ide> var ast, comments = [];
<del> for(var i = 0; i < POSSIBLE_AST_OPTIONS.length; i++) {
<add> for(var i = 0, len = POSSIBLE_AST_OPTIONS.length; i < len; i++) {
<ide> if(!ast) {
<ide> try {
<ide> comments.length = 0;
<ide><path>test/benchmarkCases/large-ast/webpack.config.js
<add>module.exports = {
<add> entry: ["react", "react-dom", "lodash", "react", "react-dom", "lodash"]
<add>}; | 2 |
Javascript | Javascript | simplify code with string.prototype.repeat() | 4d78121b7786ee5b676d45b9d11e9a89d8dd249c | <ide><path>benchmark/http_simple.js
<ide> var http = require('http');
<ide>
<ide> var port = parseInt(process.env.PORT || 8000);
<ide>
<del>var fixed = makeString(20 * 1024, 'C'),
<add>var fixed = 'C'.repeat(20 * 1024),
<ide> storedBytes = {},
<ide> storedBuffer = {},
<ide> storedUnicode = {};
<ide> var server = module.exports = http.createServer(function(req, res) {
<ide> if (n <= 0)
<ide> throw new Error('bytes called with n <= 0');
<ide> if (storedBytes[n] === undefined) {
<del> storedBytes[n] = makeString(n, 'C');
<add> storedBytes[n] = 'C'.repeat(n);
<ide> }
<ide> body = storedBytes[n];
<ide>
<ide> var server = module.exports = http.createServer(function(req, res) {
<ide> if (n <= 0)
<ide> throw new Error('unicode called with n <= 0');
<ide> if (storedUnicode[n] === undefined) {
<del> storedUnicode[n] = makeString(n, '\u263A');
<add> storedUnicode[n] = '\u263A'.repeat(n);
<ide> }
<ide> body = storedUnicode[n];
<ide>
<ide> var server = module.exports = http.createServer(function(req, res) {
<ide> }
<ide> });
<ide>
<del>function makeString(size, c) {
<del> var s = '';
<del> while (s.length < size) {
<del> s += c;
<del> }
<del> return s;
<del>}
<del>
<ide> server.listen(port, function() {
<ide> if (module === require.main)
<ide> console.error('Listening at http://127.0.0.1:' + port + '/');
<ide><path>benchmark/http_simple_auto.js
<ide> var spawn = require('child_process').spawn;
<ide>
<ide> var port = parseInt(process.env.PORT || 8000);
<ide>
<del>var fixed = '';
<del>var i;
<del>for (i = 0; i < 20 * 1024; i++) {
<del> fixed += 'C';
<del>}
<add>var fixed = "C".repeat(20 * 1024);
<ide>
<ide> var stored = {};
<ide> var storedBuffer = {};
<ide> var server = http.createServer(function(req, res) {
<ide> if (n <= 0)
<ide> throw new Error('bytes called with n <= 0');
<ide> if (stored[n] === undefined) {
<del> stored[n] = '';
<del> for (i = 0; i < n; i++) {
<del> stored[n] += 'C';
<del> }
<add> stored[n] = "C".repeat(n);
<ide> }
<ide> body = stored[n];
<ide>
<ide><path>benchmark/static_http_server.js
<ide> var bytes = 1024 * 5;
<ide> var requests = 0;
<ide> var responses = 0;
<ide>
<del>var body = '';
<del>for (var i = 0; i < bytes; i++) {
<del> body += 'C';
<del>}
<add>var body = 'C'.repeat(bytes);
<ide>
<ide> var server = http.createServer(function(req, res) {
<ide> res.writeHead(200, {
<ide><path>lib/_debugger.js
<ide> function leftPad(n, prefix, maxN) {
<ide> const nchars = Math.max(2, String(maxN).length) + 1;
<ide> const nspaces = nchars - s.length - 1;
<ide>
<del> for (var i = 0; i < nspaces; i++) {
<del> prefix += ' ';
<del> }
<del>
<del> return prefix + s;
<add> return prefix + ' '.repeat(nspaces) + s;
<ide> }
<ide>
<ide>
<ide><path>test/fixtures/print-chars.js
<ide> var assert = require('assert');
<ide>
<ide> var n = parseInt(process.argv[2]);
<ide>
<del>var s = '';
<del>for (var i = 0; i < n; i++) {
<del> s += 'c';
<del>}
<del>
<del>process.stdout.write(s);
<add>process.stdout.write('c'.repeat(n));
<ide><path>test/parallel/test-buffer.js
<ide> assert.equal(Buffer('=bad'.repeat(1e4), 'base64').length, 0);
<ide> {
<ide> // Creating buffers larger than pool size.
<ide> const l = Buffer.poolSize + 5;
<del> let s = '';
<del> for (let i = 0; i < l; i++) {
<del> s += 'h';
<del> }
<add> const s = 'h'.repeat(l);
<ide>
<ide> const b = new Buffer(s);
<ide>
<ide><path>test/parallel/test-fs-realpath.js
<ide> function test_cyclic_link_overprotection(callback) {
<ide> var folder = cycles + '/folder';
<ide> var link = folder + '/cycles';
<ide> var testPath = cycles;
<del> for (var i = 0; i < 10; i++) testPath += '/folder/cycles';
<add> testPath += '/folder/cycles'.repeat(10);
<ide> try {fs.unlinkSync(link);} catch (ex) {}
<ide> fs.symlinkSync(cycles, link, 'dir');
<ide> unlink.push(link);
<ide><path>test/parallel/test-http-full-response.js
<ide> var exec = require('child_process').exec;
<ide>
<ide> var bodyLength = 12345;
<ide>
<del>var body = '';
<del>for (var i = 0; i < bodyLength; i++) {
<del> body += 'c';
<del>}
<add>var body = 'c'.repeat(bodyLength);
<ide>
<ide> var server = http.createServer(function(req, res) {
<ide> res.writeHead(200, {
<ide><path>test/parallel/test-http-pipeline-regr-2639.js
<ide> var server = http.createServer(function(req, res) {
<ide> }).listen(common.PORT, function() {
<ide> const s = net.connect(common.PORT);
<ide>
<del> var big = '';
<del> for (var i = 0; i < COUNT; i++)
<del> big += 'GET / HTTP/1.0\r\n\r\n';
<add> var big = 'GET / HTTP/1.0\r\n\r\n'.repeat(COUNT);
<add>
<ide> s.write(big);
<ide> s.resume();
<ide> });
<ide><path>test/parallel/test-net-large-string.js
<ide> var assert = require('assert');
<ide> var net = require('net');
<ide>
<ide> var kPoolSize = 40 * 1024;
<del>var data = '';
<del>for (var i = 0; i < kPoolSize; ++i) {
<del> data += 'あ'; // 3bytes
<del>}
<add>var data = 'あ'.repeat(kPoolSize);
<ide> var receivedSize = 0;
<ide> var encoding = 'UTF-8';
<ide>
<ide><path>test/pummel/test-https-large-response.js
<ide> var options = {
<ide> };
<ide>
<ide> var reqCount = 0;
<del>var body = '';
<ide>
<ide> process.stdout.write('build body...');
<del>for (var i = 0; i < 1024 * 1024; i++) {
<del> body += 'hello world\n';
<del>}
<add>var body = 'hello world\n'.repeat(1024 * 1024);
<ide> process.stdout.write('done\n');
<ide>
<ide> var server = https.createServer(options, function(req, res) {
<ide><path>test/pummel/test-net-many-clients.js
<ide> var connections_per_client = 5;
<ide> // measured
<ide> var total_connections = 0;
<ide>
<del>var body = '';
<del>for (var i = 0; i < bytes; i++) {
<del> body += 'C';
<del>}
<add>var body = 'C'.repeat(bytes);
<ide>
<ide> var server = net.createServer(function(c) {
<ide> console.log('connected');
<ide><path>test/pummel/test-net-throttle.js
<ide> var chars_recved = 0;
<ide> var npauses = 0;
<ide>
<ide> console.log('build big string');
<del>var body = '';
<del>for (var i = 0; i < N; i++) {
<del> body += 'C';
<del>}
<add>body = 'C'.repeat(N);
<ide>
<ide> console.log('start server on port ' + common.PORT);
<ide>
<ide><path>test/pummel/test-tls-throttle.js
<ide> if (!common.hasCrypto) {
<ide> var tls = require('tls');
<ide> var fs = require('fs');
<ide>
<del>
<del>var body = '';
<del>
<ide> process.stdout.write('build body...');
<del>for (var i = 0; i < 1024 * 1024; i++) {
<del> body += 'hello world\n';
<del>}
<add>var body = 'hello world\n'.repeat(1024 * 1024);
<ide> process.stdout.write('done\n');
<ide>
<del>
<ide> var options = {
<ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'),
<ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') | 14 |
Text | Text | translate threejs-textures to zh-cn | a2dfa80df8938398f1b303a83beefbaadea706ed | <ide><path>threejs/lessons/zh_cn/threejs-textures.md
<add>Title: Three.js 纹理
<add>Description: 在three.js中使用纹理
<add>TOC: 纹理
<add>
<add>本文是关于 three.js 系列文章的一部分。第一篇文章是 [three.js 基础](threejs-fundamentals.html)。上一篇[文章](threejs-setup.html)是关于本文的环境搭建。如果你还没有读过它,建议先从那里开始。
<add>
<add>纹理是Three.js中的一种大话题,我还不能100%地确定在什么层面上解释它们,但我会试着去做它。这里面有很多主题,而且很多主题是相互关联的,所以很难一下子解释清楚。下面是本文的快速目录。
<add>
<add><ul>
<add><li><a href="#hello">你好,纹理</a></li>
<add><li><a href="#six">6种纹理,在立方体的每个面上都有不同的纹理。</a></li>
<add><li><a href="#loading">加载纹理</a></li>
<add><ul>
<add> <li><a href="#easy">简单的方法</a></li>
<add> <li><a href="#wait1">等待一个纹理加载</a></li>
<add> <li><a href="#waitmany">等待多个纹理加载</a></li>
<add> <li><a href="#cors">从其他源加载纹理</a></li>
<add></ul>
<add><li><a href="#memory">内存使用</a></li>
<add><li><a href="#format">JPG vs PNG</a></li>
<add><li><a href="#filtering-and-mips">过滤和mips</a></li>
<add><li><a href="#uvmanipulation">重复,偏移,旋转,包裹</a></li>
<add></ul>
<add>
<add>## <a name="hello"></a> 你好,纹理
<add>
<add>纹理一般是指我们常见的在一些第三方程序中创建的图像,如Photoshop或GIMP。比如我们把这张图片放在立方体上。
<add>
<add><div class="threejs_center">
<add> <img src="../resources/images/wall.jpg" style="width: 600px;" class="border" >
<add></div>
<add>
<add>我们将修改我们的第一个例子中的其中一个。我们需要做的就是创建一个`TextureLoader`。调用它的[`load`](TextureLoader.load)方法,同时传入图像的URL,并将材质的 `map` 属性设置为该方法的返回值,而不是设置它的 `color`属性。
<add>
<add>```js
<add>+const loader = new THREE.TextureLoader();
<add>
<add>const material = new THREE.MeshBasicMaterial({
<add>- color: 0xFF8844,
<add>+ map: loader.load('resources/images/wall.jpg'),
<add>});
<add>```
<add>注意,我们使用的是 `MeshBasicMaterial`, 所以没有必要增加光线
<add>
<add>{{{example url="../threejs-textured-cube.html" }}}
<add>
<add>## <a name="six"></a> 6种纹理,在立方体的每个面上都有不同的纹理。
<add>
<add>6个纹理,一个立方体的每个面都有一个,怎么样?
<add>
<add><div class="threejs_center">
<add> <div>
<add> <img src="../resources/images/flower-1.jpg" style="width: 100px;" class="border" >
<add> <img src="../resources/images/flower-2.jpg" style="width: 100px;" class="border" >
<add> <img src="../resources/images/flower-3.jpg" style="width: 100px;" class="border" >
<add> </div>
<add> <div>
<add> <img src="../resources/images/flower-4.jpg" style="width: 100px;" class="border" >
<add> <img src="../resources/images/flower-5.jpg" style="width: 100px;" class="border" >
<add> <img src="../resources/images/flower-6.jpg" style="width: 100px;" class="border" >
<add> </div>
<add></div>
<add>
<add>我们只需制作6种材料,并在创建 `Mesh` 时将它们作为一个数组传递给它们。
<add>
<add>```js
<add>const loader = new THREE.TextureLoader();
<add>
<add>-const material = new THREE.MeshBasicMaterial({
<add>- map: loader.load('resources/images/wall.jpg'),
<add>-});
<add>+const materials = [
<add>+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-1.jpg')}),
<add>+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-2.jpg')}),
<add>+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-3.jpg')}),
<add>+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-4.jpg')}),
<add>+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-5.jpg')}),
<add>+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-6.jpg')}),
<add>+];
<add>-const cube = new THREE.Mesh(geometry, material);
<add>+const cube = new THREE.Mesh(geometry, materials);
<add>```
<add>
<add>有效果了!
<add>
<add>{{{example url="../threejs-textured-cube-6-textures.html" }}}
<add>
<add>但需要注意的是,并不是所有的几何体类型都支持多种材质。`BoxGeometry` 和 `BoxBufferGeometry` 可以使用6种材料,每个面一个。`ConeGeometry` 和 `ConeBufferGeometry` 可以使用2种材料,一种用于底部,一种用于侧面。 `CylinderGeometry` 和 `CylinderBufferGeometry` 可以使用3种材料,分别是底部、顶部和侧面。对于其他情况,你需要建立或加载自定义几何体和(或)修改纹理坐标。
<add>
<add>在其他3D引擎中,如果你想在一个几何体上使用多个图像,使用 [纹理图集(Texture Atlas)](https://en.wikipedia.org/wiki/Texture_atlas) 更为常见,性能也更高。纹理图集是将多个图像放在一个单一的纹理中,然后使用几何体顶点上的纹理坐标来选择在几何体的每个三角形上使用纹理的哪些部分。
<add>
<add>什么是纹理坐标?它们是添加到一块几何体的每个顶点上的数据,用于指定该顶点对应的纹理的哪个部分。当我们开始[构建自定义几何体时(building custom geometry)](threejs-custom-geometry.html),我们会介绍它们。
<add>
<add>## <a name="loading"></a> 加载纹理
<add>
<add>### <a name="easy"></a> 简单的方法
<add>
<add>本文的大部分代码都使用最简单的加载纹理的方法。我们创建一个 `TextureLoader` ,然后调用它的[`load`](TextureLoader.load)方法。
<add>这将返回一个 `Texture` 对象。
<add>
<add>```js
<add>const texture = loader.load('resources/images/flower-1.jpg');
<add>```
<add>
<add>需要注意的是,使用这个方法,我们的纹理将是透明的,直到图片被three.js异步加载完成,这时它将用下载的图片更新纹理。
<add>
<add>这有一个很大的好处,就是我们不必等待纹理加载,我们的页面会立即开始渲染。这对于很多用例来说可能都没问题,但如果我们想要的话,我们可以让three.js告诉我们何时纹理已经下载完毕。
<add>
<add>### <a name="wait1"></a> 等待一个纹理加载
<add>
<add>为了等待贴图加载,贴图加载器的 `load` 方法会在贴图加载完成后调用一个回调。回到上面的例子,我们可以在创建Mesh并将其添加到场景之前等待贴图加载,就像这样。
<add>
<add>```js
<add>const loader = new THREE.TextureLoader();
<add>loader.load('resources/images/wall.jpg', (texture) => {
<add> const material = new THREE.MeshBasicMaterial({
<add> map: texture,
<add> });
<add> const cube = new THREE.Mesh(geometry, material);
<add> scene.add(cube);
<add> cubes.push(cube); // 添加到我们要旋转的立方体数组中
<add>});
<add>```
<add>
<add>除非你清除你的浏览器的缓存并且连接缓慢,你不太可能看到任何差异,但放心,它正在等待纹理加载。
<add>
<add>{{{example url="../threejs-textured-cube-wait-for-texture.html" }}}
<add>
<add>### <a name="waitmany"></a> 等待多个纹理加载
<add>
<add>要等到所有纹理都加载完毕,你可以使用 `LoadingManager` 。创建一个并将其传递给 `TextureLoader`,然后将其[`onLoad`](LoadingManager.onLoad)属性设置为回调。
<add>
<add>```js
<add>+const loadManager = new THREE.LoadingManager();
<add>*const loader = new THREE.TextureLoader(loadManager);
<add>
<add>const materials = [
<add> new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-1.jpg')}),
<add> new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-2.jpg')}),
<add> new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-3.jpg')}),
<add> new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-4.jpg')}),
<add> new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-5.jpg')}),
<add> new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-6.jpg')}),
<add>];
<add>
<add>+loadManager.onLoad = () => {
<add>+ const cube = new THREE.Mesh(geometry, materials);
<add>+ scene.add(cube);
<add>+ cubes.push(cube); // 添加到我们要旋转的立方体数组中
<add>+};
<add>```
<add>
<add>`LoadingManager` 也有一个 [`onProgress`](LoadingManager.onProgress) 属性,我们可以设置为另一个回调来显示进度指示器。
<add>
<add>首先,我们在HTML中添加一个进度条
<add>
<add>```html
<add><body>
<add> <canvas id="c"></canvas>
<add>+ <div id="loading">
<add>+ <div class="progress"><div class="progressbar"></div></div>
<add>+ </div>
<add></body>
<add>```
<add>
<add>然后给它加上CSS
<add>
<add>```css
<add>#loading {
<add> position: fixed;
<add> top: 0;
<add> left: 0;
<add> width: 100%;
<add> height: 100%;
<add> display: flex;
<add> justify-content: center;
<add> align-items: center;
<add>}
<add>#loading .progress {
<add> margin: 1.5em;
<add> border: 1px solid white;
<add> width: 50vw;
<add>}
<add>#loading .progressbar {
<add> margin: 2px;
<add> background: white;
<add> height: 1em;
<add> transform-origin: top left;
<add> transform: scaleX(0);
<add>}
<add>```
<add>
<add>然后在代码中,我们将在 `onProgress` 回调中更新 `progressbar` 的比例。调用它有如下几个参数:最后加载的项目的URL,目前加载的项目数量,以及加载的项目总数。
<add>
<add>```js
<add>+const loadingElem = document.querySelector('#loading');
<add>+const progressBarElem = loadingElem.querySelector('.progressbar');
<add>
<add>loadManager.onLoad = () => {
<add>+ loadingElem.style.display = 'none';
<add> const cube = new THREE.Mesh(geometry, materials);
<add> scene.add(cube);
<add> cubes.push(cube); // 添加到我们要旋转的立方体数组中
<add>};
<add>
<add>+loadManager.onProgress = (urlOfLastItemLoaded, itemsLoaded, itemsTotal) => {
<add>+ const progress = itemsLoaded / itemsTotal;
<add>+ progressBarElem.style.transform = `scaleX(${progress})`;
<add>+};
<add>```
<add>除非你清除了你的缓存,而且连接速度很慢,否则你可能看不到加载栏。
<add>
<add>{{{example url="../threejs-textured-cube-wait-for-all-textures.html" }}}
<add>
<add>## <a name="cors"></a> 从其他源加载纹理
<add>
<add>要使用其他服务器上的图片,这些服务器需要发送正确的头文件。如果他们不发送,你就不能在three.js中使用这些图片,并且会得到一个错误。如果你运行提供图片的服务器,请确保它[发送正确的头文件](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).。如果你不控制托管图片的服务器,而且它没有发送权限头文件,那么你就不能使用该服务器上的图片。
<add>
<add>例如 [imgur](https://imgur.com)、[flickr](https://flickr.com) 和 [github](https://github.com) 都会发送头文件,允许你在 three.js 中使用他们服务器上托管的图片,使用 three.js。而其他大多数网站则不允许。
<add>
<add>## <a name="memory"></a> 内存管理
<add>
<add>纹理往往是three.js应用中使用内存最多的部分。重要的是要明白,*一般来说*,纹理会占用 `宽度 * 高度 * 4 * 1.33` 字节的内存。
<add>
<add>注意,这里没有提到任何关于压缩的问题。我可以做一个.jpg的图片,然后把它的压缩率设置的超级高。比如说我在做一个房子的场景。在房子里面有一张桌子,我决定在桌子的顶面放上这个木质的纹理
<add>
<add><div class="threejs_center"><img class="border" src="resources/images/compressed-but-large-wood-texture.jpg" align="center" style="width: 300px"></div>
<add>
<add>那张图片只有157k,所以下载起来会比较快,但[实际上它的大小是3024×3761像素](resources/images/compressed-but-large-wood-texture.jpg).。按照上面的公式,那就是
<add>
<add> 3024 * 3761 * 4 * 1.33 = 60505764.5
<add>
<add>在three.js中,这张图片会占用**60兆(meg)的内存!**。只要几个这样的纹理,你就会用完内存。
<add>
<add>我之所以提出这个问题,是因为要知道使用纹理是有隐性成本的。为了让three.js使用纹理,必须把纹理交给GPU,而GPU*一般*都要求纹理数据不被压缩。
<add>
<add>这个故事的寓意在于,不仅仅要让你的纹理的文件大小小,还得让你的纹理尺寸小。文件大小小=下载速度快。尺寸小=占用的内存少。你应该把它们做得多小?越小越好,而且看起来仍然是你需要的样子。
<add>
<add>## <a name="format"></a> JPG vs PNG
<add>
<add>这和普通的HTML差不多,JPG有损压缩,PNG有无损压缩,所以PNG的下载速度一般比较慢。但是,PNG支持透明度。PNG可能也适合作为非图像数据(non-image data)的格式,比如法线图,以及其他种类的非图像图,我们后面会介绍。
<add>
<add>请记住,在WebGL中JPG使用的内存并不比PNG少。参见上文。
<add>
<add>## <a name="filtering-and-mips"></a> 过滤和mips
<add>
<add>让我们把这个16x16的纹理应用到
<add>
<add><div class="threejs_center"><img src="resources/images/mip-low-res-enlarged.png" class="nobg" align="center"></div>
<add>
<add>一个立方体上。
<add>
<add><div class="spread"><div data-diagram="filterCube"></div></div>
<add>
<add>让我们把这个立方体画得非常小
<add>
<add><div class="spread"><div data-diagram="filterCubeSmall"></div></div>
<add>
<add>嗯,我想这很难看得清楚。让我们把这个小方块放大
<add>
<add><div class="spread"><div data-diagram="filterCubeSmallLowRes"></div></div>
<add>
<add>GPU怎么知道小立方体的每一个像素需要使用哪些颜色?如果立方体小到只有1、2个像素呢?
<add>
<add>这就是过滤(filtering)的意义所在。
<add>
<add>如果是Photoshop,Photoshop会把几乎所有的像素平均在一起,来计算出这1、2个像素的颜色。这将是一个非常缓慢的操作。GPU用mipmaps解决了这个问题。
<add>
<add>Mips 是纹理的副本,每一个都是前一个 mip 的一半宽和一半高,其中的像素已经被混合以制作下一个较小的 mip。Mips一直被创建,直到我们得到1x1像素的Mip。对于上面的图片,所有的Mip最终会变成这样的样子
<add>
<add><div class="threejs_center"><img src="resources/images/mipmap-low-res-enlarged.png" class="nobg" align="center"></div>
<add>
<add>现在,当立方体被画得很小,只有1或2个像素大时,GPU可以选择只用最小或次小级别的mip来决定让小立方体变成什么颜色。
<add>
<add>在three.js中,当纹理绘制的尺寸大于其原始尺寸时,或者绘制的尺寸小于其原始尺寸时,你都可以做出相应的处理。
<add>
<add>当纹理绘制的尺寸大于其原始尺寸时,你可以将 [`texture.magFilter`](Texture.magFilter) 属性设置为 `THREE.NearestFilter` 或 `THREE.LinearFilter` 。`NearestFilter` 意味着只需从原始纹理中选取最接近的一个像素。对于低分辨率的纹理,这给你一个非常像素化的外观,就像Minecraft。
<add>
<add>`LinearFilter` 是指从纹理中选择离我们应该选择颜色的地方最近的4个像素,并根据实际点与4个像素的距离,以适当的比例进行混合。
<add>
<add><div class="spread">
<add> <div>
<add> <div data-diagram="filterCubeMagNearest" style="height: 250px;"></div>
<add> <div class="code">Nearest</div>
<add> </div>
<add> <div>
<add> <div data-diagram="filterCubeMagLinear" style="height: 250px;"></div>
<add> <div class="code">Linear</div>
<add> </div>
<add></div>
<add>
<add>为了在绘制的纹理小于其原始尺寸时设置过滤器,你可以将 [`texture.minFilter`](Texture.minFilter) 属性设置为下面6个值之一。
<add>
<add>* `THREE.NearestFilter`
<add>
<add> 同上,在纹理中选择最近的像素。
<add>
<add>* `THREE.LinearFilter`
<add>
<add> 和上面一样,从纹理中选择4个像素,然后混合它们
<add>
<add>* `THREE.NearestMipmapNearestFilter`
<add>
<add> 选择合适的mip,然后选择一个像素。
<add>
<add>* `THREE.NearestMipmapLinearFilter`
<add>
<add> 选择2个mips,从每个mips中选择一个像素,混合这2个像素。
<add>
<add>* `THREE.LinearMipmapNearestFilter`
<add>
<add> 选择合适的mip,然后选择4个像素并将它们混合。
<add>
<add>* `THREE.LinearMipmapLinearFilter`
<add>
<add> 选择2个mips,从每个mips中选择4个像素,然后将所有8个像素混合成1个像素。
<add>
<add>下面是一个分别使用上面6个设置的例子
<add>
<add><div class="spread">
<add> <div data-diagram="filterModes" style="
<add> height: 450px;
<add> position: relative;
<add> ">
<add> <div style="
<add> width: 100%;
<add> height: 100%;
<add> display: flex;
<add> align-items: center;
<add> justify-content: flex-start;
<add> ">
<add> <div style="
<add> background: rgba(255,0,0,.8);
<add> color: white;
<add> padding: .5em;
<add> margin: 1em;
<add> font-size: small;
<add> border-radius: .5em;
<add> line-height: 1.2;
<add> user-select: none;"
<add> >click to<br/>change<br/>texture</div>
<add> </div>
<add> <div class="filter-caption" style="left: 0.5em; top: 0.5em;">nearest</div>
<add> <div class="filter-caption" style="width: 100%; text-align: center; top: 0.5em;">linear</div>
<add> <div class="filter-caption" style="right: 0.5em; text-align: right; top: 0.5em;">nearest<br/>mipmap<br/>nearest</div>
<add> <div class="filter-caption" style="left: 0.5em; text-align: left; bottom: 0.5em;">nearest<br/>mipmap<br/>linear</div>
<add> <div class="filter-caption" style="width: 100%; text-align: center; bottom: 0.5em;">linear<br/>mipmap<br/>nearest</div>
<add> <div class="filter-caption" style="right: 0.5em; text-align: right; bottom: 0.5em;">linear<br/>mipmap<br/>linear</div>
<add> </div>
<add></div>
<add>
<add>需要注意的是,使用 `NearestFilter` 和 `LinearFilter` 的左上方和中上方没有使用mips。正因为如此,它们在远处会闪烁,因为GPU是从原始纹理中挑选像素。左边只有一个像素被选取,中间有4个像素被选取并混合,但这还不足以得出一个好的代表颜色。其他4条做得比较好,右下角的`LinearMipmapLinearFilter`最好。
<add>
<add>如果你点击上面的图片,它将在我们上面一直使用的纹理和每一个mip级别都是不同颜色的纹理之间切换。
<add>
<add><div class="threejs_center">
<add> <div data-texture-diagram="differentColoredMips"></div>
<add></div>
<add>
<add>这样就更清楚了。在左上角和中上角你可以看到第一个mip一直用到了远处。右上角和中下角你可以清楚地看到哪里使用了不同的mip。
<add>
<add>切换回原来的纹理,你可以看到右下角是最平滑的,质量最高的。你可能会问为什么不总是使用这种模式。最明显的原因是有时你希望东西是像素化的,以达到复古的效果或其他原因。其次最常见的原因是,读取8个像素并混合它们比读取1个像素并混合要慢。虽然单个纹理不太可能成为快和慢的区别,但随着我们在这些文章中的进一步深入,我们最终会有同时使用4或5个纹理的材料的情况。4个纹理*每个纹理8个像素,就是查找32个像素的永远渲染的像素。在移动设备上,这一嗲可能需要被重点考虑。
<add>
<add>## <a name="uvmanipulation"></a> 重复,偏移,旋转,包裹一个纹理
<add>
<add>纹理有重复、偏移和旋转纹理的设置。
<add>
<add>默认情况下,three.js中的纹理是不重复的。要设置纹理是否重复,有2个属性,[`wrapS`](Texture.wrapS) 用于水平包裹,[`wrapT`](Texture.wrapT) 用于垂直包裹。
<add>
<add>它们可以被设置为一下其中一个:
<add>
<add>* `THREE.ClampToEdgeWrapping`
<add>
<add> 每条边上的最后一个像素无限重复。
<add>
<add>* `THREE.RepeatWrapping`
<add>
<add> 纹理重复
<add>
<add>* `THREE.MirroredRepeatWrapping`
<add>
<add> 在每次重复时将进行镜像
<add>
<add>比如说,要开启两个方向的包裹。
<add>
<add>```js
<add>someTexture.wrapS = THREE.RepeatWrapping;
<add>someTexture.wrapT = THREE.RepeatWrapping;
<add>```
<add>
<add>重复是用[repeat]重复属性设置的。
<add>
<add>```js
<add>const timesToRepeatHorizontally = 4;
<add>const timesToRepeatVertically = 2;
<add>someTexture.repeat.set(timesToRepeatHorizontally, timesToRepeatVertically);
<add>```
<add>
<add>纹理的偏移可以通过设置 `offset` 属性来完成。纹理的偏移是以单位为单位的,其中1个单位=1个纹理大小。换句话说,0 = 没有偏移,1 = 偏移一个完整的纹理数量。
<add>
<add>```js
<add>const xOffset = .5; // offset by half the texture
<add>const yOffset = .25; // offset by 1/4 the texture
<add>someTexture.offset.set(xOffset, yOffset);
<add>```
<add>
<add>通过设置以弧度为单位的 `rotation` 属性以及用于选择旋转中心的 `center` 属性,可以设置纹理的旋转。它的默认值是0,0,从左下角开始旋转。像偏移一样,这些单位是以纹理大小为单位的,所以将它们设置为 `.5`,`.5` 将会围绕纹理中心旋转。
<add>
<add>```js
<add>someTexture.center.set(.5, .5);
<add>someTexture.rotation = THREE.MathUtils.degToRad(45);
<add>```
<add>
<add>让我们修改一下上面的示例,来试试这些属性吧
<add>
<add>首先,我们要保留一个对纹理的引用,这样我们就可以对它进行操作。
<add>
<add>```js
<add>+const texture = loader.load('resources/images/wall.jpg');
<add>const material = new THREE.MeshBasicMaterial({
<add>- map: loader.load('resources/images/wall.jpg');
<add>+ map: texture,
<add>});
<add>```
<add>
<add>然后,我们会再次使用 [dat.GUI](https://github.com/dataarts/dat.gui) 来提供一个简单的界面。
<add>
<add>```js
<add>import {GUI} from '../3rdparty/dat.gui.module.js';
<add>```
<add>
<add>正如我们在之前的dat.GUI例子中所做的那样,我们将使用一个简单的类来给dat.GUI提供一个可以以度数为单位进行操作的对象,但它将以弧度为单位设置该属性。
<add>
<add>```js
<add>class DegRadHelper {
<add> constructor(obj, prop) {
<add> this.obj = obj;
<add> this.prop = prop;
<add> }
<add> get value() {
<add> return THREE.MathUtils.radToDeg(this.obj[this.prop]);
<add> }
<add> set value(v) {
<add> this.obj[this.prop] = THREE.MathUtils.degToRad(v);
<add> }
<add>}
<add>```
<add>
<add>我们还需要一个类,将 `"123"` 这样的字符串转换为 `123` 这样的数字,因为three.js的枚举设置需要数字,比如 `wrapS` 和 `wrapT`,但dat.GUI只使用字符串来设置枚举。
<add>
<add>```js
<add>class StringToNumberHelper {
<add> constructor(obj, prop) {
<add> this.obj = obj;
<add> this.prop = prop;
<add> }
<add> get value() {
<add> return this.obj[this.prop];
<add> }
<add> set value(v) {
<add> this.obj[this.prop] = parseFloat(v);
<add> }
<add>}
<add>```
<add>
<add>利用这些类,我们可以为上面的设置设置一个简单的GUI。
<add>
<add>```js
<add>const wrapModes = {
<add> 'ClampToEdgeWrapping': THREE.ClampToEdgeWrapping,
<add> 'RepeatWrapping': THREE.RepeatWrapping,
<add> 'MirroredRepeatWrapping': THREE.MirroredRepeatWrapping,
<add>};
<add>
<add>function updateTexture() {
<add> texture.needsUpdate = true;
<add>}
<add>
<add>const gui = new GUI();
<add>gui.add(new StringToNumberHelper(texture, 'wrapS'), 'value', wrapModes)
<add> .name('texture.wrapS')
<add> .onChange(updateTexture);
<add>gui.add(new StringToNumberHelper(texture, 'wrapT'), 'value', wrapModes)
<add> .name('texture.wrapT')
<add> .onChange(updateTexture);
<add>gui.add(texture.repeat, 'x', 0, 5, .01).name('texture.repeat.x');
<add>gui.add(texture.repeat, 'y', 0, 5, .01).name('texture.repeat.y');
<add>gui.add(texture.offset, 'x', -2, 2, .01).name('texture.offset.x');
<add>gui.add(texture.offset, 'y', -2, 2, .01).name('texture.offset.y');
<add>gui.add(texture.center, 'x', -.5, 1.5, .01).name('texture.center.x');
<add>gui.add(texture.center, 'y', -.5, 1.5, .01).name('texture.center.y');
<add>gui.add(new DegRadHelper(texture, 'rotation'), 'value', -360, 360)
<add> .name('texture.rotation');
<add>```
<add>
<add>最后需要注意的是,如果你改变了纹理上的 `wrapS` 或 `wrapT`,你还必须设置 [`texture.needsUpdate`](Texture.needsUpdate),以便three.js知道并应用这些设置。其他的设置会自动应用。
<add>
<add>{{{example url="../threejs-textured-cube-adjust.html" }}}
<add>
<add>这只是进入纹理主题的一个步骤。在某些时候,我们将介绍纹理坐标以及其他9种可应用于材料的纹理类型。
<add>
<add>现在我们继续说说[灯光](threejs-lights.html)。
<add>
<add><!--
<add>alpha
<add>ao
<add>env
<add>light
<add>specular
<add>bumpmap ?
<add>normalmap ?
<add>metalness
<add>roughness
<add>-->
<add>
<add><link rel="stylesheet" href="resources/threejs-textures.css">
<add><script type="module" src="resources/threejs-textures.js"></script> | 1 |
Text | Text | improve zlib docs | 477d35848c33e3e5cb7643a11973e5504f659581 | <ide><path>doc/api/zlib.md
<ide>
<ide> Stability: 2 - Stable
<ide>
<del>You can access this module with:
<add>The `zlib` module provides compression functionality implemented using Gzip and
<add>Deflate/Inflate. It can be accessed using:
<ide>
<del> const zlib = require('zlib');
<del>
<del>This provides bindings to Gzip/Gunzip, Deflate/Inflate, and
<del>DeflateRaw/InflateRaw classes. Each class takes the same options, and
<del>is a readable/writable Stream.
<del>
<del>## Examples
<add>```js
<add>const zlib = require('zlib');
<add>```
<ide>
<del>Compressing or decompressing a file can be done by piping an
<del>fs.ReadStream into a zlib stream, then into an fs.WriteStream.
<add>Compressing or decompressing a stream (such as a file) can be accomplished by
<add>piping the source stream data through a `zlib` stream into a destination stream:
<ide>
<ide> ```js
<ide> const gzip = zlib.createGzip();
<ide> const out = fs.createWriteStream('input.txt.gz');
<ide> inp.pipe(gzip).pipe(out);
<ide> ```
<ide>
<del>Compressing or decompressing data in one step can be done by using
<del>the convenience methods.
<add>It is also possible to compress or decompress data in a single step:
<ide>
<ide> ```js
<ide> const input = '.................................';
<ide> zlib.unzip(buffer, (err, buffer) => {
<ide> });
<ide> ```
<ide>
<del>To use this module in an HTTP client or server, use the [accept-encoding][]
<del>on requests, and the [content-encoding][] header on responses.
<add>## Compressing HTTP requests and responses
<add>
<add>The `zlib` module can be used to implement support for the `gzip` and `deflate`
<add>content-encoding mechanisms defined by
<add>[HTTP](https://tools.ietf.org/html/rfc7230#section-4.2).
<add>
<add>The HTTP [`Accept-Encoding`][] header is used within an http request to identify
<add>the compression encodings accepted by the client. The [`Content-Encoding`][]
<add>header is used to identify the compression encodings actually applied to a
<add>message.
<ide>
<del>**Note: these examples are drastically simplified to show
<del>the basic concept.** Zlib encoding can be expensive, and the results
<add>**Note: the examples given below are drastically simplified to show
<add>the basic concept.** Using `zlib` encoding can be expensive, and the results
<ide> ought to be cached. See [Memory Usage Tuning][] for more information
<del>on the speed/memory/compression tradeoffs involved in zlib usage.
<add>on the speed/memory/compression tradeoffs involved in `zlib` usage.
<ide>
<ide> ```js
<ide> // client request example
<ide> const zlib = require('zlib');
<ide> const http = require('http');
<ide> const fs = require('fs');
<del>const request = http.get({ host: 'izs.me',
<add>const request = http.get({ host: 'example.com',
<ide> path: '/',
<ide> port: 80,
<del> headers: { 'accept-encoding': 'gzip,deflate' } });
<add> headers: { 'Accept-Encoding': 'gzip,deflate' } });
<ide> request.on('response', (response) => {
<del> var output = fs.createWriteStream('izs.me_index.html');
<add> var output = fs.createWriteStream('example.com_index.html');
<ide>
<ide> switch (response.headers['content-encoding']) {
<ide> // or, just use zlib.createUnzip() to handle both cases
<ide> http.createServer((request, response) => {
<ide> // Note: this is not a conformant accept-encoding parser.
<ide> // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
<ide> if (acceptEncoding.match(/\bdeflate\b/)) {
<del> response.writeHead(200, { 'content-encoding': 'deflate' });
<add> response.writeHead(200, { 'Content-Encoding': 'deflate' });
<ide> raw.pipe(zlib.createDeflate()).pipe(response);
<ide> } else if (acceptEncoding.match(/\bgzip\b/)) {
<del> response.writeHead(200, { 'content-encoding': 'gzip' });
<add> response.writeHead(200, { 'Content-Encoding': 'gzip' });
<ide> raw.pipe(zlib.createGzip()).pipe(response);
<ide> } else {
<ide> response.writeHead(200, {});
<ide> http.createServer((request, response) => {
<ide> }).listen(1337);
<ide> ```
<ide>
<del>By default, the zlib methods with throw an error when decompressing
<add>By default, the `zlib` methods with throw an error when decompressing
<ide> truncated data. However, if it is known that the data is incomplete, or
<ide> the desire is to inspect only the beginning of a compressed file, it is
<ide> possible to suppress the default error handling by changing the flushing
<ide> The memory requirements for deflate are (in bytes):
<ide> (1 << (windowBits+2)) + (1 << (memLevel+9))
<ide> ```
<ide>
<del>that is: 128K for windowBits=15 + 128K for memLevel = 8
<add>That is: 128K for windowBits=15 + 128K for memLevel = 8
<ide> (default values) plus a few kilobytes for small objects.
<ide>
<del>For example, if you want to reduce
<del>the default memory requirements from 256K to 128K, set the options to:
<add>For example, to reduce the default memory requirements from 256K to 128K, the
<add>options shoud be set to:
<ide>
<ide> ```
<ide> { windowBits: 14, memLevel: 7 }
<ide> ```
<ide>
<del>Of course this will generally degrade compression (there's no free lunch).
<add>This will, however, generally degrade compression.
<ide>
<ide> The memory requirements for inflate are (in bytes)
<ide>
<ide> ```
<ide> 1 << windowBits
<ide> ```
<ide>
<del>that is, 32K for windowBits=15 (default value) plus a few kilobytes
<add>That is, 32K for windowBits=15 (default value) plus a few kilobytes
<ide> for small objects.
<ide>
<ide> This is in addition to a single internal output slab buffer of size
<ide> `chunkSize`, which defaults to 16K.
<ide>
<del>The speed of zlib compression is affected most dramatically by the
<add>The speed of `zlib` compression is affected most dramatically by the
<ide> `level` setting. A higher level will result in better compression, but
<ide> will take longer to complete. A lower level will result in less
<ide> compression, but will be much faster.
<ide>
<del>In general, greater memory usage options will mean that node.js has to make
<del>fewer calls to zlib, since it'll be able to process more data in a
<del>single `write` operation. So, this is another factor that affects the
<add>In general, greater memory usage options will mean that Node.js has to make
<add>fewer calls to `zlib` because it will be able to process more data on
<add>each `write` operation. So, this is another factor that affects the
<ide> speed, at the cost of memory usage.
<ide>
<ide> ## Flushing
<ide>
<del>Calling [`.flush()`][] on a compression stream will make zlib return as much
<add>Calling [`.flush()`][] on a compression stream will make `zlib` return as much
<ide> output as currently possible. This may come at the cost of degraded compression
<ide> quality, but can be useful when data needs to be available as soon as possible.
<ide>
<ide> http.createServer((request, response) => {
<ide>
<ide> <!--type=misc-->
<ide>
<del>All of the constants defined in zlib.h are also defined on
<del>`require('zlib')`.
<del>In the normal course of operations, you will not need to ever set any of
<del>these. They are documented here so that their presence is not
<del>surprising. This section is taken almost directly from the
<del>[zlib documentation][]. See <http://zlib.net/manual.html#Constants> for more
<del>details.
<add>All of the constants defined in `zlib.h` are also defined on `require('zlib')`.
<add>In the normal course of operations, it will not be necessary to use these
<add>constants. They are documented so that their presence is not surprising. This
<add>section is taken almost directly from the [zlib documentation][]. See
<add><http://zlib.net/manual.html#Constants> for more details.
<ide>
<ide> Allowed flush values.
<ide>
<ide> For initializing zalloc, zfree, opaque.
<ide>
<ide> <!--type=misc-->
<ide>
<del>Each class takes an options object. All options are optional.
<add>Each class takes an `options` object. All options are optional.
<ide>
<ide> Note that some options are only relevant when compressing, and are
<ide> ignored by the decompression classes.
<ide>
<del>* flush (default: `zlib.Z_NO_FLUSH`)
<del>* finishFlush (default: `zlib.Z_FINISH`)
<del>* chunkSize (default: 16*1024)
<del>* windowBits
<del>* level (compression only)
<del>* memLevel (compression only)
<del>* strategy (compression only)
<del>* dictionary (deflate/inflate only, empty dictionary by default)
<add>* `flush` (default: `zlib.Z_NO_FLUSH`)
<add>* `finishFlush` (default: `zlib.Z_FINISH`)
<add>* `chunkSize` (default: 16*1024)
<add>* `windowBits`
<add>* `level` (compression only)
<add>* `memLevel` (compression only)
<add>* `strategy` (compression only)
<add>* `dictionary` (deflate/inflate only, empty dictionary by default)
<ide>
<ide> See the description of `deflateInit2` and `inflateInit2` at
<ide> <http://zlib.net/manual.html#Advanced> for more information on these.
<ide> Compress data using deflate.
<ide>
<ide> ## Class: zlib.DeflateRaw
<ide>
<del>Compress data using deflate, and do not append a zlib header.
<add>Compress data using deflate, and do not append a `zlib` header.
<ide>
<ide> ## Class: zlib.Gunzip
<ide>
<ide> class of the compressor/decompressor classes.
<ide> Flush pending data. Don't call this frivolously, premature flushes negatively
<ide> impact the effectiveness of the compression algorithm.
<ide>
<del>Calling this only flushes data from the internal zlib state, and does not
<add>Calling this only flushes data from the internal `zlib` state, and does not
<ide> perform flushing of any kind on the streams level. Rather, it behaves like a
<ide> normal call to `.write()`, i.e. it will be queued up behind other pending
<ide> writes and will only produce output when data is being read from the stream.
<ide> Returns a new [Unzip][] object with an [options][].
<ide>
<ide> <!--type=misc-->
<ide>
<del>All of these take a [Buffer][] or string as the first argument, an optional second
<del>argument to supply options to the zlib classes and will call the supplied
<del>callback with `callback(error, result)`.
<add>All of these take a [Buffer][] or string as the first argument, an optional
<add>second argument to supply options to the `zlib` classes and will call the
<add>supplied callback with `callback(error, result)`.
<ide>
<ide> Every method has a `*Sync` counterpart, which accept the same arguments, but
<ide> without a callback.
<ide> Decompress a Buffer or string with InflateRaw.
<ide>
<ide> Decompress a Buffer or string with Unzip.
<ide>
<del>[accept-encoding]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
<del>[content-encoding]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
<add>[`Accept-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
<add>[`Content-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
<ide> [Memory Usage Tuning]: #zlib_memory_usage_tuning
<ide> [zlib documentation]: http://zlib.net/manual.html#Constants
<ide> [options]: #zlib_class_options | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.