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
|
|---|---|---|---|---|---|
Python
|
Python
|
solve the issue #52 with python 2.x
|
b93dcb46b97a84e7d37af23639c6d43fa0aa4eb1
|
<ide><path>glances/glances.py
<ide> from __future__ import generators
<ide>
<ide> __appname__ = 'glances'
<del>__version__ = "1.4.1"
<add>__version__ = "1.4"
<ide> __author__ = "Nicolas Hennion <nicolas@nicolargo.com>"
<ide> __licence__ = "LGPL"
<ide>
| 1
|
Java
|
Java
|
apply promotions for v2.1
|
2d20a170454cd3bb7dbdc6d9d2d9a279bae5e2b0
|
<ide><path>src/main/java/io/reactivex/Completable.java
<ide> public final Throwable blockingGet(long timeout, TimeUnit unit) {
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code cache} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<add> * <p>History: 2.0.4 - experimental
<ide> * @return the new Completable instance
<del> * @since 2.0.4 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> @Experimental
<ide> public final Completable cache() {
<ide> return RxJavaPlugins.onAssembly(new CompletableCache(this));
<ide> }
<ide> public final Completable doAfterTerminate(final Action onAfterTerminate) {
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code doFinally} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<add> * <p>History: 2.0.1 - experimental
<ide> * @param onFinally the action called when this Completable terminates or gets cancelled
<ide> * @return the new Completable instance
<del> * @since 2.0.1 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> @Experimental
<ide> public final Completable doFinally(Action onFinally) {
<ide> ObjectHelper.requireNonNull(onFinally, "onFinally is null");
<ide> return RxJavaPlugins.onAssembly(new CompletableDoFinally(this, onFinally));
<ide> public final <T> Flowable<T> startWith(Publisher<T> other) {
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code hide} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<add> * <p>History: 2.0.5 - experimental
<ide> * @return the new Completable instance
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public final Completable hide() {
<ide><path>src/main/java/io/reactivex/Flowable.java
<ide> public final Flowable<T> distinctUntilChanged(BiPredicate<? super T, ? super T>
<ide> * <dd>This operator supports normal and conditional Subscribers as well as boundary-limited
<ide> * synchronous or asynchronous queue-fusion.</dd>
<ide> * </dl>
<add> * <p>History: 2.0.1 - experimental
<ide> * @param onFinally the action called when this Flowable terminates or gets cancelled
<ide> * @return the new Flowable instance
<del> * @since 2.0.1 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @BackpressureSupport(BackpressureKind.PASS_THROUGH)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> @Experimental
<ide> public final Flowable<T> doFinally(Action onFinally) {
<ide> ObjectHelper.requireNonNull(onFinally, "onFinally is null");
<ide> return RxJavaPlugins.onAssembly(new FlowableDoFinally<T>(this, onFinally));
<ide> public final Flowable<T> doFinally(Action onFinally) {
<ide> * <dd>This operator supports normal and conditional Subscribers as well as boundary-limited
<ide> * synchronous or asynchronous queue-fusion.</dd>
<ide> * </dl>
<add> * <p>History: 2.0.1 - experimental
<ide> * @param onAfterNext the Consumer that will be called after emitting an item from upstream to the downstream
<ide> * @return the new Flowable instance
<del> * @since 2.0.1 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @BackpressureSupport(BackpressureKind.PASS_THROUGH)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> @Experimental
<ide> public final Flowable<T> doAfterNext(Consumer<? super T> onAfterNext) {
<ide> ObjectHelper.requireNonNull(onAfterNext, "onAfterNext is null");
<ide> return RxJavaPlugins.onAssembly(new FlowableDoAfterNext<T>(this, onAfterNext));
<ide> public final Flowable<T> onTerminateDetach() {
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code parallel} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<add> * <p>History: 2.0.5 - experimental
<ide> * @return the new ParallelFlowable instance
<del> * @since 2.0.5 - experimental
<add> * @since 2.1 - beta
<ide> */
<ide> @BackpressureSupport(BackpressureKind.FULL)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> @CheckReturnValue
<del> @Experimental
<add> @Beta
<ide> public final ParallelFlowable<T> parallel() {
<ide> return ParallelFlowable.from(this);
<ide> }
<ide> public final ParallelFlowable<T> parallel() {
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code parallel} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<add> * <p>History: 2.0.5 - experimental
<ide> * @param parallelism the number of 'rails' to use
<ide> * @return the new ParallelFlowable instance
<del> * @since 2.0.5 - experimental
<add> * @since 2.1 - beta
<ide> */
<ide> @BackpressureSupport(BackpressureKind.FULL)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> @CheckReturnValue
<del> @Experimental
<add> @Beta
<ide> public final ParallelFlowable<T> parallel(int parallelism) {
<ide> ObjectHelper.verifyPositive(parallelism, "parallelism");
<ide> return ParallelFlowable.from(this, parallelism);
<ide> public final ParallelFlowable<T> parallel(int parallelism) {
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code parallel} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<add> * <p>History: 2.0.5 - experimental
<ide> * @param parallelism the number of 'rails' to use
<ide> * @param prefetch the number of items each 'rail' should prefetch
<ide> * @return the new ParallelFlowable instance
<del> * @since 2.0.5 - experimental
<add> * @since 2.1 - beta
<ide> */
<ide> @BackpressureSupport(BackpressureKind.FULL)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> @CheckReturnValue
<del> @Experimental
<add> @Beta
<ide> public final ParallelFlowable<T> parallel(int parallelism, int prefetch) {
<ide> ObjectHelper.verifyPositive(parallelism, "parallelism");
<ide> ObjectHelper.verifyPositive(prefetch, "prefetch");
<ide> public final Flowable<T> sample(long period, TimeUnit unit) {
<ide> * <dd>{@code sample} operates by default on the {@code computation} {@link Scheduler}.</dd>
<ide> * </dl>
<ide> *
<add> * <p>History: 2.0.5 - experimental
<ide> * @param period
<ide> * the sampling rate
<ide> * @param unit
<ide> public final Flowable<T> sample(long period, TimeUnit unit) {
<ide> * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a>
<ide> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a>
<ide> * @see #throttleLast(long, TimeUnit)
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @BackpressureSupport(BackpressureKind.ERROR)
<ide> @SchedulerSupport(SchedulerSupport.COMPUTATION)
<del> @Experimental
<ide> public final Flowable<T> sample(long period, TimeUnit unit, boolean emitLast) {
<ide> return sample(period, unit, Schedulers.computation(), emitLast);
<ide> }
<ide> public final Flowable<T> sample(long period, TimeUnit unit, Scheduler scheduler)
<ide> * <dd>You specify which {@link Scheduler} this operator will use</dd>
<ide> * </dl>
<ide> *
<add> * <p>History: 2.0.5 - experimental
<ide> * @param period
<ide> * the sampling rate
<ide> * @param unit
<ide> public final Flowable<T> sample(long period, TimeUnit unit, Scheduler scheduler)
<ide> * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a>
<ide> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a>
<ide> * @see #throttleLast(long, TimeUnit, Scheduler)
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @BackpressureSupport(BackpressureKind.ERROR)
<ide> @SchedulerSupport(SchedulerSupport.CUSTOM)
<del> @Experimental
<ide> public final Flowable<T> sample(long period, TimeUnit unit, Scheduler scheduler, boolean emitLast) {
<ide> ObjectHelper.requireNonNull(unit, "unit is null");
<ide> ObjectHelper.requireNonNull(scheduler, "scheduler is null");
<ide> public final <U> Flowable<T> sample(Publisher<U> sampler) {
<ide> * <dd>This version of {@code sample} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> *
<add> * <p>History: 2.0.5 - experimental
<ide> * @param <U> the element type of the sampler Publisher
<ide> * @param sampler
<ide> * the Publisher to use for sampling the source Publisher
<ide> public final <U> Flowable<T> sample(Publisher<U> sampler) {
<ide> * the {@code sampler} Publisher emits an item or completes
<ide> * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a>
<ide> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a>
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @BackpressureSupport(BackpressureKind.ERROR)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> @Experimental
<ide> public final <U> Flowable<T> sample(Publisher<U> sampler, boolean emitLast) {
<ide> ObjectHelper.requireNonNull(sampler, "sampler is null");
<ide> return RxJavaPlugins.onAssembly(new FlowableSamplePublisher<T>(this, sampler, emitLast));
<ide> public final Flowable<T> startWithArray(T... items) {
<ide> return concatArray(fromArray, this);
<ide> }
<ide>
<del> /**
<del> * Ensures that the event flow between the upstream and downstream follow
<del> * the Reactive-Streams 1.0 specification by honoring the 3 additional rules
<del> * (which are omitted in standard operators due to performance reasons).
<del> * <ul>
<del> * <li>§1.3: onNext should not be called concurrently until onSubscribe returns</li>
<del> * <li>§2.3: onError or onComplete must not call cancel</li>
<del> * <li>§3.9: negative requests should emit an onError(IllegalArgumentException)</li>
<del> * </ul>
<del> * In addition, if rule §2.12 (onSubscribe must be called at most once) is violated,
<del> * the sequence is cancelled an onError(IllegalStateException) is emitted.
<del> * <dl>
<del> * <dt><b>Backpressure:</b></dt>
<del> * <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s backpressure
<del> * behavior.</dd>
<del> * <dt><b>Scheduler:</b></dt>
<del> * <dd>{@code strict} does not operate by default on a particular {@link Scheduler}.</dd>
<del> * </dl>
<del> * @return the new Flowable instance
<del> * @since 2.0.5 - experimental
<del> * @deprecated 2.0.7, will be removed in 2.1.0; by default, the Publisher interface is always strict
<del> */
<del> @BackpressureSupport(BackpressureKind.PASS_THROUGH)
<del> @SchedulerSupport(SchedulerSupport.NONE)
<del> @Experimental
<del> @CheckReturnValue
<del> @Deprecated
<del> public final Flowable<T> strict() {
<del> return this;
<del> }
<del>
<ide> /**
<ide> * Subscribes to a Publisher and ignores {@code onNext} and {@code onComplete} emissions.
<ide> * <p>
<ide> public final void subscribe(Subscriber<? super T> s) {
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<add> * <p>History: 2.0.7 - experimental
<ide> * @param s the FlowableSubscriber that will consume signals from this Flowable
<del> * @since 2.0.7 - experimental
<add> * @since 2.1 - beta
<ide> */
<ide> @BackpressureSupport(BackpressureKind.SPECIAL)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> @Experimental
<add> @Beta
<ide> public final void subscribe(FlowableSubscriber<? super T> s) {
<ide> ObjectHelper.requireNonNull(s, "s is null");
<ide> try {
<ide><path>src/main/java/io/reactivex/FlowableSubscriber.java
<ide> * Represents a Reactive-Streams inspired Subscriber that is RxJava 2 only
<ide> * and weakens rules §1.3 and §3.9 of the specification for gaining performance.
<ide> *
<add> * <p>History: 2.0.7 - experimental
<ide> * @param <T> the value type
<del> * @since 2.0.7 - experimental
<add> * @since 2.1 - beta
<ide> */
<del>@Experimental
<add>@Beta
<ide> public interface FlowableSubscriber<T> extends Subscriber<T> {
<ide>
<ide> /**
<ide><path>src/main/java/io/reactivex/Maybe.java
<ide> public final Maybe<T> delaySubscription(long delay, TimeUnit unit, Scheduler sch
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code doAfterSuccess} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<add> * <p>History: 2.0.1 - experimental
<ide> * @param onAfterSuccess the Consumer that will be called after emitting an item from upstream to the downstream
<ide> * @return the new Maybe instance
<del> * @since 2.0.1 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> @Experimental
<ide> public final Maybe<T> doAfterSuccess(Consumer<? super T> onAfterSuccess) {
<ide> ObjectHelper.requireNonNull(onAfterSuccess, "doAfterSuccess is null");
<ide> return RxJavaPlugins.onAssembly(new MaybeDoAfterSuccess<T>(this, onAfterSuccess));
<ide> public final Maybe<T> doAfterTerminate(Action onAfterTerminate) {
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code doFinally} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<add> * <p>History: 2.0.1 - experimental
<ide> * @param onFinally the action called when this Maybe terminates or gets cancelled
<ide> * @return the new Maybe instance
<del> * @since 2.0.1 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> @Experimental
<ide> public final Maybe<T> doFinally(Action onFinally) {
<ide> ObjectHelper.requireNonNull(onFinally, "onFinally is null");
<ide> return RxJavaPlugins.onAssembly(new MaybeDoFinally<T>(this, onFinally));
<ide> public final <R> Single<R> flatMapSingle(final Function<? super T, ? extends Sin
<ide> * <dd>{@code flatMapSingleElement} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> *
<add> * <p>History: 2.0.2 - experimental
<ide> * @param <R> the result value type
<ide> * @param mapper
<ide> * a function that, when applied to the item emitted by the source Maybe, returns a
<ide> * Single
<ide> * @return the new Maybe instance
<ide> * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a>
<del> * @since 2.0.2 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> @Experimental
<ide> public final <R> Maybe<R> flatMapSingleElement(final Function<? super T, ? extends SingleSource<? extends R>> mapper) {
<ide> ObjectHelper.requireNonNull(mapper, "mapper is null");
<ide> return RxJavaPlugins.onAssembly(new MaybeFlatMapSingleElement<T, R>(this, mapper));
<ide><path>src/main/java/io/reactivex/Observable.java
<ide> public final Observable<T> distinctUntilChanged(BiPredicate<? super T, ? super T
<ide> * <td><b>Operator-fusion:</b></dt>
<ide> * <dd>This operator supports boundary-limited synchronous or asynchronous queue-fusion.</dd>
<ide> * </dl>
<add> * <p>History: 2.0.1 - experimental
<ide> * @param onAfterNext the Consumer that will be called after emitting an item from upstream to the downstream
<ide> * @return the new Observable instance
<del> * @since 2.0.1 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> @Experimental
<ide> public final Observable<T> doAfterNext(Consumer<? super T> onAfterNext) {
<ide> ObjectHelper.requireNonNull(onAfterNext, "onAfterNext is null");
<ide> return RxJavaPlugins.onAssembly(new ObservableDoAfterNext<T>(this, onAfterNext));
<ide> public final Observable<T> doAfterTerminate(Action onFinally) {
<ide> * <td><b>Operator-fusion:</b></dt>
<ide> * <dd>This operator supports boundary-limited synchronous or asynchronous queue-fusion.</dd>
<ide> * </dl>
<add> * <p>History: 2.0.1 - experimental
<ide> * @param onFinally the action called when this Observable terminates or gets cancelled
<ide> * @return the new Observable instance
<del> * @since 2.0.1 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> @Experimental
<ide> public final Observable<T> doFinally(Action onFinally) {
<ide> ObjectHelper.requireNonNull(onFinally, "onFinally is null");
<ide> return RxJavaPlugins.onAssembly(new ObservableDoFinally<T>(this, onFinally));
<ide> public final Observable<T> sample(long period, TimeUnit unit) {
<ide> * <dd>{@code sample} operates by default on the {@code computation} {@link Scheduler}.</dd>
<ide> * </dl>
<ide> *
<add> * <p>History: 2.0.5 - experimental
<ide> * @param period
<ide> * the sampling rate
<ide> * @param unit
<ide> public final Observable<T> sample(long period, TimeUnit unit) {
<ide> * if false, an unsampled last item is ignored.
<ide> * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a>
<ide> * @see #throttleLast(long, TimeUnit)
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.COMPUTATION)
<del> @Experimental
<ide> public final Observable<T> sample(long period, TimeUnit unit, boolean emitLast) {
<ide> return sample(period, unit, Schedulers.computation(), emitLast);
<ide> }
<ide> public final Observable<T> sample(long period, TimeUnit unit, Scheduler schedule
<ide> * <dd>You specify which {@link Scheduler} this operator will use</dd>
<ide> * </dl>
<ide> *
<add> * <p>History: 2.0.5 - experimental
<ide> * @param period
<ide> * the sampling rate
<ide> * @param unit
<ide> public final Observable<T> sample(long period, TimeUnit unit, Scheduler schedule
<ide> * the specified time interval
<ide> * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a>
<ide> * @see #throttleLast(long, TimeUnit, Scheduler)
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.CUSTOM)
<del> @Experimental
<ide> public final Observable<T> sample(long period, TimeUnit unit, Scheduler scheduler, boolean emitLast) {
<ide> ObjectHelper.requireNonNull(unit, "unit is null");
<ide> ObjectHelper.requireNonNull(scheduler, "scheduler is null");
<ide> public final <U> Observable<T> sample(ObservableSource<U> sampler) {
<ide> * <dd>This version of {@code sample} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> *
<add> * <p>History: 2.0.5 - experimental
<ide> * @param <U> the element type of the sampler ObservableSource
<ide> * @param sampler
<ide> * the ObservableSource to use for sampling the source ObservableSource
<ide> public final <U> Observable<T> sample(ObservableSource<U> sampler) {
<ide> * @return an Observable that emits the results of sampling the items emitted by this ObservableSource whenever
<ide> * the {@code sampler} ObservableSource emits an item or completes
<ide> * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a>
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> @Experimental
<ide> public final <U> Observable<T> sample(ObservableSource<U> sampler, boolean emitLast) {
<ide> ObjectHelper.requireNonNull(sampler, "sampler is null");
<ide> return RxJavaPlugins.onAssembly(new ObservableSampleWithObservable<T>(this, sampler, emitLast));
<ide><path>src/main/java/io/reactivex/Scheduler.java
<ide> public Disposable schedulePeriodicallyDirect(@NonNull Runnable run, long initial
<ide> * });
<ide> * </pre>
<ide> *
<add> * <p>History: 2.0.1 - experimental
<ide> * @param <S> a Scheduler and a Subscription
<ide> * @param combine the function that takes a two-level nested Flowable sequence of a Completable and returns
<ide> * the Completable that will be subscribed to and should trigger the execution of the scheduled Actions.
<ide> * @return the Scheduler with the customized execution behavior
<add> * @since 2.1
<ide> */
<ide> @SuppressWarnings("unchecked")
<del> @Experimental
<ide> @NonNull
<ide> public <S extends Scheduler & Disposable> S when(@NonNull Function<Flowable<Flowable<Completable>>, Completable> combine) {
<ide> return (S) new SchedulerWhen(combine, this);
<ide><path>src/main/java/io/reactivex/Single.java
<ide> public final <U> Single<T> delaySubscription(long time, TimeUnit unit, Scheduler
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code doAfterSuccess} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<add> * <p>History: 2.0.1 - experimental
<ide> * @param onAfterSuccess the Consumer that will be called after emitting an item from upstream to the downstream
<ide> * @return the new Single instance
<del> * @since 2.0.1 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> @Experimental
<ide> public final Single<T> doAfterSuccess(Consumer<? super T> onAfterSuccess) {
<ide> ObjectHelper.requireNonNull(onAfterSuccess, "doAfterSuccess is null");
<ide> return RxJavaPlugins.onAssembly(new SingleDoAfterSuccess<T>(this, onAfterSuccess));
<ide> public final Single<T> doAfterSuccess(Consumer<? super T> onAfterSuccess) {
<ide> * <dd>{@code doAfterTerminate} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> *
<add> * <p>History: 2.0.6 - experimental
<ide> * @param onAfterTerminate
<ide> * an {@link Action} to be invoked when the source Single finishes
<ide> * @return a Single that emits the same items as the source Single, then invokes the
<ide> * {@link Action}
<ide> * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a>
<del> * @since 2.0.6 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> @Experimental
<ide> public final Single<T> doAfterTerminate(Action onAfterTerminate) {
<ide> ObjectHelper.requireNonNull(onAfterTerminate, "onAfterTerminate is null");
<ide> return RxJavaPlugins.onAssembly(new SingleDoAfterTerminate<T>(this, onAfterTerminate));
<ide> public final Single<T> doAfterTerminate(Action onAfterTerminate) {
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code doFinally} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<add> * <p>History: 2.0.1 - experimental
<ide> * @param onFinally the action called when this Single terminates or gets cancelled
<ide> * @return the new Single instance
<del> * @since 2.0.1 - experimental
<add> * @since 2.1
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> @Experimental
<ide> public final Single<T> doFinally(Action onFinally) {
<ide> ObjectHelper.requireNonNull(onFinally, "onFinally is null");
<ide> return RxJavaPlugins.onAssembly(new SingleDoFinally<T>(this, onFinally));
<ide><path>src/main/java/io/reactivex/annotations/BackpressureKind.java
<ide>
<ide> /**
<ide> * Enumeration for various kinds of backpressure support.
<add> * @since 2.0
<ide> */
<ide> public enum BackpressureKind {
<ide> /**
<ide><path>src/main/java/io/reactivex/annotations/BackpressureSupport.java
<ide>
<ide> /**
<ide> * Indicates the backpressure support kind of the associated operator or class.
<add> * @since 2.0
<ide> */
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> @Documented
<ide><path>src/main/java/io/reactivex/annotations/CheckReturnValue.java
<ide>
<ide> /**
<ide> * Marks methods whose return values should be checked.
<del> *
<del> * @since 2.0.2 - experimental
<add> * <p>History: 2.0.2 - experimental
<add> * @since 2.1
<ide> */
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> @Documented
<ide> @Target(ElementType.METHOD)
<del>@Experimental
<ide> public @interface CheckReturnValue {
<ide>
<ide> }
<ide><path>src/main/java/io/reactivex/annotations/SchedulerSupport.java
<ide> * {@linkplain #NONE not using a scheduler} and {@linkplain #CUSTOM a manually-specified scheduler}.
<ide> * Libraries providing their own values should namespace them with their base package name followed
<ide> * by a colon ({@code :}) and then a human-readable name (e.g., {@code com.example:ui-thread}).
<add> * @since 2.0
<ide> */
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> @Documented
<ide><path>src/main/java/io/reactivex/exceptions/OnErrorNotImplementedException.java
<ide> * Represents an exception used to signal to the {@code RxJavaPlugins.onError()} that a
<ide> * callback-based subscribe() method on a base reactive type didn't specify
<ide> * an onError handler.
<del> * @since 2.0.6 - experimental
<add> * <p>History: 2.0.6 - experimental
<add> * @since 2.1 - beta
<ide> */
<del>@Experimental
<add>@Beta
<ide> public final class OnErrorNotImplementedException extends RuntimeException {
<ide>
<ide> private static final long serialVersionUID = -6298857009889503852L;
<ide><path>src/main/java/io/reactivex/exceptions/ProtocolViolationException.java
<ide>
<ide> package io.reactivex.exceptions;
<ide>
<del>import io.reactivex.annotations.Experimental;
<add>import io.reactivex.annotations.Beta;
<ide>
<ide> /**
<ide> * Explicitly named exception to indicate a Reactive-Streams
<ide> * protocol violation.
<del> * @since 2.0.6 - experimental
<add> * <p>History: 2.0.6 - experimental
<add> * @since 2.1 - beta
<ide> */
<del>@Experimental
<add>@Beta
<ide> public final class ProtocolViolationException extends IllegalStateException {
<ide>
<ide> private static final long serialVersionUID = 1644750035281290266L;
<ide><path>src/main/java/io/reactivex/exceptions/UndeliverableException.java
<ide>
<ide> package io.reactivex.exceptions;
<ide>
<del>import io.reactivex.annotations.Experimental;
<add>import io.reactivex.annotations.Beta;
<ide>
<ide> /**
<ide> * Wrapper for Throwable errors that are sent to `RxJavaPlugins.onError`.
<del> * @since 2.0.6 - experimental
<add> * <p>History: 2.0.6 - experimental
<add> * @since 2.1 - beta
<ide> */
<del>@Experimental
<add>@Beta
<ide> public final class UndeliverableException extends IllegalStateException {
<ide>
<ide> private static final long serialVersionUID = 1644750035281290266L;
<ide><path>src/main/java/io/reactivex/observers/BaseTestConsumer.java
<ide> import java.util.concurrent.*;
<ide>
<ide> import io.reactivex.Notification;
<del>import io.reactivex.annotations.Experimental;
<ide> import io.reactivex.disposables.Disposable;
<ide> import io.reactivex.exceptions.CompositeException;
<ide> import io.reactivex.functions.Predicate;
<ide> public final U assertValue(T value) {
<ide> * Assert that this TestObserver/TestSubscriber did not receive an onNext value which is equal to
<ide> * the given value with respect to Objects.equals.
<ide> *
<del> * @since 2.0.5 - experimental
<add> * <p>History: 2.0.5 - experimental
<ide> * @param value the value to expect not being received
<del> * @return this;
<add> * @return this
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> @SuppressWarnings("unchecked")
<ide> public final U assertNever(T value) {
<ide> int s = values.size();
<ide> public final U assertValue(Predicate<T> valuePredicate) {
<ide> * Asserts that this TestObserver/TestSubscriber did not receive any onNext value for which
<ide> * the provided predicate returns true.
<ide> *
<del> * @since 2.0.5 - experimental
<add> * <p>History: 2.0.5 - experimental
<ide> * @param valuePredicate the predicate that receives the onNext value
<ide> * and should return true for the expected value.
<ide> * @return this
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> @SuppressWarnings("unchecked")
<ide> public final U assertNever(Predicate<? super T> valuePredicate) {
<ide> int s = values.size();
<ide> public final U assertEmpty() {
<ide> /**
<ide> * Set the tag displayed along with an assertion failure's
<ide> * other state information.
<add> * <p>History: 2.0.7 - experimental
<ide> * @param tag the string to display (null won't print any tag)
<ide> * @return this
<del> * @since 2.0.7 - experimental
<add> * @since 2.1
<ide> */
<ide> @SuppressWarnings("unchecked")
<del> @Experimental
<ide> public final U withTag(CharSequence tag) {
<ide> this.tag = tag;
<ide> return (U)this;
<ide> public final U withTag(CharSequence tag) {
<ide> /**
<ide> * Enumeration of default wait strategies when waiting for a specific number of
<ide> * items in {@link BaseTestConsumer#awaitCount(int, Runnable)}.
<del> * @since 2.0.7 - experimental
<add> * <p>History: 2.0.7 - experimental
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> public enum TestWaitStrategy implements Runnable {
<ide> /** The wait loop will spin as fast as possible. */
<ide> SPIN {
<ide> static void sleep(int millis) {
<ide> * Await until the TestObserver/TestSubscriber receives the given
<ide> * number of items or terminates by sleeping 10 milliseconds at a time
<ide> * up to 5000 milliseconds of timeout.
<add> * <p>History: 2.0.7 - experimental
<ide> * @param atLeast the number of items expected at least
<ide> * @return this
<ide> * @see #awaitCount(int, Runnable, long)
<del> * @since 2.0.7 - experimental
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> public final U awaitCount(int atLeast) {
<ide> return awaitCount(atLeast, TestWaitStrategy.SLEEP_10MS, 5000);
<ide> }
<ide> public final U awaitCount(int atLeast) {
<ide> * Await until the TestObserver/TestSubscriber receives the given
<ide> * number of items or terminates by waiting according to the wait
<ide> * strategy and up to 5000 milliseconds of timeout.
<add> * <p>History: 2.0.7 - experimental
<ide> * @param atLeast the number of items expected at least
<ide> * @param waitStrategy a Runnable called when the current received count
<ide> * hasn't reached the expected value and there was
<ide> * no terminal event either, see {@link TestWaitStrategy}
<ide> * for examples
<ide> * @return this
<ide> * @see #awaitCount(int, Runnable, long)
<del> * @since 2.0.7 - experimental
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> public final U awaitCount(int atLeast, Runnable waitStrategy) {
<ide> return awaitCount(atLeast, waitStrategy, 5000);
<ide> }
<ide>
<ide> /**
<ide> * Await until the TestObserver/TestSubscriber receives the given
<ide> * number of items or terminates.
<add> * <p>History: 2.0.7 - experimental
<ide> * @param atLeast the number of items expected at least
<ide> * @param waitStrategy a Runnable called when the current received count
<ide> * hasn't reached the expected value and there was
<ide> public final U awaitCount(int atLeast, Runnable waitStrategy) {
<ide> * @param timeoutMillis if positive, the await ends if the specified amount of
<ide> * time has passed no matter how many items were received
<ide> * @return this
<del> * @since 2.0.7 - experimental
<add> * @since 2.1
<ide> */
<ide> @SuppressWarnings("unchecked")
<del> @Experimental
<ide> public final U awaitCount(int atLeast, Runnable waitStrategy, long timeoutMillis) {
<ide> long start = System.currentTimeMillis();
<ide> for (;;) {
<ide> public final U awaitCount(int atLeast, Runnable waitStrategy, long timeoutMillis
<ide>
<ide> /**
<ide> * @return true if one of the timeout-based await methods has timed out.
<add> * <p>History: 2.0.7 - experimental
<ide> * @see #clearTimeout()
<ide> * @see #assertTimeout()
<ide> * @see #assertNoTimeout()
<del> * @since 2.0.7 - experimental
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> public final boolean isTimeout() {
<ide> return timeout;
<ide> }
<ide>
<ide> /**
<ide> * Clears the timeout flag set by the await methods when they timed out.
<add> * <p>History: 2.0.7 - experimental
<ide> * @return this
<del> * @since 2.0.7 - experimental
<add> * @since 2.1
<ide> * @see #isTimeout()
<ide> */
<ide> @SuppressWarnings("unchecked")
<del> @Experimental
<ide> public final U clearTimeout() {
<ide> timeout = false;
<ide> return (U)this;
<ide> }
<ide>
<ide> /**
<ide> * Asserts that some awaitX method has timed out.
<add> * <p>History: 2.0.7 - experimental
<ide> * @return this
<del> * @since 2.0.7 - experimental
<add> * @since 2.1
<ide> */
<ide> @SuppressWarnings("unchecked")
<del> @Experimental
<ide> public final U assertTimeout() {
<ide> if (!timeout) {
<ide> throw fail("No timeout?!");
<ide> public final U assertTimeout() {
<ide>
<ide> /**
<ide> * Asserts that some awaitX method has not timed out.
<add> * <p>History: 2.0.7 - experimental
<ide> * @return this
<del> * @since 2.0.7 - experimental
<add> * @since 2.1
<ide> */
<ide> @SuppressWarnings("unchecked")
<del> @Experimental
<ide> public final U assertNoTimeout() {
<ide> if (timeout) {
<ide> throw fail("Timeout?!");
<ide><path>src/main/java/io/reactivex/parallel/ParallelFlowable.java
<ide> * Use {@code runOn()} to introduce where each 'rail' should run on thread-vise.
<ide> * Use {@code sequential()} to merge the sources back into a single Flowable.
<ide> *
<add> * <p>History: 2.0.5 - experimental
<ide> * @param <T> the value type
<del> * @since 2.0.5 - experimental
<add> * @since 2.1 - beta
<ide> */
<del>@Experimental
<add>@Beta
<ide> public abstract class ParallelFlowable<T> {
<ide>
<ide> /**
<ide><path>src/main/java/io/reactivex/plugins/RxJavaPlugins.java
<ide> */
<ide> package io.reactivex.plugins;
<ide>
<del>import io.reactivex.Completable;
<del>import io.reactivex.CompletableObserver;
<del>import io.reactivex.Flowable;
<del>import io.reactivex.Maybe;
<del>import io.reactivex.MaybeObserver;
<del>import io.reactivex.Observable;
<del>import io.reactivex.Observer;
<del>import io.reactivex.Scheduler;
<del>import io.reactivex.Single;
<del>import io.reactivex.SingleObserver;
<del>import io.reactivex.annotations.Experimental;
<del>import io.reactivex.annotations.NonNull;
<del>import io.reactivex.annotations.Nullable;
<add>import java.lang.Thread.UncaughtExceptionHandler;
<add>import java.util.concurrent.*;
<add>
<add>import org.reactivestreams.Subscriber;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.annotations.*;
<ide> import io.reactivex.exceptions.*;
<ide> import io.reactivex.flowables.ConnectableFlowable;
<del>import io.reactivex.functions.BiFunction;
<del>import io.reactivex.functions.BooleanSupplier;
<del>import io.reactivex.functions.Consumer;
<del>import io.reactivex.functions.Function;
<add>import io.reactivex.functions.*;
<ide> import io.reactivex.internal.functions.ObjectHelper;
<del>import io.reactivex.internal.schedulers.ComputationScheduler;
<del>import io.reactivex.internal.schedulers.IoScheduler;
<del>import io.reactivex.internal.schedulers.NewThreadScheduler;
<del>import io.reactivex.internal.schedulers.SingleScheduler;
<add>import io.reactivex.internal.schedulers.*;
<ide> import io.reactivex.internal.util.ExceptionHelper;
<ide> import io.reactivex.observables.ConnectableObservable;
<ide> import io.reactivex.parallel.ParallelFlowable;
<ide> import io.reactivex.schedulers.Schedulers;
<del>import org.reactivestreams.Subscriber;
<del>
<del>import java.lang.Thread.UncaughtExceptionHandler;
<del>import java.util.concurrent.Callable;
<del>import java.util.concurrent.ThreadFactory;
<ide> /**
<ide> * Utility class to inject handlers to certain standard RxJava operations.
<ide> */
<ide> public static boolean isLockdown() {
<ide> * Enables or disables the blockingX operators to fail
<ide> * with an IllegalStateException on a non-blocking
<ide> * scheduler such as computation or single.
<add> * <p>History: 2.0.5 - experimental
<ide> * @param enable enable or disable the feature
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> public static void setFailOnNonBlockingScheduler(boolean enable) {
<ide> if (lockdown) {
<ide> throw new IllegalStateException("Plugins can't be changed anymore");
<ide> public static void setFailOnNonBlockingScheduler(boolean enable) {
<ide> * Returns true if the blockingX operators fail
<ide> * with an IllegalStateException on a non-blocking scheduler
<ide> * such as computation or single.
<add> * <p>History: 2.0.5 - experimental
<ide> * @return true if the blockingX operators fail on a non-blocking scheduler
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> public static boolean isFailOnNonBlockingScheduler() {
<ide> return failNonBlockingScheduler;
<ide> }
<ide> public static Completable onAssembly(@NonNull Completable source) {
<ide>
<ide> /**
<ide> * Sets the specific hook function.
<add> * <p>History: 2.0.6 - experimental
<ide> * @param handler the hook function to set, null allowed
<del> * @since 2.0.6 - experimental
<add> * @since 2.1 - beta
<ide> */
<del> @Experimental
<add> @Beta
<ide> @SuppressWarnings("rawtypes")
<ide> public static void setOnParallelAssembly(@Nullable Function<? super ParallelFlowable, ? extends ParallelFlowable> handler) {
<ide> if (lockdown) {
<ide> public static void setOnParallelAssembly(@Nullable Function<? super ParallelFlow
<ide>
<ide> /**
<ide> * Returns the current hook function.
<add> * <p>History: 2.0.6 - experimental
<ide> * @return the hook function, may be null
<del> * @since 2.0.6 - experimental
<add> * @since 2.1 - beta
<ide> */
<del> @Experimental
<add> @Beta
<ide> @SuppressWarnings("rawtypes")
<ide> @Nullable
<ide> public static Function<? super ParallelFlowable, ? extends ParallelFlowable> getOnParallelAssembly() {
<ide> public static void setOnParallelAssembly(@Nullable Function<? super ParallelFlow
<ide>
<ide> /**
<ide> * Calls the associated hook function.
<add> * <p>History: 2.0.6 - experimental
<ide> * @param <T> the value type of the source
<ide> * @param source the hook's input value
<ide> * @return the value returned by the hook
<del> * @since 2.0.6 - experimental
<add> * @since 2.1 - beta
<ide> */
<del> @Experimental
<add> @Beta
<ide> @SuppressWarnings({ "rawtypes", "unchecked" })
<ide> @NonNull
<ide> public static <T> ParallelFlowable<T> onAssembly(@NonNull ParallelFlowable<T> source) {
<ide> public static <T> ParallelFlowable<T> onAssembly(@NonNull ParallelFlowable<T> so
<ide> * such as awaiting a condition or signal
<ide> * and should return true to indicate the operator
<ide> * should not block but throw an IllegalArgumentException.
<add> * <p>History: 2.0.5 - experimental
<ide> * @return true if the blocking should be prevented
<ide> * @see #setFailOnNonBlockingScheduler(boolean)
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> public static boolean onBeforeBlocking() {
<ide> BooleanSupplier f = onBeforeBlocking;
<ide> if (f != null) {
<ide> public static boolean onBeforeBlocking() {
<ide> * Set the handler that is called when an operator attempts a blocking
<ide> * await; the handler should return true to prevent the blocking
<ide> * and to signal an IllegalStateException instead.
<add> * <p>History: 2.0.5 - experimental
<ide> * @param handler the handler to set, null resets to the default handler
<ide> * that always returns false
<ide> * @see #onBeforeBlocking()
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> public static void setOnBeforeBlocking(@Nullable BooleanSupplier handler) {
<ide> if (lockdown) {
<ide> throw new IllegalStateException("Plugins can't be changed anymore");
<ide> public static void setOnBeforeBlocking(@Nullable BooleanSupplier handler) {
<ide> /**
<ide> * Returns the current blocking handler or null if no custom handler
<ide> * is set.
<add> * <p>History: 2.0.5 - experimental
<ide> * @return the current blocking handler or null if not specified
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> @Nullable
<ide> public static BooleanSupplier getOnBeforeBlocking() {
<ide> return onBeforeBlocking;
<ide> public static BooleanSupplier getOnBeforeBlocking() {
<ide> /**
<ide> * Create an instance of the default {@link Scheduler} used for {@link Schedulers#computation()}
<ide> * except using {@code threadFactory} for thread creation.
<add> * <p>History: 2.0.5 - experimental
<ide> * @param threadFactory thread factory to use for creating worker threads. Note that this takes precedence over any
<ide> * system properties for configuring new thread creation. Cannot be null.
<ide> * @return the created Scheduler instance
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> @NonNull
<ide> public static Scheduler createComputationScheduler(@NonNull ThreadFactory threadFactory) {
<ide> return new ComputationScheduler(ObjectHelper.requireNonNull(threadFactory, "threadFactory is null"));
<ide> public static Scheduler createComputationScheduler(@NonNull ThreadFactory thread
<ide> /**
<ide> * Create an instance of the default {@link Scheduler} used for {@link Schedulers#io()}
<ide> * except using {@code threadFactory} for thread creation.
<add> * <p>History: 2.0.5 - experimental
<ide> * @param threadFactory thread factory to use for creating worker threads. Note that this takes precedence over any
<ide> * system properties for configuring new thread creation. Cannot be null.
<ide> * @return the created Scheduler instance
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> @NonNull
<ide> public static Scheduler createIoScheduler(@NonNull ThreadFactory threadFactory) {
<ide> return new IoScheduler(ObjectHelper.requireNonNull(threadFactory, "threadFactory is null"));
<ide> public static Scheduler createIoScheduler(@NonNull ThreadFactory threadFactory)
<ide> /**
<ide> * Create an instance of the default {@link Scheduler} used for {@link Schedulers#newThread()}
<ide> * except using {@code threadFactory} for thread creation.
<add> * <p>History: 2.0.5 - experimental
<ide> * @param threadFactory thread factory to use for creating worker threads. Note that this takes precedence over any
<ide> * system properties for configuring new thread creation. Cannot be null.
<ide> * @return the created Scheduler instance
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> @NonNull
<ide> public static Scheduler createNewThreadScheduler(@NonNull ThreadFactory threadFactory) {
<ide> return new NewThreadScheduler(ObjectHelper.requireNonNull(threadFactory, "threadFactory is null"));
<ide> public static Scheduler createNewThreadScheduler(@NonNull ThreadFactory threadFa
<ide> /**
<ide> * Create an instance of the default {@link Scheduler} used for {@link Schedulers#single()}
<ide> * except using {@code threadFactory} for thread creation.
<add> * <p>History: 2.0.5 - experimental
<ide> * @param threadFactory thread factory to use for creating worker threads. Note that this takes precedence over any
<ide> * system properties for configuring new thread creation. Cannot be null.
<ide> * @return the created Scheduler instance
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> @NonNull
<ide> public static Scheduler createSingleScheduler(@NonNull ThreadFactory threadFactory) {
<ide> return new SingleScheduler(ObjectHelper.requireNonNull(threadFactory, "threadFactory is null"));
<ide><path>src/main/java/io/reactivex/subjects/CompletableSubject.java
<ide> * <p>
<ide> * The CompletableSubject doesn't store the Disposables coming through onSubscribe but
<ide> * disposes them once the other onXXX methods were called (terminal state reached).
<del> * @since 2.0.5 - experimental
<add> * <p>History: 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<del>@Experimental
<ide> public final class CompletableSubject extends Completable implements CompletableObserver {
<ide>
<ide> final AtomicReference<CompletableDisposable[]> observers;
<ide><path>src/main/java/io/reactivex/subjects/MaybeSubject.java
<ide> * <p>
<ide> * The MaybeSubject doesn't store the Disposables coming through onSubscribe but
<ide> * disposes them once the other onXXX methods were called (terminal state reached).
<add> * <p>History: 2.0.5 - experimental
<ide> * @param <T> the value type received and emitted
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<del>@Experimental
<ide> public final class MaybeSubject<T> extends Maybe<T> implements MaybeObserver<T> {
<ide>
<ide> final AtomicReference<MaybeDisposable<T>[]> observers;
<ide><path>src/main/java/io/reactivex/subjects/SingleSubject.java
<ide> * <p>
<ide> * The SingleSubject doesn't store the Disposables coming through onSubscribe but
<ide> * disposes them once the other onXXX methods were called (terminal state reached).
<add> * <p>History: 2.0.5 - experimental
<ide> * @param <T> the value type received and emitted
<del> * @since 2.0.5 - experimental
<add> * @since 2.1
<ide> */
<del>@Experimental
<ide> public final class SingleSubject<T> extends Single<T> implements SingleObserver<T> {
<ide>
<ide> final AtomicReference<SingleDisposable<T>[]> observers;
<ide><path>src/main/java/io/reactivex/subscribers/TestSubscriber.java
<ide> import org.reactivestreams.*;
<ide>
<ide> import io.reactivex.FlowableSubscriber;
<del>import io.reactivex.annotations.Experimental;
<ide> import io.reactivex.disposables.Disposable;
<ide> import io.reactivex.functions.Consumer;
<ide> import io.reactivex.internal.fuseable.QueueSubscription;
<ide> public final TestSubscriber<T> assertOf(Consumer<? super TestSubscriber<T>> chec
<ide>
<ide> /**
<ide> * Calls {@link #request(long)} and returns this.
<add> * <p>History: 2.0.1 - experimental
<ide> * @param n the request amount
<ide> * @return this
<del> * @since 2.0.1 - experimental
<add> * @since 2.1
<ide> */
<del> @Experimental
<ide> public final TestSubscriber<T> requestMore(long n) {
<ide> request(n);
<ide> return this;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableStrictTest.java
<del>/**
<del> * Copyright (c) 2016-present, RxJava Contributors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<del> * compliance with the License. You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<del> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<del> * the License for the specific language governing permissions and limitations under the License.
<del> */
<del>
<del>package io.reactivex.internal.operators.flowable;
<del>
<del>import static org.junit.Assert.*;
<del>
<del>import java.util.*;
<del>import java.util.concurrent.TimeUnit;
<del>
<del>import org.junit.Test;
<del>import org.reactivestreams.*;
<del>
<del>import io.reactivex.*;
<del>import io.reactivex.exceptions.TestException;
<del>import io.reactivex.internal.subscribers.StrictSubscriber;
<del>import io.reactivex.internal.subscriptions.BooleanSubscription;
<del>import io.reactivex.processors.PublishProcessor;
<del>import io.reactivex.schedulers.Schedulers;
<del>import io.reactivex.subscribers.TestSubscriber;
<del>
<del>@Deprecated
<del>public class FlowableStrictTest {
<del>
<del> @Test
<del> public void empty() {
<del> Flowable.empty()
<del> .strict()
<del> .test()
<del> .assertResult();
<del> }
<del>
<del> @Test
<del> public void just() {
<del> Flowable.just(1)
<del> .strict()
<del> .test()
<del> .assertResult(1);
<del> }
<del>
<del> @Test
<del> public void range() {
<del> Flowable.range(1, 5)
<del> .strict()
<del> .test()
<del> .assertResult(1, 2, 3, 4, 5);
<del> }
<del>
<del> @Test
<del> public void take() {
<del> Flowable.range(1, 5)
<del> .take(2)
<del> .strict()
<del> .test()
<del> .assertResult(1, 2);
<del> }
<del>
<del> @Test
<del> public void backpressure() {
<del> Flowable.range(1, 5)
<del> .strict()
<del> .test(0)
<del> .assertEmpty()
<del> .requestMore(1)
<del> .assertValue(1)
<del> .requestMore(2)
<del> .assertValues(1, 2, 3)
<del> .requestMore(2)
<del> .assertResult(1, 2, 3, 4, 5);
<del> }
<del>
<del> @Test
<del> public void error() {
<del> Flowable.error(new TestException())
<del> .strict()
<del> .test()
<del> .assertFailure(TestException.class);
<del> }
<del>
<del> @Test
<del> public void observeOn() {
<del> Flowable.range(1, 5)
<del> .hide()
<del> .observeOn(Schedulers.single())
<del> .strict()
<del> .test()
<del> .awaitDone(5, TimeUnit.SECONDS)
<del> .assertResult(1, 2, 3, 4, 5);
<del> }
<del>
<del> @Test
<del> public void invalidRequest() {
<del> for (int i = 0; i > -100; i--) {
<del> final int j = i;
<del> final List<Object> items = new ArrayList<Object>();
<del>
<del> Flowable.range(1, 2)
<del> .strict()
<del> .subscribe(new Subscriber<Integer>() {
<del> @Override
<del> public void onSubscribe(Subscription s) {
<del> s.request(j);
<del> }
<del>
<del> @Override
<del> public void onNext(Integer t) {
<del> items.add(t);
<del> }
<del>
<del> @Override
<del> public void onError(Throwable t) {
<del> items.add(t);
<del> }
<del>
<del> @Override
<del> public void onComplete() {
<del> items.add("Done");
<del> }
<del> });
<del>
<del> assertTrue(items.toString(), items.size() == 1);
<del> assertTrue(items.toString(), items.get(0) instanceof IllegalArgumentException);
<del> assertTrue(items.toString(), items.get(0).toString().contains("§3.9"));
<del> }
<del> }
<del>
<del> @Test
<del> public void doubleOnSubscribe() {
<del> final BooleanSubscription bs1 = new BooleanSubscription();
<del> final BooleanSubscription bs2 = new BooleanSubscription();
<del>
<del> final TestSubscriber<Object> ts = TestSubscriber.create();
<del>
<del> Flowable.fromPublisher(new Publisher<Object>() {
<del> @Override
<del> public void subscribe(Subscriber<? super Object> p) {
<del> p.onSubscribe(bs1);
<del> p.onSubscribe(bs2);
<del> }
<del> })
<del> .strict()
<del> .subscribe(new Subscriber<Object>() {
<del>
<del> @Override
<del> public void onSubscribe(Subscription s) {
<del> ts.onSubscribe(s);
<del> }
<del>
<del> @Override
<del> public void onNext(Object t) {
<del> ts.onNext(t);
<del> }
<del>
<del> @Override
<del> public void onError(Throwable t) {
<del> ts.onError(t);
<del> }
<del>
<del> @Override
<del> public void onComplete() {
<del> ts.onComplete();
<del> }
<del> });
<del>
<del> ts.assertFailure(IllegalStateException.class);
<del>
<del> assertTrue(bs1.isCancelled());
<del> assertTrue(bs2.isCancelled());
<del>
<del> String es = ts.errors().get(0).toString();
<del> assertTrue(es, es.contains("§2.12"));
<del> }
<del>
<del> @Test
<del> public void noCancelOnComplete() {
<del> final BooleanSubscription bs = new BooleanSubscription();
<del>
<del> Flowable.fromPublisher(new Publisher<Object>() {
<del> @Override
<del> public void subscribe(Subscriber<? super Object> p) {
<del> p.onSubscribe(bs);
<del> p.onComplete();
<del> }
<del> })
<del> .strict()
<del> .subscribe(new Subscriber<Object>() {
<del>
<del> Subscription s;
<del>
<del> @Override
<del> public void onSubscribe(Subscription s) {
<del> this.s = s;
<del> }
<del>
<del> @Override
<del> public void onNext(Object t) {
<del> // not called
<del> }
<del>
<del> @Override
<del> public void onError(Throwable t) {
<del> // not called
<del> }
<del>
<del> @Override
<del> public void onComplete() {
<del> s.cancel();
<del> }
<del> });
<del>
<del> assertFalse(bs.isCancelled());
<del> }
<del>
<del> @Test
<del> public void noCancelOnError() {
<del> final BooleanSubscription bs = new BooleanSubscription();
<del>
<del> Flowable.fromPublisher(new Publisher<Object>() {
<del> @Override
<del> public void subscribe(Subscriber<? super Object> p) {
<del> p.onSubscribe(bs);
<del> p.onError(new TestException());
<del> }
<del> })
<del> .strict()
<del> .subscribe(new Subscriber<Object>() {
<del>
<del> Subscription s;
<del>
<del> @Override
<del> public void onSubscribe(Subscription s) {
<del> this.s = s;
<del> }
<del>
<del> @Override
<del> public void onNext(Object t) {
<del> // not called
<del> }
<del>
<del> @Override
<del> public void onError(Throwable t) {
<del> s.cancel();
<del> }
<del>
<del> @Override
<del> public void onComplete() {
<del> // not called
<del> }
<del> });
<del>
<del> assertFalse(bs.isCancelled());
<del> }
<del>
<del> @Test
<del> public void normal() {
<del> TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
<del>
<del> Flowable.range(1, 5)
<del> .subscribe(new StrictSubscriber<Integer>(ts));
<del>
<del> ts.assertResult(1, 2, 3, 4, 5);
<del> }
<del>
<del> @Test
<del> public void badRequestOnNextRace() {
<del> for (int i = 0; i < 500; i++) {
<del> TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
<del>
<del> final PublishProcessor<Integer> pp = PublishProcessor.create();
<del>
<del> final StrictSubscriber<Integer> s = new StrictSubscriber<Integer>(ts);
<del>
<del> s.onSubscribe(new BooleanSubscription());
<del>
<del> Runnable r1 = new Runnable() {
<del> @Override
<del> public void run() {
<del> pp.onNext(1);
<del> }
<del> };
<del>
<del> Runnable r2 = new Runnable() {
<del> @Override
<del> public void run() {
<del> s.request(0);
<del> }
<del> };
<del>
<del> TestHelper.race(r1, r2);
<del>
<del> if (ts.valueCount() == 0) {
<del> ts.assertFailure(IllegalArgumentException.class);
<del> } else {
<del> ts.assertValue(1).assertNoErrors().assertNotComplete();
<del> }
<del> }
<del> }
<del>}
| 22
|
Ruby
|
Ruby
|
fix rubocop warnings
|
2c5beb0effd113bd0342f052d735d697e3e5af95
|
<ide><path>Library/Homebrew/cmd/upgrade.rb
<ide> def upgrade
<ide> end
<ide>
<ide> (ARGV.resolved_formulae - outdated).each do |f|
<del> versions = f.installed_kegs.map { |keg| keg.version }
<add> versions = f.installed_kegs.map(&:version)
<ide> if versions.empty?
<ide> onoe "#{f.full_name} not installed"
<ide> else
<ide> def upgrade
<ide> outdated -= pinned
<ide> end
<ide>
<del> unless outdated.empty?
<add> if outdated.empty?
<add> oh1 "No packages to upgrade"
<add> else
<ide> oh1 "Upgrading #{outdated.length} outdated package#{plural(outdated.length)}, with result:"
<ide> puts outdated.map { |f| "#{f.full_name} #{f.pkg_version}" } * ", "
<del> else
<del> oh1 "No packages to upgrade"
<ide> end
<ide>
<ide> unless upgrade_pinned? || pinned.empty?
<ide> def upgrade_formula(f)
<ide> ofail e
<ide> ensure
<ide> # restore previous installation state if build failed
<del> outdated_keg.link if outdated_keg && !f.installed? rescue nil
<add> begin
<add> outdated_keg.link if outdated_keg && !f.installed?
<add> rescue
<add> nil
<add> end
<ide> end
<ide> end
| 1
|
Python
|
Python
|
remove shebang from test modules
|
666553e6b27683d7336dafb93100041c6079a97a
|
<ide><path>numpy/core/tests/test_arrayprint.py
<del>#!/usr/bin/env python
<ide> # -*- coding: utf-8 -*-
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide><path>numpy/distutils/tests/test_misc_util.py
<del>#!/usr/bin/env python
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> from os.path import join, sep, dirname
<ide><path>numpy/fft/tests/test_helper.py
<del>#!/usr/bin/env python
<ide> """Test functions for fftpack.helper module
<ide>
<ide> Copied from fftpack.helper by Pearu Peterson, October 2005
| 3
|
Text
|
Text
|
add more details on legend sort function
|
148114b03ba8eef45c07e8c987992aa2abeef1cb
|
<ide><path>docs/configuration/legend.md
<ide> Namespace: `options.plugins.legend.labels`
<ide> | `padding` | `number` | `10` | Padding between rows of colored boxes.
<ide> | `generateLabels` | `function` | | Generates legend items for each thing in the legend. Default implementation returns the text + styling for the color box. See [Legend Item](#legend-item-interface) for details.
<ide> | `filter` | `function` | `null` | Filters legend items out of the legend. Receives 2 parameters, a [Legend Item](#legend-item-interface) and the chart data.
<del>| `sort` | `function` | `null` | Sorts legend items. Receives 3 parameters, two [Legend Items](#legend-item-interface) and the chart data.
<add>| `sort` | `function` | `null` | Sorts legend items. Type is : `sort(a: LegendItem, b: LegendItem, data: ChartData): number;`. Receives 3 parameters, two [Legend Items](#legend-item-interface) and the chart data. The return value of the function is a number that indicates the order of the two legend item parameters. The ordering matches the [return value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#description) of `Array.prototype.sort()`
<ide> | [`pointStyle`](elements.md#point-styles) | [`pointStyle`](elements.md#types) | `'circle'` | If specified, this style of point is used for the legend. Only used if `usePointStyle` is true.
<ide> | `textAlign` | `string` | `'center'` | Horizontal alignment of the label text. Options are: `'left'`, `'right'` or `'center'`.
<ide> | `usePointStyle` | `boolean` | `false` | Label style will match corresponding point style (size is based on the minimum value between boxWidth and font.size).
| 1
|
Javascript
|
Javascript
|
change var to const
|
65ea3fd3432506e4a795fc53bb7f29437102a540
|
<ide><path>examples/testAll.js
<ide> * Runs an ordered set of commands within each of the build directories.
<ide> */
<ide>
<del>var fs = require('fs')
<del>var path = require('path')
<del>var { spawnSync } = require('child_process')
<add>const fs = require('fs')
<add>const path = require('path')
<add>const { spawnSync } = require('child_process')
<ide>
<del>var exampleDirs = fs.readdirSync(__dirname).filter((file) => {
<add>const exampleDirs = fs.readdirSync(__dirname).filter((file) => {
<ide> return fs.statSync(path.join(__dirname, file)).isDirectory()
<ide> })
<ide>
<ide> // Ordering is important here. `yarn install` must come first.
<del>var cmdArgs = [
<add>const cmdArgs = [
<ide> { cmd: 'yarn', args: [ 'install', '--no-progress' ] },
<ide> { cmd: 'yarn', args: [ 'test' ] }
<ide> ]
| 1
|
Javascript
|
Javascript
|
simplify foreach() usage
|
0132cddb6f4cc7797c127438378a39cce7aa930f
|
<ide><path>test/sequential/test-http-max-http-headers.js
<ide> function once(cb) {
<ide> }
<ide>
<ide> function finished(client, callback) {
<del> 'abort error end'.split(' ').forEach((e) => {
<add> ['abort', 'error', 'end'].forEach((e) => {
<ide> client.on(e, once(() => setImmediate(callback)));
<ide> });
<ide> }
| 1
|
Javascript
|
Javascript
|
fix regression introduced in fe804d9b
|
48334dc0b1b8211f07b2fac5a00a41be58c0c3ee
|
<ide><path>src/node.js
<ide>
<ide> var cwd = process.cwd();
<ide> var path = requireNative('path');
<del>
<del> // Make process.argv[0] and process.argv[1] into full paths.
<del> if ('/\\'.indexOf(process.argv[0].charAt(0)) < 0
<del> && process.argv[0].charAt(1) != ':') {
<add> var isWindows = process.platform === 'win32';
<add>
<add> // Make process.argv[0] and process.argv[1] into full paths, but only
<add> // touch argv[0] if it's not a system $PATH lookup.
<add> // TODO: Make this work on Windows as well. Note that "node" might
<add> // execute cwd\node.exe, or some %PATH%\node.exe on Windows,
<add> // and that every directory has its own cwd, so d:node.exe is valid.
<add> var argv0 = process.argv[0];
<add> if (!isWindows && argv0.indexOf('/') !== -1 && argv0.charAt(0) !== '/') {
<ide> process.argv[0] = path.join(cwd, process.argv[0]);
<ide> }
<ide>
| 1
|
Javascript
|
Javascript
|
improve heading type detection in json.js
|
7fcb52c7b2236cbd7db1dc63274a2670fcd2fb9d
|
<ide><path>tools/doc/json.js
<ide> function cloneValue(src) {
<ide> }
<ide>
<ide>
<del>// These parse out the contents of an H# tag.
<add>// This section parse out the contents of an H# tag.
<add>
<add>// To reduse escape slashes in RegExp string components.
<add>const r = String.raw;
<add>
<add>const eventPrefix = '^Event: +';
<add>const classPrefix = '^[Cc]lass: +';
<add>const ctorPrefix = '^(?:[Cc]onstructor: +)?new +';
<add>const classMethodPrefix = '^Class Method: +';
<add>const maybeClassPropertyPrefix = '(?:Class Property: +)?';
<add>
<add>const maybeQuote = '[\'"]?';
<add>const notQuotes = '[^\'"]+';
<add>
<add>// To include constructs like `readable\[Symbol.asyncIterator\]()`
<add>// or `readable.\_read(size)` (with Markdown escapes).
<add>const simpleId = r`(?:(?:\\?_)+|\b)\w+\b`;
<add>const computedId = r`\\?\[[\w\.]+\\?\]`;
<add>const id = `(?:${simpleId}|${computedId})`;
<add>const classId = r`[A-Z]\w+`;
<add>
<add>const ancestors = r`(?:${id}\.?)+`;
<add>const maybeAncestors = r`(?:${id}\.?)*`;
<add>
<add>const callWithParams = r`\([^)]*\)`;
<add>
<add>const noCallOrProp = '(?![.[(])';
<add>
<add>const maybeExtends = `(?: +extends +${maybeAncestors}${classId})?`;
<add>
<ide> const headingExpressions = [
<del> { type: 'event', re: /^Event(?::|\s)+['"]?([^"']+).*$/i },
<del> { type: 'class', re: /^Class:\s*([^ ]+).*$/i },
<del> { type: 'property', re: /^[^.[]+(\[[^\]]+\])\s*$/ },
<del> { type: 'property', re: /^[^.]+\.([^ .()]+)\s*$/ },
<del> { type: 'classMethod', re: /^class\s*method\s*:?[^.]+\.([^ .()]+)\([^)]*\)\s*$/i },
<del> { type: 'method', re: /^(?:[^.]+\.)?([^ .()]+)\([^)]*\)\s*$/ },
<del> { type: 'ctor', re: /^new ([A-Z][a-zA-Z]+)\([^)]*\)\s*$/ },
<add> { type: 'event', re: RegExp(
<add> `${eventPrefix}${maybeQuote}(${notQuotes})${maybeQuote}$`, 'i') },
<add>
<add> { type: 'class', re: RegExp(
<add> `${classPrefix}(${maybeAncestors}${classId})${maybeExtends}$`, '') },
<add>
<add> { type: 'ctor', re: RegExp(
<add> `${ctorPrefix}(${maybeAncestors}${classId})${callWithParams}$`, '') },
<add>
<add> { type: 'classMethod', re: RegExp(
<add> `${classMethodPrefix}${maybeAncestors}(${id})${callWithParams}$`, 'i') },
<add>
<add> { type: 'method', re: RegExp(
<add> `^${maybeAncestors}(${id})${callWithParams}$`, 'i') },
<add>
<add> { type: 'property', re: RegExp(
<add> `^${maybeClassPropertyPrefix}${ancestors}(${id})${noCallOrProp}$`, 'i') },
<ide> ];
<ide>
<ide> function newSection({ text }) {
| 1
|
Java
|
Java
|
add support for flux<part> in bodyextractors
|
4525c6a5371dbae3a618b54d2b0393d97a1529b7
|
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyExtractors.java
<ide> */
<ide> public abstract class BodyExtractors {
<ide>
<del> private static final ResolvableType FORM_TYPE =
<add> private static final ResolvableType FORM_MAP_TYPE =
<ide> ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class);
<ide>
<del> private static final ResolvableType MULTIPART_TYPE = ResolvableType.forClassWithGenerics(
<add> private static final ResolvableType MULTIPART_MAP_TYPE = ResolvableType.forClassWithGenerics(
<ide> MultiValueMap.class, String.class, Part.class);
<ide>
<add> private static final ResolvableType PART_TYPE = ResolvableType.forClass(Part.class);
<add>
<ide>
<ide> /**
<ide> * Return a {@code BodyExtractor} that reads into a Reactor {@link Mono}.
<ide> public static <T> BodyExtractor<Flux<T>, ReactiveHttpInputMessage> toFlux(Resolv
<ide> public static BodyExtractor<Mono<MultiValueMap<String, String>>, ServerHttpRequest> toFormData() {
<ide> return (serverRequest, context) -> {
<ide> HttpMessageReader<MultiValueMap<String, String>> messageReader =
<del> formMessageReader(context);
<add> messageReader(FORM_MAP_TYPE, MediaType.APPLICATION_FORM_URLENCODED, context);
<ide> return context.serverResponse()
<del> .map(serverResponse -> messageReader.readMono(FORM_TYPE, FORM_TYPE, serverRequest, serverResponse, context.hints()))
<del> .orElseGet(() -> messageReader.readMono(FORM_TYPE, serverRequest, context.hints()));
<add> .map(serverResponse -> messageReader.readMono(FORM_MAP_TYPE, FORM_MAP_TYPE, serverRequest, serverResponse, context.hints()))
<add> .orElseGet(() -> messageReader.readMono(FORM_MAP_TYPE, serverRequest, context.hints()));
<ide> };
<ide> }
<ide>
<ide> /**
<del> * Return a {@code BodyExtractor} that reads form data into a {@link MultiValueMap}.
<add> * Return a {@code BodyExtractor} that reads multipart (i.e. file upload) form data into a
<add> * {@link MultiValueMap}.
<ide> * @return a {@code BodyExtractor} that reads multipart data
<ide> */
<ide> // Note that the returned BodyExtractor is parameterized to ServerHttpRequest, not
<ide> public static BodyExtractor<Mono<MultiValueMap<String, String>>, ServerHttpReque
<ide> public static BodyExtractor<Mono<MultiValueMap<String, Part>>, ServerHttpRequest> toMultipartData() {
<ide> return (serverRequest, context) -> {
<ide> HttpMessageReader<MultiValueMap<String, Part>> messageReader =
<del> multipartMessageReader(context);
<add> messageReader(MULTIPART_MAP_TYPE, MediaType.MULTIPART_FORM_DATA, context);
<ide> return context.serverResponse()
<del> .map(serverResponse -> messageReader.readMono(MULTIPART_TYPE, MULTIPART_TYPE, serverRequest, serverResponse, context.hints()))
<del> .orElseGet(() -> messageReader.readMono(MULTIPART_TYPE, serverRequest, context.hints()));
<add> .map(serverResponse -> messageReader.readMono(MULTIPART_MAP_TYPE,
<add> MULTIPART_MAP_TYPE, serverRequest, serverResponse, context.hints()))
<add> .orElseGet(() -> messageReader.readMono(MULTIPART_MAP_TYPE, serverRequest, context.hints()));
<add> };
<add> }
<add>
<add> /**
<add> * Return a {@code BodyExtractor} that reads multipart (i.e. file upload) form data into a
<add> * {@link MultiValueMap}.
<add> * @return a {@code BodyExtractor} that reads multipart data
<add> */
<add> // Note that the returned BodyExtractor is parameterized to ServerHttpRequest, not
<add> // ReactiveHttpInputMessage like other methods, since reading form data only typically happens on
<add> // the server-side
<add> public static BodyExtractor<Flux<Part>, ServerHttpRequest> toParts() {
<add> return (serverRequest, context) -> {
<add> HttpMessageReader<Part> messageReader =
<add> messageReader(PART_TYPE, MediaType.MULTIPART_FORM_DATA, context);
<add> return context.serverResponse()
<add> .map(serverResponse -> messageReader.read(PART_TYPE, PART_TYPE, serverRequest, serverResponse, context.hints()))
<add> .orElseGet(() -> messageReader.read(PART_TYPE, serverRequest, context.hints()));
<ide> };
<ide> }
<ide>
<ide> private static <T, S extends Publisher<T>> S readWithMessageReaders(
<ide> });
<ide> }
<ide>
<del> private static HttpMessageReader<MultiValueMap<String, String>> formMessageReader(BodyExtractor.Context context) {
<add> private static <T> HttpMessageReader<T> messageReader(ResolvableType elementType,
<add> MediaType mediaType, BodyExtractor.Context context) {
<ide> return context.messageReaders().get()
<del> .filter(messageReader -> messageReader
<del> .canRead(FORM_TYPE, MediaType.APPLICATION_FORM_URLENCODED))
<add> .filter(messageReader -> messageReader.canRead(elementType, mediaType))
<ide> .findFirst()
<del> .map(BodyExtractors::<MultiValueMap<String, String>>cast)
<del> .orElseThrow(() -> new IllegalStateException(
<del> "Could not find HttpMessageReader that supports " +
<del> MediaType.APPLICATION_FORM_URLENCODED_VALUE));
<del> }
<del>
<del> private static HttpMessageReader<MultiValueMap<String, Part>> multipartMessageReader(BodyExtractor.Context context) {
<del> return context.messageReaders().get()
<del> .filter(messageReader -> messageReader
<del> .canRead(MULTIPART_TYPE, MediaType.MULTIPART_FORM_DATA))
<del> .findFirst()
<del> .map(BodyExtractors::<MultiValueMap<String, Part>>cast)
<add> .map(BodyExtractors::<T>cast)
<ide> .orElseThrow(() -> new IllegalStateException(
<del> "Could not find HttpMessageReader that supports " +
<del> MediaType.MULTIPART_FORM_DATA));
<add> "Could not find HttpMessageReader that supports \"" + mediaType +
<add> "\" and \"" + elementType + "\""));
<ide> }
<ide>
<ide> private static MediaType contentType(HttpMessage message) {
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyExtractorsTests.java
<ide>
<ide> import org.springframework.core.codec.ByteBufferDecoder;
<ide> import org.springframework.core.codec.StringDecoder;
<add>import org.springframework.core.io.ClassPathResource;
<add>import org.springframework.core.io.Resource;
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DefaultDataBuffer;
<ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory;
<ide> import org.springframework.http.codec.FormHttpMessageReader;
<ide> import org.springframework.http.codec.HttpMessageReader;
<ide> import org.springframework.http.codec.json.Jackson2JsonDecoder;
<add>import org.springframework.http.codec.multipart.FilePart;
<add>import org.springframework.http.codec.multipart.FormFieldPart;
<add>import org.springframework.http.codec.multipart.MultipartHttpMessageReader;
<add>import org.springframework.http.codec.multipart.Part;
<add>import org.springframework.http.codec.multipart.SynchronossPartHttpMessageReader;
<ide> import org.springframework.http.codec.xml.Jaxb2XmlDecoder;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.http.server.reactive.ServerHttpResponse;
<ide> import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
<add>import org.springframework.util.FileCopyUtils;
<ide> import org.springframework.util.MultiValueMap;
<ide>
<ide> import static org.junit.Assert.*;
<ide> public void createContext() {
<ide> messageReaders.add(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes(true)));
<ide> messageReaders.add(new DecoderHttpMessageReader<>(new Jaxb2XmlDecoder()));
<ide> messageReaders.add(new DecoderHttpMessageReader<>(new Jackson2JsonDecoder()));
<add> messageReaders.add(new FormHttpMessageReader());
<add> SynchronossPartHttpMessageReader partReader = new SynchronossPartHttpMessageReader();
<add> messageReaders.add(partReader);
<add> messageReaders.add(new MultipartHttpMessageReader(partReader));
<add>
<ide> messageReaders.add(new FormHttpMessageReader());
<ide>
<ide> this.context = new BodyExtractor.Context() {
<ide> public void toFormData() throws Exception {
<ide> .verify();
<ide> }
<ide>
<add> @Test
<add> public void toParts() throws Exception {
<add> BodyExtractor<Flux<Part>, ServerHttpRequest> extractor = BodyExtractors.toParts();
<add>
<add> String bodyContents = "-----------------------------9051914041544843365972754266\r\n" +
<add> "Content-Disposition: form-data; name=\"text\"\r\n" +
<add> "\r\n" +
<add> "text default\r\n" +
<add> "-----------------------------9051914041544843365972754266\r\n" +
<add> "Content-Disposition: form-data; name=\"file1\"; filename=\"a.txt\"\r\n" +
<add> "Content-Type: text/plain\r\n" +
<add> "\r\n" +
<add> "Content of a.txt.\r\n" +
<add> "\r\n" +
<add> "-----------------------------9051914041544843365972754266\r\n" +
<add> "Content-Disposition: form-data; name=\"file2\"; filename=\"a.html\"\r\n" +
<add> "Content-Type: text/html\r\n" +
<add> "\r\n" +
<add> "<!DOCTYPE html><title>Content of a.html.</title>\r\n" +
<add> "\r\n" +
<add> "-----------------------------9051914041544843365972754266--\r\n";
<add>
<add> DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
<add> DefaultDataBuffer dataBuffer =
<add> factory.wrap(ByteBuffer.wrap(bodyContents.getBytes(StandardCharsets.UTF_8)));
<add> Flux<DataBuffer> body = Flux.just(dataBuffer);
<add>
<add> MockServerHttpRequest request = MockServerHttpRequest.post("/")
<add> .header("Content-Type", "multipart/form-data; boundary=---------------------------9051914041544843365972754266")
<add> .body(body);
<add>
<add> Flux<Part> result = extractor.extract(request, this.context);
<add>
<add> StepVerifier.create(result)
<add> .consumeNextWith(part -> {
<add> assertEquals("text", part.getName());
<add> assertTrue(part instanceof FormFieldPart);
<add> FormFieldPart formFieldPart = (FormFieldPart) part;
<add> assertEquals("text default", formFieldPart.getValue());
<add> })
<add> .consumeNextWith(part -> {
<add> assertEquals("file1", part.getName());
<add> assertTrue(part instanceof FilePart);
<add> FilePart filePart = (FilePart) part;
<add> assertEquals("a.txt", filePart.getFilename());
<add> assertEquals(MediaType.TEXT_PLAIN, filePart.getHeaders().getContentType());
<add> })
<add> .consumeNextWith(part -> {
<add> assertEquals("file2", part.getName());
<add> assertTrue(part instanceof FilePart);
<add> FilePart filePart = (FilePart) part;
<add> assertEquals("a.html", filePart.getFilename());
<add> assertEquals(MediaType.TEXT_HTML, filePart.getHeaders().getContentType());
<add> })
<add> .expectComplete()
<add> .verify();
<add> }
<add>
<ide> @Test
<ide> public void toDataBuffers() throws Exception {
<ide> BodyExtractor<Flux<DataBuffer>, ReactiveHttpInputMessage> extractor = BodyExtractors.toDataBuffers();
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/MultipartIntegrationTests.java
<ide>
<ide> package org.springframework.web.reactive.function;
<ide>
<add>import java.util.List;
<ide> import java.util.Map;
<ide>
<ide> import org.junit.Test;
<ide> public class MultipartIntegrationTests extends AbstractRouterFunctionIntegration
<ide> private final WebClient webClient = WebClient.create();
<ide>
<ide> @Test
<del> public void multipart() {
<add> public void multipartData() {
<ide> Mono<ClientResponse> result = webClient
<ide> .post()
<del> .uri("http://localhost:" + this.port + "/")
<add> .uri("http://localhost:" + this.port + "/multipartData")
<add> .contentType(MediaType.MULTIPART_FORM_DATA)
<add> .body(BodyInserters.fromMultipartData(generateBody()))
<add> .exchange();
<add>
<add> StepVerifier
<add> .create(result)
<add> .consumeNextWith(response -> assertEquals(HttpStatus.OK, response.statusCode()))
<add> .verifyComplete();
<add> }
<add>
<add> @Test
<add> public void parts() {
<add> Mono<ClientResponse> result = webClient
<add> .post()
<add> .uri("http://localhost:" + this.port + "/parts")
<ide> .contentType(MediaType.MULTIPART_FORM_DATA)
<ide> .body(BodyInserters.fromMultipartData(generateBody()))
<ide> .exchange();
<ide> private MultiValueMap<String, Object> generateBody() {
<ide> @Override
<ide> protected RouterFunction<ServerResponse> routerFunction() {
<ide> MultipartHandler multipartHandler = new MultipartHandler();
<del> return route(POST("/"), multipartHandler::handle);
<add> return route(POST("/multipartData"), multipartHandler::multipartData)
<add> .andRoute(POST("/parts"), multipartHandler::parts);
<ide> }
<ide>
<ide> private static class MultipartHandler {
<ide>
<del> public Mono<ServerResponse> handle(ServerRequest request) {
<add> public Mono<ServerResponse> multipartData(ServerRequest request) {
<ide> return request
<ide> .body(BodyExtractors.toMultipartData())
<ide> .flatMap(map -> {
<ide> public Mono<ServerResponse> handle(ServerRequest request) {
<ide> return ServerResponse.ok().build();
<ide> });
<ide> }
<add>
<add> public Mono<ServerResponse> parts(ServerRequest request) {
<add> return request.body(BodyExtractors.toParts()).collectList()
<add> .flatMap(parts -> {
<add> try {
<add> assertEquals(2, parts.size());
<add> assertEquals("foo.txt", ((FilePart) parts.get(0)).getFilename());
<add> assertEquals("bar", ((FormFieldPart) parts.get(1)).getValue());
<add> }
<add> catch(Exception e) {
<add> return Mono.error(e);
<add> }
<add> return ServerResponse.ok().build();
<add> });
<add> }
<ide> }
<ide>
<ide> }
| 3
|
Python
|
Python
|
set dropout rate to 0.2
|
cb16b78b0d3e7fc91eb0e7c8da725e4d5780aec5
|
<ide><path>spacy/cli/train.py
<ide> def train(
<ide> # Batch size starts at 1 and grows, so that we make updates quickly
<ide> # at the beginning of training.
<ide> dropout_rates = util.decaying(
<del> util.env_opt("dropout_from", 0.1),
<del> util.env_opt("dropout_to", 0.1),
<add> util.env_opt("dropout_from", 0.2),
<add> util.env_opt("dropout_to", 0.2),
<ide> util.env_opt("dropout_decay", 0.0),
<ide> )
<ide> batch_sizes = util.compounding(
| 1
|
Text
|
Text
|
fix typo s/postgressql/postgresql/ [ci skip]
|
2d040e756ed1d97c0f70e8542807ae13d5fc1b5b
|
<ide><path>activerecord/CHANGELOG.md
<ide>
<ide> * Add setting for enumerating column names in SELECT statements.
<ide>
<del> Adding a column to a PostgresSQL database, for example, while the application is running can
<add> Adding a column to a PostgreSQL database, for example, while the application is running can
<ide> change the result of wildcard `SELECT *` queries, which invalidates the result
<ide> of cached prepared statements and raises a `PreparedStatementCacheExpired` error.
<ide>
<ide><path>guides/source/configuring.md
<ide> in controllers and views. This defaults to `false`.
<ide>
<ide> * `config.active_record.queues.destroy` allows specifying the Active Job queue to use for destroy jobs. When this option is `nil`, purge jobs are sent to the default Active Job queue (see `config.active_job.default_queue_name`). It defaults to `nil`.
<ide>
<del>* `config.active_record.enumerate_columns_in_select_statements` when true, will always include column names in `SELECT` statements, and avoid wildcard `SELECT * FROM ...` queries. This avoids prepared statement cache errors when adding columns to a PostgresSQL database for example. Defaults to `false`.
<add>* `config.active_record.enumerate_columns_in_select_statements` when true, will always include column names in `SELECT` statements, and avoid wildcard `SELECT * FROM ...` queries. This avoids prepared statement cache errors when adding columns to a PostgreSQL database for example. Defaults to `false`.
<ide>
<ide> The MySQL adapter adds one additional configuration option:
<ide>
| 2
|
Javascript
|
Javascript
|
remove unauthenticated routes
|
ef0a801c908f8cc512a9babc57982b2fee95d306
|
<ide><path>api-server/server/boot/donate.js
<ide> const log = debug('fcc:boot:donate');
<ide>
<ide> export default function donateBoot(app, done) {
<ide> let stripe = false;
<del> const { User } = app.models;
<ide> const api = app.loopback.Router();
<ide> const donateRouter = app.loopback.Router();
<ide>
<ide> export default function donateBoot(app, done) {
<ide> function createStripeDonation(req, res) {
<ide> const { user, body } = req;
<ide>
<add> if (!user) {
<add> return res
<add> .status(500)
<add> .send({ error: 'User must be signed in for this request.' });
<add> }
<add>
<ide> if (!body || !body.amount || !body.duration) {
<del> return res.status(400).send({ error: 'Amount and duration Required.' });
<add> return res.status(500).send({
<add> error: 'The donation form had invalid values for this submission.'
<add> });
<ide> }
<ide>
<ide> const {
<ide> export default function donateBoot(app, done) {
<ide> } = body;
<ide>
<ide> if (!validStripeForm(amount, duration, email)) {
<del> return res
<del> .status(500)
<del> .send({ error: 'Invalid donation form values submitted' });
<add> return res.status(500).send({
<add> error: 'The donation form had invalid values for this submission.'
<add> });
<ide> }
<ide>
<del> const isOneTime = duration === 'onetime' ? true : false;
<del>
<del> const fccUser = user
<del> ? Promise.resolve(user)
<del> : new Promise((resolve, reject) =>
<del> User.findOrCreate(
<del> { where: { email } },
<del> { email },
<del> (err, instance, isNew) => {
<del> log('is new user instance: ', isNew);
<del> if (err) {
<del> return reject(err);
<del> }
<del> return resolve(instance);
<del> }
<del> )
<del> );
<del>
<ide> let donatingUser = {};
<ide> let donation = {
<ide> email,
<ide> export default function donateBoot(app, done) {
<ide> });
<ide> };
<ide>
<del> return fccUser
<del> .then(user => {
<del> const { isDonating } = user;
<add> return Promise.resolve(user)
<add> .then(nonDonatingUser => {
<add> const { isDonating } = nonDonatingUser;
<ide> if (isDonating) {
<ide> throw {
<ide> message: `User already has active donation(s).`,
<ide> type: 'AlreadyDonatingError'
<ide> };
<ide> }
<del> return user;
<add> return nonDonatingUser;
<ide> })
<ide> .then(createCustomer)
<ide> .then(customer => {
<del> return isOneTime
<add> return duration === 'onetime'
<ide> ? createOneTimeCharge(customer).then(charge => {
<ide> donation.subscriptionId = 'one-time-charge-prefix-' + charge.id;
<ide> return res.send(charge);
<ide> export default function donateBoot(app, done) {
<ide> donateRouter.use('/donate', api);
<ide> app.use(donateRouter);
<ide> app.use('/internal', donateRouter);
<del> app.use('/unauthenticated', donateRouter);
<ide> connectToStripe().then(done);
<ide> }
<ide> }
<ide><path>client/src/components/Donation/components/DonateFormChildViewForHOC.js
<ide> import { injectStripe } from 'react-stripe-elements';
<ide> import StripeCardForm from './StripeCardForm';
<ide> import DonateCompletion from './DonateCompletion';
<ide> import { postChargeStripe } from '../../../utils/ajax';
<del>import { userSelector, isSignedInSelector } from '../../../redux';
<add>import { userSelector } from '../../../redux';
<ide>
<ide> const propTypes = {
<ide> donationAmount: PropTypes.number.isRequired,
<ide> const initialState = {
<ide>
<ide> const mapStateToProps = createSelector(
<ide> userSelector,
<del> isSignedInSelector,
<del> ({ email, theme }, isSignedIn) => ({ email, theme, isSignedIn })
<add> ({ email, theme }) => ({ email, theme })
<ide> );
<ide>
<ide> class DonateFormChildViewForHOC extends Component {
<ide> class DonateFormChildViewForHOC extends Component {
<ide>
<ide> postDonation(token) {
<ide> const { donationAmount: amount, donationDuration: duration } = this.state;
<del> const { isSignedIn } = this.props;
<ide> this.setState(state => ({
<ide> ...state,
<ide> donationState: {
<ide> class DonateFormChildViewForHOC extends Component {
<ide> }
<ide> }));
<ide>
<del> return postChargeStripe(isSignedIn, {
<add> return postChargeStripe({
<ide> token,
<ide> amount,
<ide> duration
<ide><path>client/src/utils/ajax.js
<ide> export function getArticleById(shortId) {
<ide> }
<ide>
<ide> /** POST **/
<del>export function postChargeStripe(isSignedIn, body) {
<del> const donatePath = '/donate/charge-stripe';
<del> return isSignedIn
<del> ? post(donatePath, body)
<del> : postUnauthenticated(donatePath, body);
<add>export function postChargeStripe(body) {
<add> return post(`/donate/charge-stripe`, body);
<ide> }
<ide>
<ide> export function putUpdateLegacyCert(body) {
| 3
|
Python
|
Python
|
fix get_mathlib when path argument is none
|
a81039b7ec0834840468937a00317d85a3515eb8
|
<ide><path>numpy/distutils/misc_util.py
<ide> def get_mathlibs(path=None):
<ide> """Return the MATHLIB line from config.h
<ide> """
<ide> if path is None:
<del> path = get_numpy_include_dirs()[0]
<add> path = os.path.join(get_numpy_include_dirs()[0], 'numpy')
<ide> config_file = os.path.join(path,'config.h')
<ide> fid = open(config_file)
<ide> mathlibs = []
| 1
|
Python
|
Python
|
fix a typo in a comment
|
5246a5a44ebc52a2d2df88ca41d8a69b09c987c3
|
<ide><path>rest_framework/utils/field_mapping.py
<ide> def get_field_kwargs(field_name, model_field):
<ide> if not isinstance(validator, validators.MaxValueValidator)
<ide> ]
<ide>
<del> # Ensure that max_value is passed explicitly as a keyword arg,
<add> # Ensure that min_value is passed explicitly as a keyword arg,
<ide> # rather than as a validator.
<ide> min_value = next((
<ide> validator.limit_value for validator in validator_kwarg
| 1
|
Go
|
Go
|
extract daemon statscollector to its own package
|
835971c6fdaf6ea35a0e7e45f6d9a09fd5f03ce1
|
<ide><path>daemon/daemon.go
<ide> import (
<ide> "github.com/docker/docker/container"
<ide> "github.com/docker/docker/daemon/events"
<ide> "github.com/docker/docker/daemon/exec"
<del> "github.com/docker/docker/daemon/initlayer"
<del> "github.com/docker/docker/dockerversion"
<del> "github.com/docker/docker/plugin"
<del> "github.com/docker/libnetwork/cluster"
<ide> // register graph drivers
<ide> _ "github.com/docker/docker/daemon/graphdriver/register"
<add> "github.com/docker/docker/daemon/initlayer"
<add> "github.com/docker/docker/daemon/stats"
<ide> dmetadata "github.com/docker/docker/distribution/metadata"
<ide> "github.com/docker/docker/distribution/xfer"
<add> "github.com/docker/docker/dockerversion"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/layer"
<ide> "github.com/docker/docker/libcontainerd"
<ide> import (
<ide> "github.com/docker/docker/pkg/sysinfo"
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/docker/docker/pkg/truncindex"
<add> "github.com/docker/docker/plugin"
<ide> "github.com/docker/docker/reference"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/docker/docker/runconfig"
<ide> volumedrivers "github.com/docker/docker/volume/drivers"
<ide> "github.com/docker/docker/volume/local"
<ide> "github.com/docker/docker/volume/store"
<ide> "github.com/docker/libnetwork"
<add> "github.com/docker/libnetwork/cluster"
<ide> nwconfig "github.com/docker/libnetwork/config"
<ide> "github.com/docker/libtrust"
<ide> "github.com/pkg/errors"
<ide> type Daemon struct {
<ide> trustKey libtrust.PrivateKey
<ide> idIndex *truncindex.TruncIndex
<ide> configStore *Config
<del> statsCollector *statsCollector
<add> statsCollector *stats.Collector
<ide> defaultLogConfig containertypes.LogConfig
<ide> RegistryService registry.Service
<ide> EventsService *events.Events
<ide> type Daemon struct {
<ide> clusterProvider cluster.Provider
<ide> cluster Cluster
<ide>
<add> machineMemory uint64
<add>
<ide> seccompProfile []byte
<ide> seccompProfilePath string
<ide> }
<ide><path>daemon/daemon_unix.go
<ide> func (daemon *Daemon) stats(c *container.Container) (*types.StatsJSON, error) {
<ide> Limit: mem.Limit,
<ide> }
<ide> // if the container does not set memory limit, use the machineMemory
<del> if mem.Limit > daemon.statsCollector.machineMemory && daemon.statsCollector.machineMemory > 0 {
<del> s.MemoryStats.Limit = daemon.statsCollector.machineMemory
<add> if mem.Limit > daemon.machineMemory && daemon.machineMemory > 0 {
<add> s.MemoryStats.Limit = daemon.machineMemory
<ide> }
<ide> if cgs.PidsStats != nil {
<ide> s.PidsStats = types.PidsStats{
<ide><path>daemon/delete.go
<ide> func (daemon *Daemon) cleanupContainer(container *container.Container, forceRemo
<ide>
<ide> // stop collection of stats for the container regardless
<ide> // if stats are currently getting collected.
<del> daemon.statsCollector.stopCollection(container)
<add> daemon.statsCollector.StopCollection(container)
<ide>
<ide> if err = daemon.containerStop(container, 3); err != nil {
<ide> return err
<ide><path>daemon/stats.go
<ide> func (daemon *Daemon) ContainerStats(ctx context.Context, prefixOrName string, c
<ide> }
<ide>
<ide> func (daemon *Daemon) subscribeToContainerStats(c *container.Container) chan interface{} {
<del> return daemon.statsCollector.collect(c)
<add> return daemon.statsCollector.Collect(c)
<ide> }
<ide>
<ide> func (daemon *Daemon) unsubscribeToContainerStats(c *container.Container, ch chan interface{}) {
<del> daemon.statsCollector.unsubscribe(c, ch)
<add> daemon.statsCollector.Unsubscribe(c, ch)
<ide> }
<ide>
<ide> // GetContainerStats collects all the stats published by a container
<ide><path>daemon/stats/collector.go
<add>// +build !solaris
<add>
<add>package stats
<add>
<add>import (
<add> "time"
<add>
<add> "github.com/Sirupsen/logrus"
<add> "github.com/docker/docker/container"
<add> "github.com/docker/docker/pkg/pubsub"
<add>)
<add>
<add>// Collect registers the container with the collector and adds it to
<add>// the event loop for collection on the specified interval returning
<add>// a channel for the subscriber to receive on.
<add>func (s *Collector) Collect(c *container.Container) chan interface{} {
<add> s.m.Lock()
<add> defer s.m.Unlock()
<add> publisher, exists := s.publishers[c]
<add> if !exists {
<add> publisher = pubsub.NewPublisher(100*time.Millisecond, 1024)
<add> s.publishers[c] = publisher
<add> }
<add> return publisher.Subscribe()
<add>}
<add>
<add>// StopCollection closes the channels for all subscribers and removes
<add>// the container from metrics collection.
<add>func (s *Collector) StopCollection(c *container.Container) {
<add> s.m.Lock()
<add> if publisher, exists := s.publishers[c]; exists {
<add> publisher.Close()
<add> delete(s.publishers, c)
<add> }
<add> s.m.Unlock()
<add>}
<add>
<add>// Unsubscribe removes a specific subscriber from receiving updates for a container's stats.
<add>func (s *Collector) Unsubscribe(c *container.Container, ch chan interface{}) {
<add> s.m.Lock()
<add> publisher := s.publishers[c]
<add> if publisher != nil {
<add> publisher.Evict(ch)
<add> if publisher.Len() == 0 {
<add> delete(s.publishers, c)
<add> }
<add> }
<add> s.m.Unlock()
<add>}
<add>
<add>// Run starts the collectors and will indefinitely collect stats from the supervisor
<add>func (s *Collector) Run() {
<add> type publishersPair struct {
<add> container *container.Container
<add> publisher *pubsub.Publisher
<add> }
<add> // we cannot determine the capacity here.
<add> // it will grow enough in first iteration
<add> var pairs []publishersPair
<add>
<add> for range time.Tick(s.interval) {
<add> // it does not make sense in the first iteration,
<add> // but saves allocations in further iterations
<add> pairs = pairs[:0]
<add>
<add> s.m.Lock()
<add> for container, publisher := range s.publishers {
<add> // copy pointers here to release the lock ASAP
<add> pairs = append(pairs, publishersPair{container, publisher})
<add> }
<add> s.m.Unlock()
<add> if len(pairs) == 0 {
<add> continue
<add> }
<add>
<add> systemUsage, err := s.getSystemCPUUsage()
<add> if err != nil {
<add> logrus.Errorf("collecting system cpu usage: %v", err)
<add> continue
<add> }
<add>
<add> for _, pair := range pairs {
<add> stats, err := s.supervisor.GetContainerStats(pair.container)
<add> if err != nil {
<add> if _, ok := err.(notRunningErr); !ok {
<add> logrus.Errorf("collecting stats for %s: %v", pair.container.ID, err)
<add> }
<add> continue
<add> }
<add> // FIXME: move to containerd on Linux (not Windows)
<add> stats.CPUStats.SystemUsage = systemUsage
<add>
<add> pair.publisher.Publish(*stats)
<add> }
<add> }
<add>}
<add>
<add>type notRunningErr interface {
<add> error
<add> ContainerIsRunning() bool
<add>}
<ide><path>daemon/stats/collector_solaris.go
<add>package stats
<add>
<add>import (
<add> "github.com/docker/docker/container"
<add>)
<add>
<add>// platformNewStatsCollector performs platform specific initialisation of the
<add>// Collector structure. This is a no-op on Windows.
<add>func platformNewStatsCollector(s *Collector) {
<add>}
<add>
<add>// Collect registers the container with the collector and adds it to
<add>// the event loop for collection on the specified interval returning
<add>// a channel for the subscriber to receive on.
<add>// Currently not supported on Solaris
<add>func (s *Collector) Collect(c *container.Container) chan interface{} {
<add> return nil
<add>}
<add>
<add>// StopCollection closes the channels for all subscribers and removes
<add>// the container from metrics collection.
<add>// Currently not supported on Solaris
<add>func (s *Collector) StopCollection(c *container.Container) {
<add>}
<add>
<add>// Unsubscribe removes a specific subscriber from receiving updates for a container's stats.
<add>// Currently not supported on Solaris
<add>func (s *Collector) Unsubscribe(c *container.Container, ch chan interface{}) {
<add>}
<add><path>daemon/stats/collector_unix.go
<del><path>daemon/stats_collector_unix.go
<ide> // +build !windows,!solaris
<ide>
<del>package daemon
<add>package stats
<ide>
<ide> import (
<ide> "fmt"
<ide> "os"
<ide> "strconv"
<ide> "strings"
<ide>
<del> sysinfo "github.com/docker/docker/pkg/system"
<ide> "github.com/opencontainers/runc/libcontainer/system"
<ide> )
<ide>
<ide> // platformNewStatsCollector performs platform specific initialisation of the
<del>// statsCollector structure.
<del>func platformNewStatsCollector(s *statsCollector) {
<add>// Collector structure.
<add>func platformNewStatsCollector(s *Collector) {
<ide> s.clockTicksPerSecond = uint64(system.GetClockTicks())
<del> meminfo, err := sysinfo.ReadMemInfo()
<del> if err == nil && meminfo.MemTotal > 0 {
<del> s.machineMemory = uint64(meminfo.MemTotal)
<del> }
<ide> }
<ide>
<ide> const nanoSecondsPerSecond = 1e9
<ide> const nanoSecondsPerSecond = 1e9
<ide> // statistics line and then sums up the first seven fields
<ide> // provided. See `man 5 proc` for details on specific field
<ide> // information.
<del>func (s *statsCollector) getSystemCPUUsage() (uint64, error) {
<add>func (s *Collector) getSystemCPUUsage() (uint64, error) {
<ide> var line string
<ide> f, err := os.Open("/proc/stat")
<ide> if err != nil {
<add><path>daemon/stats/collector_windows.go
<del><path>daemon/stats_collector_windows.go
<ide> // +build windows
<ide>
<del>package daemon
<add>package stats
<ide>
<ide> // platformNewStatsCollector performs platform specific initialisation of the
<del>// statsCollector structure. This is a no-op on Windows.
<del>func platformNewStatsCollector(s *statsCollector) {
<add>// Collector structure. This is a no-op on Windows.
<add>func platformNewStatsCollector(s *Collector) {
<ide> }
<ide>
<ide> // getSystemCPUUsage returns the host system's cpu usage in
<ide> // nanoseconds. An error is returned if the format of the underlying
<ide> // file does not match. This is a no-op on Windows.
<del>func (s *statsCollector) getSystemCPUUsage() (uint64, error) {
<add>func (s *Collector) getSystemCPUUsage() (uint64, error) {
<ide> return 0, nil
<ide> }
<ide><path>daemon/stats/types.go
<add>package stats
<add>
<add>import (
<add> "bufio"
<add> "sync"
<add> "time"
<add>
<add> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/container"
<add> "github.com/docker/docker/pkg/pubsub"
<add>)
<add>
<add>type supervisor interface {
<add> // GetContainerStats collects all the stats related to a container
<add> GetContainerStats(container *container.Container) (*types.StatsJSON, error)
<add>}
<add>
<add>// NewCollector creates a stats collector that will poll the supervisor with the specified interval
<add>func NewCollector(supervisor supervisor, interval time.Duration) *Collector {
<add> s := &Collector{
<add> interval: interval,
<add> supervisor: supervisor,
<add> publishers: make(map[*container.Container]*pubsub.Publisher),
<add> bufReader: bufio.NewReaderSize(nil, 128),
<add> }
<add>
<add> platformNewStatsCollector(s)
<add>
<add> return s
<add>}
<add>
<add>// Collector manages and provides container resource stats
<add>type Collector struct {
<add> m sync.Mutex
<add> supervisor supervisor
<add> interval time.Duration
<add> publishers map[*container.Container]*pubsub.Publisher
<add> bufReader *bufio.Reader
<add>
<add> // The following fields are not set on Windows currently.
<add> clockTicksPerSecond uint64
<add>}
<ide><path>daemon/stats_collector.go
<del>// +build !solaris
<del>
<ide> package daemon
<ide>
<ide> import (
<del> "bufio"
<del> "sync"
<add> "runtime"
<ide> "time"
<ide>
<del> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/container"
<del> "github.com/docker/docker/pkg/pubsub"
<add> "github.com/docker/docker/daemon/stats"
<add> "github.com/docker/docker/pkg/system"
<ide> )
<ide>
<del>type statsSupervisor interface {
<del> // GetContainerStats collects all the stats related to a container
<del> GetContainerStats(container *container.Container) (*types.StatsJSON, error)
<del>}
<del>
<ide> // newStatsCollector returns a new statsCollector that collections
<ide> // stats for a registered container at the specified interval.
<ide> // The collector allows non-running containers to be added
<ide> // and will start processing stats when they are started.
<del>func (daemon *Daemon) newStatsCollector(interval time.Duration) *statsCollector {
<del> s := &statsCollector{
<del> interval: interval,
<del> supervisor: daemon,
<del> publishers: make(map[*container.Container]*pubsub.Publisher),
<del> bufReader: bufio.NewReaderSize(nil, 128),
<del> }
<del> platformNewStatsCollector(s)
<del> go s.run()
<del> return s
<del>}
<del>
<del>// statsCollector manages and provides container resource stats
<del>type statsCollector struct {
<del> m sync.Mutex
<del> supervisor statsSupervisor
<del> interval time.Duration
<del> publishers map[*container.Container]*pubsub.Publisher
<del> bufReader *bufio.Reader
<del>
<del> // The following fields are not set on Windows currently.
<del> clockTicksPerSecond uint64
<del> machineMemory uint64
<del>}
<del>
<del>// collect registers the container with the collector and adds it to
<del>// the event loop for collection on the specified interval returning
<del>// a channel for the subscriber to receive on.
<del>func (s *statsCollector) collect(c *container.Container) chan interface{} {
<del> s.m.Lock()
<del> defer s.m.Unlock()
<del> publisher, exists := s.publishers[c]
<del> if !exists {
<del> publisher = pubsub.NewPublisher(100*time.Millisecond, 1024)
<del> s.publishers[c] = publisher
<del> }
<del> return publisher.Subscribe()
<del>}
<del>
<del>// stopCollection closes the channels for all subscribers and removes
<del>// the container from metrics collection.
<del>func (s *statsCollector) stopCollection(c *container.Container) {
<del> s.m.Lock()
<del> if publisher, exists := s.publishers[c]; exists {
<del> publisher.Close()
<del> delete(s.publishers, c)
<del> }
<del> s.m.Unlock()
<del>}
<del>
<del>// unsubscribe removes a specific subscriber from receiving updates for a container's stats.
<del>func (s *statsCollector) unsubscribe(c *container.Container, ch chan interface{}) {
<del> s.m.Lock()
<del> publisher := s.publishers[c]
<del> if publisher != nil {
<del> publisher.Evict(ch)
<del> if publisher.Len() == 0 {
<del> delete(s.publishers, c)
<del> }
<del> }
<del> s.m.Unlock()
<del>}
<del>
<del>func (s *statsCollector) run() {
<del> type publishersPair struct {
<del> container *container.Container
<del> publisher *pubsub.Publisher
<del> }
<del> // we cannot determine the capacity here.
<del> // it will grow enough in first iteration
<del> var pairs []publishersPair
<del>
<del> for range time.Tick(s.interval) {
<del> // it does not make sense in the first iteration,
<del> // but saves allocations in further iterations
<del> pairs = pairs[:0]
<del>
<del> s.m.Lock()
<del> for container, publisher := range s.publishers {
<del> // copy pointers here to release the lock ASAP
<del> pairs = append(pairs, publishersPair{container, publisher})
<del> }
<del> s.m.Unlock()
<del> if len(pairs) == 0 {
<del> continue
<del> }
<del>
<del> systemUsage, err := s.getSystemCPUUsage()
<del> if err != nil {
<del> logrus.Errorf("collecting system cpu usage: %v", err)
<del> continue
<del> }
<del>
<del> for _, pair := range pairs {
<del> stats, err := s.supervisor.GetContainerStats(pair.container)
<del> if err != nil {
<del> if _, ok := err.(errNotRunning); !ok {
<del> logrus.Errorf("collecting stats for %s: %v", pair.container.ID, err)
<del> }
<del> continue
<del> }
<del> // FIXME: move to containerd on Linux (not Windows)
<del> stats.CPUStats.SystemUsage = systemUsage
<del>
<del> pair.publisher.Publish(*stats)
<add>func (daemon *Daemon) newStatsCollector(interval time.Duration) *stats.Collector {
<add> // FIXME(vdemeester) move this elsewhere
<add> if runtime.GOOS == "linux" {
<add> meminfo, err := system.ReadMemInfo()
<add> if err == nil && meminfo.MemTotal > 0 {
<add> daemon.machineMemory = uint64(meminfo.MemTotal)
<ide> }
<ide> }
<add> s := stats.NewCollector(daemon, interval)
<add> go s.Run()
<add> return s
<ide> }
<ide><path>daemon/stats_collector_solaris.go
<del>package daemon
<del>
<del>import (
<del> "github.com/docker/docker/container"
<del> "time"
<del>)
<del>
<del>// newStatsCollector returns a new statsCollector for collection stats
<del>// for a registered container at the specified interval. The collector allows
<del>// non-running containers to be added and will start processing stats when
<del>// they are started.
<del>func (daemon *Daemon) newStatsCollector(interval time.Duration) *statsCollector {
<del> return &statsCollector{}
<del>}
<del>
<del>// statsCollector manages and provides container resource stats
<del>type statsCollector struct {
<del>}
<del>
<del>// collect registers the container with the collector and adds it to
<del>// the event loop for collection on the specified interval returning
<del>// a channel for the subscriber to receive on.
<del>func (s *statsCollector) collect(c *container.Container) chan interface{} {
<del> return nil
<del>}
<del>
<del>// stopCollection closes the channels for all subscribers and removes
<del>// the container from metrics collection.
<del>func (s *statsCollector) stopCollection(c *container.Container) {
<del>}
<del>
<del>// unsubscribe removes a specific subscriber from receiving updates for a container's stats.
<del>func (s *statsCollector) unsubscribe(c *container.Container, ch chan interface{}) {
<del>}
| 11
|
Python
|
Python
|
add python 3.6 to show warnings error message
|
6eda4e90fe93e8c3454725ab02c2a8eb507f2337
|
<ide><path>libcloud/test/test_utils.py
<ide> from io import FileIO as file
<ide>
<ide>
<del>def show_warning(msg, cat, fname, lno, line=None):
<add>def show_warning(msg, cat, fname, lno, file=None, line=None):
<ide> WARNINGS_BUFFER.append((msg, cat, fname, lno))
<ide>
<ide> original_func = warnings.showwarning
| 1
|
Javascript
|
Javascript
|
add intersectsvisiblerowrange on texteditorelement
|
a5a80448cb20f198656d62eafae8afba0a77e96b
|
<ide><path>spec/text-editor-element-spec.js
<ide> describe('TextEditorElement', () => {
<ide> })
<ide> )
<ide>
<add> describe('::intersectsVisibleRowRange(start, end)', () => {
<add> it('returns true if the given row range intersects the visible row range', async () => {
<add> const element = buildTextEditorElement()
<add> const editor = element.getModel()
<add> editor.update({autoHeight: false})
<add> element.getModel().setText('x\n'.repeat(20))
<add> element.style.height = '120px'
<add> await element.getNextUpdatePromise()
<add> element.setScrollTop(80)
<add> await element.getNextUpdatePromise()
<add> expect(element.getVisibleRowRange()).toEqual([4, 11])
<add>
<add> expect(element.intersectsVisibleRowRange(0, 4)).toBe(false)
<add> expect(element.intersectsVisibleRowRange(0, 5)).toBe(true)
<add> expect(element.intersectsVisibleRowRange(5, 8)).toBe(true)
<add> expect(element.intersectsVisibleRowRange(11, 12)).toBe(false)
<add> expect(element.intersectsVisibleRowRange(12, 13)).toBe(false)
<add> })
<add> })
<add>
<ide> describe('events', () => {
<ide> let element = null
<ide>
<ide><path>src/text-editor-element.js
<ide> class TextEditorElement extends HTMLElement {
<ide> return this.getModel().getVisibleRowRange()
<ide> }
<ide>
<add> intersectsVisibleRowRange (startRow, endRow) {
<add> return !(
<add> endRow <= this.getFirstVisibleScreenRow() ||
<add> this.getLastVisibleScreenRow() <= startRow
<add> )
<add> }
<add>
<add> selectionIntersectsVisibleRowRange (selection) {
<add> const {start, end} = selection.getScreenRange()
<add> return this.intersectsVisibleRowRange(start.row, end.row + 1)
<add> }
<add>
<ide> setFirstVisibleScreenColumn (column) {
<ide> return this.getModel().setFirstVisibleScreenColumn(column)
<ide> }
| 2
|
Text
|
Text
|
update translation bucket-sort
|
0dfdfef52f50c53d1ee26414825926b30a074042
|
<ide><path>guide/portuguese/algorithms/sorting-algorithms/bucket-sort/index.md
<ide> Vamos dar uma olhada mais de perto.
<ide> Considere que é necessário criar uma matriz de listas, ou seja, de buckets. Os elementos agora precisam ser inseridos nesses buckets com base em suas propriedades. Cada um desses buckets pode ser classificado individualmente usando o Insertion Sort.
<ide>
<ide> ### Pseudocódigo para o tipo de balde:
<add>
<ide> ```
<del>void bucketSort(float[] a,int n)
<del>
<del> {
<del>
<del> for(each floating integer 'x' in n)
<del>
<del> {
<del>
<del> insert x into bucket[n*x];
<del>
<del> }
<del>
<del> for(each bucket)
<del>
<del> {
<del>
<del> sort(bucket);
<del>
<del> }
<del>
<del> }
<add>void bucketSort(float[] a,int n)
<add>{
<add> for(each floating integer 'x' in n)
<add> {
<add> insert x into bucket[n*x];
<add> }
<add>
<add> for(each bucket)
<add> {
<add> sort(bucket);
<add> }
<add>}
<ide> ```
<ide>
<ide> ### Mais Informações:
<ide>
<ide> * [Wikipedia](https://en.wikipedia.org/wiki/Bucket_sort)
<del>
<del>* [GeeksForGeeks](http://www.geeksforgeeks.org/bucket-sort-2/)
<ide>\ No newline at end of file
<add>
<add>* [GeeksForGeeks](http://www.geeksforgeeks.org/bucket-sort-2/)
<add>
<add>* [Hacker Earth](https://www.hackerearth.com/practice/algorithms/sorting/bucket-sort/tutorial/)
| 1
|
Python
|
Python
|
check python version before starting triggerer
|
f0e2143de688fbe2099d0e188e57fdbfaf6c12ed
|
<ide><path>airflow/cli/cli_parser.py
<ide> from functools import lru_cache
<ide> from typing import Callable, Dict, Iterable, List, NamedTuple, Optional, Union
<ide>
<del>from airflow import settings
<add>from airflow import PY37, settings
<ide> from airflow.cli.commands.legacy_commands import check_legacy_command
<ide> from airflow.configuration import conf
<ide> from airflow.exceptions import AirflowException
<ide> def _check_value(self, action, value):
<ide> "To do it, run: pip install 'apache-airflow[cncf.kubernetes]'"
<ide> )
<ide> raise ArgumentError(action, message)
<add> if action.dest == 'subcommand' and value == 'triggerer':
<add> if not PY37:
<add> raise ArgumentError(action, 'triggerer subcommand only works with Python 3.7+')
<ide>
<ide> if action.choices is not None and value not in action.choices:
<ide> check_legacy_command(action, value)
<ide><path>tests/cli/commands/test_triggerer_command.py
<ide> import unittest
<ide> from unittest import mock
<ide>
<add>import pytest
<add>
<add>from airflow import PY37
<ide> from airflow.cli import cli_parser
<ide> from airflow.cli.commands import triggerer_command
<ide>
<ide> class TestTriggererCommand(unittest.TestCase):
<ide> def setUpClass(cls):
<ide> cls.parser = cli_parser.get_parser()
<ide>
<add> @pytest.mark.skipif(not PY37, reason="triggerer subcommand only works with Python 3.7+")
<ide> @mock.patch("airflow.cli.commands.triggerer_command.TriggererJob")
<ide> def test_capacity_argument(
<ide> self,
| 2
|
Python
|
Python
|
support conflict response for google cloud's api
|
532ce827ce8f4d67080c0e39bfe4950f24e9f8e5
|
<ide><path>libcloud/common/google.py
<ide> def _get_error(self, body):
<ide> code = err.get('code')
<ide> message = err.get('message')
<ide> else:
<del> code = None
<add> code = err.get('reason', None)
<ide> message = body.get('error_description', err)
<ide>
<ide> return (code, message)
<ide> def parse_body(self):
<ide> body = self.body
<ide> json_error = True
<ide>
<del> if self.status in [httplib.OK, httplib.CREATED, httplib.ACCEPTED]:
<add> if self.status in [httplib.OK, httplib.CREATED, httplib.ACCEPTED, httplib.CONFLICT]:
<ide> if json_error:
<ide> raise JsonParseError(body, self.status, None)
<ide> elif 'error' in body:
<ide> (code, message) = self._get_error(body)
<ide> if code == 'QUOTA_EXCEEDED':
<ide> raise QuotaExceededError(message, self.status, code)
<del> elif code == 'RESOURCE_ALREADY_EXISTS':
<add> elif (code == 'RESOURCE_ALREADY_EXISTS' or code == 'alreadyExists'):
<ide> raise ResourceExistsError(message, self.status, code)
<ide> elif code.startswith('RESOURCE_IN_USE'):
<ide> raise ResourceInUseError(message, self.status, code)
| 1
|
Ruby
|
Ruby
|
use github.user for github history link
|
1e22bb4ee18e3c0ed5ba36c9bd8f760810a3ae2e
|
<ide><path>Library/Homebrew/brew.h.rb
<ide> def install
<ide> def info name
<ide> require 'formula'
<ide>
<del> user=`cd #{HOMEBREW_PREFIX}; git remote -v show`.scan(/github.com:(.*)\/.*fetch/).to_s
<add> user=`git config --global github.user`.chomp
<ide> user='mxcl' if user.empty?
<add> # FIXME it would be nice if we didn't assume the default branch is masterbrew
<ide> history="http://github.com/#{user}/homebrew/commits/masterbrew/Library/Formula/#{Formula.path(name).basename}"
<ide>
<ide> exec 'open', history if ARGV.flag? '--github'
| 1
|
Python
|
Python
|
remove problematic test
|
bdebbef45552d698d390aa430b527ee27830f11b
|
<ide><path>spacy/tests/regression/test_issue2626.py
<del>from __future__ import unicode_literals
<del>import pytest
<del>import spacy
<del>
<del>@pytest.mark.skip
<del>def test_issue2626():
<del> '''Check that this sentence doesn't cause an infinite loop in the tokenizer.'''
<del> nlp = spacy.blank('en')
<del> text = """
<del> ABLEItemColumn IAcceptance Limits of ErrorIn-Service Limits of ErrorColumn IIColumn IIIColumn IVColumn VComputed VolumeUnder Registration of\xa0VolumeOver Registration of\xa0VolumeUnder Registration of\xa0VolumeOver Registration of\xa0VolumeCubic FeetCubic FeetCubic FeetCubic FeetCubic Feet1Up to 10.0100.0050.0100.005220.0200.0100.0200.010350.0360.0180.0360.0184100.0500.0250.0500.0255Over 100.5% of computed volume0.25% of computed volume0.5% of computed volume0.25% of computed volume TABLE ItemColumn IAcceptance Limits of ErrorIn-Service Limits of ErrorColumn IIColumn IIIColumn IVColumn VComputed VolumeUnder Registration of\xa0VolumeOver Registration of\xa0VolumeUnder Registration of\xa0VolumeOver Registration of\xa0VolumeCubic FeetCubic FeetCubic FeetCubic FeetCubic Feet1Up to 10.0100.0050.0100.005220.0200.0100.0200.010350.0360.0180.0360.0184100.0500.0250.0500.0255Over 100.5% of computed volume0.25% of computed volume0.5% of computed volume0.25% of computed volume ItemColumn IAcceptance Limits of ErrorIn-Service Limits of ErrorColumn IIColumn IIIColumn IVColumn VComputed VolumeUnder Registration of\xa0VolumeOver Registration of\xa0VolumeUnder Registration of\xa0VolumeOver Registration of\xa0VolumeCubic FeetCubic FeetCubic FeetCubic FeetCubic Feet1Up to 10.0100.0050.0100.005220.0200.0100.0200.010350.0360.0180.0360.0184100.0500.0250.0500.0255Over 100.5% of computed volume0.25% of computed volume0.5% of computed volume0.25% of computed volume
<del> """
<del> doc = nlp.make_doc(text)
<del>
| 1
|
Javascript
|
Javascript
|
throw error if improperly defined factory
|
9b7967dca1eb675aef59822ba626c4c004fc5835
|
<ide><path>packages/container/lib/container.js
<ide> Container.prototype = {
<ide> validateFullName(fullName);
<ide>
<ide> if (this.factoryCache.has(normalizedName)) {
<del> throw new Error("Attempted to register a factoryInjection for a type that has already been looked up. ('" + normalizedName + "', '" + property + "', '" + injectionName + "')");
<add> throw new Error('Attempted to register a factoryInjection for a type that has already ' +
<add> 'been looked up. (\'' + normalizedName + '\', \'' + property + '\', \'' + injectionName + '\')');
<ide> }
<add>
<ide> addInjection(this.factoryInjections, normalizedName, property, normalizedInjectionName);
<ide> },
<ide>
<ide> Container.prototype = {
<ide> @method destroy
<ide> */
<ide> destroy: function() {
<del> for (var i=0, l=this.children.length; i<l; i++) {
<add> for (var i = 0, length = this.children.length; i < length; i++) {
<ide> this.children[i].destroy();
<ide> }
<ide>
<ide> Container.prototype = {
<ide> @method reset
<ide> */
<ide> reset: function() {
<del> for (var i=0, l=this.children.length; i<l; i++) {
<add> for (var i = 0, length = this.children.length; i < length; i++) {
<ide> resetCache(this.children[i]);
<ide> }
<add>
<ide> resetCache(this);
<ide> }
<ide> };
<ide> function lookup(container, fullName, options) {
<ide> }
<ide>
<ide> function illegalChildOperation(operation) {
<del> throw new Error(operation + " is not currently supported on child containers");
<add> throw new Error(operation + ' is not currently supported on child containers');
<ide> }
<ide>
<ide> function isSingleton(container, fullName) {
<ide> function buildInjections(container, injections) {
<ide>
<ide> var injection, injectable;
<ide>
<del> for (var i=0, l=injections.length; i<l; i++) {
<add> for (var i = 0, length = injections.length; i < length; i++) {
<ide> injection = injections[i];
<ide> injectable = lookup(container, injection.fullName);
<ide>
<ide> function option(container, fullName, optionName) {
<ide> return options[optionName];
<ide> }
<ide>
<del> var type = fullName.split(":")[0];
<add> var type = fullName.split(':')[0];
<ide> options = container._typeOptions.get(type);
<ide>
<ide> if (options) {
<ide> function factoryFor(container, fullName) {
<ide> var factory = container.resolve(name);
<ide> var injectedFactory;
<ide> var cache = container.factoryCache;
<del> var type = fullName.split(":")[0];
<add> var type = fullName.split(':')[0];
<ide>
<ide> if (factory === undefined) { return; }
<ide>
<ide> function factoryFor(container, fullName) {
<ide> // for now just fallback to create time injection
<ide> return factory;
<ide> } else {
<del>
<del> var injections = injectionsFor(container, fullName);
<add> var injections = injectionsFor(container, fullName);
<ide> var factoryInjections = factoryInjectionsFor(container, fullName);
<ide>
<ide> factoryInjections._toString = container.makeToString(factory, fullName);
<ide> function factoryFor(container, fullName) {
<ide> }
<ide>
<ide> function injectionsFor(container, fullName) {
<del> var splitName = fullName.split(":"),
<add> var splitName = fullName.split(':'),
<ide> type = splitName[0],
<ide> injections = [];
<ide>
<ide> function injectionsFor(container, fullName) {
<ide> }
<ide>
<ide> function factoryInjectionsFor(container, fullName) {
<del> var splitName = fullName.split(":"),
<add> var splitName = fullName.split(':'),
<ide> type = splitName[0],
<ide> factoryInjections = [];
<ide>
<ide> function instantiate(container, fullName) {
<ide> }
<ide>
<ide> if (factory) {
<add> if (typeof factory.create !== 'function') {
<add> throw new Error('Failed to create an instance of \'' + fullName + '\'. ' +
<add> 'Most likely an improperly defined class or an invalid module export.');
<add> }
<add>
<ide> if (typeof factory.extend === 'function') {
<ide> // assume the factory was extendable and is already injected
<ide> return factory.create();
<ide><path>packages/container/tests/container_test.js
<ide> test("A registered factory is returned from lookupFactory is the same factory ea
<ide> deepEqual(container.lookupFactory('controller:post'), container.lookupFactory('controller:post'), 'The return of lookupFactory is always the same');
<ide> });
<ide>
<del>test("A factory returned from lookupFactory has a debugkey", function(){
<add>test("A factory returned from lookupFactory has a debugkey", function() {
<ide> var container = new Container();
<ide> var PostController = factory();
<ide> var instance;
<ide> test("A factory returned from lookupFactory has a debugkey", function(){
<ide> equal(PostFactory._debugContainerKey, 'controller:post', 'factory instance receives _debugContainerKey');
<ide> });
<ide>
<del>test("fallback for to create time injections if factory has no extend", function(){
<add>test("fallback for to create time injections if factory has no extend", function() {
<ide> var container = new Container();
<ide> var AppleController = factory();
<ide> var PostController = factory();
<ide> test("A failed lookup returns undefined", function() {
<ide> equal(container.lookup('doesnot:exist'), undefined);
<ide> });
<ide>
<add>test("An invalid factory throws an error", function() {
<add> var container = new Container();
<add>
<add> container.register('controller:foo', {});
<add>
<add> throws(function() {
<add> container.lookup('controller:foo');
<add> }, /Failed to create an instance of \'controller:foo\'/);
<add>});
<add>
<ide> test("Injecting a failed lookup raises an error", function() {
<ide> Ember.MODEL_FACTORY_INJECTIONS = true;
<ide>
<ide> test('container.has should not accidentally cause injections on that factory to
<ide> ok(container.has('controller:apple'));
<ide> });
<ide>
<del>test('once resolved, always return the same result', function(){
<add>test('once resolved, always return the same result', function() {
<ide> expect(1);
<ide>
<ide> var container = new Container();
<ide> test('once resolved, always return the same result', function(){
<ide> equal(container.resolve('models:bar'), Bar);
<ide> });
<ide>
<del>test('once looked up, assert if an injection is registered for the entry', function(){
<add>test('once looked up, assert if an injection is registered for the entry', function() {
<ide> expect(1);
<ide>
<ide> var container = new Container(),
| 2
|
Javascript
|
Javascript
|
remove period for eslint `passhref` docs link.
|
ad5e9bd644e1e69e5108883b5a59033710561f86
|
<ide><path>packages/eslint-plugin-next/lib/rules/link-passhref.js
<ide> module.exports = {
<ide> attributes.value('passHref') !== true
<ide> ? 'must be set to true'
<ide> : 'is missing'
<del> }. See https://nextjs.org/docs/messages/link-passhref.`,
<add> }. See https://nextjs.org/docs/messages/link-passhref`,
<ide> })
<ide> }
<ide> },
<ide><path>test/eslint-plugin-next/link-passhref.unit.test.js
<ide> ruleTester.run('link-passhref', rule, {
<ide> errors: [
<ide> {
<ide> message:
<del> 'passHref is missing. See https://nextjs.org/docs/messages/link-passhref.',
<add> 'passHref is missing. See https://nextjs.org/docs/messages/link-passhref',
<ide> type: 'JSXOpeningElement',
<ide> },
<ide> ],
<ide> ruleTester.run('link-passhref', rule, {
<ide> errors: [
<ide> {
<ide> message:
<del> 'passHref must be set to true. See https://nextjs.org/docs/messages/link-passhref.',
<add> 'passHref must be set to true. See https://nextjs.org/docs/messages/link-passhref',
<ide> type: 'JSXOpeningElement',
<ide> },
<ide> ],
| 2
|
Go
|
Go
|
use the arch info from base image
|
92b17b10bad1f1788419b70db5d6ed9cdf8d15ef
|
<ide><path>image/image.go
<ide> func (img *Image) RunConfig() *container.Config {
<ide> return img.Config
<ide> }
<ide>
<add>// BaseImgArch returns the image's architecture. If not populated, defaults to the host runtime arch.
<add>func (img *Image) BaseImgArch() string {
<add> arch := img.Architecture
<add> if arch == "" {
<add> arch = runtime.GOARCH
<add> }
<add> return arch
<add>}
<add>
<ide> // OperatingSystem returns the image's operating system. If not populated, defaults to the host runtime OS.
<ide> func (img *Image) OperatingSystem() string {
<ide> os := img.OS
<ide> func NewChildImage(img *Image, child ChildConfig, platform string) *Image {
<ide> V1Image: V1Image{
<ide> DockerVersion: dockerversion.Version,
<ide> Config: child.Config,
<del> Architecture: runtime.GOARCH,
<add> Architecture: img.BaseImgArch(),
<ide> OS: platform,
<ide> Container: child.ContainerID,
<ide> ContainerConfig: *child.ContainerConfig,
| 1
|
Javascript
|
Javascript
|
normalize class access for svg
|
48096048cf92bcada9b8c4f54d7002fbcf239416
|
<ide><path>src/service/compiler.js
<ide> function $CompileProvider($provide) {
<ide> var element = cloneConnectFn
<ide> ? JQLitePrototype.clone.call(templateElement) // IMPORTANT!!!
<ide> : templateElement;
<del> element.data('$scope', scope).addClass('ng-scope');
<add> safeAddClass(element.data('$scope', scope), 'ng-scope');
<ide> if (cloneConnectFn) cloneConnectFn(element, scope);
<ide> if (linkingFn) linkingFn(scope, element, element);
<ide> return element;
<ide> function $CompileProvider($provide) {
<ide> throw Error("Unsupported '" + mode + "' for '" + localName + "'.");
<ide> }
<ide>
<add> function safeAddClass(element, className) {
<add> try {
<add> element.addClass(className);
<add> } catch(e) {
<add> // ignore, since it means that we are trying to set class on
<add> // SVG element, where class name is read-only.
<add> }
<add> }
<add>
<ide> /**
<ide> * Compile function matches each node in nodeList against the directives. Once all directives
<ide> * for a particular node are collected their compile functions are executed. The compile
<ide> function $CompileProvider($provide) {
<ide>
<ide> // use class as directive
<ide> className = node.className;
<del> while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
<del> nName = directiveNormalize(match[2]);
<del> if (addDirective(directives, nName, 'C', maxPriority)) {
<del> attrs[nName] = trim(match[3]);
<add> if (isString(className)) {
<add> while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
<add> nName = directiveNormalize(match[2]);
<add> if (addDirective(directives, nName, 'C', maxPriority)) {
<add> attrs[nName] = trim(match[3]);
<add> }
<add> className = className.substr(match.index + match[0].length);
<ide> }
<del> className = className.substr(match.index + match[0].length);
<ide> }
<ide> break;
<ide> case 3: /* Text Node */
<ide> function $CompileProvider($provide) {
<ide> if (directiveValue = directive.scope) {
<ide> assertNoDuplicate('isolated scope', newIsolatedScopeDirective, directive, element);
<ide> if (isObject(directiveValue)) {
<del> element.addClass('ng-isolate-scope');
<add> safeAddClass(element, 'ng-isolate-scope');
<ide> newIsolatedScopeDirective = directive;
<ide> }
<del> element.addClass('ng-scope');
<add> safeAddClass(element, 'ng-scope');
<ide> newScopeDirective = newScopeDirective || directive;
<ide> }
<ide>
<ide> function $CompileProvider($provide) {
<ide> // copy the new attributes on the old attrs object
<ide> forEach(src, function(value, key) {
<ide> if (key == 'class') {
<del> element.addClass(value);
<add> safeAddClass(element, value);
<ide> } else if (key == 'style') {
<ide> element.attr('style', element.attr('style') + ';' + value);
<ide> } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
<ide> function $CompileProvider($provide) {
<ide> var parent = node.parent(),
<ide> bindings = parent.data('$binding') || [];
<ide> bindings.push(interpolateFn);
<del> parent.data('$binding', bindings).addClass('ng-binding');
<add> safeAddClass(parent.data('$binding', bindings), 'ng-binding');
<ide> scope.$watch(interpolateFn, function(value) {
<ide> node[0].nodeValue = value;
<ide> });
<ide><path>test/service/compilerSpec.js
<ide> describe('$compile', function() {
<ide> }));
<ide>
<ide>
<add> it('should ignore not set CSS classes on SVG elements', inject(function($compile, $rootScope, log) {
<add> if (!window.SVGElement) return;
<add> // According to spec SVG element className property is readonly, but only FF
<add> // implements it this way which causes compile exceptions.
<add> element = $compile('<svg><text>{{1}}</text></svg>')($rootScope);
<add> $rootScope.$digest();
<add> expect(element.text()).toEqual('1');
<add> }));
<add>
<add>
<ide> it('should allow directives in comments', inject(
<ide> function($compile, $rootScope, log) {
<ide> element = $compile('<div>0<!-- directive: log angular -->1</div>')($rootScope);
| 2
|
Python
|
Python
|
remove interactive support. no one uses it
|
5f88e3d40e2c2efc530607691f822e5f73315861
|
<ide><path>numpy/distutils/core.py
<ide> def _command_line_ok(_cache=[]):
<ide> _cache.append(ok)
<ide> return ok
<ide>
<del>def _exit_interactive_session(_cache=[]):
<del> if _cache:
<del> return # been here
<del> _cache.append(1)
<del> print '-'*72
<del> raw_input('Press ENTER to close the interactive session..')
<del> print '='*72
<del>
<ide> def get_distribution(always=False):
<ide> dist = distutils.core._setup_distribution
<ide> # XXX Hack to get numpy installable with easy_install.
<ide> def get_distribution(always=False):
<ide> return dist
<ide>
<ide> def setup(**attr):
<del>
<del> if len(sys.argv)<=1 and not attr.get('script_args',[]):
<del> from interactive import interactive_sys_argv
<del> import atexit
<del> atexit.register(_exit_interactive_session)
<del> sys.argv[:] = interactive_sys_argv(sys.argv)
<del> if len(sys.argv)>1:
<del> return setup(**attr)
<del>
<ide> cmdclass = numpy_cmdclass.copy()
<ide>
<ide> new_attr = attr.copy()
<ide><path>numpy/distutils/interactive.py
<del>import os
<del>import sys
<del>from pprint import pformat
<del>
<del>__all__ = ['interactive_sys_argv']
<del>
<del>def show_information(*args):
<del> print 'Python',sys.version
<del> for a in ['platform','prefix','byteorder','path']:
<del> print 'sys.%s = %s' % (a,pformat(getattr(sys,a)))
<del> for a in ['name']:
<del> print 'os.%s = %s' % (a,pformat(getattr(os,a)))
<del> if hasattr(os,'uname'):
<del> print 'system,node,release,version,machine = ',os.uname()
<del>
<del>def show_environ(*args):
<del> for k,i in os.environ.items():
<del> print ' %s = %s' % (k, i)
<del>
<del>def show_fortran_compilers(*args):
<del> from fcompiler import show_fcompilers
<del> show_fcompilers()
<del>
<del>def show_compilers(*args):
<del> from distutils.ccompiler import show_compilers
<del> show_compilers()
<del>
<del>def show_tasks(argv,ccompiler,fcompiler):
<del> print """\
<del>
<del>Tasks:
<del> i - Show python/platform/machine information
<del> ie - Show environment information
<del> c - Show C compilers information
<del> c<name> - Set C compiler (current:%s)
<del> f - Show Fortran compilers information
<del> f<name> - Set Fortran compiler (current:%s)
<del> e - Edit proposed sys.argv[1:].
<del>
<del>Task aliases:
<del> 0 - Configure
<del> 1 - Build
<del> 2 - Install
<del> 2<prefix> - Install with prefix.
<del> 3 - Inplace build
<del> 4 - Source distribution
<del> 5 - Binary distribution
<del>
<del>Proposed sys.argv = %s
<del> """ % (ccompiler, fcompiler, argv)
<del>
<del>
<del>from exec_command import splitcmdline
<del>
<del>def edit_argv(*args):
<del> argv = args[0]
<del> readline = args[1]
<del> if readline is not None:
<del> readline.add_history(' '.join(argv[1:]))
<del> try:
<del> s = raw_input('Edit argv [UpArrow to retrive %r]: ' % (' '.join(argv[1:])))
<del> except EOFError:
<del> return
<del> if s:
<del> argv[1:] = splitcmdline(s)
<del> return
<del>
<del>def interactive_sys_argv(argv):
<del> print '='*72
<del> print 'Starting interactive session'
<del> print '-'*72
<del>
<del> readline = None
<del> try:
<del> try:
<del> import readline
<del> except ImportError:
<del> pass
<del> else:
<del> import tempfile
<del> tdir = tempfile.gettempdir()
<del> username = os.environ.get('USER',os.environ.get('USERNAME','UNKNOWN'))
<del> histfile = os.path.join(tdir,".pyhist_interactive_setup-" + username)
<del> try:
<del> try: readline.read_history_file(histfile)
<del> except IOError: pass
<del> import atexit
<del> atexit.register(readline.write_history_file, histfile)
<del> except AttributeError: pass
<del> except Exception, msg:
<del> print msg
<del>
<del> task_dict = {'i':show_information,
<del> 'ie':show_environ,
<del> 'f':show_fortran_compilers,
<del> 'c':show_compilers,
<del> 'e':edit_argv,
<del> }
<del> c_compiler_name = None
<del> f_compiler_name = None
<del>
<del> while 1:
<del> show_tasks(argv,c_compiler_name, f_compiler_name)
<del> try:
<del> task = raw_input('Choose a task (^D to quit, Enter to continue with setup): ').lower()
<del> except EOFError:
<del> print
<del> task = 'quit'
<del> if task=='': break
<del> if task=='quit': sys.exit()
<del> task_func = task_dict.get(task,None)
<del> if task_func is None:
<del> if task[0]=='c':
<del> c_compiler_name = task[1:]
<del> if c_compiler_name=='none':
<del> c_compiler_name = None
<del> continue
<del> if task[0]=='f':
<del> f_compiler_name = task[1:]
<del> if f_compiler_name=='none':
<del> f_compiler_name = None
<del> continue
<del> if task[0]=='2' and len(task)>1:
<del> prefix = task[1:]
<del> task = task[0]
<del> else:
<del> prefix = None
<del> if task == '4':
<del> argv[1:] = ['sdist','-f']
<del> continue
<del> elif task in '01235':
<del> cmd_opts = {'config':[],'config_fc':[],
<del> 'build_ext':[],'build_src':[],
<del> 'build_clib':[]}
<del> if c_compiler_name is not None:
<del> c = '--compiler=%s' % (c_compiler_name)
<del> cmd_opts['config'].append(c)
<del> if task != '0':
<del> cmd_opts['build_ext'].append(c)
<del> cmd_opts['build_clib'].append(c)
<del> if f_compiler_name is not None:
<del> c = '--fcompiler=%s' % (f_compiler_name)
<del> cmd_opts['config_fc'].append(c)
<del> if task != '0':
<del> cmd_opts['build_ext'].append(c)
<del> cmd_opts['build_clib'].append(c)
<del> if task=='3':
<del> cmd_opts['build_ext'].append('--inplace')
<del> cmd_opts['build_src'].append('--inplace')
<del> conf = []
<del> sorted_keys = ['config','config_fc','build_src',
<del> 'build_clib','build_ext']
<del> for k in sorted_keys:
<del> opts = cmd_opts[k]
<del> if opts: conf.extend([k]+opts)
<del> if task=='0':
<del> if 'config' not in conf:
<del> conf.append('config')
<del> argv[1:] = conf
<del> elif task=='1':
<del> argv[1:] = conf+['build']
<del> elif task=='2':
<del> if prefix is not None:
<del> argv[1:] = conf+['install','--prefix=%s' % (prefix)]
<del> else:
<del> argv[1:] = conf+['install']
<del> elif task=='3':
<del> argv[1:] = conf+['build']
<del> elif task=='5':
<del> if sys.platform=='win32':
<del> argv[1:] = conf+['bdist_wininst']
<del> else:
<del> argv[1:] = conf+['bdist']
<del> else:
<del> print 'Skipping unknown task:',`task`
<del> else:
<del> print '-'*68
<del> try:
<del> task_func(argv,readline)
<del> except Exception,msg:
<del> print 'Failed running task %s: %s' % (task,msg)
<del> break
<del> print '-'*68
<del> print
<del>
<del> print '-'*72
<del> return argv
| 2
|
Javascript
|
Javascript
|
remove metrolistview from sectionlist
|
4a5221884f7dfd431840c09f860451739bf8a98f
|
<ide><path>Libraries/Lists/SectionList.js
<ide> */
<ide> 'use strict';
<ide>
<del>const MetroListView = require('MetroListView');
<ide> const Platform = require('Platform');
<ide> const React = require('React');
<ide> const ScrollView = require('ScrollView');
<ide> class SectionList<SectionT: SectionBase<any>> extends React.PureComponent<
<ide> viewOffset?: number,
<ide> viewPosition?: number,
<ide> }) {
<del> this._wrapperListRef.scrollToLocation(params);
<add> if (this._wrapperListRef != null) {
<add> this._wrapperListRef.scrollToLocation(params);
<add> }
<ide> }
<ide>
<ide> /**
<ide> class SectionList<SectionT: SectionBase<any>> extends React.PureComponent<
<ide> }
<ide>
<ide> render() {
<del> const List = VirtualizedSectionList;
<ide> /* $FlowFixMe(>=0.66.0 site=react_native_fb) This comment suppresses an
<ide> * error found when Flow v0.66 was deployed. To see the error delete this
<ide> * comment and run Flow. */
<del> return <List {...this.props} ref={this._captureRef} />;
<add> return <VirtualizedSectionList {...this.props} ref={this._captureRef} />;
<ide> }
<ide>
<del> _wrapperListRef: MetroListView | VirtualizedSectionList<any>;
<add> _wrapperListRef: ?React.ElementRef<typeof VirtualizedSectionList>;
<ide> _captureRef = ref => {
<del> /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This comment
<del> * suppresses an error when upgrading Flow's support for React. To see the
<del> * error delete this comment and run Flow. */
<ide> this._wrapperListRef = ref;
<ide> };
<ide> }
| 1
|
Javascript
|
Javascript
|
remove usage of require('util')
|
5b59b5f525ac4c17e34f88a2eb672687004e606c
|
<ide><path>lib/internal/url.js
<ide> 'use strict';
<ide>
<del>const util = require('util');
<add>const { inspect } = require('internal/util/inspect');
<ide> const {
<ide> encodeStr,
<ide> hexTable,
<ide> class URLSearchParams {
<ide> this[context] = null;
<ide> }
<ide>
<del> [util.inspect.custom](recurseTimes, ctx) {
<add> [inspect.custom](recurseTimes, ctx) {
<ide> if (!this || !this[searchParams] || this[searchParams][searchParams]) {
<ide> throw new ERR_INVALID_THIS('URLSearchParams');
<ide> }
<ide> class URLSearchParams {
<ide> if (recurseTimes !== null) {
<ide> innerOpts.depth = recurseTimes - 1;
<ide> }
<del> var innerInspect = (v) => util.inspect(v, innerOpts);
<add> var innerInspect = (v) => inspect(v, innerOpts);
<ide>
<ide> var list = this[searchParams];
<ide> var output = [];
<ide> class URL {
<ide> scheme === 'file:');
<ide> }
<ide>
<del> [util.inspect.custom](depth, opts) {
<add> [inspect.custom](depth, opts) {
<ide> if (this == null ||
<ide> Object.getPrototypeOf(this[context]) !== URLContext.prototype) {
<ide> throw new ERR_INVALID_THIS('URL');
<ide> class URL {
<ide> obj[context] = this[context];
<ide> }
<ide>
<del> return util.inspect(obj, opts);
<add> return inspect(obj, opts);
<ide> }
<ide> }
<ide>
<ide> defineIDLClass(URLSearchParamsIteratorPrototype, 'URLSearchParams Iterator', {
<ide> done: false
<ide> };
<ide> },
<del> [util.inspect.custom](recurseTimes, ctx) {
<add> [inspect.custom](recurseTimes, ctx) {
<ide> if (this == null || this[context] == null || this[context].target == null)
<ide> throw new ERR_INVALID_THIS('URLSearchParamsIterator');
<ide>
<ide> defineIDLClass(URLSearchParamsIteratorPrototype, 'URLSearchParams Iterator', {
<ide> }
<ide> return prev;
<ide> }, []);
<del> const breakLn = util.inspect(output, innerOpts).includes('\n');
<del> const outputStrs = output.map((p) => util.inspect(p, innerOpts));
<add> const breakLn = inspect(output, innerOpts).includes('\n');
<add> const outputStrs = output.map((p) => inspect(p, innerOpts));
<ide> let outputStr;
<ide> if (breakLn) {
<ide> outputStr = `\n ${outputStrs.join(',\n ')}`;
| 1
|
Javascript
|
Javascript
|
initialize ngmodeloptions in prelink
|
fbf5ab8f17d28efeadb492c5a252f0778643f072
|
<ide><path>src/ng/directive/input.js
<ide> var ngModelDirective = function() {
<ide> return {
<ide> require: ['ngModel', '^?form', '^?ngModelOptions'],
<ide> controller: NgModelController,
<del> link: function(scope, element, attr, ctrls) {
<del> // notify others, especially parent forms
<add> link: {
<add> pre: function(scope, element, attr, ctrls) {
<add> // Pass the ng-model-options to the ng-model controller
<add> if (ctrls[2]) {
<add> ctrls[0].$options = ctrls[2].$options;
<add> }
<ide>
<del> var modelCtrl = ctrls[0],
<del> formCtrl = ctrls[1] || nullFormCtrl;
<add> // notify others, especially parent forms
<ide>
<del> formCtrl.$addControl(modelCtrl);
<add> var modelCtrl = ctrls[0],
<add> formCtrl = ctrls[1] || nullFormCtrl;
<ide>
<del> // Pass the ng-model-options to the ng-model controller
<del> if ( ctrls[2] ) {
<del> modelCtrl.$options = ctrls[2].$options;
<del> }
<add> formCtrl.$addControl(modelCtrl);
<ide>
<del> scope.$on('$destroy', function() {
<del> formCtrl.$removeControl(modelCtrl);
<del> });
<add> scope.$on('$destroy', function() {
<add> formCtrl.$removeControl(modelCtrl);
<add> });
<add> }
<ide> }
<ide> };
<ide> };
<ide><path>test/ng/directive/inputSpec.js
<ide> describe('input', function() {
<ide> expect(scope.name).toEqual('a');
<ide> });
<ide>
<add> it('should allow overriding the model update trigger event on text areas', function() {
<add> compileInput(
<add> '<textarea ng-model="name" name="alias" '+
<add> 'ng-model-options="{ updateOn: \'blur\' }"'+
<add> '/>');
<add>
<add> changeInputValueTo('a');
<add> expect(scope.name).toBeUndefined();
<add> browserTrigger(inputElm, 'blur');
<add> expect(scope.name).toEqual('a');
<add> });
<ide>
<ide> it('should bind the element to a list of events', function() {
<ide> compileInput(
| 2
|
Text
|
Text
|
add french translation
|
6756b017b5baccc75e99c4069047918aa1a0ebf5
|
<ide><path>threejs/lessons/fr/threejs-textures.md
<add>Title: Three.js Textures
<add>Description: Using textures in three.js
<add>TOC: Textures
<add>
<add>Cet article fait partie d'une série consacrée à Three.js.
<add>Le premier article s'intitule [Principes de base](threejs-fundamentals.html).
<add>L'[article précédent](threejs-setup.html) concerné la configuration nécessaire pour cet article.
<add>Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là.
<add>
<add>Les textures sont un gros sujet dans Three.js et je ne suis pas sûr de pouvoir les expliquer à 100% mais je vais essayer. Il y a de nombreuses choses à voir et beaucoup d'entre elles sont interdépendantes, il est donc difficile de les expliquer tous en même temps. Voici une table des matières rapide pour cet article.
<add>
<add><ul>
<add><li><a href="#hello">Hello Texture</a></li>
<add><li><a href="#six">6 textures, une pour chaque face d'un cube</a></li>
<add><li><a href="#loading">Téléchargement de textures</a></li>
<add><ul>
<add> <li><a href="#easy">La façon la plus simple</a></li>
<add> <li><a href="#wait1">En attente du chargement d'une texture</a></li>
<add> <li><a href="#waitmany">En attente du téléchargement de plusieurs textures</a></li>
<add> <li><a href="#cors">Chargement de textures d'autres origines</a></li>
<add></ul>
<add><li><a href="#memory">Utilisation de la mémoire</a></li>
<add><li><a href="#format">JPG ou PNG</a></li>
<add><li><a href="#filtering-and-mips">Filtrage et mips</a></li>
<add><li><a href="#uvmanipulation">Répétition, décalage, rotation, emballage</a></li>
<add></ul>
<add>
<add>## <a name="hello"></a> Hello Texture
<add>
<add>Les textures sont *generallement* des images qui sont le plus souvent créées dans un programme tiers comme Photoshop ou GIMP. Par exemple, mettons cette image sur un cube.
<add>
<add><div class="threejs_center">
<add> <img src="../resources/images/wall.jpg" style="width: 600px;" class="border" >
<add></div>
<add>
<add>Modifions l'un de nos premiers échantillons. Tout ce que nous avons à faire, c'est de créer un `TextureLoader`. Appelons-le avec sa méthode
<add>[`load`](TextureLoader.load) et l'URL d'une image définissons la propriété `map` du matériau sur le résultat au lieu de définir sa `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>
<add>Notez que nous utilisons un `MeshBasicMaterial`, donc pas besoin de lumières.
<add>
<add>{{{example url="../threejs-textured-cube.html" }}}
<add>
<add>## <a name="six"></a> 6 textures, une pour chaque face d'un cube
<add>
<add>Que diriez-vous de 6 textures, une sur chaque face d'un cube ?
<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>Fabriquons juste 6 materiaux et passons-les sous forme de tableau lors de la création de la `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>Ça marche !
<add>
<add>{{{example url="../threejs-textured-cube-6-textures.html" }}}
<add>
<add>Il convient de noter, cependant, que tous les types de géométries ne peuvent supporter la prise en charge de plusieurs matériaux. `BoxGeometry` ne peut utiliser que 6 materiaux, un pour chaque face.
<add>`ConeGeometry`, seulement 2, un pour la base et un pour le cône.
<add>`CylinderGeometry` peut recevoir 3 materiaux pour le bas, le haut et le côté.
<add>Dans les autres cas, vous devrez créer ou charger une géométrie personnalisée et/ou modifier les coordonnées de texture.
<add>
<add>Il est bien plus performant d'utiliser, comme dans bien d'autres moteurs 3D, un
<add>[atlas de texture](https://fr.wikipedia.org/wiki/Atlas_de_texture)
<add>si vous voulez utiliser plusieurs images sur une même géométrie. Un atlas de texture est l'endroit où vous placez plusieurs images dans une seule texture, puis utilisez les coordonnées de texture sur les sommets de votre géométrie pour sélectionner les parties d'une texture à utiliser sur chaque triangle de votre géométrie.
<add>
<add>Que sont les coordonnées de texture ? Ce sont des données ajoutées à chaque sommet d'un morceau de géométrie qui spécifient quelle partie de la texture correspond à ce sommet spécifique. Nous les examinerons lorsque nous commencerons à [créer une géométrie personnalisée](threejs-custom-buffergeometry.html).
<add>
<add>## <a name="loading"></a> Téléchargement de textures
<add>
<add>### <a name="easy"></a> La façon la plus simple
<add>
<add>La plupart du code de ce site utilise la méthode la plus simple pour charger les textures. Nous créons un `TextureLoader` puis appelons sa méthode de [`chargement`](TextureLoader.load).
<add>Cela renvoie un objet `Texture`.
<add>
<add>```js
<add>const texture = loader.load('resources/images/flower-1.jpg');
<add>```
<add>
<add>Il est important de noter qu'en utilisant cette méthode, notre texture sera transparente jusqu'à ce que l'image soit chargée de manière asynchrone par Three.js, auquel cas elle mettra à jour la texture avec l'image téléchargée.
<add>
<add>Le gros avantage, c'est que nous n'avons pas besoin d'attendre que la texture soit chargée pour que notre page s'affiche. C'est probablement correct pour un grand nombre de cas d'utilisation, mais si nous le voulons, nous pouvons demander à Three.js de nous dire quand le téléchargement de la texture est terminé.
<add>
<add>### <a name="wait1"></a> En attente du chargement d'une texture
<add>
<add>Pour attendre qu'une texture se charge, la méthode `load` du chargeur de texture prend une 'callback function' qui sera appelée lorsque la texture aura fini de se charger. Pour en revenir à notre meilleur exemple, nous pouvons attendre que la texture se charge avant de créer notre `Mesh` et de l'ajouter à une scène comme celle-ci
<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 to our list of cubes to rotate
<add>});
<add>```
<add>
<add>À moins de vider le cache de votre navigateur et d'avoir une connexion lente, il est peu probable que vous voyiez la différence, mais soyez assuré qu'il attend le chargement de la texture.
<add>
<add>{{{example url="../threejs-textured-cube-wait-for-texture.html" }}}
<add>
<add>### <a name="waitmany"></a> En attente du chargement de plusieurs textures
<add>
<add>Pour attendre que toutes les textures soient chargées, vous pouvez utiliser un `LoadingManager`. Créez-en un et transmettez-le à `TextureLoader`, puis définissez sa propriété [`onLoad`](LoadingManager.onLoad) avec une 'callback function'.
<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); // ajouter à la liste des cubes
<add>+};
<add>```
<add>
<add>Le `LoadingManager` a également une propriété [`onProgress`](LoadingManager.onProgress) que nous pouvons définir sur une autre 'callback' pour afficher un indicateur de progression.
<add>
<add>Ajoutons d'abord une barre de progression en 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>et un peu de 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>Ensuite, dans le code, nous mettrons à jour la `progressbar` dans la 'callback function' `onProgress`. Elle est appelée avec l'URL du dernier élément chargé, le nombre d'éléments chargés jusqu'à présent et le nombre total d'éléments chargés.
<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); // ajouter à la liste des cubes
<add>};
<add>
<add>+loadManager.onProgress = (urlOfLastItemLoaded, itemsLoaded, itemsTotal) => {
<add>+ const progress = itemsLoaded / itemsTotal;
<add>+ progressBarElem.style.transform = `scaleX(${progress})`;
<add>+};
<add>```
<add>
<add>À moins que vous ne vidiez votre cache et que votre connexion soit lente, vous ne verrez peut-être pas la barre de chargement.
<add>
<add>{{{example url="../threejs-textured-cube-wait-for-all-textures.html" }}}
<add>
<add>## <a name="cors"></a> Chargement de textures d'autres origines
<add>
<add>Pour utiliser des images d'autres serveurs, ces serveurs doivent envoyer les en-têtes corrects. Si ce n'est pas le cas, vous ne pouvez pas utiliser les images dans Three.js et vous obtiendrez une erreur. Si vous utilisez un serveur distant, assurez-vous qu'il envoie [les bons en-têtes](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). Sinon, vous ne pourrez pas utiliser les images provenant de ce serveur.
<add>
<add>Par exemple [imgur](https://imgur.com), [flickr](https://flickr.com), et
<add>[github](https://github.com) envoient des en-têtes vous permettant d'utiliser des images hébergées sur leurs serveurs avec Three.js. La plupart des autres sites web ne le font pas.
<add>
<add>## <a name="memory"></a> Utilisation de la mémoire
<add>
<add>Les textures sont souvent la partie d'une application Three.js qui utilise le plus de mémoire. Il est important de comprendre qu'en *général*, textures prennent `width * height * 4 * 1.33` octets de mémoire.
<add>
<add>Remarquez que cela ne dit rien sur la compression. Je peux créer une image .jpg et régler sa compression à un niveau très élevé. Par exemple, disons que je souhaite créé une maison. A l'intérieur de la maison il y a une table et je décide de mettre cette texture de bois sur la surface supérieure de la table
<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>Cette image ne pèse que 157ko, elle sera donc téléchargée relativement vite mais [sa taill est en réalité de 3024 x 3761 pixels](resources/images/compressed-but-large-wood-texture.jpg).
<add>En suivant l'équation ci-dessous
<add>
<add> 3024 * 3761 * 4 * 1.33 = 60505764.5
<add>
<add>Cette image prendra **60 MEGA de MEMOIRE!** dans Three.js.
<add>Encore quelques textures comme celle-la et vous serez à court de mémoire.
<add>
<add>J'en parle car il est important de savoir que l'utilisation de textures a un coût caché. Pour que Three.js utilise la texture, il doit la transmettre au GPU et le GPU *en général* nécessite que les données de texture soient décompressées.
<add>
<add>La morale de l'histoire, c'est d'utiliser des textures de petite taille, pas seulement petite en taille de fichier. Petit en taille de fichier = rapide à télécharger. Petit en dimensions = prend moins de mémoire. Quelle est la bonne taille ? Aussi petite que possible et toujours aussi belle que nécessaire.
<add>
<add>## <a name="format"></a> JPG ou PNG
<add>
<add>C'est à peu près la même chose qu'en HTML, en ce sens que les JPG ont une compression avec perte, les PNG ont une compression sans perte, donc les PNG sont généralement plus lents à télécharger. Mais, les PNG prennent en charge la transparence. Les PNG sont aussi probablement le format approprié pour les données non-image comme les normal maps, et d'autres types de map non-image que nous verrons plus tard.
<add>
<add>Il est important de se rappeler qu'un JPG n'utilise pas moins de mémoire qu'un PNG en WebGL. Voir au ci-dessus.
<add>
<add>## <a name="filtering-and-mips"></a> Filtrage et Mips
<add>
<add>Appliquons cette texture 16x16
<add>
<add><div class="threejs_center"><img src="resources/images/mip-low-res-enlarged.png" class="nobg" align="center"></div>
<add>
<add>sur un cube
<add>
<add><div class="spread"><div data-diagram="filterCube"></div></div>
<add>
<add>Rétrécissons-le au max
<add>
<add><div class="spread"><div data-diagram="filterCubeSmall"></div></div>
<add>
<add>Hmmm, je suppose que c'est trop difficile à voir. Agrandissons-le un peu
<add>
<add><div class="spread"><div data-diagram="filterCubeSmallLowRes"></div></div>
<add>
<add>Comment le GPU sait-il quelles couleurs créer pour chaque pixel qu'il dessine pour le petit cube ? Et si le cube était si petit qu'il ne faisait que 1 ou 2 pixels ?
<add>
<add>C'est à cela que sert le filtrage.
<add>
<add>S'il s'agissait de Photoshop, il ferait la moyenne de presque tous les pixels ensemble pour déterminer la couleur de ces 1 ou 2 pixels. Ce serait une opération très lente. Les GPU résolvent ce problème à l'aide de mipmaps.
<add>
<add>Le MIP mapping consiste à envoyer au processeur graphique (GPU) des échantillons de texture de résolutions décroissantes qui seront utilisés à la place de la texture originale, en fonction de la distance du point de vue à l'objet texturé et du niveau de détails nécessaire. Pour l'image précédente seront produites les mêmes images avec des résolutions inférieure jusqu'à obtenir 1 x 1 pixel.
<add>
<add><div class="threejs_center"><img src="resources/images/mipmap-low-res-enlarged.png" class="nobg" align="center"></div>
<add>
<add>Désormais, lorsque le cube est dessiné si petit qu'il ne fait que 1 ou 2 pixels de large, le GPU peut choisir d'utiliser uniquement le plus petit ou le plus petit niveau de mip pour décider de la couleur du petit cube.
<add>
<add>Dans Three.js, vous pouvez choisir ce qui se passe à la fois lorsque la texture est dessinée plus grande que sa taille d'origine et ce qui se passe lorsqu'elle est dessinée plus petite que sa taille d'origine.
<add>
<add>Pour définir le filtre lorsque la texture est dessinée plus grande que sa taille d'origine, définissez la propriété [`texture.magFilter`](Texture.magFilter) sur `THREE.NearestFilter` ou
<add> `THREE.LinearFilter`. `NearestFilter` signifie simplement choisir le pixel le plus proche dans la texture d'origine. Avec une texture basse résolution, cela vous donne un look très pixelisé comme Minecraft.
<add>
<add>`LinearFilter` signifie choisir les 4 pixels de la texture qui sont les plus proches de l'endroit où nous devrions choisir une couleur et les mélanger dans les proportions appropriées par rapport à la distance entre le point réel et chacun des 4 pixels.
<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>Pour définir le filtre lorsque la texture est dessinée plus petite que sa taille d'origine, définissez la propriété [`texture.minFilter`](Texture.minFilter) sur l'une des 6 valeurs :
<add>
<add>* `THREE.NearestFilter`
<add>
<add> comme ci-dessus, choisissez le pixel le plus proche dans la texture
<add>
<add>* `THREE.LinearFilter`
<add>
<add> comme ci-dessus, choisissez 4 pixels dans la texture et mélangez-les
<add>
<add>* `THREE.NearestMipmapNearestFilter`
<add>
<add> choisissez le mip approprié puis choisissez un pixe
<add>
<add>* `THREE.NearestMipmapLinearFilter`
<add>
<add> choisissez 2 mips, choisissez un pixel de chacun, mélangez les 2 pixels
<add>
<add>* `THREE.LinearMipmapNearestFilter`
<add>
<add> choisissez le mip approprié puis choisissez 4 pixels et mélangez-les
<add>
<add>* `THREE.LinearMipmapLinearFilter`
<add>
<add> choisissez 2 mips, choisissez 4 pixels de chacun et mélangez les 8 en 1 pixel
<add>
<add>Voici un exemple montrant les 6 paramètres
<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>Une chose à noter est que la texture en haut/gauche et la haut/milieu utilisent NearestFilter et LinearFilter et pas les mips. À cause de cela, ils scintillent au loin car le GPU sélectionne les pixels de la texture d'origine. Sur la gauche, un seul pixel est choisi et au milieu, 4 sont choisis et mélangés, mais il ne suffit pas de proposer une bonne couleur représentative. Les 4 autres bandes font mieux avec le bas à droite, LinearMipmapLinearFilter étant le meilleur.
<add>
<add>Si vous cliquez sur l'image ci-dessus, elle basculera entre la texture que nous avons utilisée ci-dessus et une texture où chaque niveau de mip est d'une couleur différente.
<add>
<add><div class="threejs_center">
<add> <div data-texture-diagram="differentColoredMips"></div>
<add></div>
<add>
<add>Cela clarifie les choses. Vous pouvez voir en haut à gauche et en haut au milieu que le premier mip est utilisé au loin. En haut à droite et en bas au milieu, vous pouvez clairement voir où un MIP différent est utilisé.
<add>
<add>En revenant à la texture d'origine, vous pouvez voir que celle en bas à droite est la plus douce et la plus haute qualité. Vous pourriez vous demander pourquoi ne pas toujours utiliser ce mode. La raison la plus évidente, c'est que parfois vous voulez que les choses soient pixelisées pour un look rétro ou pour une autre raison. La deuxième raison la plus courante, c' est que lire 8 pixels et les mélanger est plus lent que lire 1 pixel et mélanger. Bien qu'il soit peu probable qu'une seule texture fasse la différence entre rapide et lente à mesure que nous progressons dans ces articles, nous finirons par avoir des matériaux qui utilisent 4 ou 5 textures à la fois. 4 textures * 8 pixels par texture se transforment 32 pixels pour chaque pixel rendu. Cela peut être particulièrement important à considérer sur les appareils mobiles.
<add>
<add>## <a name="uvmanipulation"></a> Répétition, décalage, rotation, emballage d'une texture
<add>
<add>Les textures ont des paramètres pour la répétition, le décalage et la rotation d'une texture.
<add>
<add>Par défaut, les textures de three.js ne se répètent pas. Pour définir si une texture se répète ou non, il existe 2 propriétés, [`wrapS`](Texture.wrapS) pour un habillage horizontal et [`wrapT`](Texture.wrapT) pour un habillage vertical.
<add>
<add>Ils peuvent être définis sur l'un des éléments suivants :
<add>
<add>* `THREE.ClampToEdgeWrapping`
<add>
<add> le dernier pixel de chaque bord est répété indéfiniment
<add>
<add>* `THREE.RepeatWrapping`
<add>
<add> la texture est répétée
<add>
<add>* `THREE.MirroredRepeatWrapping`
<add>
<add> la texture est reflétée et répétée
<add>
<add>Par exemple pour activer le wrapping dans les deux sens :
<add>
<add>```js
<add>someTexture.wrapS = THREE.RepeatWrapping;
<add>someTexture.wrapT = THREE.RepeatWrapping;
<add>```
<add>
<add>La répétition est définie avec la propriété [repeat].
<add>
<add>```js
<add>const timesToRepeatHorizontally = 4;
<add>const timesToRepeatVertically = 2;
<add>someTexture.repeat.set(timesToRepeatHorizontally, timesToRepeatVertically);
<add>```
<add>
<add>Le décalage de la texture peut être effectué en définissant la propriété `offset`. Les textures sont décalées avec des unités où 1 unité = 1 taille de texture. En d'autres termes 0 = aucun décalage et 1 = décalage d'une quantité de texture complète.
<add>
<add>```js
<add>const xOffset = .5; // décalage de la moitié de la texture
<add>const yOffset = .25; // décalage d'un quart
<add>someTexture.offset.set(xOffset, yOffset);
<add>```
<add>
<add>La rotation de la texture peut être définie en définissant la propriété `rotation` en radians ainsi que la propriété `center` pour choisir le centre de rotation. La valeur par défaut est 0,0 qui tourne à partir du coin inférieur gauche. Comme le décalage, ces unités ont une taille de texture, donc les régler sur `.5, .5` tournerait autour du centre de la texture.
<add>
<add>```js
<add>someTexture.center.set(.5, .5);
<add>someTexture.rotation = THREE.MathUtils.degToRad(45);
<add>```
<add>
<add>Modifions l'échantillon supérieur ci-dessus pour jouer avec ces valeurs.
<add>
<add>Tout d'abord, nous allons garder une référence à la texture afin que nous puissions la manipuler
<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>Ensuite, utilisons [dat.GUI](https://github.com/dataarts/dat.gui) pour fournir une interface simple.
<add>
<add>```js
<add>import {GUI} from '../3rdparty/dat.gui.module.js';
<add>```
<add>
<add>Comme nous l'avons fait dans les exemples précédents avec dat.GUI, nous utiliserons une classe simple pour donner à dat.GUI un objet qu'il peut manipuler en degrés mais qu'il définira en radians.
<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>Nous avons également besoin d'une classe qui convertira une chaîne telle que `"123"` en un nombre tel que 123, car Three.js nécessite des nombres pour les paramètres d'énumération tels que `wrapS` et `wrapT`, mais dat.GUI n'utilise que des chaînes pour les énumérations.
<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>En utilisant ces classes, nous pouvons configurer une interface graphique simple pour les paramètres ci-dessus
<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>La dernière chose à noter à propos de l'exemple est que si vous modifiez `wrapS` ou `wrapT` sur la texture, vous devez également définir [`texture.needsUpdate`](Texture.needsUpdate)
<add>afin que three.js sache appliquer ces paramètres. Les autres paramètres sont automatiquement appliqués.
<add>
<add>{{{example url="../threejs-textured-cube-adjust.html" }}}
<add>
<add>Ce n'est qu'une étape dans le sujet des textures. À un moment donné, nous passerons en revue les coordonnées de texture ainsi que 9 autres types de textures pouvant être appliquées aux matériaux.
<add>
<add>Pour le moment, passons aux [lumières](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
|
Ruby
|
Ruby
|
run `brew style`
|
8a4f26f9522522ea938e79cb9e4651968f50045f
|
<ide><path>Library/Homebrew/dev-cmd/test-bot.rb
<ide> def homebrew
<ide> test "brew", "update-test", "--commit=HEAD"
<ide> end
<ide>
<add> test "brew", "style"
<ide> test "brew", "readall", "--syntax"
<ide>
<ide> coverage_args = []
<ide> def homebrew
<ide> test "brew", "cask-tests", *coverage_args
<ide> end
<ide> elsif @tap
<add> if @tap.name == "homebrew/core"
<add> test "brew", "style", @tap.name
<add> end
<ide> test "brew", "readall", "--aliases", @tap.name
<ide> end
<ide> end
| 1
|
Ruby
|
Ruby
|
fix some doublethink in the xcode module
|
de1eabf22c0137e4e0ad8c34cc47fd86cb78e557
|
<ide><path>Library/Homebrew/macos/xcode.rb
<ide> def prefix
<ide> end
<ide>
<ide> def installed?
<del> # Telling us whether the Xcode.app is installed or not.
<del> @installed ||= V4_BUNDLE_PATH.exist? ||
<del> V3_BUNDLE_PATH.exist? ||
<del> MacOS.app_with_bundle_id(V4_BUNDLE_ID) ||
<del> MacOS.app_with_bundle_id(V3_BUNDLE_ID) ||
<del> false
<add> not prefix.nil?
<ide> end
<ide>
<ide> def version
| 1
|
Ruby
|
Ruby
|
implement linkage repair
|
d44290571931b5c83934b31d97b58b8e2bc32c06
|
<ide><path>Library/Homebrew/cmd/reinstall.rb
<ide> require "formula_installer"
<ide> require "development_tools"
<ide> require "messages"
<add>require "reinstall"
<ide>
<ide> module Homebrew
<ide> module_function
<ide> def reinstall
<ide> end
<ide> Homebrew.messages.display_messages
<ide> end
<del>
<del> def reinstall_formula(f)
<del> if f.opt_prefix.directory?
<del> keg = Keg.new(f.opt_prefix.resolved_path)
<del> keg_had_linked_opt = true
<del> keg_was_linked = keg.linked?
<del> backup keg
<del> end
<del>
<del> build_options = BuildOptions.new(Options.create(ARGV.flags_only), f.options)
<del> options = build_options.used_options
<del> options |= f.build.used_options
<del> options &= f.options
<del>
<del> fi = FormulaInstaller.new(f)
<del> fi.options = options
<del> fi.invalid_option_names = build_options.invalid_option_names
<del> fi.build_bottle = ARGV.build_bottle? || (!f.bottled? && f.build.bottle?)
<del> fi.interactive = ARGV.interactive?
<del> fi.git = ARGV.git?
<del> fi.link_keg ||= keg_was_linked if keg_had_linked_opt
<del> fi.prelude
<del>
<del> oh1 "Reinstalling #{Formatter.identifier(f.full_name)} #{options.to_a.join " "}"
<del>
<del> fi.install
<del> fi.finish
<del> rescue FormulaInstallationAlreadyAttemptedError
<del> nil
<del> rescue Exception # rubocop:disable Lint/RescueException
<del> ignore_interrupts { restore_backup(keg, keg_was_linked) }
<del> raise
<del> else
<del> backup_path(keg).rmtree if backup_path(keg).exist?
<del> end
<del>
<del> def backup(keg)
<del> keg.unlink
<del> keg.rename backup_path(keg)
<del> end
<del>
<del> def restore_backup(keg, keg_was_linked)
<del> path = backup_path(keg)
<del>
<del> return unless path.directory?
<del>
<del> Pathname.new(keg).rmtree if keg.exist?
<del>
<del> path.rename keg
<del> keg.link if keg_was_linked
<del> end
<del>
<del> def backup_path(path)
<del> Pathname.new "#{path}.reinstall"
<del> end
<ide> end
<ide><path>Library/Homebrew/cmd/upgrade.rb
<ide> #: are pinned; see `pin`, `unpin`).
<ide>
<ide> require "install"
<add>require "reinstall"
<ide> require "formula_installer"
<ide> require "cleanup"
<ide> require "development_tools"
<ide> def upgrade
<ide> puts formulae_upgrades.join(", ")
<ide> end
<ide>
<add> upgrade_formulae(formulae_to_install)
<add>
<add> check_dependents(formulae_to_install)
<add>
<add> Homebrew.messages.display_messages
<add> end
<add>
<add> def upgrade_formulae(formulae_to_install)
<add> return if formulae_to_install.empty?
<add>
<ide> # Sort keg_only before non-keg_only formulae to avoid any needless conflicts
<ide> # with outdated, non-keg_only versions of formulae being upgraded.
<ide> formulae_to_install.sort! do |a, b|
<ide> def upgrade
<ide> onoe "#{f}: #{e}"
<ide> end
<ide> end
<del> Homebrew.messages.display_messages
<ide> end
<ide>
<ide> def upgrade_formula(f)
<ide> def upgrade_formula(f)
<ide> nil
<ide> end
<ide> end
<add>
<add> def upgradable_dependents(kegs, formulae)
<add> formulae_to_upgrade = Set.new
<add> formulae_pinned = Set.new
<add>
<add> formulae.each do |formula|
<add> descendants = Set.new
<add>
<add> dependents = kegs.select do |keg|
<add> keg.runtime_dependencies
<add> .any? { |d| d["full_name"] == formula.full_name }
<add> end
<add>
<add> next if dependents.empty?
<add>
<add> dependent_formulae = dependents.map(&:to_formula)
<add>
<add> dependent_formulae.each do |f|
<add> next if formulae_to_upgrade.include?(f)
<add> next if formulae_pinned.include?(f)
<add>
<add> if f.outdated?(fetch_head: ARGV.fetch_head?)
<add> if f.pinned?
<add> formulae_pinned << f
<add> else
<add> formulae_to_upgrade << f
<add> end
<add> end
<add>
<add> descendants << f
<add> end
<add>
<add> upgradable_descendants, pinned_descendants = upgradable_dependents(kegs, descendants)
<add>
<add> formulae_to_upgrade.merge upgradable_descendants
<add> formulae_pinned.merge pinned_descendants
<add> end
<add>
<add> [formulae_to_upgrade, formulae_pinned]
<add> end
<add>
<add> def broken_dependents(kegs, formulae)
<add> formulae_to_reinstall = Set.new
<add> formulae_pinned_and_outdated = Set.new
<add>
<add> CacheStoreDatabase.use(:linkage) do |db|
<add> formulae.each do |formula|
<add> descendants = Set.new
<add>
<add> dependents = kegs.select do |keg|
<add> keg.runtime_dependencies
<add> .any? { |d| d["full_name"] == formula.full_name }
<add> end
<add>
<add> next if dependents.empty?
<add>
<add> dependents.each do |keg|
<add> f = keg.to_formula
<add>
<add> next if formulae_to_reinstall.include?(f)
<add> next if formulae_pinned_and_outdated.include?(f)
<add>
<add> checker = LinkageChecker.new(keg, cache_db: db)
<add>
<add> if checker.broken_library_linkage?
<add> if f.outdated?(fetch_head: ARGV.fetch_head?)
<add> # Outdated formulae = pinned formulae (see function above)
<add> formulae_pinned_and_outdated << f
<add> else
<add> formulae_to_reinstall << f
<add> end
<add> end
<add>
<add> descendants << f
<add> end
<add>
<add> descendants_to_reinstall, descendants_pinned = broken_dependents(kegs, descendants)
<add>
<add> formulae_to_reinstall.merge descendants_to_reinstall
<add> formulae_pinned_and_outdated.merge descendants_pinned
<add> end
<add> end
<add>
<add> [formulae_to_reinstall, formulae_pinned_and_outdated]
<add> end
<add>
<add> # @private
<add> def depends_on(a, b)
<add> if a.opt_or_installed_prefix_keg
<add> .runtime_dependencies
<add> .any? { |d| d["full_name"] == b.full_name }
<add> 1
<add> else
<add> a <=> b
<add> end
<add> end
<add>
<add> # @private
<add> def formulae_with_runtime_dependencies
<add> Formula.installed
<add> .map(&:opt_or_installed_prefix_keg)
<add> .reject(&:nil?)
<add> .reject { |f| f.runtime_dependencies.to_a.empty? }
<add> end
<add>
<add> def check_dependents(formulae)
<add> return if formulae.empty?
<add>
<add> # First find all the outdated dependents.
<add> kegs = formulae_with_runtime_dependencies
<add>
<add> return if kegs.empty?
<add>
<add> oh1 "Checking dependents for outdated formulae" if ARGV.verbose?
<add> upgradable, pinned = upgradable_dependents(kegs, formulae).map(&:to_a)
<add>
<add> upgradable.sort! { |a, b| depends_on(a, b) }
<add>
<add> pinned.sort! { |a, b| depends_on(a, b) }
<add>
<add> # Print the pinned dependents.
<add> unless pinned.empty?
<add> ohai "Not upgrading #{Formatter.pluralize(pinned.length, "pinned dependent")}:"
<add> puts pinned.map { |f| "#{f.full_specified_name} #{f.pkg_version}" } * ", "
<add> end
<add>
<add> # Print the upgradable dependents.
<add> if upgradable.empty?
<add> ohai "No dependents to upgrade" if ARGV.verbose?
<add> else
<add> ohai "Upgrading #{Formatter.pluralize(upgradable.length, "dependent")}:"
<add> formulae_upgrades = upgradable.map do |f|
<add> if f.optlinked?
<add> "#{f.full_specified_name} #{Keg.new(f.opt_prefix).version} -> #{f.pkg_version}"
<add> else
<add> "#{f.full_specified_name} #{f.pkg_version}"
<add> end
<add> end
<add> puts formulae_upgrades.join(", ")
<add> end
<add>
<add> upgrade_formulae(upgradable)
<add>
<add> # Assess the dependents tree again.
<add> kegs = formulae_with_runtime_dependencies
<add>
<add> oh1 "Checking dependents for broken library links" if ARGV.verbose?
<add> reinstallable, pinned = broken_dependents(kegs, formulae).map(&:to_a)
<add>
<add> reinstallable.sort! { |a, b| depends_on(a, b) }
<add>
<add> pinned.sort! { |a, b| depends_on(a, b) }
<add>
<add> # Print the pinned dependents.
<add> unless pinned.empty?
<add> onoe "Not reinstalling #{Formatter.pluralize(pinned.length, "broken and outdated, but pinned dependent")}:"
<add> $stderr.puts pinned.map { |f| "#{f.full_specified_name} #{f.pkg_version}" } * ", "
<add> end
<add>
<add> # Print the broken dependents.
<add> if reinstallable.empty?
<add> ohai "No broken dependents to reinstall" if ARGV.verbose?
<add> else
<add> ohai "Reinstalling #{Formatter.pluralize(reinstallable.length, "broken dependent")} from source:"
<add> puts reinstallable.map(&:full_specified_name).join(", ")
<add> end
<add>
<add> reinstallable.each do |f|
<add> begin
<add> reinstall_formula(f, build_from_source: true)
<add> rescue FormulaInstallationAlreadyAttemptedError
<add> # We already attempted to reinstall f as part of the dependency tree of
<add> # another formula. In that case, don't generate an error, just move on.
<add> nil
<add> rescue CannotInstallFormulaError => e
<add> ofail e
<add> rescue BuildError => e
<add> e.dump
<add> puts
<add> Homebrew.failed = true
<add> rescue DownloadError => e
<add> ofail e
<add> end
<add> end
<add> end
<ide> end
<ide><path>Library/Homebrew/reinstall.rb
<add>require "formula_installer"
<add>require "development_tools"
<add>require "messages"
<add>
<add>module Homebrew
<add> module_function
<add>
<add> def reinstall_formula(f, build_from_source: false)
<add> if f.opt_prefix.directory?
<add> keg = Keg.new(f.opt_prefix.resolved_path)
<add> keg_had_linked_opt = true
<add> keg_was_linked = keg.linked?
<add> backup keg
<add> end
<add>
<add> build_options = BuildOptions.new(Options.create(ARGV.flags_only), f.options)
<add> options = build_options.used_options
<add> options |= f.build.used_options
<add> options &= f.options
<add>
<add> fi = FormulaInstaller.new(f)
<add> fi.options = options
<add> fi.invalid_option_names = build_options.invalid_option_names
<add> fi.build_bottle = ARGV.build_bottle? || (!f.bottled? && f.build.bottle?)
<add> fi.interactive = ARGV.interactive?
<add> fi.git = ARGV.git?
<add> fi.link_keg ||= keg_was_linked if keg_had_linked_opt
<add> fi.build_from_source = true if build_from_source
<add> fi.prelude
<add>
<add> oh1 "Reinstalling #{Formatter.identifier(f.full_name)} #{options.to_a.join " "}"
<add>
<add> fi.install
<add> fi.finish
<add> rescue FormulaInstallationAlreadyAttemptedError
<add> nil
<add> rescue Exception # rubocop:disable Lint/RescueException
<add> ignore_interrupts { restore_backup(keg, keg_was_linked) }
<add> raise
<add> else
<add> backup_path(keg).rmtree if backup_path(keg).exist?
<add> end
<add>
<add> def backup(keg)
<add> keg.unlink
<add> keg.rename backup_path(keg)
<add> end
<add>
<add> def restore_backup(keg, keg_was_linked)
<add> path = backup_path(keg)
<add>
<add> return unless path.directory?
<add>
<add> Pathname.new(keg).rmtree if keg.exist?
<add>
<add> path.rename keg
<add> keg.link if keg_was_linked
<add> end
<add>
<add> def backup_path(path)
<add> Pathname.new "#{path}.reinstall"
<add> end
<add>end
<ide><path>Library/Homebrew/test/cmd/upgrade_spec.rb
<ide>
<ide> expect(HOMEBREW_CELLAR/"testball/0.1").to be_a_directory
<ide> end
<add>
<add> it "upgrades a Formula and cleans up old versions" do
<add> setup_test_formula "testball"
<add> (HOMEBREW_CELLAR/"testball/0.0.1/foo").mkpath
<add>
<add> expect { brew "upgrade", "--cleanup" }.to be_a_success
<add>
<add> expect(HOMEBREW_CELLAR/"testball/0.1").to be_a_directory
<add> expect(HOMEBREW_CELLAR/"testball/0.0.1").not_to exist
<add> end
<ide> end
| 4
|
Ruby
|
Ruby
|
set resource version when missing
|
85f424b270e32d43b1695727ab621c274bb5166a
|
<ide><path>Library/Homebrew/software_spec.rb
<ide> def initialize
<ide> def owner= owner
<ide> @name = owner.name
<ide> @resource.owner = self
<del> resources.each_value { |r| r.owner = self }
<add> resources.each_value do |r|
<add> r.owner = self
<add> r.version ||= version
<add> end
<ide> end
<ide>
<ide> def url val=nil, specs={}
| 1
|
Go
|
Go
|
implement docker tag with standalone client lib
|
21ffdf0e0e402cfc00f2bb1476fb2a8510418ec0
|
<ide><path>api/client/lib/image_tag.go
<add>package lib
<add>
<add>import "net/url"
<add>
<add>// ImageTagOptions hold parameters to tag an image
<add>type ImageTagOptions struct {
<add> ImageID string
<add> RepositoryName string
<add> Tag string
<add> Force bool
<add>}
<add>
<add>// ImageTag tags an image in the docker host
<add>func (cli *Client) ImageTag(options types.ImageTagOptions) error {
<add> query := url.Values{}
<add> query.Set("repo", options.RepositoryName)
<add> query.Set("tag", options.Tag)
<add> if options.Force {
<add> query.Set("force", "1")
<add> }
<add>
<add> resp, err := cli.POST("/images/"+options.ImageID+"/tag", query, nil, nil)
<add> ensureReaderClosed(resp)
<add> return err
<add>}
<ide><path>api/client/tag.go
<ide> package client
<ide>
<ide> import (
<ide> "errors"
<del> "net/url"
<ide>
<ide> "github.com/docker/distribution/reference"
<add> "github.com/docker/docker/api/client/lib"
<ide> Cli "github.com/docker/docker/cli"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/registry"
<ide> func (cli *DockerCli) CmdTag(args ...string) error {
<ide>
<ide> cmd.ParseFlags(args, true)
<ide>
<del> v := url.Values{}
<ide> ref, err := reference.ParseNamed(cmd.Arg(1))
<ide> if err != nil {
<ide> return err
<ide> func (cli *DockerCli) CmdTag(args ...string) error {
<ide> if err := registry.ValidateRepositoryName(ref); err != nil {
<ide> return err
<ide> }
<del> v.Set("repo", ref.Name())
<del> v.Set("tag", tag)
<ide>
<del> if *force {
<del> v.Set("force", "1")
<add> options := lib.ImageTagOptions{
<add> ImageID: cmd.Arg(0),
<add> RepositoryName: ref.Name(),
<add> Tag: tag,
<add> Force: *force,
<ide> }
<ide>
<del> if _, _, err := readBody(cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil, nil)); err != nil {
<del> return err
<del> }
<del> return nil
<add> return cli.client.ImageTag(options)
<ide> }
| 2
|
Go
|
Go
|
use spf13/cobra for docker tag
|
ba7324ffcb23ba314fbab335a816004c4af7f3f3
|
<ide><path>api/client/commands.go
<ide> func (cli *DockerCli) Command(name string) func(...string) error {
<ide> "rm": cli.CmdRm,
<ide> "save": cli.CmdSave,
<ide> "stats": cli.CmdStats,
<del> "tag": cli.CmdTag,
<ide> "update": cli.CmdUpdate,
<ide> "version": cli.CmdVersion,
<ide> }[name]
<ide><path>api/client/image/tag.go
<add>package image
<add>
<add>import (
<add> "golang.org/x/net/context"
<add>
<add> "github.com/docker/docker/api/client"
<add> "github.com/docker/docker/cli"
<add> "github.com/spf13/cobra"
<add>)
<add>
<add>type tagOptions struct {
<add> image string
<add> name string
<add>}
<add>
<add>// NewTagCommand create a new `docker tag` command
<add>func NewTagCommand(dockerCli *client.DockerCli) *cobra.Command {
<add> var opts tagOptions
<add>
<add> cmd := &cobra.Command{
<add> Use: "tag IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG]",
<add> Short: "Tag an image into a repository",
<add> Args: cli.ExactArgs(2),
<add> RunE: func(cmd *cobra.Command, args []string) error {
<add> opts.image = args[0]
<add> opts.name = args[1]
<add> return runTag(dockerCli, opts)
<add> },
<add> }
<add>
<add> flags := cmd.Flags()
<add> flags.SetInterspersed(false)
<add>
<add> return cmd
<add>}
<add>
<add>func runTag(dockerCli *client.DockerCli, opts tagOptions) error {
<add> ctx := context.Background()
<add>
<add> return dockerCli.Client().ImageTag(ctx, opts.image, opts.name)
<add>}
<ide><path>api/client/tag.go
<del>package client
<del>
<del>import (
<del> "golang.org/x/net/context"
<del>
<del> Cli "github.com/docker/docker/cli"
<del> flag "github.com/docker/docker/pkg/mflag"
<del>)
<del>
<del>// CmdTag tags an image into a repository.
<del>//
<del>// Usage: docker tag [OPTIONS] IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG]
<del>func (cli *DockerCli) CmdTag(args ...string) error {
<del> cmd := Cli.Subcmd("tag", []string{"IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG]"}, Cli.DockerCommands["tag"].Description, true)
<del> cmd.Require(flag.Exact, 2)
<del>
<del> cmd.ParseFlags(args, true)
<del>
<del> return cli.client.ImageTag(context.Background(), cmd.Arg(0), cmd.Arg(1))
<del>}
<ide><path>cli/cobraadaptor/adaptor.go
<ide> func NewCobraAdaptor(clientFlags *cliflags.ClientFlags) CobraAdaptor {
<ide> image.NewRemoveCommand(dockerCli),
<ide> image.NewSearchCommand(dockerCli),
<ide> image.NewImportCommand(dockerCli),
<add> image.NewTagCommand(dockerCli),
<ide> network.NewNetworkCommand(dockerCli),
<ide> volume.NewVolumeCommand(dockerCli),
<ide> )
<ide><path>cli/usage.go
<ide> var DockerCommandUsage = []Command{
<ide> {"rm", "Remove one or more containers"},
<ide> {"save", "Save one or more images to a tar archive"},
<ide> {"stats", "Display a live stream of container(s) resource usage statistics"},
<del> {"tag", "Tag an image into a repository"},
<ide> {"update", "Update configuration of one or more containers"},
<ide> {"version", "Show the Docker version information"},
<ide> }
| 5
|
Javascript
|
Javascript
|
move param tag outside of main description
|
cddd48fe207257080ed23837dd334e1bf7aceaea
|
<ide><path>src/ng/directive/form.js
<ide> function FormController(element, attrs, $scope, $animate) {
<ide> * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
<ide> * to have access to the updated model.
<ide> *
<del> * @param {string=} name Name of the form. If specified, the form controller will be published into
<del> * related scope, under this name.
<del> *
<ide> * ## Animation Hooks
<ide> *
<ide> * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
<ide> function FormController(element, attrs, $scope, $animate) {
<ide> </file>
<ide> </example>
<ide> *
<add> * @param {string=} name Name of the form. If specified, the form controller will be published into
<add> * related scope, under this name.
<ide> */
<ide> var formDirectiveFactory = function(isNgForm) {
<ide> return ['$timeout', function($timeout) {
| 1
|
Text
|
Text
|
add initial doc for contributing to packages
|
459c11b602611021d6ba0f29cee3a64871297655
|
<ide><path>docs/contributing.md
<add># Contributing to Atom Packages
<add>
<add>The following is a set of guidelines for contributing to Atom packages, which
<add>are hosted in the [Atom Organization](https://github.com/atom) on GitHub. If
<add>you're unsure which package is causing your problem or if you're having an issue
<add>with Atom core, please use the feedback form in the application or email
<add>[atom@github.com](mailto:atom@github.com).
<add>
<add>## Submitting Issues
<add>
<add>* Include screenshots and animated GIFs whenever possible; they are immensely
<add> helpful.
<add>* Include the behavior you expected and other places you've seen that behavior
<add> such as Emacs, vi, Xcode, etc.
<add>* Check the dev tools (`alt-cmd-i`) for errors and stack traces to include.
<add>* Check Console.app for stack traces to include if reporting a crash.
<add>* Perform a cursory search to see if a similar issue has already been submitted.
<add>
<add>## Hacking on Packages
<add>
<add>### Cloning
<add>
<add>The first step is creating your own clone. You can of course do this manually
<add>with git, or you can use the `apm develop` command to create a clone based on
<add>the package's `repository` field in the `package.json`.
<add>
<add>For example, if you want to make changes to the `tree-view` package, run the
<add>following command:
<add>
<add>```
<add>> apm develop tree-view
<add>Cloning https://github.com/atom/tree-view ✓
<add>Installing modules ✓
<add>~/.atom/dev/packages/tree-view -> ~/github/tree-view
<add>```
<add>
<add>### Running in Development Mode
<add>
<add>Editing a package in Atom is a bit of a circular experience: you're using Atom
<add>to modify itself. What happens if you temporarily break something? You don't
<add>want the version of Atom you're using to edit to become useless in the process.
<add>For this reason, you'll only want to load packages in **development mode** while
<add>you are working on them. You'll perform your editing in **stable mode**, only
<add>switching to development mode to test your changes.
<add>
<add>To open a development mode window, use the "Application: Open Dev" command,
<add>which is normally bound to `cmd-shift-o`. You can also run dev mode from the
<add>command line with `atom -d`.
<add>
<add>To load your package in development mode, create a symlink to it in
<add>`~/.atom/dev/packages`. This occurs automatically when you clone the package
<add>with `apm develop`. You can also run `apm link -d` and `apm unlink -d` from the
<add>package directory to create and remove dev-mode symlinks.
<add>
<add>### Installing Dependencies
<add>
<add>Finally, you need to install the cloned package's dependencies by running
<add>`apm install` within the package directory. This step is also performed
<add>automatically the first time you run `apm develop`, but you'll want to keep
<add>dependencies up to date by running `apm update` after pulling upstream changes.
<add>
<add>## Submitting Pull Requests
<add>
<add>### Code Guidelines
<add>
<add>* Include screenshots and animated GIFs in your pull request whenever possible.
<add>* Follow the [CoffeeScript](#coffeescript-styleguide),
<add> [JavaScript](https://github.com/styleguide/javascript),
<add> and [CSS](https://github.com/styleguide/css) styleguides.
<add>* Include thoughtfully-worded, well-structured
<add> [Jasmine](http://pivotal.github.com/jasmine) specs.
<add>* Document new code based on the
<add> [Documentation Styleguide](#documentation-styleguide)
<add>* Avoid placing files in `vendor`. 3rd-party packages should be added as
<add> dependencies in `package.json`.
<add>* End files with a newline.
<add>* Place requires in the following order:
<add> * Built in Node Modules (such as `path`)
<add> * Built in Atom and Atom Shell Modules (such as `atom`, `shell`)
<add> * Local Modules (using relative paths)
<add>* Place class properties in the following order:
<add> * Class methods and properties (methods starting with a `@`)
<add> * Instance methods and properties
<add>* Avoid platform-dependent code:
<add> * Use `require('atom').fs.getHomeDirectory()` to get the home directory.
<add> * Use `path.join()` to concatenate filenames.
<add> * Use `os.tmpdir()` rather than `/tmp` when you need to reference the
<add> temporary directory.
<add>
<add>### Commit Message Guidelines
<add> * Use the present tense ("Add feature" not "Added feature")
<add> * Use the imperative mood ("Fix bug" not "Fixes bug")
<add> * Limit the first line to 72 characters or less
<add> * Reference issues and pull requests liberally
<add> * Consider starting the commit message with an applicable emoji:
<add> * :lipstick: when improving the format/structure of the code
<add> * :racehorse: when improving performance
<add> * :non-potable_water: when plugging memory leaks
<add> * :memo: when writing docs
<add>
<add>## CoffeeScript Styleguide
<add>
<add>* Use parentheses if it improves code clarity.
<add>* Prefer alphabetic keywords to symbolic keywords:
<add> * `a is b` instead of `a == b`
<add>* Avoid spaces inside the curly-braces of hash literals:
<add> * `{a: 1, b: 2}` instead of `{ a: 1, b: 2 }`
<add>* Set parameter defaults without spaces around the equal sign:
<add> * `clear = (count=1) ->` instead of `clear = (count = 1) ->`
<add>* Include a single line of whitespace between methods.
<add>
<add>## Documentation Styleguide
<add>
<add>* Use [TomDoc](http://tomdoc.org).
<add>* Use [Markdown](https://daringfireball.net/projects/markdown).
<add>* Reference classes with the custom `{ClassName}` notation.
<add>* Reference methods with the custom `{ClassName::methodName}` notation.
<add>
<add>### Example
<add>
<add>```coffee
<add># Public: Disable the package with the given name.
<add>#
<add># This method emits multiple events:
<add>#
<add># * `package-will-be-disabled` - before the package is disabled.
<add># * `package-disabled` - after the package is disabled.
<add>#
<add># name - The {String} name of the package to disable.
<add># options - The {Object} with disable options (default: {}):
<add># :trackTime - `true` to track the amount of time disabling took.
<add># :ignoreErrors - `true` to catch and ignore errors thrown.
<add># callback - The {Function} to call after the package has been disabled.
<add>#
<add># Returns `undefined`.
<add>disablePackage: (name, options, callback) ->
<add>```
| 1
|
Text
|
Text
|
switch case with same code for multiple values
|
597ba0b9beee9daaa32477f86af4b2afa24d9c9f
|
<ide><path>guide/english/c/switch/index.md
<ide> switch (n)
<ide> case constant2:
<ide> // code to be executed if n is equal to constant2;
<ide> break;
<add>
<add> case constant3:
<add> case constant4:
<add> // code to be executed if n is either equal to constant3 or constant4
<add> break;
<ide> .
<ide> .
<ide> .
<ide> int main() {
<ide> -> 12.4
<ide> -> 32.5 - 12.4 = 20.1
<ide> ```
<add>
<add>## Example
<add>
<add>The below code depicts how to handle switch case when single piece of code runs for multiple values.
<add>
<add>```c
<add>#include <stdio.h>
<add>
<add>int main()
<add>{
<add> for (int i=1; i<=4; i++) {
<add> switch (i) {
<add> case 1:
<add> printf("Hello World 1\n");
<add> break;
<add>
<add> case 2:
<add> case 3:
<add> printf("Hello World 2 or 3\n");
<add> break;
<add>
<add> case 4:
<add> printf("Hello World 4\n");
<add> break;
<add> }
<add> }
<add>
<add> return 0;
<add>}
<add>```
<add>
<add>## Output
<add>```c
<add>Hello World 1
<add>Hello World 2 or 3
<add>Hello World 2 or 3
<add>Hello World 4
<add>```
<add>
<add>
<ide> ## Nested Switch Case
<ide>
<ide> Like nested if, we can use nested switch case in C programming. A switch case statement enclosed inside another switch case statement is called nested switch case. Nested switch is used at high level where we require sub conditions or cases. The inner and outer switch() case constant may be same.
<ide> Enter first choice-t
<ide> Enter second choice-t
<ide> 2 Tails
<ide> ```
<del>
<add>
<add>
<ide> ## Review : Switch vs if else
<ide> * Check the Testing Expression: An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.
<ide> * Switch better for Multi way branching: When compiler compiles a switch statement, it will inspect each of the case constants and create a “jump table” that it will use for selecting the path of execution depending on the value of the expression. Therefore, if we need to select among a large group of values, a switch statement will run much faster than the equivalent logic coded using a sequence of if-elses. The compiler can do this because it knows that the case constants are all the same type and simply must be compared for equality with the switch expression, while in case of if expressions, the compiler has no such knowledge.
| 1
|
PHP
|
PHP
|
fix wording and remove trailing spaces
|
4ea6c158d1519677d4af6f2cf2d7f766d8efe2f8
|
<ide><path>lib/Cake/Model/Model.php
<ide> public function validates($options = array()) {
<ide>
<ide> /**
<ide> * Returns an array of fields that have failed the validation of the current model.
<del> *
<add> *
<ide> * Additionally it populates the validationErrors property of the model with the same array.
<ide> *
<ide> * @param string $options An optional array of custom options to be made available in the beforeValidate callback
<del> * @return array Array of invalid fields and its error messages
<del> *
<add> * @return array Array of invalid fields and their error messages
<ide> * @see Model::validates()
<ide> */
<ide> public function invalidFields($options = array()) {
| 1
|
Javascript
|
Javascript
|
fix hmr for reducers now that we use babel 6
|
803e7fd241744c90402be2c45b9c844da5a25a9f
|
<ide><path>examples/async/store/configureStore.js
<ide> export default function configureStore(initialState) {
<ide> if (module.hot) {
<ide> // Enable Webpack hot module replacement for reducers
<ide> module.hot.accept('../reducers', () => {
<del> const nextRootReducer = require('../reducers')
<add> const nextRootReducer = require('../reducers').default
<ide> store.replaceReducer(nextRootReducer)
<ide> })
<ide> }
<ide><path>examples/real-world/store/configureStore.dev.js
<ide> export default function configureStore(initialState) {
<ide> DevTools.instrument()
<ide> )
<ide> )
<del>
<add>
<ide> // Required for replaying actions from devtools to work
<ide> reduxRouterMiddleware.listenForReplays(store)
<del>
<add>
<ide> if (module.hot) {
<ide> // Enable Webpack hot module replacement for reducers
<ide> module.hot.accept('../reducers', () => {
<del> const nextRootReducer = require('../reducers')
<add> const nextRootReducer = require('../reducers').default
<ide> store.replaceReducer(nextRootReducer)
<ide> })
<ide> }
<ide><path>examples/todomvc/store/configureStore.js
<ide> export default function configureStore(initialState) {
<ide> if (module.hot) {
<ide> // Enable Webpack hot module replacement for reducers
<ide> module.hot.accept('../reducers', () => {
<del> const nextReducer = require('../reducers')
<add> const nextReducer = require('../reducers').default
<ide> store.replaceReducer(nextReducer)
<ide> })
<ide> }
<ide><path>examples/tree-view/store/configureStore.js
<ide> export default function configureStore(initialState) {
<ide> if (module.hot) {
<ide> // Enable Webpack hot module replacement for reducers
<ide> module.hot.accept('../reducers', () => {
<del> const nextReducer = require('../reducers')
<add> const nextReducer = require('../reducers').default
<ide> store.replaceReducer(nextReducer)
<ide> })
<ide> }
<ide><path>examples/universal/common/store/configureStore.js
<ide> export default function configureStore(initialState) {
<ide> if (module.hot) {
<ide> // Enable Webpack hot module replacement for reducers
<ide> module.hot.accept('../reducers', () => {
<del> const nextRootReducer = require('../reducers')
<add> const nextRootReducer = require('../reducers').default
<ide> store.replaceReducer(nextRootReducer)
<ide> })
<ide> }
| 5
|
Javascript
|
Javascript
|
add parsing of double sided extra effect elements
|
c49a2071502252156c890be191af8b03b7aaf319
|
<ide><path>examples/js/loaders/ColladaLoader.js
<ide> THREE.ColladaLoader.prototype = {
<ide> case 'technique':
<ide> data.technique = parseEffectTechnique( child );
<ide> break;
<add>
<add> case 'extra':
<add> data.extra = parseEffectExtra( child );
<add> break;
<ide>
<ide> }
<ide>
<ide> THREE.ColladaLoader.prototype = {
<ide> }
<ide>
<ide> }
<add>
<add> function parseEffectExtra( xml ) {
<add>
<add> var data = {};
<add>
<add> for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
<add>
<add> var child = xml.childNodes[ i ];
<add>
<add> if ( child.nodeType !== 1 ) continue;
<add>
<add> switch ( child.nodeName ) {
<add>
<add> case 'technique':
<add> data.technique = parseEffectExtraTechnique( child );
<add> break;
<add>
<add> }
<add>
<add> }
<add>
<add> return data;
<add>
<add> }
<add>
<add> function parseEffectExtraTechnique( xml ) {
<add>
<add> var data = {};
<add>
<add> for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
<add>
<add> var child = xml.childNodes[ i ];
<add>
<add> if ( child.nodeType !== 1 ) continue;
<add>
<add> switch ( child.nodeName ) {
<add>
<add> case 'double_sided':
<add> data[ child.nodeName ] = parseInt( child.textContent );
<add> break;
<add>
<add> }
<add>
<add> }
<add>
<add> return data;
<add>
<add> }
<ide>
<ide> function buildEffect( data ) {
<ide>
<ide> THREE.ColladaLoader.prototype = {
<ide>
<ide> var effect = getEffect( data.url );
<ide> var technique = effect.profile.technique;
<del>
<add> var extra = effect.profile.extra;
<add>
<ide> var material;
<ide>
<ide> switch ( technique.type ) {
<ide> THREE.ColladaLoader.prototype = {
<ide> }
<ide>
<ide> }
<add>
<add> if ( extra !== undefined && extra.technique !== undefined && isEmpty( extra.technique ) === false ) {
<add>
<add> if ( extra.technique.double_sided !== undefined ) {
<add>
<add> material.side = THREE.DoubleSide;
<add>
<add> }
<add>
<add> }
<ide>
<ide> return material;
<ide>
| 1
|
Go
|
Go
|
use https to get the latest docker version
|
734b4566df879c2c071a9785d69b2c9c51d76b06
|
<ide><path>utils/utils.go
<ide> func ParseHost(defaultHost string, defaultPort int, defaultUnix, addr string) (s
<ide> }
<ide>
<ide> func GetReleaseVersion() string {
<del> resp, err := http.Get("http://get.docker.io/latest")
<add> resp, err := http.Get("https://get.docker.io/latest")
<ide> if err != nil {
<ide> return ""
<ide> }
| 1
|
Javascript
|
Javascript
|
fix spaces to tabs
|
c0eeaedaa4225314c28f28ffe760600a0f9aeb67
|
<ide><path>examples/js/exporters/ColladaExporter.js
<ide> THREE.ColladaExporter.prototype = {
<ide>
<ide> type = 'constant';
<ide>
<del> if ( m.map !== null ) {
<add> if ( m.map !== null ) {
<ide>
<del> // The Collada spec does not support diffuse texture maps with the
<del> // constant shader type.
<del> // mrdoob/three.js#15469
<del> console.warn( 'ColladaExporter: Texture maps not supported with MeshBasicMaterial.' );
<add> // The Collada spec does not support diffuse texture maps with the
<add> // constant shader type.
<add> // mrdoob/three.js#15469
<add> console.warn( 'ColladaExporter: Texture maps not supported with MeshBasicMaterial.' );
<ide>
<del> }
<add> }
<ide>
<ide> }
<ide>
| 1
|
Mixed
|
Javascript
|
improve file insertion
|
538e7c787b75cbfba490eca5002e73405a647dc6
|
<ide><path>client/gatsby-node.js
<ide> exports.createPages = function createPages({ graphql, actions, reporter }) {
<ide> head
<ide> tail
<ide> history
<add> fileKey
<ide> }
<ide> solutions {
<ide> contents
<ide><path>client/src/templates/Challenges/rechallenge/builders.js
<del>import {
<del> cond,
<del> flow,
<del> identity,
<del> matchesProperty,
<del> partial,
<del> stubTrue,
<del> template as _template
<del>} from 'lodash-es';
<add>import { template as _template } from 'lodash-es';
<ide>
<del>import {
<del> compileHeadTail,
<del> setExt,
<del> transformContents
<del>} from '../../../../../utils/polyvinyl';
<del>
<del>const wrapInScript = partial(
<del> transformContents,
<del> content => `<script>${content}</script>`
<del>);
<del>const wrapInStyle = partial(
<del> transformContents,
<del> content => `<style>${content}</style>`
<del>);
<del>const setExtToHTML = partial(setExt, 'html');
<del>const concatHeadTail = partial(compileHeadTail, '');
<del>
<del>export const jsToHtml = cond([
<del> [
<del> matchesProperty('ext', 'js'),
<del> flow(concatHeadTail, wrapInScript, setExtToHTML)
<del> ],
<del> [stubTrue, identity]
<del>]);
<del>
<del>export const cssToHtml = cond([
<del> [
<del> matchesProperty('ext', 'css'),
<del> flow(concatHeadTail, wrapInStyle, setExtToHTML)
<del> ],
<del> [stubTrue, identity]
<del>]);
<del>
<del>export function findIndexHtml(challengeFiles) {
<del> const filtered = challengeFiles.filter(challengeFile =>
<del> wasHtmlFile(challengeFile)
<del> );
<del> if (filtered.length > 1) {
<del> throw new Error('Too many html blocks in the challenge seed');
<del> }
<del> return filtered[0];
<del>}
<del>
<del>function wasHtmlFile(challengeFile) {
<del> return challengeFile.history[0] === 'index.html';
<del>}
<del>
<del>export function concatHtml({
<del> required = [],
<del> template,
<del> challengeFiles = []
<del>} = {}) {
<add>export function concatHtml({ required = [], template, contents } = {}) {
<ide> const embedSource = template ? _template(template) : ({ source }) => source;
<ide> const head = required
<ide> .map(({ link, src }) => {
<ide> A required file can not have both a src and a link: src = ${src}, link = ${link}
<ide> })
<ide> .join('\n');
<ide>
<del> const indexHtml = findIndexHtml(challengeFiles);
<del>
<del> const source = challengeFiles.reduce((source, challengeFile) => {
<del> if (!indexHtml) return source.concat(challengeFile.contents);
<del> if (
<del> indexHtml.importedFiles.includes(challengeFile.history[0]) ||
<del> wasHtmlFile(challengeFile)
<del> ) {
<del> return source.concat(challengeFile.contents);
<del> } else {
<del> return source;
<del> }
<del> }, '');
<del>
<del> return `<head>${head}</head>${embedSource({ source })}`;
<add> return `<head>${head}</head>${embedSource({ source: contents })}`;
<ide> }
<ide><path>client/src/templates/Challenges/rechallenge/builders.test.js
<del>import { findIndexHtml } from './builders.js';
<del>
<del>const withHTML = [
<del> { history: ['index.html'], contents: 'the index html' },
<del> { history: ['index.css', 'index.html'], contents: 'the style file' }
<del>];
<del>
<del>const withoutHTML = [
<del> { history: ['index.css', 'index.html'], contents: 'the js file' },
<del> { history: ['index.js', 'index.html'], contents: 'the style file' }
<del>];
<del>
<del>const tooMuchHTML = [
<del> { history: ['index.html'], contents: 'the index html' },
<del> { history: ['index.css', 'index.html'], contents: 'index html two' },
<del> { history: ['index.html'], contents: 'index html three' }
<del>];
<del>
<del>// TODO: write tests for concatHtml instead, since findIndexHtml should not be
<del>// exported.
<del>
<del>describe('findIndexHtml', () => {
<del> it('should return the index.html file from an array', () => {
<del> expect.assertions(1);
<del>
<del> expect(findIndexHtml(withHTML)).toStrictEqual({
<del> history: ['index.html'],
<del> contents: 'the index html'
<del> });
<del> });
<del>
<del> it('should return undefined when the index.html file is missing', () => {
<del> expect.assertions(1);
<del>
<del> expect(findIndexHtml(withoutHTML)).toBeUndefined();
<del> });
<del>
<del> it('should throw if there are two or more index.htmls', () => {
<del> expect.assertions(1);
<del>
<del> expect(() => findIndexHtml(tooMuchHTML)).toThrowError(
<del> 'Too many html blocks in the challenge seed'
<del> );
<del> });
<del>});
<ide><path>client/src/templates/Challenges/rechallenge/transformers.js
<ide> import {
<ide> transformContents,
<ide> transformHeadTailAndContents,
<ide> setExt,
<del> setImportedFiles,
<ide> compileHeadTail
<ide> } from '../../../../../utils/polyvinyl';
<ide> import createWorker from '../utils/worker-executor';
<ide> async function transformScript(documentElement) {
<ide> });
<ide> }
<ide>
<del>// Find if the base html refers to the css or js files and record if they do. If
<del>// the link or script exists we remove those elements since those files don't
<del>// exist on the site, only in the editor
<del>const addImportedFiles = async function (fileP) {
<del> const file = await fileP;
<del> const transform = documentElement => {
<add>// This does the final transformations of the files needed to embed them into
<add>// HTML.
<add>export const embedFilesInHtml = async function (challengeFiles) {
<add> const { indexHtml, stylesCss, scriptJs, indexJsx } =
<add> challengeFilesToObject(challengeFiles);
<add>
<add> const embedStylesAndScript = (documentElement, contentDocument) => {
<ide> const link =
<ide> documentElement.querySelector('link[href="styles.css"]') ??
<ide> documentElement.querySelector('link[href="./styles.css"]');
<ide> const script =
<ide> documentElement.querySelector('script[src="script.js"]') ??
<ide> documentElement.querySelector('script[src="./script.js"]');
<del> const importedFiles = [];
<ide> if (link) {
<del> importedFiles.push('styles.css');
<del> link.remove();
<add> const style = contentDocument.createElement('style');
<add> style.innerHTML = stylesCss?.contents;
<add>
<add> link.parentNode.replaceChild(style, link);
<ide> }
<ide> if (script) {
<del> importedFiles.push('script.js');
<del> script.remove();
<add> const script = (contentDocument.createElement('script').innerHTML =
<add> scriptJs?.contents);
<add> link.parentNode.replaceChild(script, link);
<ide> }
<ide> return {
<del> contents: documentElement.innerHTML,
<del> importedFiles
<add> contents: documentElement.innerHTML
<ide> };
<ide> };
<ide>
<del> const { importedFiles, contents } = await transformWithFrame(
<del> transform,
<del> file.contents
<del> );
<del>
<del> return flow(
<del> partial(setImportedFiles, importedFiles),
<del> partial(transformContents, () => contents)
<del> )(file);
<add> if (indexHtml) {
<add> const { contents } = await transformWithFrame(
<add> embedStylesAndScript,
<add> indexHtml.contents
<add> );
<add> return [challengeFiles, contents];
<add> } else if (indexJsx) {
<add> return [challengeFiles, `<script>${indexJsx.contents}</script>`];
<add> } else if (scriptJs) {
<add> return [challengeFiles, `<script>${scriptJs.contents}</script>`];
<add> } else {
<add> throw Error('No html or js(x) file found');
<add> }
<ide> };
<ide>
<add>function challengeFilesToObject(challengeFiles) {
<add> const indexHtml = challengeFiles.find(file => file.fileKey === 'indexhtml');
<add> const indexJsx = challengeFiles.find(
<add> file => file.fileKey === 'indexjs' && file.history[0] === 'index.jsx'
<add> );
<add> const stylesCss = challengeFiles.find(file => file.fileKey === 'stylescss');
<add> const scriptJs = challengeFiles.find(file => file.fileKey === 'scriptjs');
<add> return { indexHtml, indexJsx, stylesCss, scriptJs };
<add>}
<add>
<ide> const transformWithFrame = async function (transform, contents) {
<ide> // we use iframe here since file.contents is destined to be be inserted into
<ide> // the root of an iframe.
<ide> const transformWithFrame = async function (transform, contents) {
<ide> // itself. It appears that the frame's documentElement can get replaced by a
<ide> // blank documentElement without the contents. This seems only to happen on
<ide> // Firefox.
<del> out = await transform(frame.contentDocument.documentElement);
<add> out = await transform(
<add> frame.contentDocument.documentElement,
<add> frame.contentDocument
<add> );
<ide> } finally {
<ide> document.body.removeChild(frame);
<ide> }
<ide> const transformHtml = async function (file) {
<ide> return transformContents(() => contents, file);
<ide> };
<ide>
<del>const composeHTML = cond([
<del> [testHTML, partial(compileHeadTail, '')],
<del> [stubTrue, identity]
<del>]);
<del>
<ide> const htmlTransformer = cond([
<del> [testHTML, flow(transformHtml, addImportedFiles)],
<add> [testHTML, flow(transformHtml)],
<ide> [stubTrue, identity]
<ide> ]);
<ide>
<ide> export const getTransformers = options => [
<ide> replaceNBSP,
<ide> babelTransformer(options ? options : {}),
<del> composeHTML,
<add> partial(compileHeadTail, ''),
<ide> htmlTransformer
<ide> ];
<ide><path>client/src/templates/Challenges/utils/build.js
<ide> import frameRunnerData from '../../../../../config/client/frame-runner.json';
<ide> import testEvaluatorData from '../../../../../config/client/test-evaluator.json';
<ide> import { challengeTypes } from '../../../../utils/challenge-types';
<del>import { cssToHtml, jsToHtml, concatHtml } from '../rechallenge/builders.js';
<del>import { getTransformers } from '../rechallenge/transformers';
<add>import { concatHtml } from '../rechallenge/builders.js';
<add>import { getTransformers, embedFilesInHtml } from '../rechallenge/transformers';
<ide> import {
<ide> createTestFramer,
<ide> runTestInTestFrame,
<ide> export function buildDOMChallenge(
<ide> const loadEnzyme = challengeFiles.some(
<ide> challengeFile => challengeFile.ext === 'jsx'
<ide> );
<del> const toHtml = [jsToHtml, cssToHtml];
<del> const pipeLine = composeFunctions(...getTransformers(), ...toHtml);
<add> const pipeLine = composeFunctions(...getTransformers());
<ide> const finalFiles = challengeFiles.map(pipeLine);
<ide> return Promise.all(finalFiles)
<ide> .then(checkFilesErrors)
<del> .then(challengeFiles => {
<add> .then(embedFilesInHtml)
<add> .then(([challengeFiles, contents]) => {
<ide> return {
<ide> challengeType:
<ide> challengeTypes.html || challengeTypes.multifileCertProject,
<ide> build: concatHtml({
<ide> required: finalRequires,
<ide> template,
<del> challengeFiles
<add> contents
<ide> }),
<ide> sources: buildSourceMap(challengeFiles),
<ide> loadEnzyme
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-basic-css-by-building-a-cafe-menu/5f3477cb2e27333b1ab2b955.md
<ide> Your code should have a `link` element.
<ide>
<ide> ```js
<ide> // link is removed -> if exists, replaced with style
<del>const link = document.querySelector('body > style');
<add>const link = document.querySelector('head > style');
<ide> assert(link);
<ide> ```
<ide>
| 6
|
Ruby
|
Ruby
|
fix constant reference
|
a463398a8b30454e532029d67fc481ee5b71b25a
|
<ide><path>Library/Homebrew/extend/ENV.rb
<ide> def fortran
<ide> self['FC'] = which 'gfortran'
<ide> self['F77'] = self['FC']
<ide>
<del> FC_FLAG_VARS.each {|key| self[key] = cflags}
<del> set_cpu_flags(FC_FLAG_VARS)
<add> HomebrewEnvExtension::FC_FLAG_VARS.each {|key| self[key] = cflags}
<add> set_cpu_flags(HomebrewEnvExtension::FC_FLAG_VARS)
<ide> else
<ide> onoe <<-EOS
<ide> This formula requires a fortran compiler, but we could not find one by
| 1
|
Python
|
Python
|
add reference to slides for rmsprop
|
5d38b04415fd27d9b0608ea297ac1dcaa49aa81f
|
<ide><path>keras/optimizers.py
<ide> class RMSprop(Optimizer):
<ide> rho: float >= 0.
<ide> epsilon: float >= 0. Fuzz factor.
<ide> decay: float >= 0. Learning rate decay over each update.
<add>
<add> # References
<add> - [rmsprop: Divide the gradient by a running average of its recent magnitude](http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
<ide> """
<ide>
<ide> def __init__(self, lr=0.001, rho=0.9, epsilon=1e-8, decay=0.,
| 1
|
PHP
|
PHP
|
retain flash also for redirect
|
b7c55c3ff3d8315063757a0a8e89d66696fe1c0c
|
<ide><path>src/TestSuite/IntegrationTestTrait.php
<ide> public function controllerSpy(EventInterface $event, ?Controller $controller = n
<ide> }
<ide> $this->_controller = $controller;
<ide> $events = $controller->getEventManager();
<add> $events->on('Controller.beforeRedirect', function () use ($controller): void {
<add> if ($this->_retainFlashMessages) {
<add> $this->_flashMessages = $controller->getRequest()->getSession()->read('Flash');
<add> }
<add> });
<ide> $events->on('View.beforeRender', function ($event, $viewFile) use ($controller): void {
<ide> if (!$this->_viewName) {
<ide> $this->_viewName = $viewFile;
| 1
|
Text
|
Text
|
js intermediate algorithm guide
|
d331ad1fcd8988eb416bb9bf830b356cbca69a39
|
<ide><path>guide/english/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union/index.md
<ide> uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
<ide>
<ide> ### Code Explanation:
<ide>
<del>* We first use `concat()` with an empty array `<a href='http://exploringjs.com/es6/ch_maps-sets.html#_set' target='_blank' rel='nofollow'>]` as a starting point and the spread operator `...` to create an array out of the Arguments object and to flatten it at the same time
<add>* We first use `concat()` with an empty array as a starting point and the spread operator `...` to create an array out of the Arguments object and to flatten it at the same time
<ide> * then we use the new ES2015 **Set** object to store only unique values
<del>* (to learn more about Sets, read [here</a>)
<ide>
<ide> #### Relevant Links
<ide>
| 1
|
Ruby
|
Ruby
|
move compilerselector logic into build env setup
|
1ae81f0bf70d7fe0b39cc05ae53b51514a9d3435
|
<ide><path>Library/Homebrew/build.rb
<ide> def install
<ide> ENV.keg_only_deps = keg_only_deps.map(&:to_s)
<ide> ENV.deps = deps.map { |d| d.to_formula.to_s }
<ide> ENV.x11 = reqs.any? { |rq| rq.kind_of?(X11Dependency) }
<del> ENV.setup_build_environment
<add> ENV.setup_build_environment(f)
<ide> post_superenv_hacks
<ide> reqs.each(&:modify_build_environment)
<ide> deps.each(&:modify_build_environment)
<ide> else
<del> ENV.setup_build_environment
<add> ENV.setup_build_environment(f)
<ide> reqs.each(&:modify_build_environment)
<ide> deps.each(&:modify_build_environment)
<ide>
<ide> def install
<ide> end
<ide> end
<ide>
<del> if f.fails_with? ENV.compiler
<del> begin
<del> ENV.send CompilerSelector.new(f).compiler
<del> rescue CompilerSelectionError => e
<del> raise e.message
<del> end
<del> end
<del>
<ide> # We only support libstdc++ right now
<ide> stdlib_in_use = CxxStdlib.new(:libstdcxx, ENV.compiler)
<ide>
<ide><path>Library/Homebrew/extend/ENV/shared.rb
<ide> def compiler
<ide> end
<ide> end
<ide>
<add> # If the given compiler isn't compatible, will try to select
<add> # an alternate compiler, altering the value of environment variables.
<add> # If no valid compiler is found, raises an exception.
<add> def validate_cc!(formula)
<add> if formula.fails_with? ENV.compiler
<add> begin
<add> send CompilerSelector.new(formula).compiler
<add> rescue CompilerSelectionError => e
<add> raise e.message
<add> end
<add> end
<add> end
<add>
<ide> # Snow Leopard defines an NCURSES value the opposite of most distros
<ide> # See: http://bugs.python.org/issue6848
<ide> # Currently only used by aalib in core
<ide> def warn_about_non_apple_gcc(gcc)
<ide>
<ide> begin
<ide> gcc_name = 'gcc' + gcc.delete('.')
<del> gcc = Formula.factory(gcc_name)
<add> gcc = Formulary.factory(gcc_name)
<ide> if !gcc.installed?
<ide> raise <<-EOS.undent
<ide> The requested Homebrew GCC, #{gcc_name}, was not installed.
<ide> def warn_about_non_apple_gcc(gcc)
<ide> brew install #{gcc_name}
<ide> EOS
<ide> end
<del>
<del> ENV.append('PATH', gcc.opt_prefix/'bin', ':')
<ide> rescue FormulaUnavailableError
<ide> raise <<-EOS.undent
<ide> Homebrew GCC requested, but formula #{gcc_name} not found!
<ide><path>Library/Homebrew/extend/ENV/std.rb
<ide> def self.extended(base)
<ide> end
<ide> end
<ide>
<del> def setup_build_environment
<add> def setup_build_environment(formula=nil)
<ide> # Clear CDPATH to avoid make issues that depend on changing directories
<ide> delete('CDPATH')
<ide> delete('GREP_OPTIONS') # can break CMake (lol)
<ide> def setup_build_environment
<ide> self.cxx = MacOS.locate("c++")
<ide> end
<ide>
<add> validate_cc!(formula) unless formula.nil?
<add>
<ide> if cc =~ GNU_GCC_REGEXP
<ide> warn_about_non_apple_gcc($1)
<add> gcc_name = 'gcc' + $1.delete('.')
<add> gcc = Formulary.factory(gcc_name)
<add> self.append_path('PATH', gcc.opt_prefix/'bin')
<ide> end
<ide>
<ide> # Add lib and include etc. from the current macosxsdk to compiler flags:
<ide><path>Library/Homebrew/extend/ENV/super.rb
<ide> def reset
<ide> delete('CLICOLOR_FORCE') # autotools doesn't like this
<ide> end
<ide>
<del> def setup_build_environment
<add> def setup_build_environment(formula=nil)
<ide> reset
<add>
<ide> self.cc = 'cc'
<ide> self.cxx = 'c++'
<add> self['HOMEBREW_CC'] = determine_cc
<add> validate_cc!(formula) unless formula.nil?
<ide> self['DEVELOPER_DIR'] = determine_developer_dir
<ide> self['MAKEFLAGS'] ||= "-j#{determine_make_jobs}"
<ide> self['PATH'] = determine_path
<ide> self['PKG_CONFIG_PATH'] = determine_pkg_config_path
<ide> self['PKG_CONFIG_LIBDIR'] = determine_pkg_config_libdir
<del> self['HOMEBREW_CC'] = determine_cc
<ide> self['HOMEBREW_CCCFG'] = determine_cccfg
<ide> self['HOMEBREW_BREW_FILE'] = HOMEBREW_BREW_FILE
<ide> self['HOMEBREW_SDKROOT'] = "#{MacOS.sdk_path}" if MacOS::Xcode.without_clt?
<ide> def setup_build_environment
<ide> # s - apply fix for sed's Unicode support
<ide> # a - apply fix for apr-1-config path
<ide>
<del> # Homebrew's apple-gcc42 will be outside the PATH in superenv,
<del> # so xcrun may not be able to find it
<del> if self['HOMEBREW_CC'] == 'gcc-4.2'
<del> apple_gcc42 = begin
<del> Formulary.factory('apple-gcc42')
<del> rescue Exception # in --debug, catch bare exceptions too
<del> nil
<del> end
<del> append_path('PATH', apple_gcc42.opt_prefix/'bin') if apple_gcc42
<del> end
<del>
<del> if ENV['HOMEBREW_CC'] =~ GNU_GCC_REGEXP
<del> warn_about_non_apple_gcc($1)
<del> end
<add> warn_about_non_apple_gcc($1) if ENV['HOMEBREW_CC'] =~ GNU_GCC_REGEXP
<ide> end
<ide>
<ide> def universal_binary
<ide> def determine_path
<ide> paths += deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/bin" }
<ide> paths << MacOS::X11.bin if x11?
<ide> paths += %w{/usr/bin /bin /usr/sbin /sbin}
<add>
<add> # Homebrew's apple-gcc42 will be outside the PATH in superenv,
<add> # so xcrun may not be able to find it
<add> if self['HOMEBREW_CC'] == 'gcc-4.2'
<add> apple_gcc42 = begin
<add> Formulary.factory('apple-gcc42')
<add> rescue Exception # in --debug, catch bare exceptions too
<add> nil
<add> end
<add> paths << apple_gcc42.opt_prefix/'bin' if apple_gcc42
<add> end
<add>
<add> if self['HOMEBREW_CC'] =~ GNU_GCC_REGEXP
<add> gcc_name = 'gcc' + $1.delete('.')
<add> gcc = Formulary.factory(gcc_name)
<add> paths << gcc.opt_prefix/'bin'
<add> end
<add>
<ide> paths.to_path_s
<ide> end
<ide>
| 4
|
Go
|
Go
|
limit the amount of prints during normal runs
|
6094257b28f2e4b5e1a6616c77961b5cec0c9195
|
<ide><path>devmapper/deviceset_devmapper.go
<ide> package devmapper
<ide>
<ide> import (
<add> "github.com/dotcloud/docker/utils"
<ide> "encoding/json"
<ide> "fmt"
<ide> "io"
<ide> func (devices *DeviceSetDM) ensureImage(name string, size int64) (string, error)
<ide> }
<ide>
<ide> func (devices *DeviceSetDM) createPool(dataFile *os.File, metadataFile *os.File) error {
<del> log.Printf("Activating device-mapper pool %s", devices.getPoolName())
<add> utils.Debugf("Activating device-mapper pool %s", devices.getPoolName())
<ide> task, err := devices.createTask(DeviceCreate, devices.getPoolName())
<ide> if task == nil {
<ide> return err
<ide><path>image.go
<ide> func (image *Image) ensureImageDevice(devices DeviceSet) error {
<ide>
<ide> mounted, err := Mounted(mountDir)
<ide> if err == nil && mounted {
<del> log.Printf("Image %s is unexpectedly mounted, unmounting...", image.ID)
<add> utils.Debugf("Image %s is unexpectedly mounted, unmounting...", image.ID)
<ide> err = syscall.Unmount(mountDir, 0)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> }
<ide>
<ide> if devices.HasDevice(image.ID) {
<del> log.Printf("Found non-initialized demove-mapper device for image %s, removing", image.ID)
<add> utils.Debugf("Found non-initialized demove-mapper device for image %s, removing", image.ID)
<ide> err = devices.RemoveDevice(image.ID)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> }
<ide>
<del> log.Printf("Creating device-mapper device for image id %s", image.ID)
<del>
<add> utils.Debugf("Creating device-mapper device for image id %s", image.ID)
<ide> err = devices.AddDevice(image.ID, image.Parent)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> utils.Debugf("Mounting device %s at %s for image setup", image.ID, mountDir)
<ide> err = devices.MountDevice(image.ID, mountDir)
<ide> if err != nil {
<ide> _ = devices.RemoveDevice(image.ID)
<ide> func (image *Image) ensureImageDevice(devices DeviceSet) error {
<ide> return err
<ide> }
<ide>
<del> utils.Debugf("Applying layer %s at %s", image.ID, mountDir)
<ide> err = image.applyLayer(layerPath(root), mountDir)
<ide> if err != nil {
<ide> _ = devices.RemoveDevice(image.ID)
<ide> return err
<ide> }
<ide>
<del> utils.Debugf("Unmounting %s", mountDir)
<ide> err = syscall.Unmount(mountDir, 0)
<ide> if err != nil {
<ide> _ = devices.RemoveDevice(image.ID)
<ide><path>runtime.go
<ide> func (runtime *Runtime) GetMountMethod() MountMethod {
<ide> if runtime.mountMethod == MountMethodNone {
<ide> // Try to automatically pick a method
<ide> if hasFilesystemSupport("aufs") {
<del> log.Printf("Using AUFS backend.")
<add> utils.Debugf("Using AUFS backend.")
<ide> runtime.mountMethod = MountMethodAUFS
<ide> } else {
<ide> _ = exec.Command("modprobe", "aufs").Run()
<ide> if hasFilesystemSupport("aufs") {
<del> log.Printf("Using AUFS backend.")
<add> utils.Debugf("Using AUFS backend.")
<ide> runtime.mountMethod = MountMethodAUFS
<ide> } else {
<del> log.Printf("Using device-mapper backend.")
<add> utils.Debugf("Using device-mapper backend.")
<ide> runtime.mountMethod = MountMethodDeviceMapper
<ide> }
<ide> }
| 3
|
Ruby
|
Ruby
|
add missing models requires to activerecord tests
|
e79eaac56e51fc1961998388e8a6f384fe277113
|
<ide><path>activerecord/test/cases/fixtures_test.rb
<ide> require "models/computer"
<ide> require "models/course"
<ide> require "models/developer"
<add>require "models/dog_lover"
<ide> require "models/dog"
<ide> require "models/doubloon"
<ide> require "models/essay"
<ide><path>activerecord/test/cases/nested_attributes_test.rb
<ide>
<ide> require "cases/helper"
<ide> require "models/pirate"
<add>require "models/developer"
<ide> require "models/ship"
<ide> require "models/ship_part"
<ide> require "models/bird"
| 2
|
Javascript
|
Javascript
|
add webgl2 to detector
|
3f0dfd9f1f78af1f3be23c61cd3d4ec8574560dd
|
<ide><path>examples/js/Detector.js
<ide> var Detector = {
<ide>
<ide> }
<ide>
<add> } )(),
<add> webgl2: ( function () {
<add>
<add> try {
<add>
<add> var canvas = document.createElement( 'canvas' ); return !! ( window.WebGL2RenderingContext && ( canvas.getContext( 'webgl2' ) ) );
<add>
<add> } catch ( e ) {
<add>
<add> return false;
<add>
<add> }
<add>
<ide> } )(),
<ide> workers: !! window.Worker,
<ide> fileapi: window.File && window.FileReader && window.FileList && window.Blob,
| 1
|
Text
|
Text
|
fix some syntax error
|
18724726c24728c0dd2bdb4981254a100568185f
|
<ide><path>docs/reference/commandline/swarm_init.md
<ide> This flag sets the validity period for node certificates.
<ide>
<ide> ### `--dispatcher-heartbeat`
<ide>
<del>This flags sets the frequency with which nodes are told to use as a
<add>This flag sets the frequency with which nodes are told to use as a
<ide> period to report their health.
<ide>
<ide> ### `--external-ca`
<ide> name, the default port 2377 will be used.
<ide>
<ide> This flag specifies the address that will be advertised to other members of the
<ide> swarm for API access and overlay networking. If unspecified, Docker will check
<del>if the system has a single IP address, and use that IP address with with the
<add>if the system has a single IP address, and use that IP address with the
<ide> listening port (see `--listen-addr`). If the system has multiple IP addresses,
<ide> `--advertise-addr` must be specified so that the correct address is chosen for
<ide> inter-manager communication and overlay networking.
<ide><path>docs/reference/commandline/swarm_join.md
<ide> This flag is generally not necessary when joining an existing swarm.
<ide>
<ide> This flag specifies the address that will be advertised to other members of the
<ide> swarm for API access. If unspecified, Docker will check if the system has a
<del>single IP address, and use that IP address with with the listening port (see
<add>single IP address, and use that IP address with the listening port (see
<ide> `--listen-addr`). If the system has multiple IP addresses, `--advertise-addr`
<ide> must be specified so that the correct address is chosen for inter-manager
<ide> communication and overlay networking.
| 2
|
Go
|
Go
|
move mount namespace after network
|
b10b950b110c93db34a399753706dc79c71b94d3
|
<ide><path>pkg/libcontainer/nsinit/init.go
<ide> package nsinit
<ide>
<ide> import (
<ide> "fmt"
<add> "os"
<add> "syscall"
<add>
<ide> "github.com/dotcloud/docker/pkg/libcontainer"
<ide> "github.com/dotcloud/docker/pkg/libcontainer/apparmor"
<ide> "github.com/dotcloud/docker/pkg/libcontainer/capabilities"
<ide> "github.com/dotcloud/docker/pkg/libcontainer/network"
<ide> "github.com/dotcloud/docker/pkg/libcontainer/utils"
<ide> "github.com/dotcloud/docker/pkg/system"
<ide> "github.com/dotcloud/docker/pkg/user"
<del> "os"
<del> "syscall"
<ide> )
<ide>
<ide> // Init is the init process that first runs inside a new namespace to setup mounts, users, networking,
<ide> func (ns *linuxNs) Init(container *libcontainer.Container, uncleanRootfs, consol
<ide> if err := system.ParentDeathSignal(uintptr(syscall.SIGTERM)); err != nil {
<ide> return fmt.Errorf("parent death signal %s", err)
<ide> }
<add> if err := setupNetwork(container, context); err != nil {
<add> return fmt.Errorf("setup networking %s", err)
<add> }
<ide> ns.logger.Println("setup mount namespace")
<ide> if err := setupNewMountNamespace(rootfs, container.Mounts, console, container.ReadonlyFs, container.NoPivotRoot); err != nil {
<ide> return fmt.Errorf("setup mount namespace %s", err)
<ide> }
<del> if err := setupNetwork(container, context); err != nil {
<del> return fmt.Errorf("setup networking %s", err)
<del> }
<ide> if err := system.Sethostname(container.Hostname); err != nil {
<ide> return fmt.Errorf("sethostname %s", err)
<ide> }
| 1
|
Javascript
|
Javascript
|
remove unneeded comma in ambiantlight
|
3abc44cceb5d10905092384b98a6d1c51a267180
|
<ide><path>src/lights/AmbientLight.js
<ide> AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
<ide>
<ide> constructor: AmbientLight,
<ide>
<del> isAmbientLight: true,
<add> isAmbientLight: true
<ide>
<ide> } );
<ide>
| 1
|
Text
|
Text
|
add missing periods in documentation.md
|
2553377d118f8762bbb665936e4ce41eb84bf3bb
|
<ide><path>doc/api/documentation.md
<ide> and in the process of being redesigned.
<ide> The stability indices are as follows:
<ide>
<ide> ```txt
<del>Stability: 0 - Deprecated
<del>This feature is known to be problematic, and changes may be planned. Do
<del>not rely on it. Use of the feature may cause warnings to be emitted.
<del>Backwards compatibility across major versions should not be expected.
<add>Stability: 0 - Deprecated. This feature is known to be problematic, and changes
<add>may be planned. Do not rely on it. Use of the feature may cause warnings to be
<add>emitted. Backwards compatibility across major versions should not be expected.
<ide> ```
<ide>
<ide> ```txt
<del>Stability: 1 - Experimental
<del>This feature is still under active development and subject to non-backwards
<del>compatible changes, or even removal, in any future version. Use of the feature
<del>is not recommended in production environments. Experimental features are not
<del>subject to the Node.js Semantic Versioning model.
<add>Stability: 1 - Experimental. This feature is still under active development and
<add>subject to non-backwards compatible changes, or even removal, in any future
<add>version. Use of the feature is not recommended in production environments.
<add>Experimental features are not subject to the Node.js Semantic Versioning model.
<ide> ```
<ide>
<ide> ```txt
<del>Stability: 2 - Stable
<del>The API has proven satisfactory. Compatibility with the npm ecosystem
<del>is a high priority, and will not be broken unless absolutely necessary.
<add>Stability: 2 - Stable. The API has proven satisfactory. Compatibility with the
<add>npm ecosystem is a high priority, and will not be broken unless absolutely
<add>necessary.
<ide> ```
<ide>
<ide> Caution must be used when making use of `Experimental` features, particularly
| 1
|
Go
|
Go
|
remove builder dependency from the api
|
d12b7c7e3e5566f49f81189b757bcd0e4ef09956
|
<ide><path>api/server/router/build/backend.go
<ide> package build
<ide> import (
<ide> "io"
<ide>
<del> "github.com/docker/docker/builder"
<add> "github.com/docker/docker/api/types/backend"
<ide> "github.com/docker/engine-api/types"
<ide> "golang.org/x/net/context"
<ide> )
<ide> type Backend interface {
<ide> // by the caller.
<ide> //
<ide> // TODO: make this return a reference instead of string
<del> Build(clientCtx context.Context, config *types.ImageBuildOptions, context builder.Context, stdout io.Writer, stderr io.Writer, out io.Writer) (string, error)
<add> BuildFromContext(ctx context.Context, src io.ReadCloser, remote string, buildOptions *types.ImageBuildOptions, pg backend.ProgressWriter) (string, error)
<ide> }
<ide><path>api/server/router/build/build_routes.go
<ide> import (
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api/server/httputils"
<del> "github.com/docker/docker/builder"
<add> "github.com/docker/docker/api/types/backend"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/progress"
<ide> "github.com/docker/docker/pkg/streamformatter"
<ide> func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r *
<ide> if err != nil {
<ide> return errf(err)
<ide> }
<add> buildOptions.AuthConfigs = authConfigs
<ide>
<ide> remoteURL := r.FormValue("remote")
<ide>
<ide> func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r *
<ide> return progress.NewProgressReader(in, progressOutput, r.ContentLength, "Downloading context", remoteURL)
<ide> }
<ide>
<del> buildContext, dockerfileName, err := builder.DetectContextFromRemoteURL(r.Body, remoteURL, createProgressReader)
<del> if err != nil {
<del> return errf(err)
<del> }
<del> defer func() {
<del> if err := buildContext.Close(); err != nil {
<del> logrus.Debugf("[BUILDER] failed to remove temporary context: %v", err)
<del> }
<del> }()
<del> if len(dockerfileName) > 0 {
<del> buildOptions.Dockerfile = dockerfileName
<del> }
<del>
<del> buildOptions.AuthConfigs = authConfigs
<del>
<ide> var out io.Writer = output
<ide> if buildOptions.SuppressOutput {
<ide> out = notVerboseBuffer
<ide> func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r *
<ide> stdout := &streamformatter.StdoutFormatter{Writer: out, StreamFormatter: sf}
<ide> stderr := &streamformatter.StderrFormatter{Writer: out, StreamFormatter: sf}
<ide>
<del> imgID, err := br.backend.Build(ctx, buildOptions,
<del> builder.DockerIgnoreContext{ModifiableContext: buildContext},
<del> stdout, stderr, out)
<add> pg := backend.ProgressWriter{
<add> Output: out,
<add> StdoutFormatter: stdout,
<add> StderrFormatter: stderr,
<add> ProgressReaderFunc: createProgressReader,
<add> }
<add>
<add> imgID, err := br.backend.BuildFromContext(ctx, r.Body, remoteURL, buildOptions, pg)
<ide> if err != nil {
<ide> return errf(err)
<ide> }
<ide><path>api/types/backend/backend.go
<ide> package backend
<ide> import (
<ide> "io"
<ide>
<add> "github.com/docker/docker/pkg/streamformatter"
<ide> "github.com/docker/engine-api/types"
<ide> )
<ide>
<ide> type ContainerCommitConfig struct {
<ide> types.ContainerCommitConfig
<ide> Changes []string
<ide> }
<add>
<add>// ProgressWriter is an interface
<add>// to transport progress streams.
<add>type ProgressWriter struct {
<add> Output io.Writer
<add> StdoutFormatter *streamformatter.StdoutFormatter
<add> StderrFormatter *streamformatter.StderrFormatter
<add> ProgressReaderFunc func(io.ReadCloser) io.ReadCloser
<add>}
<ide><path>daemon/builder.go
<add>package daemon
<add>
<add>import (
<add> "io"
<add>
<add> "github.com/Sirupsen/logrus"
<add> "github.com/docker/docker/api/types/backend"
<add> "github.com/docker/docker/builder"
<add> "github.com/docker/docker/builder/dockerfile"
<add> "github.com/docker/engine-api/types"
<add> "golang.org/x/net/context"
<add>)
<add>
<add>// BuildFromContext builds a new image from a given context.
<add>func (daemon *Daemon) BuildFromContext(ctx context.Context, src io.ReadCloser, remote string, buildOptions *types.ImageBuildOptions, pg backend.ProgressWriter) (string, error) {
<add> buildContext, dockerfileName, err := builder.DetectContextFromRemoteURL(src, remote, pg.ProgressReaderFunc)
<add> if err != nil {
<add> return "", err
<add> }
<add> defer func() {
<add> if err := buildContext.Close(); err != nil {
<add> logrus.Debugf("[BUILDER] failed to remove temporary context: %v", err)
<add> }
<add> }()
<add> if len(dockerfileName) > 0 {
<add> buildOptions.Dockerfile = dockerfileName
<add> }
<add>
<add> m := dockerfile.NewBuildManager(daemon)
<add> return m.Build(ctx, buildOptions,
<add> builder.DockerIgnoreContext{ModifiableContext: buildContext},
<add> pg.StdoutFormatter, pg.StderrFormatter, pg.Output)
<add>}
<ide><path>docker/daemon.go
<ide> import (
<ide> "github.com/docker/docker/api/server/router/network"
<ide> systemrouter "github.com/docker/docker/api/server/router/system"
<ide> "github.com/docker/docker/api/server/router/volume"
<del> "github.com/docker/docker/builder/dockerfile"
<ide> "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/cliconfig"
<ide> "github.com/docker/docker/daemon"
<ide> func initRouter(s *apiserver.Server, d *daemon.Daemon) {
<ide> image.NewRouter(d, decoder),
<ide> systemrouter.NewRouter(d),
<ide> volume.NewRouter(d),
<del> build.NewRouter(dockerfile.NewBuildManager(d)),
<add> build.NewRouter(d),
<ide> }
<ide> if d.NetworkControllerEnabled() {
<ide> routers = append(routers, network.NewRouter(d))
| 5
|
Go
|
Go
|
patch 64bit alignment on 32bit systems
|
af2e82d054a2276e5ff76fd3fb90915cad5a0a55
|
<ide><path>builder/builder-next/adapters/containerimage/pull.go
<ide> type resolverCache struct {
<ide> }
<ide>
<ide> type cachedResolver struct {
<add> counter int64 // needs to be 64bit aligned for 32bit systems
<ide> timeout time.Time
<ide> remotes.Resolver
<del> counter int64
<ide> }
<ide>
<ide> func (cr *cachedResolver) Resolve(ctx context.Context, ref string) (name string, desc ocispec.Descriptor, err error) {
| 1
|
Python
|
Python
|
raise badrequest if static file name is invalid
|
9f1be8e795ace494018689c87d8a5e5601313e4d
|
<ide><path>flask/helpers.py
<ide> from urlparse import quote as url_quote
<ide>
<ide> from werkzeug.datastructures import Headers
<del>from werkzeug.exceptions import NotFound
<add>from werkzeug.exceptions import BadRequest, NotFound
<ide>
<ide> # this was moved in 0.7
<ide> try:
<ide> def download_file(filename):
<ide> filename = safe_join(directory, filename)
<ide> if not os.path.isabs(filename):
<ide> filename = os.path.join(current_app.root_path, filename)
<del> if not os.path.isfile(filename):
<del> raise NotFound()
<add> try:
<add> if not os.path.isfile(filename):
<add> raise NotFound()
<add> except (TypeError, ValueError):
<add> raise BadRequest()
<ide> options.setdefault('conditional', True)
<ide> return send_file(filename, **options)
<ide>
<ide><path>tests/test_helpers.py
<ide> import datetime
<ide> import flask
<ide> from logging import StreamHandler
<add>from werkzeug.exceptions import BadRequest
<ide> from werkzeug.http import parse_cache_control_header, parse_options_header
<ide> from werkzeug.http import http_date
<ide> from flask._compat import StringIO, text_type
<ide> def test_send_from_directory(self):
<ide> assert rv.data.strip() == b'Hello Subdomain'
<ide> rv.close()
<ide>
<add> def test_send_from_directory_bad_request(self):
<add> app = flask.Flask(__name__)
<add> app.testing = True
<add> app.root_path = os.path.join(os.path.dirname(__file__),
<add> 'test_apps', 'subdomaintestmodule')
<add> with app.test_request_context():
<add> with pytest.raises(BadRequest):
<add> flask.send_from_directory('static', 'bad\x00')
<ide>
<ide> class TestLogging(object):
<ide>
| 2
|
Ruby
|
Ruby
|
add intel cpus to optimization_flags
|
12b5de391ed51c433a402a55afa7675d3ad823d6
|
<ide><path>Library/Homebrew/os/linux/hardware.rb
<ide> module LinuxCPUs
<del> OPTIMIZATION_FLAGS = {}.freeze
<add> OPTIMIZATION_FLAGS = {
<add> :penryn => '-march=core2 -msse4.1',
<add> :core2 => '-march=core2',
<add> :core => '-march=prescott',
<add> }.freeze
<ide> def optimization_flags; OPTIMIZATION_FLAGS; end
<ide>
<ide> # Linux supports x86 only, and universal archs do not apply
| 1
|
Ruby
|
Ruby
|
update documentation for run_callbacks
|
c97b18a347e75aadcd6fff85ecb1ba822b02e4d8
|
<ide><path>activesupport/lib/active_support/callbacks.rb
<ide> module Callbacks
<ide> # order.
<ide> #
<ide> # If the callback chain was halted, returns +false+. Otherwise returns the
<del> # result of the block, or +true+ if no block is given.
<add> # result of the block, nil if no callbacks have been set, or +true+
<add> # if callbacks have been set but no block is given.
<ide> #
<ide> # run_callbacks :save do
<ide> # save
| 1
|
Text
|
Text
|
add comment for net.server's error event
|
52ddb41c6006cfae93099e628aa040371e0512de
|
<ide><path>doc/api/net.md
<ide> added: v0.1.90
<ide>
<ide> * {Error}
<ide>
<del>Emitted when an error occurs. The [`'close'`][] event will be called directly
<del>following this event. See example in discussion of `server.listen`.
<add>Emitted when an error occurs. Unlike [`net.Socket`][], the [`'close'`][]
<add>event will **not** be emitted directly following this event unless
<add>[`server.close()`][] is manually called. See the example in discussion of
<add>[`server.listen()`][`server.listen(port, host, backlog, callback)`].
<ide>
<ide> ### Event: 'listening'
<ide> <!-- YAML
<ide> Returns true if input is a version 6 IP address, otherwise returns false.
<ide> [`resume()`]: #net_socket_resume
<ide> [`server.getConnections()`]: #net_server_getconnections_callback
<ide> [`server.listen(port, host, backlog, callback)`]: #net_server_listen_port_hostname_backlog_callback
<add>[`server.close()`]: #net_server_close_callback
<ide> [`socket.connect(options, connectListener)`]: #net_socket_connect_options_connectlistener
<ide> [`socket.connect`]: #net_socket_connect_options_connectlistener
<ide> [`socket.setTimeout()`]: #net_socket_settimeout_timeout_callback
| 1
|
Javascript
|
Javascript
|
combine source maps
|
53a2c5a7fc14dd7b6a32ed27080534eefd2362f8
|
<ide><path>server/build/plugins/combine-assets-plugin.js
<add>import { ConcatSource } from 'webpack-sources'
<add>
<ide> // This plugin combines a set of assets into a single asset
<ide> // This should be only used with text assets,
<ide> // otherwise the result is unpredictable.
<ide> export default class CombineAssetsPlugin {
<ide> }
<ide>
<ide> apply (compiler) {
<del> compiler.plugin('after-compile', (compilation, callback) => {
<del> let newSource = ''
<del> this.input.forEach((name) => {
<del> const asset = compilation.assets[name]
<del> if (!asset) return
<add> compiler.plugin('compilation', (compilation) => {
<add> compilation.plugin('additional-chunk-assets', (chunks) => {
<add> const concat = new ConcatSource()
<ide>
<del> newSource += `${asset.source()}\n`
<add> this.input.forEach((name) => {
<add> const asset = compilation.assets[name]
<add> if (!asset) return
<ide>
<del> // We keep existing assets since that helps when analyzing the bundle
<del> })
<add> concat.add(asset)
<ide>
<del> compilation.assets[this.output] = {
<del> source: () => newSource,
<del> size: () => newSource.length
<del> }
<add> // We keep existing assets since that helps when analyzing the bundle
<add> })
<ide>
<del> callback()
<add> compilation.additionalChunkAssets.push(this.output)
<add> compilation.assets[this.output] = concat
<add>
<add> // Register the combined file as an output of the associated chunks
<add> chunks.filter((chunk) => {
<add> return chunk.files.reduce((prev, file) => prev || this.input.includes(file), false)
<add> })
<add> .forEach((chunk) => chunk.files.push(this.output))
<add> })
<ide> })
<ide> }
<ide> }
<ide><path>server/build/plugins/dynamic-chunks-plugin.js
<del>export default class PagesPlugin {
<add>import { ConcatSource } from 'webpack-sources'
<add>
<add>const isImportChunk = /^chunks[/\\].*\.js$/
<add>const matchChunkName = /^chunks[/\\](.*)$/
<add>
<add>class DynamicChunkTemplatePlugin {
<add> apply (chunkTemplate) {
<add> chunkTemplate.plugin('render', function (modules, chunk) {
<add> if (!isImportChunk.test(chunk.name)) {
<add> return modules
<add> }
<add>
<add> const chunkName = matchChunkName.exec(chunk.name)[1]
<add> const source = new ConcatSource()
<add>
<add> source.add(`
<add> __NEXT_REGISTER_CHUNK('${chunkName}', function() {
<add> `)
<add> source.add(modules)
<add> source.add(`
<add> })
<add> `)
<add>
<add> return source
<add> })
<add> }
<add>}
<add>
<add>export default class DynamicChunksPlugin {
<ide> apply (compiler) {
<del> const isImportChunk = /^chunks[/\\].*\.js$/
<del> const matchChunkName = /^chunks[/\\](.*)$/
<del>
<del> compiler.plugin('after-compile', (compilation, callback) => {
<del> const chunks = Object
<del> .keys(compilation.namedChunks)
<del> .map(key => compilation.namedChunks[key])
<del> .filter(chunk => isImportChunk.test(chunk.name))
<del>
<del> chunks.forEach((chunk) => {
<del> const asset = compilation.assets[chunk.name]
<del> if (!asset) return
<del>
<del> const chunkName = matchChunkName.exec(chunk.name)[1]
<del>
<del> const content = asset.source()
<del> const newContent = `
<del> window.__NEXT_REGISTER_CHUNK('${chunkName}', function() {
<del> ${content}
<del> })
<del> `
<del> // Replace the exisiting chunk with the new content
<del> compilation.assets[chunk.name] = {
<del> source: () => newContent,
<del> size: () => newContent.length
<del> }
<del>
<del> // This is to support, webpack dynamic import support with HMR
<del> compilation.assets[`chunks/${chunk.id}`] = {
<del> source: () => newContent,
<del> size: () => newContent.length
<del> }
<add> compiler.plugin('compilation', (compilation) => {
<add> compilation.chunkTemplate.apply(new DynamicChunkTemplatePlugin())
<add>
<add> compilation.plugin('additional-chunk-assets', (chunks) => {
<add> chunks = chunks.filter(chunk =>
<add> isImportChunk.test(chunk.name) && compilation.assets[chunk.name]
<add> )
<add>
<add> chunks.forEach((chunk) => {
<add> // This is to support, webpack dynamic import support with HMR
<add> const copyFilename = `chunks/${chunk.name}`
<add> compilation.additionalChunkAssets.push(copyFilename)
<add> compilation.assets[copyFilename] = compilation.assets[chunk.name]
<add> })
<ide> })
<del> callback()
<ide> })
<ide> }
<ide> }
<ide><path>server/build/plugins/pages-plugin.js
<add>import { ConcatSource } from 'webpack-sources'
<ide> import {
<ide> IS_BUNDLED_PAGE,
<ide> MATCH_ROUTE_NAME
<ide> } from '../../utils'
<ide>
<del>export default class PagesPlugin {
<del> apply (compiler) {
<del> compiler.plugin('after-compile', (compilation, callback) => {
<del> const pages = Object
<del> .keys(compilation.namedChunks)
<del> .map(key => compilation.namedChunks[key])
<del> .filter(chunk => IS_BUNDLED_PAGE.test(chunk.name))
<add>class PageChunkTemplatePlugin {
<add> apply (chunkTemplate) {
<add> chunkTemplate.plugin('render', function (modules, chunk) {
<add> if (!IS_BUNDLED_PAGE.test(chunk.name)) {
<add> return modules
<add> }
<ide>
<del> pages.forEach((chunk) => {
<del> const page = compilation.assets[chunk.name]
<del> const pageName = MATCH_ROUTE_NAME.exec(chunk.name)[1]
<del> let routeName = pageName
<add> let routeName = MATCH_ROUTE_NAME.exec(chunk.name)[1]
<ide>
<ide> // We need to convert \ into / when we are in windows
<ide> // to get the proper route name
<ide> // Here we need to do windows check because it's possible
<ide> // to have "\" in the filename in unix.
<ide> // Anyway if someone did that, he'll be having issues here.
<ide> // But that's something we cannot avoid.
<del> if (/^win/.test(process.platform)) {
<del> routeName = routeName.replace(/\\/g, '/')
<del> }
<del>
<del> routeName = `/${routeName.replace(/(^|\/)index$/, '')}`
<del>
<del> const content = page.source()
<del> const newContent = `
<del> window.__NEXT_REGISTER_PAGE('${routeName}', function() {
<del> var comp = ${content}
<del> return { page: comp.default }
<del> })
<del> `
<del> // Replace the exisiting chunk with the new content
<del> compilation.assets[chunk.name] = {
<del> source: () => newContent,
<del> size: () => newContent.length
<del> }
<del> })
<del> callback()
<add> if (/^win/.test(process.platform)) {
<add> routeName = routeName.replace(/\\/g, '/')
<add> }
<add>
<add> routeName = `/${routeName.replace(/(^|\/)index$/, '')}`
<add>
<add> const source = new ConcatSource()
<add>
<add> source.add(`
<add> __NEXT_REGISTER_PAGE('${routeName}', function() {
<add> var comp =
<add> `)
<add> source.add(modules)
<add> source.add(`
<add> return { page: comp.default }
<add> })
<add> `)
<add>
<add> return source
<add> })
<add> }
<add>}
<add>
<add>export default class PagesPlugin {
<add> apply (compiler) {
<add> compiler.plugin('compilation', (compilation) => {
<add> compilation.chunkTemplate.apply(new PageChunkTemplatePlugin())
<ide> })
<ide> }
<ide> }
<ide><path>server/build/webpack.js
<ide> export default async function createCompiler (dir, { buildId, dev = false, quiet
<ide> output: 'app.js'
<ide> }),
<ide> new webpack.optimize.UglifyJsPlugin({
<add> exclude: ['manifest.js', 'commons.js', 'main.js'],
<ide> compress: { warnings: false },
<ide> sourceMap: false
<ide> })
<ide><path>server/index.js
<ide> export default class Server {
<ide> }
<ide>
<ide> handleBuildId (buildId, res) {
<del> if (this.dev) return true
<add> if (this.dev) {
<add> res.setHeader('Cache-Control', 'no-store, must-revalidate')
<add> return true
<add> }
<add>
<ide> if (buildId !== this.renderOpts.buildId) {
<ide> return false
<ide> }
<ide> export default class Server {
<ide> }
<ide>
<ide> handleBuildHash (filename, hash, res) {
<del> if (this.dev) return
<add> if (this.dev) {
<add> res.setHeader('Cache-Control', 'no-store, must-revalidate')
<add> return true
<add> }
<ide>
<ide> if (hash !== this.buildStats[filename].hash) {
<ide> throw new Error(`Invalid Build File Hash(${hash}) for chunk: ${filename}`)
<ide> }
<ide>
<ide> res.setHeader('Cache-Control', 'max-age=365000000, immutable')
<add> return true
<ide> }
<ide>
<ide> send404 (res) {
<ide><path>server/render.js
<ide> async function doRender (req, res, pathname, query, {
<ide> }
<ide>
<ide> const docProps = await loadGetInitialProps(Document, { ...ctx, renderPage })
<del> // While developing, we should not cache any assets.
<del> // So, we use a different buildId for each page load.
<del> // With that we can ensure, we have unique URL for assets per every page load.
<del> // So, it'll prevent issues like this: https://git.io/vHLtb
<del> const devBuildId = Date.now()
<ide>
<ide> if (res.finished) return
<ide>
<ide> async function doRender (req, res, pathname, query, {
<ide> props,
<ide> pathname,
<ide> query,
<del> buildId: dev ? devBuildId : buildId,
<add> buildId,
<ide> buildStats,
<ide> assetPrefix,
<ide> nextExport,
| 6
|
Python
|
Python
|
use compact traceback for errors reporting
|
a7567efa8d6fd008ba0a48f0e8fa7028703af386
|
<ide><path>runtests.py
<ide>
<ide>
<ide> PYTEST_ARGS = {
<del> 'default': ['tests'],
<del> 'fast': ['tests', '-q'],
<add> 'default': ['tests', '--tb=short'],
<add> 'fast': ['tests', '--tb=short', '-q'],
<ide> }
<ide>
<ide> FLAKE8_ARGS = ['rest_framework', 'tests', '--ignore=E501']
| 1
|
PHP
|
PHP
|
remove the type hint from the signature
|
6c2892f04dcbbd0c294cf60f2b82e4351d3231cc
|
<ide><path>src/Illuminate/Foundation/Application.php
<ide> public function abort($code, $message = '', array $headers = [])
<ide> /**
<ide> * Register a terminating callback with the application.
<ide> *
<del> * @param \Closure $callback
<add> * @param mixed $callback
<ide> * @return $this
<ide> */
<del> public function terminating(Closure $callback)
<add> public function terminating($callback)
<ide> {
<ide> $this->terminatingCallbacks[] = $callback;
<ide>
| 1
|
Javascript
|
Javascript
|
use chrome on mac
|
95cdb53e83994d14d6f30716d47ba0f8c33e491c
|
<ide><path>protractor-travis-conf.js
<ide> config.sauceKey = process.env.SAUCE_ACCESS_KEY;
<ide>
<ide> config.multiCapabilities = [{
<ide> 'browserName': 'chrome',
<add> 'platform': 'OS X 10.9',
<ide> 'name': 'Angular E2E',
<ide> 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
<ide> 'build': process.env.TRAVIS_BUILD_NUMBER,
| 1
|
Java
|
Java
|
add sap hana to common jpa database platforms
|
504e2768de904cd9c653e9f22b6d99a0ec26697a
|
<ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/vendor/AbstractJpaVendorAdapter.java
<ide> public abstract class AbstractJpaVendorAdapter implements JpaVendorAdapter {
<ide>
<ide> /**
<ide> * Specify the target database to operate on, as a value of the {@code Database} enum:
<del> * DB2, DERBY, H2, HSQL, INFORMIX, MYSQL, ORACLE, POSTGRESQL, SQL_SERVER, SYBASE
<add> * DB2, DERBY, H2, HANA, HSQL, INFORMIX, MYSQL, ORACLE, POSTGRESQL, SQL_SERVER, SYBASE
<ide> * <p><b>NOTE:</b> This setting will override your JPA provider's default algorithm.
<ide> * Custom vendor properties may still fine-tune the database dialect. However,
<ide> * there may nevertheless be conflicts: For example, specify either this setting
<ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/vendor/Database.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public enum Database {
<ide>
<ide> DERBY,
<ide>
<add> /** @since 2.5.5 */
<ide> H2,
<ide>
<add> /** @since 5.1 */
<add> HANA,
<add>
<ide> HSQL,
<ide>
<ide> INFORMIX,
<ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/vendor/EclipseLinkJpaVendorAdapter.java
<ide> protected String determineTargetDatabaseName(Database database) {
<ide> switch (database) {
<ide> case DB2: return TargetDatabase.DB2;
<ide> case DERBY: return TargetDatabase.Derby;
<add> case HANA: return TargetDatabase.HANA;
<ide> case HSQL: return TargetDatabase.HSQL;
<ide> case INFORMIX: return TargetDatabase.Informix;
<del> case MYSQL: return TargetDatabase.MySQL4;
<add> case MYSQL: return TargetDatabase.MySQL;
<ide> case ORACLE: return TargetDatabase.Oracle;
<ide> case POSTGRESQL: return TargetDatabase.PostgreSQL;
<ide> case SQL_SERVER: return TargetDatabase.SQLServer;
<ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaVendorAdapter.java
<ide> import org.hibernate.dialect.DB2Dialect;
<ide> import org.hibernate.dialect.DerbyTenSevenDialect;
<ide> import org.hibernate.dialect.H2Dialect;
<add>import org.hibernate.dialect.HANAColumnStoreDialect;
<ide> import org.hibernate.dialect.HSQLDialect;
<ide> import org.hibernate.dialect.InformixDialect;
<ide> import org.hibernate.dialect.MySQL5Dialect;
<ide> protected Class<?> determineDatabaseDialectClass(Database database) {
<ide> case DB2: return DB2Dialect.class;
<ide> case DERBY: return DerbyTenSevenDialect.class;
<ide> case H2: return H2Dialect.class;
<add> case HANA: return HANAColumnStoreDialect.class;
<ide> case HSQL: return HSQLDialect.class;
<ide> case INFORMIX: return InformixDialect.class;
<ide> case MYSQL: return MySQL5Dialect.class;
| 4
|
Text
|
Text
|
make link to configuring guide relative [ci skip]
|
b5397600144a640f0958c7665d300a725ba4df76
|
<ide><path>guides/source/testing.md
<ide> Notice the 'E' in the output. It denotes a test with error.
<ide> NOTE: The execution of each test method stops as soon as any error or an
<ide> assertion failure is encountered, and the test suite continues with the next
<ide> method. All test methods are executed in random order. The
<del>[`config.active_support.test_order` option](http://edgeguides.rubyonrails.org/configuring.html#configuring-active-support)
<add>[`config.active_support.test_order` option](configuring.html#configuring-active-support)
<ide> can be used to configure test order.
<ide>
<ide> When a test fails you are presented with the corresponding backtrace. By default
| 1
|
Ruby
|
Ruby
|
add regression test for nameerror#name
|
bd3fde093112275bef5ab71bfac7ca17e43af8b8
|
<ide><path>activesupport/lib/active_support/dependencies.rb
<ide> def const_missing(const_name)
<ide> # top-level constant.
<ide> def guess_for_anonymous(const_name)
<ide> if Object.const_defined?(const_name)
<del> raise NameError.new "#{const_name} cannot be autoloaded from an anonymous class or module", const_name
<add> raise NameError.new "#{const_name} cannot be autoloaded from an anonymous class or module", const_name.to_s
<ide> else
<ide> Object
<ide> end
<ide><path>activesupport/test/dependencies_test.rb
<ide> def test_non_existing_const_raises_name_error_with_fully_qualified_name
<ide> with_autoloading_fixtures do
<ide> e = assert_raise(NameError) { A::DoesNotExist.nil? }
<ide> assert_equal "uninitialized constant A::DoesNotExist", e.message
<add> assert_equal "A::DoesNotExist", e.name
<ide>
<ide> e = assert_raise(NameError) { A::B::DoesNotExist.nil? }
<ide> assert_equal "uninitialized constant A::B::DoesNotExist", e.message
<add> assert_equal "A::B::DoesNotExist", e.name
<ide> end
<ide> end
<ide>
<ide> def test_const_missing_in_anonymous_modules_raises_if_the_constant_belongs_to_Ob
<ide> mod = Module.new
<ide> e = assert_raise(NameError) { mod::E }
<ide> assert_equal 'E cannot be autoloaded from an anonymous class or module', e.message
<add> assert_equal 'E', e.name
<ide> end
<ide> end
<ide>
<ide> def test_access_unloaded_constants_for_reload
<ide> assert_kind_of Class, A::B # Necessary to load A::B for the test
<ide> ActiveSupport::Dependencies.mark_for_unload(A::B)
<ide> ActiveSupport::Dependencies.remove_unloadable_constants!
<del>
<add>
<ide> A::B # Make sure no circular dependency error
<ide> end
<ide> end
| 2
|
Text
|
Text
|
add documentation for shallow testing
|
f6804d2504ae4112cfc5fa509f5a539c363f577e
|
<ide><path>docs/docs/10.4-test-utils.md
<ide> next: clone-with-props.html
<ide>
<ide> `React.addons.TestUtils` makes it easy to test React components in the testing framework of your choice (we use [Jest](http://facebook.github.io/jest/)).
<ide>
<add>## Shallow rendering
<add>
<add>Shallow rendering allows you to render a component "one level deep" and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered. This does not require a DOM.
<add>
<add>```javascript
<add>ReactShallowRenderer createRenderer()
<add>```
<add>
<add>Call this in your tests to create a shallow renderer. You can think of this as a "place" to render the component you're testing, where it can respond to events and update itself.
<add>
<add>```javascript
<add>shallowRenderer.render(ReactElement element)
<add>```
<add>
<add>Similar to `React.render`.
<add>
<add>```javascript
<add>ReactComponent shallowRenderer.getRenderOutput()
<add>```
<add>
<add>After render has been called, returns shallowly rendered output. You can then begin to assert facts about the output. For example, if your component's render method returns:
<add>
<add>```javascript
<add><div>
<add> <span className="heading">Title</span>
<add> <Subcomponent foo="bar" />
<add></div>
<add>```
<add>
<add>Then you can assert:
<add>
<add>```javascript
<add>result = renderer.getRenderOutput();
<add>expect(result.type).toBe('div');
<add>expect(result.props.children).toEqual([
<add> <span className="heading">Title</span>
<add> <Subcomponent foo="bar" />
<add>]);
<add>```
<add>
<ide> ### Simulate
<ide>
<ide> ```javascript
| 1
|
PHP
|
PHP
|
fix merge conflicts
|
40e2cf765ba603d03f7c37c8f3edde537d4b22d6
|
<ide><path>src/Illuminate/Http/Request.php
<ide> public function only($keys)
<ide> {
<ide> $keys = is_array($keys) ? $keys : func_get_args();
<ide>
<del> return array_only($this->all(), $keys) + array_fill_keys($keys, null);
<add> $results = [];
<add>
<add> $input = $this->all();
<add>
<add> foreach ($keys as $key)
<add> {
<add> array_set($results, $key, array_get($input, $key, null));
<add> }
<add>
<add> return $results;
<ide> }
<ide>
<ide> /**
<ide><path>tests/Http/HttpRequestTest.php
<ide> public function testOnlyMethod()
<ide> $request = Request::create('/', 'GET', array('name' => 'Taylor', 'age' => 25));
<ide> $this->assertEquals(array('age' => 25), $request->only('age'));
<ide> $this->assertEquals(array('name' => 'Taylor', 'age' => 25), $request->only('name', 'age'));
<add>
<add> $request = Request::create('/', 'GET', array('developer' => array('name' => 'Taylor', 'age' => 25)));
<add> $this->assertEquals(array('developer' => array('age' => 25)), $request->only('developer.age'));
<add> $this->assertEquals(array('developer' => array('name' => 'Taylor'), 'test' => null), $request->only('developer.name', 'test'));
<ide> }
<ide>
<ide>
| 2
|
Ruby
|
Ruby
|
move the validations helpermethods to its own file
|
bfd4e6a0bc70e54d768b89c4ae8000cf50a87ec3
|
<ide><path>activemodel/lib/active_model/validations/helper_methods.rb
<add>module ActiveModel
<add> module Validations
<add> module HelperMethods
<add> private
<add> def _merge_attributes(attr_names)
<add> options = attr_names.extract_options!.symbolize_keys
<add> attr_names.flatten!
<add> options[:attributes] = attr_names
<add> options
<add> end
<add> end
<add> end
<add>end
<ide><path>activemodel/lib/active_model/validations/with.rb
<ide> module ActiveModel
<ide> module Validations
<del> module HelperMethods
<del> private
<del> def _merge_attributes(attr_names)
<del> options = attr_names.extract_options!.symbolize_keys
<del> attr_names.flatten!
<del> options[:attributes] = attr_names
<del> options
<del> end
<del> end
<del>
<ide> class WithValidator < EachValidator # :nodoc:
<ide> def validate_each(record, attr, val)
<ide> method_name = options[:with]
| 2
|
Text
|
Text
|
use new mailing list
|
c6f8887deb892f9ad34cb70a97aa195d40b040e0
|
<ide><path>docs/New-Maintainer-Checklist.md
<ide> If they accept, follow a few steps to get them set up:
<ide> - Ask them to sign in to [Bintray](https://bintray.com) using their GitHub account and they should auto-sync to [Bintray's Homebrew organisation](https://bintray.com/homebrew/organization/edit/members) as a member so they can publish new bottles
<ide> - Add them to the [Jenkins' GitHub Authorization Settings admin user names](https://jenkins.brew.sh/configureSecurity/) so they can adjust settings and restart jobs
<ide> - Add them to the [Jenkins' GitHub Pull Request Builder admin list](https://jenkins.brew.sh/configure) to enable `@BrewTestBot test this please` for them
<del>- Invite them to the [`homebrew-dev` private maintainers mailing list](https://groups.google.com/forum/#!managemembers/homebrew-dev/invite)
<add>- Invite them to the [`homebrew-maintainers` private maintainers mailing list](https://lists.sfconservancy.org/mailman/admin/homebrew-maintainers/members/add)
<ide> - Invite them to the [`machomebrew` private maintainers Slack](https://machomebrew.slack.com/admin/invites)
<ide> - Invite them to the [`homebrew` private maintainers 1Password](https://homebrew.1password.com/signin)
<ide> - Invite them to [Google Analytics](https://analytics.google.com/analytics/web/?authuser=1#management/Settings/a76679469w115400090p120682403/%3Fm.page%3DAccountUsers/)
| 1
|
Go
|
Go
|
remove daemon.vxsubnets duplicate code
|
3c5932086af51f57c497690ce3cf18a906b700cf
|
<ide><path>daemon/cluster/cluster.go
<ide> var errSwarmCertificatesExpired = errors.New("Swarm certificates have expired. T
<ide> // NetworkSubnetsProvider exposes functions for retrieving the subnets
<ide> // of networks managed by Docker, so they can be filtered.
<ide> type NetworkSubnetsProvider interface {
<del> V4Subnets() []net.IPNet
<del> V6Subnets() []net.IPNet
<add> Subnets() ([]net.IPNet, []net.IPNet)
<ide> }
<ide>
<ide> // Config provides values for Cluster.
<ide><path>daemon/cluster/listen_addr.go
<ide> func (c *Cluster) resolveSystemAddrViaSubnetCheck() (net.IP, error) {
<ide> var systemInterface string
<ide>
<ide> // List Docker-managed subnets
<del> v4Subnets := c.config.NetworkSubnetsProvider.V4Subnets()
<del> v6Subnets := c.config.NetworkSubnetsProvider.V6Subnets()
<add> v4Subnets, v6Subnets := c.config.NetworkSubnetsProvider.Subnets()
<ide>
<ide> ifaceLoop:
<ide> for _, intf := range interfaces {
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) Unmount(container *container.Container) error {
<ide> return nil
<ide> }
<ide>
<del>// V4Subnets returns the IPv4 subnets of networks that are managed by Docker.
<del>func (daemon *Daemon) V4Subnets() []net.IPNet {
<del> var subnets []net.IPNet
<add>// Subnets return the IPv4 and IPv6 subnets of networks that are manager by Docker.
<add>func (daemon *Daemon) Subnets() ([]net.IPNet, []net.IPNet) {
<add> var v4Subnets []net.IPNet
<add> var v6Subnets []net.IPNet
<ide>
<ide> managedNetworks := daemon.netController.Networks()
<ide>
<ide> for _, managedNetwork := range managedNetworks {
<del> v4Infos, _ := managedNetwork.Info().IpamInfo()
<del> for _, v4Info := range v4Infos {
<del> if v4Info.IPAMData.Pool != nil {
<del> subnets = append(subnets, *v4Info.IPAMData.Pool)
<add> v4infos, v6infos := managedNetwork.Info().IpamInfo()
<add> for _, info := range v4infos {
<add> if info.IPAMData.Pool != nil {
<add> v4Subnets = append(v4Subnets, *info.IPAMData.Pool)
<ide> }
<ide> }
<del> }
<del>
<del> return subnets
<del>}
<del>
<del>// V6Subnets returns the IPv6 subnets of networks that are managed by Docker.
<del>func (daemon *Daemon) V6Subnets() []net.IPNet {
<del> var subnets []net.IPNet
<del>
<del> managedNetworks := daemon.netController.Networks()
<del>
<del> for _, managedNetwork := range managedNetworks {
<del> _, v6Infos := managedNetwork.Info().IpamInfo()
<del> for _, v6Info := range v6Infos {
<del> if v6Info.IPAMData.Pool != nil {
<del> subnets = append(subnets, *v6Info.IPAMData.Pool)
<add> for _, info := range v6infos {
<add> if info.IPAMData.Pool != nil {
<add> v6Subnets = append(v6Subnets, *info.IPAMData.Pool)
<ide> }
<ide> }
<ide> }
<ide>
<del> return subnets
<add> return v4Subnets, v6Subnets
<ide> }
<ide>
<ide> // GraphDriverName returns the name of the graph driver used by the layer.Store
| 3
|
Text
|
Text
|
fix incorrect link in version-history.md
|
6d66743ae3da148adbd29fb7e0c0433e93fec12b
|
<ide><path>docs/api/version-history.md
<ide> keywords: "API, Docker, rcli, REST, documentation"
<ide>
<ide> ## v1.37 API changes
<ide>
<del>[Docker Engine API v1.37](https://docs.docker.com/engine/api/v1.36/) documentation
<add>[Docker Engine API v1.37](https://docs.docker.com/engine/api/v1.37/) documentation
<ide>
<ide> * `POST /containers/create` and `POST /services/create` now supports exposing SCTP ports.
<ide> * `POST /configs/create` and `POST /configs/{id}/create` now accept a `Templating` driver.
| 1
|
Text
|
Text
|
update doc for options.ticks.maxtickslimit
|
3d15e1ff54045e7f449139a2fc8e70e29d558fd2
|
<ide><path>docs/01-Scales.md
<ide> The radial linear scale extends the core scale class with the following tick tem
<ide>
<ide> //Number - The backdrop padding to the side of the label in pixels
<ide> backdropPaddingX: 2,
<add>
<add> //Number - Limit the maximum number of ticks
<add> maxTicksLimit: 11,
<ide> },
<ide>
<ide> pointLabels: {
| 1
|
Python
|
Python
|
return the correct error code from breeze shell
|
9fd54b7397f81cf71325a98099d44fa33555c612
|
<ide><path>dev/breeze/src/airflow_breeze/commands/developer_commands.py
<ide> def run_shell(verbose: bool, dry_run: bool, shell_params: ShellParams) -> RunCom
<ide> get_console().print(f"[red]Error {command_result.returncode} returned[/]")
<ide> if verbose:
<ide> get_console().print(command_result.stderr)
<del> sys.exit(1)
<add> sys.exit(command_result.returncode)
<ide>
<ide>
<ide> def stop_exec_on_error(returncode: int):
| 1
|
Go
|
Go
|
fix race condition during socket creation
|
24c73ce2d3d572313fe56bad08819e0ca8b74d26
|
<ide><path>api/server/server.go
<ide> func ListenAndServe(proto, addr string, job *engine.Job) error {
<ide> }
<ide> }
<ide>
<add> var oldmask int
<add> if proto == "unix" {
<add> oldmask = syscall.Umask(0777)
<add> }
<add>
<ide> if job.GetenvBool("BufferRequests") {
<ide> l, err = listenbuffer.NewListenBuffer(proto, addr, activationLock)
<ide> } else {
<ide> l, err = net.Listen(proto, addr)
<ide> }
<add>
<add> if proto == "unix" {
<add> syscall.Umask(oldmask)
<add> }
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func ListenAndServe(proto, addr string, job *engine.Job) error {
<ide> log.Println("/!\\ DON'T BIND ON ANOTHER IP ADDRESS THAN 127.0.0.1 IF YOU DON'T KNOW WHAT YOU'RE DOING /!\\")
<ide> }
<ide> case "unix":
<del> if err := os.Chmod(addr, 0660); err != nil {
<del> return err
<del> }
<ide> socketGroup := job.Getenv("SocketGroup")
<ide> if socketGroup != "" {
<ide> if err := changeGroup(addr, socketGroup); err != nil {
<ide> func ListenAndServe(proto, addr string, job *engine.Job) error {
<ide> }
<ide> }
<ide> }
<add> if err := os.Chmod(addr, 0660); err != nil {
<add> return err
<add> }
<ide> default:
<ide> return fmt.Errorf("Invalid protocol format.")
<ide> }
| 1
|
Python
|
Python
|
fix elasticsearch breaking the build
|
b7ca0dd23a3071c6e44aeb1dabca9928dde38702
|
<ide><path>setup.py
<ide> def write_version(filename: str = os.path.join(*[dirname(__file__), "airflow", "
<ide> 'pydruid>=0.4.1,<=0.5.8',
<ide> ]
<ide> elasticsearch = [
<del> 'elasticsearch>7',
<add> 'elasticsearch>7, <7.6.0',
<ide> 'elasticsearch-dbapi==0.1.0',
<ide> 'elasticsearch-dsl>=5.0.0',
<ide> ]
| 1
|
PHP
|
PHP
|
clarify api doc
|
87991412bd13892844dcd9171c2ff05a4e8cc427
|
<ide><path>src/Controller/Controller.php
<ide> class Controller implements EventListener {
<ide> public $View;
<ide>
<ide> /**
<del> * These properties are settable directly on Controller and passed to the View as options.
<add> * These properties are will be passed from the controller properties to the View as options.
<ide> *
<ide> * @var array
<ide> * @see \Cake\View\View
| 1
|
Go
|
Go
|
remove redundant ip_forward check
|
6a0050d0f0600cf17c0fe5dcca0d24d65e70d818
|
<ide><path>daemon/create.go
<ide> func (daemon *Daemon) Create(config *runconfig.Config, hostConfig *runconfig.Hos
<ide> if err := daemon.mergeAndVerifyConfig(config, img); err != nil {
<ide> return nil, nil, err
<ide> }
<del> if !config.NetworkDisabled && daemon.SystemConfig().IPv4ForwardingDisabled {
<del> warnings = append(warnings, "IPv4 forwarding is disabled.")
<del> }
<ide> if hostConfig == nil {
<ide> hostConfig = &runconfig.HostConfig{}
<ide> }
| 1
|
Javascript
|
Javascript
|
add lang to payload if payload doesn't exist
|
63875316d9df4983c477600dac427f1bed899ae2
|
<ide><path>common/app/Router/redux/add-lang-enhancer.js
<ide> import { langSelector } from './';
<ide>
<ide> // This enhancers sole purpose is to add the lang prop to route actions so that
<del>// they do not need to be explicitally added when using a RFR route action.
<add>// they do not need to be explicitly added when using a RFR route action.
<ide> export default function addLangToRouteEnhancer(routesMap) {
<ide> return createStore => (...args) => {
<ide> const store = createStore(...args);
<ide> export default function addLangToRouteEnhancer(routesMap) {
<ide> dispatch(action) {
<ide> if (
<ide> routesMap[action.type] &&
<del> (action && action.payload && !action.payload.lang)
<add> (!action.payload || !action.payload.lang)
<ide> ) {
<ide> action = {
<ide> ...action,
| 1
|
Java
|
Java
|
apply compiler conventions to test fixtures
|
51fa98a1b2a1e63ce3d0bbfe72db187b727437cb
|
<ide><path>buildSrc/src/main/java/org/springframework/build/compile/CompilerConventionsPlugin.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * with a dedicated property on the CLI: {@code "./gradlew test -PjavaSourceVersion=11"}.
<ide> *
<ide> * @author Brian Clozel
<add> * @author Sam Brannen
<ide> */
<ide> public class CompilerConventionsPlugin implements Plugin<Project> {
<ide>
<ide> /**
<ide> * The project property that can be used to switch the Java source
<ide> * compatibility version for building source and test classes.
<ide> */
<del> public static String JAVA_SOURCE_VERSION_PROPERTY = "javaSourceVersion";
<add> public static final String JAVA_SOURCE_VERSION_PROPERTY = "javaSourceVersion";
<ide>
<del> public static JavaVersion DEFAULT_COMPILER_VERSION = JavaVersion.VERSION_1_8;
<add> public static final JavaVersion DEFAULT_COMPILER_VERSION = JavaVersion.VERSION_1_8;
<ide>
<del> private static List<String> COMPILER_ARGS;
<add> private static final List<String> COMPILER_ARGS;
<ide>
<del> private static List<String> TEST_COMPILER_ARGS;
<add> private static final List<String> TEST_COMPILER_ARGS;
<ide>
<ide> static {
<ide> List<String> commonCompilerArgs = Arrays.asList(
<ide> public void apply(Project project) {
<ide> }
<ide>
<ide> /**
<del> * Applies the common Java compiler options for sources and test sources.
<add> * Applies the common Java compiler options for main sources, test fixture sources, and
<add> * test sources.
<ide> * @param project the current project
<ide> */
<ide> private void applyJavaCompileConventions(Project project) {
<ide> private void applyJavaCompileConventions(Project project) {
<ide> compileTask.getOptions().setEncoding("UTF-8");
<ide> });
<ide> project.getTasks().withType(JavaCompile.class)
<del> .matching(javaCompile -> javaCompile.getName().equals(JavaPlugin.COMPILE_TEST_JAVA_TASK_NAME))
<add> .matching(javaCompile -> javaCompile.getName().equals(JavaPlugin.COMPILE_TEST_JAVA_TASK_NAME)
<add> || javaCompile.getName().equals("compileTestFixturesJava"))
<ide> .forEach(compileTask -> {
<ide> compileTask.getOptions().setCompilerArgs(TEST_COMPILER_ARGS);
<ide> compileTask.getOptions().setEncoding("UTF-8");
<ide> });
<ide> }
<del>}
<ide>\ No newline at end of file
<add>
<add>}
<ide><path>spring-aop/src/testFixtures/java/org/springframework/aop/testfixture/advice/MethodCounter.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> *
<ide> * @author Rod Johnson
<ide> * @author Chris Beams
<add> * @author Sam Brannen
<ide> */
<ide> @SuppressWarnings("serial")
<ide> public class MethodCounter implements Serializable {
<ide> protected void count(Method m) {
<ide> }
<ide>
<ide> protected void count(String methodName) {
<del> Integer i = map.get(methodName);
<del> i = (i != null) ? new Integer(i.intValue() + 1) : new Integer(1);
<del> map.put(methodName, i);
<add> map.merge(methodName, 1, (n, m) -> n + 1);
<ide> ++allCount;
<ide> }
<ide>
<ide> public int getCalls(String methodName) {
<del> Integer i = map.get(methodName);
<del> return (i != null ? i.intValue() : 0);
<add> return map.getOrDefault(methodName, 0);
<ide> }
<ide>
<ide> public int getCalls() {
<ide><path>spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/TestBean.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOt
<ide>
<ide> private Date date = new Date();
<ide>
<del> private Float myFloat = new Float(0.0);
<add> private Float myFloat = Float.valueOf(0.0f);
<ide>
<ide> private Collection<? super Object> friends = new LinkedList<>();
<ide>
| 3
|
Python
|
Python
|
add type hints
|
7e2ecf2e48e1b988463a021849ca4ae85991e055
|
<ide><path>libcloud/common/vultr.py
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<ide>
<del>from typing import Dict
<add>from typing import Dict, Optional, Any
<ide>
<ide> from libcloud.common.base import ConnectionKey, JsonResponse
<ide> from libcloud.compute.base import VolumeSnapshot
<ide> class VultrNetwork:
<ide> Represents information about a Vultr private network.
<ide> """
<ide>
<del> def __init__(self, id, cidr_block, location, extra=None):
<add> def __init__(self,
<add> id: str,
<add> cidr_block: str,
<add> location: str,
<add> extra: Optional[Dict[str, Any]] = None
<add> ) -> None:
<ide> self.id = id
<ide> self.cidr_block = cidr_block
<ide> self.location = location
<ide><path>libcloud/compute/drivers/vultr.py
<ide> import json
<ide> import base64
<ide> from functools import update_wrapper
<add>from typing import Optional, List, Dict, Union, Any
<ide>
<ide> from libcloud.common.base import ConnectionKey, JsonResponse
<ide> from libcloud.common.types import InvalidCredsError
<ide> class VultrNodeDriverV2(VultrNodeDriver):
<ide> 'pending': VolumeSnapshotState.CREATING,
<ide> }
<ide>
<del> def list_nodes(self, ex_list_bare_metals=True):
<add> def list_nodes(self, ex_list_bare_metals: bool = True) -> List[Node]:
<ide> """List all nodes.
<ide>
<ide> :keyword ex_list_bare_metals: Whether to fetch bare metal nodes.
<ide> def list_nodes(self, ex_list_bare_metals=True):
<ide> nodes += self.ex_list_bare_metal_nodes()
<ide> return nodes
<ide>
<del> def create_node(self, name, size, location, image=None,
<del> ex_ssh_key_ids=None, ex_private_network_ids=None,
<del> ex_snapshot=None, ex_enable_ipv6=False, ex_backups=False,
<del> ex_userdata=None, ex_ddos_protection=False,
<del> ex_enable_private_network=False, ex_ipxe_chain_url=None,
<del> ex_iso_id=None, ex_script_id=None, ex_image_id=None,
<del> ex_activation_email=False, ex_hostname=None, ex_tag=None,
<del> ex_firewall_group_id=None, ex_reserved_ipv4=None,
<del> ex_persistent_pxe=False):
<add> def create_node(self,
<add> name: str,
<add> size: NodeSize,
<add> location: NodeLocation,
<add> image: Optional[NodeImage] = None,
<add> ex_ssh_key_ids: Optional[List[str]] = None,
<add> ex_private_network_ids: Optional[List[str]] = None,
<add> ex_snapshot: Union[VultrNodeSnapshot, str, None] = None,
<add> ex_enable_ipv6: bool = False,
<add> ex_backups: bool = False,
<add> ex_userdata: Optional[str] = None,
<add> ex_ddos_protection: bool = False,
<add> ex_enable_private_network: bool = False,
<add> ex_ipxe_chain_url: Optional[str] = None,
<add> ex_iso_id: Optional[str] = None,
<add> ex_script_id: Optional[str] = None,
<add> ex_image_id: Optional[str] = None,
<add> ex_activation_email: bool = False,
<add> ex_hostname: Optional[str] = None,
<add> ex_tag: Optional[str] = None,
<add> ex_firewall_group_id: Optional[str] = None,
<add> ex_reserved_ipv4: Optional[str] = None,
<add> ex_persistent_pxe: bool = False
<add> ) -> Node:
<ide> """Create a new node.
<ide>
<ide> :param name: The new node's name.
<ide> def create_node(self, name, size, location, image=None,
<ide> method='POST')
<ide> return self._to_node(resp.object['instance'])
<ide>
<del> def reboot_node(self, node):
<add> def reboot_node(self, node: Node) -> bool:
<ide> """Reboot the given node.
<ide>
<ide> :param node: The node to be rebooted.
<ide> def reboot_node(self, node):
<ide>
<ide> return resp.success()
<ide>
<del> def start_node(self, node):
<add> def start_node(self, node: Node) -> bool:
<ide> """Start the given node.
<ide>
<ide> :param node: The node to be started.
<ide> def start_node(self, node):
<ide>
<ide> return resp.success()
<ide>
<del> def stop_node(self, node):
<add> def stop_node(self, node: Node) -> bool:
<ide> """Stop the given node.
<ide>
<ide> :param node: The node to be stopped.
<ide> def stop_node(self, node):
<ide>
<ide> return self.ex_stop_nodes([node])
<ide>
<del> def destroy_node(self, node):
<add> def destroy_node(self, node: Node) -> bool:
<ide> """Destroy the given node.
<ide>
<ide> :param node: The node to be destroyed.
<ide> def destroy_node(self, node):
<ide>
<ide> return resp.success()
<ide>
<del> def list_sizes(self, ex_list_bare_metals=True):
<add> def list_sizes(self, ex_list_bare_metals: bool = True) -> List[NodeSize]:
<ide> """List available node sizes.
<ide>
<ide> :keyword ex_list_bare_metals: Whether to fetch bare metal sizes.
<ide> def list_sizes(self, ex_list_bare_metals=True):
<ide> sizes += self.ex_list_bare_metal_sizes()
<ide> return sizes
<ide>
<del> def list_images(self):
<add> def list_images(self) -> List[NodeImage]:
<ide> """List available node images.
<ide>
<ide> :rtype: ``list`` of :class: `NodeImage`
<ide> """
<ide> data = self._paginated_request('/v2/os', 'os')
<ide> return [self._to_image(item) for item in data]
<ide>
<del> def list_locations(self):
<add> def list_locations(self) -> List[NodeLocation]:
<ide> """List available node locations.
<ide>
<ide> :rtype: ``list`` of :class: `NodeLocation`
<ide> """
<ide> data = self._paginated_request('/v2/regions', 'regions')
<ide> return [self._to_location(item) for item in data]
<ide>
<del> def list_volumes(self):
<add> def list_volumes(self) -> List[StorageVolume]:
<ide> """List storage volumes.
<ide>
<ide> :rtype: ``list`` of :class:`StorageVolume`
<ide> """
<ide> data = self._paginated_request('/v2/blocks', 'blocks')
<ide> return [self._to_volume(item) for item in data]
<ide>
<del> def create_volume(self, size, name, location):
<add> def create_volume(self,
<add> size: int,
<add> name: str,
<add> location: Union[NodeLocation, str],
<add> ) -> StorageVolume:
<ide> """Create a new volume.
<ide>
<ide> :param size: Size of the volume in gigabytes.\
<ide> def create_volume(self, size, name, location):
<ide> method='POST')
<ide> return self._to_volume(resp.object['block'])
<ide>
<del> def attach_volume(self, node, volume, ex_live=True):
<add> def attach_volume(self,
<add> node: Node,
<add> volume: StorageVolume,
<add> ex_live: bool = True,
<add> ) -> bool:
<ide> """Attaches volume to node.
<ide>
<ide> :param node: Node to attach volume to.
<ide> def attach_volume(self, node, volume, ex_live=True):
<ide>
<ide> return resp.success()
<ide>
<del> def detach_volume(self, volume, ex_live=True):
<add> def detach_volume(self,
<add> volume: StorageVolume,
<add> ex_live: bool = True,
<add> ) -> bool:
<ide> """Detaches a volume from a node.
<ide>
<ide> :param volume: Volume to be detached
<ide> def detach_volume(self, volume, ex_live=True):
<ide>
<ide> return resp.success()
<ide>
<del> def destroy_volume(self, volume):
<add> def destroy_volume(self, volume: StorageVolume) -> bool:
<ide> """Destroys a storage volume.
<ide>
<ide> :param volume: Volume to be destroyed
<ide> def destroy_volume(self, volume):
<ide>
<ide> return resp.success()
<ide>
<del> def list_key_pairs(self):
<add> def list_key_pairs(self) -> List[KeyPair]:
<ide> """List all the available SSH key pair objects.
<ide>
<ide> :rtype: ``list`` of :class:`KeyPair`
<ide> """
<ide> data = self._paginated_request('/v2/ssh-keys', 'ssh_keys')
<ide> return [self._to_key_pair(item) for item in data]
<ide>
<del> def get_key_pair(self, key_id):
<add> def get_key_pair(self, key_id: str) -> KeyPair:
<ide> """Retrieve a single key pair.
<ide>
<ide> :param key_id: ID of the key pair to retrieve.
<ide> def get_key_pair(self, key_id):
<ide> resp = self.connection.request('/v2/ssh-keys/%s' % key_id)
<ide> return self._to_key_pair(resp.object['ssh_key'])
<ide>
<del> def import_key_pair_from_string(self, name, key_material):
<add> def import_key_pair_from_string(self,
<add> name: str,
<add> key_material: str
<add> ) -> KeyPair:
<ide> """Import a new public key from string.
<ide>
<ide> :param name: Key pair name.
<ide> def import_key_pair_from_string(self, name, key_material):
<ide> method='POST')
<ide> return self._to_key_pair(resp.object['ssh_key'])
<ide>
<del> def delete_key_pair(self, key_pair):
<add> def delete_key_pair(self, key_pair: KeyPair) -> bool:
<ide> """Delete existing key pair.
<ide>
<ide> :param key_pair: The key pair object to delete.
<ide> def delete_key_pair(self, key_pair):
<ide>
<ide> return resp.success()
<ide>
<del> def ex_list_bare_metal_nodes(self):
<add> def ex_list_bare_metal_nodes(self) -> List[Node]:
<ide> """List all bare metal nodes.
<ide>
<ide> :return: list of node objects
<ide> def ex_list_bare_metal_nodes(self):
<ide> data = self._paginated_request('/v2/bare-metals', 'bare_metals')
<ide> return [self._to_node(item) for item in data]
<ide>
<del> def ex_reboot_bare_metal_node(self, node):
<add> def ex_reboot_bare_metal_node(self, node: Node) -> bool:
<ide> """Reboot the given bare metal node.
<ide>
<ide> :param node: The bare metal node to be rebooted.
<ide> def ex_reboot_bare_metal_node(self, node):
<ide>
<ide> return resp.success()
<ide>
<del> def ex_resize_node(self, node, size):
<add> def ex_resize_node(self, node: Node, size: NodeSize) -> bool:
<ide> """Change size for the given node, only applicable for VPS nodes.
<ide>
<ide> :param node: The node to be resized.
<ide> def ex_resize_node(self, node, size):
<ide> method='PATCH')
<ide> return self._to_node(resp.object['instance'])
<ide>
<del> def ex_start_bare_metal_node(self, node):
<add> def ex_start_bare_metal_node(self, node: Node) -> bool:
<ide> """Start the given bare metal node.
<ide>
<ide> :param node: The bare metal node to be started.
<ide> def ex_start_bare_metal_node(self, node):
<ide>
<ide> return resp.success()
<ide>
<del> def ex_stop_bare_metal_node(self, node):
<add> def ex_stop_bare_metal_node(self, node: Node) -> bool:
<ide> """Stop the given bare metal node.
<ide>
<ide> :param node: The bare metal node to be stopped.
<ide> def ex_stop_bare_metal_node(self, node):
<ide>
<ide> return resp.success()
<ide>
<del> def ex_destroy_bare_metal_node(self, node):
<add> def ex_destroy_bare_metal_node(self, node: Node) -> bool:
<ide> """Destroy the given bare metal node.
<ide>
<ide> :param node: The bare metal node to be destroyed.
<ide> def ex_destroy_bare_metal_node(self, node):
<ide>
<ide> return resp.success()
<ide>
<del> def ex_get_node(self, node_id):
<add> def ex_get_node(self, node_id: str) -> Node:
<ide> """Retrieve a node object.
<ide>
<ide> :param node_id: ID of the node to retrieve.
<ide> def ex_get_node(self, node_id):
<ide> resp = self.connection.request('/v2/instances/%s' % node_id)
<ide> return self._to_node(resp.object['instance'])
<ide>
<del> def ex_stop_nodes(self, nodes):
<add> def ex_stop_nodes(self, nodes: List[Node]) -> bool:
<ide> """Stops all the nodes given.
<ide>
<ide> : param nodes: A list of the nodes to stop.
<ide> def ex_stop_nodes(self, nodes):
<ide>
<ide> return resp.success()
<ide>
<del> def ex_list_bare_metal_sizes(self):
<add> def ex_list_bare_metal_sizes(self) -> List[NodeSize]:
<ide> """List bare metal sizes.
<ide>
<ide> :rtype: ``list`` of :class: `NodeSize`
<ide> """
<ide> data = self._paginated_request('/v2/plans-metal', 'plans_metal')
<ide> return [self._to_size(item) for item in data]
<ide>
<del> def ex_list_snapshots(self):
<add> def ex_list_snapshots(self) -> List[VultrNodeSnapshot]:
<ide> """List node snapshots.
<ide>
<ide> :rtype: ``list`` of :class: `VultrNodeSnapshot`
<ide> """
<ide> data = self._paginated_request('/v2/snapshots', 'snapshots')
<ide> return [self._to_snapshot(item) for item in data]
<ide>
<del> def ex_get_snapshot(self, snapshot_id):
<add> def ex_get_snapshot(self, snapshot_id: str) -> VultrNodeSnapshot:
<ide> """Retrieve a snapshot.
<ide>
<ide> :param snapshot_id: ID of the snapshot to retrieve.
<ide> def ex_get_snapshot(self, snapshot_id):
<ide> resp = self.connection.request('/v2/snapshots/%s' % snapshot_id)
<ide> return self._to_snapshot(resp.object['snapshot'])
<ide>
<del> def ex_create_snapshot(self, node, description=None):
<add> def ex_create_snapshot(self,
<add> node: Node,
<add> description: Optional[str] = None
<add> ) -> VultrNodeSnapshot:
<ide> """Create snapshot from a node.
<ide>
<ide> :param node: Node to create the snapshot from.
<ide> def ex_create_snapshot(self, node, description=None):
<ide>
<ide> return self._to_snapshot(resp.object['snapshot'])
<ide>
<del> def ex_delete_snapshot(self, snapshot):
<add> def ex_delete_snapshot(self, snapshot: VultrNodeSnapshot) -> bool:
<ide> """Delete the given snapshot.
<ide>
<ide> :param snapshot: The snapshot to delete.
<ide> def ex_delete_snapshot(self, snapshot):
<ide>
<ide> return resp.success()
<ide>
<del> def ex_list_networks(self):
<add> def ex_list_networks(self) -> List[VultrNetwork]:
<ide> """List all private networks.
<ide>
<ide> :rtype: ``list`` of :class: `VultrNetwork`
<ide> def ex_list_networks(self):
<ide> data = self._paginated_request('/v2/private-networks', 'networks')
<ide> return [self._to_network(item) for item in data]
<ide>
<del> def ex_create_network(self, cidr_block, location, description=None):
<add> def ex_create_network(self,
<add> cidr_block: str,
<add> location: Union[NodeLocation, str],
<add> description: Optional[str] = None,
<add> ) -> VultrNetwork:
<ide> """Create a private network.
<ide>
<ide> :param cidr_block: The CIDR block assigned to the network.
<ide> def ex_create_network(self, cidr_block, location, description=None):
<ide>
<ide> return self._to_network(resp.object['network'])
<ide>
<del> def ex_get_network(self, network_id):
<add> def ex_get_network(self, network_id: str) -> VultrNetwork:
<ide> """Retrieve a private network.
<ide>
<ide> :param network_id: ID of the network to retrieve.
<ide> def ex_get_network(self, network_id):
<ide> resp = self.connection.request('/v2/private-networks/%s' % network_id)
<ide> return self._to_network(resp.object['network'])
<ide>
<del> def ex_destroy_network(self, network):
<add> def ex_destroy_network(self, network: VultrNetwork) -> bool:
<ide> """Delete a private network.
<ide>
<ide> :param network: The network to destroy.
<ide> def ex_destroy_network(self, network):
<ide>
<ide> return resp.success()
<ide>
<del> def ex_list_available_sizes_for_location(self, location):
<add> def ex_list_available_sizes_for_location(self,
<add> location: NodeLocation,
<add> ) -> List[str]:
<ide> """Get a list of available sizes for the given location.
<ide>
<ide> :param location: The location to get available sizes for.
<ide> def ex_list_available_sizes_for_location(self, location):
<ide> % location.id)
<ide> return resp.object['available_plans']
<ide>
<del> def ex_get_volume(self, volume_id):
<add> def ex_get_volume(self, volume_id: str) -> StorageVolume:
<ide> """Retrieve a single volume.
<ide>
<ide> :param volume_id: The ID of the volume to fetch.
<ide> def ex_get_volume(self, volume_id):
<ide>
<ide> return self._to_volume(resp.object['block'])
<ide>
<del> def ex_resize_volume(self, volume, size):
<add> def ex_resize_volume(self, volume: StorageVolume, size: int) -> bool:
<ide> """Resize a volume.
<ide>
<ide> :param volume: The volume to resize.
<ide> def ex_resize_volume(self, volume, size):
<ide> method='PATCH')
<ide> return resp.success()
<ide>
<del> def _is_bare_metal(self, size):
<add> def _is_bare_metal(self, size: Union[NodeSize, str]) -> bool:
<ide> try:
<ide> size_id = size.id
<ide> except AttributeError:
<ide> size_id = size
<ide>
<ide> return size_id.startswith('vbm')
<ide>
<del> def _to_node(self, data):
<add> def _to_node(self, data: Dict[str, Any]) -> Node:
<ide> id_ = data['id']
<ide> name = data['label']
<ide> public_ips = data['main_ip'].split() + data['v6_main_ip'].split()
<ide> def _to_node(self, data):
<ide> extra=extra,
<ide> created_at=created_at)
<ide>
<del> def _to_volume(self, data):
<add> def _to_volume(self, data: Dict[str, Any]) -> StorageVolume:
<ide> id_ = data['id']
<ide> name = data['label']
<ide> size = data['size_gb']
<ide> def _to_volume(self, data):
<ide> state=state,
<ide> extra=extra)
<ide>
<del> def _get_node_state(self, state, power_state=None):
<add> def _get_node_state(self,
<add> state: str,
<add> power_state: Optional[str] = None,
<add> ) -> NodeState:
<ide> try:
<ide> state = self.NODE_STATE_MAP[state]
<ide> except KeyError:
<ide> def _get_node_state(self, state, power_state=None):
<ide> state = NodeState.STOPPED
<ide> return state
<ide>
<del> def _to_key_pair(self, data):
<add> def _to_key_pair(self, data: Dict[str, Any]) -> KeyPair:
<ide> name = data['name']
<ide> public_key = data['ssh_key']
<ide> # requires cryptography module
<ide> def _to_key_pair(self, data):
<ide> extra=extra,
<ide> )
<ide>
<del> def _to_location(self, data):
<add> def _to_location(self, data: Dict[str, Any]) -> NodeLocation:
<ide> id_ = data['id']
<ide> name = data['city']
<ide> country = data['country']
<ide> def _to_location(self, data):
<ide> extra=extra
<ide> )
<ide>
<del> def _to_image(self, data):
<add> def _to_image(self, data: Dict[str, Any]) -> NodeImage:
<ide> id_ = data['id']
<ide> name = data['name']
<ide> extra = {
<ide> def _to_image(self, data):
<ide> driver=self,
<ide> extra=extra)
<ide>
<del> def _to_size(self, data):
<add> def _to_size(self, data: Dict[str, Any]) -> NodeSize:
<ide> id_ = data['id']
<ide> ram = data['ram']
<ide> disk = data['disk']
<ide> def _to_size(self, data):
<ide> driver=self,
<ide> extra=extra)
<ide>
<del> def _to_network(self, data):
<add> def _to_network(self, data: Dict[str, Any]) -> VultrNetwork:
<ide> id_ = data['id']
<ide> cidr_block = '%s/%s' % (data['v4_subnet'], data['v4_subnet_mask'])
<ide> location = data['region']
<ide> def _to_network(self, data):
<ide> location=location,
<ide> extra=extra)
<ide>
<del> def _to_snapshot(self, data):
<add> def _to_snapshot(self, data: Dict[str, Any]) -> VultrNodeSnapshot:
<ide> id_ = data['id']
<ide> created = data['date_created']
<ide> # Size is returned in bytes, convert to GBs
<ide> def _to_snapshot(self, data):
<ide> extra=extra,
<ide> driver=self)
<ide>
<del> def _paginated_request(self, url, key, params=None):
<add> def _paginated_request(self,
<add> url: str,
<add> key: str,
<add> params: Optional[Dict[str, Any]] = None
<add> ) -> List[Any]:
<ide> """Perform multiple calls to get the full list of items when
<ide> the API responses are paginated.
<ide>
<ide><path>libcloud/dns/drivers/vultr.py
<ide> Vultr DNS Driver
<ide> """
<ide> import json
<add>from typing import Optional, List, Dict, Any
<ide>
<ide> from libcloud.utils.py3 import urlencode
<ide> from libcloud.common.vultr import VultrConnection
<ide> class VultrDNSDriverV2(VultrDNSDriver):
<ide> RecordType.SSHFP: 'SSHFP',
<ide> }
<ide>
<del> def list_zones(self):
<add> def list_zones(self) -> List[Zone]:
<ide> """Return a list of zones.
<ide>
<ide> :return: ``list`` of :class:`Zone`
<ide> """
<ide> data = self._paginated_request('/v2/domains', 'domains')
<ide> return [self._to_zone(item) for item in data]
<ide>
<del> def get_zone(self, zone_id):
<add> def get_zone(self, zone_id: str) -> Zone:
<ide> """Return a Zone instance.
<ide>
<ide> :param zone_id: ID of the required zone
<ide> def get_zone(self, zone_id):
<ide> resp = self.connection.request('/v2/domains/%s' % zone_id)
<ide> return self._to_zone(resp.object['domain'])
<ide>
<del> def create_zone(self, domain, type='master', ttl=None, extra=None):
<add> def create_zone(self,
<add> domain: str,
<add> type: str = 'master',
<add> ttl: Optional[int] = None,
<add> extra: Optional[Dict[str, Any]] = None,
<add> ) -> Zone:
<ide> """Create a new zone.
<ide>
<ide> :param domain: Zone domain name (e.g. example.com)
<ide> def create_zone(self, domain, type='master', ttl=None, extra=None):
<ide> method='POST')
<ide> return self._to_zone(resp.object['domain'])
<ide>
<del> def delete_zone(self, zone):
<add> def delete_zone(self, zone: Zone) -> bool:
<ide> """Delete a zone.
<ide>
<ide> Note: This will delete all the records belonging to this zone.
<ide> def delete_zone(self, zone):
<ide> method='DELETE')
<ide> return resp.success()
<ide>
<del> def list_records(self, zone):
<add> def list_records(self, zone: Zone) -> List[Record]:
<ide> """Return a list of records for the provided zone.
<ide>
<ide> :param zone: Zone to list records for.
<ide> def list_records(self, zone):
<ide> 'records')
<ide> return [self._to_record(item, zone) for item in data]
<ide>
<del> def get_record(self, zone_id, record_id):
<add> def get_record(self, zone_id: str, record_id: str) -> Record:
<ide> """Return a Record instance.
<ide>
<ide> :param zone_id: ID of the required zone
<ide> def get_record(self, zone_id, record_id):
<ide>
<ide> return self._to_record(resp.object['record'], zone)
<ide>
<del> def create_record(self, name, zone, type, data, extra=None):
<add> def create_record(self,
<add> name: str,
<add> zone: Zone,
<add> type: RecordType,
<add> data: str,
<add> extra: Optional[Dict[str, Any]] = None
<add> ) -> Record:
<ide> """Create a new record.
<ide>
<ide> :param name: Record name without the domain name (e.g. www).
<ide> def create_record(self, name, zone, type, data, extra=None):
<ide>
<ide> return self._to_record(resp.object['record'], zone)
<ide>
<del> def update_record(self, record, name=None, type=None,
<del> data=None, extra=None):
<add> def update_record(self,
<add> record: Record,
<add> name: Optional[str] = None,
<add> type: Optional[RecordType] = None,
<add> data: Optional[str] = None,
<add> extra: Optional[Dict[str, Any]] = None
<add> ) -> bool:
<ide> """Update an existing record.
<ide>
<ide> :param record: Record to update.
<ide> def update_record(self, record, name=None, type=None,
<ide>
<ide> return resp.success()
<ide>
<del> def delete_record(self, record):
<add> def delete_record(self, record: Record) -> bool:
<ide> """Delete a record.
<ide>
<ide> :param record: Record to delete.
<ide> def delete_record(self, record):
<ide>
<ide> return resp.success()
<ide>
<del> def _to_zone(self, data):
<add> def _to_zone(self, data: Dict[str, Any]) -> Zone:
<ide> type_ = 'master'
<ide> domain = data['domain']
<ide> extra = {
<ide> def _to_zone(self, data):
<ide> ttl=None,
<ide> extra=extra)
<ide>
<del> def _to_record(self, data, zone):
<add> def _to_record(self, data: Dict[str, Any], zone: Zone) -> Record:
<ide> id_ = data['id']
<ide> name = data['name']
<ide> type_ = self._string_to_record_type(data['type'])
<ide> def _to_record(self, data, zone):
<ide> zone=zone,
<ide> extra=extra)
<ide>
<del> def _paginated_request(self, url, key, params=None):
<add> def _paginated_request(self,
<add> url: str,
<add> key: str,
<add> params: Optional[Dict[str, Any]] = None,
<add> ) -> List[Any]:
<ide> """Perform multiple calls to get the full list of items when
<ide> the API responses are paginated.
<ide>
| 3
|
Python
|
Python
|
add dns example
|
d8e3d5e4d693de2c73dcc0554d5ecca802c98875
|
<ide><path>example_dns.py
<add># Licensed to the Apache Software Foundation (ASF) under one or more
<add># contributor license agreements. See the NOTICE file distributed with
<add># this work for additional information regarding copyright ownership.
<add># The ASF licenses this file to You under the Apache License, Version 2.0
<add># (the "License"); you may not use this file except in compliance with
<add># the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>
<add>from pprint import pprint
<add>
<add>from libcloud.dns.types import Provider
<add>from libcloud.dns.providers import get_driver
<add>
<add>Zerigo = get_driver(Provider.ZERIGO)
<add>
<add>driver = Zerigo('email', 'key')
<add>
<add>zones = driver.list_zones()
<add>pprint(zones)
<add>
<add>records = zones[0].list_records()
<add>pprint(records)
| 1
|
PHP
|
PHP
|
add method to contract
|
b257d849d0010c9c6571a4b7c62be948470c95d8
|
<ide><path>src/Illuminate/Contracts/Events/Dispatcher.php
<ide> public function until($event, $payload = array());
<ide> */
<ide> public function fire($event, $payload = array(), $halt = false);
<ide>
<add> /**
<add> * Get the event that is currently firing.
<add> *
<add> * @return string
<add> */
<add> public function firing();
<add>
<ide> /**
<ide> * Remove a set of listeners from the dispatcher.
<ide> *
| 1
|
PHP
|
PHP
|
fix typhint to avoid test failure
|
00a6259067a990f3df8fa82feac24e540b80f93c
|
<ide><path>src/Collection/CollectionInterface.php
<ide> public function last();
<ide> * @param iterable $items Items list.
<ide> * @return \Cake\Collection\CollectionInterface
<ide> */
<del> public function append(iterable $items): CollectionInterface;
<add> public function append($items): CollectionInterface;
<ide>
<ide> /**
<ide> * Append a single item creating a new collection.
<ide><path>src/Collection/CollectionTrait.php
<ide> public function takeLast(int $howMany): CollectionInterface
<ide> /**
<ide> * @inheritDoc
<ide> */
<del> public function append(iterable $items): CollectionInterface
<add> public function append($items): CollectionInterface
<ide> {
<ide> $list = new AppendIterator();
<ide> $list->append($this->unwrap());
| 2
|
Python
|
Python
|
fix constant string values
|
f010a00959c486572466557876b30e29642d899d
|
<ide><path>libcloud/compute/types.py
<ide> class Provider(object):
<ide> @cvar ABIQUO: Abiquo driver
<ide> """
<ide> DUMMY = 'dummy'
<del> EC2 = 'ec2'
<add> EC2 = 'ec2_us_east'
<ide> RACKSPACE = 'rackspace'
<ide> SLICEHOST = 'slicehost'
<ide> GOGRID = 'gogrid'
<ide> class Provider(object):
<ide>
<ide> # Deprecated constants which are still supported
<ide> EC2_US_EAST = 'ec2_us_east'
<del> EC2_EU = 'ec2_eu' # deprecated name
<add> EC2_EU = 'ec2_eu_west' # deprecated name
<ide> EC2_EU_WEST = 'ec2_eu_west'
<ide> EC2_US_WEST = 'ec2_us_west'
<ide> EC2_AP_SOUTHEAST = 'ec2_ap_southeast'
| 1
|
Python
|
Python
|
fix module id generation on windows
|
36f017afaf034ff858b86ad0655032b229d9c8f8
|
<ide><path>tools/js2c.py
<ide> def JS2C(source, target):
<ide> lines = ExpandMacros(lines, macros)
<ide> lines = CompressScript(lines, do_jsmin)
<ide> data = ToCArray(s, lines)
<del> id = '/'.join(re.split('/|\\\\', s)[1:]).split('.')[0]
<add>
<add> # On Windows, "./foo.bar" in the .gyp file is passed as "foo.bar"
<add> # so don't assume there is always a slash in the file path.
<add> if '/' in s or '\\' in s:
<add> id = '/'.join(re.split('/|\\\\', s)[1:])
<add> else:
<add> id = s
<add>
<add> if '.' in id:
<add> id = id.split('.', 1)[0]
<add>
<ide> if delay: id = id[:-6]
<ide> if delay:
<ide> delay_ids.append((id, len(lines)))
| 1
|
Javascript
|
Javascript
|
move premultiplied_alpha chunk
|
218d8e5b252a5de6af3960865fceb361a7a82c2c
|
<ide><path>examples/js/effects/OutlineEffect.js
<ide> THREE.OutlineEffect = function ( renderer, parameters ) {
<ide>
<ide> " gl_FragColor = vec4( outlineColor, outlineAlpha );",
<ide>
<del> " #include <premultiplied_alpha_fragment>",
<ide> " #include <tonemapping_fragment>",
<ide> " #include <encodings_fragment>",
<ide> " #include <fog_fragment>",
<add> " #include <premultiplied_alpha_fragment>",
<ide>
<ide> "}"
<ide>
<ide><path>examples/js/lines/LineMaterial.js
<ide> THREE.ShaderLib[ 'line' ] = {
<ide>
<ide> gl_FragColor = vec4( diffuseColor.rgb, diffuseColor.a );
<ide>
<del> #include <premultiplied_alpha_fragment>
<ide> #include <tonemapping_fragment>
<ide> #include <encodings_fragment>
<ide> #include <fog_fragment>
<add> #include <premultiplied_alpha_fragment>
<ide>
<ide> }
<ide> `
<ide><path>examples/js/loaders/LDrawLoader.js
<ide> THREE.LDrawLoader = ( function () {
<ide> #include <color_fragment>
<ide> outgoingLight = diffuseColor.rgb; // simple shader
<ide> gl_FragColor = vec4( outgoingLight, diffuseColor.a );
<del> #include <premultiplied_alpha_fragment>
<ide> #include <tonemapping_fragment>
<ide> #include <encodings_fragment>
<ide> #include <fog_fragment>
<add> #include <premultiplied_alpha_fragment>
<ide> }
<ide> `;
<ide>
<ide><path>examples/jsm/effects/OutlineEffect.js
<ide> var OutlineEffect = function ( renderer, parameters ) {
<ide>
<ide> " gl_FragColor = vec4( outlineColor, outlineAlpha );",
<ide>
<del> " #include <premultiplied_alpha_fragment>",
<ide> " #include <tonemapping_fragment>",
<ide> " #include <encodings_fragment>",
<ide> " #include <fog_fragment>",
<add> " #include <premultiplied_alpha_fragment>",
<ide>
<ide> "}"
<ide>
<ide><path>examples/jsm/lines/LineMaterial.js
<ide> ShaderLib[ 'line' ] = {
<ide>
<ide> gl_FragColor = vec4( diffuseColor.rgb, diffuseColor.a );
<ide>
<del> #include <premultiplied_alpha_fragment>
<ide> #include <tonemapping_fragment>
<ide> #include <encodings_fragment>
<ide> #include <fog_fragment>
<add> #include <premultiplied_alpha_fragment>
<ide>
<ide> }
<ide> `
<ide><path>examples/jsm/loaders/LDrawLoader.js
<ide> var LDrawLoader = ( function () {
<ide> #include <color_fragment>
<ide> outgoingLight = diffuseColor.rgb; // simple shader
<ide> gl_FragColor = vec4( outgoingLight, diffuseColor.a );
<del> #include <premultiplied_alpha_fragment>
<ide> #include <tonemapping_fragment>
<ide> #include <encodings_fragment>
<ide> #include <fog_fragment>
<add> #include <premultiplied_alpha_fragment>
<ide> }
<ide> `;
<ide>
<ide><path>examples/jsm/nodes/materials/nodes/PhongNode.js
<ide> PhongNode.prototype.build = function ( builder ) {
<ide> }
<ide>
<ide> output.push(
<del> "#include <premultiplied_alpha_fragment>",
<ide> "#include <tonemapping_fragment>",
<ide> "#include <encodings_fragment>",
<del> "#include <fog_fragment>"
<add> "#include <fog_fragment>",
<add> "#include <premultiplied_alpha_fragment>"
<ide> );
<ide>
<ide> code = output.join( "\n" );
<ide><path>src/renderers/shaders/ShaderLib/linedashed_frag.glsl.js
<ide> void main() {
<ide>
<ide> gl_FragColor = vec4( outgoingLight, diffuseColor.a );
<ide>
<del> #include <premultiplied_alpha_fragment>
<ide> #include <tonemapping_fragment>
<ide> #include <encodings_fragment>
<ide> #include <fog_fragment>
<add> #include <premultiplied_alpha_fragment>
<ide>
<ide> }
<ide> `;
<ide><path>src/renderers/shaders/ShaderLib/meshbasic_frag.glsl.js
<ide> void main() {
<ide>
<ide> gl_FragColor = vec4( outgoingLight, diffuseColor.a );
<ide>
<del> #include <premultiplied_alpha_fragment>
<ide> #include <tonemapping_fragment>
<ide> #include <encodings_fragment>
<ide> #include <fog_fragment>
<add> #include <premultiplied_alpha_fragment>
<ide>
<ide> }
<ide> `;
<ide><path>src/renderers/shaders/ShaderLib/meshmatcap_frag.glsl.js
<ide> void main() {
<ide>
<ide> gl_FragColor = vec4( outgoingLight, diffuseColor.a );
<ide>
<del> #include <premultiplied_alpha_fragment>
<ide> #include <tonemapping_fragment>
<ide> #include <encodings_fragment>
<ide> #include <fog_fragment>
<add> #include <premultiplied_alpha_fragment>
<ide>
<ide> }
<ide> `;
<ide><path>src/renderers/shaders/ShaderLib/points_frag.glsl.js
<ide> void main() {
<ide>
<ide> gl_FragColor = vec4( outgoingLight, diffuseColor.a );
<ide>
<del> #include <premultiplied_alpha_fragment>
<ide> #include <tonemapping_fragment>
<ide> #include <encodings_fragment>
<ide> #include <fog_fragment>
<add> #include <premultiplied_alpha_fragment>
<ide>
<ide> }
<ide> `;
| 11
|
PHP
|
PHP
|
fix updateorinsert method for query builder
|
ad3bdfe0a7eeeacec18c1a6a73bcfe873e1c1edc
|
<ide><path>src/Illuminate/Database/Query/Builder.php
<ide> public function updateOrInsert(array $attributes, array $values = [])
<ide> return $this->insert(array_merge($attributes, $values));
<ide> }
<ide>
<add> if (empty($values)) {
<add> return true;
<add> }
<add>
<ide> return (bool) $this->take(1)->update($values);
<ide> }
<ide>
<ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> public function testUpdateOrInsertMethod()
<ide> $this->assertTrue($builder->updateOrInsert(['email' => 'foo'], ['name' => 'bar']));
<ide> }
<ide>
<add> public function testUpdateOrInsertMethodWorksWithEmptyUpdateValues()
<add> {
<add> $builder = m::mock(Builder::class.'[where,exists,insert]', [
<add> m::mock(ConnectionInterface::class),
<add> new Grammar,
<add> m::mock(Processor::class),
<add> ]);
<add>
<add> $builder->shouldReceive('where')->once()->with(['email' => 'foo'])->andReturn(m::self());
<add> $builder->shouldReceive('exists')->once()->andReturn(false);
<add> $builder->shouldReceive('insert')->once()->with(['email' => 'foo', 'name' => 'bar'])->andReturn(true);
<add>
<add> $this->assertTrue($builder->updateOrInsert(['email' => 'foo'], ['name' => 'bar']));
<add>
<add> $builder = m::mock(Builder::class.'[where,exists,update]', [
<add> m::mock(ConnectionInterface::class),
<add> new Grammar,
<add> m::mock(Processor::class),
<add> ]);
<add>
<add> $builder->shouldReceive('where')->once()->with(['email' => 'foo'])->andReturn(m::self());
<add> $builder->shouldReceive('exists')->once()->andReturn(true);
<add> $builder->shouldReceive('take')->andReturnSelf();
<add> $builder->shouldNotReceive('update')->with([]);
<add>
<add> $this->assertTrue($builder->updateOrInsert(['email' => 'foo']));
<add> }
<add>
<ide> public function testDeleteMethod()
<ide> {
<ide> $builder = $this->getBuilder();
| 2
|
Javascript
|
Javascript
|
add new line on ctrl+d
|
197690972c3cb8d193bfa3e1a99f3d8b4c414ee1
|
<ide><path>lib/repl.js
<ide> function REPLServer(prompt,
<ide> return;
<ide> }
<ide> if (!self.editorMode || !self.terminal) {
<add> // Before exiting, make sure to clear the line.
<add> if (key.ctrl && key.name === 'd' &&
<add> self.cursor === 0 && self.line.length === 0) {
<add> self.clearLine();
<add> }
<ide> ttyWrite(d, key);
<ide> return;
<ide> }
<ide><path>test/parallel/test-repl-save-load.js
<ide> assert.strictEqual(fs.readFileSync(saveFileName, 'utf8'),
<ide> putIn.run([`.save ${saveFileName}`]);
<ide> replServer.close();
<ide> assert.strictEqual(fs.readFileSync(saveFileName, 'utf8'),
<del> `${cmds.join('\n')}\n`);
<add> `${cmds.join('\n')}\n\n`);
<ide> }
<ide>
<ide> // make sure that the REPL data is "correct"
| 2
|
Ruby
|
Ruby
|
remove assertion, leave command
|
d843f70a3501e05d81777ef9d0e8612fcaa1a659
|
<ide><path>Library/Homebrew/test/test_tap.rb
<ide> def test_tap
<ide> assert_match "Unpinned homebrew/foo", cmd("tap-unpin", "homebrew/foo")
<ide> assert_match "Tapped", cmd("tap", "homebrew/bar", path/".git")
<ide> assert_match "Untapped", cmd("untap", "homebrew/bar")
<del> assert_match /.*/, cmd("tap", "homebrew/bar", path/".git", "-q", "--full")
<add> cmd("tap", "homebrew/bar", path/".git", "-q", "--full")
<ide> assert_match "Untapped", cmd("untap", "homebrew/bar")
<ide> end
<ide> end
| 1
|
Javascript
|
Javascript
|
add container to event listener signature
|
1000f6135efba4f8d8ebffedeb7b472f532a8475
|
<ide><path>packages/legacy-events/ReactGenericBatching.js
<ide> import {invokeGuardedCallbackAndCatchFirstError} from 'shared/ReactErrorUtils';
<ide> let batchedUpdatesImpl = function(fn, bookkeeping) {
<ide> return fn(bookkeeping);
<ide> };
<del>let discreteUpdatesImpl = function(fn, a, b, c) {
<del> return fn(a, b, c);
<add>let discreteUpdatesImpl = function(fn, a, b, c, d) {
<add> return fn(a, b, c, d);
<ide> };
<ide> let flushDiscreteUpdatesImpl = function() {};
<ide> let batchedEventUpdatesImpl = batchedUpdatesImpl;
<ide> export function executeUserEventHandler(fn: any => void, value: any): void {
<ide> }
<ide> }
<ide>
<del>export function discreteUpdates(fn, a, b, c) {
<add>export function discreteUpdates(fn, a, b, c, d) {
<ide> const prevIsInsideEventHandler = isInsideEventHandler;
<ide> isInsideEventHandler = true;
<ide> try {
<del> return discreteUpdatesImpl(fn, a, b, c);
<add> return discreteUpdatesImpl(fn, a, b, c, d);
<ide> } finally {
<ide> isInsideEventHandler = prevIsInsideEventHandler;
<ide> if (!isInsideEventHandler) {
<ide><path>packages/react-dom/src/events/ReactDOMEventListener.js
<ide> export function addResponderEventSystemEvent(
<ide> null,
<ide> ((topLevelType: any): DOMTopLevelEventType),
<ide> eventFlags,
<add> document,
<ide> );
<ide> if (passiveBrowserEventsSupported) {
<ide> addEventCaptureListenerWithPassiveFlag(
<ide> export function removeActiveResponderEventSystemEvent(
<ide> }
<ide>
<ide> function trapEventForPluginEventSystem(
<del> element: Document | Element | Node,
<add> container: Document | Element | Node,
<ide> topLevelType: DOMTopLevelEventType,
<ide> capture: boolean,
<ide> ): void {
<ide> function trapEventForPluginEventSystem(
<ide> null,
<ide> topLevelType,
<ide> PLUGIN_EVENT_SYSTEM,
<add> container,
<ide> );
<ide> break;
<ide> case UserBlockingEvent:
<ide> listener = dispatchUserBlockingUpdate.bind(
<ide> null,
<ide> topLevelType,
<ide> PLUGIN_EVENT_SYSTEM,
<add> container,
<ide> );
<ide> break;
<ide> case ContinuousEvent:
<ide> default:
<del> listener = dispatchEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM);
<add> listener = dispatchEvent.bind(
<add> null,
<add> topLevelType,
<add> PLUGIN_EVENT_SYSTEM,
<add> container,
<add> );
<ide> break;
<ide> }
<ide>
<ide> const rawEventName = getRawEventName(topLevelType);
<ide> if (capture) {
<del> addEventCaptureListener(element, rawEventName, listener);
<add> addEventCaptureListener(container, rawEventName, listener);
<ide> } else {
<del> addEventBubbleListener(element, rawEventName, listener);
<add> addEventBubbleListener(container, rawEventName, listener);
<ide> }
<ide> }
<ide>
<del>function dispatchDiscreteEvent(topLevelType, eventSystemFlags, nativeEvent) {
<add>function dispatchDiscreteEvent(
<add> topLevelType,
<add> eventSystemFlags,
<add> container,
<add> nativeEvent,
<add>) {
<ide> flushDiscreteUpdatesIfNeeded(nativeEvent.timeStamp);
<del> discreteUpdates(dispatchEvent, topLevelType, eventSystemFlags, nativeEvent);
<add> discreteUpdates(
<add> dispatchEvent,
<add> topLevelType,
<add> eventSystemFlags,
<add> container,
<add> nativeEvent,
<add> );
<ide> }
<ide>
<ide> function dispatchUserBlockingUpdate(
<ide> topLevelType,
<ide> eventSystemFlags,
<add> container,
<ide> nativeEvent,
<ide> ) {
<ide> runWithPriority(
<ide> UserBlockingPriority,
<del> dispatchEvent.bind(null, topLevelType, eventSystemFlags, nativeEvent),
<add> dispatchEvent.bind(
<add> null,
<add> topLevelType,
<add> eventSystemFlags,
<add> container,
<add> nativeEvent,
<add> ),
<ide> );
<ide> }
<ide>
<ide> export function dispatchEvent(
<ide> topLevelType: DOMTopLevelEventType,
<ide> eventSystemFlags: EventSystemFlags,
<add> container: Document | Element | Node,
<ide> nativeEvent: AnyNativeEvent,
<ide> ): void {
<ide> if (!_enabled) {
<ide> export function dispatchEvent(
<ide> topLevelType,
<ide> eventSystemFlags,
<ide> nativeEvent,
<add> container,
<ide> );
<ide> return;
<ide> }
<ide> export function dispatchEvent(
<ide> topLevelType,
<ide> eventSystemFlags,
<ide> nativeEvent,
<add> container,
<ide> );
<ide>
<ide> if (blockedOn === null) {
<ide> export function dispatchEvent(
<ide>
<ide> if (isReplayableDiscreteEvent(topLevelType)) {
<ide> // This this to be replayed later once the target is available.
<del> queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent);
<add> queueDiscreteEvent(
<add> blockedOn,
<add> topLevelType,
<add> eventSystemFlags,
<add> nativeEvent,
<add> container,
<add> );
<ide> return;
<ide> }
<ide>
<ide> export function dispatchEvent(
<ide> topLevelType,
<ide> eventSystemFlags,
<ide> nativeEvent,
<add> container,
<ide> )
<ide> ) {
<ide> return;
<ide> export function attemptToDispatchEvent(
<ide> topLevelType: DOMTopLevelEventType,
<ide> eventSystemFlags: EventSystemFlags,
<ide> nativeEvent: AnyNativeEvent,
<add> container: Document | Element | Node,
<ide> ): null | Container | SuspenseInstance {
<ide> // TODO: Warn if _enabled is false.
<ide>
<ide><path>packages/react-dom/src/events/ReactDOMEventReplaying.js
<ide> type QueuedReplayableEvent = {|
<ide> topLevelType: DOMTopLevelEventType,
<ide> eventSystemFlags: EventSystemFlags,
<ide> nativeEvent: AnyNativeEvent,
<add> container: Document | Element | Node,
<ide> |};
<ide>
<ide> let hasScheduledReplayAttempt = false;
<ide> function createQueuedReplayableEvent(
<ide> topLevelType: DOMTopLevelEventType,
<ide> eventSystemFlags: EventSystemFlags,
<ide> nativeEvent: AnyNativeEvent,
<add> container: Document | Element | Node,
<ide> ): QueuedReplayableEvent {
<ide> return {
<ide> blockedOn,
<ide> topLevelType,
<ide> eventSystemFlags: eventSystemFlags | IS_REPLAYED,
<ide> nativeEvent,
<add> container,
<ide> };
<ide> }
<ide>
<ide> export function queueDiscreteEvent(
<ide> topLevelType: DOMTopLevelEventType,
<ide> eventSystemFlags: EventSystemFlags,
<ide> nativeEvent: AnyNativeEvent,
<add> container: Document | Element | Node,
<ide> ): void {
<ide> const queuedEvent = createQueuedReplayableEvent(
<ide> blockedOn,
<ide> topLevelType,
<ide> eventSystemFlags,
<ide> nativeEvent,
<add> container,
<ide> );
<ide> queuedDiscreteEvents.push(queuedEvent);
<ide> if (enableSelectiveHydration) {
<ide> function accumulateOrCreateContinuousQueuedReplayableEvent(
<ide> topLevelType: DOMTopLevelEventType,
<ide> eventSystemFlags: EventSystemFlags,
<ide> nativeEvent: AnyNativeEvent,
<add> container: Document | Element | Node,
<ide> ): QueuedReplayableEvent {
<ide> if (
<ide> existingQueuedEvent === null ||
<ide> function accumulateOrCreateContinuousQueuedReplayableEvent(
<ide> topLevelType,
<ide> eventSystemFlags,
<ide> nativeEvent,
<add> container,
<ide> );
<ide> if (blockedOn !== null) {
<ide> let fiber = getInstanceFromNode(blockedOn);
<ide> export function queueIfContinuousEvent(
<ide> topLevelType: DOMTopLevelEventType,
<ide> eventSystemFlags: EventSystemFlags,
<ide> nativeEvent: AnyNativeEvent,
<add> container: Document | Element | Node,
<ide> ): boolean {
<ide> // These set relatedTarget to null because the replayed event will be treated as if we
<ide> // moved from outside the window (no target) onto the target once it hydrates.
<ide> export function queueIfContinuousEvent(
<ide> topLevelType,
<ide> eventSystemFlags,
<ide> focusEvent,
<add> container,
<ide> );
<ide> return true;
<ide> }
<ide> export function queueIfContinuousEvent(
<ide> topLevelType,
<ide> eventSystemFlags,
<ide> dragEvent,
<add> container,
<ide> );
<ide> return true;
<ide> }
<ide> export function queueIfContinuousEvent(
<ide> topLevelType,
<ide> eventSystemFlags,
<ide> mouseEvent,
<add> container,
<ide> );
<ide> return true;
<ide> }
<ide> export function queueIfContinuousEvent(
<ide> topLevelType,
<ide> eventSystemFlags,
<ide> pointerEvent,
<add> container,
<ide> ),
<ide> );
<ide> return true;
<ide> export function queueIfContinuousEvent(
<ide> topLevelType,
<ide> eventSystemFlags,
<ide> pointerEvent,
<add> container,
<ide> ),
<ide> );
<ide> return true;
<ide> function attemptReplayContinuousQueuedEvent(
<ide> queuedEvent.topLevelType,
<ide> queuedEvent.eventSystemFlags,
<ide> queuedEvent.nativeEvent,
<add> queuedEvent.container,
<ide> );
<ide> if (nextBlockedOn !== null) {
<ide> // We're still blocked. Try again later.
<ide> function replayUnblockedEvents() {
<ide> nextDiscreteEvent.topLevelType,
<ide> nextDiscreteEvent.eventSystemFlags,
<ide> nextDiscreteEvent.nativeEvent,
<add> nextDiscreteEvent.container,
<ide> );
<ide> if (nextBlockedOn !== null) {
<ide> // We're still blocked. Try again later.
<ide><path>packages/react-dom/src/test-utils/ReactTestUtils.js
<ide> let hasWarnedAboutDeprecatedMockComponent = false;
<ide> */
<ide> function simulateNativeEventOnNode(topLevelType, node, fakeNativeEvent) {
<ide> fakeNativeEvent.target = node;
<del> dispatchEvent(topLevelType, PLUGIN_EVENT_SYSTEM, fakeNativeEvent);
<add> dispatchEvent(topLevelType, PLUGIN_EVENT_SYSTEM, document, fakeNativeEvent);
<ide> }
<ide>
<ide> /**
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.js
<ide> export function batchedEventUpdates<A, R>(fn: A => R, a: A): R {
<ide> }
<ide> }
<ide>
<del>export function discreteUpdates<A, B, C, R>(
<add>export function discreteUpdates<A, B, C, D, R>(
<ide> fn: (A, B, C) => R,
<ide> a: A,
<ide> b: B,
<ide> c: C,
<add> d: D,
<ide> ): R {
<ide> const prevExecutionContext = executionContext;
<ide> executionContext |= DiscreteEventContext;
<ide> try {
<ide> // Should this
<del> return runWithPriority(UserBlockingPriority, fn.bind(null, a, b, c));
<add> return runWithPriority(UserBlockingPriority, fn.bind(null, a, b, c, d));
<ide> } finally {
<ide> executionContext = prevExecutionContext;
<ide> if (executionContext === NoContext) {
| 5
|
Python
|
Python
|
fix docstrings in exceptions.py
|
5cf25854459284a8466cc85ff1f5cfbf5a9cc95e
|
<ide><path>airflow/exceptions.py
<ide> class BackfillUnfinished(AirflowException):
<ide> Raises when not all tasks succeed in backfill.
<ide>
<ide> :param message: The human-readable description of the exception
<del> :zparam ti_status: The information about all task statuses
<add> :param ti_status: The information about all task statuses
<ide> """
<ide> def __init__(self, message, ti_status):
<ide> super().__init__(message)
| 1
|
Python
|
Python
|
add japanese model
|
410fb7ee437b649c8bd291da84db5dc7cd65db45
|
<ide><path>spacy/lang/ja/__init__.py
<ide> from collections import namedtuple
<ide>
<ide> from .stop_words import STOP_WORDS
<add>from .syntax_iterators import SYNTAX_ITERATORS
<ide> from .tag_map import TAG_MAP
<add>from .tag_orth_map import TAG_ORTH_MAP
<add>from .tag_bigram_map import TAG_BIGRAM_MAP
<ide> from ...attrs import LANG
<add>from ...compat import copy_reg
<ide> from ...language import Language
<add>from ...symbols import POS
<ide> from ...tokens import Doc
<del>from ...compat import copy_reg
<del>from ...util import DummyTokenizer
<add>from ...util import DummyTokenizer, get_words_and_spaces
<add>
<add># Hold the attributes we need with convenient names
<add>DetailedToken = namedtuple("DetailedToken", ["surface", "pos", "lemma"])
<ide>
<ide> # Handling for multiple spaces in a row is somewhat awkward, this simplifies
<ide> # the flow by creating a dummy with the same interface.
<del>DummyNode = namedtuple("DummyNode", ["surface", "pos", "feature"])
<del>DummyNodeFeatures = namedtuple("DummyNodeFeatures", ["lemma"])
<del>DummySpace = DummyNode(" ", " ", DummyNodeFeatures(" "))
<add>DummyNode = namedtuple("DummyNode", ["surface", "pos", "lemma"])
<add>DummySpace = DummyNode(" ", " ", " ")
<ide>
<ide>
<del>def try_fugashi_import():
<del> """Fugashi is required for Japanese support, so check for it.
<add>def try_sudachi_import():
<add> """SudachiPy is required for Japanese support, so check for it.
<ide> It it's not available blow up and explain how to fix it."""
<ide> try:
<del> import fugashi
<add> from sudachipy import dictionary, tokenizer
<ide>
<del> return fugashi
<add> tok = dictionary.Dictionary().create(
<add> mode=tokenizer.Tokenizer.SplitMode.A
<add> )
<add> return tok
<ide> except ImportError:
<ide> raise ImportError(
<del> "Japanese support requires Fugashi: " "https://github.com/polm/fugashi"
<add> "Japanese support requires SudachiPy: " "https://github.com/WorksApplications/SudachiPy"
<ide> )
<ide>
<ide>
<del>def resolve_pos(token):
<add>def resolve_pos(token, next_token):
<ide> """If necessary, add a field to the POS tag for UD mapping.
<ide> Under Universal Dependencies, sometimes the same Unidic POS tag can
<ide> be mapped differently depending on the literal token or its context
<del> in the sentence. This function adds information to the POS tag to
<del> resolve ambiguous mappings.
<add> in the sentence. This function returns resolved POSs for both token
<add> and next_token by tuple.
<ide> """
<ide>
<del> # this is only used for consecutive ascii spaces
<del> if token.surface == " ":
<del> return "空白"
<add> # Some tokens have their UD tag decided based on the POS of the following
<add> # token.
<ide>
<del> # TODO: This is a first take. The rules here are crude approximations.
<del> # For many of these, full dependencies are needed to properly resolve
<del> # PoS mappings.
<del> if token.pos == "連体詞,*,*,*":
<del> if re.match(r"[こそあど此其彼]の", token.surface):
<del> return token.pos + ",DET"
<del> if re.match(r"[こそあど此其彼]", token.surface):
<del> return token.pos + ",PRON"
<del> return token.pos + ",ADJ"
<del> return token.pos
<add> # orth based rules
<add> if token.pos in TAG_ORTH_MAP:
<add> orth_map = TAG_ORTH_MAP[token.pos[0]]
<add> if token.surface in orth_map:
<add> return orth_map[token.surface], None
<ide>
<add> # tag bi-gram mapping
<add> if next_token:
<add> tag_bigram = token.pos[0], next_token.pos[0]
<add> if tag_bigram in TAG_BIGRAM_MAP:
<add> bipos = TAG_BIGRAM_MAP[tag_bigram]
<add> if bipos[0] is None:
<add> return TAG_MAP[token.pos[0]][POS], bipos[1]
<add> else:
<add> return bipos
<ide>
<del>def get_words_and_spaces(tokenizer, text):
<del> """Get the individual tokens that make up the sentence and handle white space.
<add> return TAG_MAP[token.pos[0]][POS], None
<ide>
<del> Japanese doesn't usually use white space, and MeCab's handling of it for
<del> multiple spaces in a row is somewhat awkward.
<del> """
<ide>
<del> tokens = tokenizer.parseToNodeList(text)
<add># Use a mapping of paired punctuation to avoid splitting quoted sentences.
<add>pairpunct = {'「':'」', '『': '』', '【': '】'}
<ide>
<del> words = []
<del> spaces = []
<del> for token in tokens:
<del> # If there's more than one space, spaces after the first become tokens
<del> for ii in range(len(token.white_space) - 1):
<del> words.append(DummySpace)
<del> spaces.append(False)
<ide>
<del> words.append(token)
<del> spaces.append(bool(token.white_space))
<del> return words, spaces
<add>def separate_sentences(doc):
<add> """Given a doc, mark tokens that start sentences based on Unidic tags.
<add> """
<ide>
<add> stack = [] # save paired punctuation
<add>
<add> for i, token in enumerate(doc[:-2]):
<add> # Set all tokens after the first to false by default. This is necessary
<add> # for the doc code to be aware we've done sentencization, see
<add> # `is_sentenced`.
<add> token.sent_start = (i == 0)
<add> if token.tag_:
<add> if token.tag_ == "補助記号-括弧開":
<add> ts = str(token)
<add> if ts in pairpunct:
<add> stack.append(pairpunct[ts])
<add> elif stack and ts == stack[-1]:
<add> stack.pop()
<add>
<add> if token.tag_ == "補助記号-句点":
<add> next_token = doc[i+1]
<add> if next_token.tag_ != token.tag_ and not stack:
<add> next_token.sent_start = True
<add>
<add>
<add>def get_dtokens(tokenizer, text):
<add> tokens = tokenizer.tokenize(text)
<add> words = []
<add> for ti, token in enumerate(tokens):
<add> tag = '-'.join([xx for xx in token.part_of_speech()[:4] if xx != '*'])
<add> inf = '-'.join([xx for xx in token.part_of_speech()[4:] if xx != '*'])
<add> dtoken = DetailedToken(
<add> token.surface(),
<add> (tag, inf),
<add> token.dictionary_form())
<add> if ti > 0 and words[-1].pos[0] == '空白' and tag == '空白':
<add> # don't add multiple space tokens in a row
<add> continue
<add> words.append(dtoken)
<add>
<add> # remove empty tokens. These can be produced with characters like … that
<add> # Sudachi normalizes internally.
<add> words = [ww for ww in words if len(ww.surface) > 0]
<add> return words
<ide>
<ide> class JapaneseTokenizer(DummyTokenizer):
<ide> def __init__(self, cls, nlp=None):
<ide> self.vocab = nlp.vocab if nlp is not None else cls.create_vocab(nlp)
<del> self.tokenizer = try_fugashi_import().Tagger()
<del> self.tokenizer.parseToNodeList("") # see #2901
<add> self.tokenizer = try_sudachi_import()
<ide>
<ide> def __call__(self, text):
<del> dtokens, spaces = get_words_and_spaces(self.tokenizer, text)
<add> dtokens = get_dtokens(self.tokenizer, text)
<add>
<ide> words = [x.surface for x in dtokens]
<add> words, spaces = get_words_and_spaces(words, text)
<add> unidic_tags = [",".join(x.pos) for x in dtokens]
<ide> doc = Doc(self.vocab, words=words, spaces=spaces)
<del> unidic_tags = []
<del> for token, dtoken in zip(doc, dtokens):
<del> unidic_tags.append(dtoken.pos)
<del> token.tag_ = resolve_pos(dtoken)
<add> next_pos = None
<add> for ii, (token, dtoken) in enumerate(zip(doc, dtokens)):
<add> ntoken = dtokens[ii+1] if ii+1 < len(dtokens) else None
<add> token.tag_ = dtoken.pos[0]
<add> if next_pos:
<add> token.pos = next_pos
<add> next_pos = None
<add> else:
<add> token.pos, next_pos = resolve_pos(dtoken, ntoken)
<ide>
<ide> # if there's no lemma info (it's an unk) just use the surface
<del> token.lemma_ = dtoken.feature.lemma or dtoken.surface
<add> token.lemma_ = dtoken.lemma
<ide> doc.user_data["unidic_tags"] = unidic_tags
<add>
<add> separate_sentences(doc)
<ide> return doc
<ide>
<ide>
<ide> class JapaneseDefaults(Language.Defaults):
<ide> lex_attr_getters[LANG] = lambda _text: "ja"
<ide> stop_words = STOP_WORDS
<ide> tag_map = TAG_MAP
<add> syntax_iterators = SYNTAX_ITERATORS
<ide> writing_system = {"direction": "ltr", "has_case": False, "has_letters": False}
<ide>
<ide> @classmethod
<ide><path>spacy/lang/ja/bunsetu.py
<add># coding: utf8
<add>from __future__ import unicode_literals
<add>
<add>from .stop_words import STOP_WORDS
<add>
<add>
<add>POS_PHRASE_MAP = {
<add> "NOUN": "NP",
<add> "NUM": "NP",
<add> "PRON": "NP",
<add> "PROPN": "NP",
<add>
<add> "VERB": "VP",
<add>
<add> "ADJ": "ADJP",
<add>
<add> "ADV": "ADVP",
<add>
<add> "CCONJ": "CCONJP",
<add>}
<add>
<add>
<add># return value: [(bunsetu_tokens, phrase_type={'NP', 'VP', 'ADJP', 'ADVP'}, phrase_tokens)]
<add>def yield_bunsetu(doc, debug=False):
<add> bunsetu = []
<add> bunsetu_may_end = False
<add> phrase_type = None
<add> phrase = None
<add> prev = None
<add> prev_tag = None
<add> prev_dep = None
<add> prev_head = None
<add> for t in doc:
<add> pos = t.pos_
<add> pos_type = POS_PHRASE_MAP.get(pos, None)
<add> tag = t.tag_
<add> dep = t.dep_
<add> head = t.head.i
<add> if debug:
<add> print(t.i, t.orth_, pos, pos_type, dep, head, bunsetu_may_end, phrase_type, phrase, bunsetu)
<add>
<add> # DET is always an individual bunsetu
<add> if pos == "DET":
<add> if bunsetu:
<add> yield bunsetu, phrase_type, phrase
<add> yield [t], None, None
<add> bunsetu = []
<add> bunsetu_may_end = False
<add> phrase_type = None
<add> phrase = None
<add>
<add> # PRON or Open PUNCT always splits bunsetu
<add> elif tag == "補助記号-括弧開":
<add> if bunsetu:
<add> yield bunsetu, phrase_type, phrase
<add> bunsetu = [t]
<add> bunsetu_may_end = True
<add> phrase_type = None
<add> phrase = None
<add>
<add> # bunsetu head not appeared
<add> elif phrase_type is None:
<add> if bunsetu and prev_tag == "補助記号-読点":
<add> yield bunsetu, phrase_type, phrase
<add> bunsetu = []
<add> bunsetu_may_end = False
<add> phrase_type = None
<add> phrase = None
<add> bunsetu.append(t)
<add> if pos_type: # begin phrase
<add> phrase = [t]
<add> phrase_type = pos_type
<add> if pos_type in {"ADVP", "CCONJP"}:
<add> bunsetu_may_end = True
<add>
<add> # entering new bunsetu
<add> elif pos_type and (
<add> pos_type != phrase_type or # different phrase type arises
<add> bunsetu_may_end # same phrase type but bunsetu already ended
<add> ):
<add> # exceptional case: NOUN to VERB
<add> if phrase_type == "NP" and pos_type == "VP" and prev_dep == 'compound' and prev_head == t.i:
<add> bunsetu.append(t)
<add> phrase_type = "VP"
<add> phrase.append(t)
<add> # exceptional case: VERB to NOUN
<add> elif phrase_type == "VP" and pos_type == "NP" and (
<add> prev_dep == 'compound' and prev_head == t.i or
<add> dep == 'compound' and prev == head or
<add> prev_dep == 'nmod' and prev_head == t.i
<add> ):
<add> bunsetu.append(t)
<add> phrase_type = "NP"
<add> phrase.append(t)
<add> else:
<add> yield bunsetu, phrase_type, phrase
<add> bunsetu = [t]
<add> bunsetu_may_end = False
<add> phrase_type = pos_type
<add> phrase = [t]
<add>
<add> # NOUN bunsetu
<add> elif phrase_type == "NP":
<add> bunsetu.append(t)
<add> if not bunsetu_may_end and ((
<add> (pos_type == "NP" or pos == "SYM") and (prev_head == t.i or prev_head == head) and prev_dep in {'compound', 'nummod'}
<add> ) or (
<add> pos == "PART" and (prev == head or prev_head == head) and dep == 'mark'
<add> )):
<add> phrase.append(t)
<add> else:
<add> bunsetu_may_end = True
<add>
<add> # VERB bunsetu
<add> elif phrase_type == "VP":
<add> bunsetu.append(t)
<add> if not bunsetu_may_end and pos == "VERB" and prev_head == t.i and prev_dep == 'compound':
<add> phrase.append(t)
<add> else:
<add> bunsetu_may_end = True
<add>
<add> # ADJ bunsetu
<add> elif phrase_type == "ADJP" and tag != '連体詞':
<add> bunsetu.append(t)
<add> if not bunsetu_may_end and ((
<add> pos == "NOUN" and (prev_head == t.i or prev_head == head) and prev_dep in {'amod', 'compound'}
<add> ) or (
<add> pos == "PART" and (prev == head or prev_head == head) and dep == 'mark'
<add> )):
<add> phrase.append(t)
<add> else:
<add> bunsetu_may_end = True
<add>
<add> # other bunsetu
<add> else:
<add> bunsetu.append(t)
<add>
<add> prev = t.i
<add> prev_tag = t.tag_
<add> prev_dep = t.dep_
<add> prev_head = head
<add>
<add> if bunsetu:
<add> yield bunsetu, phrase_type, phrase
<ide><path>spacy/lang/ja/syntax_iterators.py
<add># coding: utf8
<add>from __future__ import unicode_literals
<add>
<add>from ...symbols import NOUN, PROPN, PRON, VERB
<add>
<add># XXX this can probably be pruned a bit
<add>labels = [
<add> "nsubj",
<add> "nmod",
<add> "dobj",
<add> "nsubjpass",
<add> "pcomp",
<add> "pobj",
<add> "obj",
<add> "obl",
<add> "dative",
<add> "appos",
<add> "attr",
<add> "ROOT",
<add>]
<add>
<add>def noun_chunks(obj):
<add> """
<add> Detect base noun phrases from a dependency parse. Works on both Doc and Span.
<add> """
<add>
<add> doc = obj.doc # Ensure works on both Doc and Span.
<add> np_deps = [doc.vocab.strings.add(label) for label in labels]
<add> conj = doc.vocab.strings.add("conj")
<add> np_label = doc.vocab.strings.add("NP")
<add> seen = set()
<add> for i, word in enumerate(obj):
<add> if word.pos not in (NOUN, PROPN, PRON):
<add> continue
<add> # Prevent nested chunks from being produced
<add> if word.i in seen:
<add> continue
<add> if word.dep in np_deps:
<add> unseen = [w.i for w in word.subtree if w.i not in seen]
<add> if not unseen:
<add> continue
<add>
<add> # this takes care of particles etc.
<add> seen.update(j.i for j in word.subtree)
<add> # This avoids duplicating embedded clauses
<add> seen.update(range(word.i + 1))
<add>
<add> # if the head of this is a verb, mark that and rights seen
<add> # Don't do the subtree as that can hide other phrases
<add> if word.head.pos == VERB:
<add> seen.add(word.head.i)
<add> seen.update(w.i for w in word.head.rights)
<add> yield unseen[0], word.i + 1, np_label
<add>
<add>SYNTAX_ITERATORS = {"noun_chunks": noun_chunks}
<ide><path>spacy/lang/ja/tag_bigram_map.py
<add># encoding: utf8
<add>from __future__ import unicode_literals
<add>
<add>from ...symbols import POS, ADJ, AUX, NOUN, PART, VERB
<add>
<add># mapping from tag bi-gram to pos of previous token
<add>TAG_BIGRAM_MAP = {
<add> # This covers only small part of AUX.
<add> ("形容詞-非自立可能", "助詞-終助詞"): (AUX, None),
<add>
<add> ("名詞-普通名詞-形状詞可能", "助動詞"): (ADJ, None),
<add> # ("副詞", "名詞-普通名詞-形状詞可能"): (None, ADJ),
<add>
<add> # This covers acl, advcl, obl and root, but has side effect for compound.
<add> ("名詞-普通名詞-サ変可能", "動詞-非自立可能"): (VERB, AUX),
<add> # This covers almost all of the deps
<add> ("名詞-普通名詞-サ変形状詞可能", "動詞-非自立可能"): (VERB, AUX),
<add>
<add> ("名詞-普通名詞-副詞可能", "動詞-非自立可能"): (None, VERB),
<add> ("副詞", "動詞-非自立可能"): (None, VERB),
<add> ("形容詞-一般", "動詞-非自立可能"): (None, VERB),
<add> ("形容詞-非自立可能", "動詞-非自立可能"): (None, VERB),
<add> ("接頭辞", "動詞-非自立可能"): (None, VERB),
<add> ("助詞-係助詞", "動詞-非自立可能"): (None, VERB),
<add> ("助詞-副助詞", "動詞-非自立可能"): (None, VERB),
<add> ("助詞-格助詞", "動詞-非自立可能"): (None, VERB),
<add> ("補助記号-読点", "動詞-非自立可能"): (None, VERB),
<add>
<add> ("形容詞-一般", "接尾辞-名詞的-一般"): (None, PART),
<add>
<add> ("助詞-格助詞", "形状詞-助動詞語幹"): (None, NOUN),
<add> ("連体詞", "形状詞-助動詞語幹"): (None, NOUN),
<add>
<add> ("動詞-一般", "助詞-副助詞"): (None, PART),
<add> ("動詞-非自立可能", "助詞-副助詞"): (None, PART),
<add> ("助動詞", "助詞-副助詞"): (None, PART),
<add>}
<ide><path>spacy/lang/ja/tag_map.py
<ide> # encoding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ...symbols import POS, PUNCT, INTJ, X, ADJ, AUX, ADP, PART, SCONJ, NOUN
<add>from ...symbols import POS, PUNCT, INTJ, X, ADJ, AUX, ADP, PART, CCONJ, SCONJ, NOUN
<ide> from ...symbols import SYM, PRON, VERB, ADV, PROPN, NUM, DET, SPACE
<ide>
<ide>
<ide> TAG_MAP = {
<ide> # Explanation of Unidic tags:
<ide> # https://www.gavo.t.u-tokyo.ac.jp/~mine/japanese/nlp+slp/UNIDIC_manual.pdf
<del> # Universal Dependencies Mapping:
<add> # Universal Dependencies Mapping: (Some of the entries in this mapping are updated to v2.6 in the list below)
<ide> # http://universaldependencies.org/ja/overview/morphology.html
<ide> # http://universaldependencies.org/ja/pos/all.html
<del> "記号,一般,*,*": {
<del> POS: PUNCT
<add> "記号-一般": {
<add> POS: NOUN
<ide> }, # this includes characters used to represent sounds like ドレミ
<del> "記号,文字,*,*": {
<del> POS: PUNCT
<del> }, # this is for Greek and Latin characters used as sumbols, as in math
<del> "感動詞,フィラー,*,*": {POS: INTJ},
<del> "感動詞,一般,*,*": {POS: INTJ},
<del> # this is specifically for unicode full-width space
<del> "空白,*,*,*": {POS: X},
<del> # This is used when sequential half-width spaces are present
<add> "記号-文字": {
<add> POS: NOUN
<add> }, # this is for Greek and Latin characters having some meanings, or used as symbols, as in math
<add> "感動詞-フィラー": {POS: INTJ},
<add> "感動詞-一般": {POS: INTJ},
<add>
<ide> "空白": {POS: SPACE},
<del> "形状詞,一般,*,*": {POS: ADJ},
<del> "形状詞,タリ,*,*": {POS: ADJ},
<del> "形状詞,助動詞語幹,*,*": {POS: ADJ},
<del> "形容詞,一般,*,*": {POS: ADJ},
<del> "形容詞,非自立可能,*,*": {POS: AUX}, # XXX ADJ if alone, AUX otherwise
<del> "助詞,格助詞,*,*": {POS: ADP},
<del> "助詞,係助詞,*,*": {POS: ADP},
<del> "助詞,終助詞,*,*": {POS: PART},
<del> "助詞,準体助詞,*,*": {POS: SCONJ}, # の as in 走るのが速い
<del> "助詞,接続助詞,*,*": {POS: SCONJ}, # verb ending て
<del> "助詞,副助詞,*,*": {POS: PART}, # ばかり, つつ after a verb
<del> "助動詞,*,*,*": {POS: AUX},
<del> "接続詞,*,*,*": {POS: SCONJ}, # XXX: might need refinement
<del> "接頭辞,*,*,*": {POS: NOUN},
<del> "接尾辞,形状詞的,*,*": {POS: ADJ}, # がち, チック
<del> "接尾辞,形容詞的,*,*": {POS: ADJ}, # -らしい
<del> "接尾辞,動詞的,*,*": {POS: NOUN}, # -じみ
<del> "接尾辞,名詞的,サ変可能,*": {POS: NOUN}, # XXX see 名詞,普通名詞,サ変可能,*
<del> "接尾辞,名詞的,一般,*": {POS: NOUN},
<del> "接尾辞,名詞的,助数詞,*": {POS: NOUN},
<del> "接尾辞,名詞的,副詞可能,*": {POS: NOUN}, # -後, -過ぎ
<del> "代名詞,*,*,*": {POS: PRON},
<del> "動詞,一般,*,*": {POS: VERB},
<del> "動詞,非自立可能,*,*": {POS: VERB}, # XXX VERB if alone, AUX otherwise
<del> "動詞,非自立可能,*,*,AUX": {POS: AUX},
<del> "動詞,非自立可能,*,*,VERB": {POS: VERB},
<del> "副詞,*,*,*": {POS: ADV},
<del> "補助記号,AA,一般,*": {POS: SYM}, # text art
<del> "補助記号,AA,顔文字,*": {POS: SYM}, # kaomoji
<del> "補助記号,一般,*,*": {POS: SYM},
<del> "補助記号,括弧開,*,*": {POS: PUNCT}, # open bracket
<del> "補助記号,括弧閉,*,*": {POS: PUNCT}, # close bracket
<del> "補助記号,句点,*,*": {POS: PUNCT}, # period or other EOS marker
<del> "補助記号,読点,*,*": {POS: PUNCT}, # comma
<del> "名詞,固有名詞,一般,*": {POS: PROPN}, # general proper noun
<del> "名詞,固有名詞,人名,一般": {POS: PROPN}, # person's name
<del> "名詞,固有名詞,人名,姓": {POS: PROPN}, # surname
<del> "名詞,固有名詞,人名,名": {POS: PROPN}, # first name
<del> "名詞,固有名詞,地名,一般": {POS: PROPN}, # place name
<del> "名詞,固有名詞,地名,国": {POS: PROPN}, # country name
<del> "名詞,助動詞語幹,*,*": {POS: AUX},
<del> "名詞,数詞,*,*": {POS: NUM}, # includes Chinese numerals
<del> "名詞,普通名詞,サ変可能,*": {POS: NOUN}, # XXX: sometimes VERB in UDv2; suru-verb noun
<del> "名詞,普通名詞,サ変可能,*,NOUN": {POS: NOUN},
<del> "名詞,普通名詞,サ変可能,*,VERB": {POS: VERB},
<del> "名詞,普通名詞,サ変形状詞可能,*": {POS: NOUN}, # ex: 下手
<del> "名詞,普通名詞,一般,*": {POS: NOUN},
<del> "名詞,普通名詞,形状詞可能,*": {POS: NOUN}, # XXX: sometimes ADJ in UDv2
<del> "名詞,普通名詞,形状詞可能,*,NOUN": {POS: NOUN},
<del> "名詞,普通名詞,形状詞可能,*,ADJ": {POS: ADJ},
<del> "名詞,普通名詞,助数詞可能,*": {POS: NOUN}, # counter / unit
<del> "名詞,普通名詞,副詞可能,*": {POS: NOUN},
<del> "連体詞,*,*,*": {POS: ADJ}, # XXX this has exceptions based on literal token
<del> "連体詞,*,*,*,ADJ": {POS: ADJ},
<del> "連体詞,*,*,*,PRON": {POS: PRON},
<del> "連体詞,*,*,*,DET": {POS: DET},
<add>
<add> "形状詞-一般": {POS: ADJ},
<add> "形状詞-タリ": {POS: ADJ},
<add> "形状詞-助動詞語幹": {POS: AUX},
<add>
<add> "形容詞-一般": {POS: ADJ},
<add>
<add> "形容詞-非自立可能": {POS: ADJ}, # XXX ADJ if alone, AUX otherwise
<add>
<add> "助詞-格助詞": {POS: ADP},
<add>
<add> "助詞-係助詞": {POS: ADP},
<add>
<add> "助詞-終助詞": {POS: PART},
<add> "助詞-準体助詞": {POS: SCONJ}, # の as in 走るのが速い
<add> "助詞-接続助詞": {POS: SCONJ}, # verb ending て0
<add>
<add> "助詞-副助詞": {POS: ADP}, # ばかり, つつ after a verb
<add>
<add> "助動詞": {POS: AUX},
<add>
<add> "接続詞": {POS: CCONJ}, # XXX: might need refinement
<add> "接頭辞": {POS: NOUN},
<add> "接尾辞-形状詞的": {POS: PART}, # がち, チック
<add>
<add> "接尾辞-形容詞的": {POS: AUX}, # -らしい
<add>
<add> "接尾辞-動詞的": {POS: PART}, # -じみ
<add> "接尾辞-名詞的-サ変可能": {POS: NOUN}, # XXX see 名詞,普通名詞,サ変可能,*
<add> "接尾辞-名詞的-一般": {POS: NOUN},
<add> "接尾辞-名詞的-助数詞": {POS: NOUN},
<add> "接尾辞-名詞的-副詞可能": {POS: NOUN}, # -後, -過ぎ
<add>
<add> "代名詞": {POS: PRON},
<add>
<add> "動詞-一般": {POS: VERB},
<add>
<add> "動詞-非自立可能": {POS: AUX}, # XXX VERB if alone, AUX otherwise
<add>
<add> "副詞": {POS: ADV},
<add>
<add> "補助記号-AA-一般": {POS: SYM}, # text art
<add> "補助記号-AA-顔文字": {POS: PUNCT}, # kaomoji
<add>
<add> "補助記号-一般": {POS: SYM},
<add>
<add> "補助記号-括弧開": {POS: PUNCT}, # open bracket
<add> "補助記号-括弧閉": {POS: PUNCT}, # close bracket
<add> "補助記号-句点": {POS: PUNCT}, # period or other EOS marker
<add> "補助記号-読点": {POS: PUNCT}, # comma
<add>
<add> "名詞-固有名詞-一般": {POS: PROPN}, # general proper noun
<add> "名詞-固有名詞-人名-一般": {POS: PROPN}, # person's name
<add> "名詞-固有名詞-人名-姓": {POS: PROPN}, # surname
<add> "名詞-固有名詞-人名-名": {POS: PROPN}, # first name
<add> "名詞-固有名詞-地名-一般": {POS: PROPN}, # place name
<add> "名詞-固有名詞-地名-国": {POS: PROPN}, # country name
<add>
<add> "名詞-助動詞語幹": {POS: AUX},
<add> "名詞-数詞": {POS: NUM}, # includes Chinese numerals
<add>
<add> "名詞-普通名詞-サ変可能": {POS: NOUN}, # XXX: sometimes VERB in UDv2; suru-verb noun
<add>
<add> "名詞-普通名詞-サ変形状詞可能": {POS: NOUN},
<add>
<add> "名詞-普通名詞-一般": {POS: NOUN},
<add>
<add> "名詞-普通名詞-形状詞可能": {POS: NOUN}, # XXX: sometimes ADJ in UDv2
<add>
<add> "名詞-普通名詞-助数詞可能": {POS: NOUN}, # counter / unit
<add>
<add> "名詞-普通名詞-副詞可能": {POS: NOUN},
<add>
<add> "連体詞": {POS: DET}, # XXX this has exceptions based on literal token
<add>
<add> # GSD tags. These aren't in Unidic, but we need them for the GSD data.
<add> "外国語": {POS: PROPN}, # Foreign words
<add>
<add> "絵文字・記号等": {POS: SYM}, # emoji / kaomoji ^^;
<add>
<ide> }
<ide><path>spacy/lang/ja/tag_orth_map.py
<add># encoding: utf8
<add>from __future__ import unicode_literals
<add>
<add>from ...symbols import POS, ADJ, AUX, DET, PART, PRON, SPACE ,X
<add>
<add># mapping from tag bi-gram to pos of previous token
<add>TAG_ORTH_MAP = {
<add> "空白": {
<add> " ": SPACE,
<add> " ": X,
<add> },
<add> "助詞-副助詞": {
<add> "たり": PART,
<add> },
<add> "連体詞": {
<add> "あの": DET,
<add> "かの": DET,
<add> "この": DET,
<add> "その": DET,
<add> "どの": DET,
<add> "彼の": DET,
<add> "此の": DET,
<add> "其の": DET,
<add> "ある": PRON,
<add> "こんな": PRON,
<add> "そんな": PRON,
<add> "どんな": PRON,
<add> "あらゆる": PRON,
<add> },
<add>}
<ide><path>spacy/tests/lang/ja/test_lemmatization.py
<ide>
<ide> @pytest.mark.parametrize(
<ide> "word,lemma",
<del> [("新しく", "新しい"), ("赤く", "赤い"), ("すごく", "凄い"), ("いただきました", "頂く"), ("なった", "成る")],
<add> [("新しく", "新しい"), ("赤く", "赤い"), ("すごく", "すごい"), ("いただきました", "いただく"), ("なった", "なる")],
<ide> )
<ide> def test_ja_lemmatizer_assigns(ja_tokenizer, word, lemma):
<ide> test_lemma = ja_tokenizer(word)[0].lemma_
<ide><path>spacy/tests/lang/ja/test_tokenizer.py
<ide> ]
<ide>
<ide> TAG_TESTS = [
<del> ("日本語だよ", ['名詞,固有名詞,地名,国', '名詞,普通名詞,一般,*', '助動詞,*,*,*', '助詞,終助詞,*,*']),
<del> ("東京タワーの近くに住んでいます。", ['名詞,固有名詞,地名,一般', '名詞,普通名詞,一般,*', '助詞,格助詞,*,*', '名詞,普通名詞,副詞可能,*', '助詞,格助詞,*,*', '動詞,一般,*,*', '助詞,接続助詞,*,*', '動詞,非自立可能,*,*', '助動詞,*,*,*', '補助記号,句点,*,*']),
<del> ("吾輩は猫である。", ['代名詞,*,*,*', '助詞,係助詞,*,*', '名詞,普通名詞,一般,*', '助動詞,*,*,*', '動詞,非自立可能,*,*', '補助記号,句点,*,*']),
<del> ("月に代わって、お仕置きよ!", ['名詞,普通名詞,助数詞可能,*', '助詞,格助詞,*,*', '動詞,一般,*,*', '助詞,接続助詞,*,*', '補助記号,読点,*,*', '接頭辞,*,*,*', '名詞,普通名詞,一般,*', '助詞,終助詞,*,*', '補助記号,句点,*,*']),
<del> ("すもももももももものうち", ['名詞,普通名詞,一般,*', '助詞,係助詞,*,*', '名詞,普通名詞,一般,*', '助詞,係助詞,*,*', '名詞,普通名詞,一般,*', '助詞,格助詞,*,*', '名詞,普通名詞,副詞可能,*'])
<add> ("日本語だよ", ['名詞-固有名詞-地名-国', '名詞-普通名詞-一般', '助動詞', '助詞-終助詞']),
<add> ("東京タワーの近くに住んでいます。", ['名詞-固有名詞-地名-一般', '名詞-普通名詞-一般', '助詞-格助詞', '名詞-普通名詞-副詞可能', '助詞-格助詞', '動詞-一般', '助詞-接続助詞', '動詞-非自立可能', '助動詞', '補助記号-句点']),
<add> ("吾輩は猫である。", ['代名詞', '助詞-係助詞', '名詞-普通名詞-一般', '助動詞', '動詞-非自立可能', '補助記号-句点']),
<add> ("月に代わって、お仕置きよ!", ['名詞-普通名詞-助数詞可能', '助詞-格助詞', '動詞-一般', '助詞-接続助詞', '補助記号-読点', '接頭辞', '名詞-普通名詞-一般', '助詞-終助詞', '補助記号-句点']),
<add> ("すもももももももものうち", ['名詞-普通名詞-一般', '助詞-係助詞', '名詞-普通名詞-一般', '助詞-係助詞', '名詞-普通名詞-一般', '助詞-格助詞', '名詞-普通名詞-副詞可能'])
<ide> ]
<ide>
<ide> POS_TESTS = [
<del> ('日本語だよ', ['PROPN', 'NOUN', 'AUX', 'PART']),
<add> ('日本語だよ', ['fish', 'NOUN', 'AUX', 'PART']),
<ide> ('東京タワーの近くに住んでいます。', ['PROPN', 'NOUN', 'ADP', 'NOUN', 'ADP', 'VERB', 'SCONJ', 'VERB', 'AUX', 'PUNCT']),
<ide> ('吾輩は猫である。', ['PRON', 'ADP', 'NOUN', 'AUX', 'VERB', 'PUNCT']),
<ide> ('月に代わって、お仕置きよ!', ['NOUN', 'ADP', 'VERB', 'SCONJ', 'PUNCT', 'NOUN', 'NOUN', 'PART', 'PUNCT']),
<ide> ('すもももももももものうち', ['NOUN', 'ADP', 'NOUN', 'ADP', 'NOUN', 'ADP', 'NOUN'])
<ide> ]
<add>
<add>SENTENCE_TESTS = [
<add> ('あれ。これ。', ['あれ。', 'これ。']),
<add> ('「伝染るんです。」という漫画があります。',
<add> ['「伝染るんです。」という漫画があります。']),
<add> ]
<ide> # fmt: on
<ide>
<ide>
<ide> def test_ja_tokenizer_tags(ja_tokenizer, text, expected_tags):
<ide> assert tags == expected_tags
<ide>
<ide>
<add>#XXX This isn't working? Always passes
<ide> @pytest.mark.parametrize("text,expected_pos", POS_TESTS)
<ide> def test_ja_tokenizer_pos(ja_tokenizer, text, expected_pos):
<ide> pos = [token.pos_ for token in ja_tokenizer(text)]
<ide> assert pos == expected_pos
<ide>
<add>@pytest.mark.parametrize("text,expected_sents", SENTENCE_TESTS)
<add>def test_ja_tokenizer_pos(ja_tokenizer, text, expected_sents):
<add> sents = [str(sent) for sent in ja_tokenizer(text).sents]
<add> assert sents == expected_sents
<add>
<ide>
<ide> def test_extra_spaces(ja_tokenizer):
<ide> # note: three spaces after "I"
<ide> tokens = ja_tokenizer("I like cheese.")
<del> assert tokens[1].orth_ == " "
<del> assert tokens[2].orth_ == " "
<add> assert tokens[1].orth_ == " "
<add>
<add>from ...tokenizer.test_naughty_strings import NAUGHTY_STRINGS
<add>
<add>@pytest.mark.parametrize("text", NAUGHTY_STRINGS)
<add>def test_tokenizer_naughty_strings(ja_tokenizer, text):
<add> tokens = ja_tokenizer(text)
<add> assert tokens.text_with_ws == text
<add>
| 8
|
Ruby
|
Ruby
|
fix doc typo on dispatcher.dispatch. closes [fxn]
|
a3e57ad11ece0238849747f22d355747a81eb281
|
<ide><path>actionpack/lib/action_controller/dispatcher.rb
<ide> module ActionController
<ide> class Dispatcher
<ide> class << self
<ide> # Backward-compatible class method takes CGI-specific args. Deprecated
<del> # in favor of Dispatcher.new(output, request, response).dispatch!
<add> # in favor of Dispatcher.new(output, request, response).dispatch.
<ide> def dispatch(cgi = nil, session_options = CgiRequest::DEFAULT_SESSION_OPTIONS, output = $stdout)
<ide> new(output).dispatch_cgi(cgi, session_options)
<ide> end
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.