content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
|---|---|---|---|---|---|
Javascript
|
Javascript
|
add nalathe kerala to showcase
|
bd99f31358200252e662dbdf6fae26ead8670101
|
<ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> link: 'https://itunes.apple.com/in/app/myntra-fashion-shopping-app/id907394059',
<ide> author: 'Myntra Designs',
<ide> },
<add> {
<add> name: 'Nalathe Kerala',
<add> icon: 'https://lh3.googleusercontent.com/5N0WYat5WuFbhi5yR2ccdbqmiZ0wbTtKRG9GhT3YK7Z-qRvmykZyAgk0HNElOxD2JOPr=w300-rw',
<add> link: 'https://play.google.com/store/apps/details?id=com.rhyble.nalathekerala',
<add> author: 'Rhyble',
<add> },
<ide> {
<ide> name: 'Ncredible',
<ide> icon: 'http://a3.mzstatic.com/us/r30/Purple2/v4/a9/00/74/a9007400-7ccf-df10-553b-3b6cb67f3f5f/icon350x350.png',
| 1
|
Text
|
Text
|
deprecate top-level `this`
|
300f5ce3461f01daa994a4a4f78546f164d28ca8
|
<ide><path>doc/api/deprecations.md
<ide> Type: Runtime
<ide>
<ide> The [`crypto.DEFAULT_ENCODING`][] property is deprecated.
<ide>
<add><a id="DEP00XX"></a>
<add>### DEP00XX: Top-level `this` bound to `module.exports`
<add>
<add>Type: Documentation-only
<add>
<add>Assigning properties to the top-level `this` as an alternative
<add>to `module.exports` is deprecated. Developers should use `exports`
<add>or `module.exports` instead.
<add>
<ide> [`--pending-deprecation`]: cli.html#cli_pending_deprecation
<ide> [`Buffer.allocUnsafeSlow(size)`]: buffer.html#buffer_class_method_buffer_allocunsafeslow_size
<ide> [`Buffer.from(array)`]: buffer.html#buffer_class_method_buffer_from_array
| 1
|
Python
|
Python
|
add tests for locally connected layers
|
ee17ccc3746dbbc8bc20e2bc48ea5dc11ef36f30
|
<ide><path>tests/keras/layers/test_local.py
<ide> import pytest
<del>import numpy as np
<del>from numpy.testing import assert_allclose
<ide>
<ide> from keras.utils.test_utils import layer_test
<del>from keras import backend as K
<ide> from keras.layers import local
<ide>
<ide>
<ide> def test_locallyconnected_2d():
<ide>
<ide>
<ide> if __name__ == '__main__':
<del> # pytest.main([__file__])
<del> test_locallyconnected_1d()
<del> test_locallyconnected_2d()
<add> pytest.main([__file__])
| 1
|
Go
|
Go
|
run 'gofmt -s -w'
|
8f3b8f383519452001cc05bf6505e9c301ebe954
|
<ide><path>engine/http.go
<ide> package engine
<ide>
<ide> import (
<del> "path"
<ide> "net/http"
<add> "path"
<ide> )
<ide>
<ide> // ServeHTTP executes a job as specified by the http request `r`, and sends the
<ide> func (eng *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
<ide> jobArgs = []string{}
<ide> }
<ide> w.Header().Set("Job-Name", jobName)
<del> for _, arg := range(jobArgs) {
<add> for _, arg := range jobArgs {
<ide> w.Header().Add("Job-Args", arg)
<ide> }
<ide> job := eng.Job(jobName, jobArgs...)
<ide><path>reflink_copy_darwin.go
<ide> package docker
<ide>
<ide> import (
<del> "os"
<ide> "io"
<add> "os"
<ide> )
<ide>
<ide> func CopyFile(dstFile, srcFile *os.File) error {
<ide><path>reflink_copy_linux.go
<ide> btrfs_reflink(int fd_out, int fd_in)
<ide> import "C"
<ide>
<ide> import (
<del> "os"
<ide> "io"
<add> "os"
<ide> "syscall"
<ide> )
<ide>
<ide><path>utils.go
<ide> func migratePortMappings(config *Config, hostConfig *HostConfig) error {
<ide> return nil
<ide> }
<ide>
<del>
<ide> // Links come in the format of
<ide> // name:alias
<ide> func parseLink(rawLink string) (map[string]string, error) {
<ide><path>utils/utils.go
<ide> func ParseHost(defaultHost string, defaultPort int, defaultUnix, addr string) (s
<ide> host string
<ide> port int
<ide> )
<del> addr = strings.TrimSpace(addr)
<add> addr = strings.TrimSpace(addr)
<ide> switch {
<ide> case strings.HasPrefix(addr, "unix://"):
<ide> proto = "unix"
<ide><path>utils/utils_test.go
<ide> func TestParseHost(t *testing.T) {
<ide> if addr, err := ParseHost(defaultHttpHost, defaultHttpPort, defaultUnix, "tcp://:7777"); err != nil || addr != "tcp://127.0.0.1:7777" {
<ide> t.Errorf("tcp://:7777 -> expected tcp://127.0.0.1:7777, got %s", addr)
<ide> }
<del> if addr, err := ParseHost(defaultHttpHost, defaultHttpPort, defaultUnix, ""); err != nil || addr != "unix:///var/run/docker.sock" {
<del> t.Errorf("empty argument -> expected unix:///var/run/docker.sock, got %s", addr)
<del> }
<add> if addr, err := ParseHost(defaultHttpHost, defaultHttpPort, defaultUnix, ""); err != nil || addr != "unix:///var/run/docker.sock" {
<add> t.Errorf("empty argument -> expected unix:///var/run/docker.sock, got %s", addr)
<add> }
<ide> if addr, err := ParseHost(defaultHttpHost, defaultHttpPort, defaultUnix, "unix:///var/run/docker.sock"); err != nil || addr != "unix:///var/run/docker.sock" {
<ide> t.Errorf("unix:///var/run/docker.sock -> expected unix:///var/run/docker.sock, got %s", addr)
<ide> }
| 6
|
PHP
|
PHP
|
remove unused use statements
|
6d13f743f9054293499696ce3f07c568116acdcc
|
<ide><path>src/Auth/Storage/MemoryStorage.php
<ide> */
<ide> namespace Cake\Auth\Storage;
<ide>
<del>use Cake\Core\InstanceConfigTrait;
<del>use Cake\Network\Request;
<del>
<ide> /**
<ide> * Memory based non-persistent storage for authenticated user record.
<ide> */
<ide><path>src/Controller/Controller.php
<ide> use Cake\ORM\Locator\LocatorAwareTrait;
<ide> use Cake\Routing\RequestActionTrait;
<ide> use Cake\Routing\Router;
<del>use Cake\Utility\Inflector;
<ide> use Cake\Utility\MergeVariablesTrait;
<ide> use Cake\View\ViewVarsTrait;
<ide> use LogicException;
<ide><path>src/Database/Query.php
<ide> use Cake\Database\Expression\QueryExpression;
<ide> use Cake\Database\Expression\ValuesExpression;
<ide> use Cake\Database\Statement\CallbackStatement;
<del>use Cake\Database\TypeMap;
<ide> use IteratorAggregate;
<ide> use RuntimeException;
<ide>
<ide><path>src/Database/Schema/SqliteSchema.php
<ide> */
<ide> namespace Cake\Database\Schema;
<ide>
<del>use Cake\Core\Configure;
<ide> use Cake\Database\Exception;
<del>use RuntimeException;
<ide>
<ide> /**
<ide> * Schema management/reflection features for Sqlite
<ide><path>src/Database/Type/UuidType.php
<ide> use Cake\Database\Driver;
<ide> use Cake\Database\Type;
<ide> use Cake\Utility\Text;
<del>use PDO;
<ide>
<ide> /**
<ide> * Provides behavior for the UUID type
<ide><path>src/Datasource/RulesChecker.php
<ide> */
<ide> namespace Cake\Datasource;
<ide>
<del>use Cake\Datasource\InvalidPropertyInterface;
<ide> use InvalidArgumentException;
<ide>
<ide> /**
<ide><path>src/Error/BaseErrorHandler.php
<ide> namespace Cake\Error;
<ide>
<ide> use Cake\Core\Configure;
<del>use Cake\Error\PHP7ErrorException;
<ide> use Cake\Log\Log;
<ide> use Cake\Routing\Router;
<ide> use Error;
<ide><path>src/Error/ExceptionRenderer.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Exception\Exception as CakeException;
<ide> use Cake\Core\Exception\MissingPluginException;
<del>use Cake\Error\PHP7ErrorException;
<ide> use Cake\Event\Event;
<ide> use Cake\Network\Exception\HttpException;
<ide> use Cake\Network\Request;
<ide><path>src/I18n/DateFormatTrait.php
<ide> */
<ide> namespace Cake\I18n;
<ide>
<del>use DateTime;
<ide> use IntlDateFormatter;
<ide>
<ide> /**
<ide><path>src/I18n/FrozenTime.php
<ide> namespace Cake\I18n;
<ide>
<ide> use Cake\Chronos\Chronos;
<del>use Cake\Chronos\ChronosInterface;
<ide> use DateTime;
<ide> use DateTimeInterface;
<ide> use DateTimeZone;
<ide><path>src/Mailer/MailerAwareTrait.php
<ide>
<ide> use Cake\Core\App;
<ide> use Cake\Mailer\Exception\MissingMailerException;
<del>use InvalidArgumentException;
<ide>
<ide> /**
<ide> * Provides functionality for loading mailer classes
<ide><path>src/Network/CorsBuilder.php
<ide> */
<ide> namespace Cake\Network;
<ide>
<del>use Cake\Network\Response;
<ide>
<ide> /**
<ide> * A builder object that assists in defining Cross Origin Request related
<ide><path>src/Shell/RoutesShell.php
<ide> namespace Cake\Shell;
<ide>
<ide> use Cake\Console\Shell;
<del>use Cake\Core\Configure;
<ide> use Cake\Routing\Exception\MissingRouteException;
<ide> use Cake\Routing\Router;
<ide>
<ide><path>src/Shell/Task/CommandTask.php
<ide> */
<ide> namespace Cake\Shell\Task;
<ide>
<del>use Cake\Console\ConsoleOptionParser;
<ide> use Cake\Console\Shell;
<ide> use Cake\Core\App;
<ide> use Cake\Core\Plugin;
<ide><path>src/TestSuite/Fixture/TestFixture.php
<ide> namespace Cake\TestSuite\Fixture;
<ide>
<ide> use Cake\Core\Exception\Exception as CakeException;
<del>use Cake\Database\Driver\Sqlite;
<ide> use Cake\Database\Schema\Table;
<ide> use Cake\Datasource\ConnectionInterface;
<ide> use Cake\Datasource\ConnectionManager;
<ide><path>src/View/CellTrait.php
<ide> */
<ide> namespace Cake\View;
<ide>
<del>use BadMethodCallException;
<ide> use Cake\Core\App;
<ide> use Cake\Utility\Inflector;
<del>use ReflectionException;
<del>use ReflectionMethod;
<ide>
<ide> /**
<ide> * Provides cell() method for usage in Controller and View classes.
<ide><path>src/View/Helper/FormHelper.php
<ide> use Cake\View\Form\FormContext;
<ide> use Cake\View\Form\NullContext;
<ide> use Cake\View\Helper;
<del>use Cake\View\Helper\SecureFieldTokenTrait;
<ide> use Cake\View\StringTemplateTrait;
<ide> use Cake\View\View;
<ide> use Cake\View\Widget\WidgetRegistry;
<ide><path>src/View/JsonView.php
<ide> namespace Cake\View;
<ide>
<ide> use Cake\Core\Configure;
<del>use Cake\Event\EventManager;
<ide> use Cake\Network\Request;
<ide> use Cake\Network\Response;
<ide>
<ide><path>src/View/ViewVarsTrait.php
<ide> */
<ide> namespace Cake\View;
<ide>
<del>use Cake\Core\App;
<ide> use Cake\Event\EventDispatcherInterface;
<ide>
<ide> /**
<ide><path>src/View/XmlView.php
<ide> namespace Cake\View;
<ide>
<ide> use Cake\Core\Configure;
<del>use Cake\Event\EventManager;
<ide> use Cake\Network\Request;
<ide> use Cake\Network\Response;
<ide> use Cake\Utility\Hash;
| 20
|
Python
|
Python
|
improve test coverage for test_common_schema.py
|
5b683f09c0fffd781111c1a8268ed41b1abfd6e0
|
<ide><path>tests/api_connexion/schemas/test_common_schema.py
<ide> def test_should_deserialize_relative_delta(self):
<ide> expected_instance = relativedelta.relativedelta(days=+12)
<ide> self.assertEqual(expected_instance, result)
<ide>
<del> def test_should_serialize_cron_expresssion(self):
<add> def test_should_serialize_cron_expression(self):
<ide> instance = "5 4 * * *"
<ide> schema_instance = ScheduleIntervalSchema()
<ide> result = schema_instance.dump(instance)
<ide> expected_instance = {"__type": "CronExpression", "value": "5 4 * * *"}
<ide> self.assertEqual(expected_instance, result)
<add>
<add> def test_should_error_unknown_obj_type(self):
<add> instance = 342
<add> schema_instance = ScheduleIntervalSchema()
<add> with self.assertRaisesRegex(Exception, "Unknown object type: int"):
<add> schema_instance.dump(instance)
| 1
|
Java
|
Java
|
scheduler overload with recursive support
|
dc7a3f8f575edc28d86daa2039715866059a574d
|
<ide><path>rxjava-core/src/main/java/rx/Scheduler.java
<ide> import org.mockito.Mockito;
<ide>
<ide> import rx.concurrency.TestScheduler;
<add>import rx.subscriptions.CompositeSubscription;
<add>import rx.subscriptions.MultipleAssignmentSubscription;
<ide> import rx.subscriptions.Subscriptions;
<ide> import rx.util.functions.Action0;
<add>import rx.util.functions.Action1;
<ide> import rx.util.functions.Func1;
<ide> import rx.util.functions.Func2;
<ide>
<ide> public abstract class Scheduler {
<ide> * Schedules a cancelable action to be executed periodically.
<ide> * This default implementation schedules recursively and waits for actions to complete (instead of potentially executing
<ide> * long-running actions concurrently). Each scheduler that can do periodic scheduling in a better way should override this.
<del> *
<del> * @param state
<add> *
<add> * @param state
<ide> * State to pass into the action.
<del> * @param action
<add> * @param action
<ide> * The action to execute periodically.
<del> * @param initialDelay
<add> * @param initialDelay
<ide> * Time to wait before executing the action for the first time.
<del> * @param period
<add> * @param period
<ide> * The time interval to wait each time in between executing the action.
<del> * @param unit
<add> * @param unit
<ide> * The time unit the interval above is given in.
<ide> * @return A subscription to be able to unsubscribe from action.
<ide> */
<ide> public <T> Subscription schedulePeriodically(T state, final Func2<? super Scheduler, ? super T, ? extends Subscription> action, long initialDelay, long period, TimeUnit unit) {
<ide> final long periodInNanos = unit.toNanos(period);
<ide> final AtomicBoolean complete = new AtomicBoolean();
<del>
<add>
<ide> final Func2<Scheduler, T, Subscription> recursiveAction = new Func2<Scheduler, T, Subscription>() {
<ide> @Override
<ide> public Subscription call(Scheduler scheduler, T state0) {
<ide> public void call() {
<ide> }
<ide> });
<ide> }
<del>
<add>
<ide> /**
<ide> * Schedules a cancelable action to be executed at dueTime.
<ide> *
<ide> public <T> Subscription schedule(T state, Func2<? super Scheduler, ? super T, ?
<ide> }
<ide> }
<ide>
<add> /**
<add> * Schedules an action and receives back an action for recursive execution.
<add> *
<add> * @param action
<add> * action
<add> * @return a subscription to be able to unsubscribe from action.
<add> */
<add> public Subscription schedule(final Action1<Action0> action) {
<add> final CompositeSubscription parentSubscription = new CompositeSubscription();
<add> final MultipleAssignmentSubscription childSubscription = new MultipleAssignmentSubscription();
<add> parentSubscription.add(childSubscription);
<add>
<add> final Func2<Scheduler, Func2, Subscription> parentAction = new Func2<Scheduler, Func2, Subscription>() {
<add>
<add> @Override
<add> public Subscription call(final Scheduler scheduler, final Func2 parentAction) {
<add> action.call(new Action0() {
<add>
<add> @Override
<add> public void call() {
<add> if (!parentSubscription.isUnsubscribed()) {
<add> childSubscription.setSubscription(scheduler.schedule(parentAction, parentAction));
<add> }
<add> }
<add>
<add> });
<add> return childSubscription;
<add> }
<add> };
<add>
<add> parentSubscription.add(schedule(parentAction, parentAction));
<add>
<add> return parentSubscription;
<add> }
<ide>
<ide> /**
<ide> * Schedules an action to be executed.
<ide> public Subscription call(Scheduler scheduler, Void state) {
<ide> }, delayTime, unit);
<ide> }
<ide>
<del>
<ide> /**
<ide> * Schedules an action to be executed periodically.
<ide> *
<del> * @param action
<add> * @param action
<ide> * The action to execute periodically.
<del> * @param initialDelay
<add> * @param initialDelay
<ide> * Time to wait before executing the action for the first time.
<del> * @param period
<add> * @param period
<ide> * The time interval to wait each time in between executing the action.
<del> * @param unit
<add> * @param unit
<ide> * The time unit the interval above is given in.
<ide> * @return A subscription to be able to unsubscribe from action.
<ide> */
<ide> public int degreeOfParallelism() {
<ide> }
<ide>
<ide> public static class UnitTest {
<del> @SuppressWarnings("unchecked") // mocking is unchecked, unfortunately
<add> @SuppressWarnings("unchecked")
<add> // mocking is unchecked, unfortunately
<ide> @Test
<ide> public void testPeriodicScheduling() {
<ide> final Func1<Long, Void> calledOp = mock(Func1.class);
<del>
<add>
<ide> final TestScheduler scheduler = new TestScheduler();
<ide> Subscription subscription = scheduler.schedulePeriodically(new Action0() {
<del> @Override public void call() {
<add> @Override
<add> public void call() {
<ide> System.out.println(scheduler.now());
<ide> calledOp.call(scheduler.now());
<ide> }
<ide> }, 1, 2, TimeUnit.SECONDS);
<del>
<add>
<ide> verify(calledOp, never()).call(anyLong());
<ide>
<ide> InOrder inOrder = Mockito.inOrder(calledOp);
<del>
<add>
<ide> scheduler.advanceTimeBy(999L, TimeUnit.MILLISECONDS);
<ide> inOrder.verify(calledOp, never()).call(anyLong());
<ide>
<ide> scheduler.advanceTimeBy(1L, TimeUnit.MILLISECONDS);
<ide> inOrder.verify(calledOp, times(1)).call(1000L);
<del>
<add>
<ide> scheduler.advanceTimeBy(1999L, TimeUnit.MILLISECONDS);
<ide> inOrder.verify(calledOp, never()).call(3000L);
<del>
<add>
<ide> scheduler.advanceTimeBy(1L, TimeUnit.MILLISECONDS);
<ide> inOrder.verify(calledOp, times(1)).call(3000L);
<del>
<add>
<ide> scheduler.advanceTimeBy(5L, TimeUnit.SECONDS);
<ide> inOrder.verify(calledOp, times(1)).call(5000L);
<ide> inOrder.verify(calledOp, times(1)).call(7000L);
<del>
<add>
<ide> subscription.unsubscribe();
<ide> scheduler.advanceTimeBy(11L, TimeUnit.SECONDS);
<ide> inOrder.verify(calledOp, never()).call(anyLong());
<ide><path>rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java
<ide> import rx.Subscription;
<ide> import rx.subscriptions.BooleanSubscription;
<ide> import rx.subscriptions.Subscriptions;
<add>import rx.util.functions.Action0;
<ide> import rx.util.functions.Action1;
<ide> import rx.util.functions.Func1;
<ide> import rx.util.functions.Func2;
<ide> public Subscription onSubscribe(final Observer<? super String> observer) {
<ide> fail("Error: " + observer.error.get().getMessage());
<ide> }
<ide> }
<add>
<add> @Test
<add> public void testRecursion() {
<add> TestScheduler s = new TestScheduler();
<add>
<add> final AtomicInteger counter = new AtomicInteger(0);
<add>
<add> Subscription subscription = s.schedule(new Action1<Action0>() {
<add>
<add> @Override
<add> public void call(Action0 self) {
<add> counter.incrementAndGet();
<add> System.out.println("counter: " + counter.get());
<add> self.call();
<add> }
<add>
<add> });
<add> subscription.unsubscribe();
<add> assertEquals(0, counter.get());
<add> }
<add>
<ide>
<ide> /**
<ide> * Used to determine if onNext is being invoked concurrently.
| 2
|
Go
|
Go
|
unify both debug logging middlewares
|
82323294db96e8043244027c262481af6c8f478d
|
<ide><path>api/server/middleware.go
<ide> import (
<ide> // Any function that has the appropriate signature can be register as a middleware.
<ide> type middleware func(handler httputils.APIFunc) httputils.APIFunc
<ide>
<del>// loggingMiddleware logs each request when logging is enabled.
<del>func (s *Server) loggingMiddleware(handler httputils.APIFunc) httputils.APIFunc {
<del> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<del> if s.cfg.Logging {
<del> logrus.Debugf("%s %s", r.Method, r.RequestURI)
<del> }
<del> return handler(ctx, w, r, vars)
<del> }
<del>}
<del>
<ide> // debugRequestMiddleware dumps the request to logger
<del>// This is implemented separately from `loggingMiddleware` so that we don't have to
<del>// check the logging level or have httputil.DumpRequest called on each request.
<del>// Instead the middleware is only injected when the logging level is set to debug
<del>func (s *Server) debugRequestMiddleware(handler httputils.APIFunc) httputils.APIFunc {
<add>func debugRequestMiddleware(handler httputils.APIFunc) httputils.APIFunc {
<ide> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<del> if s.cfg.Logging && r.Method == "POST" {
<add> logrus.Debugf("%s %s", r.Method, r.RequestURI)
<add>
<add> if r.Method == "POST" {
<ide> if err := httputils.CheckForJSON(r); err == nil {
<ide> var buf bytes.Buffer
<ide> if _, err := buf.ReadFrom(r.Body); err == nil {
<ide> func (s *Server) debugRequestMiddleware(handler httputils.APIFunc) httputils.API
<ide> }
<ide> }
<ide> }
<add>
<ide> return handler(ctx, w, r, vars)
<ide> }
<ide> }
<ide> func (s *Server) handleWithGlobalMiddlewares(handler httputils.APIFunc) httputil
<ide> versionMiddleware,
<ide> s.corsMiddleware,
<ide> s.userAgentMiddleware,
<del> s.loggingMiddleware,
<ide> }
<ide>
<ide> // Only want this on debug level
<del> // this is separate from the logging middleware so that we can do this check here once,
<del> // rather than for each request.
<del> if logrus.GetLevel() == logrus.DebugLevel {
<del> middlewares = append(middlewares, s.debugRequestMiddleware)
<add> if s.cfg.Logging && logrus.GetLevel() == logrus.DebugLevel {
<add> middlewares = append(middlewares, debugRequestMiddleware)
<ide> }
<ide>
<ide> h := handler
| 1
|
Go
|
Go
|
fix race in access closeerr in bytespipe
|
b32478488ce6d373e44bb8a6c9cb986c773ad48e
|
<ide><path>pkg/ioutils/bytespipe.go
<ide> func (bp *BytesPipe) Read(p []byte) (n int, err error) {
<ide> }
<ide> bp.wait.Wait()
<ide> if bp.bufLen == 0 && bp.closeErr != nil {
<add> err := bp.closeErr
<ide> bp.mu.Unlock()
<del> return 0, bp.closeErr
<add> return 0, err
<ide> }
<ide> }
<ide>
| 1
|
PHP
|
PHP
|
set relation connection on eager loaded morphto
|
6ead73349126c7eee5fd9702c420915f6a02a889
|
<ide><path>src/Illuminate/Database/Eloquent/Relations/MorphTo.php
<ide> public function createModelByType($type)
<ide> {
<ide> $class = Model::getActualClassNameForMorph($type);
<ide>
<del> return new $class;
<add> return tap(new $class, function ($instance) {
<add> if (! $instance->getConnectionName()) {
<add> $instance->setConnection($this->getConnection()->getName());
<add> }
<add> });
<ide> }
<ide>
<ide> /**
<ide><path>tests/Database/DatabaseEloquentIntegrationTest.php
<ide> public function testMorphToRelationsAcrossDatabaseConnections()
<ide> $this->assertInstanceOf(EloquentTestItem::class, $item);
<ide> }
<ide>
<add> public function testEagerLoadedMorphToRelationsOnAnotherDatabaseConnection()
<add> {
<add> EloquentTestPost::create(['id' => 1, 'name' => 'Default Connection Post', 'user_id' => 1]);
<add> EloquentTestPhoto::create(['id' => 1, 'imageable_type' => EloquentTestPost::class, 'imageable_id' => 1, 'name' => 'Photo']);
<add>
<add> EloquentTestPost::on('second_connection')
<add> ->create(['id' => 1, 'name' => 'Second Connection Post', 'user_id' => 1]);
<add> EloquentTestPhoto::on('second_connection')
<add> ->create(['id' => 1, 'imageable_type' => EloquentTestPost::class, 'imageable_id' => 1, 'name' => 'Photo']);
<add>
<add> $defaultConnectionPost = EloquentTestPhoto::with('imageable')->first()->imageable;
<add> $secondConnectionPost = EloquentTestPhoto::on('second_connection')->with('imageable')->first()->imageable;
<add>
<add> $this->assertEquals($defaultConnectionPost->name, 'Default Connection Post');
<add> $this->assertEquals($secondConnectionPost->name, 'Second Connection Post');
<add> }
<add>
<ide> public function testBelongsToManyCustomPivot()
<ide> {
<ide> $john = EloquentTestUserWithCustomFriendPivot::create(['id' => 1, 'name' => 'John Doe', 'email' => 'johndoe@example.com']);
| 2
|
Ruby
|
Ruby
|
move wkhtmltopdf to the boneyard
|
79caaf5112f98d6c4b81d968995b501d5ec25520
|
<ide><path>Library/Homebrew/tap_migrations.rb
<ide> 'nlopt' => 'homebrew/science',
<ide> 'comparepdf' => 'homebrew/boneyard',
<ide> 'colormake' => 'homebrew/headonly',
<add> 'wkhtmltopdf' => 'homebrew/boneyard',
<ide> }
| 1
|
Text
|
Text
|
update react package readme
|
9fdf5899761b3ceaae6ef274365bba35c6428dea
|
<ide><path>npm-react-core/README.md
<ide> without also requiring the JSX transformer. This is especially useful for cases
<ide> want to [`browserify`](https://github.com/substack/node-browserify) your module using
<ide> `React`.
<ide>
<add>## The `react` npm package has recently changed!
<add>
<add>If you're looking for jeffbski's [React.js](https://github.com/jeffbski/react) project, it's now in `npm` as `reactjs` rather than `react`.
<add>
<ide> ## Example Usage
<ide>
<ide> ```js
<ide> want to [`browserify`](https://github.com/substack/node-browserify) your module
<ide> var React = require('react-tools').React;
<ide>
<ide> // Now you can access React directly with react-core.
<del>var React = require('react-core');
<add>var React = require('react');
<ide>
<ide> // You can also access ReactWithAddons.
<del>var React = require('react-core/addons');
<add>var React = require('react/addons');
<ide> ```
<ide>
| 1
|
Python
|
Python
|
add sensors plugins
|
30826905928fe2a712a2e21c209190c3123d154a
|
<ide><path>glances/core/glances_core.py
<ide> print('PsUtil 0.5.1 or higher is needed. Glances cannot start.')
<ide> sys.exit(1)
<ide>
<del>try:
<del> # psutil.net_io_counters() only available from psutil >= 1.0.0
<del> psutil.net_io_counters()
<del>except Exception:
<del> psutil_net_io_counters = False
<del>else:
<del> psutil_net_io_counters = True
<del>
<ide> if not is_Mac:
<ide> psutil_get_io_counter_tag = True
<ide> else:
<ide> # get_io_counters() not available on OS X
<ide> psutil_get_io_counter_tag = False
<ide>
<del># sensors library (optional; Linux-only)
<del>if is_Linux:
<del> try:
<del> import sensors
<del> except ImportError:
<del> sensors_lib_tag = False
<del> else:
<del> sensors_lib_tag = True
<del>else:
<del> sensors_lib_tag = False
<del>
<del># batinfo library (optional; Linux-only)
<del>if is_Linux:
<del> try:
<del> import batinfo
<del> except ImportError:
<del> batinfo_lib_tag = False
<del> else:
<del> batinfo_lib_tag = True
<del>else:
<del> batinfo_lib_tag = False
<del>
<ide>
<ide> class GlancesCore(object):
<ide> """
<ide> def parse_arg(self):
<ide> self.hddtemp_flag = args.disable_hddtemp
<ide> self.network_tag = args.disable_network
<ide> self.process_tag = args.disable_process
<del> self.sensors_tag = args.disable_sensors and is_Linux and sensors_lib_tag
<add> self.sensors_tag = args.disable_sensors and is_Linux # and sensors_lib_tag
<ide> self.use_bold = args.no_bold
<ide> self.percpu_tag = args.percpu
<ide> if (args.config is not None):
<ide><path>glances/plugins/glances_batpercent.py
<add>#!/usr/bin/env python
<add># -*- coding: utf-8 -*-
<add>#
<add># Glances - An eye on your system
<add>#
<add># Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
<add>#
<add># Glances is free software; you can redistribute it and/or modify
<add># it under the terms of the GNU Lesser General Public License as published by
<add># the Free Software Foundation, either version 3 of the License, or
<add># (at your option) any later version.
<add>#
<add># Glances is distributed in the hope that it will be useful,
<add># but WITHOUT ANY WARRANTY; without even the implied warranty of
<add># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
<add># GNU Lesser General Public License for more details.
<add>#
<add># You should have received a copy of the GNU Lesser General Public License
<add># along with this program. If not, see <http://www.gnu.org/licenses/>.
<add>
<add># Import system libs
<add># batinfo library (optional; Linux-only)
<add>try:
<add> import batinfo
<add>except:
<add> pass
<add>
<add>from glances_plugin import GlancesPlugin, getTimeSinceLastUpdate
<add>
<add>
<add>class Plugin(GlancesPlugin):
<add> """
<add> Glances's batterie capacity Plugin
<add>
<add> stats is a list
<add> """
<add>
<add> def __init__(self):
<add> GlancesPlugin.__init__(self)
<add>
<add> # Init the sensor class
<add> self.glancesgrabbat = glancesGrabBat()
<add>
<add>
<add> def update(self):
<add> """
<add> Update batterie capacity stats
<add> """
<add>
<add> self.stats = self.glancesgrabbat.getcapacitypercent()
<add>
<add>
<add>class glancesGrabBat:
<add> """
<add> Get batteries stats using the Batinfo librairie
<add> """
<add>
<add> def __init__(self):
<add> """
<add> Init batteries stats
<add> """
<add> try:
<add> self.bat = batinfo.batteries()
<add> self.initok = True
<add> self.__update__()
<add> except Exception:
<add> self.initok = False
<add>
<add> def __update__(self):
<add> """
<add> Update the stats
<add> """
<add> if self.initok:
<add> try:
<add> self.bat.update()
<add> except Exception:
<add> self.bat_list = []
<add> else:
<add> self.bat_list = self.bat.stat
<add> else:
<add> self.bat_list = []
<add>
<add> def get(self):
<add> # Update the stats
<add> self.__update__()
<add> return self.bat_list
<add>
<add> def getcapacitypercent(self):
<add> if not self.initok or self.bat_list == []:
<add> return []
<add> # Init the bsum (sum of percent) and bcpt (number of batteries)
<add> # and Loop over batteries (yes a computer could have more than 1 battery)
<add> bsum = 0
<add> for bcpt in range(len(self.get())):
<add> try:
<add> bsum = bsum + int(self.bat_list[bcpt].capacity)
<add> except ValueError:
<add> return []
<add> bcpt = bcpt + 1
<add> # Return the global percent
<add> return int(bsum / bcpt)
<ide>\ No newline at end of file
<ide><path>glances/plugins/glances_hddtemp.py
<add>#!/usr/bin/env python
<add># -*- coding: utf-8 -*-
<add>#
<add># Glances - An eye on your system
<add>#
<add># Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
<add>#
<add># Glances is free software; you can redistribute it and/or modify
<add># it under the terms of the GNU Lesser General Public License as published by
<add># the Free Software Foundation, either version 3 of the License, or
<add># (at your option) any later version.
<add>#
<add># Glances is distributed in the hope that it will be useful,
<add># but WITHOUT ANY WARRANTY; without even the implied warranty of
<add># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
<add># GNU Lesser General Public License for more details.
<add>#
<add># You should have received a copy of the GNU Lesser General Public License
<add># along with this program. If not, see <http://www.gnu.org/licenses/>.
<add>
<add># Import system libs
<add>import socket
<add>
<add>from glances_plugin import GlancesPlugin, getTimeSinceLastUpdate
<add>
<add>class Plugin(GlancesPlugin):
<add> """
<add> Glances's HDD temperature sensors Plugin
<add>
<add> stats is a list
<add> """
<add>
<add> def __init__(self):
<add> GlancesPlugin.__init__(self)
<add>
<add> # Init the sensor class
<add> self.glancesgrabhddtemp = glancesGrabHDDTemp()
<add>
<add>
<add> def update(self):
<add> """
<add> Update Sensors stats
<add> """
<add>
<add> self.stats = self.glancesgrabhddtemp.get()
<add>
<add>
<add> def get_stats(self):
<add> # Return the stats object for the RPC API
<add> # Sort it by label name
<add> # Convert it to string
<add> return str(sorted(self.stats, key=lambda sensors: sensors['label']))
<add>
<add>
<add>class glancesGrabHDDTemp:
<add> """
<add> Get hddtemp stats using a socket connection
<add> """
<add> cache = ""
<add> address = "127.0.0.1"
<add> port = 7634
<add>
<add> def __init__(self):
<add> """
<add> Init hddtemp stats
<add> """
<add> try:
<add> sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
<add> sck.connect((self.address, self.port))
<add> sck.close()
<add> except Exception:
<add> self.initok = False
<add> else:
<add> self.initok = True
<add>
<add> def __update__(self):
<add> """
<add> Update the stats
<add> """
<add> # Reset the list
<add> self.hddtemp_list = []
<add>
<add> if self.initok:
<add> data = ""
<add> # Taking care of sudden deaths/stops of hddtemp daemon
<add> try:
<add> sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
<add> sck.connect((self.address, self.port))
<add> data = sck.recv(4096)
<add> sck.close()
<add> except Exception:
<add> hddtemp_current = {}
<add> hddtemp_current['label'] = "hddtemp is gone"
<add> hddtemp_current['value'] = 0
<add> self.hddtemp_list.append(hddtemp_current)
<add> return
<add> else:
<add> # Considering the size of "|/dev/sda||0||" as the minimum
<add> if len(data) < 14:
<add> if len(self.cache) == 0:
<add> data = "|hddtemp error||0||"
<add> else:
<add> data = self.cache
<add> self.cache = data
<add> fields = data.decode('utf-8').split("|")
<add> devices = (len(fields) - 1) // 5
<add> for i in range(0, devices):
<add> offset = i * 5
<add> hddtemp_current = {}
<add> temperature = fields[offset + 3]
<add> if temperature == "ERR":
<add> hddtemp_current['label'] = _("hddtemp error")
<add> hddtemp_current['value'] = 0
<add> elif temperature == "SLP":
<add> hddtemp_current['label'] = fields[offset + 1].split("/")[-1] + " is sleeping"
<add> hddtemp_current['value'] = 0
<add> elif temperature == "UNK":
<add> hddtemp_current['label'] = fields[offset + 1].split("/")[-1] + " is unknown"
<add> hddtemp_current['value'] = 0
<add> else:
<add> hddtemp_current['label'] = fields[offset + 1].split("/")[-1]
<add> try:
<add> hddtemp_current['value'] = int(temperature)
<add> except TypeError:
<add> hddtemp_current['label'] = fields[offset + 1].split("/")[-1] + " is unknown"
<add> hddtemp_current['value'] = 0
<add> self.hddtemp_list.append(hddtemp_current)
<add>
<add> def get(self):
<add> self.__update__()
<add> return self.hddtemp_list
<ide><path>glances/plugins/glances_network.py
<ide> # along with this program. If not, see <http://www.gnu.org/licenses/>.
<ide>
<ide> # Import system libs
<del># Check for PSUtil already done in the glances_core script
<del>import psutil
<del>
<ide> try:
<del> # psutil.net_io_counters() only available from psutil >= 1.0.0
<del> psutil.net_io_counters()
<del>except Exception:
<del> psutil_net_io_counters = False
<del>else:
<del> psutil_net_io_counters = True
<add> # psutil >= 1.0.0
<add> from psutil import net_io_counters
<add>except:
<add> # psutil < 1.0.0
<add> try:
<add> from psutil import network_io_counters
<add> except:
<add> pass
<ide>
<ide> # from ..plugins.glances_plugin import GlancesPlugin
<ide> from glances_plugin import GlancesPlugin, getTimeSinceLastUpdate
<ide> def update(self):
<ide> # for users of the API
<ide> time_since_update = getTimeSinceLastUpdate('net')
<ide>
<del> if psutil_net_io_counters:
<del> # psutil >= 1.0.0
<del> try:
<del> get_net_io_counters = psutil.net_io_counters(pernic=True)
<del> except IOError:
<del> pass
<del> else:
<add> # psutil >= 1.0.0
<add> try:
<add> get_net_io_counters = net_io_counters(pernic=True)
<add> except IOError:
<ide> # psutil < 1.0.0
<ide> try:
<del> get_net_io_counters = psutil.network_io_counters(pernic=True)
<add> get_net_io_counters = network_io_counters(pernic=True)
<ide> except IOError:
<ide> pass
<ide>
<ide> network = []
<del>
<add>
<ide> # Previous network interface stats are stored in the network_old variable
<ide> if not hasattr(self, 'network_old'):
<ide> # First call, we init the network_old var
<ide> def update(self):
<ide> self.network_old = network_new
<ide>
<ide> self.stats = network
<add>
<add>
<add> def get_stats(self):
<add> # Return the stats object for the RPC API
<add> # Sort it by interface name
<add> # Convert it to string
<add> return str(sorted(self.stats, key=lambda network: network['interface_name']))
<ide><path>glances/plugins/glances_plugin.py
<ide>
<ide> from time import time
<ide>
<add># Global list to manage the elapsed time
<ide> last_update_times = {}
<ide>
<add>
<ide> def getTimeSinceLastUpdate(IOType):
<ide> global last_update_times
<ide> # assert(IOType in ['net', 'disk', 'process_disk'])
<ide><path>glances/plugins/glances_sensors.py
<add>#!/usr/bin/env python
<add># -*- coding: utf-8 -*-
<add>#
<add># Glances - An eye on your system
<add>#
<add># Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
<add>#
<add># Glances is free software; you can redistribute it and/or modify
<add># it under the terms of the GNU Lesser General Public License as published by
<add># the Free Software Foundation, either version 3 of the License, or
<add># (at your option) any later version.
<add>#
<add># Glances is distributed in the hope that it will be useful,
<add># but WITHOUT ANY WARRANTY; without even the implied warranty of
<add># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
<add># GNU Lesser General Public License for more details.
<add>#
<add># You should have received a copy of the GNU Lesser General Public License
<add># along with this program. If not, see <http://www.gnu.org/licenses/>.
<add>
<add># Import system libs
<add># sensors library (optional; Linux-only)
<add>try:
<add> import sensors
<add>except:
<add> pass
<add>
<add>from glances_plugin import GlancesPlugin, getTimeSinceLastUpdate
<add>
<add>
<add>class Plugin(GlancesPlugin):
<add> """
<add> Glances's sensors Plugin
<add>
<add> stats is a list
<add> """
<add>
<add> def __init__(self):
<add> GlancesPlugin.__init__(self)
<add>
<add> # Init the sensor class
<add> self.glancesgrabsensors = glancesGrabSensors()
<add>
<add>
<add> def update(self):
<add> """
<add> Update Sensors stats
<add> """
<add>
<add> self.stats = self.glancesgrabsensors.get()
<add>
<add>
<add> def get_stats(self):
<add> # Return the stats object for the RPC API
<add> # Sort it by label name
<add> # Convert it to string
<add> return str(sorted(self.stats, key=lambda sensors: sensors['label']))
<add>
<add>
<add>class glancesGrabSensors:
<add> """
<add> Get sensors stats using the PySensors library
<add> """
<add>
<add> def __init__(self):
<add> """
<add> Init sensors stats
<add> """
<add> try:
<add> sensors.init()
<add> except Exception:
<add> self.initok = False
<add> else:
<add> self.initok = True
<add>
<add> def __update__(self):
<add> """
<add> Update the stats
<add> """
<add> # Reset the list
<add> self.sensors_list = []
<add>
<add> # grab only temperature stats
<add> if self.initok:
<add> for chip in sensors.iter_detected_chips():
<add> for feature in chip:
<add> sensors_current = {}
<add> if feature.name.startswith('temp'):
<add> sensors_current['label'] = feature.label[:20]
<add> sensors_current['value'] = int(feature.get_value())
<add> self.sensors_list.append(sensors_current)
<add>
<add> def get(self):
<add> self.__update__()
<add> return self.sensors_list
<add>
<add> def quit(self):
<add> if self.initok:
<add> sensors.cleanup()
<ide>\ No newline at end of file
| 6
|
Python
|
Python
|
fix old seq2seqtrainer
|
97b787fb4e59168ca1c9c329884fe24a5292d001
|
<ide><path>examples/seq2seq/seq2seq_trainer.py
<ide> def __init__(self, config=None, data_args=None, *args, **kwargs):
<ide> assert isinstance(
<ide> self.model, PreTrainedModel
<ide> ), f"If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is {self.model.__class__}"
<del> self.config = self._actual_model(self.model).config
<add> self.config = self.model.config
<ide> else:
<ide> self.config = config
<ide>
| 1
|
Python
|
Python
|
corret an issue on memory display
|
2e8276f9403f253b666d63012dadc90a52b6696f
|
<ide><path>glances/glances.py
<ide> def displayMem(self, mem, memswap, proclist, offset_x=0):
<ide> # Display extended informations if space is available
<ide> y = 0
<ide> if screen_x > self.mem_x + offset_x + memblocksize:
<del> # active and inactive (only available for psutil >= 0.6)
<add> # active and inactive (UNIX; only available for psutil >= 0.6)
<ide> if psutil_mem_vm:
<del> # active
<del> if 'active' in mem:
<add> if not is_Windows:
<ide> self.term_window.addnstr(self.mem_y + y,
<ide> self.mem_x + offset_x + 14,
<ide> _("active:"), 7)
<ide> def displayMem(self, mem, memswap, proclist, offset_x=0):
<ide> format(self.__autoUnit(mem['active']), '>5'), 5)
<ide> y += 1
<ide>
<del> # inactive
<del> if 'inactive' in mem:
<ide> self.term_window.addnstr(self.mem_y + y,
<ide> self.mem_x + offset_x + 14,
<ide> _("inactive:"), 9)
<ide> def displayMem(self, mem, memswap, proclist, offset_x=0):
<ide> format(self.__autoUnit(mem['inactive']), '>5'), 5)
<ide> y += 1
<ide>
<del> # buffers (Linux, BSD)
<del> if 'buffers' in mem:
<add> # buffers & cached (Linux, BSD)
<add> if is_Linux or is_Bsd:
<ide> self.term_window.addnstr(self.mem_y + y,
<ide> self.mem_x + offset_x + 14,
<ide> _("buffers:"), 8)
<ide> def displayMem(self, mem, memswap, proclist, offset_x=0):
<ide> format(self.__autoUnit(mem['buffers']), '>5'), 5)
<ide> y += 1
<ide>
<del> # cached (Linux, BSD)
<del> if 'cached' in mem:
<ide> self.term_window.addnstr(self.mem_y + y,
<ide> self.mem_x + offset_x + 14,
<ide> _("cached:"), 7)
<ide> self.term_window.addnstr(
<ide> self.mem_y + y, self.mem_x + offset_x + 24,
<ide> format(self.__autoUnit(mem['cached']), '>5'), 5)
<ide> y += 1
<del>
<ide> else:
<ide> # If space is NOT available then mind the gap...
<ide> offset_x -= extblocksize
| 1
|
Javascript
|
Javascript
|
add picture element and related attributes
|
33bd509737d9e86ac93f4f88921b62e52e5f08e9
|
<ide><path>src/browser/ReactDOM.js
<ide> var ReactDOM = mapObject({
<ide> output: false,
<ide> p: false,
<ide> param: true,
<add> picture: false,
<ide> pre: false,
<ide> progress: false,
<ide> q: false,
<ide><path>src/browser/ui/dom/HTMLDOMPropertyConfig.js
<ide> var HTMLDOMPropertyConfig = {
<ide> loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
<ide> max: null,
<ide> maxLength: MUST_USE_ATTRIBUTE,
<add> media: null,
<ide> mediaGroup: null,
<ide> method: null,
<ide> min: null,
<ide> var HTMLDOMPropertyConfig = {
<ide> selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
<ide> shape: null,
<ide> size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
<add> sizes: null,
<ide> span: HAS_POSITIVE_NUMERIC_VALUE,
<ide> spellCheck: null,
<ide> src: null,
| 2
|
Mixed
|
Go
|
allow swarm init with `--availability=drain`
|
0f30c644441b3b4150252af1b41db99d4b6e697a
|
<ide><path>api/types/swarm/swarm.go
<ide> type InitRequest struct {
<ide> ForceNewCluster bool
<ide> Spec Spec
<ide> AutoLockManagers bool
<add> Availability NodeAvailability
<ide> }
<ide>
<ide> // JoinRequest is the request used to join a swarm.
<ide><path>cli/command/swarm/init.go
<ide> type initOptions struct {
<ide> // Not a NodeAddrOption because it has no default port.
<ide> advertiseAddr string
<ide> forceNewCluster bool
<add> availability string
<ide> }
<ide>
<ide> func newInitCommand(dockerCli command.Cli) *cobra.Command {
<ide> func newInitCommand(dockerCli command.Cli) *cobra.Command {
<ide> flags.StringVar(&opts.advertiseAddr, flagAdvertiseAddr, "", "Advertised address (format: <ip|interface>[:port])")
<ide> flags.BoolVar(&opts.forceNewCluster, "force-new-cluster", false, "Force create a new cluster from current state")
<ide> flags.BoolVar(&opts.autolock, flagAutolock, false, "Enable manager autolocking (requiring an unlock key to start a stopped manager)")
<add> flags.StringVar(&opts.availability, flagAvailability, "active", "Availability of the node (active/pause/drain)")
<ide> addSwarmFlags(flags, &opts.swarmOptions)
<ide> return cmd
<ide> }
<ide> func runInit(dockerCli command.Cli, flags *pflag.FlagSet, opts initOptions) erro
<ide> Spec: opts.swarmOptions.ToSpec(flags),
<ide> AutoLockManagers: opts.swarmOptions.autolock,
<ide> }
<add> if flags.Changed(flagAvailability) {
<add> availability := swarm.NodeAvailability(strings.ToLower(opts.availability))
<add> switch availability {
<add> case swarm.NodeAvailabilityActive, swarm.NodeAvailabilityPause, swarm.NodeAvailabilityDrain:
<add> req.Availability = availability
<add> default:
<add> return fmt.Errorf("invalid availability %q, only active, pause and drain are supported", opts.availability)
<add> }
<add> }
<ide>
<ide> nodeID, err := client.SwarmInit(ctx, req)
<ide> if err != nil {
<ide><path>daemon/cluster/cluster.go
<ide> func (c *Cluster) Init(req types.InitRequest) (string, error) {
<ide> LocalAddr: localAddr,
<ide> ListenAddr: net.JoinHostPort(listenHost, listenPort),
<ide> AdvertiseAddr: net.JoinHostPort(advertiseHost, advertisePort),
<add> availability: req.Availability,
<ide> })
<ide> if err != nil {
<ide> return "", err
<ide><path>docs/reference/commandline/swarm_init.md
<ide> Initialize a swarm
<ide> Options:
<ide> --advertise-addr string Advertised address (format: <ip|interface>[:port])
<ide> --autolock Enable manager autolocking (requiring an unlock key to start a stopped manager)
<add> --availability string Availability of the node (active/pause/drain) (default "active")
<ide> --cert-expiry duration Validity period for node certificates (ns|us|ms|s|m|h) (default 2160h0m0s)
<ide> --dispatcher-heartbeat duration Dispatcher heartbeat period (ns|us|ms|s|m|h) (default 5s)
<ide> --external-ca external-ca Specifications of one or more certificate signing endpoints
<ide> Snapshots compact the Raft log and allow for more efficient transfer of the
<ide> state to new managers. However, there is a performance cost to taking snapshots
<ide> frequently.
<ide>
<add>### `--availability`
<add>
<add>This flag specifies the availability of the node at the time the node joins a master.
<add>Possible availability values are `active`, `pause`, or `drain`.
<add>
<add>This flag is useful in certain situations. For example, a cluster may want to have
<add>dedicated manager nodes that are not served as worker nodes. This could be achieved
<add>by passing `--availability=drain` to `docker swarm init`.
<add>
<add>
<ide> ## Related information
<ide>
<ide> * [swarm join](swarm_join.md)
<ide><path>integration-cli/docker_cli_swarm_test.go
<ide> func (s *DockerSwarmSuite) TestSwarmJoinWithDrain(c *check.C) {
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(out, checker.Contains, "Drain")
<ide> }
<add>
<add>func (s *DockerSwarmSuite) TestSwarmInitWithDrain(c *check.C) {
<add> d := s.AddDaemon(c, false, false)
<add>
<add> out, err := d.Cmd("swarm", "init", "--availability", "drain")
<add> c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
<add>
<add> out, err = d.Cmd("node", "ls")
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(out, checker.Contains, "Drain")
<add>}
| 5
|
Javascript
|
Javascript
|
consolidate work loops
|
db8539a47d32772e022689959296798bf59ec0c6
|
<ide><path>src/renderers/shared/fiber/ReactFiberScheduler.js
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide> SynchronousPriority :
<ide> LowPriority;
<ide>
<del> // Whether updates should be batched. Only applies when using sync scheduling.
<del> let shouldBatchUpdates : boolean = false;
<del>
<del> // Need this to prevent recursion while in a Task loop.
<del> let isPerformingTaskWork : boolean = false;
<add> // Keeps track of whether we're currently in a work loop. Used to batch
<add> // nested updates.
<add> let isPerformingWork : boolean = false;
<ide>
<ide> // The next work in progress fiber that we're currently working on.
<ide> let nextUnitOfWork : ?Fiber = null;
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide> ReactFiberInstrumentation.debugTool.onWillBeginWork(workInProgress);
<ide> }
<ide> // See if beginning this work spawns more work.
<del> let next;
<del> const isFailedWork = capturedErrors && capturedErrors.has(workInProgress);
<del> if (isFailedWork) {
<del> next = beginFailedWork(current, workInProgress, nextPriorityLevel);
<del> workInProgress.effectTag |= Err;
<del> } else {
<del> next = beginWork(current, workInProgress, nextPriorityLevel);
<del> }
<add> let next = beginWork(current, workInProgress, nextPriorityLevel);
<ide>
<ide> if (__DEV__ && ReactFiberInstrumentation.debugTool) {
<ide> ReactFiberInstrumentation.debugTool.onDidBeginWork(workInProgress);
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide> return next;
<ide> }
<ide>
<del> function performDeferredWorkUnsafe(deadline) {
<del> if (!nextUnitOfWork && !pendingCommit) {
<del> nextUnitOfWork = findNextUnitOfWork();
<add> function performFailedUnitOfWork(workInProgress : Fiber) : ?Fiber {
<add> // The current, flushed, state of this fiber is the alternate.
<add> // Ideally nothing should rely on this, but relying on it here
<add> // means that we don't need an additional field on the work in
<add> // progress.
<add> const current = workInProgress.alternate;
<add>
<add> if (__DEV__ && ReactFiberInstrumentation.debugTool) {
<add> ReactFiberInstrumentation.debugTool.onWillBeginWork(workInProgress);
<ide> }
<del> while (nextUnitOfWork || pendingCommit) {
<del> if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) {
<del> if (pendingCommit) {
<del> nextUnitOfWork = commitAllWork(pendingCommit);
<del> } else if (nextUnitOfWork) {
<del> nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
<del> }
<del> if (!nextUnitOfWork && !pendingCommit) {
<del> // Find more work. We might have time to complete some more.
<del> nextUnitOfWork = findNextUnitOfWork();
<del> }
<del> } else {
<del> scheduleDeferredCallback(performDeferredWork);
<del> return;
<add> // See if beginning this work spawns more work.
<add> let next = beginFailedWork(current, workInProgress, nextPriorityLevel);
<add> workInProgress.effectTag |= Err;
<add>
<add> if (__DEV__ && ReactFiberInstrumentation.debugTool) {
<add> ReactFiberInstrumentation.debugTool.onDidBeginWork(workInProgress);
<add> }
<add>
<add> if (!next) {
<add> if (__DEV__ && ReactFiberInstrumentation.debugTool) {
<add> ReactFiberInstrumentation.debugTool.onWillCompleteWork(workInProgress);
<add> }
<add> // If this doesn't spawn new work, complete the current work.
<add> next = completeUnitOfWork(workInProgress);
<add> if (__DEV__ && ReactFiberInstrumentation.debugTool) {
<add> ReactFiberInstrumentation.debugTool.onDidCompleteWork(workInProgress);
<ide> }
<ide> }
<add>
<add> ReactCurrentOwner.current = null;
<add>
<add> return next;
<ide> }
<ide>
<ide> function performDeferredWork(deadline) {
<add> // We pass the lowest deferred priority here because it acts as a minimum.
<add> // Higher priorities will also be performed.
<ide> isDeferredCallbackScheduled = false;
<del> performAndHandleErrors(LowPriority, deadline);
<del> }
<del>
<del> function performAnimationWorkUnsafe() {
<del> if (!nextUnitOfWork && !pendingCommit) {
<del> nextUnitOfWork = findNextUnitOfWork();
<del> }
<del> while (
<del> pendingCommit ||
<del> (nextUnitOfWork && nextPriorityLevel === AnimationPriority)
<del> ) {
<del> if (pendingCommit) {
<del> nextUnitOfWork = commitAllWork(pendingCommit);
<del> } else if (nextUnitOfWork) {
<del> nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
<del> }
<del> if (!nextUnitOfWork && !pendingCommit) {
<del> // Keep searching for animation work until there's no more left
<del> nextUnitOfWork = findNextUnitOfWork();
<del> }
<del> }
<del> if (nextUnitOfWork) {
<del> scheduleCallbackAtPriority(nextPriorityLevel);
<del> }
<add> performWork(OffscreenPriority, deadline);
<ide> }
<ide>
<ide> function performAnimationWork() {
<ide> isAnimationCallbackScheduled = false;
<del> performAndHandleErrors(AnimationPriority);
<add> performWork(AnimationPriority);
<ide> }
<ide>
<del> function performSynchronousWorkUnsafe() {
<del> if (!nextUnitOfWork && !pendingCommit) {
<del> nextUnitOfWork = findNextUnitOfWork();
<del> }
<del> while (
<del> pendingCommit ||
<del> (nextUnitOfWork && nextPriorityLevel === SynchronousPriority)
<del> ) {
<del> if (pendingCommit) {
<del> nextUnitOfWork = commitAllWork(pendingCommit);
<del> } else if (nextUnitOfWork) {
<del> nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
<add> function workLoop(priorityLevel) {
<add> // If there are errors, use a forked version of performUnitOfWork
<add> // TODO: Need to make commitAllWork throw on error before doing this
<add> if (true || (capturedErrors && capturedErrors.size)) {
<add> while (true) {
<add> if (!nextUnitOfWork && !pendingCommit) {
<add> nextUnitOfWork = findNextUnitOfWork();
<add> }
<add> if (pendingCommit && !(priorityLevel === TaskPriority && pendingCommit.pendingWorkPriority !== TaskPriority)) {
<add> nextUnitOfWork = commitAllWork(pendingCommit);
<add> } else if (nextUnitOfWork && nextPriorityLevel !== NoWork && nextPriorityLevel <= priorityLevel) {
<add> if (capturedErrors && capturedErrors.has(nextUnitOfWork)) {
<add> nextUnitOfWork = performFailedUnitOfWork(nextUnitOfWork);
<add> } else {
<add> nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
<add> }
<add> } else {
<add> return;
<add> }
<ide> }
<add> }
<add>
<add> // Otherwise, handle the normal, faster case where there are no errors:
<add> while (true) {
<ide> if (!nextUnitOfWork && !pendingCommit) {
<del> // Keep searching for sync work until there's no more left
<ide> nextUnitOfWork = findNextUnitOfWork();
<ide> }
<del> }
<del> if (nextUnitOfWork) {
<del> scheduleCallbackAtPriority(nextPriorityLevel);
<add> if (pendingCommit && !(priorityLevel === TaskPriority && pendingCommit.pendingWorkPriority !== TaskPriority)) {
<add> nextUnitOfWork = commitAllWork(pendingCommit);
<add> } else if (nextUnitOfWork && nextPriorityLevel !== NoWork && nextPriorityLevel <= priorityLevel) {
<add> nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
<add> } else {
<add> return;
<add> }
<ide> }
<ide> }
<ide>
<del> function performSynchronousWork() {
<del> performAndHandleErrors(SynchronousPriority);
<del> }
<del>
<del> function performTaskWorkUnsafe() {
<del> if (isPerformingTaskWork) {
<del> throw new Error('Already performing task work');
<add> function deferredWorkLoop(deadline) {
<add> if (!nextUnitOfWork) {
<add> nextUnitOfWork = findNextUnitOfWork();
<ide> }
<ide>
<del> isPerformingTaskWork = true;
<del> try {
<del> if (!nextUnitOfWork && !pendingCommit) {
<del> nextUnitOfWork = findNextUnitOfWork();
<add> // If there are errors, use a forked version of performUnitOfWork
<add> // TODO: Need to make commitAllWork throw on error before doing this
<add> if (true || (capturedErrors && capturedErrors.size)) {
<add> while (true) {
<add> if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) {
<add> if (!nextUnitOfWork && !pendingCommit) {
<add> nextUnitOfWork = findNextUnitOfWork();
<add> }
<add> if (pendingCommit) {
<add> nextUnitOfWork = commitAllWork(pendingCommit);
<add> } else if (nextUnitOfWork) {
<add> if (capturedErrors && capturedErrors.has(nextUnitOfWork)) {
<add> nextUnitOfWork = performFailedUnitOfWork(nextUnitOfWork);
<add> } else {
<add> nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
<add> }
<add> } else {
<add> return;
<add> }
<add> } else {
<add> return;
<add> }
<ide> }
<del> while (
<del> (pendingCommit && pendingCommit.pendingWorkPriority === TaskPriority) ||
<del> (nextUnitOfWork && nextPriorityLevel === TaskPriority)
<del> ) {
<del> if (pendingCommit && pendingCommit.pendingWorkPriority === TaskPriority) {
<add> }
<add>
<add> // Otherwise, handle the normal, faster case where there are no errors:
<add> while (true) {
<add> if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) {
<add> if (!nextUnitOfWork && !pendingCommit) {
<add> nextUnitOfWork = findNextUnitOfWork();
<add> }
<add> if (pendingCommit) {
<ide> nextUnitOfWork = commitAllWork(pendingCommit);
<ide> } else if (nextUnitOfWork) {
<ide> nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
<add> } else {
<add> return;
<ide> }
<del> if (!nextUnitOfWork && !pendingCommit) {
<del> // Keep searching for sync work until there's no more left
<del> nextUnitOfWork = findNextUnitOfWork();
<del> }
<del> }
<del> if (nextUnitOfWork) {
<del> scheduleCallbackAtPriority(nextPriorityLevel);
<add> } else {
<add> return;
<ide> }
<del> } finally {
<del> isPerformingTaskWork = false;
<ide> }
<ide> }
<ide>
<del> function performTaskWork() {
<del> performAndHandleErrors(TaskPriority);
<del> }
<add> function performWork(priorityLevel : PriorityLevel, deadline : null | Deadline) {
<add> if (isPerformingWork) {
<add> throw new Error('performWork was called recursively.');
<add> }
<add> isPerformingWork = true;
<ide>
<del> function performAndHandleErrors(priorityLevel : PriorityLevel, deadline : null | Deadline) {
<del> // The exact priority level doesn't matter, so long as it's in range of the
<del> // work (sync, animation, deferred) being performed.
<del> let shouldContinue = true;
<del> while (shouldContinue) {
<del> shouldContinue = false;
<del> const prevShouldBatchUpdates = shouldBatchUpdates;
<del> shouldBatchUpdates = true;
<add> // Perform work until either there's no more work at this priority level, or
<add> // (in the case of deferred work) we've run out of time.
<add> while (priorityLevel !== NoWork) {
<add> // Functions that contain a try-catch block are not optimizable by the
<add> // JS engine. The hottest code paths have been extracted to separate
<add> // functions, workLoop and deferredWorkLoop, which run on every unit of
<add> // work. The loop we're in now runs infrequently: to flush task work at
<add> // the end of a frame, or to restart after an error.
<ide> try {
<del> switch (priorityLevel) {
<add> if (priorityLevel >= HighPriority) {
<add> if (!deadline) {
<add> throw new Error('Cannot perform deferred work without a deadline.');
<add> }
<add> // The deferred work loop will run until there's no time left in
<add> // the current frame
<add> deferredWorkLoop(deadline);
<add> } else {
<add> // The non-deferred work loop will run until there's no more work
<add> // at the given priority level
<add> workLoop(priorityLevel);
<add> }
<add>
<add> // Stop performing work
<add> priorityLevel = NoWork;
<add>
<add> // There might still be work left. Depending on the priority, we should
<add> // either perform it now or schedule a callback to perform it later.
<add> switch (nextPriorityLevel) {
<ide> case SynchronousPriority:
<del> performSynchronousWorkUnsafe();
<del> break;
<ide> case TaskPriority:
<del> if (!isPerformingTaskWork) {
<del> performTaskWorkUnsafe();
<del> }
<add> // Perform work immediately by switching the priority level
<add> // and continuing the loop.
<add> priorityLevel = nextPriorityLevel;
<ide> break;
<ide> case AnimationPriority:
<del> performAnimationWorkUnsafe();
<add> scheduleAnimationCallback(performAnimationWork);
<add> // Even though the next unit of work has animation priority, there
<add> // may still be deferred work left over as well. I think this is
<add> // only important for unit tests. In a real app, a deferred callback
<add> // would be scheduled during the next animation frame.
<add> scheduleDeferredCallback(performDeferredWork);
<ide> break;
<ide> case HighPriority:
<ide> case LowPriority:
<ide> case OffscreenPriority:
<del> if (!deadline) {
<del> throw new Error('No deadline');
<del> } else {
<del> performDeferredWorkUnsafe(deadline);
<del> }
<del> break;
<del> default:
<add> scheduleDeferredCallback(performDeferredWork);
<ide> break;
<ide> }
<ide> } catch (error) {
<add> // We caught an error during either the begin or complete phases.
<ide> const failedWork = nextUnitOfWork;
<del> const boundary = captureError(failedWork, error, false);
<del> if (boundary) {
<del> // The boundary failed to complete. Complete it as if rendered null.
<add>
<add> // "Capture" the error by finding the nearest boundary. If there is no
<add> // error boundary, the nearest host container acts as one.
<add> const maybeBoundary = captureError(failedWork, error, false);
<add> if (maybeBoundary) {
<add> const boundary = maybeBoundary;
<add>
<add> // Schedule an Task update on the boundary
<add> const previousPriorityContext = priorityContext;
<add> priorityContext = TaskPriority;
<add> scheduleUpdate(boundary);
<add> priorityContext = previousPriorityContext;
<add>
<add> // Complete the boundary as if rendered null.
<ide> beginFailedWork(boundary.alternate, boundary, priorityLevel);
<ide>
<ide> // The next unit of work is now the boundary that captured the error.
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide> unwindContext(failedWork, boundary);
<ide> }
<ide> nextUnitOfWork = completeUnitOfWork(boundary);
<del>
<del> // We were interupted by an error. Continue performing work.
<del> shouldContinue = true;
<ide> }
<del> } finally {
<del> shouldBatchUpdates = prevShouldBatchUpdates;
<add> // The loop will continue performing work
<ide> }
<ide> }
<ide>
<del> // Flush any task work that was scheduled during this batch
<del> if (priorityLevel !== TaskPriority) {
<del> performTaskWork();
<add> // We're done performing work. Time to clean up.
<add> isPerformingWork = false;
<add> if (capturedErrors && !capturedErrors.size) {
<add> capturedErrors = null;
<ide> }
<ide>
<del> // Throw the first uncaught error
<del> if (!nextUnitOfWork && firstUncaughtError) {
<add> // It's now safe to throw the first uncaught error.
<add> if (firstUncaughtError) {
<ide> let e = firstUncaughtError;
<ide> firstUncaughtError = null;
<ide> throw e;
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide> let priorityLevel = priorityContext;
<ide>
<ide> // If we're in a batch, switch to task priority
<del> if (priorityLevel === SynchronousPriority && shouldBatchUpdates) {
<add> if (priorityLevel === SynchronousPriority && isPerformingWork) {
<ide> priorityLevel = TaskPriority;
<ide> }
<ide>
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide> }
<ide> }
<ide>
<del> // We must reset the current unit of work pointer so that we restart the
<del> // search from the root during the next tick, in case there is now higher
<del> // priority work somewhere earlier than before.
<ide> if (priorityLevel <= nextPriorityLevel) {
<add> // We must reset the current unit of work pointer so that we restart the
<add> // search from the root during the next tick, in case there is now higher
<add> // priority work somewhere earlier than before.
<ide> nextUnitOfWork = null;
<ide> }
<ide>
<del> scheduleCallbackAtPriority(priorityLevel);
<del> }
<del>
<del> function scheduleCallbackAtPriority(priorityLevel : PriorityLevel) {
<add> // Depending on the priority level, either perform work now or schedule
<add> // a callback to perform work later.
<ide> switch (priorityLevel) {
<ide> case SynchronousPriority:
<ide> // Perform work immediately
<del> performSynchronousWork();
<add> performWork(SynchronousPriority);
<ide> return;
<ide> case TaskPriority:
<del> // Do nothing. Task work should be flushed after committing.
<add> // If we're already performing work, Task work will be flushed before
<add> // exiting the current batch. So we can skip it here.
<add> if (!isPerformingWork) {
<add> performWork(TaskPriority);
<add> }
<ide> return;
<ide> case AnimationPriority:
<ide> scheduleAnimationCallback(performAnimationWork);
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide>
<ide> function scheduleUpdate(fiber : Fiber) {
<ide> let priorityLevel = priorityContext;
<del> // If we're in a batch, switch to task priority
<del> if (priorityLevel === SynchronousPriority && shouldBatchUpdates) {
<add> // If we're in a batch, downgrade sync priority to task priority
<add> if (priorityLevel === SynchronousPriority && isPerformingWork) {
<ide> priorityLevel = TaskPriority;
<ide> }
<ide>
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide> }
<ide>
<ide> function batchedUpdates<A, R>(fn : (a: A) => R, a : A) : R {
<del> const prev = shouldBatchUpdates;
<del> shouldBatchUpdates = true;
<add> const previousIsPerformingWork = isPerformingWork;
<add> // Simulate that we're performing work so that sync work is batched
<add> isPerformingWork = true;
<ide> try {
<ide> return fn(a);
<ide> } finally {
<del> // If we're exiting the batch, perform any scheduled task work
<del> try {
<del> if (!prev) {
<del> performTaskWork();
<del> }
<del> } finally {
<del> shouldBatchUpdates = prev;
<add> isPerformingWork = previousIsPerformingWork;
<add> // If we're not already performing work, we need to flush any task work
<add> // that was created by the user-provided function.
<add> if (!isPerformingWork) {
<add> performWork(TaskPriority);
<ide> }
<ide> }
<ide> }
<ide><path>src/renderers/shared/fiber/__tests__/ReactIncremental-test.js
<ide> describe('ReactIncremental', () => {
<ide> ]);
<ide> expect(instance.state.n).toEqual(4);
<ide> });
<add>
<ide> it('can handle if setState callback throws', () => {
<ide> var ops = [];
<ide> var instance;
<ide><path>src/renderers/shared/fiber/__tests__/ReactIncrementalErrorHandling-test.js
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> expect(ReactNoop.getChildren()).toEqual([]);
<ide>
<ide> ops.length = 0;
<del> ReactNoop.flushDeferredPri(30 + 5 + 5 + 5);
<add> ReactNoop.flushDeferredPri(30 + 5 + 5 + 5 + 5);
<ide> expect(ops).toEqual([
<ide> 'BrokenRender',
<ide> 'ErrorBoundary unstable_handleError',
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> 'BrokenRender',
<ide> ]);
<ide> ops = [];
<del> ReactNoop.flushDeferredPri(25 + 5 + 5);
<add> ReactNoop.flushDeferredPri(25 + 5 + 5 + 5);
<ide> expect(ops).toEqual([
<ide> 'ErrorBoundary unstable_handleError',
<ide> 'ErrorBoundary render error',
<ide><path>src/renderers/shared/fiber/__tests__/ReactIncrementalScheduling-test.js
<ide> describe('ReactIncrementalScheduling', () => {
<ide> expect(ReactNoop.getChildren('b')).toEqual([]);
<ide> expect(ReactNoop.getChildren('c')).toEqual(null);
<ide> // Then the second one gets processed
<del> ReactNoop.flushDeferredPri(15 + 5);
<add> ReactNoop.flushDeferredPri(15 + 5 + 5);
<ide> expect(ReactNoop.getChildren('a')).toEqual([span('a:2')]);
<ide> expect(ReactNoop.getChildren('b')).toEqual([span('b:2')]);
<ide> expect(ReactNoop.getChildren('c')).toEqual(null);
<ide> describe('ReactIncrementalScheduling', () => {
<ide>
<ide> ReactNoop.render(<Foo />);
<ide>
<del> ReactNoop.flushDeferredPri(20 + 5);
<add> ReactNoop.flushDeferredPri(20 + 5 + 5);
<ide> expect(ops).toEqual([
<ide> 'render: 0',
<ide> 'componentDidMount (before setState): 0',
<ide> describe('ReactIncrementalScheduling', () => {
<ide>
<ide> ops = [];
<ide> instance.setState({ tick: 2 });
<del> ReactNoop.flushDeferredPri(20 + 5);
<add> ReactNoop.flushDeferredPri(20 + 5 + 5);
<ide>
<ide> expect(ops).toEqual([
<ide> 'render: 2',
| 4
|
PHP
|
PHP
|
add prohibited validation rule
|
e464182760dfae06f68347f3f56ec4baec6e0c60
|
<ide><path>resources/lang/en/validation.php
<ide> 'required_with_all' => 'The :attribute field is required when :values are present.',
<ide> 'required_without' => 'The :attribute field is required when :values is not present.',
<ide> 'required_without_all' => 'The :attribute field is required when none of :values are present.',
<add> 'prohibited' => 'The :attribute field is prohibited.',
<ide> 'prohibited_if' => 'The :attribute field is prohibited when :other is :value.',
<ide> 'prohibited_unless' => 'The :attribute field is prohibited unless :other is in :values.',
<ide> 'same' => 'The :attribute and :other must match.',
| 1
|
Python
|
Python
|
ensure path in save_to_directory
|
e2299dc389bbf84ee1bd56edc23202ec5f9249e2
|
<ide><path>spacy/language.py
<ide> def save_to_directory(self, path):
<ide> 'ner': self.entity.cfg if self.entity else {},
<ide> }
<ide>
<add> path = util.ensure_path(path)
<ide> self.setup_directory(path, **configs)
<ide>
<ide> strings_loc = path / 'vocab' / 'strings.json'
| 1
|
Text
|
Text
|
clarify use of script
|
cd4798415259e932a18b91e883cb76f754067f0a
|
<ide><path>docs/basic-features/script.md
<ide> description: Next.js helps you optimize loading third-party scripts with the bui
<ide>
<ide> </details>
<ide>
<del>The Next.js Script component, [`next/script`](/docs/api-reference/next/script.md), is an extension of the HTML `<script>` element. It enables developers to set the loading priority of third-party scripts anywhere in their application without needing to append directly to `next/head`, saving developer time while improving loading performance.
<add>The Next.js Script component, [`next/script`](/docs/api-reference/next/script.md), is an extension of the HTML `<script>` element. It enables developers to set the loading priority of third-party scripts anywhere in their application, outside `next/head`, saving developer time while improving loading performance.
<ide>
<ide> ```jsx
<ide> import Script from 'next/script'
| 1
|
Javascript
|
Javascript
|
add prerelease flag and find right zip
|
b1ac2e024914caca1557ccec255db7577a860308
|
<ide><path>build/gh-release.js
<ide> var ghrelease = require('gh-release');
<ide> var currentChangelog = require('./current-changelog.js');
<ide> var safeParse = require('safe-json-parse/tuple');
<ide> var pkg = require('../package.json')
<add>var minimist = require('minimist');
<add>
<add>var args = minimist(process.argv.slice(2), {
<add> boolean: ['prerelease'],
<add> default: {
<add> prerelease: false
<add> },
<add> alias: {
<add> p: 'prerelease'
<add> }
<add>}
<ide>
<ide> var options = {
<ide> owner: 'videojs',
<ide> repo: 'video.js',
<ide> body: currentChangelog(),
<del> assets: ['./dist/videojs-'+pkg.version+'.zip'],
<add> assets: ['./dist/video-js-'+pkg.version+'.zip'],
<ide> endpoint: 'https://api.github.com',
<ide> auth: {
<ide> username: process.env.VJS_GITHUB_USER,
<ide> var options = {
<ide> var tuple = safeParse(process.env.npm_config_argv);
<ide> var npmargs = tuple[0] ? [] : tuple[1].cooked;
<ide>
<del>if (npmargs.some(function(arg) { return /next/.test(arg); })) {
<add>if (args.prerelease || npmargs.some(function(arg) { return /next/.test(arg); })) {
<ide> options.prerelease = true;
<ide> }
<ide>
| 1
|
Javascript
|
Javascript
|
fix minor grammatical error in documentation
|
4447bff97678ebfaa3bf32528f69ab27530736f3
|
<ide><path>Libraries/CustomComponents/Navigator/Navigator.js
<ide> var GESTURE_ACTIONS = [
<ide> * - `replacePrevious(route)` - Replace the previous scene
<ide> * - `immediatelyResetRouteStack(routeStack)` - Reset every scene with an
<ide> * array of routes
<del> * - `popToRoute(route)` - Pop to a particular scene, as specified by it's
<add> * - `popToRoute(route)` - Pop to a particular scene, as specified by its
<ide> * route. All scenes after it will be unmounted
<ide> * - `popToTop()` - Pop to the first scene in the stack, unmounting every
<ide> * other scene
| 1
|
Text
|
Text
|
add xcode 6.4
|
ec4bfee3e72f6fe438455ace35ca2126a7134ba1
|
<ide><path>share/doc/homebrew/Xcode.md
<ide> Tools available for your platform:
<ide> 10.7 | 4.6.3 | April 2013
<ide> 10.8 | 5.1.1 | April 2014
<ide> 10.9 | 6.2 | 6.2
<del> 10.10 | 6.3.2 | 6.3.2
<add> 10.10 | 6.4 | 6.4
<ide>
<ide>
<ide> ## Compiler Version Database
<ide> Tools available for your platform:
<ide> 6.3 | — | — | — | — | 6.1 (602.0.49) | 3.6
<ide> 6.3.1 | — | — | — | — | 6.1 (602.0.49) | 3.6
<ide> 6.3.2 | — | — | — | — | 6.1 (602.0.53) | 3.6
<add> 6.4 | — | — | — | — | 6.1 (602.0.53) | 3.6
<ide>
<ide> ## References to Xcode and compiler versions in code
<ide> When a new Xcode release is made, the following things need to be
| 1
|
Text
|
Text
|
add man page
|
d53d0cf88dbc59b48bc54466b4e736e4062380e7
|
<ide><path>guide/english/bash/bash-cat/index.md
<del>---
<del>title: Bash cat
<del>---
<del>
<del>## Bash command: cat
<del>
<del>The bash command `cat` is one of the most frequently used commands in Unix operating systems. It is used to read a file sequentially and print it to the standard output.
<del>The command's name is derived from its function to con**cat**enate files.
<del>
<del>The cat command can also be used to create a text file.
<del>
<del>### Usage
<del>
<del>```bash
<del>cat [options] [file_names]
<del>```
<del>
<del>Most used options:
<del>
<del>* `-b`, numer non-blank output lines
<del>* `-n`, number all output lines
<del>* `-s`, squeeze multiple adjacent blank lines
<del>* `-v`, display nonprinting characters, except for tabs and the end of line character
<del>
<del>### Example
<del>
<del>Print in terminal the content of file.txt:
<del>```bash
<del>cat file.txt
<del>```
<del>
<del>Concatenate the content of the two files and display the result in terminal:
<del>```bash
<del>cat file1.txt file2.txt
<del>```
<del>
<del>Concatenate the content of two files and store it in a new file:
<del>```bash
<del>cat file1.txt file2.txt > new_file.txt
<del>```
<del>
<del>Creating a new text file:
<del>```bash
<del>cat > yourfile.txt
<del>```
<del>After pressing Enter, the cursor will be placed on the next line. You can start entering your desired text directly into your file. Press Ctrl+D or Ctrl+C to exit the file.
<del>
<del>**Tip**: Using `cat` on a directory will cause error, so make sure it's a readable file.
<del>
<del>#### More Information:
<del>* Wikipedia: https://en.wikipedia.org/wiki/Cat_(Unix)
<add>---
<add>title: Bash cat
<add>---
<add>
<add>## Bash command: cat
<add>
<add>The bash command `cat` is one of the most frequently used commands in Unix operating systems. It is used to read a file sequentially and print it to the standard output.
<add>The command's name is derived from its function to con**cat**enate files.
<add>
<add>The cat command can also be used to create a text file.
<add>
<add>### Usage
<add>
<add>```bash
<add>cat [options] [file_names]
<add>```
<add>
<add>Most used options:
<add>
<add>* `-b`, numer non-blank output lines
<add>* `-n`, number all output lines
<add>* `-s`, squeeze multiple adjacent blank lines
<add>* `-v`, display nonprinting characters, except for tabs and the end of line character
<add>
<add>### Example
<add>
<add>Print in terminal the content of file.txt:
<add>```bash
<add>cat file.txt
<add>```
<add>
<add>Concatenate the content of the two files and display the result in terminal:
<add>```bash
<add>cat file1.txt file2.txt
<add>```
<add>
<add>Concatenate the content of two files and store it in a new file:
<add>```bash
<add>cat file1.txt file2.txt > new_file.txt
<add>```
<add>
<add>Creating a new text file:
<add>```bash
<add>cat > yourfile.txt
<add>```
<add>After pressing Enter, the cursor will be placed on the next line. You can start entering your desired text directly into your file. Press Ctrl+D or Ctrl+C to exit the file.
<add>
<add>**Tip**: Using `cat` on a directory will cause error, so make sure it's a readable file.
<add>
<add>#### More Information:
<add>* Wikipedia: https://en.wikipedia.org/wiki/Cat_(Unix)
<add>* Man Page: https://ss64.com/bash/cat.html
| 1
|
Text
|
Text
|
add license information
|
44878e623faaee327024d1f3b9b0301e6fc0e234
|
<ide><path>README.md
<ide> Who Are You?
<ide> ------------
<ide> I'm [Max Howell][mxcl] and I'm a splendid chap.
<ide>
<add>License
<add>-------
<add>Code is under the [BSD 2 Clause (NetBSD) license][license].
<ide>
<ide> [home]:http://brew.sh
<ide> [wiki]:http://wiki.github.com/mxcl/homebrew
<ide> [mxcl]:http://twitter.com/mxcl
<ide> [formula]:http://github.com/mxcl/homebrew/tree/master/Library/Formula/
<ide> [braumeister]:http://braumeister.org
<add>[license]:https://github.com/mxcl/homebrew/tree/master/Library/Homebrew/LICENSE
| 1
|
Javascript
|
Javascript
|
create a tick typedef
|
428411319a24d2d8e4823a80a07fd3038fcc6dfa
|
<ide><path>src/core/core.scale.js
<ide> import Ticks from './core.ticks';
<ide>
<ide> /**
<ide> * @typedef { import("./core.controller").default } Chart
<add> * @typedef {{value:any, label?:string, major?:boolean}} Tick
<ide> */
<ide>
<ide> defaults.set('scale', {
<ide> defaults.set('scale', {
<ide> }
<ide> });
<ide>
<del>/** Returns a new array containing numItems from arr */
<add>/**
<add> * Returns a new array containing numItems from arr
<add> * @param {any[]} arr
<add> * @param {number} numItems
<add> */
<ide> function sample(arr, numItems) {
<ide> const result = [];
<ide> const increment = arr.length / numItems;
<ide> function sample(arr, numItems) {
<ide> return result;
<ide> }
<ide>
<add>/**
<add> * @param {Scale} scale
<add> * @param {number} index
<add> * @param {boolean} offsetGridLines
<add> */
<ide> function getPixelForGridLine(scale, index, offsetGridLines) {
<ide> const length = scale.ticks.length;
<ide> const validIndex = Math.min(index, length - 1);
<ide> function getPixelForGridLine(scale, index, offsetGridLines) {
<ide> return lineValue;
<ide> }
<ide>
<add>/**
<add> * @param {object} caches
<add> * @param {number} length
<add> */
<ide> function garbageCollect(caches, length) {
<ide> each(caches, (cache) => {
<ide> const gc = cache.gc;
<ide> function garbageCollect(caches, length) {
<ide> });
<ide> }
<ide>
<add>/**
<add> * @param {object} options
<add> */
<ide> function getTickMarkLength(options) {
<ide> return options.drawTicks ? options.tickMarkLength : 0;
<ide> }
<ide>
<add>/**
<add> * @param {object} options
<add> */
<ide> function getScaleLabelHeight(options) {
<ide> if (!options.display) {
<ide> return 0;
<ide> function getScaleLabelHeight(options) {
<ide> return font.lineHeight + padding.height;
<ide> }
<ide>
<add>/**
<add> * @param {number[]} arr
<add> */
<ide> function getEvenSpacing(arr) {
<ide> const len = arr.length;
<ide> let i, diff;
<ide> function getEvenSpacing(arr) {
<ide> return diff;
<ide> }
<ide>
<add>/**
<add> * @param {number[]} majorIndices
<add> * @param {Tick[]} ticks
<add> * @param {number} axisLength
<add> * @param {number} ticksLimit
<add> */
<ide> function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
<ide> const evenMajorSpacing = getEvenSpacing(majorIndices);
<ide> const spacing = ticks.length / ticksLimit;
<ide> function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
<ide> return Math.max(spacing, 1);
<ide> }
<ide>
<add>/**
<add> * @param {Tick[]} ticks
<add> */
<ide> function getMajorIndices(ticks) {
<ide> const result = [];
<ide> let i, ilen;
<ide> function getMajorIndices(ticks) {
<ide> return result;
<ide> }
<ide>
<add>/**
<add> * @param {Tick[]} ticks
<add> * @param {Tick[]} newTicks
<add> * @param {number[]} majorIndices
<add> * @param {number} spacing
<add> */
<ide> function skipMajors(ticks, newTicks, majorIndices, spacing) {
<ide> let count = 0;
<ide> let next = majorIndices[0];
<ide> function skipMajors(ticks, newTicks, majorIndices, spacing) {
<ide> }
<ide> }
<ide>
<add>/**
<add> * @param {Tick[]} ticks
<add> * @param {Tick[]} newTicks
<add> * @param {number} spacing
<add> * @param {number} [majorStart]
<add> * @param {number} [majorEnd]
<add> */
<ide> function skip(ticks, newTicks, spacing, majorStart, majorEnd) {
<ide> const start = valueOrDefault(majorStart, 0);
<ide> const end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length);
<ide> export default class Scale extends Element {
<ide> this.labelRotation = undefined;
<ide> this.min = undefined;
<ide> this.max = undefined;
<del> /** @type {object[]} */
<add> /** @type {Tick[]} */
<ide> this.ticks = [];
<ide> /** @type {object[]|null} */
<ide> this._gridLineItems = null;
<ide> export default class Scale extends Element {
<ide> }
<ide>
<ide> /**
<del> * Returns the scale tick objects ({label, major})
<del> * @return {object[]}
<add> * Returns the scale tick objects
<add> * @return {Tick[]}
<ide> * @since 2.7
<ide> */
<ide> getTicks() {
<ide> export default class Scale extends Element {
<ide> }
<ide> /**
<ide> * Convert ticks to label strings
<del> * @param {object[]} ticks
<add> * @param {Tick[]} ticks
<ide> */
<ide> generateTickLabels(ticks) {
<ide> const me = this;
<ide> export default class Scale extends Element {
<ide> }
<ide>
<ide> /**
<del> * @param {object[]} ticks
<add> * @param {Tick[]} ticks
<ide> * @private
<ide> */
<ide> _convertTicksToLabels(ticks) {
<ide> export default class Scale extends Element {
<ide>
<ide> /**
<ide> * Returns a subset of ticks to be plotted to avoid overlapping labels.
<del> * @param {object[]} ticks
<del> * @return {object[]}
<add> * @param {Tick[]} ticks
<add> * @return {Tick[]}
<ide> * @private
<ide> */
<ide> _autoSkip(ticks) {
<ide> export default class Scale extends Element {
<ide> const alignBorderValue = function(pixel) {
<ide> return _alignPixel(chart, pixel, axisWidth);
<ide> };
<del> let borderValue, i, tick, lineValue, alignedLineValue;
<add> let borderValue, i, lineValue, alignedLineValue;
<ide> let tx1, ty1, tx2, ty2, x1, y1, x2, y2;
<ide>
<ide> if (position === 'top') {
<ide> export default class Scale extends Element {
<ide> }
<ide>
<ide> for (i = 0; i < ticksLength; ++i) {
<del> tick = ticks[i] || {};
<add> /** @type {Tick|object} */
<add> const tick = ticks[i] || {};
<ide>
<ide> context = {
<ide> scale: me,
| 1
|
PHP
|
PHP
|
rewrite request construction
|
646120a57219f8185f1ec946673ebfccee4e51d1
|
<ide><path>lib/Cake/Network/Request.php
<ide> class Request implements \ArrayAccess {
<ide> */
<ide> protected $_input = '';
<ide>
<add>/**
<add> * Wrapper method to create a new request from PHP superglobals.
<add> *
<add> * @return Cake\Network\Request
<add> */
<add> public static function createFromGlobals() {
<add> list($base, $webroot) = static::_base();
<add> $config = array(
<add> 'query' => $_GET,
<add> 'post' => $_POST,
<add> 'files' => $_FILES,
<add> 'cookies' => $_COOKIE,
<add> 'base' => $base,
<add> 'webroot' => $webroot,
<add> );
<add> $config['url'] = static::_url($config);
<add> return new static($config);
<add> }
<add>
<ide> /**
<ide> * Constructor
<ide> *
<del> * @param string $url Trimmed url string to use. Should not contain the application base path.
<del> * @param boolean $parseEnvironment Set to false to not auto parse the environment. ie. GET, POST and FILES.
<add> * @param array $config An array of request data to create a request with.
<ide> */
<del> public function __construct($url = null, $parseEnvironment = true) {
<del> $this->_base();
<del> if (empty($url)) {
<del> $url = $this->_url();
<del> }
<del> if ($url[0] == '/') {
<del> $url = substr($url, 1);
<del> }
<del> $this->url = $url;
<add> public function __construct($config = array()) {
<add> $config = (array)$config;
<add> $config += array(
<add> 'params' => $this->params,
<add> 'query' => array(),
<add> 'post' => array(),
<add> 'files' => array(),
<add> 'cookies' => array(),
<add> 'url' => '',
<add> 'base' => '',
<add> 'webroot' => '',
<add> );
<add> $this->_setConfig($config);
<add> }
<ide>
<del> if ($parseEnvironment) {
<del> $this->_processPost();
<del> $this->_processGet();
<del> $this->_processFiles();
<add>/**
<add> * Process the config/settings data into properties.
<add> *
<add> * @param array $config The config data to use.
<add> * @return void
<add> */
<add> protected function _setConfig($config) {
<add> if (!empty($config['url']) && $config['url'][0] == '/') {
<add> $config['url'] = substr($config['url'], 1);
<ide> }
<add>
<add> $this->url = $config['url'];
<add> $this->base = $config['base'];
<add> $this->cookies = $config['cookies'];
<ide> $this->here = $this->base . '/' . $this->url;
<add> $this->webroot = $config['webroot'];
<add>
<add> $config['post'] = $this->_processPost($config['post']);
<add> $this->data = $this->_processFiles($config['post'], $config['files']);
<add> $this->query = $this->_processGet($config['query']);
<add> $this->params = $config['params'];
<ide> }
<ide>
<ide> /**
<del> * process the post data and set what is there into the object.
<del> * processed data is available at `$this->data`
<del> *
<del> * Will merge POST vars prefixed with `data`, and ones without
<del> * into a single array. Variables prefixed with `data` will overwrite those without.
<add> * Sets the env('REQUEST_METHOD') based on the simulated _method HTTP override
<add> * value.
<ide> *
<del> * If you have mixed POST values be careful not to make any top level keys numeric
<del> * containing arrays. Hash::merge() is used to merge data, and it has possibly
<del> * unexpected behavior in this situation.
<del> *
<del> * @return void
<add> * @param array $data Array of post data.
<add> * @return array
<ide> */
<del> protected function _processPost() {
<del> if ($_POST) {
<del> $this->data = $_POST;
<del> } elseif ($this->is('put') || $this->is('delete')) {
<del> $this->data = $this->_readInput();
<add> protected function _processPost($data) {
<add> if ($this->is('put')) {
<add> $data = $this->_readInput();
<ide> if (env('CONTENT_TYPE') === 'application/x-www-form-urlencoded') {
<del> parse_str($this->data, $this->data);
<add> parse_str($data, $data);
<ide> }
<ide> }
<ide> if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
<del> $this->data['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
<add> $data['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
<ide> }
<del> if (isset($this->data['_method'])) {
<add> if (isset($data['_method'])) {
<ide> if (!empty($_SERVER)) {
<del> $_SERVER['REQUEST_METHOD'] = $this->data['_method'];
<add> $_SERVER['REQUEST_METHOD'] = $data['_method'];
<ide> } else {
<del> $_ENV['REQUEST_METHOD'] = $this->data['_method'];
<del> }
<del> unset($this->data['_method']);
<del> }
<del>
<del> if (isset($this->data['data'])) {
<del> $data = $this->data['data'];
<del> if (count($this->data) <= 1) {
<del> $this->data = $data;
<del> } else {
<del> unset($this->data['data']);
<del> $this->data = Hash::merge($this->data, $data);
<add> $_ENV['REQUEST_METHOD'] = $data['_method'];
<ide> }
<add> unset($data['_method']);
<ide> }
<add> return $data;
<ide> }
<ide>
<ide> /**
<ide> * Process the GET parameters and move things into the object.
<ide> *
<ide> * @return void
<ide> */
<del> protected function _processGet() {
<del> $query = $_GET;
<del>
<add> protected function _processGet($query) {
<ide> unset($query['/' . str_replace('.', '_', urldecode($this->url))]);
<ide> if (strpos($this->url, '?') !== false) {
<ide> list(, $querystr) = explode('?', $this->url);
<ide> parse_str($querystr, $queryArgs);
<ide> $query += $queryArgs;
<ide> }
<del> if (isset($this->params['url'])) {
<del> $query = array_merge($this->params['url'], $query);
<del> }
<del> $this->query = $query;
<add> return $query;
<ide> }
<ide>
<ide> /**
<ide> protected function _processGet() {
<ide> *
<ide> * @return string URI The CakePHP request path that is being accessed.
<ide> */
<del> protected function _url() {
<add> protected static function _url($config) {
<ide> if (!empty($_SERVER['PATH_INFO'])) {
<ide> return $_SERVER['PATH_INFO'];
<ide> } elseif (isset($_SERVER['REQUEST_URI'])) {
<ide> protected function _url() {
<ide> $uri = $var[0];
<ide> }
<ide>
<del> $base = $this->base;
<add> $base = $config['base'];
<ide>
<ide> if (strlen($base) > 0 && strpos($uri, $base) === 0) {
<ide> $uri = substr($uri, strlen($base));
<ide> protected function _url() {
<ide> /**
<ide> * Returns a base URL and sets the proper webroot
<ide> *
<del> * @return string Base URL
<add> * @return array Base URL, webroot dir ending in /
<ide> */
<del> protected function _base() {
<add> protected static function _base() {
<ide> $dir = $webroot = null;
<ide> $config = Configure::read('App');
<ide> extract($config);
<ide> protected function _base() {
<ide> $base = $this->base;
<ide> }
<ide> if ($base !== false) {
<del> $this->webroot = $base . '/';
<del> return $this->base = $base;
<add> return array($base, $base . '/');
<ide> }
<ide>
<ide> if (!$baseUrl) {
<ide> protected function _base() {
<ide> if ($base === DS || $base === '.') {
<ide> $base = '';
<ide> }
<del>
<del> $this->webroot = $base . '/';
<del> return $this->base = $base;
<add> return array($base, $base . '/');
<ide> }
<ide>
<ide> $file = '/' . basename($baseUrl);
<ide> protected function _base() {
<ide> if ($base === DS || $base === '.') {
<ide> $base = '';
<ide> }
<del> $this->webroot = $base . '/';
<add> $webrootDir = $base . '/';
<ide>
<ide> $docRoot = env('DOCUMENT_ROOT');
<ide> $docRootContainsWebroot = strpos($docRoot, $dir . '/' . $webroot);
<ide>
<ide> if (!empty($base) || !$docRootContainsWebroot) {
<del> if (strpos($this->webroot, '/' . $dir . '/') === false) {
<del> $this->webroot .= $dir . '/';
<add> if (strpos($webrootDir, '/' . $dir . '/') === false) {
<add> $webrootDir .= $dir . '/';
<ide> }
<del> if (strpos($this->webroot, '/' . $webroot . '/') === false) {
<del> $this->webroot .= $webroot . '/';
<add> if (strpos($webrootDir, '/' . $webroot . '/') === false) {
<add> $webrootDir .= $webroot . '/';
<ide> }
<ide> }
<del> return $this->base = $base . $file;
<add> return array($base . $file, $webrootDir);
<ide> }
<ide>
<ide> /**
<del> * Process $_FILES and move things into the object.
<add> * Process uploaded files and move things onto the post data.
<ide> *
<del> * @return void
<add> * @param array $data Post data to merge files onto.
<add> * @param array $files Uploaded files to merge in.
<add> * @return array merged post + file data.
<ide> */
<del> protected function _processFiles() {
<del> if (isset($_FILES) && is_array($_FILES)) {
<del> foreach ($_FILES as $name => $data) {
<del> if ($name != 'data') {
<del> $this->params['form'][$name] = $data;
<del> }
<del> }
<del> }
<del>
<del> if (isset($_FILES['data'])) {
<del> foreach ($_FILES['data'] as $key => $data) {
<del> $this->_processFileData('', $data, $key);
<add> protected function _processFiles($post, $files) {
<add> if (isset($files) && is_array($files)) {
<add> foreach ($files as $key => $data) {
<add> $this->_processFileData($post, '', $data, $key);
<ide> }
<ide> }
<add> return $post;
<ide> }
<ide>
<ide> /**
<ide> protected function _processFiles() {
<ide> * @param string $path The dot separated path to insert $data into.
<ide> * @param array $data The data to traverse/insert.
<ide> * @param string $field The terminal field name, which is the top level key in $_FILES.
<add> * @param array $post The post data having files inserted into
<ide> * @return void
<ide> */
<del> protected function _processFileData($path, $data, $field) {
<add> protected function _processFileData(&$post, $path, $data, $field) {
<ide> foreach ($data as $key => $fields) {
<ide> $newPath = $key;
<ide> if (!empty($path)) {
<ide> $newPath = $path . '.' . $key;
<ide> }
<ide> if (is_array($fields)) {
<del> $this->_processFileData($newPath, $fields, $field);
<add> $this->_processFileData($post, $newPath, $fields, $field);
<ide> } else {
<ide> $newPath .= '.' . $field;
<del> $this->data = Set::insert($this->data, $newPath, $fields);
<add> $post = Hash::insert($post, $newPath, $fields);
<ide> }
<ide> }
<ide> }
<ide><path>lib/Cake/Test/TestCase/Network/RequestTest.php
<ide> class RequestTest extends TestCase {
<ide> */
<ide> public function setUp() {
<ide> parent::setUp();
<del> $this->_app = Configure::read('App');
<ide> $this->_case = null;
<ide> if (isset($_GET['case'])) {
<ide> $this->_case = $_GET['case'];
<ide> public function tearDown() {
<ide> if (!empty($this->_case)) {
<ide> $_GET['case'] = $this->_case;
<ide> }
<del> Configure::write('App', $this->_app);
<ide> }
<ide>
<ide> /**
<ide> public function testNoAutoParseConstruction() {
<ide> $_GET = array(
<ide> 'one' => 'param'
<ide> );
<del> $request = new Request(null, false);
<add> $request = new Request();
<ide> $this->assertFalse(isset($request->query['one']));
<ide> }
<ide>
<ide> public function testNoAutoParseConstruction() {
<ide> *
<ide> * @return void
<ide> */
<del> public function testConstructionGetParsing() {
<del> $_GET = array(
<del> 'one' => 'param',
<del> 'two' => 'banana'
<del> );
<del> $request = new Request('some/path');
<del> $this->assertEquals($request->query, $_GET);
<del>
<del> $_GET = array(
<del> 'one' => 'param',
<del> 'two' => 'banana',
<add> public function testConstructionQueryData() {
<add> $data = array(
<add> 'query' => array(
<add> 'one' => 'param',
<add> 'two' => 'banana'
<add> ),
<add> 'url' => 'some/path'
<ide> );
<del> $request = new Request('some/path');
<del> $this->assertEquals($request->query, $_GET);
<add> $request = new Request($data);
<add> $this->assertEquals($request->query, $data['query']);
<ide> $this->assertEquals('some/path', $request->url);
<ide> }
<ide>
<ide> public function testConstructionGetParsing() {
<ide> */
<ide> public function testQueryStringParsingFromInputUrl() {
<ide> $_GET = array();
<del> $request = new Request('some/path?one=something&two=else');
<add> $request = new Request(array('url' => 'some/path?one=something&two=else'));
<ide> $expected = array('one' => 'something', 'two' => 'else');
<ide> $this->assertEquals($expected, $request->query);
<ide> $this->assertEquals('some/path?one=something&two=else', $request->url);
<ide> public function testQueryStringParsingFromInputUrl() {
<ide> */
<ide> public function testQueryStringAndNamedParams() {
<ide> $_SERVER['REQUEST_URI'] = '/tasks/index/page:1?ts=123456';
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide> $this->assertEquals('tasks/index/page:1', $request->url);
<ide>
<ide> $_SERVER['REQUEST_URI'] = '/tasks/index/page:1/?ts=123456';
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide> $this->assertEquals('tasks/index/page:1/', $request->url);
<ide> }
<ide>
<ide> public function testQueryStringAndNamedParams() {
<ide> * @return void
<ide> */
<ide> public function testAddParams() {
<del> $request = new Request('some/path');
<add> $request = new Request();
<ide> $request->params = array('controller' => 'posts', 'action' => 'view');
<ide> $result = $request->addParams(array('plugin' => null, 'action' => 'index'));
<ide>
<ide> public function testAddParams() {
<ide> * @return void
<ide> */
<ide> public function testAddPaths() {
<del> $request = new Request('some/path');
<add> $request = new Request();
<ide> $request->webroot = '/some/path/going/here/';
<ide> $result = $request->addPaths(array(
<ide> 'random' => '/something', 'webroot' => '/', 'here' => '/', 'base' => '/base_dir'
<ide> public function testAddPaths() {
<ide> * @return void
<ide> */
<ide> public function testPostParsing() {
<del> $_POST = array('data' => array(
<add> $post = array(
<ide> 'Article' => array('title')
<del> ));
<del> $request = new Request('some/path');
<del> $this->assertEquals($_POST['data'], $request->data);
<add> );
<add> $request = new Request(compact('post'));
<add> $this->assertEquals($post, $request->data);
<ide>
<del> $_POST = array('one' => 1, 'two' => 'three');
<del> $request = new Request('some/path');
<del> $this->assertEquals($_POST, $request->data);
<add> $post = array('one' => 1, 'two' => 'three');
<add> $request = new Request(compact('post'));
<add> $this->assertEquals($post, $request->data);
<ide>
<del> $_POST = array(
<del> 'data' => array(
<del> 'Article' => array('title' => 'Testing'),
<del> ),
<del> 'action' => 'update'
<del> );
<del> $request = new Request('some/path');
<del> $expected = array(
<add> $post = array(
<ide> 'Article' => array('title' => 'Testing'),
<ide> 'action' => 'update'
<ide> );
<del> $this->assertEquals($expected, $request->data);
<del>
<del> $_POST = array('data' => array(
<del> 'Article' => array('title'),
<del> 'Tag' => array('Tag' => array(1, 2))
<del> ));
<del> $request = new Request('some/path');
<del> $this->assertEquals($_POST['data'], $request->data);
<del>
<del> $_POST = array('data' => array(
<del> 'Article' => array('title' => 'some title'),
<del> 'Tag' => array('Tag' => array(1, 2))
<del> ));
<del> $request = new Request('some/path');
<del> $this->assertEquals($_POST['data'], $request->data);
<del>
<del> $_POST = array(
<del> 'a' => array(1, 2),
<del> 'b' => array(1, 2)
<del> );
<del> $request = new Request('some/path');
<del> $this->assertEquals($_POST, $request->data);
<add> $request = new Request(compact('post'));
<add> $this->assertEquals($post, $request->data);
<ide> }
<ide>
<ide> /**
<ide> public function testPutParsing() {
<ide> * @return void
<ide> */
<ide> public function testFilesParsing() {
<del> $_FILES = array(
<del> 'data' => array(
<del> 'name' => array(
<del> 'File' => array(
<del> array('data' => 'cake_sqlserver_patch.patch'),
<del> array('data' => 'controller.diff'),
<del> array('data' => ''),
<del> array('data' => ''),
<del> ),
<del> 'Post' => array('attachment' => 'jquery-1.2.1.js'),
<del> ),
<del> 'type' => array(
<del> 'File' => array(
<del> array('data' => ''),
<del> array('data' => ''),
<add> $files = array(
<add> 'name' => array(
<add> 'File' => array(
<add> array('data' => 'cake_sqlserver_patch.patch'),
<add> array('data' => 'controller.diff'),
<ide> array('data' => ''),
<ide> array('data' => ''),
<ide> ),
<del> 'Post' => array('attachment' => 'application/x-javascript'),
<add> 'Post' => array('attachment' => 'jquery-1.2.1.js'),
<ide> ),
<del> 'tmp_name' => array(
<del> 'File' => array(
<del> array('data' => '/private/var/tmp/phpy05Ywj'),
<del> array('data' => '/private/var/tmp/php7MBztY'),
<del> array('data' => ''),
<del> array('data' => ''),
<del> ),
<del> 'Post' => array('attachment' => '/private/var/tmp/phpEwlrIo'),
<add> 'type' => array(
<add> 'File' => array(
<add> array('data' => ''),
<add> array('data' => ''),
<add> array('data' => ''),
<add> array('data' => ''),
<ide> ),
<del> 'error' => array(
<del> 'File' => array(
<del> array('data' => 0),
<del> array('data' => 0),
<del> array('data' => 4),
<del> array('data' => 4)
<del> ),
<del> 'Post' => array('attachment' => 0)
<add> 'Post' => array('attachment' => 'application/x-javascript'),
<add> ),
<add> 'tmp_name' => array(
<add> 'File' => array(
<add> array('data' => '/private/var/tmp/phpy05Ywj'),
<add> array('data' => '/private/var/tmp/php7MBztY'),
<add> array('data' => ''),
<add> array('data' => ''),
<ide> ),
<del> 'size' => array(
<del> 'File' => array(
<del> array('data' => 6271),
<del> array('data' => 350),
<del> array('data' => 0),
<del> array('data' => 0),
<del> ),
<del> 'Post' => array('attachment' => 80469)
<add> 'Post' => array('attachment' => '/private/var/tmp/phpEwlrIo'),
<add> ),
<add> 'error' => array(
<add> 'File' => array(
<add> array('data' => 0),
<add> array('data' => 0),
<add> array('data' => 4),
<add> array('data' => 4)
<ide> ),
<del> )
<add> 'Post' => array('attachment' => 0)
<add> ),
<add> 'size' => array(
<add> 'File' => array(
<add> array('data' => 6271),
<add> array('data' => 350),
<add> array('data' => 0),
<add> array('data' => 0),
<add> ),
<add> 'Post' => array('attachment' => 80469)
<add> ),
<ide> );
<ide>
<del> $request = new Request('some/path');
<add> $request = new Request(compact('files'));
<ide> $expected = array(
<ide> 'File' => array(
<ide> array(
<ide> public function testFilesParsing() {
<ide> );
<ide> $this->assertEquals($expected, $request->data);
<ide>
<del> $_FILES = array(
<del> 'data' => array(
<del> 'name' => array(
<del> 'Document' => array(
<del> 1 => array(
<del> 'birth_cert' => 'born on.txt',
<del> 'passport' => 'passport.txt',
<del> 'drivers_license' => 'ugly pic.jpg'
<del> ),
<del> 2 => array(
<del> 'birth_cert' => 'aunt betty.txt',
<del> 'passport' => 'betty-passport.txt',
<del> 'drivers_license' => 'betty-photo.jpg'
<del> ),
<add> $files = array(
<add> 'name' => array(
<add> 'Document' => array(
<add> 1 => array(
<add> 'birth_cert' => 'born on.txt',
<add> 'passport' => 'passport.txt',
<add> 'drivers_license' => 'ugly pic.jpg'
<add> ),
<add> 2 => array(
<add> 'birth_cert' => 'aunt betty.txt',
<add> 'passport' => 'betty-passport.txt',
<add> 'drivers_license' => 'betty-photo.jpg'
<ide> ),
<ide> ),
<del> 'type' => array(
<del> 'Document' => array(
<del> 1 => array(
<del> 'birth_cert' => 'application/octet-stream',
<del> 'passport' => 'application/octet-stream',
<del> 'drivers_license' => 'application/octet-stream',
<del> ),
<del> 2 => array(
<del> 'birth_cert' => 'application/octet-stream',
<del> 'passport' => 'application/octet-stream',
<del> 'drivers_license' => 'application/octet-stream',
<del> )
<add> ),
<add> 'type' => array(
<add> 'Document' => array(
<add> 1 => array(
<add> 'birth_cert' => 'application/octet-stream',
<add> 'passport' => 'application/octet-stream',
<add> 'drivers_license' => 'application/octet-stream',
<add> ),
<add> 2 => array(
<add> 'birth_cert' => 'application/octet-stream',
<add> 'passport' => 'application/octet-stream',
<add> 'drivers_license' => 'application/octet-stream',
<ide> )
<del> ),
<del> 'tmp_name' => array(
<del> 'Document' => array(
<del> 1 => array(
<del> 'birth_cert' => '/private/var/tmp/phpbsUWfH',
<del> 'passport' => '/private/var/tmp/php7f5zLt',
<del> 'drivers_license' => '/private/var/tmp/phpMXpZgT',
<del> ),
<del> 2 => array(
<del> 'birth_cert' => '/private/var/tmp/php5kHZt0',
<del> 'passport' => '/private/var/tmp/phpnYkOuM',
<del> 'drivers_license' => '/private/var/tmp/php9Rq0P3',
<del> )
<add> )
<add> ),
<add> 'tmp_name' => array(
<add> 'Document' => array(
<add> 1 => array(
<add> 'birth_cert' => '/private/var/tmp/phpbsUWfH',
<add> 'passport' => '/private/var/tmp/php7f5zLt',
<add> 'drivers_license' => '/private/var/tmp/phpMXpZgT',
<add> ),
<add> 2 => array(
<add> 'birth_cert' => '/private/var/tmp/php5kHZt0',
<add> 'passport' => '/private/var/tmp/phpnYkOuM',
<add> 'drivers_license' => '/private/var/tmp/php9Rq0P3',
<ide> )
<del> ),
<del> 'error' => array(
<del> 'Document' => array(
<del> 1 => array(
<del> 'birth_cert' => 0,
<del> 'passport' => 0,
<del> 'drivers_license' => 0,
<del> ),
<del> 2 => array(
<del> 'birth_cert' => 0,
<del> 'passport' => 0,
<del> 'drivers_license' => 0,
<del> )
<add> )
<add> ),
<add> 'error' => array(
<add> 'Document' => array(
<add> 1 => array(
<add> 'birth_cert' => 0,
<add> 'passport' => 0,
<add> 'drivers_license' => 0,
<add> ),
<add> 2 => array(
<add> 'birth_cert' => 0,
<add> 'passport' => 0,
<add> 'drivers_license' => 0,
<ide> )
<del> ),
<del> 'size' => array(
<del> 'Document' => array(
<del> 1 => array(
<del> 'birth_cert' => 123,
<del> 'passport' => 458,
<del> 'drivers_license' => 875,
<del> ),
<del> 2 => array(
<del> 'birth_cert' => 876,
<del> 'passport' => 976,
<del> 'drivers_license' => 9783,
<del> )
<add> )
<add> ),
<add> 'size' => array(
<add> 'Document' => array(
<add> 1 => array(
<add> 'birth_cert' => 123,
<add> 'passport' => 458,
<add> 'drivers_license' => 875,
<add> ),
<add> 2 => array(
<add> 'birth_cert' => 876,
<add> 'passport' => 976,
<add> 'drivers_license' => 9783,
<ide> )
<ide> )
<ide> )
<ide> );
<ide>
<del> $request = new Request('some/path');
<add> $request = new Request(compact('files'));
<ide> $expected = array(
<ide> 'Document' => array(
<ide> 1 => array(
<ide> public function testFilesParsing() {
<ide> );
<ide> $this->assertEquals($expected, $request->data);
<ide>
<del> $_FILES = array(
<del> 'data' => array(
<del> 'name' => array('birth_cert' => 'born on.txt'),
<del> 'type' => array('birth_cert' => 'application/octet-stream'),
<del> 'tmp_name' => array('birth_cert' => '/private/var/tmp/phpbsUWfH'),
<del> 'error' => array('birth_cert' => 0),
<del> 'size' => array('birth_cert' => 123)
<del> )
<add> $files = array(
<add> 'name' => array('birth_cert' => 'born on.txt'),
<add> 'type' => array('birth_cert' => 'application/octet-stream'),
<add> 'tmp_name' => array('birth_cert' => '/private/var/tmp/phpbsUWfH'),
<add> 'error' => array('birth_cert' => 0),
<add> 'size' => array('birth_cert' => 123)
<ide> );
<ide>
<del> $request = new Request('some/path');
<add> $request = new Request(compact('files'));
<ide> $expected = array(
<ide> 'birth_cert' => array(
<ide> 'name' => 'born on.txt',
<ide> public function testFilesParsing() {
<ide> )
<ide> );
<ide> $this->assertEquals($expected, $request->data);
<del>
<del> $_FILES = array(
<del> 'something' => array(
<del> 'name' => 'something.txt',
<del> 'type' => 'text/plain',
<del> 'tmp_name' => '/some/file',
<del> 'error' => 0,
<del> 'size' => 123
<del> )
<del> );
<del> $request = new Request('some/path');
<del> $this->assertEquals($request->params['form'], $_FILES);
<ide> }
<ide>
<ide> /**
<ide> public function testFilesParsing() {
<ide> * @return void
<ide> */
<ide> public function testMethodOverrides() {
<del> $_POST = array('_method' => 'POST');
<del> $request = new Request('some/path');
<add> $post = array('_method' => 'POST');
<add> $request = new Request(compact('post'));
<ide> $this->assertEquals(env('REQUEST_METHOD'), 'POST');
<ide>
<del> $_POST = array('_method' => 'DELETE');
<del> $request = new Request('some/path');
<add> $post = array('_method' => 'DELETE');
<add> $request = new Request(compact('post'));
<ide> $this->assertEquals(env('REQUEST_METHOD'), 'DELETE');
<ide>
<ide> $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'PUT';
<del> $request = new Request('some/path');
<add> $request = new Request();
<ide> $this->assertEquals(env('REQUEST_METHOD'), 'PUT');
<ide> }
<ide>
<ide> public function testMagicisset() {
<ide> * @return void
<ide> */
<ide> public function testArrayAccess() {
<del> $request = new Request('some/path');
<add> $request = new Request();
<ide> $request->params = array('controller' => 'posts', 'action' => 'view', 'plugin' => 'blogs');
<ide>
<ide> $this->assertEquals('posts', $request['controller']);
<ide> public function testArrayAccess() {
<ide> $this->assertNull($request['plugin']);
<ide> $this->assertNull($request->plugin);
<ide>
<del> $request = new Request('some/path?one=something&two=else');
<add> $request = new Request(array('url' => 'some/path?one=something&two=else'));
<ide> $this->assertTrue(isset($request['url']['one']));
<ide>
<ide> $request->data = array('Post' => array('title' => 'something'));
<ide> public function testBaseUrlAndWebrootWithModRewrite() {
<ide> $_SERVER['PHP_SELF'] = '/1.2.x.x/App/webroot/index.php';
<ide> $_SERVER['PATH_INFO'] = '/posts/view/1';
<ide>
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide> $this->assertEquals('/1.2.x.x', $request->base);
<ide> $this->assertEquals('/1.2.x.x/', $request->webroot);
<ide> $this->assertEquals('posts/view/1', $request->url);
<ide>
<ide> $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches/1.2.x.x/App/webroot';
<ide> $_SERVER['PHP_SELF'] = '/index.php';
<ide> $_SERVER['PATH_INFO'] = '/posts/add';
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide>
<ide> $this->assertEquals('', $request->base);
<ide> $this->assertEquals('/', $request->webroot);
<ide> $this->assertEquals('posts/add', $request->url);
<ide>
<ide> $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches/1.2.x.x/test/';
<ide> $_SERVER['PHP_SELF'] = '/webroot/index.php';
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide>
<ide> $this->assertEquals('', $request->base);
<ide> $this->assertEquals('/', $request->webroot);
<ide>
<ide> $_SERVER['DOCUMENT_ROOT'] = '/some/apps/where';
<ide> $_SERVER['PHP_SELF'] = '/App/webroot/index.php';
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide>
<ide> $this->assertEquals('', $request->base);
<ide> $this->assertEquals('/', $request->webroot);
<ide> public function testBaseUrlAndWebrootWithModRewrite() {
<ide> $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches';
<ide> $_SERVER['PHP_SELF'] = '/demos/auth/webroot/index.php';
<ide>
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide>
<ide> $this->assertEquals('/demos/auth', $request->base);
<ide> $this->assertEquals('/demos/auth/', $request->webroot);
<ide> public function testBaseUrlAndWebrootWithModRewrite() {
<ide>
<ide> $_SERVER['DOCUMENT_ROOT'] = '/Library/WebServer/Documents';
<ide> $_SERVER['PHP_SELF'] = '/clients/PewterReport/code/webroot/index.php';
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide>
<ide> $this->assertEquals('/clients/PewterReport/code', $request->base);
<ide> $this->assertEquals('/clients/PewterReport/code/', $request->webroot);
<ide> public function testBaseUrlwithModRewriteAlias() {
<ide>
<ide> Configure::write('App.base', '/control');
<ide>
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide>
<ide> $this->assertEquals('/control', $request->base);
<ide> $this->assertEquals('/control/', $request->webroot);
<ide> public function testBaseUrlwithModRewriteAlias() {
<ide>
<ide> $_SERVER['DOCUMENT_ROOT'] = '/var/www/abtravaff/html';
<ide> $_SERVER['PHP_SELF'] = '/newaffiliate/index.php';
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide>
<ide> $this->assertEquals('/newaffiliate', $request->base);
<ide> $this->assertEquals('/newaffiliate/', $request->webroot);
<ide> public function testBaseUrlWithNoModRewrite() {
<ide> 'baseUrl' => '/cake/index.php'
<ide> ));
<ide>
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide> $this->assertEquals('/cake/index.php', $request->base);
<ide> $this->assertEquals('/cake/App/webroot/', $request->webroot);
<ide> $this->assertEquals('posts/index', $request->url);
<ide> public function testBaseUrlAndWebrootWithBaseUrl() {
<ide> Configure::write('App.dir', 'App');
<ide> Configure::write('App.baseUrl', '/App/webroot/index.php');
<ide>
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide> $this->assertEquals('/App/webroot/index.php', $request->base);
<ide> $this->assertEquals('/App/webroot/', $request->webroot);
<ide>
<ide> Configure::write('App.baseUrl', '/App/webroot/test.php');
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide> $this->assertEquals('/App/webroot/test.php', $request->base);
<ide> $this->assertEquals('/App/webroot/', $request->webroot);
<ide>
<ide> Configure::write('App.baseUrl', '/App/index.php');
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide> $this->assertEquals('/App/index.php', $request->base);
<ide> $this->assertEquals('/App/webroot/', $request->webroot);
<ide>
<ide> Configure::write('App.baseUrl', '/CakeBB/App/webroot/index.php');
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide> $this->assertEquals('/CakeBB/App/webroot/index.php', $request->base);
<ide> $this->assertEquals('/CakeBB/App/webroot/', $request->webroot);
<ide>
<ide> Configure::write('App.baseUrl', '/CakeBB/App/index.php');
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide>
<ide> $this->assertEquals('/CakeBB/App/index.php', $request->base);
<ide> $this->assertEquals('/CakeBB/App/webroot/', $request->webroot);
<ide>
<ide> Configure::write('App.baseUrl', '/CakeBB/index.php');
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide>
<ide> $this->assertEquals('/CakeBB/index.php', $request->base);
<ide> $this->assertEquals('/CakeBB/App/webroot/', $request->webroot);
<ide>
<ide> Configure::write('App.baseUrl', '/dbhauser/index.php');
<ide> $_SERVER['DOCUMENT_ROOT'] = '/kunden/homepages/4/d181710652/htdocs/joomla';
<ide> $_SERVER['SCRIPT_FILENAME'] = '/kunden/homepages/4/d181710652/htdocs/joomla/dbhauser/index.php';
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide>
<ide> $this->assertEquals('/dbhauser/index.php', $request->base);
<ide> $this->assertEquals('/dbhauser/App/webroot/', $request->webroot);
<ide> public function testBaseUrlNoRewriteTopLevelIndex() {
<ide> $_SERVER['DOCUMENT_ROOT'] = '/Users/markstory/Sites/cake_dev';
<ide> $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/cake_dev/index.php';
<ide>
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide> $this->assertEquals('/index.php', $request->base);
<ide> $this->assertEquals('/App/webroot/', $request->webroot);
<ide> }
<ide> public function testBaseUrlWithAppAndWebrootInDirname() {
<ide> $_SERVER['DOCUMENT_ROOT'] = '/Users/markstory/Sites/';
<ide> $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/approval/index.php';
<ide>
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide> $this->assertEquals('/approval/index.php', $request->base);
<ide> $this->assertEquals('/approval/App/webroot/', $request->webroot);
<ide>
<ide> Configure::write('App.baseUrl', '/webrootable/index.php');
<ide> $_SERVER['DOCUMENT_ROOT'] = '/Users/markstory/Sites/';
<ide> $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/webrootable/index.php';
<ide>
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide> $this->assertEquals('/webrootable/index.php', $request->base);
<ide> $this->assertEquals('/webrootable/App/webroot/', $request->webroot);
<ide> }
<ide> public function testBaseUrlNoRewriteWebrootIndex() {
<ide> $_SERVER['DOCUMENT_ROOT'] = '/Users/markstory/Sites/cake_dev/App/webroot';
<ide> $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/cake_dev/App/webroot/index.php';
<ide>
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide> $this->assertEquals('/index.php', $request->base);
<ide> $this->assertEquals('/', $request->webroot);
<ide> }
<ide> public function testGetParamsWithDot() {
<ide> $_SERVER['PHP_SELF'] = '/cake_dev/App/webroot/index.php';
<ide> $_SERVER['REQUEST_URI'] = '/cake_dev/posts/index/add.add';
<ide>
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide> $this->assertEquals(array(), $request->query);
<ide> }
<ide>
<ide> public function testEnvironmentDetection($name, $env, $expected) {
<ide> $_GET = array();
<ide> $this->__loadEnvironment($env);
<ide>
<del> $request = new Request();
<add> $request = Request::createFromGlobals();
<ide> $this->assertEquals($expected['url'], $request->url, "url error");
<ide> $this->assertEquals($expected['base'], $request->base, "base error");
<ide> $this->assertEquals($expected['webroot'], $request->webroot, "webroot error");
<ide> public function testEnvironmentDetection($name, $env, $expected) {
<ide> * @return void
<ide> */
<ide> public function testDataReading() {
<del> $_POST['data'] = array(
<add> $post = array(
<ide> 'Model' => array(
<ide> 'field' => 'value'
<ide> )
<ide> );
<del> $request = new Request('posts/index');
<add> $request = new Request(compact('post'));
<ide> $result = $request->data('Model');
<del> $this->assertEquals($_POST['data']['Model'], $result);
<add> $this->assertEquals($post['Model'], $result);
<ide>
<ide> $result = $request->data('Model.imaginary');
<ide> $this->assertNull($result);
<ide> public function testAcceptLanguage() {
<ide> */
<ide> public function testHere() {
<ide> Configure::write('App.base', '/base_path');
<del> $_GET = array('test' => 'value');
<del> $request = new Request('/posts/add/1/name:value');
<add> $q = array('test' => 'value');
<add> $request = new Request(array(
<add> 'query' => $q,
<add> 'url' => '/posts/add/1/value',
<add> 'base' => '/base_path'
<add> ));
<ide>
<ide> $result = $request->here();
<del> $this->assertEquals('/base_path/posts/add/1/name:value?test=value', $result);
<add> $this->assertEquals('/base_path/posts/add/1/value?test=value', $result);
<ide>
<ide> $result = $request->here(false);
<del> $this->assertEquals('/posts/add/1/name:value?test=value', $result);
<add> $this->assertEquals('/posts/add/1/value?test=value', $result);
<ide>
<del> $request = new Request('/posts/base_path/1/name:value');
<add> $request = new Request(array(
<add> 'url' => '/posts/base_path/1/value',
<add> 'query' => array('test' => 'value'),
<add> 'base' => '/base_path'
<add> ));
<ide> $result = $request->here();
<del> $this->assertEquals('/base_path/posts/base_path/1/name:value?test=value', $result);
<add> $this->assertEquals('/base_path/posts/base_path/1/value?test=value', $result);
<ide>
<ide> $result = $request->here(false);
<del> $this->assertEquals('/posts/base_path/1/name:value?test=value', $result);
<add> $this->assertEquals('/posts/base_path/1/value?test=value', $result);
<ide> }
<ide>
<ide> /**
| 2
|
PHP
|
PHP
|
move test classes to their own files
|
5df3cff39a6a3c1515f78ee6d8bb10f0368a3c1a
|
<ide><path>tests/Database/DatabaseEloquentIntegrationTest.php
<ide> use Illuminate\Database\Eloquent\SoftDeletes;
<ide> use Illuminate\Database\Capsule\Manager as DB;
<ide> use Illuminate\Pagination\LengthAwarePaginator;
<del>use Illuminate\Tests\Integration\Database\Post;
<del>use Illuminate\Tests\Integration\Database\User;
<ide> use Illuminate\Database\Eloquent\Relations\Pivot;
<ide> use Illuminate\Database\Eloquent\Model as Eloquent;
<ide> use Illuminate\Database\Eloquent\SoftDeletingScope;
<ide> use Illuminate\Database\Eloquent\Relations\Relation;
<ide> use Illuminate\Database\Eloquent\ModelNotFoundException;
<add>use Illuminate\Tests\Integration\Database\Fixtures\Post;
<add>use Illuminate\Tests\Integration\Database\Fixtures\User;
<ide> use Illuminate\Pagination\AbstractPaginator as Paginator;
<ide>
<ide> class DatabaseEloquentIntegrationTest extends TestCase
<ide><path>tests/Integration/Database/EloquentCollectionFreshTest.php
<ide> namespace Illuminate\Tests\Integration\Database;
<ide>
<ide> use Illuminate\Support\Facades\Schema;
<del>use Illuminate\Database\Eloquent\Model;
<ide> use Illuminate\Database\Schema\Blueprint;
<add>use Illuminate\Tests\Integration\Database\Fixtures\User;
<ide>
<ide> /**
<ide> * @group integration
<ide> public function test_eloquent_collection_fresh()
<ide> $this->assertEmpty($collection->fresh()->filter());
<ide> }
<ide> }
<del>
<del>class User extends Model
<del>{
<del> protected $guarded = [];
<del>}
<ide><path>tests/Integration/Database/EloquentDeleteTest.php
<ide> use Illuminate\Database\Eloquent\Model;
<ide> use Illuminate\Database\Schema\Blueprint;
<ide> use Illuminate\Database\Eloquent\SoftDeletes;
<add>use Illuminate\Tests\Integration\Database\Fixtures\Post;
<ide>
<ide> /**
<ide> * @group integration
<ide> public function testForceDeletedEventIsFired()
<ide> }
<ide> }
<ide>
<del>class Post extends Model
<del>{
<del> public $table = 'posts';
<del>}
<del>
<ide> class Comment extends Model
<ide> {
<ide> public $table = 'comments';
<ide><path>tests/Integration/Database/Fixtures/Post.php
<add><?php
<add>
<add>namespace Illuminate\Tests\Integration\Database\Fixtures;
<add>
<add>use Illuminate\Database\Eloquent\Model;
<add>
<add>class Post extends Model
<add>{
<add> public $table = 'posts';
<add>}
<ide><path>tests/Integration/Database/Fixtures/User.php
<add><?php
<add>
<add>namespace Illuminate\Tests\Integration\Database\Fixtures;
<add>
<add>use Illuminate\Database\Eloquent\Model;
<add>
<add>class User extends Model
<add>{
<add> protected $guarded = [];
<add>}
| 5
|
Java
|
Java
|
improve handling of send failures
|
b2f31a3c741ddfaad94ffe5da7de762f8e3cc6cb
|
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java
<ide>
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.MessageChannel;
<add>import org.springframework.messaging.MessageDeliveryException;
<ide> import org.springframework.messaging.MessageHandler;
<ide> import org.springframework.messaging.simp.SimpMessageType;
<ide> import org.springframework.messaging.simp.handler.AbstractBrokerMessageHandler;
<ide> protected void handleMessageInternal(Message<?> message) {
<ide> return;
<ide> }
<ide>
<del> try {
<del> if (SimpMessageType.CONNECT.equals(messageType)) {
<del> message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build();
<del> StompRelaySession session = new StompRelaySession(sessionId);
<del> this.relaySessions.put(sessionId, session);
<del> session.connect(message);
<del> }
<del> else if (SimpMessageType.DISCONNECT.equals(messageType)) {
<del> StompRelaySession session = this.relaySessions.remove(sessionId);
<del> if (session == null) {
<del> if (logger.isTraceEnabled()) {
<del> logger.trace("Session already removed, sessionId=" + sessionId);
<del> }
<del> return;
<del> }
<del> session.forward(message);
<del> }
<del> else {
<del> StompRelaySession session = this.relaySessions.get(sessionId);
<del> if (session == null) {
<del> logger.warn("Session id=" + sessionId + " not found. Ignoring message: " + message);
<del> return;
<add> if (SimpMessageType.CONNECT.equals(messageType)) {
<add> message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build();
<add> StompRelaySession session = new StompRelaySession(sessionId);
<add> this.relaySessions.put(sessionId, session);
<add> session.connect(message);
<add> }
<add> else if (SimpMessageType.DISCONNECT.equals(messageType)) {
<add> StompRelaySession session = this.relaySessions.remove(sessionId);
<add> if (session == null) {
<add> if (logger.isTraceEnabled()) {
<add> logger.trace("Session already removed, sessionId=" + sessionId);
<ide> }
<del> session.forward(message);
<add> return;
<ide> }
<add> session.forward(message);
<ide> }
<del> catch (Throwable t) {
<del> logger.error("Failed to handle message " + message, t);
<add> else {
<add> StompRelaySession session = this.relaySessions.get(sessionId);
<add> if (session == null) {
<add> logger.warn("Session id=" + sessionId + " not found. Ignoring message: " + message);
<add> return;
<add> }
<add> session.forward(message);
<ide> }
<ide> }
<ide>
<ide> protected void connected(StompHeaderAccessor headers, StompConnection stompConne
<ide> publishBrokerAvailableEvent();
<ide> }
<ide>
<del> private void handleTcpClientFailure(String message, Throwable ex) {
<add> protected void handleTcpClientFailure(String message, Throwable ex) {
<ide> if (logger.isErrorEnabled()) {
<ide> logger.error(message + ", sessionId=" + this.sessionId, ex);
<ide> }
<ide> protected void sendMessageToClient(Message<?> message) {
<ide> messageChannel.send(message);
<ide> }
<ide>
<del> public void forward(Message<?> message) {
<add> private void forward(Message<?> message) {
<ide> TcpConnection<Message<byte[]>, Message<byte[]>> tcpConnection = this.stompConnection.getReadyConnection();
<ide> if (tcpConnection == null) {
<del> logger.warn("Connection to STOMP broker is not active, discarding message: " + message);
<del> return;
<add> logger.warn("Connection to STOMP broker is not active");
<add> handleForwardFailure(message);
<add> }
<add> else if (!forwardInternal(tcpConnection, message)) {
<add> handleForwardFailure(message);
<add> }
<add> }
<add>
<add> protected void handleForwardFailure(Message<?> message) {
<add> if (logger.isWarnEnabled()) {
<add> logger.warn("Failed to forward message to the broker. message=" + message);
<ide> }
<del> forwardInternal(tcpConnection, message);
<ide> }
<ide>
<ide> private boolean forwardInternal(
<ide> protected void connectionClosed() {
<ide>
<ide> @Override
<ide> protected void connected(StompHeaderAccessor headers, final StompConnection stompConnection) {
<del> long brokerReceiveInterval = headers.getHeartbeat()[1];
<ide>
<del> if (HEARTBEAT_SEND_INTERVAL > 0 && brokerReceiveInterval > 0) {
<add> long brokerReceiveInterval = headers.getHeartbeat()[1];
<add> if ((HEARTBEAT_SEND_INTERVAL > 0) && (brokerReceiveInterval > 0)) {
<ide> long interval = Math.max(HEARTBEAT_SEND_INTERVAL, brokerReceiveInterval);
<ide> stompConnection.connection.on().writeIdle(interval, new Runnable() {
<ide>
<ide> @Override
<ide> public void run() {
<del> TcpConnection<Message<byte[]>, Message<byte[]>> connection = stompConnection.connection;
<del> if (connection != null) {
<del> connection.send(MessageBuilder.withPayload(heartbeatPayload).build());
<add> TcpConnection<Message<byte[]>, Message<byte[]>> tcpConn = stompConnection.connection;
<add> if (tcpConn != null) {
<add> tcpConn.send(MessageBuilder.withPayload(heartbeatPayload).build(),
<add> new Consumer<Boolean>() {
<add> @Override
<add> public void accept(Boolean t) {
<add> handleTcpClientFailure("Failed to send heartbeat to the broker", null);
<add> }
<add> });
<ide> }
<ide> }
<del>
<ide> });
<ide> }
<ide>
<ide> long brokerSendInterval = headers.getHeartbeat()[0];
<ide> if (HEARTBEAT_RECEIVE_INTERVAL > 0 && brokerSendInterval > 0) {
<del> final long interval =
<del> Math.max(HEARTBEAT_RECEIVE_INTERVAL, brokerSendInterval) * HEARTBEAT_RECEIVE_MULTIPLIER;
<add> final long interval = Math.max(HEARTBEAT_RECEIVE_INTERVAL, brokerSendInterval)
<add> * HEARTBEAT_RECEIVE_MULTIPLIER;
<ide> stompConnection.connection.on().readIdle(interval, new Runnable() {
<add>
<ide> @Override
<ide> public void run() {
<ide> String message = "Broker hearbeat missed: connection idle for more than " + interval + "ms";
<del> logger.warn(message);
<add> if (logger.isWarnEnabled()) {
<add> logger.warn(message);
<add> }
<ide> disconnected(message);
<ide> }
<ide> });
<ide> protected void sendMessageToClient(Message<?> message) {
<ide> // Ignore
<ide> }
<ide> }
<add>
<add> @Override
<add> protected void handleForwardFailure(Message<?> message) {
<add> super.handleForwardFailure(message);
<add> throw new MessageDeliveryException(message);
<add> }
<ide> }
<ide>
<ide> }
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java
<ide> import org.springframework.context.ApplicationEvent;
<ide> import org.springframework.context.ApplicationEventPublisher;
<ide> import org.springframework.messaging.Message;
<add>import org.springframework.messaging.MessageDeliveryException;
<ide> import org.springframework.messaging.MessageHandler;
<ide> import org.springframework.messaging.MessagingException;
<ide> import org.springframework.messaging.simp.BrokerAvailabilityEvent;
<ide> public void brokerUnvailableErrorFrameOnConnect() throws Exception {
<ide> this.responseHandler.awaitAndAssert();
<ide> }
<ide>
<add> @Test(expected=MessageDeliveryException.class)
<add> public void messageDeliverExceptionIfSystemSessionForwardFails() throws Exception {
<add> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE);
<add> this.relay.handleMessage(MessageBuilder.withPayloadAndHeaders("test", headers).build());
<add> }
<add>
<ide> @Test
<ide> public void brokerBecomingUnvailableTriggersErrorFrame() throws Exception {
<ide>
| 2
|
Ruby
|
Ruby
|
use consistent explicit module inclusion
|
08c4d8eac302b8f9a6375b937586b79d208e756d
|
<ide><path>actionpack/test/abstract/abstract_controller_test.rb
<ide> class TestBasic < ActiveSupport::TestCase
<ide> # Test Render mixin
<ide> # ====
<ide> class RenderingController < AbstractController::Base
<del> include ::AbstractController::Rendering
<add> include AbstractController::Rendering
<ide>
<ide> def _prefixes
<ide> []
<ide> def setup
<ide> # ====
<ide> # self._layout is used when defined
<ide> class WithLayouts < PrefixedViews
<del> include Layouts
<add> include AbstractController::Layouts
<ide>
<ide> private
<ide> def self.layout(formats)
<ide><path>actionpack/test/abstract/collector_test.rb
<ide> module AbstractController
<ide> module Testing
<ide> class MyCollector
<del> include Collector
<add> include AbstractController::Collector
<ide> attr_accessor :responses
<ide>
<ide> def initialize
<ide> class TestCollector < ActiveSupport::TestCase
<ide> end
<ide> end
<ide> end
<del>end
<ide>\ No newline at end of file
<add>end
<ide><path>actionpack/test/abstract/helper_test.rb
<ide> module Testing
<ide>
<ide> class ControllerWithHelpers < AbstractController::Base
<ide> include AbstractController::Rendering
<del> include Helpers
<add> include AbstractController::Helpers
<ide>
<ide> def with_module
<ide> render :inline => "Module <%= included_method %>"
<ide> class ::HelperyTestController < AbstractHelpers
<ide>
<ide> class AbstractHelpersBlock < ControllerWithHelpers
<ide> helper do
<del> include ::AbstractController::Testing::HelperyTest
<add> include AbstractController::Testing::HelperyTest
<ide> end
<ide> end
<ide>
| 3
|
Text
|
Text
|
remove versions template
|
e514de3eb2bb961822a397e89284fb1c183f2b6c
|
<ide><path>ISSUE_TEMPLATE.md
<ide>
<ide> ### Versions
<ide>
<del>You can get this information from executing `atom --version` and `apm --version` at the command line:
<del>
<del>* **Atom:** x.y.z
<del>* **Electron:** x.y.z
<del>* **OS:** OS x.y.z
<del>* **APM**
<del> * apm x.y.z
<del> * npm x.y.z
<del> * python x.y.z
<del> * git x.y.z
<add>You can get this information from executing `atom --version` and `apm --version` at the command line.
| 1
|
Text
|
Text
|
add doc for system events and events[fix ]
|
ea820cae7b70322349fcc96315fda50deec5e0d1
|
<ide><path>docs/reference/commandline/events.md
<ide> keywords: "events, container, report"
<ide> ---
<ide>
<ide> <!-- This file is maintained within the docker/docker Github
<del> repository at https://github.com/docker/docker/. Make all
<add> repository at https://github.com/moby/moby/. Make all
<ide> pull requests against that repo. If you see this file in
<ide> another repository, consider it read-only there, as it will
<ide> periodically be overwritten by the definitive file. Pull
<ide> The currently supported filters are:
<ide> * label (`label=<key>` or `label=<key>=<value>`)
<ide> * network (`network=<name or id>`)
<ide> * plugin (`plugin=<name or id>`)
<del>* type (`type=<container or image or volume or network or daemon>`)
<add>* type (`type=<container or image or volume or network or daemon or plugin>`)
<ide> * volume (`volume=<name or id>`)
<ide>
<ide> #### Format
<ide> $ docker events --filter 'type=network'
<ide>
<ide> 2015-12-23T21:38:24.705709133Z network create 8b111217944ba0ba844a65b13efcd57dc494932ee2527577758f939315ba2c5b (name=test-event-network-local, type=bridge)
<ide> 2015-12-23T21:38:25.119625123Z network connect 8b111217944ba0ba844a65b13efcd57dc494932ee2527577758f939315ba2c5b (name=test-event-network-local, container=b4be644031a3d90b400f88ab3d4bdf4dc23adb250e696b6328b85441abe2c54e, type=bridge)
<del>```
<del>
<del>The `type=plugin` filter is experimental.
<ide>
<del>```bash
<ide> $ docker events --filter 'type=plugin'
<ide>
<ide> 2016-07-25T17:30:14.825557616Z plugin pull ec7b87f2ce84330fe076e666f17dfc049d2d7ae0b8190763de94e1f2d105993f (name=tiborvass/sample-volume-plugin:latest)
<ide><path>docs/reference/commandline/system_events.md
<add>---
<add>title: "system events"
<add>description: "The system events command description and usage"
<add>keywords: "system, events, container, report"
<add>---
<add>
<add><!-- This file is maintained within the moby/moby Github
<add> repository at https://github.com/moby/moby/. Make all
<add> pull requests against that repo. If you see this file in
<add> another repository, consider it read-only there, as it will
<add> periodically be overwritten by the definitive file. Pull
<add> requests which include edits to this file in other repositories
<add> will be rejected.
<add>-->
<add>
<add># system events
<add>
<add>```markdown
<add>Usage: docker system events [OPTIONS]
<add>
<add>Get real time events from the server
<add>
<add>Options:
<add> -f, --filter value Filter output based on conditions provided (default [])
<add> --format string Format the output using the given Go template
<add> --help Print usage
<add> --since string Show all events created since timestamp
<add> --until string Stream events until this timestamp
<add>```
<add>
<add>## Description
<add>
<add>Use `docker system events` to get real-time events from the server. These
<add>events differ per Docker object type.
<add>
<add>### Object types
<add>
<add>#### Containers
<add>
<add>Docker containers report the following events:
<add>
<add>- `attach`
<add>- `commit`
<add>- `copy`
<add>- `create`
<add>- `destroy`
<add>- `detach`
<add>- `die`
<add>- `exec_create`
<add>- `exec_detach`
<add>- `exec_start`
<add>- `export`
<add>- `health_status`
<add>- `kill`
<add>- `oom`
<add>- `pause`
<add>- `rename`
<add>- `resize`
<add>- `restart`
<add>- `start`
<add>- `stop`
<add>- `top`
<add>- `unpause`
<add>- `update`
<add>
<add>#### Images
<add>
<add>Docker images report the following events:
<add>
<add>- `delete`
<add>- `import`
<add>- `load`
<add>- `pull`
<add>- `push`
<add>- `save`
<add>- `tag`
<add>- `untag`
<add>
<add>#### Plugins
<add>
<add>Docker plugins report the following events:
<add>
<add>- `install`
<add>- `enable`
<add>- `disable`
<add>- `remove`
<add>
<add>#### Volumes
<add>
<add>Docker volumes report the following events:
<add>
<add>- `create`
<add>- `mount`
<add>- `unmount`
<add>- `destroy`
<add>
<add>#### Networks
<add>
<add>Docker networks report the following events:
<add>
<add>- `create`
<add>- `connect`
<add>- `disconnect`
<add>- `destroy`
<add>
<add>#### Daemons
<add>
<add>Docker daemons report the following events:
<add>
<add>- `reload`
<add>
<add>### Limiting, filtering, and formatting the output
<add>
<add>#### Limit events by time
<add>
<add>The `--since` and `--until` parameters can be Unix timestamps, date formatted
<add>timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed
<add>relative to the client machine’s time. If you do not provide the `--since` option,
<add>the command returns only new and/or live events. Supported formats for date
<add>formatted time stamps include RFC3339Nano, RFC3339, `2006-01-02T15:04:05`,
<add>`2006-01-02T15:04:05.999999999`, `2006-01-02Z07:00`, and `2006-01-02`. The local
<add>timezone on the client will be used if you do not provide either a `Z` or a
<add>`+-00:00` timezone offset at the end of the timestamp. When providing Unix
<add>timestamps enter seconds[.nanoseconds], where seconds is the number of seconds
<add>that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap
<add>seconds (aka Unix epoch or Unix time), and the optional .nanoseconds field is a
<add>fraction of a second no more than nine digits long.
<add>
<add>#### Filtering
<add>
<add>The filtering flag (`-f` or `--filter`) format is of "key=value". If you would
<add>like to use multiple filters, pass multiple flags (e.g.,
<add>`--filter "foo=bar" --filter "bif=baz"`)
<add>
<add>Using the same filter multiple times will be handled as a *OR*; for example
<add>`--filter container=588a23dac085 --filter container=a8f7720b8c22` will display
<add>events for container 588a23dac085 *OR* container a8f7720b8c22
<add>
<add>Using multiple filters will be handled as a *AND*; for example
<add>`--filter container=588a23dac085 --filter event=start` will display events for
<add>container container 588a23dac085 *AND* the event type is *start*
<add>
<add>The currently supported filters are:
<add>
<add>* container (`container=<name or id>`)
<add>* daemon (`daemon=<name or id>`)
<add>* event (`event=<event action>`)
<add>* image (`image=<tag or id>`)
<add>* label (`label=<key>` or `label=<key>=<value>`)
<add>* network (`network=<name or id>`)
<add>* plugin (`plugin=<name or id>`)
<add>* type (`type=<container or image or volume or network or daemon or plugin>`)
<add>* volume (`volume=<name or id>`)
<add>
<add>#### Format
<add>
<add>If a format (`--format`) is specified, the given template will be executed
<add>instead of the default
<add>format. Go's [text/template](http://golang.org/pkg/text/template/) package
<add>describes all the details of the format.
<add>
<add>If a format is set to `{{json .}}`, the events are streamed as valid JSON
<add>Lines. For information about JSON Lines, please refer to http://jsonlines.org/ .
<add>
<add>## Examples
<add>
<add>### Basic example
<add>
<add>You'll need two shells for this example.
<add>
<add>**Shell 1: Listening for events:**
<add>
<add>```bash
<add>$ docker system events
<add>```
<add>
<add>**Shell 2: Start and Stop containers:**
<add>
<add>```bash
<add>$ docker create --name test alpine:latest top
<add>$ docker start test
<add>$ docker stop test
<add>```
<add>
<add>**Shell 1: (Again .. now showing events):**
<add>
<add>```none
<add>2017-01-05T00:35:58.859401177+08:00 container create 0fdb48addc82871eb34eb23a847cfd033dedd1a0a37bef2e6d9eb3870fc7ff37 (image=alpine:latest, name=test)
<add>2017-01-05T00:36:04.703631903+08:00 network connect e2e1f5ceda09d4300f3a846f0acfaa9a8bb0d89e775eb744c5acecd60e0529e2 (container=0fdb...ff37, name=bridge, type=bridge)
<add>2017-01-05T00:36:04.795031609+08:00 container start 0fdb...ff37 (image=alpine:latest, name=test)
<add>2017-01-05T00:36:09.830268747+08:00 container kill 0fdb...ff37 (image=alpine:latest, name=test, signal=15)
<add>2017-01-05T00:36:09.840186338+08:00 container die 0fdb...ff37 (exitCode=143, image=alpine:latest, name=test)
<add>2017-01-05T00:36:09.880113663+08:00 network disconnect e2e...29e2 (container=0fdb...ff37, name=bridge, type=bridge)
<add>2017-01-05T00:36:09.890214053+08:00 container stop 0fdb...ff37 (image=alpine:latest, name=test)
<add>```
<add>
<add>To exit the `docker system events` command, use `CTRL+C`.
<add>
<add>### Filter events by time
<add>
<add>You can filter the output by an absolute timestamp or relative time on the host
<add>machine, using the following different time syntaxes:
<add>
<add>```bash
<add>$ docker system events --since 1483283804
<add>2017-01-05T00:35:41.241772953+08:00 volume create testVol (driver=local)
<add>2017-01-05T00:35:58.859401177+08:00 container create d9cd...4d70 (image=alpine:latest, name=test)
<add>2017-01-05T00:36:04.703631903+08:00 network connect e2e1...29e2 (container=0fdb...ff37, name=bridge, type=bridge)
<add>2017-01-05T00:36:04.795031609+08:00 container start 0fdb...ff37 (image=alpine:latest, name=test)
<add>2017-01-05T00:36:09.830268747+08:00 container kill 0fdb...ff37 (image=alpine:latest, name=test, signal=15)
<add>2017-01-05T00:36:09.840186338+08:00 container die 0fdb...ff37 (exitCode=143, image=alpine:latest, name=test)
<add>2017-01-05T00:36:09.880113663+08:00 network disconnect e2e...29e2 (container=0fdb...ff37, name=bridge, type=bridge)
<add>2017-01-05T00:36:09.890214053+08:00 container stop 0fdb...ff37 (image=alpine:latest, name=test)
<add>
<add>$ docker system events --since '2017-01-05'
<add>2017-01-05T00:35:41.241772953+08:00 volume create testVol (driver=local)
<add>2017-01-05T00:35:58.859401177+08:00 container create d9cd...4d70 (image=alpine:latest, name=test)
<add>2017-01-05T00:36:04.703631903+08:00 network connect e2e1...29e2 (container=0fdb...ff37, name=bridge, type=bridge)
<add>2017-01-05T00:36:04.795031609+08:00 container start 0fdb...ff37 (image=alpine:latest, name=test)
<add>2017-01-05T00:36:09.830268747+08:00 container kill 0fdb...ff37 (image=alpine:latest, name=test, signal=15)
<add>2017-01-05T00:36:09.840186338+08:00 container die 0fdb...ff37 (exitCode=143, image=alpine:latest, name=test)
<add>2017-01-05T00:36:09.880113663+08:00 network disconnect e2e...29e2 (container=0fdb...ff37, name=bridge, type=bridge)
<add>2017-01-05T00:36:09.890214053+08:00 container stop 0fdb...ff37 (image=alpine:latest, name=test)
<add>
<add>$ docker system events --since '2013-09-03T15:49:29'
<add>2017-01-05T00:35:41.241772953+08:00 volume create testVol (driver=local)
<add>2017-01-05T00:35:58.859401177+08:00 container create d9cd...4d70 (image=alpine:latest, name=test)
<add>2017-01-05T00:36:04.703631903+08:00 network connect e2e1...29e2 (container=0fdb...ff37, name=bridge, type=bridge)
<add>2017-01-05T00:36:04.795031609+08:00 container start 0fdb...ff37 (image=alpine:latest, name=test)
<add>2017-01-05T00:36:09.830268747+08:00 container kill 0fdb...ff37 (image=alpine:latest, name=test, signal=15)
<add>2017-01-05T00:36:09.840186338+08:00 container die 0fdb...ff37 (exitCode=143, image=alpine:latest, name=test)
<add>2017-01-05T00:36:09.880113663+08:00 network disconnect e2e...29e2 (container=0fdb...ff37, name=bridge, type=bridge)
<add>2017-01-05T00:36:09.890214053+08:00 container stop 0fdb...ff37 (image=alpine:latest, name=test)
<add>
<add>$ docker system events --since '10m'
<add>2017-01-05T00:35:41.241772953+08:00 volume create testVol (driver=local)
<add>2017-01-05T00:35:58.859401177+08:00 container create d9cd...4d70 (image=alpine:latest, name=test)
<add>2017-01-05T00:36:04.703631903+08:00 network connect e2e1...29e2 (container=0fdb...ff37, name=bridge, type=bridge)
<add>2017-01-05T00:36:04.795031609+08:00 container start 0fdb...ff37 (image=alpine:latest, name=test)
<add>2017-01-05T00:36:09.830268747+08:00 container kill 0fdb...ff37 (image=alpine:latest, name=test, signal=15)
<add>2017-01-05T00:36:09.840186338+08:00 container die 0fdb...ff37 (exitCode=143, image=alpine:latest, name=test)
<add>2017-01-05T00:36:09.880113663+08:00 network disconnect e2e...29e2 (container=0fdb...ff37, name=bridge, type=bridge)
<add>2017-01-05T00:36:09.890214053+08:00 container stop 0fdb...ff37 (image=alpine:latest, name=test)
<add>```
<add>
<add>### Filter events by criteria
<add>
<add>The following commands show several different ways to filter the `docker event`
<add>output.
<add>
<add>```bash
<add>$ docker system events --filter 'event=stop'
<add>
<add>2017-01-05T00:40:22.880175420+08:00 container stop 0fdb...ff37 (image=alpine:latest, name=test)
<add>2017-01-05T00:41:17.888104182+08:00 container stop 2a8f...4e78 (image=alpine, name=kickass_brattain)
<add>
<add>$ docker system events --filter 'image=alpine'
<add>
<add>2017-01-05T00:41:55.784240236+08:00 container create d9cd...4d70 (image=alpine, name=happy_meitner)
<add>2017-01-05T00:41:55.913156783+08:00 container start d9cd...4d70 (image=alpine, name=happy_meitner)
<add>2017-01-05T00:42:01.106875249+08:00 container kill d9cd...4d70 (image=alpine, name=happy_meitner, signal=15)
<add>2017-01-05T00:42:11.111934041+08:00 container kill d9cd...4d70 (image=alpine, name=happy_meitner, signal=9)
<add>2017-01-05T00:42:11.119578204+08:00 container die d9cd...4d70 (exitCode=137, image=alpine, name=happy_meitner)
<add>2017-01-05T00:42:11.173276611+08:00 container stop d9cd...4d70 (image=alpine, name=happy_meitner)
<add>
<add>$ docker system events --filter 'container=test'
<add>
<add>2017-01-05T00:43:00.139719934+08:00 container start 0fdb...ff37 (image=alpine:latest, name=test)
<add>2017-01-05T00:43:09.259951086+08:00 container kill 0fdb...ff37 (image=alpine:latest, name=test, signal=15)
<add>2017-01-05T00:43:09.270102715+08:00 container die 0fdb...ff37 (exitCode=143, image=alpine:latest, name=test)
<add>2017-01-05T00:43:09.312556440+08:00 container stop 0fdb...ff37 (image=alpine:latest, name=test)
<add>
<add>$ docker system events --filter 'container=test' --filter 'container=d9cdb1525ea8'
<add>
<add>2017-01-05T00:44:11.517071981+08:00 container start 0fdb...ff37 (image=alpine:latest, name=test)
<add>2017-01-05T00:44:17.685870901+08:00 container start d9cd...4d70 (image=alpine, name=happy_meitner)
<add>2017-01-05T00:44:29.757658470+08:00 container kill 0fdb...ff37 (image=alpine:latest, name=test, signal=9)
<add>2017-01-05T00:44:29.767718510+08:00 container die 0fdb...ff37 (exitCode=137, image=alpine:latest, name=test)
<add>2017-01-05T00:44:29.815798344+08:00 container destroy 0fdb...ff37 (image=alpine:latest, name=test)
<add>
<add>$ docker system events --filter 'container=test' --filter 'event=stop'
<add>
<add>2017-01-05T00:46:13.664099505+08:00 container stop a9d1...e130 (image=alpine, name=test)
<add>
<add>$ docker system events --filter 'type=volume'
<add>
<add>2015-12-23T21:05:28.136212689Z volume create test-event-volume-local (driver=local)
<add>2015-12-23T21:05:28.383462717Z volume mount test-event-volume-local (read/write=true, container=562f...5025, destination=/foo, driver=local, propagation=rprivate)
<add>2015-12-23T21:05:28.650314265Z volume unmount test-event-volume-local (container=562f...5025, driver=local)
<add>2015-12-23T21:05:28.716218405Z volume destroy test-event-volume-local (driver=local)
<add>
<add>$ docker system events --filter 'type=network'
<add>
<add>2015-12-23T21:38:24.705709133Z network create 8b11...2c5b (name=test-event-network-local, type=bridge)
<add>2015-12-23T21:38:25.119625123Z network connect 8b11...2c5b (name=test-event-network-local, container=b4be...c54e, type=bridge)
<add>
<add>$ docker system events --filter 'container=container_1' --filter 'container=container_2'
<add>
<add>2014-09-03T15:49:29.999999999Z07:00 container die 4386fb97867d (image=ubuntu-1:14.04)
<add>2014-05-10T17:42:14.999999999Z07:00 container stop 4386fb97867d (image=ubuntu-1:14.04)
<add>2014-05-10T17:42:14.999999999Z07:00 container die 7805c1d35632 (imager=redis:2.8)
<add>2014-09-03T15:49:29.999999999Z07:00 container stop 7805c1d35632 (image=redis:2.8)
<add>
<add>$ docker system events --filter 'type=volume'
<add>
<add>2015-12-23T21:05:28.136212689Z volume create test-event-volume-local (driver=local)
<add>2015-12-23T21:05:28.383462717Z volume mount test-event-volume-local (read/write=true, container=562fe10671e9273da25eed36cdce26159085ac7ee6707105fd534866340a5025, destination=/foo, driver=local, propagation=rprivate)
<add>2015-12-23T21:05:28.650314265Z volume unmount test-event-volume-local (container=562fe10671e9273da25eed36cdce26159085ac7ee6707105fd534866340a5025, driver=local)
<add>2015-12-23T21:05:28.716218405Z volume destroy test-event-volume-local (driver=local)
<add>
<add>$ docker system events --filter 'type=network'
<add>
<add>2015-12-23T21:38:24.705709133Z network create 8b111217944ba0ba844a65b13efcd57dc494932ee2527577758f939315ba2c5b (name=test-event-network-local, type=bridge)
<add>2015-12-23T21:38:25.119625123Z network connect 8b111217944ba0ba844a65b13efcd57dc494932ee2527577758f939315ba2c5b (name=test-event-network-local, container=b4be644031a3d90b400f88ab3d4bdf4dc23adb250e696b6328b85441abe2c54e, type=bridge)
<add>
<add>$ docker system events --filter 'type=plugin'
<add>
<add>2016-07-25T17:30:14.825557616Z plugin pull ec7b87f2ce84330fe076e666f17dfc049d2d7ae0b8190763de94e1f2d105993f (name=tiborvass/sample-volume-plugin:latest)
<add>2016-07-25T17:30:14.888127370Z plugin enable ec7b87f2ce84330fe076e666f17dfc049d2d7ae0b8190763de94e1f2d105993f (name=tiborvass/sample-volume-plugin:latest)
<add>```
<add>
<add>### Format the output
<add>
<add>```bash
<add>$ docker system events --filter 'type=container' --format 'Type={{.Type}} Status={{.Status}} ID={{.ID}}'
<add>
<add>Type=container Status=create ID=2ee349dac409e97974ce8d01b70d250b85e0ba8189299c126a87812311951e26
<add>Type=container Status=attach ID=2ee349dac409e97974ce8d01b70d250b85e0ba8189299c126a87812311951e26
<add>Type=container Status=start ID=2ee349dac409e97974ce8d01b70d250b85e0ba8189299c126a87812311951e26
<add>Type=container Status=resize ID=2ee349dac409e97974ce8d01b70d250b85e0ba8189299c126a87812311951e26
<add>Type=container Status=die ID=2ee349dac409e97974ce8d01b70d250b85e0ba8189299c126a87812311951e26
<add>Type=container Status=destroy ID=2ee349dac409e97974ce8d01b70d250b85e0ba8189299c126a87812311951e26
<add>```
<add>
<add>#### Format as JSON
<add>
<add>```none
<add> $ docker system events --format '{{json .}}'
<add>
<add> {"status":"create","id":"196016a57679bf42424484918746a9474cd905dd993c4d0f4..
<add> {"status":"attach","id":"196016a57679bf42424484918746a9474cd905dd993c4d0f4..
<add> {"Type":"network","Action":"connect","Actor":{"ID":"1b50a5bf755f6021dfa78e..
<add> {"status":"start","id":"196016a57679bf42424484918746a9474cd905dd993c4d0f42..
<add> {"status":"resize","id":"196016a57679bf42424484918746a9474cd905dd993c4d0f4..
<add>```
| 2
|
Ruby
|
Ruby
|
fix typo in dependenciestesthelpers module name
|
8778e1c4af499ae42da10c1cc07a4eb2736199ac
|
<ide><path>activesupport/test/caching_test.rb
<ide> require 'logger'
<ide> require 'abstract_unit'
<ide> require 'active_support/cache'
<del>require 'dependecies_test_helpers'
<add>require 'dependencies_test_helpers'
<ide>
<ide> class CacheKeyTest < ActiveSupport::TestCase
<ide> def test_entry_legacy_optional_ivars
<ide> def test_middleware
<ide> end
<ide>
<ide> module AutoloadingCacheBehavior
<del> include DependeciesTestHelpers
<add> include DependenciesTestHelpers
<ide> def test_simple_autoloading
<ide> with_autoloading_fixtures do
<ide> @cache.write('foo', E.new)
<ide><path>activesupport/test/core_ext/marshal_test.rb
<ide> require 'abstract_unit'
<ide> require 'active_support/core_ext/marshal'
<del>require 'dependecies_test_helpers'
<add>require 'dependencies_test_helpers'
<ide>
<ide> class MarshalTest < ActiveSupport::TestCase
<ide> include ActiveSupport::Testing::Isolation
<del> include DependeciesTestHelpers
<add> include DependenciesTestHelpers
<ide>
<ide> def teardown
<ide> ActiveSupport::Dependencies.clear
<ide><path>activesupport/test/dependencies_test.rb
<ide> require 'abstract_unit'
<ide> require 'pp'
<ide> require 'active_support/dependencies'
<del>require 'dependecies_test_helpers'
<add>require 'dependencies_test_helpers'
<ide>
<ide> module ModuleWithMissing
<ide> mattr_accessor :missing_count
<ide> def teardown
<ide> ActiveSupport::Dependencies.clear
<ide> end
<ide>
<del> include DependeciesTestHelpers
<add> include DependenciesTestHelpers
<ide>
<ide> def test_depend_on_path
<ide> skip "LoadError#path does not exist" if RUBY_VERSION < '2.0.0'
<add><path>activesupport/test/dependencies_test_helpers.rb
<del><path>activesupport/test/dependecies_test_helpers.rb
<del>module DependeciesTestHelpers
<add>module DependenciesTestHelpers
<ide> def with_loading(*from)
<ide> old_mechanism, ActiveSupport::Dependencies.mechanism = ActiveSupport::Dependencies.mechanism, :load
<ide> this_dir = File.dirname(__FILE__)
| 4
|
Javascript
|
Javascript
|
use assigned variable instead of arguments
|
1c7acd2c843d9f19a0b8ecee48ec48fa617eac5e
|
<ide><path>lib/events.js
<ide> EventEmitter.prototype.setMaxListeners = function(n) {
<ide> // non-global reference, for speed.
<ide> var PROCESS;
<ide>
<del>EventEmitter.prototype.emit = function() {
<del> var type = arguments[0];
<add>EventEmitter.prototype.emit = function(type) {
<ide> // If there is no 'error' event listener then throw.
<ide> if (type === 'error') {
<ide> if (!this._events || !this._events.error ||
| 1
|
Go
|
Go
|
add "private" flag
|
fc1169a220196b78b73d5c1874d3c7bdc38d9fe3
|
<ide><path>pkg/mount/flags_linux.go
<ide> func parseOptions(options string) (int, string) {
<ide> "nodiratime": {false, syscall.MS_NODIRATIME},
<ide> "bind": {false, syscall.MS_BIND},
<ide> "rbind": {false, syscall.MS_BIND | syscall.MS_REC},
<add> "private": {false, syscall.MS_PRIVATE},
<ide> "relatime": {false, syscall.MS_RELATIME},
<ide> "norelatime": {true, syscall.MS_RELATIME},
<ide> "strictatime": {false, syscall.MS_STRICTATIME},
| 1
|
Python
|
Python
|
update pytest conf for sudachipy with japanese
|
fe167fcf7d23ee6c73877a11351984221a9aacd5
|
<ide><path>spacy/tests/conftest.py
<ide> def it_tokenizer():
<ide>
<ide> @pytest.fixture(scope="session")
<ide> def ja_tokenizer():
<del> pytest.importorskip("fugashi")
<add> pytest.importorskip("sudachipy")
<ide> return get_lang_class("ja").Defaults.create_tokenizer()
<ide>
<ide>
| 1
|
Go
|
Go
|
fix parsing of apparmor pcre syntax
|
c0f7fdc025da69283eb00d80bf47f4d47eeb0a65
|
<ide><path>daemon/execdriver/native/apparmor.go
<ide> profile {{.Name}} flags=(attach_disconnected,mediate_deleted) {
<ide> file,
<ide> umount,
<ide>
<del> deny @{PROC}/{*,**^[0-9*],sys/kernel/shm*} wkx,
<add> deny @{PROC}/{*,**^[0-9]*,sys/kernel/shm*} wkx,
<ide> deny @{PROC}/sysrq-trigger rwklx,
<ide> deny @{PROC}/mem rwklx,
<ide> deny @{PROC}/kmem rwklx,
| 1
|
Javascript
|
Javascript
|
fix jsfiddle integration
|
669b53ede21d74a7efd05592e7697e473b37e2a0
|
<ide><path>docs/src/templates/doc_widgets.js
<ide> fiddleSrc = fiddleSrc.replace(new RegExp('^\\s{' + stripIndent + '}', 'gm'), '');
<ide>
<ide> return '<form class="jsfiddle" method="post" action="' + fiddleUrl + '" target="_blank">' +
<del> '<textarea ng:model="css">' +
<add> '<textarea name="css">' +
<ide> '.ng-invalid { border: 1px solid red; } \n' +
<ide> 'body { font-family: Arial,Helvetica,sans-serif; }\n' +
<ide> 'body, td, th { font-size: 14px; margin: 0; }\n' +
<ide> 'table { border-collapse: separate; border-spacing: 2px; display: table; margin-bottom: 0; margin-top: 0; -moz-box-sizing: border-box; text-indent: 0; }\n' +
<ide> 'a:link, a:visited, a:hover { color: #5D6DB6; text-decoration: none; }\n' +
<ide> '.error { color: red; }\n' +
<ide> '</textarea>' +
<del> '<input type="text" ng:model="title" value="AngularJS Live Example">' +
<del> '<textarea ng:model="html">' +
<add> '<input type="text" name="title" value="AngularJS Live Example">' +
<add> '<textarea name="html">' +
<ide> '<script src="' + angularJsUrl + '" ng:autobind></script>\n\n' +
<ide> '<!-- AngularJS Example Code: -->\n\n' +
<ide> fiddleSrc +
| 1
|
PHP
|
PHP
|
fix absolute url generation
|
9f9c103c6f8d54a37d3e5912f5cd1fcff739a850
|
<ide><path>lib/Cake/bootstrap.php
<ide> App::uses('Object', 'Core');
<ide> App::uses('Multibyte', 'I18n');
<ide>
<add>App::$bootstrapping = true;
<add>
<add>Configure::bootstrap(isset($boot) ? $boot : true);
<add>
<ide> /**
<ide> * Full URL prefix
<ide> */
<ide> unset($httpHost, $s);
<ide> }
<ide>
<del>App::$bootstrapping = true;
<del>
<del>Configure::bootstrap(isset($boot) ? $boot : true);
<del>
<ide> if (function_exists('mb_internal_encoding')) {
<ide> $encoding = Configure::read('App.encoding');
<ide> if (!empty($encoding)) {
| 1
|
Text
|
Text
|
add absolute import example
|
046deab685254b906b13b2c247f6118e864ef44c
|
<ide><path>docs/advanced-features/module-path-aliases.md
<ide> description: Configure module path aliases that allow you to remap certain impor
<ide>
<ide> # Absolute Imports and Module path aliases
<ide>
<add><details>
<add> <summary><b>Examples</b></summary>
<add> <ul>
<add> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-absolute-imports">With env</a></li>
<add> </ul>
<add></details>
<add>
<ide> Next.js automatically supports the `tsconfig.json` and `jsconfig.json` `"paths"` and `"baseUrl"` options since [Next.js 9.4](https://nextjs.org/blog/next-9-4).
<ide>
<ide> > Note: `jsconfig.json` can be used when you don't use TypeScript
| 1
|
Java
|
Java
|
introduce subject as analogue to rx isubject
|
5b9bca978150a0ec352da38dbd49df7b5d9997f6
|
<ide><path>rxjava-core/src/main/java/rx/subjects/PublishSubject.java
<ide> import rx.util.functions.Action1;
<ide> import rx.util.functions.Func1;
<ide>
<del>public class PublishSubject<T> extends Observable<T> implements Observer<T> {
<add>public class PublishSubject<T> extends Subject<T, T> {
<ide> public static <T> PublishSubject<T> create() {
<ide> final ConcurrentHashMap<Subscription, Observer<T>> observers = new ConcurrentHashMap<Subscription, Observer<T>>();
<ide>
<ide><path>rxjava-core/src/main/java/rx/subjects/Subject.java
<add>package rx.subjects;
<add>
<add>import rx.Observable;
<add>import rx.Observer;
<add>import rx.Subscription;
<add>import rx.util.functions.Func1;
<add>
<add>public abstract class Subject<I, O> extends Observable<O> implements Observer<I> {
<add> protected Subject()
<add> {
<add> super();
<add> }
<add>
<add> protected Subject(Func1<Observer<O>, Subscription> onSubscribe)
<add> {
<add> super(onSubscribe);
<add> }
<add>}
| 2
|
Javascript
|
Javascript
|
remove hmrclient out of the bundle
|
179ac1e35930ce1a8e1e21323429932faf906b03
|
<ide><path>Libraries/JavaScriptAppEngine/Initialization/SourceMapsUtils.js
<ide>
<ide> 'use strict';
<ide>
<del>var HMRClient = require('../../Utilities/HMRClient');
<ide> var Promise = require('Promise');
<ide> var NativeModules = require('NativeModules');
<ide> var SourceMapConsumer = require('SourceMap').SourceMapConsumer;
| 1
|
Go
|
Go
|
handle escapes without swallowing all of them
|
be49867cab663b5bdcf7804f3d2504f056db9db1
|
<ide><path>builder/support.go
<ide> func (b *Builder) replaceEnv(str string) string {
<ide> continue
<ide> }
<ide>
<add> prefix := match[:idx]
<ide> stripped := match[idx+2:]
<del> str = strings.Replace(str, match, "$"+stripped, -1)
<add> str = strings.Replace(str, match, prefix+"$"+stripped, -1)
<ide> continue
<ide> }
<ide>
<ide><path>integration-cli/docker_cli_build_test.go
<ide> import (
<ide> "github.com/docker/docker/pkg/archive"
<ide> )
<ide>
<add>func TestBuildHandleEscapes(t *testing.T) {
<add> name := "testbuildhandleescapes"
<add>
<add> defer deleteImages(name)
<add>
<add> _, err := buildImage(name,
<add> `
<add> FROM scratch
<add> ENV FOO bar
<add> VOLUME ${FOO}
<add> `, true)
<add>
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> var result map[string]map[string]struct{}
<add>
<add> res, err := inspectFieldJSON(name, "Config.Volumes")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err = unmarshalJSON([]byte(res), &result); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if _, ok := result["bar"]; !ok {
<add> t.Fatal("Could not find volume bar set from env foo in volumes table")
<add> }
<add>
<add> _, err = buildImage(name,
<add> `
<add> FROM scratch
<add> ENV FOO bar
<add> VOLUME \${FOO}
<add> `, true)
<add>
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> res, err = inspectFieldJSON(name, "Config.Volumes")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err = unmarshalJSON([]byte(res), &result); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if _, ok := result["${FOO}"]; !ok {
<add> t.Fatal("Could not find volume ${FOO} set from env foo in volumes table")
<add> }
<add>
<add> // this test in particular provides *7* backslashes and expects 6 to come back.
<add> // Like above, the first escape is swallowed and the rest are treated as
<add> // literals, this one is just less obvious because of all the character noise.
<add>
<add> _, err = buildImage(name,
<add> `
<add> FROM scratch
<add> ENV FOO bar
<add> VOLUME \\\\\\\${FOO}
<add> `, true)
<add>
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> res, err = inspectFieldJSON(name, "Config.Volumes")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err = unmarshalJSON([]byte(res), &result); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if _, ok := result[`\\\\\\${FOO}`]; !ok {
<add> t.Fatal(`Could not find volume \\\\\\${FOO} set from env foo in volumes table`)
<add> }
<add>
<add> logDone("build - handle escapes")
<add>}
<add>
<ide> func TestBuildOnBuildLowercase(t *testing.T) {
<ide> name := "testbuildonbuildlowercase"
<ide> name2 := "testbuildonbuildlowercase2"
| 2
|
Text
|
Text
|
fix changelog spacing [ci skip]
|
4f21ac7e9c3a2a21f7fc9ac0d8a0be0c0c7525a2
|
<ide><path>actioncable/CHANGELOG.md
<del>* Allow channel identifiers with no backslahes/escaping to be accepted
<del> by the subscription storer.
<add>* Allow channel identifiers with no backslahes/escaping to be accepted
<add> by the subscription storer.
<ide>
<del> *Jon Moss*
<add> *Jon Moss*
<ide>
<ide> * Safely support autoloading and class unloading, by preventing concurrent
<ide> loads, and disconnecting all cables during reload.
<ide>
<ide> *Matthew Draper*
<ide>
<del>* Ensure ActionCable behaves correctly for non-string queue names.
<add>* Ensure ActionCable behaves correctly for non-string queue names.
<ide>
<del> *Jay Hayes*
<add> *Jay Hayes*
<ide>
<ide> ## Rails 5.0.0.beta3 (February 24, 2016) ##
<ide>
<del>* Added `em_redis_connector` and `redis_connector` to
<del> `ActionCable::SubscriptionAdapter::EventedRedis` and added `redis_connector`
<del> to `ActionCable::SubscriptionAdapter::Redis`, so you can overwrite with your
<del> own initializers. This is used when you want to use different-than-standard
<del> Redis adapters, like for Makara distributed Redis.
<add>* Added `em_redis_connector` and `redis_connector` to
<add> `ActionCable::SubscriptionAdapter::EventedRedis` and added `redis_connector`
<add> to `ActionCable::SubscriptionAdapter::Redis`, so you can overwrite with your
<add> own initializers. This is used when you want to use different-than-standard
<add> Redis adapters, like for Makara distributed Redis.
<ide>
<del> *DHH*
<add> *DHH*
<ide>
<ide> ## Rails 5.0.0.beta2 (February 01, 2016) ##
<ide>
<ide> ActionCable was changed from`config/redis/cable.yml` to
<ide> `config/cable.yml`.
<ide>
<del> *Jon Moss*
<add> *Jon Moss*
<ide>
<ide> ## Rails 5.0.0.beta1 (December 18, 2015) ##
<ide>
<ide><path>actionview/CHANGELOG.md
<del>* Added log "Rendering ...", when starting to render a template to log that
<del> we have started rendering something. This helps to easily identify the origin
<del> of queries in the log whether they came from controller or views.
<add>* Added log "Rendering ...", when starting to render a template to log that
<add> we have started rendering something. This helps to easily identify the origin
<add> of queries in the log whether they came from controller or views.
<ide>
<del> *Vipul A M and Prem Sichanugrist*
<add> *Vipul A M and Prem Sichanugrist*
<ide>
<ide> ## Rails 5.0.0.beta3 (February 24, 2016) ##
<ide>
<ide><path>activesupport/CHANGELOG.md
<ide>
<ide> *Brian Christian*
<ide>
<del>* Fix regression in `Hash#dig` for HashWithIndifferentAccess.
<add>* Fix regression in `Hash#dig` for HashWithIndifferentAccess.
<ide>
<del> *Jon Moss*
<add> *Jon Moss*
<ide>
<ide> ## Rails 5.0.0.beta2 (February 01, 2016) ##
<ide>
<ide><path>railties/CHANGELOG.md
<ide>
<ide> *Ryo Hashimoto*
<ide>
<del>* Enable HSTS with IncludeSudomains header for new applications.
<add>* Enable HSTS with IncludeSudomains header for new applications.
<ide>
<del> *Egor Homakov*, *Prathamesh Sonpatki*
<add> *Egor Homakov*, *Prathamesh Sonpatki*
<ide>
<ide> ## Rails 5.0.0.beta3 (February 24, 2016) ##
<ide>
| 4
|
Go
|
Go
|
allow mirroring only for the official index
|
c19962ade10619e5edd8057249566c494d4719bb
|
<ide><path>graph/pull.go
<ide> func (s *TagStore) Pull(image string, tag string, imagePullConfig *ImagePullConf
<ide> logName = utils.ImageReference(logName, tag)
<ide> }
<ide>
<del> v2mirrorEndpoint, v2mirrorRepoInfo, err := configureV2Mirror(repoInfo.Index.Mirrors, repoInfo, s.registryService)
<del> if err != nil {
<del> logrus.Errorf("Error configuring mirrors: %s", err)
<del> return err
<del> }
<add> // Attempt pulling official content from a provided v2 mirror
<add> if repoInfo.Index.Official {
<add> v2mirrorEndpoint, v2mirrorRepoInfo, err := configureV2Mirror(repoInfo, s.registryService)
<add> if err != nil {
<add> logrus.Errorf("Error configuring mirrors: %s", err)
<add> return err
<add> }
<ide>
<del> if v2mirrorEndpoint != nil {
<del> logrus.Debugf("Attempting pull from v2 mirror: %s", v2mirrorEndpoint.URL)
<del> return s.pullFromV2Mirror(v2mirrorEndpoint, v2mirrorRepoInfo, imagePullConfig, tag, sf, logName)
<add> if v2mirrorEndpoint != nil {
<add> logrus.Debugf("Attempting pull from v2 mirror: %s", v2mirrorEndpoint.URL)
<add> return s.pullFromV2Mirror(v2mirrorEndpoint, v2mirrorRepoInfo, imagePullConfig, tag, sf, logName)
<add> }
<ide> }
<ide>
<ide> logrus.Debugf("pulling image from host %q with remote name %q", repoInfo.Index.Name, repoInfo.RemoteName)
<ide> func makeMirrorRepoInfo(repoInfo *registry.RepositoryInfo, mirror string) *regis
<ide> return mirrorRepo
<ide> }
<ide>
<del>func configureV2Mirror(mirrors []string, repoInfo *registry.RepositoryInfo, s *registry.Service) (*registry.Endpoint, *registry.RepositoryInfo, error) {
<del> if len(mirrors) > 0 {
<del> // repoInfo
<del> } else {
<add>func configureV2Mirror(repoInfo *registry.RepositoryInfo, s *registry.Service) (*registry.Endpoint, *registry.RepositoryInfo, error) {
<add> mirrors := repoInfo.Index.Mirrors
<add> if len(mirrors) == 0 && !repoInfo.Index.Official {
<ide> officialIndex, err := s.ResolveIndex(registry.IndexServerName())
<ide> if err != nil {
<ide> return nil, nil, err
<ide> func (s *TagStore) pullFromV2Mirror(mirrorEndpoint *registry.Endpoint, repoInfo
<ide> registry.DockerHeaders(imagePullConfig.MetaHeaders)...,
<ide> )
<ide> client := registry.HTTPClient(tr)
<del> mirrorSession, err := registry.NewSession(client, imagePullConfig.AuthConfig, mirrorEndpoint)
<add> mirrorSession, err := registry.NewSession(client, &cliconfig.AuthConfig{}, mirrorEndpoint)
<ide> if err != nil {
<ide> return err
<ide> }
| 1
|
Go
|
Go
|
remove rpc error when shut down daemon
|
a02ae66d361464cc24bec4fb6aa5778c9d5b8cda
|
<ide><path>libcontainerd/remote_linux.go
<ide> import (
<ide> "golang.org/x/net/context"
<ide> "google.golang.org/grpc"
<ide> "google.golang.org/grpc/grpclog"
<add> "google.golang.org/grpc/transport"
<ide> )
<ide>
<ide> const (
<ide> const (
<ide>
<ide> type remote struct {
<ide> sync.RWMutex
<del> apiClient containerd.APIClient
<del> daemonPid int
<del> stateDir string
<del> rpcAddr string
<del> startDaemon bool
<del> debugLog bool
<del> rpcConn *grpc.ClientConn
<del> clients []*client
<del> eventTsPath string
<del> pastEvents map[string]*containerd.Event
<del> runtimeArgs []string
<add> apiClient containerd.APIClient
<add> daemonPid int
<add> stateDir string
<add> rpcAddr string
<add> startDaemon bool
<add> closeManually bool
<add> debugLog bool
<add> rpcConn *grpc.ClientConn
<add> clients []*client
<add> eventTsPath string
<add> pastEvents map[string]*containerd.Event
<add> runtimeArgs []string
<ide> }
<ide>
<ide> // New creates a fresh instance of libcontainerd remote.
<ide> func (r *remote) Cleanup() {
<ide> if r.daemonPid == -1 {
<ide> return
<ide> }
<add> r.closeManually = true
<ide> r.rpcConn.Close()
<ide> // Ask the daemon to quit
<ide> syscall.Kill(r.daemonPid, syscall.SIGTERM)
<ide> func (r *remote) handleEventStream(events containerd.API_EventsClient) {
<ide> for {
<ide> e, err := events.Recv()
<ide> if err != nil {
<add> if grpc.ErrorDesc(err) == transport.ErrConnClosing.Desc &&
<add> r.closeManually {
<add> // ignore error if grpc remote connection is closed manually
<add> return
<add> }
<ide> logrus.Errorf("failed to receive event from containerd: %v", err)
<ide> go r.startEventsMonitor()
<ide> return
| 1
|
Javascript
|
Javascript
|
remove unused parameters
|
ba42cedce5c07f53a6dccf1e8b4828e5b61c1298
|
<ide><path>docs/config/services/getVersion.js
<ide> var path = require('canonical-path');
<ide> * Find the current version of the node module
<ide> */
<ide> module.exports = function getVersion(readFilesProcessor) {
<del> var basePath = readFilesProcessor.basePath;
<add> var sourceFolder = path.resolve(readFilesProcessor.basePath, 'node_modules');
<add> var packageFile = 'package.json';
<ide>
<del> return function(component, sourceFolder, packageFile) {
<del> sourceFolder = path.resolve(basePath, sourceFolder || 'node_modules');
<del> packageFile = packageFile || 'package.json';
<del> return require(path.join(sourceFolder,component,packageFile)).version;
<add> return function(component) {
<add> return require(path.join(sourceFolder, component, packageFile)).version;
<ide> };
<ide> };
| 1
|
Go
|
Go
|
fix ps output
|
044bdc1b5fc748e98e7baaa7e95ce216cc667323
|
<ide><path>commands.go
<ide> func (cli *DockerCli) CmdPs(args ...string) error {
<ide> for _, out := range outs {
<ide> if !*quiet {
<ide> if *noTrunc {
<del> fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s ago\t%s\n", out.Id, out.Image, out.Command, utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.Status, out.Ports)
<add> fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\t%s\n", out.Id, out.Image, out.Command, utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.Status, out.Ports)
<ide> } else {
<del> fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s ago\t%s\n", utils.TruncateId(out.Id), out.Image, utils.Trunc(out.Command, 20), utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.Status, out.Ports)
<add> fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\t%s\n", utils.TruncateId(out.Id), out.Image, utils.Trunc(out.Command, 20), utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.Status, out.Ports)
<ide> }
<ide> } else {
<ide> if *noTrunc {
| 1
|
Ruby
|
Ruby
|
add pkgconfig dirs for all deps under superenv
|
149e65cc8a8858ce1d9c5235a92ed5bfc94dbbbe
|
<ide><path>Library/Homebrew/superenv.rb
<ide> def determine_path
<ide> end
<ide>
<ide> def determine_pkg_config_path
<del> paths = deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/lib/pkgconfig" }
<del> paths += deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/share/pkgconfig" }
<add> paths = all_deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/lib/pkgconfig" }
<add> paths += all_deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/share/pkgconfig" }
<ide> paths.to_path_s
<ide> end
<ide>
| 1
|
Go
|
Go
|
remove more of registry v1 code
|
7a50fe8a52f4e6fc6a1e6624ca81defc1e69d748
|
<ide><path>api/server/router/distribution/backend.go
<ide> import (
<ide> // Backend is all the methods that need to be implemented
<ide> // to provide image specific functionality.
<ide> type Backend interface {
<del> GetRepository(context.Context, reference.Named, *types.AuthConfig) (distribution.Repository, bool, error)
<add> GetRepository(context.Context, reference.Named, *types.AuthConfig) (distribution.Repository, error)
<ide> }
<ide><path>api/server/router/distribution/distribution_routes.go
<ide> func (s *distributionRouter) getDistributionInfo(ctx context.Context, w http.Res
<ide> return errdefs.InvalidParameter(errors.Errorf("unknown image reference format: %s", image))
<ide> }
<ide>
<del> distrepo, _, err := s.backend.GetRepository(ctx, namedRef, config)
<add> distrepo, err := s.backend.GetRepository(ctx, namedRef, config)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>daemon/cluster/executor/backend.go
<ide> type VolumeBackend interface {
<ide> // ImageBackend is used by an executor to perform image operations
<ide> type ImageBackend interface {
<ide> PullImage(ctx context.Context, image, tag string, platform *specs.Platform, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error
<del> GetRepository(context.Context, reference.Named, *types.AuthConfig) (distribution.Repository, bool, error)
<add> GetRepository(context.Context, reference.Named, *types.AuthConfig) (distribution.Repository, error)
<ide> LookupImage(name string) (*types.ImageInspect, error)
<ide> }
<ide><path>daemon/cluster/services.go
<ide> func (c *Cluster) imageWithDigestString(ctx context.Context, image string, authC
<ide> return "", errors.Errorf("image reference not tagged: %s", image)
<ide> }
<ide>
<del> repo, _, err := c.config.ImageBackend.GetRepository(ctx, taggedRef, authConfig)
<add> repo, err := c.config.ImageBackend.GetRepository(ctx, taggedRef, authConfig)
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide><path>daemon/images/image_pull.go
<ide> import (
<ide> progressutils "github.com/docker/docker/distribution/utils"
<ide> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/pkg/progress"
<del> "github.com/docker/docker/registry"
<ide> digest "github.com/opencontainers/go-digest"
<ide> specs "github.com/opencontainers/image-spec/specs-go/v1"
<ide> "github.com/pkg/errors"
<ide> func (i *ImageService) pullImageWithReference(ctx context.Context, ref reference
<ide> }
<ide>
<ide> // GetRepository returns a repository from the registry.
<del>func (i *ImageService) GetRepository(ctx context.Context, ref reference.Named, authConfig *types.AuthConfig) (dist.Repository, bool, error) {
<add>func (i *ImageService) GetRepository(ctx context.Context, ref reference.Named, authConfig *types.AuthConfig) (dist.Repository, error) {
<ide> // get repository info
<ide> repoInfo, err := i.registryService.ResolveRepository(ref)
<ide> if err != nil {
<del> return nil, false, errdefs.InvalidParameter(err)
<add> return nil, errdefs.InvalidParameter(err)
<ide> }
<ide> // makes sure name is not empty or `scratch`
<ide> if err := distribution.ValidateRepoName(repoInfo.Name); err != nil {
<del> return nil, false, errdefs.InvalidParameter(err)
<add> return nil, errdefs.InvalidParameter(err)
<ide> }
<ide>
<ide> // get endpoints
<ide> endpoints, err := i.registryService.LookupPullEndpoints(reference.Domain(repoInfo.Name))
<ide> if err != nil {
<del> return nil, false, err
<add> return nil, err
<ide> }
<ide>
<ide> // retrieve repository
<ide> var (
<del> confirmedV2 bool
<del> repository dist.Repository
<del> lastError error
<add> repository dist.Repository
<add> lastError error
<ide> )
<ide>
<ide> for _, endpoint := range endpoints {
<del> if endpoint.Version == registry.APIVersion1 {
<del> continue
<del> }
<del>
<del> repository, confirmedV2, lastError = distribution.NewV2Repository(ctx, repoInfo, endpoint, nil, authConfig, "pull")
<del> if lastError == nil && confirmedV2 {
<add> repository, lastError = distribution.NewV2Repository(ctx, repoInfo, endpoint, nil, authConfig, "pull")
<add> if lastError == nil {
<ide> break
<ide> }
<ide> }
<del> return repository, confirmedV2, lastError
<add> return repository, lastError
<ide> }
<ide>
<ide> func tempLease(ctx context.Context, mgr leases.Manager) (context.Context, func(context.Context) error, error) {
<ide><path>distribution/errors.go
<ide> func (e ErrNoSupport) Error() string {
<ide> type fallbackError struct {
<ide> // err is the error being wrapped.
<ide> err error
<del> // confirmedV2 is set to true if it was confirmed that the registry
<del> // supports the v2 protocol. This is used to limit fallbacks to the v1
<del> // protocol.
<del> confirmedV2 bool
<ide> // transportOK is set to true if we managed to speak HTTP with the
<ide> // registry. This confirms that we're using appropriate TLS settings
<ide> // (or lack of TLS).
<ide> func (f fallbackError) Cause() error {
<ide> return f.err
<ide> }
<ide>
<del>// shouldV2Fallback returns true if this error is a reason to fall back to v1.
<del>func shouldV2Fallback(err errcode.Error) bool {
<del> switch err.Code {
<del> case errcode.ErrorCodeUnauthorized, v2.ErrorCodeManifestUnknown, v2.ErrorCodeNameUnknown:
<del> return true
<del> }
<del> return false
<del>}
<del>
<ide> type notFoundError struct {
<ide> cause errcode.Error
<ide> ref reference.Named
<ide> func continueOnError(err error, mirrorEndpoint bool) bool {
<ide> case ErrNoSupport:
<ide> return continueOnError(v.Err, mirrorEndpoint)
<ide> case errcode.Error:
<del> return mirrorEndpoint || shouldV2Fallback(v)
<add> return mirrorEndpoint
<ide> case *client.UnexpectedHTTPResponseError:
<ide> return true
<ide> case ImageConfigPullError:
<ide><path>distribution/pull.go
<ide> type Puller interface {
<ide> Pull(ctx context.Context, ref reference.Named, platform *specs.Platform) error
<ide> }
<ide>
<del>// newPuller returns a Puller interface that will pull from either a v1 or v2
<del>// registry. The endpoint argument contains a Version field that determines
<del>// whether a v1 or v2 puller will be created. The other parameters are passed
<del>// through to the underlying puller implementation for use during the actual
<del>// pull operation.
<add>// newPuller returns a Puller interface that will pull from a v2 registry.
<ide> func newPuller(endpoint registry.APIEndpoint, repoInfo *registry.RepositoryInfo, imagePullConfig *ImagePullConfig, local ContentStore) (Puller, error) {
<ide> switch endpoint.Version {
<ide> case registry.APIVersion2:
<ide> func Pull(ctx context.Context, ref reference.Named, imagePullConfig *ImagePullCo
<ide> // error is the ones from v2 endpoints not v1.
<ide> discardNoSupportErrors bool
<ide>
<del> // confirmedV2 is set to true if a pull attempt managed to
<del> // confirm that it was talking to a v2 registry. This will
<del> // prevent fallback to the v1 protocol.
<del> confirmedV2 bool
<del>
<ide> // confirmedTLSRegistries is a map indicating which registries
<ide> // are known to be using TLS. There should never be a plaintext
<ide> // retry for any of these.
<ide> confirmedTLSRegistries = make(map[string]struct{})
<ide> )
<ide> for _, endpoint := range endpoints {
<del> if imagePullConfig.RequireSchema2 && endpoint.Version == registry.APIVersion1 {
<del> continue
<del> }
<del>
<del> if confirmedV2 && endpoint.Version == registry.APIVersion1 {
<del> logrus.Debugf("Skipping v1 endpoint %s because v2 registry was detected", endpoint.URL)
<del> continue
<del> }
<del>
<ide> if endpoint.URL.Scheme != "https" {
<ide> if _, confirmedTLS := confirmedTLSRegistries[endpoint.URL.Host]; confirmedTLS {
<ide> logrus.Debugf("Skipping non-TLS endpoint %s for host/port that appears to use TLS", endpoint.URL)
<ide> func Pull(ctx context.Context, ref reference.Named, imagePullConfig *ImagePullCo
<ide> default:
<ide> if fallbackErr, ok := err.(fallbackError); ok {
<ide> fallback = true
<del> confirmedV2 = confirmedV2 || fallbackErr.confirmedV2
<ide> if fallbackErr.transportOK && endpoint.URL.Scheme == "https" {
<ide> confirmedTLSRegistries[endpoint.URL.Host] = struct{}{}
<ide> }
<ide><path>distribution/pull_v2.go
<ide> import (
<ide> "fmt"
<ide> "io"
<ide> "io/ioutil"
<del> "net/url"
<ide> "os"
<ide> "runtime"
<ide> "strings"
<ide> import (
<ide> "github.com/docker/distribution/manifest/schema1"
<ide> "github.com/docker/distribution/manifest/schema2"
<ide> "github.com/docker/distribution/reference"
<del> "github.com/docker/distribution/registry/api/errcode"
<del> "github.com/docker/distribution/registry/client/auth"
<ide> "github.com/docker/distribution/registry/client/transport"
<ide> "github.com/docker/docker/distribution/metadata"
<ide> "github.com/docker/docker/distribution/xfer"
<ide> type v2Puller struct {
<ide> config *ImagePullConfig
<ide> repoInfo *registry.RepositoryInfo
<ide> repo distribution.Repository
<del> // confirmedV2 is set to true if we confirm we're talking to a v2
<del> // registry. This is used to limit fallbacks to the v1 protocol.
<del> confirmedV2 bool
<del> manifestStore *manifestStore
<add> manifestStore *manifestStore
<ide> }
<ide>
<ide> func (p *v2Puller) Pull(ctx context.Context, ref reference.Named, platform *specs.Platform) (err error) {
<ide> // TODO(tiborvass): was ReceiveTimeout
<del> p.repo, p.confirmedV2, err = NewV2Repository(ctx, p.repoInfo, p.endpoint, p.config.MetaHeaders, p.config.AuthConfig, "pull")
<add> p.repo, err = NewV2Repository(ctx, p.repoInfo, p.endpoint, p.config.MetaHeaders, p.config.AuthConfig, "pull")
<ide> if err != nil {
<ide> logrus.Warnf("Error getting v2 registry: %v", err)
<ide> return err
<ide> func (p *v2Puller) Pull(ctx context.Context, ref reference.Named, platform *spec
<ide> if continueOnError(err, p.endpoint.Mirror) {
<ide> return fallbackError{
<ide> err: err,
<del> confirmedV2: p.confirmedV2,
<ide> transportOK: true,
<ide> }
<ide> }
<ide> func (p *v2Puller) pullV2Repository(ctx context.Context, ref reference.Named, pl
<ide> } else {
<ide> tags, err := p.repo.Tags(ctx).All(ctx)
<ide> if err != nil {
<del> // If this repository doesn't exist on V2, we should
<del> // permit a fallback to V1.
<del> return allowV1Fallback(err)
<add> return err
<ide> }
<ide>
<del> // The v2 registry knows about this repository, so we will not
<del> // allow fallback to the v1 protocol even if we encounter an
<del> // error later on.
<del> p.confirmedV2 = true
<del>
<ide> for _, tag := range tags {
<ide> tagRef, err := reference.WithTag(ref, tag)
<ide> if err != nil {
<ide> func (p *v2Puller) pullV2Tag(ctx context.Context, ref reference.Named, platform
<ide> tagService := p.repo.Tags(ctx)
<ide> desc, err := tagService.Get(ctx, tagged.Tag())
<ide> if err != nil {
<del> return false, allowV1Fallback(err)
<add> return false, err
<ide> }
<ide>
<ide> dgst = desc.Digest
<ide> func (p *v2Puller) pullV2Tag(ctx context.Context, ref reference.Named, platform
<ide> }
<ide> }
<ide>
<del> // If manSvc.Get succeeded, we can be confident that the registry on
<del> // the other side speaks the v2 protocol.
<del> p.confirmedV2 = true
<del>
<ide> logrus.Debugf("Pulling ref from V2 registry: %s", reference.FamiliarString(ref))
<ide> progress.Message(p.config.ProgressOutput, tagOrDigest, "Pulling from "+reference.FamiliarName(p.repo.Named()))
<ide>
<ide> func schema2ManifestDigest(ref reference.Named, mfst distribution.Manifest) (dig
<ide> return digest.FromBytes(canonical), nil
<ide> }
<ide>
<del>// allowV1Fallback checks if the error is a possible reason to fallback to v1
<del>// (even if confirmedV2 has been set already), and if so, wraps the error in
<del>// a fallbackError with confirmedV2 set to false. Otherwise, it returns the
<del>// error unmodified.
<del>func allowV1Fallback(err error) error {
<del> switch v := err.(type) {
<del> case errcode.Errors:
<del> if len(v) != 0 {
<del> if v0, ok := v[0].(errcode.Error); ok && shouldV2Fallback(v0) {
<del> return fallbackError{
<del> err: err,
<del> confirmedV2: false,
<del> transportOK: true,
<del> }
<del> }
<del> }
<del> case errcode.Error:
<del> if shouldV2Fallback(v) {
<del> return fallbackError{
<del> err: err,
<del> confirmedV2: false,
<del> transportOK: true,
<del> }
<del> }
<del> case *url.Error:
<del> if v.Err == auth.ErrNoBasicAuthCredentials {
<del> return fallbackError{err: err, confirmedV2: false}
<del> }
<del> }
<del>
<del> return err
<del>}
<del>
<ide> func verifySchema1Manifest(signedManifest *schema1.SignedManifest, ref reference.Reference) (m *schema1.Manifest, err error) {
<ide> // If pull by digest, then verify the manifest digest. NOTE: It is
<ide> // important to do this first, before any other content validation. If the
<ide><path>distribution/push.go
<ide> func Push(ctx context.Context, ref reference.Named, imagePushConfig *ImagePushCo
<ide> var (
<ide> lastErr error
<ide>
<del> // confirmedV2 is set to true if a push attempt managed to
<del> // confirm that it was talking to a v2 registry. This will
<del> // prevent fallback to the v1 protocol.
<del> confirmedV2 bool
<del>
<ide> // confirmedTLSRegistries is a map indicating which registries
<ide> // are known to be using TLS. There should never be a plaintext
<ide> // retry for any of these.
<ide> confirmedTLSRegistries = make(map[string]struct{})
<ide> )
<ide>
<ide> for _, endpoint := range endpoints {
<del> if imagePushConfig.RequireSchema2 && endpoint.Version == registry.APIVersion1 {
<del> continue
<del> }
<del> if confirmedV2 && endpoint.Version == registry.APIVersion1 {
<del> logrus.Debugf("Skipping v1 endpoint %s because v2 registry was detected", endpoint.URL)
<del> continue
<del> }
<del>
<ide> if endpoint.URL.Scheme != "https" {
<ide> if _, confirmedTLS := confirmedTLSRegistries[endpoint.URL.Host]; confirmedTLS {
<ide> logrus.Debugf("Skipping non-TLS endpoint %s for host/port that appears to use TLS", endpoint.URL)
<ide> func Push(ctx context.Context, ref reference.Named, imagePushConfig *ImagePushCo
<ide> case <-ctx.Done():
<ide> default:
<ide> if fallbackErr, ok := err.(fallbackError); ok {
<del> confirmedV2 = confirmedV2 || fallbackErr.confirmedV2
<ide> if fallbackErr.transportOK && endpoint.URL.Scheme == "https" {
<ide> confirmedTLSRegistries[endpoint.URL.Host] = struct{}{}
<ide> }
<ide><path>distribution/push_v2.go
<ide> type pushState struct {
<ide> // involve the same layers. It is also used to fill in digest and size
<ide> // information when building the manifest.
<ide> remoteLayers map[layer.DiffID]distribution.Descriptor
<del> // confirmedV2 is set to true if we confirm we're talking to a v2
<del> // registry. This is used to limit fallbacks to the v1 protocol.
<del> confirmedV2 bool
<del> hasAuthInfo bool
<add> hasAuthInfo bool
<ide> }
<ide>
<ide> func (p *v2Pusher) Push(ctx context.Context) (err error) {
<ide> p.pushState.remoteLayers = make(map[layer.DiffID]distribution.Descriptor)
<ide>
<del> p.repo, p.pushState.confirmedV2, err = NewV2Repository(ctx, p.repoInfo, p.endpoint, p.config.MetaHeaders, p.config.AuthConfig, "push", "pull")
<add> p.repo, err = NewV2Repository(ctx, p.repoInfo, p.endpoint, p.config.MetaHeaders, p.config.AuthConfig, "push", "pull")
<ide> p.pushState.hasAuthInfo = p.config.AuthConfig.RegistryToken != "" || (p.config.AuthConfig.Username != "" && p.config.AuthConfig.Password != "")
<ide> if err != nil {
<ide> logrus.Debugf("Error getting v2 registry: %v", err)
<ide> func (p *v2Pusher) Push(ctx context.Context) (err error) {
<ide> if continueOnError(err, p.endpoint.Mirror) {
<ide> return fallbackError{
<ide> err: err,
<del> confirmedV2: p.pushState.confirmedV2,
<ide> transportOK: true,
<ide> }
<ide> }
<ide> func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress.
<ide> err.Descriptor.MediaType = schema2.MediaTypeLayer
<ide>
<ide> pd.pushState.Lock()
<del> pd.pushState.confirmedV2 = true
<ide> pd.pushState.remoteLayers[diffID] = err.Descriptor
<ide> pd.pushState.Unlock()
<ide>
<ide> func (pd *v2PushDescriptor) uploadUsingSession(
<ide> }
<ide>
<ide> pd.pushState.Lock()
<del> // If Commit succeeded, that's an indication that the remote registry speaks the v2 protocol.
<del> pd.pushState.confirmedV2 = true
<ide> pd.pushState.remoteLayers[diffID] = desc
<ide> pd.pushState.Unlock()
<ide>
<ide><path>distribution/push_v2_test.go
<ide> func TestWhenEmptyAuthConfig(t *testing.T) {
<ide> Scheme: "https",
<ide> Host: "index.docker.io",
<ide> },
<del> Version: registry.APIVersion1,
<add> Version: registry.APIVersion2,
<ide> TrimHostname: true,
<ide> },
<ide> }
<ide><path>distribution/registry.go
<ide> func init() {
<ide> func NewV2Repository(
<ide> ctx context.Context, repoInfo *registry.RepositoryInfo, endpoint registry.APIEndpoint,
<ide> metaHeaders http.Header, authConfig *types.AuthConfig, actions ...string,
<del>) (repo distribution.Repository, foundVersion bool, err error) {
<add>) (repo distribution.Repository, err error) {
<ide> repoName := repoInfo.Name.Name()
<ide> // If endpoint does not support CanonicalName, use the RemoteName instead
<ide> if endpoint.TrimHostname {
<ide> func NewV2Repository(
<ide> modifiers := registry.Headers(dockerversion.DockerUserAgent(ctx), metaHeaders)
<ide> authTransport := transport.NewTransport(base, modifiers...)
<ide>
<del> challengeManager, foundVersion, err := registry.PingV2Registry(endpoint.URL, authTransport)
<add> challengeManager, err := registry.PingV2Registry(endpoint.URL, authTransport)
<ide> if err != nil {
<ide> transportOK := false
<ide> if responseErr, ok := err.(registry.PingResponseError); ok {
<ide> transportOK = true
<ide> err = responseErr.Err
<ide> }
<del> return nil, foundVersion, fallbackError{
<add> return nil, fallbackError{
<ide> err: err,
<del> confirmedV2: foundVersion,
<ide> transportOK: transportOK,
<ide> }
<ide> }
<ide> func NewV2Repository(
<ide>
<ide> repoNameRef, err := reference.WithName(repoName)
<ide> if err != nil {
<del> return nil, foundVersion, fallbackError{
<add> return nil, fallbackError{
<ide> err: err,
<del> confirmedV2: foundVersion,
<ide> transportOK: true,
<ide> }
<ide> }
<ide> func NewV2Repository(
<ide> if err != nil {
<ide> err = fallbackError{
<ide> err: err,
<del> confirmedV2: foundVersion,
<ide> transportOK: true,
<ide> }
<ide> }
<ide><path>distribution/registry_unit_test.go
<ide> func testTokenPassThru(t *testing.T, ts *httptest.Server) {
<ide> }
<ide> p := puller.(*v2Puller)
<ide> ctx := context.Background()
<del> p.repo, _, err = NewV2Repository(ctx, p.repoInfo, p.endpoint, p.config.MetaHeaders, p.config.AuthConfig, "pull")
<add> p.repo, err = NewV2Repository(ctx, p.repoInfo, p.endpoint, p.config.MetaHeaders, p.config.AuthConfig, "pull")
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide><path>registry/auth.go
<ide> func loginV2(authConfig *types.AuthConfig, endpoint APIEndpoint, userAgent strin
<ide>
<ide> logrus.Debugf("attempting v2 login to registry endpoint %s", endpointStr)
<ide>
<del> loginClient, foundV2, err := v2AuthHTTPClient(endpoint.URL, authTransport, modifiers, creds, nil)
<add> loginClient, err := v2AuthHTTPClient(endpoint.URL, authTransport, modifiers, creds, nil)
<ide> if err != nil {
<ide> return "", "", err
<ide> }
<ide>
<ide> req, err := http.NewRequest(http.MethodGet, endpointStr, nil)
<ide> if err != nil {
<del> if !foundV2 {
<del> err = fallbackError{err: err}
<del> }
<ide> return "", "", err
<ide> }
<ide>
<ide> resp, err := loginClient.Do(req)
<ide> if err != nil {
<ide> err = translateV2AuthError(err)
<del> if !foundV2 {
<del> err = fallbackError{err: err}
<del> }
<del>
<ide> return "", "", err
<ide> }
<ide> defer resp.Body.Close()
<ide> func loginV2(authConfig *types.AuthConfig, endpoint APIEndpoint, userAgent strin
<ide>
<ide> // TODO(dmcgowan): Attempt to further interpret result, status code and error code string
<ide> err = errors.Errorf("login attempt to %s failed with status: %d %s", endpointStr, resp.StatusCode, http.StatusText(resp.StatusCode))
<del> if !foundV2 {
<del> err = fallbackError{err: err}
<del> }
<ide> return "", "", err
<ide> }
<ide>
<del>func v2AuthHTTPClient(endpoint *url.URL, authTransport http.RoundTripper, modifiers []transport.RequestModifier, creds auth.CredentialStore, scopes []auth.Scope) (*http.Client, bool, error) {
<del> challengeManager, foundV2, err := PingV2Registry(endpoint, authTransport)
<add>func v2AuthHTTPClient(endpoint *url.URL, authTransport http.RoundTripper, modifiers []transport.RequestModifier, creds auth.CredentialStore, scopes []auth.Scope) (*http.Client, error) {
<add> challengeManager, err := PingV2Registry(endpoint, authTransport)
<ide> if err != nil {
<del> if !foundV2 {
<del> err = fallbackError{err: err}
<del> }
<del> return nil, foundV2, err
<add> return nil, err
<ide> }
<ide>
<ide> tokenHandlerOptions := auth.TokenHandlerOptions{
<ide> func v2AuthHTTPClient(endpoint *url.URL, authTransport http.RoundTripper, modifi
<ide> return &http.Client{
<ide> Transport: tr,
<ide> Timeout: 15 * time.Second,
<del> }, foundV2, nil
<del>
<add> }, nil
<ide> }
<ide>
<ide> // ConvertToHostname converts a registry url which has http|https prepended
<ide> func (err PingResponseError) Error() string {
<ide> }
<ide>
<ide> // PingV2Registry attempts to ping a v2 registry and on success return a
<del>// challenge manager for the supported authentication types and
<del>// whether v2 was confirmed by the response. If a response is received but
<del>// cannot be interpreted a PingResponseError will be returned.
<del>func PingV2Registry(endpoint *url.URL, transport http.RoundTripper) (challenge.Manager, bool, error) {
<del> var (
<del> foundV2 = false
<del> v2Version = auth.APIVersion{
<del> Type: "registry",
<del> Version: "2.0",
<del> }
<del> )
<del>
<add>// challenge manager for the supported authentication types.
<add>// If a response is received but cannot be interpreted, a PingResponseError will be returned.
<add>func PingV2Registry(endpoint *url.URL, transport http.RoundTripper) (challenge.Manager, error) {
<ide> pingClient := &http.Client{
<ide> Transport: transport,
<ide> Timeout: 15 * time.Second,
<ide> }
<ide> endpointStr := strings.TrimRight(endpoint.String(), "/") + "/v2/"
<ide> req, err := http.NewRequest(http.MethodGet, endpointStr, nil)
<ide> if err != nil {
<del> return nil, false, err
<add> return nil, err
<ide> }
<ide> resp, err := pingClient.Do(req)
<ide> if err != nil {
<del> return nil, false, err
<add> return nil, err
<ide> }
<ide> defer resp.Body.Close()
<ide>
<del> versions := auth.APIVersions(resp, DefaultRegistryVersionHeader)
<del> for _, pingVersion := range versions {
<del> if pingVersion == v2Version {
<del> // The version header indicates we're definitely
<del> // talking to a v2 registry. So don't allow future
<del> // fallbacks to the v1 protocol.
<del>
<del> foundV2 = true
<del> break
<del> }
<del> }
<del>
<ide> challengeManager := challenge.NewSimpleManager()
<ide> if err := challengeManager.AddResponse(resp); err != nil {
<del> return nil, foundV2, PingResponseError{
<add> return nil, PingResponseError{
<ide> Err: err,
<ide> }
<ide> }
<ide>
<del> return challengeManager, foundV2, nil
<add> return challengeManager, nil
<ide> }
<ide><path>registry/endpoint_v1.go
<ide> type V1Endpoint struct {
<ide> }
<ide>
<ide> // NewV1Endpoint parses the given address to return a registry endpoint.
<add>// TODO: remove. This is only used by search.
<ide> func NewV1Endpoint(index *registrytypes.IndexInfo, userAgent string, metaHeaders http.Header) (*V1Endpoint, error) {
<ide> tlsConfig, err := newTLSConfig(index.Name, index.Secure)
<ide> if err != nil {
<ide><path>registry/service.go
<ide> func (s *DefaultService) Auth(ctx context.Context, authConfig *types.AuthConfig,
<ide> }
<ide>
<ide> for _, endpoint := range endpoints {
<del> status, token, err = loginV2(authConfig, endpoint, userAgent)
<del> if err == nil {
<del> return
<del> }
<del> if fErr, ok := err.(fallbackError); ok {
<del> logrus.WithError(fErr.err).Infof("Error logging in to endpoint, trying next endpoint")
<del> continue
<del> }
<del>
<del> return "", "", err
<add> return loginV2(authConfig, endpoint, userAgent)
<ide> }
<ide>
<ide> return "", "", err
<ide> func (s *DefaultService) Search(ctx context.Context, term string, limit int, aut
<ide> }
<ide>
<ide> modifiers := Headers(userAgent, nil)
<del> v2Client, foundV2, err := v2AuthHTTPClient(endpoint.URL, endpoint.client.Transport, modifiers, creds, scopes)
<add> v2Client, err := v2AuthHTTPClient(endpoint.URL, endpoint.client.Transport, modifiers, creds, scopes)
<ide> if err != nil {
<ide> if fErr, ok := err.(fallbackError); ok {
<ide> logrus.Errorf("Cannot use identity token for search, v2 auth not supported: %v", fErr.err)
<ide> } else {
<ide> return nil, err
<ide> }
<del> } else if foundV2 {
<add> } else {
<ide> // Copy non transport http client features
<ide> v2Client.Timeout = endpoint.client.Timeout
<ide> v2Client.CheckRedirect = endpoint.client.CheckRedirect
| 16
|
Java
|
Java
|
add apply method to webclient.builder
|
d6c102d1b89b374e637639453d57c97b0f3f42b3
|
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultWebClientBuilder.java
<ide> public WebClient.Builder clone() {
<ide> return new DefaultWebClientBuilder(this);
<ide> }
<ide>
<add> @Override
<add> public WebClient.Builder apply(Consumer<WebClient.Builder> builderConsumer) {
<add> Assert.notNull(builderConsumer, "'builderConsumer' must not be null");
<add>
<add> builderConsumer.accept(this);
<add> return this;
<add> }
<add>
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/WebClient.java
<ide> interface Builder {
<ide> Builder exchangeFunction(ExchangeFunction exchangeFunction);
<ide>
<ide> /**
<del> * Builder the {@link WebClient} instance.
<add> * Clone this {@code WebClient.Builder}
<ide> */
<del> WebClient build();
<add> Builder clone();
<ide>
<ide> /**
<del> * Clone this {@code WebClient.Builder}
<add> * Shortcut for pre-packaged customizations to WebTest builder.
<add> * @param builderConsumer the consumer to apply
<ide> */
<del> Builder clone();
<add> Builder apply(Consumer<Builder> builderConsumer);
<add>
<add> /**
<add> * Builder the {@link WebClient} instance.
<add> */
<add> WebClient build();
<ide>
<ide> }
<ide>
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultWebClientTests.java
<ide> public void attributes() {
<ide> client.get().uri("/path").attribute("foo", "bar").exchange();
<ide> }
<ide>
<add> @Test
<add> public void apply() {
<add> WebClient client = builder()
<add> .apply(builder -> builder.defaultHeader("Accept", "application/json").defaultCookie("id", "123"))
<add> .build();
<add> client.get().uri("/path").exchange();
<add>
<add> ClientRequest request = verifyExchange();
<add> assertEquals("application/json", request.headers().getFirst("Accept"));
<add> assertEquals("123", request.cookies().getFirst("id"));
<add> verifyNoMoreInteractions(this.exchangeFunction);
<add> }
<add>
<ide>
<ide>
<ide> private WebClient.Builder builder() {
| 3
|
Python
|
Python
|
fix typo on rebuild warning message
|
108ecbe815b3651e1021cc944d29b050b72233ea
|
<ide><path>dev/breeze/src/airflow_breeze/commands/ci_image_commands.py
<ide> def should_we_run_the_build(build_ci_params: BuildCiParams) -> bool:
<ide> return True
<ide> else:
<ide> get_console().print(
<del> "\n[warning]This might take a lot of time (more than 10 minutes) even if you have"
<add> "\n[warning]This might take a lot of time (more than 10 minutes) even if you have "
<ide> "a good network connection. We think you should attempt to rebase first.[/]\n"
<ide> )
<ide> answer = user_confirm(
| 1
|
Python
|
Python
|
fix unboundlocalerror in handle_url_build_error
|
5da31f8af36012a4f76c3bd0d536ae107e0519b5
|
<ide><path>flask/app.py
<ide> def handle_url_build_error(self, error, endpoint, values):
<ide> rv = handler(error, endpoint, values)
<ide> if rv is not None:
<ide> return rv
<del> except BuildError as error:
<del> pass
<add> except BuildError as e:
<add> # make error available outside except block (py3)
<add> error = e
<ide>
<ide> # At this point we want to reraise the exception. If the error is
<ide> # still the same one we can reraise it with the original traceback,
<ide><path>flask/testsuite/basic.py
<ide> def handler(error, endpoint, values):
<ide> with app.test_request_context():
<ide> self.assert_equal(flask.url_for('spam'), '/test_handler/')
<ide>
<add> def test_build_error_handler_reraise(self):
<add> app = flask.Flask(__name__)
<add>
<add> # Test a custom handler which reraises the BuildError
<add> def handler_raises_build_error(error, endpoint, values):
<add> raise error
<add> app.url_build_error_handlers.append(handler_raises_build_error)
<add>
<add> with app.test_request_context():
<add> self.assertRaises(BuildError, flask.url_for, 'not.existing')
<add>
<ide> def test_custom_converters(self):
<ide> from werkzeug.routing import BaseConverter
<ide> class ListConverter(BaseConverter):
| 2
|
Javascript
|
Javascript
|
improve transform performance
|
e5dc934ef6f66edade76720dc7592e9e348db49f
|
<ide><path>benchmark/streams/transform-creation.js
<add>'use strict';
<add>var common = require('../common.js');
<add>var Transform = require('stream').Transform;
<add>var inherits = require('util').inherits;
<add>
<add>var bench = common.createBenchmark(main, {
<add> n: [1e6]
<add>});
<add>
<add>function MyTransform() {
<add> Transform.call(this);
<add>}
<add>inherits(MyTransform, Transform);
<add>MyTransform.prototype._transform = function() {};
<add>
<add>function main(conf) {
<add> var n = +conf.n;
<add>
<add> bench.start();
<add> for (var i = 0; i < n; ++i)
<add> new MyTransform();
<add> bench.end(n);
<add>}
<ide><path>lib/_stream_transform.js
<ide> const util = require('util');
<ide> util.inherits(Transform, Duplex);
<ide>
<ide>
<del>function TransformState(stream) {
<del> this.afterTransform = function(er, data) {
<del> return afterTransform(stream, er, data);
<del> };
<del>
<del> this.needTransform = false;
<del> this.transforming = false;
<del> this.writecb = null;
<del> this.writechunk = null;
<del> this.writeencoding = null;
<del>}
<del>
<del>function afterTransform(stream, er, data) {
<del> var ts = stream._transformState;
<add>function afterTransform(er, data) {
<add> var ts = this._transformState;
<ide> ts.transforming = false;
<ide>
<ide> var cb = ts.writecb;
<ide>
<ide> if (!cb) {
<del> return stream.emit('error',
<del> new Error('write callback called multiple times'));
<add> return this.emit('error',
<add> new Error('write callback called multiple times'));
<ide> }
<ide>
<ide> ts.writechunk = null;
<ide> ts.writecb = null;
<ide>
<del> if (data !== null && data !== undefined)
<del> stream.push(data);
<add> if (data != null) // single equals check for both `null` and `undefined`
<add> this.push(data);
<ide>
<ide> cb(er);
<ide>
<del> var rs = stream._readableState;
<add> var rs = this._readableState;
<ide> rs.reading = false;
<ide> if (rs.needReadable || rs.length < rs.highWaterMark) {
<del> stream._read(rs.highWaterMark);
<add> this._read(rs.highWaterMark);
<ide> }
<ide> }
<ide>
<ide> function Transform(options) {
<ide>
<ide> Duplex.call(this, options);
<ide>
<del> this._transformState = new TransformState(this);
<del>
<del> var stream = this;
<add> this._transformState = {
<add> afterTransform: afterTransform.bind(this),
<add> needTransform: false,
<add> transforming: false,
<add> writecb: null,
<add> writechunk: null,
<add> writeencoding: null
<add> };
<ide>
<ide> // start out asking for a readable event once data is transformed.
<ide> this._readableState.needReadable = true;
<ide> function Transform(options) {
<ide> }
<ide>
<ide> // When the writable side finishes, then flush out anything remaining.
<del> this.once('prefinish', function() {
<del> if (typeof this._flush === 'function')
<del> this._flush(function(er, data) {
<del> done(stream, er, data);
<del> });
<del> else
<del> done(stream);
<del> });
<add> this.on('prefinish', prefinish);
<add>}
<add>
<add>function prefinish() {
<add> if (typeof this._flush === 'function') {
<add> this._flush((er, data) => {
<add> done(this, er, data);
<add> });
<add> } else {
<add> done(this, null, null);
<add> }
<ide> }
<ide>
<ide> Transform.prototype.push = function(chunk, encoding) {
<ide> function done(stream, er, data) {
<ide> if (er)
<ide> return stream.emit('error', er);
<ide>
<del> if (data !== null && data !== undefined)
<add> if (data != null) // single equals check for both `null` and `undefined`
<ide> stream.push(data);
<ide>
<ide> // if there's nothing in the write buffer, then that means
<ide> // that nothing more will ever be provided
<del> var ws = stream._writableState;
<del> var ts = stream._transformState;
<del>
<del> if (ws.length)
<add> if (stream._writableState.length)
<ide> throw new Error('Calling transform done when ws.length != 0');
<ide>
<del> if (ts.transforming)
<add> if (stream._transformState.transforming)
<ide> throw new Error('Calling transform done when still transforming');
<ide>
<ide> return stream.push(null);
| 2
|
Javascript
|
Javascript
|
name anonymous functions
|
ef030da818c962af92f9a02d289e7eb7cc8cecd5
|
<ide><path>lib/assert.js
<ide> function _throws(shouldThrow, block, expected, message) {
<ide> // 11. Expected to throw an error:
<ide> // assert.throws(block, Error_opt, message_opt);
<ide>
<del>assert.throws = function(block, /*optional*/error, /*optional*/message) {
<add>assert.throws = function throws(block, /*optional*/error, /*optional*/message) {
<ide> _throws(true, block, error, message);
<ide> };
<ide>
<ide> // EXTENSION! This is annoying to write outside this module.
<del>assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
<add>assert.doesNotThrow = doesNotThrow;
<add>function doesNotThrow(block, /*optional*/error, /*optional*/message) {
<ide> _throws(false, block, error, message);
<del>};
<add>}
<ide>
<del>assert.ifError = function(err) { if (err) throw err; };
<add>assert.ifError = function ifError(err) { if (err) throw err; };
| 1
|
Text
|
Text
|
adjust listfield & dictfield signature docs
|
43c7af0bb51ba2110ec075a0ebe17f52dbb08e9c
|
<ide><path>docs/api-guide/fields.md
<ide> Requires either the `Pillow` package or `PIL` package. The `Pillow` package is
<ide>
<ide> A field class that validates a list of objects.
<ide>
<del>**Signature**: `ListField(child, min_length=None, max_length=None)`
<add>**Signature**: `ListField(child=<A_FIELD_INSTANCE>, min_length=None, max_length=None)`
<ide>
<ide> - `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
<ide> - `min_length` - Validates that the list contains no fewer than this number of elements.
<ide> We can now reuse our custom `StringListField` class throughout our application,
<ide>
<ide> A field class that validates a dictionary of objects. The keys in `DictField` are always assumed to be string values.
<ide>
<del>**Signature**: `DictField(child)`
<add>**Signature**: `DictField(child=<A_FIELD_INSTANCE>)`
<ide>
<ide> - `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
<ide>
| 1
|
PHP
|
PHP
|
add method to commandname
|
34b2ed68e2dfe038050d74a28947e1180bb8cb2b
|
<ide><path>src/Illuminate/Queue/Queue.php
<ide> protected function createPayload($job, $data = '', $queue = null)
<ide> } elseif (is_object($job)) {
<ide> return json_encode([
<ide> 'job' => 'Illuminate\Queue\CallQueuedHandler@call',
<del> 'data' => ['commandName' => get_class($job), 'command' => serialize(clone $job)],
<add> 'data' => [
<add> 'commandName' => get_class($job).'@handle',
<add> 'command' => serialize(clone $job),
<add> ],
<ide> ]);
<ide> }
<ide>
| 1
|
Ruby
|
Ruby
|
add test cases for negative position in array#from
|
3920d64479c8763e1f0a64db872e5f072268cda9
|
<ide><path>activesupport/lib/active_support/core_ext/array/access.rb
<ide> class Array
<ide> # %w( a b c d ).from(2) # => ["c", "d"]
<ide> # %w( a b c d ).from(10) # => []
<ide> # %w().from(0) # => []
<add> # %w( a b c d ).from(-2) # => ["c", "d"]
<add> # %w( a b c ).from(-10) # => []
<ide> def from(position)
<ide> self[position, length] || []
<ide> end
<ide><path>activesupport/test/core_ext/array_ext_test.rb
<ide> def test_from
<ide> assert_equal %w( a b c d ), %w( a b c d ).from(0)
<ide> assert_equal %w( c d ), %w( a b c d ).from(2)
<ide> assert_equal %w(), %w( a b c d ).from(10)
<add> assert_equal %w( d e ), %w( a b c d e ).from(-2)
<add> assert_equal %w(), %w( a b c d e ).from(-10)
<ide> end
<ide>
<ide> def test_to
| 2
|
Python
|
Python
|
add remaining tests for generics
|
31e9f7dfbba7ad967d7f912e2014d9ad291fca3e
|
<ide><path>tests/test_generics.py
<ide> def get(self, request):
<ide> request = factory.get('/')
<ide> with pytest.raises(RuntimeError):
<ide> view(request).render()
<add>
<add>
<add>class ApiViewsTests(TestCase):
<add>
<add> def test_create_api_view_post(self):
<add> class MockCreateApiView(generics.CreateAPIView):
<add> def create(self, request, *args, **kwargs):
<add> self.called = True
<add> self.call_args = (request, args, kwargs)
<add> view = MockCreateApiView()
<add> data = ('test request', ('test arg',), {'test_kwarg': 'test'})
<add> view.post('test request', 'test arg', test_kwarg='test')
<add> assert view.called is True
<add> assert view.call_args == data
<add>
<add> def test_destroy_api_view_delete(self):
<add> class MockDestroyApiView(generics.DestroyAPIView):
<add> def destroy(self, request, *args, **kwargs):
<add> self.called = True
<add> self.call_args = (request, args, kwargs)
<add> view = MockDestroyApiView()
<add> data = ('test request', ('test arg',), {'test_kwarg': 'test'})
<add> view.delete('test request', 'test arg', test_kwarg='test')
<add> assert view.called is True
<add> assert view.call_args == data
<add>
<add> def test_update_api_view_partial_update(self):
<add> class MockUpdateApiView(generics.UpdateAPIView):
<add> def partial_update(self, request, *args, **kwargs):
<add> self.called = True
<add> self.call_args = (request, args, kwargs)
<add> view = MockUpdateApiView()
<add> data = ('test request', ('test arg',), {'test_kwarg': 'test'})
<add> view.patch('test request', 'test arg', test_kwarg='test')
<add> assert view.called is True
<add> assert view.call_args == data
<add>
<add> def test_retrieve_update_api_view_get(self):
<add> class MockRetrieveUpdateApiView(generics.RetrieveUpdateAPIView):
<add> def retrieve(self, request, *args, **kwargs):
<add> self.called = True
<add> self.call_args = (request, args, kwargs)
<add> view = MockRetrieveUpdateApiView()
<add> data = ('test request', ('test arg',), {'test_kwarg': 'test'})
<add> view.get('test request', 'test arg', test_kwarg='test')
<add> assert view.called is True
<add> assert view.call_args == data
<add>
<add> def test_retrieve_update_api_view_put(self):
<add> class MockRetrieveUpdateApiView(generics.RetrieveUpdateAPIView):
<add> def update(self, request, *args, **kwargs):
<add> self.called = True
<add> self.call_args = (request, args, kwargs)
<add> view = MockRetrieveUpdateApiView()
<add> data = ('test request', ('test arg',), {'test_kwarg': 'test'})
<add> view.put('test request', 'test arg', test_kwarg='test')
<add> assert view.called is True
<add> assert view.call_args == data
<add>
<add> def test_retrieve_update_api_view_patch(self):
<add> class MockRetrieveUpdateApiView(generics.RetrieveUpdateAPIView):
<add> def partial_update(self, request, *args, **kwargs):
<add> self.called = True
<add> self.call_args = (request, args, kwargs)
<add> view = MockRetrieveUpdateApiView()
<add> data = ('test request', ('test arg',), {'test_kwarg': 'test'})
<add> view.patch('test request', 'test arg', test_kwarg='test')
<add> assert view.called is True
<add> assert view.call_args == data
<add>
<add> def test_retrieve_destroy_api_view_get(self):
<add> class MockRetrieveDestroyUApiView(generics.RetrieveDestroyAPIView):
<add> def retrieve(self, request, *args, **kwargs):
<add> self.called = True
<add> self.call_args = (request, args, kwargs)
<add> view = MockRetrieveDestroyUApiView()
<add> data = ('test request', ('test arg',), {'test_kwarg': 'test'})
<add> view.get('test request', 'test arg', test_kwarg='test')
<add> assert view.called is True
<add> assert view.call_args == data
<add>
<add> def test_retrieve_destroy_api_view_delete(self):
<add> class MockRetrieveDestroyUApiView(generics.RetrieveDestroyAPIView):
<add> def destroy(self, request, *args, **kwargs):
<add> self.called = True
<add> self.call_args = (request, args, kwargs)
<add> view = MockRetrieveDestroyUApiView()
<add> data = ('test request', ('test arg',), {'test_kwarg': 'test'})
<add> view.delete('test request', 'test arg', test_kwarg='test')
<add> assert view.called is True
<add> assert view.call_args == data
| 1
|
Javascript
|
Javascript
|
mark 3 regressions as skipped
|
0346b9bfe8b5a94480f0027eddf7887f8896b8fb
|
<ide><path>packages/ember-views/tests/views/collection_test.js
<ide> QUnit.test("should render a view for each item in its content array", function()
<ide> equal(view.$('div').length, 4);
<ide> });
<ide>
<del>QUnit.test("should render the emptyView if content array is empty (view class)", function() {
<add>QUnit.skip("should render the emptyView if content array is empty (view class)", function() {
<ide> view = CollectionView.create({
<ide> tagName: 'del',
<ide> content: Ember.A(),
<ide> QUnit.test("when a collection view is emptied, deeply nested views elements are
<ide> deepEqual(gotDestroyed, ['parent', 'child'], "The child view was destroyed");
<ide> });
<ide>
<del>QUnit.test("should render the emptyView if content array is empty and emptyView is given as string", function() {
<add>QUnit.skip("should render the emptyView if content array is empty and emptyView is given as string", function() {
<ide> expectDeprecation(/Resolved the view "App.EmptyView" on the global context/);
<ide>
<ide> Ember.lookup = {
<ide> QUnit.test("should lookup only global path against the container if itemViewClas
<ide> equal(view.$().text(), 'hi');
<ide> });
<ide>
<del>QUnit.test("should lookup against the container and render the emptyView if emptyView is given as string and content array is empty ", function() {
<add>QUnit.skip("should lookup against the container and render the emptyView if emptyView is given as string and content array is empty ", function() {
<ide> var EmptyView = View.extend({
<ide> tagName: 'kbd',
<ide> template: compile('THIS IS AN EMPTY VIEW')
| 1
|
PHP
|
PHP
|
remove manual class loading
|
0e9a609ef2e5de164862f09415cf497ccbf533db
|
<ide><path>lib/Cake/Core/App.php
<ide> class App {
<ide> */
<ide> const RESET = true;
<ide>
<del>/**
<del> * Paths to search for files.
<del> *
<del> * @var array
<del> */
<del> public static $search = array();
<del>
<del>/**
<del> * Whether or not to return the file that is loaded.
<del> *
<del> * @var boolean
<del> */
<del> public static $return = false;
<del>
<del>/**
<del> * Holds key/value pairs of $type => file path.
<del> *
<del> * @var array
<del> */
<del> protected static $_map = array();
<del>
<ide> /**
<ide> * Holds and key => value array of object types.
<ide> *
<ide> * @var array
<ide> */
<ide> protected static $_objects = array();
<ide>
<del>/**
<del> * Holds the location of each class
<del> *
<del> * @var array
<del> */
<del> protected static $_classMap = array();
<del>
<ide> /**
<ide> * Holds the possible paths for each package name
<ide> *
<ide> class App {
<ide> */
<ide> protected static $_packageFormat = array();
<ide>
<del>/**
<del> * Indicates whether the class cache should be stored again because of an addition to it
<del> *
<del> * @var boolean
<del> */
<del> protected static $_cacheChange = false;
<del>
<ide> /**
<ide> * Indicates whether the object cache should be stored again because of an addition to it
<ide> *
<ide> public static function objects($type, $path = null, $cache = true) {
<ide> return static::$_objects[$cacheLocation][$name];
<ide> }
<ide>
<del>/**
<del> * Method to handle the class loading manually, ie. Vendor classes.
<del> *
<del> * @param string $className the name of the class to load
<del> * @return boolean
<del> */
<del> public static function load($className) {
<del> if (!isset(static::$_classMap[$className])) {
<del> return false;
<del> }
<del> if (empty(static::$_map)) {
<del> static::$_map = (array)Cache::read('file_map', '_cake_core_');
<del> }
<del> if (strpos($className, '..') !== false) {
<del> return false;
<del> }
<del>
<del> $parts = explode('.', static::$_classMap[$className], 2);
<del> list($plugin, $package) = count($parts) > 1 ? $parts : array(null, current($parts));
<del>
<del> $file = static::_mapped($className, $plugin);
<del> if ($file) {
<del> return include $file;
<del> }
<del> $paths = static::path($package, $plugin);
<del>
<del> if (empty($plugin)) {
<del> $appLibs = empty(static::$_packages['Lib']) ? APPLIBS : current(static::$_packages['Lib']);
<del> $paths[] = $appLibs . $package . DS;
<del> $paths[] = APP . $package . DS;
<del> $paths[] = CAKE . $package . DS;
<del> } else {
<del> $pluginPath = static::pluginPath($plugin);
<del> $paths[] = $pluginPath . 'Lib' . DS . $package . DS;
<del> $paths[] = $pluginPath . $package . DS;
<del> }
<del>
<del> $normalizedClassName = str_replace('\\', DS, $className);
<del> foreach ($paths as $path) {
<del> $file = $path . $normalizedClassName . '.php';
<del> if (file_exists($file)) {
<del> static::_map($file, $className, $plugin);
<del> return include $file;
<del> }
<del> }
<del>
<del> return false;
<del> }
<del>
<ide> /**
<ide> * Initializes the App, registers a shutdown function.
<ide> *
<ide> public static function init() {
<ide> register_shutdown_function(array(get_called_class(), 'shutdown'));
<ide> }
<ide>
<del>/**
<del> * Maps the $name to the $file.
<del> *
<del> * @param string $file full path to file
<del> * @param string $name unique name for this map
<del> * @param string $plugin camelized if object is from a plugin, the name of the plugin
<del> * @return void
<del> */
<del> protected static function _map($file, $name, $plugin = null) {
<del> $key = $name;
<del> if ($plugin) {
<del> $key = 'plugin.' . $name;
<del> }
<del> if ($plugin && empty(static::$_map[$name])) {
<del> static::$_map[$key] = $file;
<del> }
<del> if (!$plugin && empty(static::$_map['plugin.' . $name])) {
<del> static::$_map[$key] = $file;
<del> }
<del> }
<del>
<del>/**
<del> * Returns a file's complete path.
<del> *
<del> * @param string $name unique name
<del> * @param string $plugin camelized if object is from a plugin, the name of the plugin
<del> * @return mixed file path if found, false otherwise
<del> */
<del> protected static function _mapped($name, $plugin = null) {
<del> $key = $name;
<del> if ($plugin) {
<del> $key = 'plugin.' . $name;
<del> }
<del> return isset(static::$_map[$key]) ? static::$_map[$key] : false;
<del> }
<del>
<ide> /**
<ide> * Sets then returns the templates for each customizable package path
<ide> *
<ide> protected static function _packageFormat() {
<ide> * @return void
<ide> */
<ide> public static function shutdown() {
<del> if (static::$_cacheChange) {
<del> Cache::write('file_map', array_filter(static::$_map), '_cake_core_');
<del> }
<ide> if (static::$_objectCacheChange) {
<ide> Cache::write('object_map', static::$_objects, '_cake_core_');
<ide> }
| 1
|
PHP
|
PHP
|
allow code highligthing in generated api
|
eea4bcbb7b65c54b4b12c8270bae9ab4160c520f
|
<ide><path>src/Auth/DigestAuthenticate.php
<ide> * DigestAuthenticate requires a special password hash that conforms to RFC2617.
<ide> * You can generate this password using `DigestAuthenticate::password()`
<ide> *
<del> * `$digestPass = DigestAuthenticate::password($username, $password, env('SERVER_NAME'));`
<add> * ```
<add> * $digestPass = DigestAuthenticate::password($username, $password, env('SERVER_NAME'));
<add> * ```
<ide> *
<ide> * If you wish to use digest authentication alongside other authentication methods,
<ide> * it's recommended that you store the digest authentication separately. For
<ide><path>src/Cache/Cache.php
<ide> public static function gc($config = 'default', $expires = null)
<ide> *
<ide> * Writing to the active cache config:
<ide> *
<del> * `Cache::write('cached_data', $data);`
<add> * ```
<add> * Cache::write('cached_data', $data);
<add> * ```
<ide> *
<ide> * Writing to a specific cache config:
<ide> *
<del> * `Cache::write('cached_data', $data, 'long_term');`
<add> * ```
<add> * Cache::write('cached_data', $data, 'long_term');
<add> * ```
<ide> *
<ide> * @param string $key Identifier for the data
<ide> * @param mixed $value Data to be cached - anything except a resource
<ide> public static function write($key, $value, $config = 'default')
<ide> *
<ide> * Writing to the active cache config:
<ide> *
<del> * `Cache::writeMany(['cached_data_1' => 'data 1', 'cached_data_2' => 'data 2']);`
<add> * ```
<add> * Cache::writeMany(['cached_data_1' => 'data 1', 'cached_data_2' => 'data 2']);
<add> * ```
<ide> *
<ide> * Writing to a specific cache config:
<ide> *
<del> * `Cache::writeMany(['cached_data_1' => 'data 1', 'cached_data_2' => 'data 2'], 'long_term');`
<add> * ```
<add> * Cache::writeMany(['cached_data_1' => 'data 1', 'cached_data_2' => 'data 2'], 'long_term');
<add> * ```
<ide> *
<ide> * @param array $data An array of data to be stored in the cache
<ide> * @param string $config Optional string configuration name to write to. Defaults to 'default'
<ide> public static function writeMany($data, $config = 'default')
<ide> *
<ide> * Reading from the active cache configuration.
<ide> *
<del> * `Cache::read('my_data');`
<add> * ```
<add> * Cache::read('my_data');
<add> * ```
<ide> *
<ide> * Reading from a specific cache configuration.
<ide> *
<del> * `Cache::read('my_data', 'long_term');`
<add> * ```
<add> * Cache::read('my_data', 'long_term');
<add> * ```
<ide> *
<ide> * @param string $key Identifier for the data
<ide> * @param string $config optional name of the configuration to use. Defaults to 'default'
<ide> public static function read($key, $config = 'default')
<ide> *
<ide> * Reading multiple keys from the active cache configuration.
<ide> *
<del> * `Cache::readMany(['my_data_1', 'my_data_2]);`
<add> * ```
<add> * Cache::readMany(['my_data_1', 'my_data_2]);
<add> * ```
<ide> *
<ide> * Reading from a specific cache configuration.
<ide> *
<del> * `Cache::readMany(['my_data_1', 'my_data_2], 'long_term');`
<add> * ```
<add> * Cache::readMany(['my_data_1', 'my_data_2], 'long_term');
<add> * ```
<ide> *
<ide> * @param array $keys an array of keys to fetch from the cache
<ide> * @param string $config optional name of the configuration to use. Defaults to 'default'
<ide> public static function decrement($key, $offset = 1, $config = 'default')
<ide> *
<ide> * Deleting from the active cache configuration.
<ide> *
<del> * `Cache::delete('my_data');`
<add> * ```
<add> * Cache::delete('my_data');
<add> * ```
<ide> *
<ide> * Deleting from a specific cache configuration.
<ide> *
<del> * `Cache::delete('my_data', 'long_term');`
<add> * ```
<add> * Cache::delete('my_data', 'long_term');
<add> * ```
<ide> *
<ide> * @param string $key Identifier for the data
<ide> * @param string $config name of the configuration to use. Defaults to 'default'
<ide> public static function delete($key, $config = 'default')
<ide> *
<ide> * Deleting multiple keys from the active cache configuration.
<ide> *
<del> * `Cache::deleteMany(['my_data_1', 'my_data_2']);`
<add> * ```
<add> * Cache::deleteMany(['my_data_1', 'my_data_2']);
<add> * ```
<ide> *
<ide> * Deleting from a specific cache configuration.
<ide> *
<del> * `Cache::deleteMany(['my_data_1', 'my_data_2], 'long_term');`
<add> * ```
<add> * Cache::deleteMany(['my_data_1', 'my_data_2], 'long_term');
<add> * ```
<ide> *
<ide> * @param array $keys Array of cache keys to be deleted
<ide> * @param string $config name of the configuration to use. Defaults to 'default'
<ide><path>src/Console/ConsoleOptionParser.php
<ide> * arguments any arguments greater than those defined will cause exceptions. Additionally you can
<ide> * declare arguments as optional, by setting the required param to false.
<ide> *
<del> * `$parser->addArgument('model', ['required' => false]);`
<add> * ```
<add> * $parser->addArgument('model', ['required' => false]);
<add> * ```
<ide> *
<ide> * ### Providing Help text
<ide> *
<ide><path>src/Console/ConsoleOutput.php
<ide> *
<ide> * You can format console output using tags with the name of the style to apply. From inside a shell object
<ide> *
<del> * `$this->out('<warning>Overwrite:</warning> foo.php was overwritten.');`
<add> * ```
<add> * $this->out('<warning>Overwrite:</warning> foo.php was overwritten.');
<add> * ```
<ide> *
<ide> * This would create orange 'Overwrite:' text, while the rest of the text would remain the normal color.
<ide> * See ConsoleOutput::styles() to learn more about defining your own styles. Nested styles are not supported
<ide> protected function _write($message)
<ide> *
<ide> * ### Get a style definition
<ide> *
<del> * `$output->styles('error');`
<add> * ```
<add> * $output->styles('error');
<add> * ```
<ide> *
<ide> * ### Get all the style definitions
<ide> *
<del> * `$output->styles();`
<add> * ```
<add> * $output->styles();
<add> * ```
<ide> *
<ide> * ### Create or modify an existing style
<ide> *
<del> * `$output->styles('annoy', ['text' => 'purple', 'background' => 'yellow', 'blink' => true]);`
<add> * ```
<add> * $output->styles('annoy', ['text' => 'purple', 'background' => 'yellow', 'blink' => true]);
<add> * ```
<ide> *
<ide> * ### Remove a style
<ide> *
<del> * `$this->output->styles('annoy', false);`
<add> * ```
<add> * $this->output->styles('annoy', false);
<add> * ```
<ide> *
<ide> * @param string|null $style The style to get or create.
<ide> * @param array|bool|null $definition The array definition of the style to change or create a style
<ide><path>src/Console/Shell.php
<ide> public function hasMethod($name)
<ide> *
<ide> * With a string command:
<ide> *
<del> * `return $this->dispatchShell('schema create DbAcl');`
<add> * ```
<add> * return $this->dispatchShell('schema create DbAcl');
<add> * ```
<ide> *
<ide> * Avoid using this form if you have string arguments, with spaces in them.
<ide> * The dispatched will be invoked incorrectly. Only use this form for simple
<ide> * command dispatching.
<ide> *
<ide> * With an array command:
<ide> *
<del> * `return $this->dispatchShell('schema', 'create', 'i18n', '--dry');`
<add> * ```
<add> * return $this->dispatchShell('schema', 'create', 'i18n', '--dry');
<add> * ```
<ide> *
<ide> * @return mixed The return of the other shell.
<ide> * @link http://book.cakephp.org/3.0/en/console-and-shells.html#invoking-other-shells-from-your-shell
<ide><path>src/Console/ShellDispatcher.php
<ide> public function __construct($args = [], $bootstrap = true)
<ide> *
<ide> * Aliasing a shell named ClassName:
<ide> *
<del> * `$this->alias('alias', 'ClassName');`
<add> * ```
<add> * $this->alias('alias', 'ClassName');
<add> * ```
<ide> *
<ide> * Getting the original name for a given alias:
<ide> *
<del> * `$this->alias('alias');`
<add> * ```
<add> * $this->alias('alias');
<add> * ```
<ide> *
<ide> * @param string $short The new short name for the shell.
<ide> * @param string|null $original The original full name for the shell.
<ide><path>src/Controller/Component/AuthComponent.php
<ide> public function getAuthorize($alias)
<ide> *
<ide> * You can use allow with either an array or a simple string.
<ide> *
<del> * `$this->Auth->allow('view');`
<del> * `$this->Auth->allow(['edit', 'add']);`
<del> * `$this->Auth->allow();` to allow all actions
<add> * ```
<add> * $this->Auth->allow('view');
<add> * $this->Auth->allow(['edit', 'add']);
<add> * ```
<add> * or to allow all actions
<add> * ```
<add> * $this->Auth->allow();
<add> * ```
<ide> *
<ide> * @param string|array $actions Controller action name or array of actions
<ide> * @return void
<ide> public function allow($actions = null)
<ide> *
<ide> * You can use deny with either an array or a simple string.
<ide> *
<del> * `$this->Auth->deny('view');`
<del> * `$this->Auth->deny(['edit', 'add']);`
<del> * `$this->Auth->deny();` to remove all items from the allowed list
<add> * ```
<add> * $this->Auth->deny('view');
<add> * $this->Auth->deny(['edit', 'add']);
<add> * ```
<add> * or
<add> * ```
<add> * $this->Auth->deny();
<add> * ```
<add> * to remove all items from the allowed list
<ide> *
<ide> * @param string|array $actions Controller action name or array of actions
<ide> * @return void
<ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> public function isWap()
<ide> *
<ide> * Usage:
<ide> *
<del> * `$this->RequestHandler->accepts(['xml', 'html', 'json']);`
<add> * ```
<add> * $this->RequestHandler->accepts(['xml', 'html', 'json']);
<add> * ```
<ide> *
<ide> * Returns true if the client accepts any of the supplied types.
<ide> *
<del> * `$this->RequestHandler->accepts('xml');`
<add> * ```
<add> * $this->RequestHandler->accepts('xml');
<add> * ```
<ide> *
<ide> * Returns true if the client accepts xml.
<ide> *
<ide> public function prefers($type = null)
<ide> *
<ide> * Render the response as an 'ajax' response.
<ide> *
<del> * `$this->RequestHandler->renderAs($this, 'ajax');`
<add> * ```
<add> * $this->RequestHandler->renderAs($this, 'ajax');
<add> * ```
<ide> *
<ide> * Render the response as an xml file and force the result as a file download.
<ide> *
<del> * `$this->RequestHandler->renderAs($this, 'xml', ['attachment' => 'myfile.xml'];`
<add> * ```
<add> * $this->RequestHandler->renderAs($this, 'xml', ['attachment' => 'myfile.xml'];
<add> * ```
<ide> *
<ide> * @param Controller $controller A reference to a controller object
<ide> * @param string $type Type of response to send (e.g: 'ajax')
<ide><path>src/Controller/Controller.php
<ide> class Controller implements EventListenerInterface
<ide> * An array containing the names of helpers this controller uses. The array elements should
<ide> * not contain the "Helper" part of the class name.
<ide> *
<del> * Example: `public $helpers = ['Form', 'Html', 'Time'];`
<add> * Example:
<add> * ```
<add> * public $helpers = ['Form', 'Html', 'Time'];
<add> * ```
<ide> *
<ide> * @var mixed
<ide> * @link http://book.cakephp.org/3.0/en/controllers.html#configuring-helpers-to-load
<ide> class Controller implements EventListenerInterface
<ide> * Array containing the names of components this controller uses. Component names
<ide> * should not contain the "Component" portion of the class name.
<ide> *
<del> * Example: `public $components = ['RequestHandler', 'Acl'];`
<add> * Example:
<add> * ```
<add> * public $components = ['RequestHandler', 'Acl'];
<add> * ```
<ide> *
<ide> * @var array
<ide> * @link http://book.cakephp.org/3.0/en/controllers/components.html
<ide> public function components()
<ide> * This method will also set the component to a property.
<ide> * For example:
<ide> *
<del> * `$this->loadComponent('Acl.Acl');`
<add> * ```
<add> * $this->loadComponent('Acl.Acl');
<add> * ```
<ide> *
<ide> * Will result in a `Toolbar` property being set.
<ide> *
<ide><path>src/Core/App.php
<ide> protected static function _classExistsInBase($name, $namespace)
<ide> *
<ide> * Usage:
<ide> *
<del> * `App::path('Plugin');`
<add> * ```
<add> * App::path('Plugin');
<add> * ```
<ide> *
<ide> * Will return the configured paths for plugins. This is a simpler way to access
<ide> * the `App.paths.plugins` configure variable.
<ide> *
<del> * `App::path('Model/Datasource', 'MyPlugin');`
<add> * ```
<add> * App::path('Model/Datasource', 'MyPlugin');
<add> * ```
<ide> *
<ide> * Will return the path for datasources under the 'MyPlugin' plugin.
<ide> *
<ide> public static function path($type, $plugin = null)
<ide> *
<ide> * Usage:
<ide> *
<del> * `App::core('Cache/Engine');`
<add> * ```
<add> * App::core('Cache/Engine');
<add> * ```
<ide> *
<ide> * Will return the full path to the cache engines package.
<ide> *
<ide><path>src/Core/Configure.php
<ide> public static function consume($var)
<ide> *
<ide> * To add a new engine to Configure:
<ide> *
<del> * `Configure::config('ini', new IniConfig());`
<add> * ```
<add> * Configure::config('ini', new IniConfig());
<add> * ```
<ide> *
<ide> * @param string $name The name of the engine being configured. This alias is used later to
<ide> * read values from a specific engine.
<ide> public static function drop($name)
<ide> * Would load the 'user' config file using the default config engine. You can load
<ide> * app config files by giving the name of the resource you want loaded.
<ide> *
<del> * `Configure::load('setup', 'default');`
<add> * ```
<add> * Configure::load('setup', 'default');
<add> * ```
<ide> *
<ide> * If using `default` config and no engine has been configured for it yet,
<ide> * one will be automatically created using PhpConfig
<ide> public static function load($key, $config = 'default', $merge = true)
<ide> * Given that the 'default' engine is an instance of PhpConfig.
<ide> * Save all data in Configure to the file `my_config.php`:
<ide> *
<del> * `Configure::dump('my_config', 'default');`
<add> * ```
<add> * Configure::dump('my_config', 'default');
<add> * ```
<ide> *
<ide> * Save only the error handling configuration:
<ide> *
<del> * `Configure::dump('error', 'default', ['Error', 'Exception'];`
<add> * ```
<add> * Configure::dump('error', 'default', ['Error', 'Exception'];
<add> * ```
<ide> *
<ide> * @param string $key The identifier to create in the config adapter.
<ide> * This could be a filename or a cache key depending on the adapter being used.
<ide> protected static function _getEngine($config)
<ide> /**
<ide> * Used to determine the current version of CakePHP.
<ide> *
<del> * Usage `Configure::version();`
<add> * Usage
<add> * ```
<add> * Configure::version();
<add> * ```
<ide> *
<ide> * @return string Current version of CakePHP
<ide> */
<ide><path>src/Core/InstanceConfigTrait.php
<ide> trait InstanceConfigTrait
<ide> *
<ide> * Reading the whole config:
<ide> *
<del> * `$this->config();`
<add> * ```
<add> * $this->config();
<add> * ```
<ide> *
<ide> * Reading a specific value:
<ide> *
<del> * `$this->config('key');`
<add> * ```
<add> * $this->config('key');
<add> * ```
<ide> *
<ide> * Reading a nested value:
<ide> *
<del> * `$this->config('some.nested.key');`
<add> * ```
<add> * $this->config('some.nested.key');
<add> * ```
<ide> *
<ide> * Setting a specific value:
<ide> *
<del> * `$this->config('key', $value);`
<add> * ```
<add> * $this->config('key', $value);
<add> * ```
<ide> *
<ide> * Setting a nested value:
<ide> *
<del> * `$this->config('some.nested.key', $value);`
<add> * ```
<add> * $this->config('some.nested.key', $value);
<add> * ```
<ide> *
<ide> * Updating multiple config settings at the same time:
<ide> *
<del> * `$this->config(['one' => 'value', 'another' => 'value']);`
<add> * ```
<add> * $this->config(['one' => 'value', 'another' => 'value']);
<add> * ```
<ide> *
<ide> * @param string|array|null $key The key to get/set, or a complete array of configs.
<ide> * @param mixed|null $value The value to set.
<ide> public function config($key = null, $value = null, $merge = true)
<ide> *
<ide> * Setting a specific value:
<ide> *
<del> * `$this->config('key', $value);`
<add> * ```
<add> * $this->config('key', $value);
<add> * ```
<ide> *
<ide> * Setting a nested value:
<ide> *
<del> * `$this->config('some.nested.key', $value);`
<add> * ```
<add> * $this->config('some.nested.key', $value);
<add> * ```
<ide> *
<ide> * Updating multiple config settings at the same time:
<ide> *
<del> * `$this->config(['one' => 'value', 'another' => 'value']);`
<add> * ```
<add> * $this->config(['one' => 'value', 'another' => 'value']);
<add> * ```
<ide> *
<ide> * @param string|array $key The key to set, or a complete array of configs.
<ide> * @param mixed|null $value The value to set.
<ide><path>src/Core/StaticConfigTrait.php
<ide> trait StaticConfigTrait
<ide> *
<ide> * Reading config data back:
<ide> *
<del> * `Cache::config('default');`
<add> * ```
<add> * Cache::config('default');
<add> * ```
<ide> *
<ide> * Setting a cache engine up.
<ide> *
<del> * `Cache::config('default', $settings);`
<add> * ```
<add> * Cache::config('default', $settings);
<add> * ```
<ide> *
<ide> * Injecting a constructed adapter in:
<ide> *
<del> * `Cache::config('default', $instance);`
<add> * ```
<add> * Cache::config('default', $instance);
<add> * ```
<ide> *
<ide> * Configure multiple adapters at once:
<ide> *
<del> * `Cache::config($arrayOfConfig);`
<add> * ```
<add> * Cache::config($arrayOfConfig);
<add> * ```
<ide> *
<ide> * @param string|array $key The name of the configuration, or an array of multiple configs.
<ide> * @param array $config An array of name => configuration data for adapter.
<ide><path>src/Core/functions.php
<ide> function h($text, $double = true, $charset = null)
<ide> * Splits a dot syntax plugin name into its plugin and class name.
<ide> * If $name does not have a dot, then index 0 will be null.
<ide> *
<del> * Commonly used like `list($plugin, $name) = pluginSplit($name);`
<add> * Commonly used like
<add> * ```
<add> * list($plugin, $name) = pluginSplit($name);
<add> * ```
<ide> *
<ide> * @param string $name The name you want to plugin split.
<ide> * @param bool $dotAppend Set to true if you want the plugin to have a '.' appended to it.
<ide><path>src/Database/StatementInterface.php
<ide> interface StatementInterface
<ide> *
<ide> * ### Examples:
<ide> *
<del> * `$statement->bindValue(1, 'a title');`
<del> * `$statement->bindValue('active', true, 'boolean');`
<del> * `$statement->bindValue(5, new \DateTime(), 'date');`
<add> * ```
<add> * $statement->bindValue(1, 'a title');
<add> * $statement->bindValue('active', true, 'boolean');
<add> * $statement->bindValue(5, new \DateTime(), 'date');
<add> * ```
<ide> *
<ide> * @param string|int $column name or param position to be bound
<ide> * @param mixed $value The value to bind to variable in query
<ide><path>src/Datasource/EntityTrait.php
<ide> trait EntityTrait
<ide> * property name points to a boolean indicating its status. An empty array
<ide> * means no properties are accessible
<ide> *
<del> * The special property '*' can also be mapped, meaning that any other property
<del> * not defined in the map will take its value. For example, `'*' => true`
<add> * The special property '\*' can also be mapped, meaning that any other property
<add> * not defined in the map will take its value. For example, `'\*' => true`
<ide> * means that any property not defined in the map will be accessible by default
<ide> *
<ide> * @var array
<ide><path>src/Datasource/QueryTrait.php
<ide> public function formatResults(callable $formatter = null, $mode = 0)
<ide> *
<ide> * ### Example:
<ide> *
<del> * `$singleUser = $query->select(['id', 'username'])->first();`
<add> * ```
<add> * $singleUser = $query->select(['id', 'username'])->first();
<add> * ```
<ide> *
<ide> * @return mixed the first result from the ResultSet
<ide> */
<ide><path>src/Error/Debugger.php
<ide> public static function trimPath($path)
<ide> *
<ide> * Usage:
<ide> *
<del> * `Debugger::excerpt('/path/to/file', 100, 4);`
<add> * ```
<add> * Debugger::excerpt('/path/to/file', 100, 4);
<add> * ```
<ide> *
<ide> * The above would return an array of 8 items. The 4th item would be the provided line,
<ide> * and would be wrapped in `<span class="code-highlight"></span>`. All of the lines
<ide> public static function outputAs($format = null)
<ide> /**
<ide> * Add an output format or update a format in Debugger.
<ide> *
<del> * `Debugger::addFormat('custom', $data);`
<add> * ```
<add> * Debugger::addFormat('custom', $data);
<add> * ```
<ide> *
<ide> * Where $data is an array of strings that use Text::insert() variable
<ide> * replacement. The template vars should be in a `{:id}` style.
<ide> public static function outputAs($format = null)
<ide> * Alternatively if you want to use a custom callback to do all the formatting, you can use
<ide> * the callback key, and provide a callable:
<ide> *
<del> * `Debugger::addFormat('custom', ['callback' => [$foo, 'outputError']];`
<add> * ```
<add> * Debugger::addFormat('custom', ['callback' => [$foo, 'outputError']];
<add> * ```
<ide> *
<ide> * The callback can expect two parameters. The first is an array of all
<ide> * the error data. The second contains the formatted strings generated using
<ide><path>src/Error/ErrorHandler.php
<ide> * You can control which errors are logged / displayed by ErrorHandler by setting `errorLevel`. Setting this
<ide> * to one or a combination of a few of the E_* constants will only enable the specified errors:
<ide> *
<del> * `$options['errorLevel'] = E_ALL & ~E_NOTICE;`
<add> * ```
<add> * $options['errorLevel'] = E_ALL & ~E_NOTICE;
<add> * ```
<ide> *
<ide> * Would enable handling for all non Notice errors.
<ide> *
<ide><path>src/Log/Log.php
<ide> public static function levels()
<ide> *
<ide> * Reading config data back:
<ide> *
<del> * `Log::config('default');`
<add> * ```
<add> * Log::config('default');
<add> * ```
<ide> *
<ide> * Setting a cache engine up.
<ide> *
<del> * `Log::config('default', $settings);`
<add> * ```
<add> * Log::config('default', $settings);
<add> * ```
<ide> *
<ide> * Injecting a constructed adapter in:
<ide> *
<del> * `Log::config('default', $instance);`
<add> * ```
<add> * Log::config('default', $instance);
<add> * ```
<ide> *
<ide> * Using a factory function to get an adapter:
<ide> *
<del> * `Log::config('default', function () { return new FileLog(); });`
<add> * ```
<add> * Log::config('default', function () { return new FileLog(); });
<add> * ```
<ide> *
<ide> * Configure multiple adapters at once:
<ide> *
<del> * `Log::config($arrayOfConfig);`
<add> * ```
<add> * Log::config($arrayOfConfig);
<add> * ```
<ide> *
<ide> * @param string|array $key The name of the logger config, or an array of multiple configs.
<ide> * @param array|null $config An array of name => config data for adapter.
<ide> public static function engine($name)
<ide> *
<ide> * Write a 'warning' message to the logs:
<ide> *
<del> * `Log::write('warning', 'Stuff is broken here');`
<add> * ```
<add> * Log::write('warning', 'Stuff is broken here');
<add> * ```
<ide> *
<ide> * ### Using scopes
<ide> *
<ide> * When writing a log message you can define one or many scopes for the message.
<ide> * This allows you to handle messages differently based on application section/feature.
<ide> *
<del> * `Log::write('warning', 'Payment failed', ['scope' => 'payment']);`
<add> * ```
<add> * Log::write('warning', 'Payment failed', ['scope' => 'payment']);
<add> * ```
<ide> *
<ide> * When configuring loggers you can configure the scopes a particular logger will handle.
<ide> * When using scopes, you must ensure that the level of the message, and the scope of the message
<ide><path>src/Network/Http/Client.php
<ide> * When sending request bodies you can use the `type` option to
<ide> * set the Content-Type for the request:
<ide> *
<del> * `$http->get('/users', [], ['type' => 'json']);`
<add> * ```
<add> * $http->get('/users', [], ['type' => 'json']);
<add> * ```
<ide> *
<ide> * The `type` option sets both the `Content-Type` and `Accept` header, to
<ide> * the same mime type. When using `type` you can use either a full mime
<ide><path>src/Network/Http/Request.php
<ide> public function url($url = null)
<ide> *
<ide> * ### Getting headers
<ide> *
<del> * `$request->header('Content-Type');`
<add> * ```
<add> * $request->header('Content-Type');
<add> * ```
<ide> *
<ide> * ### Setting one header
<ide> *
<del> * `$request->header('Content-Type', 'application/json');`
<add> * ```
<add> * $request->header('Content-Type', 'application/json');
<add> * ```
<ide> *
<ide> * ### Setting multiple headers
<ide> *
<del> * `$request->header(['Connection' => 'close', 'User-Agent' => 'CakePHP']);`
<add> * ```
<add> * $request->header(['Connection' => 'close', 'User-Agent' => 'CakePHP']);
<add> * ```
<ide> *
<ide> * @param string|array|null $name The name to get, or array of multiple values to set.
<ide> * @param string|null $value The value to set for the header.
<ide> public function header($name = null, $value = null)
<ide> *
<ide> * ### Getting a cookie
<ide> *
<del> * `$request->cookie('session');`
<add> * ```
<add> * $request->cookie('session');
<add> * ```
<ide> *
<ide> * ### Setting one cookie
<ide> *
<del> * `$request->cookie('session', '123456');`
<add> * ```
<add> * $request->cookie('session', '123456');
<add> * ```
<ide> *
<ide> * ### Setting multiple headers
<ide> *
<del> * `$request->cookie(['test' => 'value', 'split' => 'banana']);`
<add> * ```
<add> * $request->cookie(['test' => 'value', 'split' => 'banana']);
<add> * ```
<ide> *
<ide> * @param string $name The name of the cookie to get/set
<ide> * @param string|null $value Either the value or null when getting values.
<ide><path>src/Network/Http/Response.php
<ide> * Header names are case-insensitive, but normalized to Title-Case
<ide> * when the response is parsed.
<ide> *
<del> * `$val = $response->header('content-type');`
<add> * ```
<add> * $val = $response->header('content-type');
<add> * ```
<ide> *
<ide> * Will read the Content-Type header. You can get all set
<ide> * headers using:
<ide> *
<del> * `$response->header();`
<add> * ```
<add> * $response->header();
<add> * ```
<ide> *
<ide> * You can also get at the headers using object access. When getting
<ide> * headers with object access, you have to use case-sensitive header
<ide> * names:
<ide> *
<del> * `$val = $response->headers['Content-Type'];`
<add> * ```
<add> * $val = $response->headers['Content-Type'];
<add> * ```
<ide> *
<ide> * ### Get the response body
<ide> *
<ide> * You can access the response body using:
<ide> *
<del> * `$content = $response->body();`
<add> * ```
<add> * $content = $response->body();
<add> * ```
<ide> *
<ide> * You can also use object access:
<ide> *
<del> * `$content = $response->body;`
<add> * ```
<add> * $content = $response->body;
<add> * ```
<ide> *
<ide> * If your response body is in XML or JSON you can use
<ide> * special content type specific accessors to read the decoded data.
<ide> *
<ide> * You can access the response status code using:
<ide> *
<del> * `$content = $response->statusCode();`
<add> * ```
<add> * $content = $response->statusCode();
<add> * ```
<ide> *
<ide> * You can also use object access:
<ide> *
<del> * `$content = $response->code;`
<add> * ```
<add> * $content = $response->code;
<add> * ```
<ide> */
<ide> class Response extends Message
<ide> {
<ide> public function cookie($name = null, $all = false)
<ide> *
<ide> * For example to get the json data as an object:
<ide> *
<del> * `$body = $response->body('json_decode');`
<add> * ```
<add> * $body = $response->body('json_decode');
<add> * ```
<ide> *
<ide> * @param callable|null $parser The callback to use to decode
<ide> * the response body.
<ide><path>src/Network/Request.php
<ide> public function isAll(array $types)
<ide> * Callback detectors allow you to provide a callable to handle the check.
<ide> * The callback will receive the request object as its only parameter.
<ide> *
<del> * e.g `addDetector('custom', function ($request) { //Return a boolean });`
<del> * e.g `addDetector('custom', ['SomeClass', 'somemethod']);`
<add> * ```
<add> * addDetector('custom', function ($request) { //Return a boolean });
<add> * addDetector('custom', ['SomeClass', 'somemethod']);
<add> * ```
<ide> *
<ide> * ### Environment value comparison
<ide> *
<ide> public function isAll(array $types)
<ide> *
<ide> * Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
<ide> *
<del> * e.g `addDetector('iphone', ['env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i']);`
<add> * ```
<add> * addDetector('iphone', ['env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i']);
<add> * ```
<ide> *
<ide> * ### Option based comparison
<ide> *
<ide> * Option based comparisons use a list of options to create a regular expression. Subsequent calls
<ide> * to add an already defined options detector will merge the options.
<ide> *
<del> * e.g `addDetector('mobile', ['env' => 'HTTP_USER_AGENT', 'options' => ['Fennec']]);`
<add> * ```
<add> * addDetector('mobile', ['env' => 'HTTP_USER_AGENT', 'options' => ['Fennec']]);
<add> * ```
<ide> *
<ide> * ### Request parameter detectors
<ide> *
<ide> public function subdomains($tldLength = 1)
<ide> *
<ide> * #### Get all types:
<ide> *
<del> * `$this->request->accepts();`
<add> * ```
<add> * $this->request->accepts();
<add> * ```
<ide> *
<ide> * #### Check for a single type:
<ide> *
<del> * `$this->request->accepts('application/json');`
<add> * ```
<add> * $this->request->accepts('application/json');
<add> * ```
<ide> *
<ide> * This method will order the returned content types by the preference values indicated
<ide> * by the client.
<ide> public function query($name)
<ide> *
<ide> * ### Reading values.
<ide> *
<del> * `$request->data('Post.title');`
<add> * ```
<add> * $request->data('Post.title');
<add> * ```
<ide> *
<ide> * When reading values you will get `null` for keys/values that do not exist.
<ide> *
<ide> * ### Writing values
<ide> *
<del> * `$request->data('Post.title', 'New post!');`
<add> * ```
<add> * $request->data('Post.title', 'New post!');
<add> * ```
<ide> *
<ide> * You can write to any value, even paths/keys that do not exist, and the arrays
<ide> * will be created for you.
<ide> public function param($name)
<ide> *
<ide> * Getting input with a decoding function:
<ide> *
<del> * `$this->request->input('json_decode');`
<add> * ```
<add> * $this->request->input('json_decode');
<add> * ```
<ide> *
<ide> * Getting input using a decoding function, and additional params:
<ide> *
<del> * `$this->request->input('Xml::build', ['return' => 'DOMDocument']);`
<add> * ```
<add> * $this->request->input('Xml::build', ['return' => 'DOMDocument']);
<add> * ```
<ide> *
<ide> * Any additional parameters are applied to the callback in the order they are given.
<ide> *
<ide><path>src/Network/Response.php
<ide> protected function _sendContent($content)
<ide> * Returns the complete list of buffered headers
<ide> *
<ide> * ### Single header
<del> * e.g `header('Location', 'http://example.com');`
<add> * ```
<add> * header('Location', 'http://example.com');
<add> * ```
<ide> *
<ide> * ### Multiple headers
<del> * e.g `header(['Location' => 'http://example.com', 'X-Extra' => 'My header']);`
<add> * ```
<add> * header(['Location' => 'http://example.com', 'X-Extra' => 'My header']);
<add> * ```
<ide> *
<ide> * ### String header
<del> * e.g `header('WWW-Authenticate: Negotiate');`
<add> * ```
<add> * header('WWW-Authenticate: Negotiate');
<add> * ```
<ide> *
<ide> * ### Array of string headers
<del> * e.g `header(['WWW-Authenticate: Negotiate', 'Content-type: application/pdf']);`
<add> * ```
<add> * header(['WWW-Authenticate: Negotiate', 'Content-type: application/pdf']);
<add> * ```
<ide> *
<ide> * Multiple calls for setting the same header name will have the same effect as setting the header once
<ide> * with the last value sent for it
<del> * e.g `header('WWW-Authenticate: Negotiate'); header('WWW-Authenticate: Not-Negotiate');`
<del> * will have the same effect as only doing `header('WWW-Authenticate: Not-Negotiate');`
<add> * ```
<add> * header('WWW-Authenticate: Negotiate');
<add> * header('WWW-Authenticate: Not-Negotiate');
<add> * ```
<add> * will have the same effect as only doing
<add> * ```
<add> * header('WWW-Authenticate: Not-Negotiate');
<add> * ```
<ide> *
<ide> * @param string|array|null $header An array of header strings or a single header string
<ide> * - an associative array of "header name" => "header value" is also accepted
<ide> public function httpCodes($code = null)
<ide> *
<ide> * ### Setting the content type
<ide> *
<del> * e.g `type('jpg');`
<add> * ```
<add> * type('jpg');
<add> * ```
<ide> *
<ide> * ### Returning the current content type
<ide> *
<del> * e.g `type();`
<add> * ```
<add> * type();
<add> * ```
<ide> *
<ide> * ### Storing content type definitions
<ide> *
<del> * e.g `type(['keynote' => 'application/keynote', 'bat' => 'application/bat']);`
<add> * ```
<add> * type(['keynote' => 'application/keynote', 'bat' => 'application/bat']);
<add> * ```
<ide> *
<ide> * ### Replacing a content type definition
<ide> *
<del> * e.g `type(['jpg' => 'text/plain']);`
<add> * ```
<add> * type(['jpg' => 'text/plain']);
<add> * ```
<ide> *
<ide> * @param string|null $contentType Content type key.
<ide> * @return mixed Current content type or false if supplied an invalid content type
<ide> public function cookie($options = null)
<ide> * This method allow multiple ways to setup the domains, see the examples
<ide> *
<ide> * ### Full URI
<del> * e.g `cors($request, 'http://www.cakephp.org');`
<add> * ```
<add> * cors($request, 'http://www.cakephp.org');
<add> * ```
<ide> *
<ide> * ### URI with wildcard
<del> * e.g `cors($request, 'http://*.cakephp.org');`
<add> * ```
<add> * cors($request, 'http://*.cakephp.org');
<add> * ```
<ide> *
<ide> * ### Ignoring the requested protocol
<del> * e.g `cors($request, 'www.cakephp.org');`
<add> * ```
<add> * cors($request, 'www.cakephp.org');
<add> * ```
<ide> *
<ide> * ### Any URI
<del> * e.g `cors($request, '*');`
<add> * ```
<add> * cors($request, '*');
<add> * ```
<ide> *
<ide> * ### Whitelist of URIs
<del> * e.g `cors($request, ['http://www.cakephp.org', '*.google.com', 'https://myproject.github.io']);`
<add> * ```
<add> * cors($request, ['http://www.cakephp.org', '*.google.com', 'https://myproject.github.io']);
<add> * ```
<ide> *
<ide> * @param \Cake\Network\Request $request Request object
<ide> * @param string|array $allowedDomains List of allowed domains, see method description for more details
<ide><path>src/Network/Session.php
<ide> public function engine($class = null, array $options = [])
<ide> *
<ide> * ### Example:
<ide> *
<del> * `$session->options(['session.use_cookies' => 1]);`
<add> * ```
<add> * $session->options(['session.use_cookies' => 1]);
<add> * ```
<ide> *
<ide> * @param array $options Ini options to set.
<ide> * @return void
<ide><path>src/Routing/RouteBuilder.php
<ide> public function resources($name, $options = [], $callback = null)
<ide> *
<ide> * Examples:
<ide> *
<del> * `$routes->connect('/:controller/:action/*');`
<add> * ```
<add> * $routes->connect('/:controller/:action/*');
<add> * ```
<ide> *
<ide> * The first parameter will be used as a controller name while the second is
<ide> * used as the action name. The '/*' syntax makes this route greedy in that
<ide> * it will match requests like `/posts/index` as well as requests
<ide> * like `/posts/edit/1/foo/bar`.
<ide> *
<del> * `$routes->connect('/home-page', ['controller' => 'Pages', 'action' => 'display', 'home']);`
<add> * ```
<add> * $routes->connect('/home-page', ['controller' => 'Pages', 'action' => 'display', 'home']);
<add> * ```
<ide> *
<ide> * The above shows the use of route parameter defaults. And providing routing
<ide> * parameters for a static route.
<ide> public function resources($name, $options = [], $callback = null)
<ide> *
<ide> * Example of using the `_method` condition:
<ide> *
<del> * `$routes->connect('/tasks', ['controller' => 'Tasks', 'action' => 'index', '_method' => 'GET']);`
<add> * ```
<add> * $routes->connect('/tasks', ['controller' => 'Tasks', 'action' => 'index', '_method' => 'GET']);
<add> * ```
<ide> *
<ide> * The above route will only be matched for GET requests. POST requests will fail to match this route.
<ide> *
<ide> protected function _makeRoute($route, $defaults, $options)
<ide> *
<ide> * Examples:
<ide> *
<del> * `$routes->redirect('/home/*', ['controller' => 'posts', 'action' => 'view']);`
<add> * ```
<add> * $routes->redirect('/home/*', ['controller' => 'posts', 'action' => 'view']);
<add> * ```
<ide> *
<ide> * Redirects /home/* to /posts/view and passes the parameters to /posts/view. Using an array as the
<ide> * redirect destination allows you to use other routes to define where an URL string should be redirected to.
<ide> *
<del> * `$routes-redirect('/posts/*', 'http://google.com', ['status' => 302]);`
<add> * ```
<add> * $routes-redirect('/posts/*', 'http://google.com', ['status' => 302]);
<add> * ```
<ide> *
<ide> * Redirects /posts/* to http://google.com with a HTTP status of 302
<ide> *
<ide><path>src/Utility/Hash.php
<ide> public static function reduce(array $data, $path, $function)
<ide> * You can easily count the results of an extract using apply().
<ide> * For example to count the comments on an Article:
<ide> *
<del> * `$count = Hash::apply($data, 'Article.Comment.{n}', 'count');`
<add> * ```
<add> * $count = Hash::apply($data, 'Article.Comment.{n}', 'count');
<add> * ```
<ide> *
<ide> * You could also use a function like `array_sum` to sum the results.
<ide> *
<del> * `$total = Hash::apply($data, '{n}.Item.price', 'array_sum');`
<add> * ```
<add> * $total = Hash::apply($data, '{n}.Item.price', 'array_sum');
<add> * ```
<ide> *
<ide> * @param array $data The data to reduce.
<ide> * @param string $path The path to extract from $data.
<ide><path>src/Utility/Text.php
<ide> public static function tokenize($data, $separator = ',', $leftBound = '(', $righ
<ide> /**
<ide> * Replaces variable placeholders inside a $str with any given $data. Each key in the $data array
<ide> * corresponds to a variable placeholder name in $str.
<del> * Example: `Text::insert(':name is :age years old.', ['name' => 'Bob', '65']);`
<add> * Example:
<add> * ```
<add> * Text::insert(':name is :age years old.', ['name' => 'Bob', '65']);
<add> * ```
<ide> * Returns: Bob is 65 years old.
<ide> *
<ide> * Available $options are:
<ide><path>src/Utility/Xml.php
<ide> class Xml
<ide> *
<ide> * Building XML from a string:
<ide> *
<del> * `$xml = Xml::build('<example>text</example>');`
<add> * ```
<add> * $xml = Xml::build('<example>text</example>');
<add> * ```
<ide> *
<ide> * Building XML from string (output DOMDocument):
<ide> *
<del> * `$xml = Xml::build('<example>text</example>', ['return' => 'domdocument']);`
<add> * ```
<add> * $xml = Xml::build('<example>text</example>', ['return' => 'domdocument']);
<add> * ```
<ide> *
<ide> * Building XML from a file path:
<ide> *
<del> * `$xml = Xml::build('/path/to/an/xml/file.xml');`
<add> * ```
<add> * $xml = Xml::build('/path/to/an/xml/file.xml');
<add> * ```
<ide> *
<ide> * Building from a remote URL:
<ide> *
<del> * `$xml = Xml::build('http://example.com/example.xml');`
<add> * ```
<add> * $xml = Xml::build('http://example.com/example.xml');
<add> * ```
<ide> *
<ide> * Building from an array:
<ide> *
<ide><path>src/View/Helper/FormHelper.php
<ide> public function radio($fieldName, $options = [], array $attributes = [])
<ide> *
<ide> * ### Usage
<ide> *
<del> * `$this->Form->search('User.query', ['value' => 'test']);`
<add> * ```
<add> * $this->Form->search('User.query', ['value' => 'test']);
<add> * ```
<ide> *
<ide> * Will make an input like:
<ide> *
<ide><path>src/View/Helper/HtmlHelper.php
<ide> public function docType($type = 'html5')
<ide> *
<ide> * Append the meta tag to custom view block "meta":
<ide> *
<del> * `$this->Html->meta('description', 'A great page', ['block' => true]);`
<add> * ```
<add> * $this->Html->meta('description', 'A great page', ['block' => true]);
<add> * ```
<ide> *
<ide> * Append the meta tag to custom view block:
<ide> *
<del> * `$this->Html->meta('description', 'A great page', ['block' => 'metaTags']);`
<add> * ```
<add> * $this->Html->meta('description', 'A great page', ['block' => 'metaTags']);
<add> * ```
<ide> *
<ide> * Create a custom meta tag:
<ide> *
<del> * `$this->Html->meta(['property' => 'og:site_name', 'content' => 'CakePHP']);`
<add> * ```
<add> * $this->Html->meta(['property' => 'og:site_name', 'content' => 'CakePHP']);
<add> * ```
<ide> *
<ide> * ### Options
<ide> *
<ide> public function link($title, $url = null, array $options = [])
<ide> *
<ide> * Include one CSS file:
<ide> *
<del> * `echo $this->Html->css('styles.css');`
<add> * ```
<add> * echo $this->Html->css('styles.css');
<add> * ```
<ide> *
<ide> * Include multiple CSS files:
<ide> *
<del> * `echo $this->Html->css(['one.css', 'two.css']);`
<add> * ```
<add> * echo $this->Html->css(['one.css', 'two.css']);
<add> * ```
<ide> *
<ide> * Add the stylesheet to view block "css":
<ide> *
<del> * `$this->Html->css('styles.css', ['block' => true]);`
<add> * ```
<add> * $this->Html->css('styles.css', ['block' => true]);
<add> * ```
<ide> *
<ide> * Add the stylesheet to a custom block:
<ide> *
<del> * `$this->Html->css('styles.css', ['block' => 'layoutCss']);`
<add> * ```
<add> * $this->Html->css('styles.css', ['block' => 'layoutCss']);
<add> * ```
<ide> *
<ide> * ### Options
<ide> *
<ide> public function css($path, array $options = [])
<ide> *
<ide> * Include one script file:
<ide> *
<del> * `echo $this->Html->script('styles.js');`
<add> * ```
<add> * echo $this->Html->script('styles.js');
<add> * ```
<ide> *
<ide> * Include multiple script files:
<ide> *
<del> * `echo $this->Html->script(['one.js', 'two.js']);`
<add> * ```
<add> * echo $this->Html->script(['one.js', 'two.js']);
<add> * ```
<ide> *
<ide> * Add the script file to a custom block:
<ide> *
<del> * `$this->Html->script('styles.js', ['block' => 'bodyScript']);`
<add> * ```
<add> * $this->Html->script('styles.js', ['block' => 'bodyScript']);
<add> * ```
<ide> *
<ide> * ### Options
<ide> *
<ide> protected function _prepareCrumbs($startText, $escape = true)
<ide> *
<ide> * Create a regular image:
<ide> *
<del> * `echo $this->Html->image('cake_icon.png', ['alt' => 'CakePHP']);`
<add> * ```
<add> * echo $this->Html->image('cake_icon.png', ['alt' => 'CakePHP']);
<add> * ```
<ide> *
<ide> * Create an image link:
<ide> *
<del> * `echo $this->Html->image('cake_icon.png', ['alt' => 'CakePHP', 'url' => 'http://cakephp.org']);`
<add> * ```
<add> * echo $this->Html->image('cake_icon.png', ['alt' => 'CakePHP', 'url' => 'http://cakephp.org']);
<add> * ```
<ide> *
<ide> * ### Options:
<ide> *
<ide> public function para($class, $text, array $options = [])
<ide> *
<ide> * Using an audio file:
<ide> *
<del> * `echo $this->Html->media('audio.mp3', ['fullBase' => true]);`
<add> * ```
<add> * echo $this->Html->media('audio.mp3', ['fullBase' => true]);
<add> * ```
<ide> *
<ide> * Outputs:
<ide> *
<ide> * `<video src="http://www.somehost.com/files/audio.mp3">Fallback text</video>`
<ide> *
<ide> * Using a video file:
<ide> *
<del> * `echo $this->Html->media('video.mp4', ['text' => 'Fallback text']);`
<add> * ```
<add> * echo $this->Html->media('video.mp4', ['text' => 'Fallback text']);
<add> * ```
<ide> *
<ide> * Outputs:
<ide> *
<ide><path>src/View/Helper/PaginatorHelper.php
<ide> public function counter($options = [])
<ide> * Returns a set of numbers for the paged result set
<ide> * uses a modulus to decide how many numbers to show on each side of the current page (default: 8).
<ide> *
<del> * `$this->Paginator->numbers(['first' => 2, 'last' => 2]);`
<add> * ```
<add> * $this->Paginator->numbers(['first' => 2, 'last' => 2]);
<add> * ```
<ide> *
<ide> * Using the first and last options you can create links to the beginning and end of the page set.
<ide> *
<ide> protected function _numbers($templater, $params, $options)
<ide> /**
<ide> * Returns a first or set of numbers for the first pages.
<ide> *
<del> * `echo $this->Paginator->first('< first');`
<add> * ```
<add> * echo $this->Paginator->first('< first');
<add> * ```
<ide> *
<ide> * Creates a single link for the first page. Will output nothing if you are on the first page.
<ide> *
<del> * `echo $this->Paginator->first(3);`
<add> * ```
<add> * echo $this->Paginator->first(3);
<add> * ```
<ide> *
<ide> * Will create links for the first 3 pages, once you get to the third or greater page. Prior to that
<ide> * nothing will be output.
<ide> public function first($first = '<< first', array $options = [])
<ide> /**
<ide> * Returns a last or set of numbers for the last pages.
<ide> *
<del> * `echo $this->Paginator->last('last >');`
<add> * ```
<add> * echo $this->Paginator->last('last >');
<add> * ```
<ide> *
<ide> * Creates a single link for the last page. Will output nothing if you are on the last page.
<ide> *
<del> * `echo $this->Paginator->last(3);`
<add> * ```
<add> * echo $this->Paginator->last(3);
<add> * ```
<ide> *
<ide> * Will create links for the last 3 pages. Once you enter the page range, no output will be created.
<ide> *
<ide> public function last($last = 'last >>', array $options = [])
<ide> /**
<ide> * Returns the meta-links for a paginated result set.
<ide> *
<del> * `echo $this->Paginator->meta();`
<add> * ```
<add> * echo $this->Paginator->meta();
<add> * ```
<ide> *
<ide> * Echos the links directly, will output nothing if there is neither a previous nor next page.
<ide> *
<del> * `$this->Paginator->meta(['block' => true]);`
<add> * ```
<add> * $this->Paginator->meta(['block' => true]);
<add> * ```
<ide> *
<ide> * Will append the output of the meta function to the named block - if true is passed the "meta"
<ide> * block is used.
<ide><path>src/View/Helper/SessionHelper.php
<ide> public function __construct(View $View, array $config = [])
<ide> /**
<ide> * Reads a session value for a key or returns values for all keys.
<ide> *
<del> * In your view: `$this->Session->read('Controller.sessKey');`
<add> * In your view:
<add> * ```
<add> * $this->Session->read('Controller.sessKey');
<add> * ```
<ide> * Calling the method without a param will return all session vars
<ide> *
<ide> * @param string|null $name The name of the session key you want to read
<ide> public function read($name = null)
<ide> /**
<ide> * Checks if a session key has been set.
<ide> *
<del> * In your view: `$this->Session->check('Controller.sessKey');`
<add> * In your view:
<add> * ```
<add> * $this->Session->check('Controller.sessKey');
<add> * ```
<ide> *
<ide> * @param string $name Session key to check.
<ide> * @return bool
<ide><path>src/View/JsonView.php
<ide> *
<ide> * In your controller, you could do the following:
<ide> *
<del> * `$this->set(['posts' => $posts, '_serialize' => 'posts']);`
<add> * ```
<add> * $this->set(['posts' => $posts, '_serialize' => 'posts']);
<add> * ```
<ide> *
<ide> * When the view is rendered, the `$posts` view variable will be serialized
<ide> * into JSON.
<ide><path>src/View/XmlView.php
<ide> *
<ide> * In your controller, you could do the following:
<ide> *
<del> * `$this->set(['posts' => $posts, '_serialize' => 'posts']);`
<add> * ```
<add> * $this->set(['posts' => $posts, '_serialize' => 'posts']);
<add> * ```
<ide> *
<ide> * When the view is rendered, the `$posts` view variable will be serialized
<ide> * into XML.
| 36
|
Python
|
Python
|
fix libcloud connection class
|
1c5deaf5dc26685a5a5f46f18fef732269029507
|
<ide><path>libcloud/utils/loggingconnection.py
<ide> from pipes import quote as pquote
<ide> from xml.dom.minidom import parseString
<ide>
<del>import sys
<ide> import os
<ide>
<ide> from libcloud.common.base import (LibcloudConnection,
<del> HTTPResponse,
<ide> HttpLibResponseProxy)
<del>from libcloud.utils.py3 import httplib
<del>from libcloud.utils.py3 import PY3
<del>from libcloud.utils.py3 import StringIO
<ide> from libcloud.utils.py3 import u
<del>from libcloud.utils.py3 import b
<del>
<ide>
<ide> from libcloud.utils.misc import lowercase_keys
<ide> from libcloud.utils.compression import decompress_data
<ide> def _log_response(self, r):
<ide> ht += "%s: %s\r\n" % (h[0].title(), h[1])
<ide> ht += "\r\n"
<ide>
<del> # this is evil. laugh with me. ha arharhrhahahaha
<del> class fakesock(object):
<del> def __init__(self, s):
<del> self.s = s
<del>
<del> def makefile(self, *args, **kwargs):
<del> if PY3:
<del> from io import BytesIO
<del> cls = BytesIO
<del> else:
<del> cls = StringIO
<del>
<del> return cls(b(self.s))
<del> rr = r
<ide> headers = lowercase_keys(dict(r.getheaders()))
<ide>
<ide> encoding = headers.get('content-encoding', None)
<ide> def makefile(self, *args, **kwargs):
<ide> pretty_print = os.environ.get('LIBCLOUD_DEBUG_PRETTY_PRINT_RESPONSE',
<ide> False)
<ide>
<del> if r.chunked:
<del> ht += "%x\r\n" % (len(body))
<del> ht += body.decode('utf-8')
<del> ht += "\r\n0\r\n"
<del> else:
<del> if pretty_print and content_type == 'application/json':
<del> try:
<del> body = json.loads(body.decode('utf-8'))
<del> body = json.dumps(body, sort_keys=True, indent=4)
<del> except:
<del> # Invalid JSON or server is lying about content-type
<del> pass
<del> elif pretty_print and content_type == 'text/xml':
<del> try:
<del> elem = parseString(body.decode('utf-8'))
<del> body = elem.toprettyxml()
<del> except Exception:
<del> # Invalid XML
<del> pass
<del>
<del> ht += u(body)
<del>
<del> if sys.version_info >= (2, 6) and sys.version_info < (2, 7):
<del> cls = HTTPResponse
<del> else:
<del> cls = httplib.HTTPResponse
<add> if pretty_print and content_type == 'application/json':
<add> try:
<add> body = json.loads(body.decode('utf-8'))
<add> body = json.dumps(body, sort_keys=True, indent=4)
<add> except:
<add> # Invalid JSON or server is lying about content-type
<add> pass
<add> elif pretty_print and content_type == 'text/xml':
<add> try:
<add> elem = parseString(body.decode('utf-8'))
<add> body = elem.toprettyxml()
<add> except Exception:
<add> # Invalid XML
<add> pass
<add>
<add> ht += u(body)
<ide>
<del> rr = cls(sock=fakesock(ht), method=r._method,
<del> debuglevel=r.debuglevel)
<del> rr.begin()
<ide> rv += ht
<ide> rv += ("\n# -------- end %d:%d response ----------\n"
<ide> % (id(self), id(r)))
<ide>
<del> rr._original_data = body
<del> return (rr, rv)
<add> return rv
<ide>
<ide> def _log_curl(self, method, url, body, headers):
<ide> cmd = ["curl"]
<ide> def _log_curl(self, method, url, body, headers):
<ide> return " ".join(cmd)
<ide>
<ide> def getresponse(self):
<del> r = HttpLibResponseProxy(LibcloudConnection.getresponse(self))
<add> original_response = LibcloudConnection.getresponse(self)
<ide> if self.log is not None:
<del> r, rv = self._log_response(r)
<add> rv = self._log_response(HttpLibResponseProxy(original_response))
<ide> self.log.write(rv + "\n")
<ide> self.log.flush()
<del> return r
<add> return original_response
<ide>
<ide> def request(self, method, url, body=None, headers=None):
<ide> headers.update({'X-LC-Request-ID': str(id(self))})
| 1
|
Text
|
Text
|
add rreverser to collaborators
|
efebd0b79d930c50217caaddf1d245d510937bb0
|
<ide><path>README.md
<ide> information about the governance of the Node.js project, see
<ide> * [robertkowalski](https://github.com/robertkowalski) - **Robert Kowalski** <rok@kowalski.gd>
<ide> * [romankl](https://github.com/romankl) - **Roman Klauke** <romaaan.git@gmail.com>
<ide> * [ronkorving](https://github.com/ronkorving) - **Ron Korving** <ron@ronkorving.nl>
<add>* [RReverser](https://github.com/RReverser) - **Ingvar Stepanyan** <me@rreverser.com>
<ide> * [saghul](https://github.com/saghul) - **Saúl Ibarra Corretgé** <saghul@gmail.com>
<ide> * [sam-github](https://github.com/sam-github) - **Sam Roberts** <vieuxtech@gmail.com>
<ide> * [santigimeno](https://github.com/santigimeno) - **Santiago Gimeno** <santiago.gimeno@gmail.com>
| 1
|
Java
|
Java
|
fix checkstyle violations
|
784d72cc56a95a11ed8058dec5a703e4dc8fbbe2
|
<ide><path>spring-core/src/jmh/java/org/springframework/core/codec/StringDecoderBenchmark.java
<ide> public void setup() {
<ide> "data:abcdefg-$1-hijklmnop-$1-qrstuvw-$1-xyz-$1\n\n";
<ide>
<ide> int eventLength = String.format(eventTemplate, String.format("%05d", 1)).length();
<del> int eventCount = totalSize / eventLength;
<add> int eventCount = this.totalSize / eventLength;
<ide> DataBufferFactory bufferFactory = new DefaultDataBufferFactory();
<ide>
<ide> this.chunks = Flux.range(1, eventCount)
<ide> .map(index -> String.format(eventTemplate, String.format("%05d", index)))
<del> .buffer(chunkSize > eventLength ? chunkSize / eventLength : 1)
<add> .buffer(this.chunkSize > eventLength ? this.chunkSize / eventLength : 1)
<ide> .map(strings -> String.join("", strings))
<ide> .map(chunk -> {
<ide> byte[] bytes = chunk.getBytes(CHARSET);
| 1
|
Java
|
Java
|
relocate runtime hints to aot package
|
6936f7e0cb1eae8357f3c700d2c2d33834475ec2
|
<add><path>spring-core/src/main/java/org/springframework/aot/hint/AbstractTypeReference.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/AbstractTypeReference.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.util.Objects;
<ide>
<add><path>spring-core/src/main/java/org/springframework/aot/hint/ClassProxyHint.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/ClassProxyHint.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.util.Arrays;
<ide> import java.util.LinkedList;
<add><path>spring-core/src/main/java/org/springframework/aot/hint/ExecutableHint.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/ExecutableHint.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.lang.reflect.Constructor;
<ide> import java.lang.reflect.Executable;
<add><path>spring-core/src/main/java/org/springframework/aot/hint/ExecutableMode.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/ExecutableMode.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.lang.reflect.Executable;
<ide>
<add><path>spring-core/src/main/java/org/springframework/aot/hint/FieldHint.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/FieldHint.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.lang.reflect.Field;
<ide>
<add><path>spring-core/src/main/java/org/springframework/aot/hint/JavaSerializationHints.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/JavaSerializationHints.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.io.Serializable;
<ide> import java.util.LinkedHashSet;
<add><path>spring-core/src/main/java/org/springframework/aot/hint/JdkProxyHint.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/JdkProxyHint.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.lang.reflect.Proxy;
<ide> import java.util.Arrays;
<add><path>spring-core/src/main/java/org/springframework/aot/hint/MemberCategory.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/MemberCategory.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.lang.reflect.Constructor;
<ide> import java.lang.reflect.Field;
<add><path>spring-core/src/main/java/org/springframework/aot/hint/MemberHint.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/MemberHint.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.lang.reflect.Member;
<ide>
<add><path>spring-core/src/main/java/org/springframework/aot/hint/ProxyHints.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/ProxyHints.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.util.Arrays;
<ide> import java.util.LinkedHashSet;
<ide> import java.util.stream.Collectors;
<ide> import java.util.stream.Stream;
<ide>
<del>import org.springframework.core.hint.ClassProxyHint.Builder;
<add>import org.springframework.aot.hint.ClassProxyHint.Builder;
<ide>
<ide> /**
<ide> * Gather the need of using proxies at runtime.
<add><path>spring-core/src/main/java/org/springframework/aot/hint/ReflectionHints.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/ReflectionHints.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.lang.reflect.Constructor;
<ide> import java.lang.reflect.Executable;
<ide> import java.util.stream.Collectors;
<ide> import java.util.stream.Stream;
<ide>
<del>import org.springframework.core.hint.TypeHint.Builder;
<add>import org.springframework.aot.hint.TypeHint.Builder;
<ide>
<ide> /**
<ide> * Gather the need for reflection at runtime.
<add><path>spring-core/src/main/java/org/springframework/aot/hint/ReflectionTypeReference.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/ReflectionTypeReference.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import org.springframework.lang.Nullable;
<ide>
<add><path>spring-core/src/main/java/org/springframework/aot/hint/ResourceBundleHint.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/ResourceBundleHint.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.util.ResourceBundle;
<ide>
<add><path>spring-core/src/main/java/org/springframework/aot/hint/ResourceHints.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/ResourceHints.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.HashSet;
<ide> import java.util.function.Consumer;
<ide> import java.util.stream.Stream;
<ide>
<del>import org.springframework.core.hint.ResourcePatternHint.Builder;
<add>import org.springframework.aot.hint.ResourcePatternHint.Builder;
<ide>
<ide> /**
<ide> * Gather the need for resources available at runtime.
<add><path>spring-core/src/main/java/org/springframework/aot/hint/ResourcePatternHint.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/ResourcePatternHint.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<add><path>spring-core/src/main/java/org/springframework/aot/hint/RuntimeHints.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/RuntimeHints.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> /**
<ide> * Gather hints that can be used to optimize the application runtime.
<add><path>spring-core/src/main/java/org/springframework/aot/hint/SimpleTypeReference.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/SimpleTypeReference.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<add><path>spring-core/src/main/java/org/springframework/aot/hint/TypeHint.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/TypeHint.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.util.Arrays;
<ide> import java.util.HashMap;
<add><path>spring-core/src/main/java/org/springframework/aot/hint/TypeReference.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/TypeReference.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import org.springframework.lang.Nullable;
<ide>
<add><path>spring-core/src/main/java/org/springframework/aot/hint/package-info.java
<del><path>spring-core/src/main/java/org/springframework/core/hint/package-info.java
<ide> * Support for registering the need for reflection, resources, java serialization
<ide> * and proxies.
<ide> */
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<add><path>spring-core/src/test/java/org/springframework/aot/hint/ClassProxyHintTests.java
<del><path>spring-core/src/test/java/org/springframework/core/hint/ClassProxyHintTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.io.Closeable;
<ide> import java.io.Serializable;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<del>import org.springframework.core.hint.JdkProxyHint.Builder;
<add>import org.springframework.aot.hint.JdkProxyHint.Builder;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide>
<add><path>spring-core/src/test/java/org/springframework/aot/hint/JavaSerializationHintsTests.java
<del><path>spring-core/src/test/java/org/springframework/core/hint/JavaSerializationHintsTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.net.URL;
<ide>
<add><path>spring-core/src/test/java/org/springframework/aot/hint/JdkProxyHintTests.java
<del><path>spring-core/src/test/java/org/springframework/core/hint/JdkProxyHintTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.util.function.Consumer;
<ide> import java.util.function.Function;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<del>import org.springframework.core.hint.JdkProxyHint.Builder;
<add>import org.springframework.aot.hint.JdkProxyHint.Builder;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide>
<add><path>spring-core/src/test/java/org/springframework/aot/hint/ProxyHintsTests.java
<del><path>spring-core/src/test/java/org/springframework/core/hint/ProxyHintsTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.io.Serializable;
<ide> import java.util.Arrays;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<del>import org.springframework.core.hint.JdkProxyHint.Builder;
<add>import org.springframework.aot.hint.JdkProxyHint.Builder;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
<add><path>spring-core/src/test/java/org/springframework/aot/hint/ReflectionHintsTests.java
<del><path>spring-core/src/test/java/org/springframework/core/hint/ReflectionHintsTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.util.function.Consumer;
<ide>
<add><path>spring-core/src/test/java/org/springframework/aot/hint/ResourceHintsTests.java
<del><path>spring-core/src/test/java/org/springframework/core/hint/ResourceHintsTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<del>import org.springframework.core.hint.ResourceHintsTests.Nested.Inner;
<add>import org.springframework.aot.hint.ResourceHintsTests.Nested.Inner;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide>
<ide> void registerType() {
<ide> void registerTypeWithNestedType() {
<ide> this.resourceHints.registerType(TypeReference.of(Nested.class));
<ide> assertThat(this.resourceHints.resourcePatterns()).singleElement().satisfies(
<del> patternOf("org/springframework/core/hint/ResourceHintsTests$Nested.class"));
<add> patternOf("org/springframework/aot/hint/ResourceHintsTests$Nested.class"));
<ide> }
<ide>
<ide> @Test
<ide> void registerTypeWithInnerNestedType() {
<ide> this.resourceHints.registerType(TypeReference.of(Inner.class));
<ide> assertThat(this.resourceHints.resourcePatterns()).singleElement().satisfies(
<del> patternOf("org/springframework/core/hint/ResourceHintsTests$Nested$Inner.class"));
<add> patternOf("org/springframework/aot/hint/ResourceHintsTests$Nested$Inner.class"));
<ide> }
<ide>
<ide> @Test
<add><path>spring-core/src/test/java/org/springframework/aot/hint/RuntimeHintsTests.java
<del><path>spring-core/src/test/java/org/springframework/core/hint/RuntimeHintsTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.util.function.Function;
<ide>
<add><path>spring-core/src/test/java/org/springframework/aot/hint/TypeHintTests.java
<del><path>spring-core/src/test/java/org/springframework/core/hint/TypeHintTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import java.util.List;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<del>import org.springframework.core.hint.TypeHint.Builder;
<add>import org.springframework.aot.hint.TypeHint.Builder;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
<add><path>spring-core/src/test/java/org/springframework/aot/hint/TypeReferenceTests.java
<del><path>spring-core/src/test/java/org/springframework/core/hint/TypeReferenceTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.core.hint;
<add>package org.springframework.aot.hint;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
| 29
|
PHP
|
PHP
|
use jsonb type for pgsql wherejsonlength
|
5e0b273ae3012cbb1e959efe4627f03811b705cd
|
<ide><path>src/Illuminate/Database/Query/Grammars/PostgresGrammar.php
<ide> protected function compileJsonLength($column, $operator, $value)
<ide> {
<ide> $column = str_replace('->>', '->', $this->wrap($column));
<ide>
<del> return 'json_array_length(('.$column.')::json) '.$operator.' '.$value;
<add> return 'jsonb_array_length(('.$column.')::jsonb) '.$operator.' '.$value;
<ide> }
<ide>
<ide> /**
<ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> public function testWhereJsonLengthPostgres()
<ide> {
<ide> $builder = $this->getPostgresBuilder();
<ide> $builder->select('*')->from('users')->whereJsonLength('options', 0);
<del> $this->assertSame('select * from "users" where json_array_length(("options")::json) = ?', $builder->toSql());
<add> $this->assertSame('select * from "users" where jsonb_array_length(("options")::jsonb) = ?', $builder->toSql());
<ide> $this->assertEquals([0], $builder->getBindings());
<ide>
<ide> $builder = $this->getPostgresBuilder();
<ide> $builder->select('*')->from('users')->whereJsonLength('users.options->languages', '>', 0);
<del> $this->assertSame('select * from "users" where json_array_length(("users"."options"->\'languages\')::json) > ?', $builder->toSql());
<add> $this->assertSame('select * from "users" where jsonb_array_length(("users"."options"->\'languages\')::jsonb) > ?', $builder->toSql());
<ide> $this->assertEquals([0], $builder->getBindings());
<ide>
<ide> $builder = $this->getPostgresBuilder();
<ide> $builder->select('*')->from('users')->where('id', '=', 1)->orWhereJsonLength('options->languages', new Raw('0'));
<del> $this->assertSame('select * from "users" where "id" = ? or json_array_length(("options"->\'languages\')::json) = 0', $builder->toSql());
<add> $this->assertSame('select * from "users" where "id" = ? or jsonb_array_length(("options"->\'languages\')::jsonb) = 0', $builder->toSql());
<ide> $this->assertEquals([1], $builder->getBindings());
<ide>
<ide> $builder = $this->getPostgresBuilder();
<ide> $builder->select('*')->from('users')->where('id', '=', 1)->orWhereJsonLength('options->languages', '>', new Raw('0'));
<del> $this->assertSame('select * from "users" where "id" = ? or json_array_length(("options"->\'languages\')::json) > 0', $builder->toSql());
<add> $this->assertSame('select * from "users" where "id" = ? or jsonb_array_length(("options"->\'languages\')::jsonb) > 0', $builder->toSql());
<ide> $this->assertEquals([1], $builder->getBindings());
<ide> }
<ide>
| 2
|
Ruby
|
Ruby
|
pass cache key to dependency.expand
|
22053ca2c3cb1b1a214087f1309def98757387bf
|
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def check_conflicts
<ide> # being installed.
<ide> def compute_dependencies
<ide> @compute_dependencies ||= begin
<del> req_map, req_deps = expand_requirements
<del> check_requirements(req_map)
<del> expand_dependencies(req_deps + formula.deps)
<add> check_requirements(expand_requirements)
<add> expand_dependencies
<ide> end
<ide> end
<ide>
<ide> def runtime_requirements(formula)
<ide>
<ide> def expand_requirements
<ide> unsatisfied_reqs = Hash.new { |h, k| h[k] = [] }
<del> req_deps = []
<ide> formulae = [formula]
<ide> formula_deps_map = formula.recursive_dependencies
<ide> .index_by(&:name)
<ide> def expand_requirements
<ide> end
<ide> end
<ide>
<del> # Merge the repeated dependencies, which may have different tags.
<del> req_deps = Dependency.merge_repeats(req_deps)
<del>
<del> [unsatisfied_reqs, req_deps]
<add> unsatisfied_reqs
<ide> end
<ide>
<del> def expand_dependencies(deps)
<add> def expand_dependencies
<ide> inherited_options = Hash.new { |hash, key| hash[key] = Options.new }
<ide> pour_bottle = pour_bottle?
<ide>
<del> expanded_deps = Dependency.expand(formula, deps) do |dependent, dep|
<add> # Cache for this expansion only. FormulaInstaller has a lot of inputs which can alter expansion.
<add> cache_key = "FormulaInstaller-#{formula.full_name}-#{Time.now.to_f}"
<add> expanded_deps = Dependency.expand(formula, cache_key: cache_key) do |dependent, dep|
<ide> inherited_options[dep.name] |= inherited_options_for(dep)
<ide> build = effective_build_options_for(
<ide> dependent,
| 1
|
Javascript
|
Javascript
|
prefix mock scheduler apis with _unstable
|
4d307de458dfdf25e704cb2ca20b0578bba8998c
|
<ide><path>packages/create-subscription/src/__tests__/createSubscription-test.internal.js
<ide> describe('createSubscription', () => {
<ide> ReactNoop.render(
<ide> <Subscription source={observable}>
<ide> {(value = 'default') => {
<del> Scheduler.yieldValue(value);
<add> Scheduler.unstable_yieldValue(value);
<ide> return null;
<ide> }}
<ide> </Subscription>,
<ide> describe('createSubscription', () => {
<ide> });
<ide>
<ide> function render(value = 'default') {
<del> Scheduler.yieldValue(value);
<add> Scheduler.unstable_yieldValue(value);
<ide> return null;
<ide> }
<ide>
<ide> describe('createSubscription', () => {
<ide>
<ide> function render(hasLoaded) {
<ide> if (hasLoaded === undefined) {
<del> Scheduler.yieldValue('loading');
<add> Scheduler.unstable_yieldValue('loading');
<ide> } else {
<del> Scheduler.yieldValue(hasLoaded ? 'finished' : 'failed');
<add> Scheduler.unstable_yieldValue(hasLoaded ? 'finished' : 'failed');
<ide> }
<ide> return null;
<ide> }
<ide> describe('createSubscription', () => {
<ide> });
<ide>
<ide> function render(value = 'default') {
<del> Scheduler.yieldValue(value);
<add> Scheduler.unstable_yieldValue(value);
<ide> return null;
<ide> }
<ide>
<ide> describe('createSubscription', () => {
<ide> });
<ide>
<ide> function render(hasLoaded) {
<del> Scheduler.yieldValue('rendered');
<add> Scheduler.unstable_yieldValue('rendered');
<ide> return null;
<ide> }
<ide>
<ide> describe('createSubscription', () => {
<ide> });
<ide>
<ide> function render(value = 'default') {
<del> Scheduler.yieldValue(value);
<add> Scheduler.unstable_yieldValue(value);
<ide> return null;
<ide> }
<ide>
<ide> describe('createSubscription', () => {
<ide> const log = [];
<ide>
<ide> function Child({value}) {
<del> Scheduler.yieldValue('Child: ' + value);
<add> Scheduler.unstable_yieldValue('Child: ' + value);
<ide> return null;
<ide> }
<ide>
<ide> describe('createSubscription', () => {
<ide> return (
<ide> <Subscription source={this.state.observed}>
<ide> {(value = 'default') => {
<del> Scheduler.yieldValue('Subscriber: ' + value);
<add> Scheduler.unstable_yieldValue('Subscriber: ' + value);
<ide> return <Child value={value} />;
<ide> }}
<ide> </Subscription>
<ide> describe('createSubscription', () => {
<ide> const log = [];
<ide>
<ide> function Child({value}) {
<del> Scheduler.yieldValue('Child: ' + value);
<add> Scheduler.unstable_yieldValue('Child: ' + value);
<ide> return null;
<ide> }
<ide>
<ide> describe('createSubscription', () => {
<ide> return (
<ide> <Subscription source={this.state.observed}>
<ide> {(value = 'default') => {
<del> Scheduler.yieldValue('Subscriber: ' + value);
<add> Scheduler.unstable_yieldValue('Subscriber: ' + value);
<ide> return <Child value={value} />;
<ide> }}
<ide> </Subscription>
<ide><path>packages/react-art/src/__tests__/ReactART-test.js
<ide> describe('ReactART', () => {
<ide> const CurrentRendererContext = React.createContext(null);
<ide>
<ide> function Yield(props) {
<del> Scheduler.yieldValue(props.value);
<add> Scheduler.unstable_yieldValue(props.value);
<ide> return null;
<ide> }
<ide>
<ide><path>packages/react-cache/src/__tests__/ReactCache-test.internal.js
<ide> describe('ReactCache', () => {
<ide> listeners = [{resolve, reject}];
<ide> setTimeout(() => {
<ide> if (textResourceShouldFail) {
<del> Scheduler.yieldValue(`Promise rejected [${text}]`);
<add> Scheduler.unstable_yieldValue(`Promise rejected [${text}]`);
<ide> status = 'rejected';
<ide> value = new Error('Failed to load: ' + text);
<ide> listeners.forEach(listener => listener.reject(value));
<ide> } else {
<del> Scheduler.yieldValue(`Promise resolved [${text}]`);
<add> Scheduler.unstable_yieldValue(`Promise resolved [${text}]`);
<ide> status = 'resolved';
<ide> value = text;
<ide> listeners.forEach(listener => listener.resolve(value));
<ide> describe('ReactCache', () => {
<ide> });
<ide>
<ide> function Text(props) {
<del> Scheduler.yieldValue(props.text);
<add> Scheduler.unstable_yieldValue(props.text);
<ide> return props.text;
<ide> }
<ide>
<ide> function AsyncText(props) {
<ide> const text = props.text;
<ide> try {
<ide> TextResource.read([props.text, props.ms]);
<del> Scheduler.yieldValue(text);
<add> Scheduler.unstable_yieldValue(text);
<ide> return text;
<ide> } catch (promise) {
<ide> if (typeof promise.then === 'function') {
<del> Scheduler.yieldValue(`Suspend! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
<ide> } else {
<del> Scheduler.yieldValue(`Error! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Error! [${text}]`);
<ide> }
<ide> throw promise;
<ide> }
<ide> describe('ReactCache', () => {
<ide> });
<ide>
<ide> function App() {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> return BadTextResource.read(['Hi', 100]);
<ide> }
<ide>
<ide> describe('ReactCache', () => {
<ide> const text = props.text;
<ide> try {
<ide> const actualText = BadTextResource.read([props.text, props.ms]);
<del> Scheduler.yieldValue(actualText);
<add> Scheduler.unstable_yieldValue(actualText);
<ide> return actualText;
<ide> } catch (promise) {
<ide> if (typeof promise.then === 'function') {
<del> Scheduler.yieldValue(`Suspend! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
<ide> } else {
<del> Scheduler.yieldValue(`Error! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Error! [${text}]`);
<ide> }
<ide> throw promise;
<ide> }
<ide><path>packages/react-debug-tools/src/__tests__/ReactHooksInspectionIntegration-test.js
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide>
<ide> await LazyFoo;
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> let childFiber = renderer.root._currentFiber();
<ide> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<ide><path>packages/react-dom/src/__tests__/ReactDOMFiberAsync-test.internal.js
<ide> describe('ReactDOMFiberAsync', () => {
<ide> }
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> root.render(<Counter />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(asyncValueRef.current.textContent).toBe('');
<ide> expect(syncValueRef.current.textContent).toBe('');
<ide>
<ide> describe('ReactDOMFiberAsync', () => {
<ide>
<ide> // Should flush both updates now.
<ide> jest.runAllTimers();
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(asyncValueRef.current.textContent).toBe('hello');
<ide> expect(syncValueRef.current.textContent).toBe('hello');
<ide> });
<ide> describe('ReactDOMFiberAsync', () => {
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> root.render(<div>Hi</div>);
<ide> expect(container.textContent).toEqual('');
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('Hi');
<ide>
<ide> root.render(<div>Bye</div>);
<ide> expect(container.textContent).toEqual('Hi');
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('Bye');
<ide> });
<ide>
<ide> describe('ReactDOMFiberAsync', () => {
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> root.render(<Component />);
<ide> expect(container.textContent).toEqual('');
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('0');
<ide>
<ide> instance.setState({step: 1});
<ide> expect(container.textContent).toEqual('0');
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('1');
<ide> });
<ide>
<ide> describe('ReactDOMFiberAsync', () => {
<ide>
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> root.render(<Component />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> // Updates are async by default
<ide> instance.push('A');
<ide> describe('ReactDOMFiberAsync', () => {
<ide> expect(ops).toEqual(['BC']);
<ide>
<ide> // Flush the async updates
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('ABCD');
<ide> expect(ops).toEqual(['BC', 'ABCD']);
<ide> });
<ide> describe('ReactDOMFiberAsync', () => {
<ide> }
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> root.render(<Counter />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('0');
<ide>
<ide> // Test that a normal update is async
<ide> inst.increment();
<ide> expect(container.textContent).toEqual('0');
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('1');
<ide>
<ide> let ops = [];
<ide> describe('ReactDOMFiberAsync', () => {
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> root.render(<Form />);
<ide> // Flush
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> let disableButton = disableButtonRef.current;
<ide> expect(disableButton.tagName).toBe('BUTTON');
<ide> describe('ReactDOMFiberAsync', () => {
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> root.render(<Form />);
<ide> // Flush
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> let disableButton = disableButtonRef.current;
<ide> expect(disableButton.tagName).toBe('BUTTON');
<ide> describe('ReactDOMFiberAsync', () => {
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> root.render(<Form />);
<ide> // Flush
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> let enableButton = enableButtonRef.current;
<ide> expect(enableButton.tagName).toBe('BUTTON');
<ide> describe('ReactDOMFiberAsync', () => {
<ide> const root = ReactDOM.unstable_createSyncRoot(container);
<ide>
<ide> function Text(props) {
<del> Scheduler.yieldValue(props.text);
<add> Scheduler.unstable_yieldValue(props.text);
<ide> return props.text;
<ide> }
<ide>
<ide><path>packages/react-dom/src/__tests__/ReactDOMHooks-test.js
<ide> describe('ReactDOMHooks', () => {
<ide> expect(container.textContent).toBe('1');
<ide> expect(container2.textContent).toBe('');
<ide> expect(container3.textContent).toBe('');
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toBe('1');
<ide> expect(container2.textContent).toBe('2');
<ide> expect(container3.textContent).toBe('3');
<ide> describe('ReactDOMHooks', () => {
<ide> expect(container.textContent).toBe('2');
<ide> expect(container2.textContent).toBe('2'); // Not flushed yet
<ide> expect(container3.textContent).toBe('3'); // Not flushed yet
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toBe('2');
<ide> expect(container2.textContent).toBe('4');
<ide> expect(container3.textContent).toBe('6');
<ide> describe('ReactDOMHooks', () => {
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> root.render(<Example inputRef={inputRef} labelRef={labelRef} />);
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> inputRef.current.value = 'abc';
<ide> inputRef.current.dispatchEvent(
<ide> new Event('input', {bubbles: true, cancelable: true}),
<ide> );
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> expect(labelRef.current.innerHTML).toBe('abc');
<ide> });
<ide><path>packages/react-dom/src/__tests__/ReactDOMRoot-test.js
<ide> describe('ReactDOMRoot', () => {
<ide> it('renders children', () => {
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> root.render(<div>Hi</div>);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('Hi');
<ide> });
<ide>
<ide> it('unmounts children', () => {
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> root.render(<div>Hi</div>);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('Hi');
<ide> root.unmount();
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('');
<ide> });
<ide>
<ide> describe('ReactDOMRoot', () => {
<ide> ops.push('inside callback: ' + container.textContent);
<ide> });
<ide> ops.push('before committing: ' + container.textContent);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> ops.push('after committing: ' + container.textContent);
<ide> expect(ops).toEqual([
<ide> 'before committing: ',
<ide> describe('ReactDOMRoot', () => {
<ide> it('resolves `work.then` callback synchronously if the work already committed', () => {
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> const work = root.render('Hi');
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> let ops = [];
<ide> work.then(() => {
<ide> ops.push('inside callback');
<ide> describe('ReactDOMRoot', () => {
<ide> <span />
<ide> </div>,
<ide> );
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> // Accepts `hydrate` option
<ide> const container2 = document.createElement('div');
<ide> describe('ReactDOMRoot', () => {
<ide> <span />
<ide> </div>,
<ide> );
<del> expect(() => Scheduler.flushAll()).toWarnDev('Extra attributes', {
<add> expect(() => Scheduler.unstable_flushAll()).toWarnDev('Extra attributes', {
<ide> withoutStack: true,
<ide> });
<ide> });
<ide> describe('ReactDOMRoot', () => {
<ide> <span>d</span>
<ide> </div>,
<ide> );
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('abcd');
<ide> root.render(
<ide> <div>
<ide> <span>d</span>
<ide> <span>c</span>
<ide> </div>,
<ide> );
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('abdc');
<ide> });
<ide>
<ide> describe('ReactDOMRoot', () => {
<ide> const batch = root.createBatch();
<ide> batch.render(<App />);
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> // Hasn't updated yet
<ide> expect(container.textContent).toEqual('');
<ide> describe('ReactDOMRoot', () => {
<ide> const batch = root.createBatch();
<ide> batch.render(<Foo>Hi</Foo>);
<ide> // Flush all async work.
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> // Root should complete without committing.
<ide> expect(ops).toEqual(['Foo']);
<ide> expect(container.textContent).toEqual('');
<ide> describe('ReactDOMRoot', () => {
<ide> const batch = root.createBatch();
<ide> batch.render('Foo');
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> // Hasn't updated yet
<ide> expect(container.textContent).toEqual('');
<ide> describe('ReactDOMRoot', () => {
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> root.render(1);
<ide>
<del> Scheduler.advanceTime(2000);
<add> Scheduler.unstable_advanceTime(2000);
<ide> // This batch has a later expiration time than the earlier update.
<ide> const batch = root.createBatch();
<ide>
<ide> // This should not flush the earlier update.
<ide> batch.commit();
<ide> expect(container.textContent).toEqual('');
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('1');
<ide> });
<ide>
<ide> describe('ReactDOMRoot', () => {
<ide> batch1.render(1);
<ide>
<ide> // This batch has a later expiration time
<del> Scheduler.advanceTime(2000);
<add> Scheduler.unstable_advanceTime(2000);
<ide> const batch2 = root.createBatch();
<ide> batch2.render(2);
<ide>
<ide> describe('ReactDOMRoot', () => {
<ide> batch1.render(1);
<ide>
<ide> // This batch has a later expiration time
<del> Scheduler.advanceTime(2000);
<add> Scheduler.unstable_advanceTime(2000);
<ide> const batch2 = root.createBatch();
<ide> batch2.render(2);
<ide>
<ide> describe('ReactDOMRoot', () => {
<ide> expect(container.textContent).toEqual('2');
<ide>
<ide> batch1.commit();
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('1');
<ide> });
<ide>
<ide> describe('ReactDOMRoot', () => {
<ide> it('warns when rendering with legacy API into createRoot() container', () => {
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> root.render(<div>Hi</div>);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('Hi');
<ide> expect(() => {
<ide> ReactDOM.render(<div>Bye</div>, container);
<ide> describe('ReactDOMRoot', () => {
<ide> ],
<ide> {withoutStack: true},
<ide> );
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> // This works now but we could disallow it:
<ide> expect(container.textContent).toEqual('Bye');
<ide> });
<ide>
<ide> it('warns when hydrating with legacy API into createRoot() container', () => {
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> root.render(<div>Hi</div>);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('Hi');
<ide> expect(() => {
<ide> ReactDOM.hydrate(<div>Hi</div>, container);
<ide> describe('ReactDOMRoot', () => {
<ide> it('warns when unmounting with legacy API (no previous content)', () => {
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> root.render(<div>Hi</div>);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('Hi');
<ide> let unmounted = false;
<ide> expect(() => {
<ide> describe('ReactDOMRoot', () => {
<ide> {withoutStack: true},
<ide> );
<ide> expect(unmounted).toBe(false);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('Hi');
<ide> root.unmount();
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('');
<ide> });
<ide>
<ide> describe('ReactDOMRoot', () => {
<ide> // The rest is the same as test above.
<ide> const root = ReactDOM.unstable_createRoot(container);
<ide> root.render(<div>Hi</div>);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('Hi');
<ide> let unmounted = false;
<ide> expect(() => {
<ide> unmounted = ReactDOM.unmountComponentAtNode(container);
<ide> }).toWarnDev('Did you mean to call root.unmount()?', {withoutStack: true});
<ide> expect(unmounted).toBe(false);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('Hi');
<ide> root.unmount();
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(container.textContent).toEqual('');
<ide> });
<ide>
<ide><path>packages/react-dom/src/__tests__/ReactDOMServerIntegrationSpecialTypes-test.js
<ide> let ReactTestUtils;
<ide> let forwardRef;
<ide> let memo;
<ide> let yieldedValues;
<del>let yieldValue;
<add>let unstable_yieldValue;
<ide> let clearYields;
<ide>
<ide> function initModules() {
<ide> function initModules() {
<ide> memo = React.memo;
<ide>
<ide> yieldedValues = [];
<del> yieldValue = value => {
<add> unstable_yieldValue = value => {
<ide> yieldedValues.push(value);
<ide> };
<ide> clearYields = () => {
<ide> describe('ReactDOMServerIntegration', () => {
<ide> });
<ide>
<ide> function Text({text}) {
<del> yieldValue(text);
<add> unstable_yieldValue(text);
<ide> return <span>{text}</span>;
<ide> }
<ide>
<ide> describe('ReactDOMServerIntegration', () => {
<ide> 'comparator functions are not invoked on the server',
<ide> async render => {
<ide> const MemoCounter = React.memo(Counter, (oldProps, newProps) => {
<del> yieldValue(
<add> unstable_yieldValue(
<ide> `Old count: ${oldProps.count}, New count: ${newProps.count}`,
<ide> );
<ide> return oldProps.count === newProps.count;
<ide><path>packages/react-dom/src/__tests__/ReactDOMServerPartialHydration-test.internal.js
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> suspend = true;
<ide> let root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<ide> root.render(<App />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> expect(ref.current).toBe(null);
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> suspend = false;
<ide> resolve();
<ide> await promise;
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> // We should now have hydrated with a ref on the existing span.
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> suspend = true;
<ide> let root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<ide> root.render(<App text="Hello" className="hello" />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> expect(ref.current).toBe(null);
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide>
<ide> // Flushing both of these in the same batch won't be able to hydrate so we'll
<ide> // probably throw away the existing subtree.
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> // Pick up the new span. In an ideal implementation this might be the same span
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> suspend = true;
<ide> let root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<ide> root.render(<App text="Hello" className="hello" />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> expect(ref.current).toBe(null);
<ide>
<ide> // Render an update, but leave it still suspended.
<ide> root.render(<App text="Hi" className="hi" />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> // Flushing now should delete the existing content and show the fallback.
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> resolve();
<ide> await promise;
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> let span = container.getElementsByTagName('span')[0];
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> suspend = true;
<ide> let root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<ide> root.render(<App text="Hello" className="hello" />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> expect(ref.current).toBe(null);
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> root.render(<App text="Hi" className="hi" />);
<ide>
<ide> // Flushing now should delete the existing content and show the fallback.
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> expect(container.getElementsByTagName('span').length).toBe(0);
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> resolve();
<ide> await promise;
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> let span = container.getElementsByTagName('span')[0];
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> suspend = true;
<ide> let root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<ide> root.render(<App text="Hello" className="hello" />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> expect(ref.current).toBe(null);
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> root.render(<App text="Hi" className="hi" />);
<ide>
<ide> // Flushing now should delete the existing content and show the fallback.
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> expect(container.getElementsByTagName('span').length).toBe(0);
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> resolve();
<ide> await promise;
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> let span = container.getElementsByTagName('span')[0];
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> <App />
<ide> </Context.Provider>,
<ide> );
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> expect(ref.current).toBe(null);
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide>
<ide> // Flushing both of these in the same batch won't be able to hydrate so we'll
<ide> // probably throw away the existing subtree.
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> // Pick up the new span. In an ideal implementation this might be the same span
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> <App />
<ide> </Context.Provider>,
<ide> );
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> expect(ref.current).toBe(null);
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> );
<ide>
<ide> // Flushing now should delete the existing content and show the fallback.
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> expect(container.getElementsByTagName('span').length).toBe(0);
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> resolve();
<ide> await promise;
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> let span = container.getElementsByTagName('span')[0];
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> suspend = false;
<ide> let root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<ide> root.render(<App />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> expect(container.textContent).toBe('Hello');
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> suspend = false;
<ide> let root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<ide> root.render(<App />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> // This will have exceeded the suspended time so we should timeout.
<ide> jest.advanceTimersByTime(500);
<ide> // The boundary should longer be suspended for the middle content
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> suspend = false;
<ide> let root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<ide> root.render(<App />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> // This will have exceeded the suspended time so we should timeout.
<ide> jest.advanceTimersByTime(500);
<ide> // The boundary should longer be suspended for the middle content
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> suspend = false;
<ide> let root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<ide> root.render(<App />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> // We're still loading because we're waiting for the server to stream more content.
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> // But it is not yet hydrated.
<ide> expect(ref.current).toBe(null);
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> // Now it's hydrated.
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> suspend = false;
<ide> let root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<ide> root.render(<App />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> // We're still loading because we're waiting for the server to stream more content.
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> expect(container.textContent).toBe('Loading...');
<ide> expect(ref.current).toBe(null);
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> // Hydrating should've generated an error and replaced the suspense boundary.
<ide><path>packages/react-dom/src/__tests__/ReactDOMSuspensePlaceholder-test.js
<ide> describe('ReactDOMSuspensePlaceholder', () => {
<ide>
<ide> await advanceTimers(500);
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> expect(window.getComputedStyle(divs[0].current).display).toEqual('block');
<ide> expect(window.getComputedStyle(divs[1].current).display).toEqual('block');
<ide> describe('ReactDOMSuspensePlaceholder', () => {
<ide>
<ide> await advanceTimers(500);
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> expect(container.textContent).toEqual('ABC');
<ide> });
<ide> describe('ReactDOMSuspensePlaceholder', () => {
<ide>
<ide> await advanceTimers(500);
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> expect(container.innerHTML).toEqual(
<ide> '<span style="display: inline;">Sibling</span><span style="">Async</span>',
<ide><path>packages/react-dom/src/__tests__/ReactServerRenderingHydration-test.js
<ide> describe('ReactDOMServerHydration', () => {
<ide>
<ide> jest.runAllTimers();
<ide> await Promise.resolve();
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(element.textContent).toBe('Hello world');
<ide> });
<ide> });
<ide><path>packages/react-dom/src/__tests__/ReactTestUtilsAct-test.js
<ide> function runActTests(label, render, unmount) {
<ide> it('can use act to flush effects', () => {
<ide> function App() {
<ide> React.useEffect(() => {
<del> Scheduler.yieldValue(100);
<add> Scheduler.unstable_yieldValue(100);
<ide> });
<ide> return null;
<ide> }
<ide> function runActTests(label, render, unmount) {
<ide> function App() {
<ide> let [ctr, setCtr] = React.useState(0);
<ide> React.useEffect(() => {
<del> Scheduler.yieldValue(ctr);
<add> Scheduler.unstable_yieldValue(ctr);
<ide> });
<ide> return (
<ide> <button id="button" onClick={() => setCtr(x => x + 1)}>
<ide> function runActTests(label, render, unmount) {
<ide> it('should flush effects only on exiting the outermost act', () => {
<ide> function App() {
<ide> React.useEffect(() => {
<del> Scheduler.yieldValue(0);
<add> Scheduler.unstable_yieldValue(0);
<ide> });
<ide> return null;
<ide> }
<ide> function runActTests(label, render, unmount) {
<ide> something();
<ide> }, []);
<ide> React.useEffect(() => {
<del> Scheduler.yieldValue(state);
<add> Scheduler.unstable_yieldValue(state);
<ide> });
<ide> return state;
<ide> }
<ide> function runActTests(label, render, unmount) {
<ide> }
<ide> React.useEffect(
<ide> () => {
<del> Scheduler.yieldValue(state);
<add> Scheduler.unstable_yieldValue(state);
<ide> ticker();
<ide> },
<ide> [Math.min(state, 4)],
<ide> function runActTests(label, render, unmount) {
<ide> it('should cleanup after errors - sync', () => {
<ide> function App() {
<ide> React.useEffect(() => {
<del> Scheduler.yieldValue('oh yes');
<add> Scheduler.unstable_yieldValue('oh yes');
<ide> });
<ide> return null;
<ide> }
<ide> function runActTests(label, render, unmount) {
<ide> function App() {
<ide> async function somethingAsync() {
<ide> await null;
<del> Scheduler.yieldValue('oh yes');
<add> Scheduler.unstable_yieldValue('oh yes');
<ide> }
<ide> React.useEffect(() => {
<ide> somethingAsync();
<ide><path>packages/react-dom/src/__tests__/ReactUpdates-test.js
<ide> describe('ReactUpdates', () => {
<ide> const container = document.createElement('div');
<ide>
<ide> function Baz() {
<del> Scheduler.yieldValue('Baz');
<add> Scheduler.unstable_yieldValue('Baz');
<ide> return <p>baz</p>;
<ide> }
<ide>
<ide> let setCounter;
<ide> function Bar() {
<ide> const [counter, _setCounter] = React.useState(0);
<ide> setCounter = _setCounter;
<del> Scheduler.yieldValue('Bar');
<add> Scheduler.unstable_yieldValue('Bar');
<ide> return <p>bar {counter}</p>;
<ide> }
<ide>
<ide> function Foo() {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> React.useEffect(() => {
<del> Scheduler.yieldValue('Foo#effect');
<add> Scheduler.unstable_yieldValue('Foo#effect');
<ide> });
<ide> return (
<ide> <div>
<ide> describe('ReactUpdates', () => {
<ide> const [step, setStep] = React.useState(0);
<ide> React.useEffect(() => {
<ide> setStep(x => x + 1);
<del> Scheduler.yieldValue(step);
<add> Scheduler.unstable_yieldValue(step);
<ide> });
<ide> return step;
<ide> }
<ide> describe('ReactUpdates', () => {
<ide> React.useEffect(() => {
<ide> if (step < LIMIT) {
<ide> setStep(x => x + 1);
<del> Scheduler.yieldValue(step);
<add> Scheduler.unstable_yieldValue(step);
<ide> }
<ide> });
<ide> return step;
<ide> describe('ReactUpdates', () => {
<ide> for (let i = 0; i < 1000; i++) {
<ide> setStep(x => x + 1);
<ide> }
<del> Scheduler.yieldValue('Done');
<add> Scheduler.unstable_yieldValue('Done');
<ide> }, []);
<ide> return step;
<ide> }
<ide><path>packages/react-dom/src/events/__tests__/ChangeEventPlugin-test.internal.js
<ide> describe('ChangeEventPlugin', () => {
<ide> expect(ops).toEqual([]);
<ide> expect(input).toBe(undefined);
<ide> // Flush callbacks.
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(ops).toEqual(['render: initial']);
<ide> expect(input.value).toBe('initial');
<ide>
<ide> describe('ChangeEventPlugin', () => {
<ide> expect(ops).toEqual([]);
<ide> expect(input).toBe(undefined);
<ide> // Flush callbacks.
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(ops).toEqual(['render: false']);
<ide> expect(input.checked).toBe(false);
<ide>
<ide> describe('ChangeEventPlugin', () => {
<ide>
<ide> // Now let's make sure we're using the controlled value.
<ide> root.render(<ControlledInput reverse={true} />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> ops = [];
<ide>
<ide> describe('ChangeEventPlugin', () => {
<ide> expect(ops).toEqual([]);
<ide> expect(textarea).toBe(undefined);
<ide> // Flush callbacks.
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(ops).toEqual(['render: initial']);
<ide> expect(textarea.value).toBe('initial');
<ide>
<ide> describe('ChangeEventPlugin', () => {
<ide> expect(ops).toEqual([]);
<ide> expect(input).toBe(undefined);
<ide> // Flush callbacks.
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(ops).toEqual(['render: initial']);
<ide> expect(input.value).toBe('initial');
<ide>
<ide> describe('ChangeEventPlugin', () => {
<ide> expect(ops).toEqual([]);
<ide> expect(input).toBe(undefined);
<ide> // Flush callbacks.
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(ops).toEqual(['render: initial']);
<ide> expect(input.value).toBe('initial');
<ide>
<ide> describe('ChangeEventPlugin', () => {
<ide> expect(input.value).toBe('initial');
<ide>
<ide> // Flush callbacks.
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> // Now the click update has flushed.
<ide> expect(ops).toEqual(['render: ']);
<ide> expect(input.value).toBe('');
<ide> describe('ChangeEventPlugin', () => {
<ide> target.current.dispatchEvent(mouseOverEvent);
<ide>
<ide> // 3s should be enough to expire the updates
<del> Scheduler.advanceTime(3000);
<add> Scheduler.unstable_advanceTime(3000);
<ide> expect(container.textContent).toEqual('hovered');
<ide> });
<ide> });
<ide><path>packages/react-dom/src/events/__tests__/SimpleEventPlugin-test.internal.js
<ide> describe('SimpleEventPlugin', function() {
<ide> expect(ops).toEqual([]);
<ide> expect(button).toBe(undefined);
<ide> // Flush async work
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(ops).toEqual(['render button: enabled']);
<ide>
<ide> ops = [];
<ide> describe('SimpleEventPlugin', function() {
<ide> click();
<ide> click();
<ide> click();
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(ops).toEqual([]);
<ide> });
<ide>
<ide> describe('SimpleEventPlugin', function() {
<ide> // Should not have flushed yet because it's async
<ide> expect(button).toBe(undefined);
<ide> // Flush async work
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(button.textContent).toEqual('Count: 0');
<ide>
<ide> function click() {
<ide> describe('SimpleEventPlugin', function() {
<ide> click();
<ide>
<ide> // Flush the remaining work
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> // The counter should equal the total number of clicks
<ide> expect(button.textContent).toEqual('Count: 7');
<ide> });
<ide> describe('SimpleEventPlugin', function() {
<ide> const text = `High-pri count: ${
<ide> this.props.highPriCount
<ide> }, Low-pri count: ${this.state.lowPriCount}`;
<del> Scheduler.yieldValue(text);
<add> Scheduler.unstable_yieldValue(text);
<ide> return (
<ide> <button
<ide> ref={el => (button = el)}
<ide><path>packages/react-dom/src/test-utils/ReactTestUtilsAct.js
<ide> const {ReactCurrentActingRendererSigil} = ReactSharedInternals;
<ide>
<ide> let hasWarnedAboutMissingMockScheduler = false;
<ide> const flushWork =
<del> Scheduler.unstable_flushWithoutYielding ||
<add> Scheduler.unstable_flushAllWithoutAsserting ||
<ide> function() {
<ide> if (warnAboutMissingMockScheduler === true) {
<ide> if (hasWarnedAboutMissingMockScheduler === false) {
<ide><path>packages/react-events/src/dom/__tests__/Hover-test.internal.js
<ide> describe('Hover event responder', () => {
<ide> target.current.dispatchEvent(createEvent('mouseover'));
<ide>
<ide> // 3s should be enough to expire the updates
<del> Scheduler.advanceTime(3000);
<add> Scheduler.unstable_advanceTime(3000);
<ide> expect(newContainer.textContent).toEqual('hovered');
<ide> });
<ide> });
<ide><path>packages/react-events/src/dom/__tests__/Press-test.internal.js
<ide> describe('Event responder: Press', () => {
<ide> const root = ReactDOM.unstable_createRoot(newContainer);
<ide> document.body.appendChild(newContainer);
<ide> root.render(<MyComponent />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> dispatchEventWithTimeStamp(ref.current, 'pointerdown', 100);
<ide> dispatchEventWithTimeStamp(ref.current, 'pointerup', 100);
<ide> describe('Event responder: Press', () => {
<ide> } else {
<ide> expect(renderCounts).toBe(1);
<ide> }
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> if (__DEV__) {
<ide> expect(renderCounts).toBe(4);
<ide> } else {
<ide> describe('Event responder: Press', () => {
<ide> expect(renderCounts).toBe(3);
<ide> }
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> document.body.removeChild(newContainer);
<ide> });
<ide>
<ide> describe('Event responder: Press', () => {
<ide> const root = ReactDOM.unstable_createRoot(newContainer);
<ide> document.body.appendChild(newContainer);
<ide> root.render(<MyComponent />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> dispatchEventWithTimeStamp(ref.current, 'pointerdown', 100);
<ide> dispatchEventWithTimeStamp(ref.current, 'pointerup', 100);
<ide> describe('Event responder: Press', () => {
<ide> } else {
<ide> expect(renderCounts).toBe(2);
<ide> }
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> if (__DEV__) {
<ide> expect(renderCounts).toBe(6);
<ide> } else {
<ide> describe('Event responder: Press', () => {
<ide> expect(renderCounts).toBe(4);
<ide> }
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> document.body.removeChild(newContainer);
<ide> });
<ide>
<ide> describe('Event responder: Press', () => {
<ide> const root = ReactDOM.unstable_createRoot(newContainer);
<ide>
<ide> root.render(<MyComponent />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(newContainer.textContent).toEqual('Presses: 0, Clicks: 0');
<ide>
<ide> dispatchEventWithTimeStamp(button.current, 'pointerdown', 100);
<ide> dispatchEventWithTimeStamp(button.current, 'pointerup', 100);
<ide> dispatchEventWithTimeStamp(button.current, 'click', 100);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(newContainer.textContent).toEqual('Presses: 1, Clicks: 1');
<ide>
<ide> expect(ops).toEqual(['Presses: 0, Clicks: 0']);
<ide><path>packages/react-noop-renderer/src/createReactNoop.js
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide>
<ide> let hasWarnedAboutMissingMockScheduler = false;
<ide> const flushWork =
<del> Scheduler.unstable_flushWithoutYielding ||
<add> Scheduler.unstable_flushAllWithoutAsserting ||
<ide> function() {
<ide> if (warnAboutMissingMockScheduler === true) {
<ide> if (hasWarnedAboutMissingMockScheduler === false) {
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> hostUpdateCounter = 0;
<ide> hostCloneCounter = 0;
<ide> try {
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> return useMutation
<ide> ? {
<ide> hostDiffCounter,
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> }
<ide> },
<ide>
<del> expire: Scheduler.advanceTime,
<add> expire: Scheduler.unstable_advanceTime,
<ide>
<ide> flushExpired(): Array<mixed> {
<ide> return Scheduler.unstable_flushExpired();
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> _next: null,
<ide> };
<ide> root.firstBatch = batch;
<del> Scheduler.unstable_flushWithoutYielding();
<add> Scheduler.unstable_flushAllWithoutAsserting();
<ide> const actual = Scheduler.unstable_clearYields();
<ide> expect(actual).toEqual(expectedFlush);
<ide> return (expectedCommit: Array<mixed>) => {
<ide><path>packages/react-reconciler/src/__tests__/ErrorBoundaryReconciliation-test.internal.js
<ide> describe('ErrorBoundaryReconciliation', () => {
<ide> </ErrorBoundary>,
<ide> {unstable_isConcurrent: isConcurrent},
<ide> );
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(renderer).toMatchRenderedOutput(<span prop="BrokenRender" />);
<ide>
<ide> expect(() => {
<ide> describe('ErrorBoundaryReconciliation', () => {
<ide> <BrokenRender fail={true} />
<ide> </ErrorBoundary>,
<ide> );
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> }).toWarnDev(isConcurrent ? ['invalid', 'invalid'] : ['invalid']);
<ide> const Fallback = fallbackTagName;
<ide> expect(renderer).toMatchRenderedOutput(<Fallback prop="ErrorBoundary" />);
<ide><path>packages/react-reconciler/src/__tests__/ReactBatchedMode-test.internal.js
<ide> describe('ReactBatchedMode', () => {
<ide> TextResource = ReactCache.unstable_createResource(([text, ms = 0]) => {
<ide> return new Promise((resolve, reject) =>
<ide> setTimeout(() => {
<del> Scheduler.yieldValue(`Promise resolved [${text}]`);
<add> Scheduler.unstable_yieldValue(`Promise resolved [${text}]`);
<ide> resolve(text);
<ide> }, ms),
<ide> );
<ide> }, ([text, ms]) => text);
<ide> });
<ide>
<ide> function Text(props) {
<del> Scheduler.yieldValue(props.text);
<add> Scheduler.unstable_yieldValue(props.text);
<ide> return props.text;
<ide> }
<ide>
<ide> function AsyncText(props) {
<ide> const text = props.text;
<ide> try {
<ide> TextResource.read([props.text, props.ms]);
<del> Scheduler.yieldValue(text);
<add> Scheduler.unstable_yieldValue(text);
<ide> return props.text;
<ide> } catch (promise) {
<ide> if (typeof promise.then === 'function') {
<del> Scheduler.yieldValue(`Suspend! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
<ide> } else {
<del> Scheduler.yieldValue(`Error! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Error! [${text}]`);
<ide> }
<ide> throw promise;
<ide> }
<ide> describe('ReactBatchedMode', () => {
<ide>
<ide> function App() {
<ide> useLayoutEffect(() => {
<del> Scheduler.yieldValue('Layout effect');
<add> Scheduler.unstable_yieldValue('Layout effect');
<ide> });
<ide> return <Text text="Hi" />;
<ide> }
<ide><path>packages/react-reconciler/src/__tests__/ReactExpiration-test.internal.js
<ide> describe('ReactExpiration', () => {
<ide> it('two updates of like priority in the same event always flush within the same batch', () => {
<ide> class Text extends React.Component {
<ide> componentDidMount() {
<del> Scheduler.yieldValue(`${this.props.text} [commit]`);
<add> Scheduler.unstable_yieldValue(`${this.props.text} [commit]`);
<ide> }
<ide> componentDidUpdate() {
<del> Scheduler.yieldValue(`${this.props.text} [commit]`);
<add> Scheduler.unstable_yieldValue(`${this.props.text} [commit]`);
<ide> }
<ide> render() {
<del> Scheduler.yieldValue(`${this.props.text} [render]`);
<add> Scheduler.unstable_yieldValue(`${this.props.text} [render]`);
<ide> return <span prop={this.props.text} />;
<ide> }
<ide> }
<ide> describe('ReactExpiration', () => {
<ide> // Schedule an update.
<ide> ReactNoop.render(<Text text="A" />);
<ide> // Advance the timer.
<del> Scheduler.advanceTime(2000);
<add> Scheduler.unstable_advanceTime(2000);
<ide> // Partially flush the the first update, then interrupt it.
<ide> expect(Scheduler).toFlushAndYieldThrough(['A [render]']);
<ide> interrupt();
<ide> describe('ReactExpiration', () => {
<ide> // Now do the same thing again, except this time don't flush any work in
<ide> // between the two updates.
<ide> ReactNoop.render(<Text text="A" />);
<del> Scheduler.advanceTime(2000);
<add> Scheduler.unstable_advanceTime(2000);
<ide> expect(Scheduler).toHaveYielded([]);
<ide> expect(ReactNoop.getChildren()).toEqual([span('B')]);
<ide> // Schedule another update.
<ide> describe('ReactExpiration', () => {
<ide> () => {
<ide> class Text extends React.Component {
<ide> componentDidMount() {
<del> Scheduler.yieldValue(`${this.props.text} [commit]`);
<add> Scheduler.unstable_yieldValue(`${this.props.text} [commit]`);
<ide> }
<ide> componentDidUpdate() {
<del> Scheduler.yieldValue(`${this.props.text} [commit]`);
<add> Scheduler.unstable_yieldValue(`${this.props.text} [commit]`);
<ide> }
<ide> render() {
<del> Scheduler.yieldValue(`${this.props.text} [render]`);
<add> Scheduler.unstable_yieldValue(`${this.props.text} [render]`);
<ide> return <span prop={this.props.text} />;
<ide> }
<ide> }
<ide> describe('ReactExpiration', () => {
<ide> // Schedule an update.
<ide> ReactNoop.render(<Text text="A" />);
<ide> // Advance the timer.
<del> Scheduler.advanceTime(2000);
<add> Scheduler.unstable_advanceTime(2000);
<ide> // Partially flush the the first update, then interrupt it.
<ide> expect(Scheduler).toFlushAndYieldThrough(['A [render]']);
<ide> interrupt();
<ide> describe('ReactExpiration', () => {
<ide> // Now do the same thing again, except this time don't flush any work in
<ide> // between the two updates.
<ide> ReactNoop.render(<Text text="A" />);
<del> Scheduler.advanceTime(2000);
<add> Scheduler.unstable_advanceTime(2000);
<ide> expect(Scheduler).toHaveYielded([]);
<ide> expect(ReactNoop.getChildren()).toEqual([span('B')]);
<ide>
<ide> describe('ReactExpiration', () => {
<ide> state = {text: store.text};
<ide> componentDidMount() {
<ide> subscribers.push(this);
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> `${this.state.text} [${this.props.label}] [commit]`,
<ide> );
<ide> }
<ide> componentDidUpdate() {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> `${this.state.text} [${this.props.label}] [commit]`,
<ide> );
<ide> }
<ide> render() {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> `${this.state.text} [${this.props.label}] [render]`,
<ide> );
<ide> return <span prop={this.state.text} />;
<ide> describe('ReactExpiration', () => {
<ide> // Before importing the renderer, advance the current time by a number
<ide> // larger than the maximum allowed for bitwise operations.
<ide> const maxSigned31BitInt = 1073741823;
<del> Scheduler.advanceTime(maxSigned31BitInt * 100);
<add> Scheduler.unstable_advanceTime(maxSigned31BitInt * 100);
<ide>
<ide> // Now import the renderer. On module initialization, it will read the
<ide> // current time.
<ide> describe('ReactExpiration', () => {
<ide> expect(ReactNoop).toMatchRenderedOutput(null);
<ide>
<ide> // Advance the time some more to expire the update.
<del> Scheduler.advanceTime(10000);
<add> Scheduler.unstable_advanceTime(10000);
<ide> expect(Scheduler).toFlushExpired([]);
<ide> expect(ReactNoop).toMatchRenderedOutput('Hi');
<ide> });
<ide> describe('ReactExpiration', () => {
<ide> // default to 0, and most tests don't advance time.
<ide>
<ide> // Before scheduling an update, advance the current time.
<del> Scheduler.advanceTime(10000);
<add> Scheduler.unstable_advanceTime(10000);
<ide>
<ide> ReactNoop.render('Hi');
<ide> expect(Scheduler).toFlushExpired([]);
<ide> expect(ReactNoop).toMatchRenderedOutput(null);
<ide>
<ide> // Advancing by ~5 seconds should be sufficient to expire the update. (I
<ide> // used a slightly larger number to allow for possible rounding.)
<del> Scheduler.advanceTime(6000);
<add> Scheduler.unstable_advanceTime(6000);
<ide>
<ide> ReactNoop.render('Hi');
<ide> expect(Scheduler).toFlushExpired([]);
<ide><path>packages/react-reconciler/src/__tests__/ReactFiberEvents-test-internal.js
<ide> describe('ReactFiberEvents', () => {
<ide> };
<ide>
<ide> function Async() {
<del> Scheduler.yieldValue('Suspend!');
<add> Scheduler.unstable_yieldValue('Suspend!');
<ide> throw thenable;
<ide> }
<ide>
<ide> function Text(props) {
<del> Scheduler.yieldValue(props.text);
<add> Scheduler.unstable_yieldValue(props.text);
<ide> return props.text;
<ide> }
<ide>
<ide><path>packages/react-reconciler/src/__tests__/ReactHooks-test.internal.js
<ide> describe('ReactHooks', () => {
<ide> const {useState, useLayoutEffect} = React;
<ide>
<ide> function Child({text}) {
<del> Scheduler.yieldValue('Child: ' + text);
<add> Scheduler.unstable_yieldValue('Child: ' + text);
<ide> return text;
<ide> }
<ide>
<ide> describe('ReactHooks', () => {
<ide> setCounter2 = _setCounter2;
<ide>
<ide> const text = `${counter1}, ${counter2}`;
<del> Scheduler.yieldValue(`Parent: ${text}`);
<add> Scheduler.unstable_yieldValue(`Parent: ${text}`);
<ide> useLayoutEffect(() => {
<del> Scheduler.yieldValue(`Effect: ${text}`);
<add> Scheduler.unstable_yieldValue(`Effect: ${text}`);
<ide> });
<ide> return <Child text={text} />;
<ide> }
<ide> describe('ReactHooks', () => {
<ide> const {useState, memo} = React;
<ide>
<ide> function Child({text}) {
<del> Scheduler.yieldValue('Child: ' + text);
<add> Scheduler.unstable_yieldValue('Child: ' + text);
<ide> return text;
<ide> }
<ide>
<ide> describe('ReactHooks', () => {
<ide> setCounter2 = _setCounter2;
<ide>
<ide> const text = `${counter1}, ${counter2} (${theme})`;
<del> Scheduler.yieldValue(`Parent: ${text}`);
<add> Scheduler.unstable_yieldValue(`Parent: ${text}`);
<ide> return <Child text={text} />;
<ide> }
<ide>
<ide> describe('ReactHooks', () => {
<ide> const [counter, _setCounter] = useState(0);
<ide> setCounter = _setCounter;
<ide>
<del> Scheduler.yieldValue(`Count: ${counter}`);
<add> Scheduler.unstable_yieldValue(`Count: ${counter}`);
<ide> return counter;
<ide> }
<ide>
<ide> describe('ReactHooks', () => {
<ide> const [counter, _dispatch] = useReducer((s, a) => a, 0);
<ide> dispatch = _dispatch;
<ide>
<del> Scheduler.yieldValue(`Count: ${counter}`);
<add> Scheduler.unstable_yieldValue(`Count: ${counter}`);
<ide> return counter;
<ide> }
<ide>
<ide> describe('ReactHooks', () => {
<ide> let setTheme;
<ide> function ThemeProvider({children}) {
<ide> const [theme, _setTheme] = useState('light');
<del> Scheduler.yieldValue('Theme: ' + theme);
<add> Scheduler.unstable_yieldValue('Theme: ' + theme);
<ide> setTheme = _setTheme;
<ide> return (
<ide> <ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>
<ide> );
<ide> }
<ide>
<ide> function Child({text}) {
<del> Scheduler.yieldValue('Child: ' + text);
<add> Scheduler.unstable_yieldValue('Child: ' + text);
<ide> return text;
<ide> }
<ide>
<ide> describe('ReactHooks', () => {
<ide> const theme = useContext(ThemeContext);
<ide>
<ide> const text = `${counter} (${theme})`;
<del> Scheduler.yieldValue(`Parent: ${text}`);
<add> Scheduler.unstable_yieldValue(`Parent: ${text}`);
<ide> useLayoutEffect(() => {
<del> Scheduler.yieldValue(`Effect: ${text}`);
<add> Scheduler.unstable_yieldValue(`Effect: ${text}`);
<ide> });
<ide> return <Child text={text} />;
<ide> }
<ide> describe('ReactHooks', () => {
<ide> const {useState, useLayoutEffect} = React;
<ide>
<ide> function Child({text}) {
<del> Scheduler.yieldValue('Child: ' + text);
<add> Scheduler.unstable_yieldValue('Child: ' + text);
<ide> return text;
<ide> }
<ide>
<ide> let setCounter;
<ide> function Parent() {
<ide> const [counter, _setCounter] = useState(0);
<ide> setCounter = _setCounter;
<del> Scheduler.yieldValue('Parent: ' + counter);
<add> Scheduler.unstable_yieldValue('Parent: ' + counter);
<ide> useLayoutEffect(() => {
<del> Scheduler.yieldValue('Effect: ' + counter);
<add> Scheduler.unstable_yieldValue('Effect: ' + counter);
<ide> });
<ide> return <Child text={counter} />;
<ide> }
<ide> describe('ReactHooks', () => {
<ide> const {useState} = React;
<ide>
<ide> function Child({text}) {
<del> Scheduler.yieldValue('Child: ' + text);
<add> Scheduler.unstable_yieldValue('Child: ' + text);
<ide> return text;
<ide> }
<ide>
<ide> let setCounter;
<ide> function Parent() {
<ide> const [counter, _setCounter] = useState(0);
<ide> setCounter = _setCounter;
<del> Scheduler.yieldValue('Parent: ' + counter);
<add> Scheduler.unstable_yieldValue('Parent: ' + counter);
<ide> return <Child text={counter} />;
<ide> }
<ide>
<ide> describe('ReactHooks', () => {
<ide>
<ide> const update = value => {
<ide> setCounter(previous => {
<del> Scheduler.yieldValue(`Compute state (${previous} -> ${value})`);
<add> Scheduler.unstable_yieldValue(
<add> `Compute state (${previous} -> ${value})`,
<add> );
<ide> return value;
<ide> });
<ide> };
<ide> describe('ReactHooks', () => {
<ide> const {useState} = React;
<ide>
<ide> function Child({text}) {
<del> Scheduler.yieldValue('Child: ' + text);
<add> Scheduler.unstable_yieldValue('Child: ' + text);
<ide> return text;
<ide> }
<ide>
<ide> let setCounter;
<ide> function Parent() {
<ide> const [counter, _setCounter] = useState(1);
<ide> setCounter = _setCounter;
<del> Scheduler.yieldValue('Parent: ' + counter);
<add> Scheduler.unstable_yieldValue('Parent: ' + counter);
<ide> return <Child text={counter} />;
<ide> }
<ide>
<ide> describe('ReactHooks', () => {
<ide> const update = compute => {
<ide> setCounter(previous => {
<ide> const value = compute(previous);
<del> Scheduler.yieldValue(`Compute state (${previous} -> ${value})`);
<add> Scheduler.unstable_yieldValue(
<add> `Compute state (${previous} -> ${value})`,
<add> );
<ide> return value;
<ide> });
<ide> };
<ide> describe('ReactHooks', () => {
<ide> const {useLayoutEffect} = React;
<ide> function App(props) {
<ide> useLayoutEffect(() => {
<del> Scheduler.yieldValue('Did commit: ' + props.dependencies.join(', '));
<add> Scheduler.unstable_yieldValue(
<add> 'Did commit: ' + props.dependencies.join(', '),
<add> );
<ide> }, props.dependencies);
<ide> return props.dependencies;
<ide> }
<ide> describe('ReactHooks', () => {
<ide> const {useMemo} = React;
<ide> function App({text, hasDeps}) {
<ide> const resolvedText = useMemo(() => {
<del> Scheduler.yieldValue('Compute');
<add> Scheduler.unstable_yieldValue('Compute');
<ide> return text.toUpperCase();
<ide> }, hasDeps ? null : [text]);
<ide> return resolvedText;
<ide> describe('ReactHooks', () => {
<ide> );
<ide> expect(root).toMatchRenderedOutput('loading');
<ide> await Promise.resolve();
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(root).toMatchRenderedOutput('hello');
<ide> });
<ide>
<ide> describe('ReactHooks', () => {
<ide> );
<ide> expect(root).toMatchRenderedOutput('loading');
<ide> await Promise.resolve();
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(root).toMatchRenderedOutput('hello');
<ide> });
<ide>
<ide> describe('ReactHooks', () => {
<ide> );
<ide> expect(root).toMatchRenderedOutput('loading');
<ide> await Promise.resolve();
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(root).toMatchRenderedOutput('hello');
<ide> });
<ide>
<ide><path>packages/react-reconciler/src/__tests__/ReactHooksWithNoopRenderer-test.internal.js
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> }
<ide>
<ide> function Text(props) {
<del> Scheduler.yieldValue(props.text);
<add> Scheduler.unstable_yieldValue(props.text);
<ide> return <span prop={props.text} />;
<ide> }
<ide>
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> it('lazy state initializer', () => {
<ide> function Counter(props, ref) {
<ide> const [count, updateCount] = useState(() => {
<del> Scheduler.yieldValue('getInitialState');
<add> Scheduler.unstable_yieldValue('getInitialState');
<ide> return props.initialState;
<ide> });
<ide> useImperativeHandle(ref, () => ({updateCount}));
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> if (count < 3) {
<ide> setCount(count + 1);
<ide> }
<del> Scheduler.yieldValue('Render: ' + count);
<add> Scheduler.unstable_yieldValue('Render: ' + count);
<ide> return <Text text={count} />;
<ide> }
<ide>
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> setCount(c => c + 1);
<ide> setCount(c => c + 1);
<ide> }
<del> Scheduler.yieldValue('Render: ' + count);
<add> Scheduler.unstable_yieldValue('Render: ' + count);
<ide> return <Text text={count} />;
<ide> }
<ide>
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> function Counter({row: newRow}) {
<ide> let [count, setCount] = useState(0);
<ide> setCount(count + 1);
<del> Scheduler.yieldValue('Render: ' + count);
<add> Scheduler.unstable_yieldValue('Render: ' + count);
<ide> return <Text text={count} />;
<ide> }
<ide> ReactNoop.render(<Counter />);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> if (count < 3) {
<ide> dispatch('increment');
<ide> }
<del> Scheduler.yieldValue('Render: ' + count);
<add> Scheduler.unstable_yieldValue('Render: ' + count);
<ide> return <Text text={count} />;
<ide> }
<ide>
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> setReducer(() => reducerA);
<ide> }
<ide> }
<del> Scheduler.yieldValue('Render: ' + count);
<add> Scheduler.unstable_yieldValue('Render: ' + count);
<ide> return <Text text={count} />;
<ide> }
<ide> Counter = forwardRef(Counter);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> function Counter(props, ref) {
<ide> const [count, dispatch] = useReducer(reducer, props, p => {
<del> Scheduler.yieldValue('Init');
<add> Scheduler.unstable_yieldValue('Init');
<ide> return p.initialCount;
<ide> });
<ide> useImperativeHandle(ref, () => ({dispatch}));
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> it('simple mount and update', () => {
<ide> function Counter(props) {
<ide> useEffect(() => {
<del> Scheduler.yieldValue(`Passive effect [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Passive effect [${props.count}]`);
<ide> });
<ide> return <Text text={'Count: ' + props.count} />;
<ide> }
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 0', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 1', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 1')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> it('flushes passive effects even with sibling deletions', () => {
<ide> function LayoutEffect(props) {
<ide> useLayoutEffect(() => {
<del> Scheduler.yieldValue(`Layout effect`);
<add> Scheduler.unstable_yieldValue(`Layout effect`);
<ide> });
<ide> return <Text text="Layout" />;
<ide> }
<ide> function PassiveEffect(props) {
<ide> useEffect(() => {
<del> Scheduler.yieldValue(`Passive effect`);
<add> Scheduler.unstable_yieldValue(`Passive effect`);
<ide> }, []);
<ide> return <Text text="Passive" />;
<ide> }
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> it('flushes passive effects even if siblings schedule an update', () => {
<ide> function PassiveEffect(props) {
<ide> useEffect(() => {
<del> Scheduler.yieldValue('Passive effect');
<add> Scheduler.unstable_yieldValue('Passive effect');
<ide> });
<ide> return <Text text="Passive" />;
<ide> }
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> if (count === 0) {
<ide> setCount(1);
<ide> }
<del> Scheduler.yieldValue('Layout effect ' + count);
<add> Scheduler.unstable_yieldValue('Layout effect ' + count);
<ide> });
<ide> return <Text text="Layout" />;
<ide> }
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> it('flushes passive effects even if siblings schedule a new root', () => {
<ide> function PassiveEffect(props) {
<ide> useEffect(() => {
<del> Scheduler.yieldValue('Passive effect');
<add> Scheduler.unstable_yieldValue('Passive effect');
<ide> }, []);
<ide> return <Text text="Passive" />;
<ide> }
<ide> function LayoutEffect(props) {
<ide> useLayoutEffect(() => {
<del> Scheduler.yieldValue('Layout effect');
<add> Scheduler.unstable_yieldValue('Layout effect');
<ide> // Scheduling work shouldn't interfere with the queued passive effect
<ide> ReactNoop.renderToRootWithID(<Text text="New Root" />, 'root2');
<ide> });
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> function Counter(props) {
<ide> useEffect(() => {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> `Committed state when effect was fired: ${getCommittedText()}`,
<ide> );
<ide> });
<ide> return <Text text={props.count} />;
<ide> }
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough([0, 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span(0)]);
<ide> // Before the effects have a chance to flush, schedule another update
<ide> ReactNoop.render(<Counter count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough([
<ide> // The previous effect flushes before the reconciliation
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> const [count, updateCount] = useState('(empty)');
<ide> useEffect(
<ide> () => {
<del> Scheduler.yieldValue(`Schedule update [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Schedule update [${props.count}]`);
<ide> updateCount(props.count);
<ide> },
<ide> [props.count],
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> }
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough([
<ide> 'Count: (empty)',
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 0', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> const [count, updateCount] = useState('(empty)');
<ide> useEffect(
<ide> () => {
<del> Scheduler.yieldValue(`Schedule update [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Schedule update [${props.count}]`);
<ide> updateCount(props.count);
<ide> },
<ide> [props.count],
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> }
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough([
<ide> 'Count: (empty)',
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> // Rendering again should flush the previous commit's effects
<ide> ReactNoop.render(<Counter count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough([
<ide> 'Schedule update [0]',
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> const [count, updateCount] = useState(0);
<ide> _updateCount = updateCount;
<ide> useEffect(() => {
<del> Scheduler.yieldValue(`Will set count to 1`);
<add> Scheduler.unstable_yieldValue(`Will set count to 1`);
<ide> updateCount(1);
<ide> }, []);
<ide> return <Text text={'Count: ' + count} />;
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> // it's a lot harder to simulate this condition inside an act scope
<ide> expect(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 0', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> expect(SchedulerTracing.unstable_getCurrent()).toMatchInteractions([
<ide> tracingEvent,
<ide> ]);
<del> Scheduler.yieldValue(`Will set count to 1`);
<add> Scheduler.unstable_yieldValue(`Will set count to 1`);
<ide> updateCount(1);
<ide> }, []);
<ide> return <Text text={'Count: ' + count} />;
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> tracingEvent.timestamp,
<ide> () => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> },
<ide> );
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> const [count, updateCount] = useState('(empty)');
<ide> useEffect(
<ide> () => {
<del> Scheduler.yieldValue(`Schedule update [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Schedule update [${props.count}]`);
<ide> ReactNoop.flushSync(() => {
<ide> updateCount(props.count);
<ide> });
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> }
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough([
<ide> 'Count: (empty)',
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> it('unmounts previous effect', () => {
<ide> function Counter(props) {
<ide> useEffect(() => {
<del> Scheduler.yieldValue(`Did create [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Did create [${props.count}]`);
<ide> return () => {
<del> Scheduler.yieldValue(`Did destroy [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Did destroy [${props.count}]`);
<ide> };
<ide> });
<ide> return <Text text={'Count: ' + props.count} />;
<ide> }
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 0', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 1', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 1')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> it('unmounts on deletion', () => {
<ide> function Counter(props) {
<ide> useEffect(() => {
<del> Scheduler.yieldValue(`Did create [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Did create [${props.count}]`);
<ide> return () => {
<del> Scheduler.yieldValue(`Did destroy [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Did destroy [${props.count}]`);
<ide> };
<ide> });
<ide> return <Text text={'Count: ' + props.count} />;
<ide> }
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 0', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> it('unmounts on deletion after skipped effect', () => {
<ide> function Counter(props) {
<ide> useEffect(() => {
<del> Scheduler.yieldValue(`Did create [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Did create [${props.count}]`);
<ide> return () => {
<del> Scheduler.yieldValue(`Did destroy [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Did destroy [${props.count}]`);
<ide> };
<ide> }, []);
<ide> return <Text text={'Count: ' + props.count} />;
<ide> }
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 0', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 1', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 1')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> it('always fires effects if no dependencies are provided', () => {
<ide> function effect() {
<del> Scheduler.yieldValue(`Did create`);
<add> Scheduler.unstable_yieldValue(`Did create`);
<ide> return () => {
<del> Scheduler.yieldValue(`Did destroy`);
<add> Scheduler.unstable_yieldValue(`Did destroy`);
<ide> };
<ide> }
<ide> function Counter(props) {
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> }
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 0', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 1', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 1')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> const text = `${props.label}: ${props.count}`;
<ide> useEffect(
<ide> () => {
<del> Scheduler.yieldValue(`Did create [${text}]`);
<add> Scheduler.unstable_yieldValue(`Did create [${text}]`);
<ide> return () => {
<del> Scheduler.yieldValue(`Did destroy [${text}]`);
<add> Scheduler.unstable_yieldValue(`Did destroy [${text}]`);
<ide> };
<ide> },
<ide> [props.label, props.count],
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> }
<ide> act(() => {
<ide> ReactNoop.render(<Counter label="Count" count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 0', 'Sync effect']);
<ide> });
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> act(() => {
<ide> ReactNoop.render(<Counter label="Count" count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> // Count changed
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 1', 'Sync effect']);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> act(() => {
<ide> ReactNoop.render(<Counter label="Count" count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> // Nothing changed, so no effect should have fired
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 1', 'Sync effect']);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> act(() => {
<ide> ReactNoop.render(<Counter label="Total" count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> // Label changed
<ide> expect(Scheduler).toFlushAndYieldThrough(['Total: 1', 'Sync effect']);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> it('multiple effects', () => {
<ide> function Counter(props) {
<ide> useEffect(() => {
<del> Scheduler.yieldValue(`Did commit 1 [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Did commit 1 [${props.count}]`);
<ide> });
<ide> useEffect(() => {
<del> Scheduler.yieldValue(`Did commit 2 [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Did commit 2 [${props.count}]`);
<ide> });
<ide> return <Text text={'Count: ' + props.count} />;
<ide> }
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 0', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 1', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 1')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> it('unmounts all previous effects before creating any new ones', () => {
<ide> function Counter(props) {
<ide> useEffect(() => {
<del> Scheduler.yieldValue(`Mount A [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Mount A [${props.count}]`);
<ide> return () => {
<del> Scheduler.yieldValue(`Unmount A [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Unmount A [${props.count}]`);
<ide> };
<ide> });
<ide> useEffect(() => {
<del> Scheduler.yieldValue(`Mount B [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Mount B [${props.count}]`);
<ide> return () => {
<del> Scheduler.yieldValue(`Unmount B [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Unmount B [${props.count}]`);
<ide> };
<ide> });
<ide> return <Text text={'Count: ' + props.count} />;
<ide> }
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 0', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 1', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 1')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> it('handles errors on mount', () => {
<ide> function Counter(props) {
<ide> useEffect(() => {
<del> Scheduler.yieldValue(`Mount A [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Mount A [${props.count}]`);
<ide> return () => {
<del> Scheduler.yieldValue(`Unmount A [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Unmount A [${props.count}]`);
<ide> };
<ide> });
<ide> useEffect(() => {
<del> Scheduler.yieldValue('Oops!');
<add> Scheduler.unstable_yieldValue('Oops!');
<ide> throw new Error('Oops!');
<ide> // eslint-disable-next-line no-unreachable
<del> Scheduler.yieldValue(`Mount B [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Mount B [${props.count}]`);
<ide> return () => {
<del> Scheduler.yieldValue(`Unmount B [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Unmount B [${props.count}]`);
<ide> };
<ide> });
<ide> return <Text text={'Count: ' + props.count} />;
<ide> }
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 0', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> it('handles errors on update', () => {
<ide> function Counter(props) {
<ide> useEffect(() => {
<del> Scheduler.yieldValue(`Mount A [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Mount A [${props.count}]`);
<ide> return () => {
<del> Scheduler.yieldValue(`Unmount A [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Unmount A [${props.count}]`);
<ide> };
<ide> });
<ide> useEffect(() => {
<ide> if (props.count === 1) {
<del> Scheduler.yieldValue('Oops!');
<add> Scheduler.unstable_yieldValue('Oops!');
<ide> throw new Error('Oops!');
<ide> }
<del> Scheduler.yieldValue(`Mount B [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Mount B [${props.count}]`);
<ide> return () => {
<del> Scheduler.yieldValue(`Unmount B [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Unmount B [${props.count}]`);
<ide> };
<ide> });
<ide> return <Text text={'Count: ' + props.count} />;
<ide> }
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 0', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> act(() => {
<ide> // This update will trigger an errror
<ide> ReactNoop.render(<Counter count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 1', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 1')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> it('handles errors on unmount', () => {
<ide> function Counter(props) {
<ide> useEffect(() => {
<del> Scheduler.yieldValue(`Mount A [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Mount A [${props.count}]`);
<ide> return () => {
<del> Scheduler.yieldValue('Oops!');
<add> Scheduler.unstable_yieldValue('Oops!');
<ide> throw new Error('Oops!');
<ide> // eslint-disable-next-line no-unreachable
<del> Scheduler.yieldValue(`Unmount A [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Unmount A [${props.count}]`);
<ide> };
<ide> });
<ide> useEffect(() => {
<del> Scheduler.yieldValue(`Mount B [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Mount B [${props.count}]`);
<ide> return () => {
<del> Scheduler.yieldValue(`Unmount B [${props.count}]`);
<add> Scheduler.unstable_yieldValue(`Unmount B [${props.count}]`);
<ide> };
<ide> });
<ide> return <Text text={'Count: ' + props.count} />;
<ide> }
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 0', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> act(() => {
<ide> // This update will trigger an errror
<ide> ReactNoop.render(<Counter count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 1', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 1')]);
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> it('works with memo', () => {
<ide> function Counter({count}) {
<ide> useLayoutEffect(() => {
<del> Scheduler.yieldValue('Mount: ' + count);
<del> return () => Scheduler.yieldValue('Unmount: ' + count);
<add> Scheduler.unstable_yieldValue('Mount: ' + count);
<add> return () => Scheduler.unstable_yieldValue('Unmount: ' + count);
<ide> });
<ide> return <Text text={'Count: ' + count} />;
<ide> }
<ide> Counter = memo(Counter);
<ide>
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough([
<ide> 'Count: 0',
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]);
<ide>
<ide> ReactNoop.render(<Counter count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough([
<ide> 'Count: 1',
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> function getCommittedText() {
<ide> const yields = Scheduler.unstable_clearYields();
<ide> const children = ReactNoop.getChildren();
<del> Scheduler.yieldValue(yields);
<add> Scheduler.unstable_yieldValue(yields);
<ide> if (children === null) {
<ide> return null;
<ide> }
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> function Counter(props) {
<ide> useLayoutEffect(() => {
<del> Scheduler.yieldValue(`Current: ${getCommittedText()}`);
<add> Scheduler.unstable_yieldValue(`Current: ${getCommittedText()}`);
<ide> });
<ide> return <Text text={props.count} />;
<ide> }
<ide>
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough([
<ide> [0],
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> expect(ReactNoop.getChildren()).toEqual([span(0)]);
<ide>
<ide> ReactNoop.render(<Counter count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough([
<ide> [1],
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> // intentionally omits a mutation effect.
<ide> committedText = props.count + '';
<ide>
<del> Scheduler.yieldValue(`Mount layout [current: ${committedText}]`);
<add> Scheduler.unstable_yieldValue(
<add> `Mount layout [current: ${committedText}]`,
<add> );
<ide> return () => {
<del> Scheduler.yieldValue(`Unmount layout [current: ${committedText}]`);
<add> Scheduler.unstable_yieldValue(
<add> `Unmount layout [current: ${committedText}]`,
<add> );
<ide> };
<ide> });
<ide> useEffect(() => {
<del> Scheduler.yieldValue(`Mount normal [current: ${committedText}]`);
<add> Scheduler.unstable_yieldValue(
<add> `Mount normal [current: ${committedText}]`,
<add> );
<ide> return () => {
<del> Scheduler.yieldValue(`Unmount normal [current: ${committedText}]`);
<add> Scheduler.unstable_yieldValue(
<add> `Unmount normal [current: ${committedText}]`,
<add> );
<ide> };
<ide> });
<ide> return null;
<ide> }
<ide>
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough([
<ide> 'Mount layout [current: 0]',
<ide> 'Sync effect',
<ide> ]);
<ide> expect(committedText).toEqual('0');
<ide> ReactNoop.render(<Counter count={1} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough([
<ide> 'Mount normal [current: 0]',
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> const text = props.text;
<ide> const capitalizedText = useMemo(
<ide> () => {
<del> Scheduler.yieldValue(`Capitalize '${text}'`);
<add> Scheduler.unstable_yieldValue(`Capitalize '${text}'`);
<ide> return text.toUpperCase();
<ide> },
<ide> [text],
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> }
<ide>
<ide> function computeA() {
<del> Scheduler.yieldValue('compute A');
<add> Scheduler.unstable_yieldValue('compute A');
<ide> return 'A';
<ide> }
<ide>
<ide> function computeB() {
<del> Scheduler.yieldValue('compute B');
<add> Scheduler.unstable_yieldValue('compute B');
<ide> return 'B';
<ide> }
<ide>
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> }
<ide>
<ide> function compute(val) {
<del> Scheduler.yieldValue('compute ' + val);
<add> Scheduler.unstable_yieldValue('compute ' + val);
<ide> return val;
<ide> }
<ide>
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> function App() {
<ide> ping = useDebouncedCallback(
<ide> value => {
<del> Scheduler.yieldValue('ping: ' + value);
<add> Scheduler.unstable_yieldValue('ping: ' + value);
<ide> },
<ide> 100,
<ide> [],
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> it('unmount effects', () => {
<ide> function App(props) {
<ide> useEffect(() => {
<del> Scheduler.yieldValue('Mount A');
<add> Scheduler.unstable_yieldValue('Mount A');
<ide> return () => {
<del> Scheduler.yieldValue('Unmount A');
<add> Scheduler.unstable_yieldValue('Unmount A');
<ide> };
<ide> }, []);
<ide>
<ide> if (props.showMore) {
<ide> useEffect(() => {
<del> Scheduler.yieldValue('Mount B');
<add> Scheduler.unstable_yieldValue('Mount B');
<ide> return () => {
<del> Scheduler.yieldValue('Unmount B');
<add> Scheduler.unstable_yieldValue('Unmount B');
<ide> };
<ide> }, []);
<ide> }
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> act(() => {
<ide> ReactNoop.render(<App showMore={false} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Sync effect']);
<ide> });
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> // This reducer closes over a value from props. If the reducer is not
<ide> // properly updated, the eager reducer will compare to an old value
<ide> // and bail out incorrectly.
<del> Scheduler.yieldValue('Reducer: ' + count);
<add> Scheduler.unstable_yieldValue('Reducer: ' + count);
<ide> return count;
<ide> }, -1);
<ide> useEffect(
<ide> () => {
<del> Scheduler.yieldValue('Effect: ' + count);
<add> Scheduler.unstable_yieldValue('Effect: ' + count);
<ide> dispatch();
<ide> },
<ide> [count],
<ide> );
<del> Scheduler.yieldValue('Render: ' + state);
<add> Scheduler.unstable_yieldValue('Render: ' + state);
<ide> return count;
<ide> }
<ide>
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> setStep(step + 1);
<ide> }
<ide>
<del> Scheduler.yieldValue(`Step: ${step}, Shadow: ${shadow}`);
<add> Scheduler.unstable_yieldValue(`Step: ${step}, Shadow: ${shadow}`);
<ide> return shadow;
<ide> }
<ide>
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> const [count, updateCount] = useState(0);
<ide> _updateCount = updateCount;
<ide> useEffect(() => {
<del> Scheduler.yieldValue(`Will set count to 1`);
<add> Scheduler.unstable_yieldValue(`Will set count to 1`);
<ide> updateCount(1);
<ide> }, []);
<ide> return <Text text={'Count: ' + count} />;
<ide> }
<ide>
<ide> act(() => {
<ide> ReactNoop.render(<Counter count={0} />, () =>
<del> Scheduler.yieldValue('Sync effect'),
<add> Scheduler.unstable_yieldValue('Sync effect'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Count: 0', 'Sync effect']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]);
<ide><path>packages/react-reconciler/src/__tests__/ReactIncremental-test.internal.js
<ide> describe('ReactIncremental', () => {
<ide>
<ide> it('should render a simple component, in steps if needed', () => {
<ide> function Bar() {
<del> Scheduler.yieldValue('Bar');
<add> Scheduler.unstable_yieldValue('Bar');
<ide> return (
<ide> <span>
<ide> <div>Hello World</div>
<ide> describe('ReactIncremental', () => {
<ide> }
<ide>
<ide> function Foo() {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return [<Bar key="a" isBar={true} />, <Bar key="b" isBar={true} />];
<ide> }
<ide>
<del> ReactNoop.render(<Foo />, () => Scheduler.yieldValue('callback'));
<add> ReactNoop.render(<Foo />, () => Scheduler.unstable_yieldValue('callback'));
<ide> // Do one step of work.
<ide> expect(ReactNoop.flushNextYield()).toEqual(['Foo']);
<ide>
<ide> describe('ReactIncremental', () => {
<ide>
<ide> it('can cancel partially rendered work and restart', () => {
<ide> function Bar(props) {
<del> Scheduler.yieldValue('Bar');
<add> Scheduler.unstable_yieldValue('Bar');
<ide> return <div>{props.children}</div>;
<ide> }
<ide>
<ide> function Foo(props) {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <div>
<ide> <Bar>{props.text}</Bar>
<ide> describe('ReactIncremental', () => {
<ide>
<ide> inst.setState(
<ide> () => {
<del> Scheduler.yieldValue('setState1');
<add> Scheduler.unstable_yieldValue('setState1');
<ide> return {text: 'bar'};
<ide> },
<del> () => Scheduler.yieldValue('callback1'),
<add> () => Scheduler.unstable_yieldValue('callback1'),
<ide> );
<ide>
<ide> // Flush part of the work
<ide> describe('ReactIncremental', () => {
<ide> ReactNoop.flushSync(() => ReactNoop.render(<Foo />));
<ide> inst.setState(
<ide> () => {
<del> Scheduler.yieldValue('setState2');
<add> Scheduler.unstable_yieldValue('setState2');
<ide> return {text2: 'baz'};
<ide> },
<del> () => Scheduler.yieldValue('callback2'),
<add> () => Scheduler.unstable_yieldValue('callback2'),
<ide> );
<ide>
<ide> // Flush the rest of the work which now includes the low priority
<ide> describe('ReactIncremental', () => {
<ide>
<ide> it('can deprioritize unfinished work and resume it later', () => {
<ide> function Bar(props) {
<del> Scheduler.yieldValue('Bar');
<add> Scheduler.unstable_yieldValue('Bar');
<ide> return <div>{props.children}</div>;
<ide> }
<ide>
<ide> function Middle(props) {
<del> Scheduler.yieldValue('Middle');
<add> Scheduler.unstable_yieldValue('Middle');
<ide> return <span>{props.children}</span>;
<ide> }
<ide>
<ide> function Foo(props) {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <div>
<ide> <Bar>{props.text}</Bar>
<ide> describe('ReactIncremental', () => {
<ide> class Foo extends React.PureComponent {
<ide> render() {
<ide> const msg = `A: ${a}, B: ${this.props.b}`;
<del> Scheduler.yieldValue(msg);
<add> Scheduler.unstable_yieldValue(msg);
<ide> return msg;
<ide> }
<ide> }
<ide> describe('ReactIncremental', () => {
<ide> class Parent extends React.Component {
<ide> state = {parentRenders: 0};
<ide> static getDerivedStateFromProps(props, prevState) {
<del> Scheduler.yieldValue('getDerivedStateFromProps');
<add> Scheduler.unstable_yieldValue('getDerivedStateFromProps');
<ide> return prevState.parentRenders + 1;
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('Parent');
<add> Scheduler.unstable_yieldValue('Parent');
<ide> return <Child parentRenders={this.state.parentRenders} ref={child} />;
<ide> }
<ide> }
<ide>
<ide> class Child extends React.Component {
<ide> render() {
<del> Scheduler.yieldValue('Child');
<add> Scheduler.unstable_yieldValue('Child');
<ide> return this.props.parentRenders;
<ide> }
<ide> }
<ide> describe('ReactIncremental', () => {
<ide> };
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('Intl ' + JSON.stringify(this.context));
<add> Scheduler.unstable_yieldValue('Intl ' + JSON.stringify(this.context));
<ide> return this.props.children;
<ide> }
<ide> }
<ide> describe('ReactIncremental', () => {
<ide> };
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('Router ' + JSON.stringify(this.context));
<add> Scheduler.unstable_yieldValue('Router ' + JSON.stringify(this.context));
<ide> return this.props.children;
<ide> }
<ide> }
<ide> describe('ReactIncremental', () => {
<ide> locale: PropTypes.string,
<ide> };
<ide> render() {
<del> Scheduler.yieldValue('ShowLocale ' + JSON.stringify(this.context));
<add> Scheduler.unstable_yieldValue(
<add> 'ShowLocale ' + JSON.stringify(this.context),
<add> );
<ide> return this.context.locale;
<ide> }
<ide> }
<ide> describe('ReactIncremental', () => {
<ide> route: PropTypes.string,
<ide> };
<ide> render() {
<del> Scheduler.yieldValue('ShowRoute ' + JSON.stringify(this.context));
<add> Scheduler.unstable_yieldValue(
<add> 'ShowRoute ' + JSON.stringify(this.context),
<add> );
<ide> return this.context.route;
<ide> }
<ide> }
<ide>
<ide> function ShowBoth(props, context) {
<del> Scheduler.yieldValue('ShowBoth ' + JSON.stringify(context));
<add> Scheduler.unstable_yieldValue('ShowBoth ' + JSON.stringify(context));
<ide> return `${context.route} in ${context.locale}`;
<ide> }
<ide> ShowBoth.contextTypes = {
<ide> describe('ReactIncremental', () => {
<ide>
<ide> class ShowNeither extends React.Component {
<ide> render() {
<del> Scheduler.yieldValue('ShowNeither ' + JSON.stringify(this.context));
<add> Scheduler.unstable_yieldValue(
<add> 'ShowNeither ' + JSON.stringify(this.context),
<add> );
<ide> return null;
<ide> }
<ide> }
<ide>
<ide> class Indirection extends React.Component {
<ide> render() {
<del> Scheduler.yieldValue('Indirection ' + JSON.stringify(this.context));
<add> Scheduler.unstable_yieldValue(
<add> 'Indirection ' + JSON.stringify(this.context),
<add> );
<ide> return [
<ide> <ShowLocale key="a" />,
<ide> <ShowRoute key="b" />,
<ide> describe('ReactIncremental', () => {
<ide> };
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('Intl ' + JSON.stringify(this.context));
<add> Scheduler.unstable_yieldValue('Intl ' + JSON.stringify(this.context));
<ide> return this.props.children;
<ide> }
<ide> }
<ide> describe('ReactIncremental', () => {
<ide> locale: PropTypes.string,
<ide> };
<ide> render() {
<del> Scheduler.yieldValue('ShowLocale ' + JSON.stringify(this.context));
<add> Scheduler.unstable_yieldValue(
<add> 'ShowLocale ' + JSON.stringify(this.context),
<add> );
<ide> return this.context.locale;
<ide> }
<ide> }
<ide> describe('ReactIncremental', () => {
<ide>
<ide> it('does not interrupt for update at same priority', () => {
<ide> function Parent(props) {
<del> Scheduler.yieldValue('Parent: ' + props.step);
<add> Scheduler.unstable_yieldValue('Parent: ' + props.step);
<ide> return <Child step={props.step} />;
<ide> }
<ide>
<ide> function Child(props) {
<del> Scheduler.yieldValue('Child: ' + props.step);
<add> Scheduler.unstable_yieldValue('Child: ' + props.step);
<ide> return null;
<ide> }
<ide>
<ide> describe('ReactIncremental', () => {
<ide>
<ide> it('does not interrupt for update at lower priority', () => {
<ide> function Parent(props) {
<del> Scheduler.yieldValue('Parent: ' + props.step);
<add> Scheduler.unstable_yieldValue('Parent: ' + props.step);
<ide> return <Child step={props.step} />;
<ide> }
<ide>
<ide> function Child(props) {
<del> Scheduler.yieldValue('Child: ' + props.step);
<add> Scheduler.unstable_yieldValue('Child: ' + props.step);
<ide> return null;
<ide> }
<ide>
<ide> describe('ReactIncremental', () => {
<ide>
<ide> it('does interrupt for update at higher priority', () => {
<ide> function Parent(props) {
<del> Scheduler.yieldValue('Parent: ' + props.step);
<add> Scheduler.unstable_yieldValue('Parent: ' + props.step);
<ide> return <Child step={props.step} />;
<ide> }
<ide>
<ide> function Child(props) {
<del> Scheduler.yieldValue('Child: ' + props.step);
<add> Scheduler.unstable_yieldValue('Child: ' + props.step);
<ide> return null;
<ide> }
<ide>
<ide><path>packages/react-reconciler/src/__tests__/ReactIncrementalErrorHandling-test.internal.js
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> class ErrorBoundary extends React.Component {
<ide> state = {error: null};
<ide> static getDerivedStateFromError(error) {
<del> Scheduler.yieldValue('getDerivedStateFromError');
<add> Scheduler.unstable_yieldValue('getDerivedStateFromError');
<ide> return {error};
<ide> }
<ide> render() {
<ide> if (this.state.error) {
<del> Scheduler.yieldValue('ErrorBoundary (catch)');
<add> Scheduler.unstable_yieldValue('ErrorBoundary (catch)');
<ide> return <ErrorMessage error={this.state.error} />;
<ide> }
<del> Scheduler.yieldValue('ErrorBoundary (try)');
<add> Scheduler.unstable_yieldValue('ErrorBoundary (try)');
<ide> return this.props.children;
<ide> }
<ide> }
<ide>
<ide> function ErrorMessage(props) {
<del> Scheduler.yieldValue('ErrorMessage');
<add> Scheduler.unstable_yieldValue('ErrorMessage');
<ide> return <span prop={`Caught an error: ${props.error.message}`} />;
<ide> }
<ide>
<ide> function Indirection(props) {
<del> Scheduler.yieldValue('Indirection');
<add> Scheduler.unstable_yieldValue('Indirection');
<ide> return props.children || null;
<ide> }
<ide>
<ide> function BadRender() {
<del> Scheduler.yieldValue('throw');
<add> Scheduler.unstable_yieldValue('throw');
<ide> throw new Error('oops!');
<ide> }
<ide>
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> class ErrorBoundary extends React.Component {
<ide> state = {error: null};
<ide> componentDidCatch(error) {
<del> Scheduler.yieldValue('componentDidCatch');
<add> Scheduler.unstable_yieldValue('componentDidCatch');
<ide> this.setState({error});
<ide> }
<ide> render() {
<ide> if (this.state.error) {
<del> Scheduler.yieldValue('ErrorBoundary (catch)');
<add> Scheduler.unstable_yieldValue('ErrorBoundary (catch)');
<ide> return <ErrorMessage error={this.state.error} />;
<ide> }
<del> Scheduler.yieldValue('ErrorBoundary (try)');
<add> Scheduler.unstable_yieldValue('ErrorBoundary (try)');
<ide> return this.props.children;
<ide> }
<ide> }
<ide>
<ide> function ErrorMessage(props) {
<del> Scheduler.yieldValue('ErrorMessage');
<add> Scheduler.unstable_yieldValue('ErrorMessage');
<ide> return <span prop={`Caught an error: ${props.error.message}`} />;
<ide> }
<ide>
<ide> function Indirection(props) {
<del> Scheduler.yieldValue('Indirection');
<add> Scheduler.unstable_yieldValue('Indirection');
<ide> return props.children || null;
<ide> }
<ide>
<ide> function BadRender() {
<del> Scheduler.yieldValue('throw');
<add> Scheduler.unstable_yieldValue('throw');
<ide> throw new Error('oops!');
<ide> }
<ide>
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> it("retries at a lower priority if there's additional pending work", () => {
<ide> function App(props) {
<ide> if (props.isBroken) {
<del> Scheduler.yieldValue('error');
<add> Scheduler.unstable_yieldValue('error');
<ide> throw new Error('Oops!');
<ide> }
<del> Scheduler.yieldValue('success');
<add> Scheduler.unstable_yieldValue('success');
<ide> return <span prop="Everything is fine." />;
<ide> }
<ide>
<ide> function onCommit() {
<del> Scheduler.yieldValue('commit');
<add> Scheduler.unstable_yieldValue('commit');
<ide> }
<ide>
<ide> function interrupt() {
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> }
<ide>
<ide> ReactNoop.render(<App isBroken={true} />, onCommit);
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['error']);
<ide> interrupt();
<ide>
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> class Parent extends React.Component {
<ide> state = {hideChild: false};
<ide> componentDidUpdate() {
<del> Scheduler.yieldValue('commit: ' + this.state.hideChild);
<add> Scheduler.unstable_yieldValue('commit: ' + this.state.hideChild);
<ide> }
<ide> render() {
<ide> if (this.state.hideChild) {
<del> Scheduler.yieldValue('(empty)');
<add> Scheduler.unstable_yieldValue('(empty)');
<ide> return <span prop="(empty)" />;
<ide> }
<ide> return <Child isBroken={this.props.childIsBroken} />;
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide>
<ide> function Child(props) {
<ide> if (props.isBroken) {
<del> Scheduler.yieldValue('Error!');
<add> Scheduler.unstable_yieldValue('Error!');
<ide> throw new Error('Error!');
<ide> }
<del> Scheduler.yieldValue('Child');
<add> Scheduler.unstable_yieldValue('Child');
<ide> return <span prop="Child" />;
<ide> }
<ide>
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide>
<ide> it('retries one more time before handling error', () => {
<ide> function BadRender() {
<del> Scheduler.yieldValue('BadRender');
<add> Scheduler.unstable_yieldValue('BadRender');
<ide> throw new Error('oops');
<ide> }
<ide>
<ide> function Sibling() {
<del> Scheduler.yieldValue('Sibling');
<add> Scheduler.unstable_yieldValue('Sibling');
<ide> return <span prop="Sibling" />;
<ide> }
<ide>
<ide> function Parent() {
<del> Scheduler.yieldValue('Parent');
<add> Scheduler.unstable_yieldValue('Parent');
<ide> return (
<ide> <React.Fragment>
<ide> <BadRender />
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> );
<ide> }
<ide>
<del> ReactNoop.render(<Parent />, () => Scheduler.yieldValue('commit'));
<add> ReactNoop.render(<Parent />, () => Scheduler.unstable_yieldValue('commit'));
<ide>
<ide> // Render the bad component asynchronously
<ide> expect(Scheduler).toFlushAndYieldThrough(['Parent', 'BadRender']);
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> throw new Error(`Error ${++id}`);
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('BadMount');
<add> Scheduler.unstable_yieldValue('BadMount');
<ide> return null;
<ide> }
<ide> }
<ide>
<ide> class ErrorBoundary extends React.Component {
<ide> state = {errorCount: 0};
<ide> componentDidCatch(error) {
<del> Scheduler.yieldValue(`componentDidCatch: ${error.message}`);
<add> Scheduler.unstable_yieldValue(`componentDidCatch: ${error.message}`);
<ide> this.setState(state => ({errorCount: state.errorCount + 1}));
<ide> }
<ide> render() {
<ide> if (this.state.errorCount > 0) {
<ide> return <span prop={`Number of errors: ${this.state.errorCount}`} />;
<ide> }
<del> Scheduler.yieldValue('ErrorBoundary');
<add> Scheduler.unstable_yieldValue('ErrorBoundary');
<ide> return this.props.children;
<ide> }
<ide> }
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> class ErrorBoundary extends React.Component {
<ide> state = {error: null};
<ide> componentDidCatch(error) {
<del> Scheduler.yieldValue('ErrorBoundary componentDidCatch');
<add> Scheduler.unstable_yieldValue('ErrorBoundary componentDidCatch');
<ide> this.setState({error});
<ide> }
<ide> render() {
<ide> if (this.state.error) {
<del> Scheduler.yieldValue('ErrorBoundary render error');
<add> Scheduler.unstable_yieldValue('ErrorBoundary render error');
<ide> return (
<ide> <span prop={`Caught an error: ${this.state.error.message}.`} />
<ide> );
<ide> }
<del> Scheduler.yieldValue('ErrorBoundary render success');
<add> Scheduler.unstable_yieldValue('ErrorBoundary render success');
<ide> return this.props.children;
<ide> }
<ide> }
<ide>
<ide> function BrokenRender(props) {
<del> Scheduler.yieldValue('BrokenRender');
<add> Scheduler.unstable_yieldValue('BrokenRender');
<ide> throw new Error('Hello');
<ide> }
<ide>
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> it('propagates an error from a noop error boundary during partial deferred mounting', () => {
<ide> class RethrowErrorBoundary extends React.Component {
<ide> componentDidCatch(error) {
<del> Scheduler.yieldValue('RethrowErrorBoundary componentDidCatch');
<add> Scheduler.unstable_yieldValue('RethrowErrorBoundary componentDidCatch');
<ide> throw error;
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('RethrowErrorBoundary render');
<add> Scheduler.unstable_yieldValue('RethrowErrorBoundary render');
<ide> return this.props.children;
<ide> }
<ide> }
<ide>
<ide> function BrokenRender() {
<del> Scheduler.yieldValue('BrokenRender');
<add> Scheduler.unstable_yieldValue('BrokenRender');
<ide> throw new Error('Hello');
<ide> }
<ide>
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> });
<ide> });
<ide> }).toThrow('Hello');
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(ReactNoop.getChildren()).toEqual([span('a:3')]);
<ide> });
<ide>
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> it('should not attempt to recover an unmounting error boundary', () => {
<ide> class Parent extends React.Component {
<ide> componentWillUnmount() {
<del> Scheduler.yieldValue('Parent componentWillUnmount');
<add> Scheduler.unstable_yieldValue('Parent componentWillUnmount');
<ide> }
<ide> render() {
<ide> return <Boundary />;
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide>
<ide> class Boundary extends React.Component {
<ide> componentDidCatch(e) {
<del> Scheduler.yieldValue(`Caught error: ${e.message}`);
<add> Scheduler.unstable_yieldValue(`Caught error: ${e.message}`);
<ide> }
<ide> render() {
<ide> return <ThrowsOnUnmount />;
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide>
<ide> class ThrowsOnUnmount extends React.Component {
<ide> componentWillUnmount() {
<del> Scheduler.yieldValue('ThrowsOnUnmount componentWillUnmount');
<add> Scheduler.unstable_yieldValue('ThrowsOnUnmount componentWillUnmount');
<ide> throw new Error('unmount error');
<ide> }
<ide> render() {
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> class ErrorBoundary extends React.Component {
<ide> state = {error: null};
<ide> componentDidCatch(error) {
<del> Scheduler.yieldValue('componentDidCatch');
<add> Scheduler.unstable_yieldValue('componentDidCatch');
<ide> this.setState({error});
<ide> }
<ide> render() {
<ide> if (this.state.error) {
<del> Scheduler.yieldValue('ErrorBoundary (catch)');
<add> Scheduler.unstable_yieldValue('ErrorBoundary (catch)');
<ide> return <ErrorMessage error={this.state.error} />;
<ide> }
<del> Scheduler.yieldValue('ErrorBoundary (try)');
<add> Scheduler.unstable_yieldValue('ErrorBoundary (try)');
<ide> return this.props.children;
<ide> }
<ide> }
<ide>
<ide> function ErrorMessage(props) {
<del> Scheduler.yieldValue('ErrorMessage');
<add> Scheduler.unstable_yieldValue('ErrorMessage');
<ide> return <span prop={`Caught an error: ${props.error.message}`} />;
<ide> }
<ide>
<ide> function BadRenderSibling(props) {
<del> Scheduler.yieldValue('BadRenderSibling');
<add> Scheduler.unstable_yieldValue('BadRenderSibling');
<ide> return null;
<ide> }
<ide>
<ide> function BadRender() {
<del> Scheduler.yieldValue('throw');
<add> Scheduler.unstable_yieldValue('throw');
<ide> throw new Error('oops!');
<ide> }
<ide>
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> // where we checked for the existence of didUpdate instead of didMount, and
<ide> // didMount was not defined.
<ide> function BadRender() {
<del> Scheduler.yieldValue('throw');
<add> Scheduler.unstable_yieldValue('throw');
<ide> throw new Error('oops!');
<ide> }
<ide>
<ide> class Parent extends React.Component {
<ide> state = {error: null, other: false};
<ide> componentDidCatch(error) {
<del> Scheduler.yieldValue('did catch');
<add> Scheduler.unstable_yieldValue('did catch');
<ide> this.setState({error});
<ide> }
<ide> componentDidUpdate() {
<del> Scheduler.yieldValue('did update');
<add> Scheduler.unstable_yieldValue('did update');
<ide> }
<ide> render() {
<ide> if (this.state.error) {
<del> Scheduler.yieldValue('render error message');
<add> Scheduler.unstable_yieldValue('render error message');
<ide> return <span prop={`Caught an error: ${this.state.error.message}`} />;
<ide> }
<del> Scheduler.yieldValue('render');
<add> Scheduler.unstable_yieldValue('render');
<ide> return <BadRender />;
<ide> }
<ide> }
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> }
<ide> render() {
<ide> if (this.state.errorInfo) {
<del> Scheduler.yieldValue('render error message');
<add> Scheduler.unstable_yieldValue('render error message');
<ide> return (
<ide> <span
<ide> prop={`Caught an error:${normalizeCodeLocInfo(
<ide><path>packages/react-reconciler/src/__tests__/ReactIncrementalErrorLogging-test.js
<ide> describe('ReactIncrementalErrorLogging', () => {
<ide> this.setState({step: 1});
<ide> }
<ide> componentWillUnmount() {
<del> Scheduler.yieldValue('componentWillUnmount: ' + this.state.step);
<add> Scheduler.unstable_yieldValue(
<add> 'componentWillUnmount: ' + this.state.step,
<add> );
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('render: ' + this.state.step);
<add> Scheduler.unstable_yieldValue('render: ' + this.state.step);
<ide> if (this.state.step > 0) {
<ide> throw new Error('oops');
<ide> }
<ide><path>packages/react-reconciler/src/__tests__/ReactIncrementalPerf-test.internal.js
<ide> describe('ReactDebugFiberPerf', () => {
<ide> it('measures deferred work in chunks', () => {
<ide> class A extends React.Component {
<ide> render() {
<del> Scheduler.yieldValue('A');
<add> Scheduler.unstable_yieldValue('A');
<ide> return <div>{this.props.children}</div>;
<ide> }
<ide> }
<ide>
<ide> class B extends React.Component {
<ide> render() {
<del> Scheduler.yieldValue('B');
<add> Scheduler.unstable_yieldValue('B');
<ide> return <div>{this.props.children}</div>;
<ide> }
<ide> }
<ide>
<ide> class C extends React.Component {
<ide> render() {
<del> Scheduler.yieldValue('C');
<add> Scheduler.unstable_yieldValue('C');
<ide> return <div>{this.props.children}</div>;
<ide> }
<ide> }
<ide> describe('ReactDebugFiberPerf', () => {
<ide>
<ide> it('warns if an in-progress update is interrupted', () => {
<ide> function Foo() {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return <span />;
<ide> }
<ide>
<ide><path>packages/react-reconciler/src/__tests__/ReactIncrementalReflection-test.internal.js
<ide> describe('ReactIncrementalReflection', () => {
<ide> }
<ide> UNSAFE_componentWillMount() {
<ide> instances.push(this);
<del> Scheduler.yieldValue('componentWillMount: ' + this._isMounted());
<add> Scheduler.unstable_yieldValue(
<add> 'componentWillMount: ' + this._isMounted(),
<add> );
<ide> }
<ide> componentDidMount() {
<del> Scheduler.yieldValue('componentDidMount: ' + this._isMounted());
<add> Scheduler.unstable_yieldValue(
<add> 'componentDidMount: ' + this._isMounted(),
<add> );
<ide> }
<ide> render() {
<ide> return <span />;
<ide> describe('ReactIncrementalReflection', () => {
<ide> instances.push(this);
<ide> }
<ide> componentWillUnmount() {
<del> Scheduler.yieldValue('componentWillUnmount: ' + this._isMounted());
<add> Scheduler.unstable_yieldValue(
<add> 'componentWillUnmount: ' + this._isMounted(),
<add> );
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('Component');
<add> Scheduler.unstable_yieldValue('Component');
<ide> return <span />;
<ide> }
<ide> }
<ide>
<ide> function Other() {
<del> Scheduler.yieldValue('Other');
<add> Scheduler.unstable_yieldValue('Other');
<ide> return <span />;
<ide> }
<ide>
<ide> describe('ReactIncrementalReflection', () => {
<ide> class Component extends React.Component {
<ide> UNSAFE_componentWillMount() {
<ide> classInstance = this;
<del> Scheduler.yieldValue(['componentWillMount', findInstance(this)]);
<add> Scheduler.unstable_yieldValue([
<add> 'componentWillMount',
<add> findInstance(this),
<add> ]);
<ide> }
<ide> componentDidMount() {
<del> Scheduler.yieldValue(['componentDidMount', findInstance(this)]);
<add> Scheduler.unstable_yieldValue([
<add> 'componentDidMount',
<add> findInstance(this),
<add> ]);
<ide> }
<ide> UNSAFE_componentWillUpdate() {
<del> Scheduler.yieldValue(['componentWillUpdate', findInstance(this)]);
<add> Scheduler.unstable_yieldValue([
<add> 'componentWillUpdate',
<add> findInstance(this),
<add> ]);
<ide> }
<ide> componentDidUpdate() {
<del> Scheduler.yieldValue(['componentDidUpdate', findInstance(this)]);
<add> Scheduler.unstable_yieldValue([
<add> 'componentDidUpdate',
<add> findInstance(this),
<add> ]);
<ide> }
<ide> componentWillUnmount() {
<del> Scheduler.yieldValue(['componentWillUnmount', findInstance(this)]);
<add> Scheduler.unstable_yieldValue([
<add> 'componentWillUnmount',
<add> findInstance(this),
<add> ]);
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('render');
<add> Scheduler.unstable_yieldValue('render');
<ide> return this.props.step < 2 ? (
<ide> <span ref={ref => (this.span = ref)} />
<ide> ) : this.props.step === 2 ? (
<ide> describe('ReactIncrementalReflection', () => {
<ide>
<ide> function Sibling() {
<ide> // Sibling is used to assert that we've rendered past the first component.
<del> Scheduler.yieldValue('render sibling');
<add> Scheduler.unstable_yieldValue('render sibling');
<ide> return <span />;
<ide> }
<ide>
<ide><path>packages/react-reconciler/src/__tests__/ReactIncrementalScheduling-test.internal.js
<ide> describe('ReactIncrementalScheduling', () => {
<ide> function Text({text}) {
<ide> useEffect(
<ide> () => {
<del> Scheduler.yieldValue(text);
<add> Scheduler.unstable_yieldValue(text);
<ide> },
<ide> [text],
<ide> );
<ide> describe('ReactIncrementalScheduling', () => {
<ide> state = {tick: 0};
<ide>
<ide> componentDidMount() {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> 'componentDidMount (before setState): ' + this.state.tick,
<ide> );
<ide> this.setState({tick: 1});
<ide> // We're in a batch. Update hasn't flushed yet.
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> 'componentDidMount (after setState): ' + this.state.tick,
<ide> );
<ide> }
<ide>
<ide> componentDidUpdate() {
<del> Scheduler.yieldValue('componentDidUpdate: ' + this.state.tick);
<add> Scheduler.unstable_yieldValue('componentDidUpdate: ' + this.state.tick);
<ide> if (this.state.tick === 2) {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> 'componentDidUpdate (before setState): ' + this.state.tick,
<ide> );
<ide> this.setState({tick: 3});
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> 'componentDidUpdate (after setState): ' + this.state.tick,
<ide> );
<ide> // We're in a batch. Update hasn't flushed yet.
<ide> }
<ide> }
<ide>
<ide> render() {
<del> Scheduler.yieldValue('render: ' + this.state.tick);
<add> Scheduler.unstable_yieldValue('render: ' + this.state.tick);
<ide> instance = this;
<ide> return <span prop={this.state.tick} />;
<ide> }
<ide> describe('ReactIncrementalScheduling', () => {
<ide>
<ide> componentDidMount() {
<ide> ReactNoop.deferredUpdates(() => {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> 'componentDidMount (before setState): ' + this.state.tick,
<ide> );
<ide> this.setState({tick: 1});
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> 'componentDidMount (after setState): ' + this.state.tick,
<ide> );
<ide> });
<ide> }
<ide>
<ide> componentDidUpdate() {
<ide> ReactNoop.deferredUpdates(() => {
<del> Scheduler.yieldValue('componentDidUpdate: ' + this.state.tick);
<add> Scheduler.unstable_yieldValue(
<add> 'componentDidUpdate: ' + this.state.tick,
<add> );
<ide> if (this.state.tick === 2) {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> 'componentDidUpdate (before setState): ' + this.state.tick,
<ide> );
<ide> this.setState({tick: 3});
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> 'componentDidUpdate (after setState): ' + this.state.tick,
<ide> );
<ide> }
<ide> });
<ide> }
<ide>
<ide> render() {
<del> Scheduler.yieldValue('render: ' + this.state.tick);
<add> Scheduler.unstable_yieldValue('render: ' + this.state.tick);
<ide> instance = this;
<ide> return <span prop={this.state.tick} />;
<ide> }
<ide> describe('ReactIncrementalScheduling', () => {
<ide> });
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return <span prop={this.state.step} />;
<ide> }
<ide> }
<ide><path>packages/react-reconciler/src/__tests__/ReactIncrementalSideEffects-test.internal.js
<ide> describe('ReactIncrementalSideEffects', () => {
<ide>
<ide> it('does not update child nodes if a flush is aborted', () => {
<ide> function Bar(props) {
<del> Scheduler.yieldValue('Bar');
<add> Scheduler.unstable_yieldValue('Bar');
<ide> return <span prop={props.text} />;
<ide> }
<ide>
<ide> function Foo(props) {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <div>
<ide> <div>
<ide> describe('ReactIncrementalSideEffects', () => {
<ide>
<ide> it('preserves a previously rendered node when deprioritized', () => {
<ide> function Middle(props) {
<del> Scheduler.yieldValue('Middle');
<add> Scheduler.unstable_yieldValue('Middle');
<ide> return <span prop={props.children} />;
<ide> }
<ide>
<ide> function Foo(props) {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <div>
<ide> <div hidden={true}>
<ide> describe('ReactIncrementalSideEffects', () => {
<ide> </div>,
<ide> );
<ide>
<del> ReactNoop.render(<Foo text="bar" />, () => Scheduler.yieldValue('commit'));
<add> ReactNoop.render(<Foo text="bar" />, () =>
<add> Scheduler.unstable_yieldValue('commit'),
<add> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Foo', 'commit']);
<ide> expect(ReactNoop.getChildrenAsJSX()).toEqual(
<ide> <div>
<ide> describe('ReactIncrementalSideEffects', () => {
<ide>
<ide> it('can reuse side-effects after being preempted', () => {
<ide> function Bar(props) {
<del> Scheduler.yieldValue('Bar');
<add> Scheduler.unstable_yieldValue('Bar');
<ide> return <span prop={props.children} />;
<ide> }
<ide>
<ide> describe('ReactIncrementalSideEffects', () => {
<ide> );
<ide>
<ide> function Foo(props) {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <div hidden={true}>
<ide> {props.step === 0 ? (
<ide> describe('ReactIncrementalSideEffects', () => {
<ide> // Make a quick update which will schedule low priority work to
<ide> // update the middle content.
<ide> ReactNoop.render(<Foo text="bar" step={1} />, () =>
<del> Scheduler.yieldValue('commit'),
<add> Scheduler.unstable_yieldValue('commit'),
<ide> );
<ide> expect(Scheduler).toFlushAndYieldThrough(['Foo', 'commit', 'Bar']);
<ide>
<ide> describe('ReactIncrementalSideEffects', () => {
<ide> return this.props.children !== nextProps.children;
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('Bar');
<add> Scheduler.unstable_yieldValue('Bar');
<ide> return <span prop={this.props.children} />;
<ide> }
<ide> }
<ide> describe('ReactIncrementalSideEffects', () => {
<ide> return this.props.step !== nextProps.step;
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('Content');
<add> Scheduler.unstable_yieldValue('Content');
<ide> return (
<ide> <div>
<ide> <Bar>{this.props.step === 0 ? 'Hi' : 'Hello'}</Bar>
<ide> describe('ReactIncrementalSideEffects', () => {
<ide> }
<ide>
<ide> function Foo(props) {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <div hidden={true}>
<ide> <Content step={props.step} text={props.text} />
<ide> describe('ReactIncrementalSideEffects', () => {
<ide>
<ide> it('can update a completed tree before it has a chance to commit', () => {
<ide> function Foo(props) {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return <span prop={props.step} />;
<ide> }
<ide> ReactNoop.render(<Foo step={1} />);
<ide> describe('ReactIncrementalSideEffects', () => {
<ide> this.setState({active: true});
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('Bar');
<add> Scheduler.unstable_yieldValue('Bar');
<ide> return <span prop={this.state.active ? 'X' : this.props.idx} />;
<ide> }
<ide> }
<ide> function Foo(props) {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <div>
<ide> <span prop={props.tick} />
<ide><path>packages/react-reconciler/src/__tests__/ReactIncrementalTriangle-test.internal.js
<ide> describe('ReactIncrementalTriangle', () => {
<ide> }
<ide> render() {
<ide> if (yieldAfterEachRender) {
<del> Scheduler.yieldValue(this);
<add> Scheduler.unstable_yieldValue(this);
<ide> }
<ide> const {counter, remainingDepth} = this.props;
<ide> return (
<ide> describe('ReactIncrementalTriangle', () => {
<ide> } else {
<ide> ReactNoop.render(<App remainingDepth={MAX_DEPTH} key={keyCounter++} />);
<ide> }
<del> Scheduler.unstable_flushWithoutYielding();
<add> Scheduler.unstable_flushAllWithoutAsserting();
<ide> assertConsistentTree();
<ide> return appInstance;
<ide> }
<ide> describe('ReactIncrementalTriangle', () => {
<ide> Scheduler.unstable_flushNumberOfYields(action.unitsOfWork);
<ide> break;
<ide> case FLUSH_ALL:
<del> Scheduler.unstable_flushWithoutYielding();
<add> Scheduler.unstable_flushAllWithoutAsserting();
<ide> break;
<ide> case STEP:
<ide> ReactNoop.deferredUpdates(() => {
<ide> describe('ReactIncrementalTriangle', () => {
<ide> assertConsistentTree(activeLeafIndices);
<ide> }
<ide> // Flush remaining work
<del> Scheduler.unstable_flushWithoutYielding();
<add> Scheduler.unstable_flushAllWithoutAsserting();
<ide> assertConsistentTree(activeLeafIndices, expectedCounterAtEnd);
<ide> }
<ide>
<ide><path>packages/react-reconciler/src/__tests__/ReactIncrementalUpdates-test.internal.js
<ide> describe('ReactIncrementalUpdates', () => {
<ide> class Foo extends React.Component {
<ide> state = {};
<ide> componentDidMount() {
<del> Scheduler.yieldValue('commit');
<add> Scheduler.unstable_yieldValue('commit');
<ide> ReactNoop.deferredUpdates(() => {
<ide> // Has low priority
<ide> this.setState({b: 'b'});
<ide> describe('ReactIncrementalUpdates', () => {
<ide>
<ide> function createUpdate(letter) {
<ide> return () => {
<del> Scheduler.yieldValue(letter);
<add> Scheduler.unstable_yieldValue(letter);
<ide> return {
<ide> [letter]: letter,
<ide> };
<ide> describe('ReactIncrementalUpdates', () => {
<ide>
<ide> function createUpdate(letter) {
<ide> return () => {
<del> Scheduler.yieldValue(letter);
<add> Scheduler.unstable_yieldValue(letter);
<ide> return {
<ide> [letter]: letter,
<ide> };
<ide> describe('ReactIncrementalUpdates', () => {
<ide> const {useEffect} = React;
<ide>
<ide> function App({label}) {
<del> Scheduler.yieldValue('Render: ' + label);
<add> Scheduler.unstable_yieldValue('Render: ' + label);
<ide> useEffect(() => {
<del> Scheduler.yieldValue('Commit: ' + label);
<add> Scheduler.unstable_yieldValue('Commit: ' + label);
<ide> });
<ide> return label;
<ide> }
<ide> describe('ReactIncrementalUpdates', () => {
<ide> // updates in separate batches are all flushed in the same callback
<ide> ReactNoop.act(() => {
<ide> ReactNoop.render(<App label="" />);
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['Render: ']);
<ide> interrupt();
<ide>
<ide> ReactNoop.render(<App label="he" />);
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['Render: ']);
<ide> interrupt();
<ide>
<ide> ReactNoop.render(<App label="hell" />);
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['Render: ']);
<ide> interrupt();
<ide>
<ide> ReactNoop.render(<App label="hello" />);
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['Render: ']);
<ide> interrupt();
<ide>
<ide> describe('ReactIncrementalUpdates', () => {
<ide> // Now do the same thing over again, but this time, expire all the updates
<ide> // instead of flushing them normally.
<ide> ReactNoop.render(<App label="" />);
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['Render: ']);
<ide> interrupt();
<ide>
<ide> ReactNoop.render(<App label="go" />);
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['Render: ']);
<ide> interrupt();
<ide>
<ide> ReactNoop.render(<App label="good" />);
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['Render: ']);
<ide> interrupt();
<ide>
<ide> ReactNoop.render(<App label="goodbye" />);
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['Render: ']);
<ide> interrupt();
<ide>
<ide> // All the updates should render and commit in a single batch.
<del> Scheduler.advanceTime(10000);
<add> Scheduler.unstable_advanceTime(10000);
<ide> expect(Scheduler).toHaveYielded(['Render: goodbye']);
<ide> // Passive effect
<ide> expect(Scheduler).toFlushAndYield(['Commit: goodbye']);
<ide> describe('ReactIncrementalUpdates', () => {
<ide> const {useEffect} = React;
<ide>
<ide> function App({label}) {
<del> Scheduler.yieldValue('Render: ' + label);
<add> Scheduler.unstable_yieldValue('Render: ' + label);
<ide> useEffect(() => {
<del> Scheduler.yieldValue('Commit: ' + label);
<add> Scheduler.unstable_yieldValue('Commit: ' + label);
<ide> });
<ide> return label;
<ide> }
<ide> describe('ReactIncrementalUpdates', () => {
<ide> // updates in separate batches are all flushed in the same callback
<ide> ReactNoop.renderToRootWithID(<App label="" />, 'a');
<ide> ReactNoop.renderToRootWithID(<App label="" />, 'b');
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['Render: ']);
<ide> interrupt();
<ide>
<ide> ReactNoop.renderToRootWithID(<App label="he" />, 'a');
<ide> ReactNoop.renderToRootWithID(<App label="he" />, 'b');
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['Render: ']);
<ide> interrupt();
<ide>
<ide> ReactNoop.renderToRootWithID(<App label="hell" />, 'a');
<ide> ReactNoop.renderToRootWithID(<App label="hell" />, 'b');
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['Render: ']);
<ide> interrupt();
<ide>
<ide> ReactNoop.renderToRootWithID(<App label="hello" />, 'a');
<ide> ReactNoop.renderToRootWithID(<App label="hello" />, 'b');
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['Render: ']);
<ide> interrupt();
<ide>
<ide> describe('ReactIncrementalUpdates', () => {
<ide> // instead of flushing them normally.
<ide> ReactNoop.renderToRootWithID(<App label="" />, 'a');
<ide> ReactNoop.renderToRootWithID(<App label="" />, 'b');
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['Render: ']);
<ide> interrupt();
<ide>
<ide> ReactNoop.renderToRootWithID(<App label="go" />, 'a');
<ide> ReactNoop.renderToRootWithID(<App label="go" />, 'b');
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['Render: ']);
<ide> interrupt();
<ide>
<ide> ReactNoop.renderToRootWithID(<App label="good" />, 'a');
<ide> ReactNoop.renderToRootWithID(<App label="good" />, 'b');
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['Render: ']);
<ide> interrupt();
<ide>
<ide> ReactNoop.renderToRootWithID(<App label="goodbye" />, 'a');
<ide> ReactNoop.renderToRootWithID(<App label="goodbye" />, 'b');
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> expect(Scheduler).toFlushAndYieldThrough(['Render: ']);
<ide> interrupt();
<ide>
<ide> // All the updates should render and commit in a single batch.
<del> Scheduler.advanceTime(10000);
<add> Scheduler.unstable_advanceTime(10000);
<ide> expect(Scheduler).toHaveYielded([
<ide> 'Render: goodbye',
<ide> 'Commit: goodbye',
<ide><path>packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js
<ide> describe('ReactLazy', () => {
<ide> });
<ide>
<ide> function Text(props) {
<del> Scheduler.yieldValue(props.text);
<add> Scheduler.unstable_yieldValue(props.text);
<ide> return props.text;
<ide> }
<ide>
<ide> describe('ReactLazy', () => {
<ide> it('mount and reorder', async () => {
<ide> class Child extends React.Component {
<ide> componentDidMount() {
<del> Scheduler.yieldValue('Did mount: ' + this.props.label);
<add> Scheduler.unstable_yieldValue('Did mount: ' + this.props.label);
<ide> }
<ide> componentDidUpdate() {
<del> Scheduler.yieldValue('Did update: ' + this.props.label);
<add> Scheduler.unstable_yieldValue('Did update: ' + this.props.label);
<ide> }
<ide> render() {
<ide> return <Text text={this.props.label} />;
<ide> describe('ReactLazy', () => {
<ide>
<ide> it('resolves defaultProps without breaking memoization', async () => {
<ide> function LazyImpl(props) {
<del> Scheduler.yieldValue('Lazy');
<add> Scheduler.unstable_yieldValue('Lazy');
<ide> return (
<ide> <React.Fragment>
<ide> <Text text={props.siblingText} />
<ide> describe('ReactLazy', () => {
<ide> state = {};
<ide>
<ide> static getDerivedStateFromProps(props) {
<del> Scheduler.yieldValue(`getDerivedStateFromProps: ${props.text}`);
<add> Scheduler.unstable_yieldValue(
<add> `getDerivedStateFromProps: ${props.text}`,
<add> );
<ide> return null;
<ide> }
<ide>
<ide> constructor(props) {
<ide> super(props);
<del> Scheduler.yieldValue(`constructor: ${this.props.text}`);
<add> Scheduler.unstable_yieldValue(`constructor: ${this.props.text}`);
<ide> }
<ide>
<ide> componentDidMount() {
<del> Scheduler.yieldValue(`componentDidMount: ${this.props.text}`);
<add> Scheduler.unstable_yieldValue(`componentDidMount: ${this.props.text}`);
<ide> }
<ide>
<ide> componentDidUpdate(prevProps) {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> `componentDidUpdate: ${prevProps.text} -> ${this.props.text}`,
<ide> );
<ide> }
<ide>
<ide> componentWillUnmount() {
<del> Scheduler.yieldValue(`componentWillUnmount: ${this.props.text}`);
<add> Scheduler.unstable_yieldValue(
<add> `componentWillUnmount: ${this.props.text}`,
<add> );
<ide> }
<ide>
<ide> shouldComponentUpdate(nextProps) {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> `shouldComponentUpdate: ${this.props.text} -> ${nextProps.text}`,
<ide> );
<ide> return true;
<ide> }
<ide>
<ide> getSnapshotBeforeUpdate(prevProps) {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> `getSnapshotBeforeUpdate: ${prevProps.text} -> ${this.props.text}`,
<ide> );
<ide> return null;
<ide> describe('ReactLazy', () => {
<ide> state = {};
<ide>
<ide> UNSAFE_componentWillMount() {
<del> Scheduler.yieldValue(`UNSAFE_componentWillMount: ${this.props.text}`);
<add> Scheduler.unstable_yieldValue(
<add> `UNSAFE_componentWillMount: ${this.props.text}`,
<add> );
<ide> }
<ide>
<ide> UNSAFE_componentWillUpdate(nextProps) {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> `UNSAFE_componentWillUpdate: ${this.props.text} -> ${nextProps.text}`,
<ide> );
<ide> }
<ide>
<ide> UNSAFE_componentWillReceiveProps(nextProps) {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> `UNSAFE_componentWillReceiveProps: ${this.props.text} -> ${
<ide> nextProps.text
<ide> }`,
<ide> describe('ReactLazy', () => {
<ide>
<ide> it('resolves defaultProps on the outer wrapper but warns', async () => {
<ide> function T(props) {
<del> Scheduler.yieldValue(props.inner + ' ' + props.outer);
<add> Scheduler.unstable_yieldValue(props.inner + ' ' + props.outer);
<ide> return props.inner + ' ' + props.outer;
<ide> }
<ide> T.defaultProps = {inner: 'Hi'};
<ide> describe('ReactLazy', () => {
<ide> await Promise.resolve();
<ide> expect(() => {
<ide> expect(Scheduler);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> }).toWarnDev([
<ide> 'Invalid prop `inner` of type `string` supplied to `Add`, expected `number`.',
<ide> ]);
<ide> describe('ReactLazy', () => {
<ide>
<ide> it('includes lazy-loaded component in warning stack', async () => {
<ide> const LazyFoo = lazy(() => {
<del> Scheduler.yieldValue('Started loading');
<add> Scheduler.unstable_yieldValue('Started loading');
<ide> const Foo = props => <div>{[<Text text="A" />, <Text text="B" />]}</div>;
<ide> return fakeImport(Foo);
<ide> });
<ide> describe('ReactLazy', () => {
<ide> }
<ide> return fakeImport(
<ide> React.forwardRef((props, ref) => {
<del> Scheduler.yieldValue('forwardRef');
<add> Scheduler.unstable_yieldValue('forwardRef');
<ide> return <Bar ref={ref} />;
<ide> }),
<ide> );
<ide><path>packages/react-reconciler/src/__tests__/ReactMemo-test.internal.js
<ide> describe('memo', () => {
<ide> }
<ide>
<ide> function Text(props) {
<del> Scheduler.yieldValue(props.text);
<add> Scheduler.unstable_yieldValue(props.text);
<ide> return <span prop={props.text} />;
<ide> }
<ide>
<ide> describe('memo', () => {
<ide> return <Text text={count} />;
<ide> }
<ide> Counter = memo(Counter, (oldProps, newProps) => {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> `Old count: ${oldProps.count}, New count: ${newProps.count}`,
<ide> );
<ide> return oldProps.count === newProps.count;
<ide><path>packages/react-reconciler/src/__tests__/ReactNewContext-test.internal.js
<ide> describe('ReactNewContext', () => {
<ide> });
<ide>
<ide> function Text(props) {
<del> Scheduler.yieldValue(props.text);
<add> Scheduler.unstable_yieldValue(props.text);
<ide> return <span prop={props.text} />;
<ide> }
<ide>
<ide> describe('ReactNewContext', () => {
<ide> const ContextConsumer = getConsumer(Context);
<ide>
<ide> function Provider(props) {
<del> Scheduler.yieldValue('Provider');
<add> Scheduler.unstable_yieldValue('Provider');
<ide> return (
<ide> <Context.Provider value={props.value}>
<ide> {props.children}
<ide> describe('ReactNewContext', () => {
<ide> }
<ide>
<ide> function Consumer(props) {
<del> Scheduler.yieldValue('Consumer');
<add> Scheduler.unstable_yieldValue('Consumer');
<ide> return (
<ide> <ContextConsumer>
<ide> {value => {
<del> Scheduler.yieldValue('Consumer render prop');
<add> Scheduler.unstable_yieldValue('Consumer render prop');
<ide> return <span prop={'Result: ' + value} />;
<ide> }}
<ide> </ContextConsumer>
<ide> describe('ReactNewContext', () => {
<ide> return false;
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('Indirection');
<add> Scheduler.unstable_yieldValue('Indirection');
<ide> return this.props.children;
<ide> }
<ide> }
<ide>
<ide> function App(props) {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> return (
<ide> <Provider value={props.value}>
<ide> <Indirection>
<ide> describe('ReactNewContext', () => {
<ide> const ContextConsumer = getConsumer(Context);
<ide>
<ide> function Provider(props) {
<del> Scheduler.yieldValue('Provider');
<add> Scheduler.unstable_yieldValue('Provider');
<ide> return (
<ide> <Context.Provider value={props.value}>
<ide> {props.children}
<ide> describe('ReactNewContext', () => {
<ide> }
<ide>
<ide> function Consumer(props) {
<del> Scheduler.yieldValue('Consumer');
<add> Scheduler.unstable_yieldValue('Consumer');
<ide> return (
<ide> <ContextConsumer>
<ide> {value => {
<del> Scheduler.yieldValue('Consumer render prop');
<add> Scheduler.unstable_yieldValue('Consumer render prop');
<ide> return <span prop={'Result: ' + value} />;
<ide> }}
<ide> </ContextConsumer>
<ide> describe('ReactNewContext', () => {
<ide> return false;
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('Indirection');
<add> Scheduler.unstable_yieldValue('Indirection');
<ide> return this.props.children;
<ide> }
<ide> }
<ide>
<ide> function App(props) {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> return (
<ide> <Provider value={props.value}>
<ide> <Indirection>
<ide> describe('ReactNewContext', () => {
<ide> const ContextConsumer = getConsumer(Context);
<ide>
<ide> function Provider(props) {
<del> Scheduler.yieldValue('Provider');
<add> Scheduler.unstable_yieldValue('Provider');
<ide> return (
<ide> <Context.Provider value={props.value}>
<ide> {props.children}
<ide> describe('ReactNewContext', () => {
<ide> }
<ide>
<ide> function Consumer(props) {
<del> Scheduler.yieldValue('Consumer');
<add> Scheduler.unstable_yieldValue('Consumer');
<ide> return (
<ide> <ContextConsumer>
<ide> {value => {
<del> Scheduler.yieldValue('Consumer render prop');
<add> Scheduler.unstable_yieldValue('Consumer render prop');
<ide> return <span prop={'Result: ' + value} />;
<ide> }}
<ide> </ContextConsumer>
<ide> describe('ReactNewContext', () => {
<ide> return false;
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('Indirection');
<add> Scheduler.unstable_yieldValue('Indirection');
<ide> return this.props.children;
<ide> }
<ide> }
<ide>
<ide> function App(props) {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> return (
<ide> <Provider value={props.value}>
<ide> <Indirection>
<ide> describe('ReactNewContext', () => {
<ide> return (
<ide> <Consumer unstable_observedBits={0b01}>
<ide> {value => {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return <span prop={'Foo: ' + value.foo} />;
<ide> }}
<ide> </Consumer>
<ide> describe('ReactNewContext', () => {
<ide> return (
<ide> <Consumer unstable_observedBits={0b10}>
<ide> {value => {
<del> Scheduler.yieldValue('Bar');
<add> Scheduler.unstable_yieldValue('Bar');
<ide> return <span prop={'Bar: ' + value.bar} />;
<ide> }}
<ide> </Consumer>
<ide> describe('ReactNewContext', () => {
<ide> return (
<ide> <Consumer unstable_observedBits={0b01}>
<ide> {value => {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <React.Fragment>
<ide> <span prop={'Foo: ' + value.foo} />
<ide> describe('ReactNewContext', () => {
<ide> return (
<ide> <Consumer unstable_observedBits={0b10}>
<ide> {value => {
<del> Scheduler.yieldValue('Bar');
<add> Scheduler.unstable_yieldValue('Bar');
<ide> return (
<ide> <React.Fragment>
<ide> <span prop={'Bar: ' + value.bar} />
<ide> describe('ReactNewContext', () => {
<ide> class Child extends React.Component {
<ide> state = {step: 0};
<ide> render() {
<del> Scheduler.yieldValue('Child');
<add> Scheduler.unstable_yieldValue('Child');
<ide> return (
<ide> <span
<ide> prop={`Context: ${this.props.context}, Step: ${
<ide> describe('ReactNewContext', () => {
<ide> <Context.Provider value={props.value}>
<ide> <Consumer>
<ide> {value => {
<del> Scheduler.yieldValue('Consumer render prop');
<add> Scheduler.unstable_yieldValue('Consumer render prop');
<ide> return <Child ref={inst => (child = inst)} context={value} />;
<ide> }}
<ide> </Consumer>
<ide> describe('ReactNewContext', () => {
<ide> const Consumer = getConsumer(Context);
<ide>
<ide> function renderChildValue(value) {
<del> Scheduler.yieldValue('Consumer');
<add> Scheduler.unstable_yieldValue('Consumer');
<ide> return <span prop={value} />;
<ide> }
<ide>
<ide> function ChildWithInlineRenderCallback() {
<del> Scheduler.yieldValue('ChildWithInlineRenderCallback');
<add> Scheduler.unstable_yieldValue('ChildWithInlineRenderCallback');
<ide> // Note: we are intentionally passing an inline arrow. Don't refactor.
<ide> return <Consumer>{value => renderChildValue(value)}</Consumer>;
<ide> }
<ide>
<ide> function ChildWithCachedRenderCallback() {
<del> Scheduler.yieldValue('ChildWithCachedRenderCallback');
<add> Scheduler.unstable_yieldValue('ChildWithCachedRenderCallback');
<ide> return <Consumer>{renderChildValue}</Consumer>;
<ide> }
<ide>
<ide> class PureIndirection extends React.PureComponent {
<ide> render() {
<del> Scheduler.yieldValue('PureIndirection');
<add> Scheduler.unstable_yieldValue('PureIndirection');
<ide> return (
<ide> <React.Fragment>
<ide> <ChildWithInlineRenderCallback />
<ide> describe('ReactNewContext', () => {
<ide>
<ide> class App extends React.Component {
<ide> render() {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> return (
<ide> <Context.Provider value={this.props.value}>
<ide> <PureIndirection />
<ide> describe('ReactNewContext', () => {
<ide> };
<ide>
<ide> render() {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> return (
<ide> <Context.Provider value={this.state.step}>
<ide> <StaticContent />
<ide> describe('ReactNewContext', () => {
<ide> return (
<ide> <ContextConsumer>
<ide> {value => {
<del> Scheduler.yieldValue('Consumer');
<add> Scheduler.unstable_yieldValue('Consumer');
<ide> return <span prop={value} />;
<ide> }}
<ide> </ContextConsumer>
<ide> describe('ReactNewContext', () => {
<ide> const Context = React.createContext(0);
<ide>
<ide> function Foo(props) {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return null;
<ide> }
<ide>
<ide> describe('ReactNewContext', () => {
<ide> const Context = React.createContext(0);
<ide>
<ide> function Child() {
<del> Scheduler.yieldValue('Child');
<add> Scheduler.unstable_yieldValue('Child');
<ide> return <span prop="Child" />;
<ide> }
<ide>
<ide> const children = <Child />;
<ide>
<ide> function App(props) {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> return (
<ide> <Context.Provider value={props.value}>{children}</Context.Provider>
<ide> );
<ide> describe('ReactNewContext', () => {
<ide> const Context = React.createContext(0);
<ide>
<ide> function Child() {
<del> Scheduler.yieldValue('Child');
<add> Scheduler.unstable_yieldValue('Child');
<ide> return <span prop="Child" />;
<ide> }
<ide>
<ide> describe('ReactNewContext', () => {
<ide> return {legacyValue: this.state.legacyValue};
<ide> }
<ide> render() {
<del> Scheduler.yieldValue('LegacyProvider');
<add> Scheduler.unstable_yieldValue('LegacyProvider');
<ide> return this.props.children;
<ide> }
<ide> }
<ide>
<ide> class App extends React.Component {
<ide> state = {value: 1};
<ide> render() {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> return (
<ide> <Context.Provider value={this.state.value}>
<ide> {this.props.children}
<ide> describe('ReactNewContext', () => {
<ide> };
<ide>
<ide> renderConsumer = context => {
<del> Scheduler.yieldValue('App#renderConsumer');
<add> Scheduler.unstable_yieldValue('App#renderConsumer');
<ide> return <span prop={this.state.text} />;
<ide> };
<ide>
<ide> render() {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> return (
<ide> <Context.Provider value={this.props.value}>
<ide> <Consumer>{this.renderConsumer}</Consumer>
<ide> describe('ReactNewContext', () => {
<ide> };
<ide>
<ide> renderConsumer = context => {
<del> Scheduler.yieldValue('App#renderConsumer');
<add> Scheduler.unstable_yieldValue('App#renderConsumer');
<ide> return <span prop={this.state.text} />;
<ide> };
<ide>
<ide> render() {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> return (
<ide> <Context.Provider value={this.props.value}>
<ide> <Consumer>{this.renderConsumer}</Consumer>
<ide> describe('ReactNewContext', () => {
<ide> };
<ide>
<ide> renderConsumer = context => {
<del> Scheduler.yieldValue('App#renderConsumer');
<add> Scheduler.unstable_yieldValue('App#renderConsumer');
<ide> return <span prop={this.state.text} />;
<ide> };
<ide>
<ide> render() {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> return (
<ide> <Context.Provider value={this.props.value}>
<ide> <Consumer>{this.renderConsumer}</Consumer>
<ide> describe('ReactNewContext', () => {
<ide> return false;
<ide> }
<ide> render() {
<del> Scheduler.yieldValue();
<add> Scheduler.unstable_yieldValue();
<ide> if (this.props.depth >= this.props.maxDepth) {
<ide> return null;
<ide> }
<ide> describe('ReactNewContext', () => {
<ide> actions.forEach(action => {
<ide> switch (action.type) {
<ide> case FLUSH_ALL:
<del> Scheduler.unstable_flushWithoutYielding();
<add> Scheduler.unstable_flushAllWithoutAsserting();
<ide> break;
<ide> case FLUSH:
<ide> Scheduler.unstable_flushNumberOfYields(action.unitsOfWork);
<ide> describe('ReactNewContext', () => {
<ide> assertConsistentTree();
<ide> });
<ide>
<del> Scheduler.unstable_flushWithoutYielding();
<add> Scheduler.unstable_flushAllWithoutAsserting();
<ide> assertConsistentTree(finalExpectedValues);
<ide> }
<ide>
<ide><path>packages/react-reconciler/src/__tests__/ReactNoopRendererAct-test.js
<ide> describe('ReactNoop.act()', () => {
<ide> function App() {
<ide> let [ctr, setCtr] = React.useState(0);
<ide> async function someAsyncFunction() {
<del> Scheduler.yieldValue('stage 1');
<add> Scheduler.unstable_yieldValue('stage 1');
<ide> await null;
<del> Scheduler.yieldValue('stage 2');
<add> Scheduler.unstable_yieldValue('stage 2');
<ide> await null;
<ide> setCtr(1);
<ide> }
<ide><path>packages/react-reconciler/src/__tests__/ReactSchedulerIntegration-test.internal.js
<ide> describe('ReactSchedulerIntegration', () => {
<ide>
<ide> it('has correct priority during rendering', () => {
<ide> function ReadPriority() {
<del> Scheduler.yieldValue('Priority: ' + getCurrentPriorityAsString());
<add> Scheduler.unstable_yieldValue(
<add> 'Priority: ' + getCurrentPriorityAsString(),
<add> );
<ide> return null;
<ide> }
<ide> ReactNoop.render(<ReadPriority />);
<ide> describe('ReactSchedulerIntegration', () => {
<ide>
<ide> it('has correct priority when continuing a render after yielding', () => {
<ide> function ReadPriority() {
<del> Scheduler.yieldValue('Priority: ' + getCurrentPriorityAsString());
<add> Scheduler.unstable_yieldValue(
<add> 'Priority: ' + getCurrentPriorityAsString(),
<add> );
<ide> return null;
<ide> }
<ide>
<ide> describe('ReactSchedulerIntegration', () => {
<ide> it('layout effects have immediate priority', () => {
<ide> const {useLayoutEffect} = React;
<ide> function ReadPriority() {
<del> Scheduler.yieldValue('Render priority: ' + getCurrentPriorityAsString());
<add> Scheduler.unstable_yieldValue(
<add> 'Render priority: ' + getCurrentPriorityAsString(),
<add> );
<ide> useLayoutEffect(() => {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> 'Layout priority: ' + getCurrentPriorityAsString(),
<ide> );
<ide> });
<ide> describe('ReactSchedulerIntegration', () => {
<ide> it('passive effects have the same priority as render', () => {
<ide> const {useEffect} = React;
<ide> function ReadPriority() {
<del> Scheduler.yieldValue('Render priority: ' + getCurrentPriorityAsString());
<add> Scheduler.unstable_yieldValue(
<add> 'Render priority: ' + getCurrentPriorityAsString(),
<add> );
<ide> useEffect(() => {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> 'Passive priority: ' + getCurrentPriorityAsString(),
<ide> );
<ide> });
<ide> describe('ReactSchedulerIntegration', () => {
<ide>
<ide> it('after completing a level of work, infers priority of the next batch based on its expiration time', () => {
<ide> function App({label}) {
<del> Scheduler.yieldValue(`${label} [${getCurrentPriorityAsString()}]`);
<add> Scheduler.unstable_yieldValue(
<add> `${label} [${getCurrentPriorityAsString()}]`,
<add> );
<ide> return label;
<ide> }
<ide>
<ide> describe('ReactSchedulerIntegration', () => {
<ide>
<ide> const root = ReactNoop.createRoot();
<ide> root.render('Initial');
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('A'));
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('B'));
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('C'));
<add> scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('A'));
<add> scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('B'));
<add> scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('C'));
<ide>
<ide> // Schedule a React render. React will request a paint after committing it.
<ide> root.render('Update');
<ide>
<ide> // Advance time just to be sure the next tasks have lower priority
<del> Scheduler.advanceTime(2000);
<add> Scheduler.unstable_advanceTime(2000);
<ide>
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('D'));
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('E'));
<add> scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('D'));
<add> scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('E'));
<ide>
<ide> // Flush everything up to the next paint. Should yield after the
<ide> // React commit.
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspense-test.internal.js
<ide> describe('ReactSuspense', () => {
<ide> listeners = [{resolve, reject}];
<ide> setTimeout(() => {
<ide> if (textResourceShouldFail) {
<del> Scheduler.yieldValue(`Promise rejected [${text}]`);
<add> Scheduler.unstable_yieldValue(`Promise rejected [${text}]`);
<ide> status = 'rejected';
<ide> value = new Error('Failed to load: ' + text);
<ide> listeners.forEach(listener => listener.reject(value));
<ide> } else {
<del> Scheduler.yieldValue(`Promise resolved [${text}]`);
<add> Scheduler.unstable_yieldValue(`Promise resolved [${text}]`);
<ide> status = 'resolved';
<ide> value = text;
<ide> listeners.forEach(listener => listener.resolve(value));
<ide> describe('ReactSuspense', () => {
<ide> });
<ide>
<ide> function Text(props) {
<del> Scheduler.yieldValue(props.text);
<add> Scheduler.unstable_yieldValue(props.text);
<ide> return props.text;
<ide> }
<ide>
<ide> function AsyncText(props) {
<ide> const text = props.text;
<ide> try {
<ide> TextResource.read([props.text, props.ms]);
<del> Scheduler.yieldValue(text);
<add> Scheduler.unstable_yieldValue(text);
<ide> return text;
<ide> } catch (promise) {
<ide> if (typeof promise.then === 'function') {
<del> Scheduler.yieldValue(`Suspend! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
<ide> } else {
<del> Scheduler.yieldValue(`Error! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Error! [${text}]`);
<ide> }
<ide> throw promise;
<ide> }
<ide> }
<ide>
<ide> it('suspends rendering and continues later', () => {
<ide> function Bar(props) {
<del> Scheduler.yieldValue('Bar');
<add> Scheduler.unstable_yieldValue('Bar');
<ide> return props.children;
<ide> }
<ide>
<ide> function Foo({renderBar}) {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <Suspense fallback={<Text text="Loading..." />}>
<ide> {renderBar ? (
<ide> describe('ReactSuspense', () => {
<ide>
<ide> function Async() {
<ide> if (!didResolve) {
<del> Scheduler.yieldValue('Suspend!');
<add> Scheduler.unstable_yieldValue('Suspend!');
<ide> throw thenable;
<ide> }
<del> Scheduler.yieldValue('Async');
<add> Scheduler.unstable_yieldValue('Async');
<ide> return 'Async';
<ide> }
<ide>
<ide> describe('ReactSuspense', () => {
<ide> it('mounts a lazy class component in non-concurrent mode', async () => {
<ide> class Class extends React.Component {
<ide> componentDidMount() {
<del> Scheduler.yieldValue('Did mount: ' + this.props.label);
<add> Scheduler.unstable_yieldValue('Did mount: ' + this.props.label);
<ide> }
<ide> componentDidUpdate() {
<del> Scheduler.yieldValue('Did update: ' + this.props.label);
<add> Scheduler.unstable_yieldValue('Did update: ' + this.props.label);
<ide> }
<ide> render() {
<ide> return <Text text={this.props.label} />;
<ide> describe('ReactSuspense', () => {
<ide> it('a mounted class component can suspend without losing state', () => {
<ide> class TextWithLifecycle extends React.Component {
<ide> componentDidMount() {
<del> Scheduler.yieldValue(`Mount [${this.props.text}]`);
<add> Scheduler.unstable_yieldValue(`Mount [${this.props.text}]`);
<ide> }
<ide> componentDidUpdate() {
<del> Scheduler.yieldValue(`Update [${this.props.text}]`);
<add> Scheduler.unstable_yieldValue(`Update [${this.props.text}]`);
<ide> }
<ide> componentWillUnmount() {
<del> Scheduler.yieldValue(`Unmount [${this.props.text}]`);
<add> Scheduler.unstable_yieldValue(`Unmount [${this.props.text}]`);
<ide> }
<ide> render() {
<ide> return <Text {...this.props} />;
<ide> describe('ReactSuspense', () => {
<ide> class AsyncTextWithLifecycle extends React.Component {
<ide> state = {step: 1};
<ide> componentDidMount() {
<del> Scheduler.yieldValue(`Mount [${this.props.text}:${this.state.step}]`);
<add> Scheduler.unstable_yieldValue(
<add> `Mount [${this.props.text}:${this.state.step}]`,
<add> );
<ide> }
<ide> componentDidUpdate() {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> `Update [${this.props.text}:${this.state.step}]`,
<ide> );
<ide> }
<ide> componentWillUnmount() {
<del> Scheduler.yieldValue(
<add> Scheduler.unstable_yieldValue(
<ide> `Unmount [${this.props.text}:${this.state.step}]`,
<ide> );
<ide> }
<ide> describe('ReactSuspense', () => {
<ide> const ms = this.props.ms;
<ide> try {
<ide> TextResource.read([text, ms]);
<del> Scheduler.yieldValue(text);
<add> Scheduler.unstable_yieldValue(text);
<ide> return text;
<ide> } catch (promise) {
<ide> if (typeof promise.then === 'function') {
<del> Scheduler.yieldValue(`Suspend! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
<ide> } else {
<del> Scheduler.yieldValue(`Error! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Error! [${text}]`);
<ide> }
<ide> throw promise;
<ide> }
<ide> describe('ReactSuspense', () => {
<ide> it('suspends in a class that has componentWillUnmount and is then deleted', () => {
<ide> class AsyncTextWithUnmount extends React.Component {
<ide> componentWillUnmount() {
<del> Scheduler.yieldValue('will unmount');
<add> Scheduler.unstable_yieldValue('will unmount');
<ide> }
<ide> render() {
<ide> const text = this.props.text;
<ide> const ms = this.props.ms;
<ide> try {
<ide> TextResource.read([text, ms]);
<del> Scheduler.yieldValue(text);
<add> Scheduler.unstable_yieldValue(text);
<ide> return text;
<ide> } catch (promise) {
<ide> if (typeof promise.then === 'function') {
<del> Scheduler.yieldValue(`Suspend! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
<ide> } else {
<del> Scheduler.yieldValue(`Error! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Error! [${text}]`);
<ide> }
<ide> throw promise;
<ide> }
<ide> describe('ReactSuspense', () => {
<ide>
<ide> useLayoutEffect(
<ide> () => {
<del> Scheduler.yieldValue('Did commit: ' + text);
<add> Scheduler.unstable_yieldValue('Did commit: ' + text);
<ide> },
<ide> [text],
<ide> );
<ide>
<ide> try {
<ide> TextResource.read([props.text, props.ms]);
<del> Scheduler.yieldValue(text);
<add> Scheduler.unstable_yieldValue(text);
<ide> return text;
<ide> } catch (promise) {
<ide> if (typeof promise.then === 'function') {
<del> Scheduler.yieldValue(`Suspend! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
<ide> } else {
<del> Scheduler.yieldValue(`Error! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Error! [${text}]`);
<ide> }
<ide> throw promise;
<ide> }
<ide> describe('ReactSuspense', () => {
<ide> const fullText = `${text}:${step}`;
<ide> try {
<ide> TextResource.read([fullText, ms]);
<del> Scheduler.yieldValue(fullText);
<add> Scheduler.unstable_yieldValue(fullText);
<ide> return fullText;
<ide> } catch (promise) {
<ide> if (typeof promise.then === 'function') {
<del> Scheduler.yieldValue(`Suspend! [${fullText}]`);
<add> Scheduler.unstable_yieldValue(`Suspend! [${fullText}]`);
<ide> } else {
<del> Scheduler.yieldValue(`Error! [${fullText}]`);
<add> Scheduler.unstable_yieldValue(`Error! [${fullText}]`);
<ide> }
<ide> throw promise;
<ide> }
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseFuzz-test.internal.js
<ide> describe('ReactSuspenseFuzz', () => {
<ide> };
<ide> const timeoutID = setTimeout(() => {
<ide> pendingTasks.delete(task);
<del> Scheduler.yieldValue(task.label);
<add> Scheduler.unstable_yieldValue(task.label);
<ide> setStep(i + 1);
<ide> }, remountAfter);
<ide> pendingTasks.add(task);
<ide> describe('ReactSuspenseFuzz', () => {
<ide> };
<ide> const timeoutID = setTimeout(() => {
<ide> pendingTasks.delete(task);
<del> Scheduler.yieldValue(task.label);
<add> Scheduler.unstable_yieldValue(task.label);
<ide> setStep([i + 1, suspendFor]);
<ide> }, beginAfter);
<ide> pendingTasks.add(task);
<ide> describe('ReactSuspenseFuzz', () => {
<ide> setTimeout(() => {
<ide> cache.set(fullText, fullText);
<ide> pendingTasks.delete(task);
<del> Scheduler.yieldValue(task.label);
<add> Scheduler.unstable_yieldValue(task.label);
<ide> resolve();
<ide> }, delay);
<ide> },
<ide> };
<ide> cache.set(fullText, thenable);
<del> Scheduler.yieldValue(`Suspended! [${fullText}]`);
<add> Scheduler.unstable_yieldValue(`Suspended! [${fullText}]`);
<ide> throw thenable;
<ide> } else if (typeof resolvedText.then === 'function') {
<ide> const thenable = resolvedText;
<del> Scheduler.yieldValue(`Suspended! [${fullText}]`);
<add> Scheduler.unstable_yieldValue(`Suspended! [${fullText}]`);
<ide> throw thenable;
<ide> }
<ide> } else {
<ide> resolvedText = fullText;
<ide> }
<ide>
<del> Scheduler.yieldValue(resolvedText);
<add> Scheduler.unstable_yieldValue(resolvedText);
<ide> return resolvedText;
<ide> }
<ide>
<ide> function resolveAllTasks() {
<del> Scheduler.unstable_flushWithoutYielding();
<add> Scheduler.unstable_flushAllWithoutAsserting();
<ide> let elapsedTime = 0;
<ide> while (pendingTasks && pendingTasks.size > 0) {
<ide> if ((elapsedTime += 1000) > 1000000) {
<ide> throw new Error('Something did not resolve properly.');
<ide> }
<ide> ReactNoop.act(() => jest.advanceTimersByTime(1000));
<del> Scheduler.unstable_flushWithoutYielding();
<add> Scheduler.unstable_flushAllWithoutAsserting();
<ide> }
<ide> }
<ide>
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseList-test.internal.js
<ide> describe('ReactSuspenseList', () => {
<ide> });
<ide>
<ide> function Text(props) {
<del> Scheduler.yieldValue(props.text);
<add> Scheduler.unstable_yieldValue(props.text);
<ide> return <span>{props.text}</span>;
<ide> }
<ide>
<ide> function createAsyncText(text) {
<ide> let resolved = false;
<ide> let Component = function() {
<ide> if (!resolved) {
<del> Scheduler.yieldValue('Suspend! [' + text + ']');
<add> Scheduler.unstable_yieldValue('Suspend! [' + text + ']');
<ide> throw promise;
<ide> }
<ide> return <Text text={text} />;
<ide> describe('ReactSuspenseList', () => {
<ide>
<ide> ReactNoop.render(<Foo />);
<ide>
<del> expect(() => Scheduler.flushAll()).toWarnDev([
<add> expect(() => Scheduler.unstable_flushAll()).toWarnDev([
<ide> 'Warning: "something" is not a supported revealOrder on ' +
<ide> '<SuspenseList />. Did you mean "together", "forwards" or "backwards"?' +
<ide> '\n in SuspenseList (at **)' +
<ide> describe('ReactSuspenseList', () => {
<ide>
<ide> ReactNoop.render(<Foo />);
<ide>
<del> expect(() => Scheduler.flushAll()).toWarnDev([
<add> expect(() => Scheduler.unstable_flushAll()).toWarnDev([
<ide> 'Warning: "TOGETHER" is not a valid value for revealOrder on ' +
<ide> '<SuspenseList />. Use lowercase "together" instead.' +
<ide> '\n in SuspenseList (at **)' +
<ide> describe('ReactSuspenseList', () => {
<ide>
<ide> ReactNoop.render(<Foo />);
<ide>
<del> expect(() => Scheduler.flushAll()).toWarnDev([
<add> expect(() => Scheduler.unstable_flushAll()).toWarnDev([
<ide> 'Warning: "forward" is not a valid value for revealOrder on ' +
<ide> '<SuspenseList />. React uses the -s suffix in the spelling. ' +
<ide> 'Use "forwards" instead.' +
<ide> describe('ReactSuspenseList', () => {
<ide>
<ide> expect(Scheduler).toFlushAndYieldThrough(['A']);
<ide>
<del> Scheduler.advanceTime(300);
<add> Scheduler.unstable_advanceTime(300);
<ide> jest.advanceTimersByTime(300);
<ide>
<ide> expect(Scheduler).toFlushAndYieldThrough(['B']);
<ide>
<del> Scheduler.advanceTime(300);
<add> Scheduler.unstable_advanceTime(300);
<ide> jest.advanceTimersByTime(300);
<ide>
<ide> // We've still not been able to show anything on the screen even though
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspensePlaceholder-test.internal.js
<ide> describe('ReactSuspensePlaceholder', () => {
<ide> listeners = [{resolve, reject}];
<ide> setTimeout(() => {
<ide> if (textResourceShouldFail) {
<del> Scheduler.yieldValue(`Promise rejected [${text}]`);
<add> Scheduler.unstable_yieldValue(`Promise rejected [${text}]`);
<ide> status = 'rejected';
<ide> value = new Error('Failed to load: ' + text);
<ide> listeners.forEach(listener => listener.reject(value));
<ide> } else {
<del> Scheduler.yieldValue(`Promise resolved [${text}]`);
<add> Scheduler.unstable_yieldValue(`Promise resolved [${text}]`);
<ide> status = 'resolved';
<ide> value = text;
<ide> listeners.forEach(listener => listener.resolve(value));
<ide> describe('ReactSuspensePlaceholder', () => {
<ide> });
<ide>
<ide> function Text({fakeRenderDuration = 0, text = 'Text'}) {
<del> Scheduler.advanceTime(fakeRenderDuration);
<del> Scheduler.yieldValue(text);
<add> Scheduler.unstable_advanceTime(fakeRenderDuration);
<add> Scheduler.unstable_yieldValue(text);
<ide> return text;
<ide> }
<ide>
<ide> function AsyncText({fakeRenderDuration = 0, ms, text}) {
<del> Scheduler.advanceTime(fakeRenderDuration);
<add> Scheduler.unstable_advanceTime(fakeRenderDuration);
<ide> try {
<ide> TextResource.read([text, ms]);
<del> Scheduler.yieldValue(text);
<add> Scheduler.unstable_yieldValue(text);
<ide> return text;
<ide> } catch (promise) {
<ide> if (typeof promise.then === 'function') {
<del> Scheduler.yieldValue(`Suspend! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
<ide> } else {
<del> Scheduler.yieldValue(`Error! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Error! [${text}]`);
<ide> }
<ide> throw promise;
<ide> }
<ide> describe('ReactSuspensePlaceholder', () => {
<ide> class HiddenText extends React.PureComponent {
<ide> render() {
<ide> const text = this.props.text;
<del> Scheduler.yieldValue(text);
<add> Scheduler.unstable_yieldValue(text);
<ide> return <span hidden={true}>{text}</span>;
<ide> }
<ide> }
<ide> describe('ReactSuspensePlaceholder', () => {
<ide> onRender = jest.fn();
<ide>
<ide> const Fallback = () => {
<del> Scheduler.yieldValue('Fallback');
<del> Scheduler.advanceTime(10);
<add> Scheduler.unstable_yieldValue('Fallback');
<add> Scheduler.unstable_advanceTime(10);
<ide> return 'Loading...';
<ide> };
<ide>
<ide> const Suspending = () => {
<del> Scheduler.yieldValue('Suspending');
<del> Scheduler.advanceTime(2);
<add> Scheduler.unstable_yieldValue('Suspending');
<add> Scheduler.unstable_advanceTime(2);
<ide> return <AsyncText ms={1000} text="Loaded" fakeRenderDuration={1} />;
<ide> };
<ide>
<ide> App = ({shouldSuspend, text = 'Text', textRenderDuration = 5}) => {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> return (
<ide> <Profiler id="root" onRender={onRender}>
<ide> <Suspense fallback={<Fallback />}>
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseWithNoopRenderer-test.internal.js
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> return new Promise((resolve, reject) =>
<ide> setTimeout(() => {
<ide> if (textResourceShouldFail) {
<del> Scheduler.yieldValue(`Promise rejected [${text}]`);
<add> Scheduler.unstable_yieldValue(`Promise rejected [${text}]`);
<ide> reject(new Error('Failed to load: ' + text));
<ide> } else {
<del> Scheduler.yieldValue(`Promise resolved [${text}]`);
<add> Scheduler.unstable_yieldValue(`Promise resolved [${text}]`);
<ide> resolve(text);
<ide> }
<ide> }, ms),
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> }
<ide>
<ide> function Text(props) {
<del> Scheduler.yieldValue(props.text);
<add> Scheduler.unstable_yieldValue(props.text);
<ide> return <span prop={props.text} ref={props.hostRef} />;
<ide> }
<ide>
<ide> function AsyncText(props) {
<ide> const text = props.text;
<ide> try {
<ide> TextResource.read([props.text, props.ms]);
<del> Scheduler.yieldValue(text);
<add> Scheduler.unstable_yieldValue(text);
<ide> return <span prop={text} />;
<ide> } catch (promise) {
<ide> if (typeof promise.then === 'function') {
<del> Scheduler.yieldValue(`Suspend! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
<ide> } else {
<del> Scheduler.yieldValue(`Error! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Error! [${text}]`);
<ide> }
<ide> throw promise;
<ide> }
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> ReactNoop.render(<Foo />);
<ide>
<del> expect(() => Scheduler.flushAll()).toWarnDev([
<add> expect(() => Scheduler.unstable_flushAll()).toWarnDev([
<ide> 'Warning: maxDuration has been removed from React. ' +
<ide> 'Remove the maxDuration prop.' +
<ide> '\n in Suspense (at **)' +
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> it('does not restart rendering for initial render', async () => {
<ide> function Bar(props) {
<del> Scheduler.yieldValue('Bar');
<add> Scheduler.unstable_yieldValue('Bar');
<ide> return props.children;
<ide> }
<ide>
<ide> function Foo() {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <React.Fragment>
<ide> <Suspense fallback={<Text text="Loading..." />}>
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> expect(ReactNoop.getChildren()).toEqual([]);
<ide>
<ide> // Flush the promise completely
<del> Scheduler.advanceTime(100);
<add> Scheduler.unstable_advanceTime(100);
<ide> await advanceTimers(100);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [A]']);
<ide>
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> it('suspends rendering and continues later', async () => {
<ide> function Bar(props) {
<del> Scheduler.yieldValue('Bar');
<add> Scheduler.unstable_yieldValue('Bar');
<ide> return props.children;
<ide> }
<ide>
<ide> function Foo({renderBar}) {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <Suspense fallback={<Text text="Loading..." />}>
<ide> {renderBar ? (
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> <AsyncText text="B" ms={100} />
<ide> </Suspense>,
<ide> );
<del> Scheduler.advanceTime(10000);
<add> Scheduler.unstable_advanceTime(10000);
<ide> expect(Scheduler).toHaveYielded([
<ide> 'Suspend! [A]',
<ide> 'Suspend! [B]',
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> it('flushes all expired updates in a single batch', async () => {
<ide> class Foo extends React.Component {
<ide> componentDidUpdate() {
<del> Scheduler.yieldValue('Commit: ' + this.props.text);
<add> Scheduler.unstable_yieldValue('Commit: ' + this.props.text);
<ide> }
<ide> componentDidMount() {
<del> Scheduler.yieldValue('Commit: ' + this.props.text);
<add> Scheduler.unstable_yieldValue('Commit: ' + this.props.text);
<ide> }
<ide> render() {
<ide> return (
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> jest.advanceTimersByTime(1000);
<ide> ReactNoop.render(<Foo text="goodbye" />);
<ide>
<del> Scheduler.advanceTime(10000);
<add> Scheduler.unstable_advanceTime(10000);
<ide> jest.advanceTimersByTime(10000);
<ide>
<ide> expect(Scheduler).toHaveYielded([
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> ]);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Loading...')]);
<ide>
<del> Scheduler.advanceTime(20000);
<add> Scheduler.unstable_advanceTime(20000);
<ide> await advanceTimers(20000);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [goodbye]']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Loading...')]);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> // Regression test. This test used to fall into an infinite loop.
<ide> function ExpensiveText({text}) {
<ide> // This causes the update to expire.
<del> Scheduler.advanceTime(10000);
<add> Scheduler.unstable_advanceTime(10000);
<ide> // Then something suspends.
<ide> return <AsyncText text={text} ms={200000} />;
<ide> }
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> // Update.
<ide> text.current.setState({step: 2}, () =>
<del> Scheduler.yieldValue('Update did commit'),
<add> Scheduler.unstable_yieldValue('Update did commit'),
<ide> );
<ide>
<ide> expect(ReactNoop.flushNextYield()).toEqual([
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> it('does not re-render siblings in loose mode', async () => {
<ide> class TextWithLifecycle extends React.Component {
<ide> componentDidMount() {
<del> Scheduler.yieldValue(`Mount [${this.props.text}]`);
<add> Scheduler.unstable_yieldValue(`Mount [${this.props.text}]`);
<ide> }
<ide> componentDidUpdate() {
<del> Scheduler.yieldValue(`Update [${this.props.text}]`);
<add> Scheduler.unstable_yieldValue(`Update [${this.props.text}]`);
<ide> }
<ide> render() {
<ide> return <Text {...this.props} />;
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> class AsyncTextWithLifecycle extends React.Component {
<ide> componentDidMount() {
<del> Scheduler.yieldValue(`Mount [${this.props.text}]`);
<add> Scheduler.unstable_yieldValue(`Mount [${this.props.text}]`);
<ide> }
<ide> componentDidUpdate() {
<del> Scheduler.yieldValue(`Update [${this.props.text}]`);
<add> Scheduler.unstable_yieldValue(`Update [${this.props.text}]`);
<ide> }
<ide> render() {
<ide> return <AsyncText {...this.props} />;
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> }
<ide>
<ide> ReactNoop.renderLegacySyncRoot(<App />, () =>
<del> Scheduler.yieldValue('Commit root'),
<add> Scheduler.unstable_yieldValue('Commit root'),
<ide> );
<ide> expect(Scheduler).toHaveYielded([
<ide> 'A',
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> constructor(props) {
<ide> super(props);
<ide> const text = props.text;
<del> Scheduler.yieldValue('constructor');
<add> Scheduler.unstable_yieldValue('constructor');
<ide> try {
<ide> TextResource.read([props.text, props.ms]);
<ide> this.state = {text};
<ide> } catch (promise) {
<ide> if (typeof promise.then === 'function') {
<del> Scheduler.yieldValue(`Suspend! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
<ide> } else {
<del> Scheduler.yieldValue(`Error! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Error! [${text}]`);
<ide> }
<ide> throw promise;
<ide> }
<ide> }
<ide> componentDidMount() {
<del> Scheduler.yieldValue('componentDidMount');
<add> Scheduler.unstable_yieldValue('componentDidMount');
<ide> }
<ide> render() {
<del> Scheduler.yieldValue(this.state.text);
<add> Scheduler.unstable_yieldValue(this.state.text);
<ide> return <span prop={this.state.text} />;
<ide> }
<ide> }
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> const child = useRef(null);
<ide>
<ide> useLayoutEffect(() => {
<del> Scheduler.yieldValue(ReactNoop.getPendingChildrenAsJSX());
<add> Scheduler.unstable_yieldValue(ReactNoop.getPendingChildrenAsJSX());
<ide> });
<ide>
<ide> return (
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> const child = useRef(null);
<ide>
<ide> useLayoutEffect(() => {
<del> Scheduler.yieldValue('Child is hidden: ' + child.current.hidden);
<add> Scheduler.unstable_yieldValue(
<add> 'Child is hidden: ' + child.current.hidden,
<add> );
<ide> });
<ide>
<ide> return (
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> it('does not call lifecycles of a suspended component', async () => {
<ide> class TextWithLifecycle extends React.Component {
<ide> componentDidMount() {
<del> Scheduler.yieldValue(`Mount [${this.props.text}]`);
<add> Scheduler.unstable_yieldValue(`Mount [${this.props.text}]`);
<ide> }
<ide> componentDidUpdate() {
<del> Scheduler.yieldValue(`Update [${this.props.text}]`);
<add> Scheduler.unstable_yieldValue(`Update [${this.props.text}]`);
<ide> }
<ide> componentWillUnmount() {
<del> Scheduler.yieldValue(`Unmount [${this.props.text}]`);
<add> Scheduler.unstable_yieldValue(`Unmount [${this.props.text}]`);
<ide> }
<ide> render() {
<ide> return <Text {...this.props} />;
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> class AsyncTextWithLifecycle extends React.Component {
<ide> componentDidMount() {
<del> Scheduler.yieldValue(`Mount [${this.props.text}]`);
<add> Scheduler.unstable_yieldValue(`Mount [${this.props.text}]`);
<ide> }
<ide> componentDidUpdate() {
<del> Scheduler.yieldValue(`Update [${this.props.text}]`);
<add> Scheduler.unstable_yieldValue(`Update [${this.props.text}]`);
<ide> }
<ide> componentWillUnmount() {
<del> Scheduler.yieldValue(`Unmount [${this.props.text}]`);
<add> Scheduler.unstable_yieldValue(`Unmount [${this.props.text}]`);
<ide> }
<ide> render() {
<ide> const text = this.props.text;
<ide> const ms = this.props.ms;
<ide> try {
<ide> TextResource.read([text, ms]);
<del> Scheduler.yieldValue(text);
<add> Scheduler.unstable_yieldValue(text);
<ide> return <span prop={text} />;
<ide> } catch (promise) {
<ide> if (typeof promise.then === 'function') {
<del> Scheduler.yieldValue(`Suspend! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
<ide> } else {
<del> Scheduler.yieldValue(`Error! [${text}]`);
<add> Scheduler.unstable_yieldValue(`Error! [${text}]`);
<ide> }
<ide> throw promise;
<ide> }
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> }
<ide>
<ide> ReactNoop.renderLegacySyncRoot(<App />, () =>
<del> Scheduler.yieldValue('Commit root'),
<add> Scheduler.unstable_yieldValue('Commit root'),
<ide> );
<ide> expect(Scheduler).toHaveYielded([
<ide> 'A',
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> it('suspends for longer if something took a long (CPU bound) time to render', async () => {
<ide> function Foo({renderContent}) {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <Suspense fallback={<Text text="Loading..." />}>
<ide> {renderContent ? <AsyncText text="A" ms={5000} /> : null}
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> expect(Scheduler).toFlushAndYield(['Foo']);
<ide>
<ide> ReactNoop.render(<Foo renderContent={true} />);
<del> Scheduler.advanceTime(100);
<add> Scheduler.unstable_advanceTime(100);
<ide> await advanceTimers(100);
<ide> // Start rendering
<ide> expect(Scheduler).toFlushAndYieldThrough(['Foo']);
<ide> // For some reason it took a long time to render Foo.
<del> Scheduler.advanceTime(1250);
<add> Scheduler.unstable_advanceTime(1250);
<ide> await advanceTimers(1250);
<ide> expect(Scheduler).toFlushAndYield([
<ide> // A suspends
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> expect(ReactNoop.getChildren()).toEqual([]);
<ide>
<ide> // Flush some of the time
<del> Scheduler.advanceTime(450);
<add> Scheduler.unstable_advanceTime(450);
<ide> await advanceTimers(450);
<ide> // Because we've already been waiting for so long we can
<ide> // wait a bit longer. Still nothing...
<ide> expect(Scheduler).toFlushWithoutYielding();
<ide> expect(ReactNoop.getChildren()).toEqual([]);
<ide>
<ide> // Eventually we'll show the fallback.
<del> Scheduler.advanceTime(500);
<add> Scheduler.unstable_advanceTime(500);
<ide> await advanceTimers(500);
<ide> // No need to rerender.
<ide> expect(Scheduler).toFlushWithoutYielding();
<ide> expect(ReactNoop.getChildren()).toEqual([span('Loading...')]);
<ide>
<ide> // Flush the promise completely
<del> Scheduler.advanceTime(4500);
<add> Scheduler.unstable_advanceTime(4500);
<ide> await advanceTimers(4500);
<ide> // Renders successfully
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [A]']);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> it('does not suspends if a fallback has been shown for a long time', async () => {
<ide> function Foo() {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <Suspense fallback={<Text text="Loading..." />}>
<ide> <AsyncText text="A" ms={5000} />
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> expect(ReactNoop.getChildren()).toEqual([span('Loading...')]);
<ide>
<ide> // Wait a long time.
<del> Scheduler.advanceTime(5000);
<add> Scheduler.unstable_advanceTime(5000);
<ide> await advanceTimers(5000);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [A]']);
<ide>
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> ]);
<ide>
<ide> // Flush the last promise completely
<del> Scheduler.advanceTime(5000);
<add> Scheduler.unstable_advanceTime(5000);
<ide> await advanceTimers(5000);
<ide> // Renders successfully
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [B]']);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> it('does suspend if a fallback has been shown for a short time', async () => {
<ide> function Foo() {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <Suspense fallback={<Text text="Loading..." />}>
<ide> <AsyncText text="A" ms={200} />
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> expect(ReactNoop.getChildren()).toEqual([span('Loading...')]);
<ide>
<ide> // Wait a short time.
<del> Scheduler.advanceTime(250);
<add> Scheduler.unstable_advanceTime(250);
<ide> await advanceTimers(250);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [A]']);
<ide>
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> // wait a bit longer. Still nothing...
<ide> expect(ReactNoop.getChildren()).toEqual([span('Loading...')]);
<ide>
<del> Scheduler.advanceTime(200);
<add> Scheduler.unstable_advanceTime(200);
<ide> await advanceTimers(200);
<ide>
<ide> // Before we commit another Promise resolves.
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> it('does not suspend for very long after a higher priority update', async () => {
<ide> function Foo({renderContent}) {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <Suspense fallback={<Text text="Loading..." />}>
<ide> {renderContent ? <AsyncText text="A" ms={5000} /> : null}
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> expect(Scheduler).toFlushAndYieldThrough(['Foo']);
<ide>
<ide> // Advance some time.
<del> Scheduler.advanceTime(100);
<add> Scheduler.unstable_advanceTime(100);
<ide> await advanceTimers(100);
<ide>
<ide> expect(Scheduler).toFlushAndYield([
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> expect(ReactNoop.getChildren()).toEqual([]);
<ide>
<ide> // Flush some of the time
<del> Scheduler.advanceTime(500);
<add> Scheduler.unstable_advanceTime(500);
<ide> expect(() => {
<ide> jest.advanceTimersByTime(500);
<ide> }).toWarnDev(
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> it('warns when suspending inside discrete update', async () => {
<ide> function A() {
<del> Scheduler.yieldValue('A');
<add> Scheduler.unstable_yieldValue('A');
<ide> TextResource.read(['A', 1000]);
<ide> return 'A';
<ide> }
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> // Timeout and commit the fallback
<ide> expect(() => {
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> }).toWarnDev(
<ide> 'The following components suspended during a user-blocking update: A, C',
<ide> {withoutStack: true},
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> it('shows the parent fallback if the inner fallback should be avoided', async () => {
<ide> function Foo({showC}) {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <Suspense fallback={<Text text="Initial load..." />}>
<ide> <Suspense
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> expect(ReactNoop.getChildren()).toEqual([span('Initial load...')]);
<ide>
<ide> // Eventually we resolve and show the data.
<del> Scheduler.advanceTime(5000);
<add> Scheduler.unstable_advanceTime(5000);
<ide> await advanceTimers(5000);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [A]']);
<ide> expect(Scheduler).toFlushAndYield(['A', 'B']);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> 'B',
<ide> ]);
<ide> // Flush to skip suspended time.
<del> Scheduler.advanceTime(600);
<add> Scheduler.unstable_advanceTime(600);
<ide> await advanceTimers(600);
<ide> // Since the optional suspense boundary is already showing its content,
<ide> // we have to use the inner fallback instead.
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> ]);
<ide>
<ide> // Later we load the data.
<del> Scheduler.advanceTime(5000);
<add> Scheduler.unstable_advanceTime(5000);
<ide> await advanceTimers(5000);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [C]']);
<ide> expect(Scheduler).toFlushAndYield(['A', 'C']);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> it('favors showing the inner fallback for nested top level avoided fallback', async () => {
<ide> function Foo({showB}) {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <Suspense
<ide> unstable_avoidThisFallback={true}
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> 'Loading B...',
<ide> ]);
<ide> // Flush to skip suspended time.
<del> Scheduler.advanceTime(600);
<add> Scheduler.unstable_advanceTime(600);
<ide> await advanceTimers(600);
<ide>
<ide> expect(ReactNoop.getChildren()).toEqual([span('A'), span('Loading B...')]);
<ide> });
<ide>
<ide> it('keeps showing an avoided parent fallback if it is already showing', async () => {
<ide> function Foo({showB}) {
<del> Scheduler.yieldValue('Foo');
<add> Scheduler.unstable_yieldValue('Foo');
<ide> return (
<ide> <Suspense fallback={<Text text="Initial load..." />}>
<ide> <Suspense
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> expect(ReactNoop.getChildren()).toEqual([span('A')]);
<ide>
<ide> // Flush to skip suspended time.
<del> Scheduler.advanceTime(600);
<add> Scheduler.unstable_advanceTime(600);
<ide> await advanceTimers(600);
<ide>
<ide> expect(ReactNoop.getChildren()).toEqual([span('A'), span('Loading B...')]);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> // Took a long time to render. This is to ensure we get a long suspense time.
<ide> // Could also use something like withSuspenseConfig to simulate this.
<del> Scheduler.advanceTime(1500);
<add> Scheduler.unstable_advanceTime(1500);
<ide> await advanceTimers(1500);
<ide>
<ide> expect(Scheduler).toFlushAndYield(['Suspend! [A]', 'Loading A...']);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> expect(ReactNoop.getChildren()).toEqual([]);
<ide>
<ide> // Advance time a little bit.
<del> Scheduler.advanceTime(150);
<add> Scheduler.unstable_advanceTime(150);
<ide> await advanceTimers(150);
<ide>
<ide> // We should not have committed yet because we had a long suspense time.
<ide> expect(ReactNoop.getChildren()).toEqual([]);
<ide>
<ide> // Flush to skip suspended time.
<del> Scheduler.advanceTime(600);
<add> Scheduler.unstable_advanceTime(600);
<ide> await advanceTimers(600);
<ide>
<ide> expect(ReactNoop.getChildren()).toEqual([span('Loading A...')]);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> expect(Scheduler).toFlushAndYield(['Suspend! [A]', 'Loading...']);
<ide> // Only a short time is needed to unsuspend the initial loading state.
<del> Scheduler.advanceTime(400);
<add> Scheduler.unstable_advanceTime(400);
<ide> await advanceTimers(400);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Loading...')]);
<ide>
<ide> // Later we load the data.
<del> Scheduler.advanceTime(5000);
<add> Scheduler.unstable_advanceTime(5000);
<ide> await advanceTimers(5000);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [A]']);
<ide> expect(Scheduler).toFlushAndYield(['A']);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> );
<ide>
<ide> expect(Scheduler).toFlushAndYield(['Suspend! [B]', 'Loading...']);
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> await advanceTimers(1000);
<ide> // Even after a second, we have still not yet flushed the loading state.
<ide> expect(ReactNoop.getChildren()).toEqual([span('A')]);
<del> Scheduler.advanceTime(1100);
<add> Scheduler.unstable_advanceTime(1100);
<ide> await advanceTimers(1100);
<ide> // After the timeout, we do show the loading state.
<ide> expect(ReactNoop.getChildren()).toEqual([
<ide> hiddenSpan('A'),
<ide> span('Loading...'),
<ide> ]);
<ide> // Later we load the data.
<del> Scheduler.advanceTime(3000);
<add> Scheduler.unstable_advanceTime(3000);
<ide> await advanceTimers(3000);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [B]']);
<ide> expect(Scheduler).toFlushAndYield(['B']);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> expect(Scheduler).toFlushAndYield(['Suspend! [A]', 'Loading...']);
<ide> // Only a short time is needed to unsuspend the initial loading state.
<del> Scheduler.advanceTime(400);
<add> Scheduler.unstable_advanceTime(400);
<ide> await advanceTimers(400);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Loading...')]);
<ide> });
<ide>
<ide> // Later we load the data.
<del> Scheduler.advanceTime(5000);
<add> Scheduler.unstable_advanceTime(5000);
<ide> await advanceTimers(5000);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [A]']);
<ide> expect(Scheduler).toFlushAndYield(['A']);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> );
<ide>
<ide> expect(Scheduler).toFlushAndYield(['Suspend! [B]', 'Loading...']);
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> await advanceTimers(1000);
<ide> // Even after a second, we have still not yet flushed the loading state.
<ide> expect(ReactNoop.getChildren()).toEqual([span('A')]);
<del> Scheduler.advanceTime(1100);
<add> Scheduler.unstable_advanceTime(1100);
<ide> await advanceTimers(1100);
<ide> // After the timeout, we do show the loading state.
<ide> expect(ReactNoop.getChildren()).toEqual([
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> ]);
<ide> });
<ide> // Later we load the data.
<del> Scheduler.advanceTime(3000);
<add> Scheduler.unstable_advanceTime(3000);
<ide> await advanceTimers(3000);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [B]']);
<ide> expect(Scheduler).toFlushAndYield(['B']);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> expect(Scheduler).toFlushAndYield(['Suspend! [A]', 'Loading...']);
<ide> // Only a short time is needed to unsuspend the initial loading state.
<del> Scheduler.advanceTime(400);
<add> Scheduler.unstable_advanceTime(400);
<ide> await advanceTimers(400);
<ide> expect(ReactNoop.getChildren()).toEqual([span('Loading...')]);
<ide> });
<ide>
<ide> // Later we load the data.
<del> Scheduler.advanceTime(5000);
<add> Scheduler.unstable_advanceTime(5000);
<ide> await advanceTimers(5000);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [A]']);
<ide> expect(Scheduler).toFlushAndYield(['A']);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> );
<ide>
<ide> expect(Scheduler).toFlushAndYield(['Suspend! [B]', 'Loading...']);
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> await advanceTimers(1000);
<ide> // Even after a second, we have still not yet flushed the loading state.
<ide> expect(ReactNoop.getChildren()).toEqual([span('A')]);
<del> Scheduler.advanceTime(1100);
<add> Scheduler.unstable_advanceTime(1100);
<ide> await advanceTimers(1100);
<ide> // After the timeout, we do show the loading state.
<ide> expect(ReactNoop.getChildren()).toEqual([
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> ]);
<ide> });
<ide> // Later we load the data.
<del> Scheduler.advanceTime(3000);
<add> Scheduler.unstable_advanceTime(3000);
<ide> await advanceTimers(3000);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [B]']);
<ide> expect(Scheduler).toFlushAndYield(['B']);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> // Initial render.
<ide> ReactNoop.render(<App page="A" />);
<ide> expect(Scheduler).toFlushAndYield(['Suspend! [A]', 'Loading...']);
<del> Scheduler.advanceTime(2000);
<add> Scheduler.unstable_advanceTime(2000);
<ide> await advanceTimers(2000);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [A]']);
<ide> expect(Scheduler).toFlushAndYield(['A']);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> expect(Scheduler).toFlushAndYield(['Suspend! [B]', 'Loading...']);
<ide> // Suspended
<ide> expect(ReactNoop.getChildren()).toEqual([span('A')]);
<del> Scheduler.advanceTime(500);
<add> Scheduler.unstable_advanceTime(500);
<ide> await advanceTimers(500);
<ide> // Committed loading state.
<ide> expect(ReactNoop.getChildren()).toEqual([
<ide> hiddenSpan('A'),
<ide> span('Loading...'),
<ide> ]);
<ide>
<del> Scheduler.advanceTime(2000);
<add> Scheduler.unstable_advanceTime(2000);
<ide> await advanceTimers(2000);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [B]']);
<ide> expect(Scheduler).toFlushAndYield(['B']);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> 'Loading...',
<ide> ]);
<ide> expect(ReactNoop.getChildren()).toEqual([span('B')]);
<del> Scheduler.advanceTime(1200);
<add> Scheduler.unstable_advanceTime(1200);
<ide> await advanceTimers(1200);
<ide> // Even after a second, we have still not yet flushed the loading state.
<ide> expect(ReactNoop.getChildren()).toEqual([span('B')]);
<del> Scheduler.advanceTime(1200);
<add> Scheduler.unstable_advanceTime(1200);
<ide> await advanceTimers(1200);
<ide> // After the two second timeout we show the loading state.
<ide> expect(ReactNoop.getChildren()).toEqual([
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> // Initial render.
<ide> ReactNoop.render(<App page="A" />);
<ide> expect(Scheduler).toFlushAndYield(['Hi!', 'Suspend! [A]', 'Loading...']);
<del> Scheduler.advanceTime(3000);
<add> Scheduler.unstable_advanceTime(3000);
<ide> await advanceTimers(3000);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [A]']);
<ide> expect(Scheduler).toFlushAndYield(['Hi!', 'A']);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> // Suspended
<ide> expect(ReactNoop.getChildren()).toEqual([span('Hi!'), span('A')]);
<del> Scheduler.advanceTime(1800);
<add> Scheduler.unstable_advanceTime(1800);
<ide> await advanceTimers(1800);
<ide> expect(Scheduler).toFlushAndYield([]);
<ide> // We should still be suspended here because this loading state should be avoided.
<ide> expect(ReactNoop.getChildren()).toEqual([span('Hi!'), span('A')]);
<del> Scheduler.advanceTime(1500);
<add> Scheduler.unstable_advanceTime(1500);
<ide> await advanceTimers(1500);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [B]']);
<ide> expect(ReactNoop.getChildren()).toEqual([
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> // Suspended
<ide> expect(ReactNoop.getChildren()).toEqual([span('Hi!'), span('A')]);
<del> Scheduler.advanceTime(1800);
<add> Scheduler.unstable_advanceTime(1800);
<ide> await advanceTimers(1800);
<ide> expect(Scheduler).toFlushAndYield([]);
<ide> // We should still be suspended here because this loading state should be avoided.
<ide> expect(ReactNoop.getChildren()).toEqual([span('Hi!'), span('A')]);
<del> Scheduler.advanceTime(1500);
<add> Scheduler.unstable_advanceTime(1500);
<ide> await advanceTimers(1500);
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [B]']);
<ide> expect(ReactNoop.getChildren()).toEqual([
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> transitionToPage('B');
<ide> // Rendering B is quick and we didn't have enough
<ide> // time to show the loading indicator.
<del> Scheduler.advanceTime(200);
<add> Scheduler.unstable_advanceTime(200);
<ide> await advanceTimers(200);
<ide> expect(Scheduler).toFlushAndYield(['A', 'L', 'B']);
<ide> expect(ReactNoop.getChildren()).toEqual([span('B')]);
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> transitionToPage('C');
<ide> // Rendering C is a bit slower so we've already showed
<ide> // the loading indicator.
<del> Scheduler.advanceTime(600);
<add> Scheduler.unstable_advanceTime(600);
<ide> await advanceTimers(600);
<ide> expect(Scheduler).toFlushAndYield(['B', 'L', 'C']);
<ide> // We're technically done now but we haven't shown the
<ide> // loading indicator for long enough yet so we'll suspend
<ide> // while we keep it on the screen a bit longer.
<ide> expect(ReactNoop.getChildren()).toEqual([span('B'), span('L')]);
<del> Scheduler.advanceTime(400);
<add> Scheduler.unstable_advanceTime(400);
<ide> await advanceTimers(400);
<ide> expect(ReactNoop.getChildren()).toEqual([span('C')]);
<ide> });
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide> transitionToPage('D');
<ide> // Rendering D is very slow so we've already showed
<ide> // the loading indicator.
<del> Scheduler.advanceTime(1000);
<add> Scheduler.unstable_advanceTime(1000);
<ide> await advanceTimers(1000);
<ide> expect(Scheduler).toFlushAndYield(['C', 'L', 'D']);
<ide> // However, since we exceeded the minimum time to show
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<ide>
<ide> // Resolve initial render
<ide> await ReactNoop.act(async () => {
<del> Scheduler.advanceTime(2000);
<add> Scheduler.unstable_advanceTime(2000);
<ide> await advanceTimers(2000);
<ide> });
<ide> expect(Scheduler).toHaveYielded([
<ide><path>packages/react-refresh/src/__tests__/ReactFresh-test.js
<ide> describe('ReactFresh', () => {
<ide> const AppV1 = prepare(() => {
<ide> function Hello() {
<ide> React.useLayoutEffect(() => {
<del> Scheduler.yieldValue('Hello#layout');
<add> Scheduler.unstable_yieldValue('Hello#layout');
<ide> });
<ide> const [val, setVal] = React.useState(0);
<ide> return (
<ide> describe('ReactFresh', () => {
<ide>
<ide> return function App({offscreen}) {
<ide> React.useLayoutEffect(() => {
<del> Scheduler.yieldValue('App#layout');
<add> Scheduler.unstable_yieldValue('App#layout');
<ide> });
<ide> return (
<ide> <div hidden={offscreen}>
<ide> describe('ReactFresh', () => {
<ide> patch(() => {
<ide> function Hello() {
<ide> React.useLayoutEffect(() => {
<del> Scheduler.yieldValue('Hello#layout');
<add> Scheduler.unstable_yieldValue('Hello#layout');
<ide> });
<ide> const [val, setVal] = React.useState(0);
<ide> return (
<ide> describe('ReactFresh', () => {
<ide> patch(() => {
<ide> function Hello() {
<ide> React.useLayoutEffect(() => {
<del> Scheduler.yieldValue('Hello#layout');
<add> Scheduler.unstable_yieldValue('Hello#layout');
<ide> });
<ide> const [val, setVal] = React.useState(0);
<ide> return (
<ide><path>packages/react-test-renderer/src/ReactTestRendererAct.js
<ide> const {ReactCurrentActingRendererSigil} = ReactSharedInternals;
<ide>
<ide> let hasWarnedAboutMissingMockScheduler = false;
<ide> const flushWork =
<del> Scheduler.unstable_flushWithoutYielding ||
<add> Scheduler.unstable_flushAllWithoutAsserting ||
<ide> function() {
<ide> if (warnAboutMissingMockScheduler === true) {
<ide> if (hasWarnedAboutMissingMockScheduler === false) {
<ide><path>packages/react-test-renderer/src/__tests__/ReactTestRenderer-test.js
<ide> describe('ReactTestRenderer', () => {
<ide> const root = ReactTestRenderer.create(<App text="initial" />);
<ide> PendingResources.initial('initial');
<ide> await Promise.resolve();
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(root.toJSON()).toEqual('initial');
<ide>
<ide> root.update(<App text="dynamic" />);
<ide> expect(root.toJSON()).toEqual('fallback');
<ide>
<ide> PendingResources.dynamic('dynamic');
<ide> await Promise.resolve();
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(root.toJSON()).toEqual('dynamic');
<ide>
<ide> done();
<ide> describe('ReactTestRenderer', () => {
<ide> const root = ReactTestRenderer.create(<App text="initial" />);
<ide> PendingResources.initial('initial');
<ide> await Promise.resolve();
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(root.toJSON().children).toEqual(['initial']);
<ide>
<ide> root.update(<App text="dynamic" />);
<ide> expect(root.toJSON().children).toEqual(['fallback']);
<ide>
<ide> PendingResources.dynamic('dynamic');
<ide> await Promise.resolve();
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> expect(root.toJSON().children).toEqual(['dynamic']);
<ide>
<ide> done();
<ide><path>packages/react-test-renderer/src/__tests__/ReactTestRendererAct-test.js
<ide> describe('ReactTestRenderer.act()', () => {
<ide> // This component will keep updating itself until step === 3
<ide> const [step, proceed] = useReducer(s => (s === 3 ? 3 : s + 1), 1);
<ide> useEffect(() => {
<del> Scheduler.yieldValue('Effect');
<add> Scheduler.unstable_yieldValue('Effect');
<ide> alreadyResolvedPromise.then(() => {
<del> Scheduler.yieldValue('Microtask');
<add> Scheduler.unstable_yieldValue('Microtask');
<ide> proceed();
<ide> });
<ide> });
<ide><path>packages/react-test-renderer/src/__tests__/ReactTestRendererAsync-test.js
<ide> describe('ReactTestRendererAsync', () => {
<ide>
<ide> it('flushAll returns array of yielded values', () => {
<ide> function Child(props) {
<del> Scheduler.yieldValue(props.children);
<add> Scheduler.unstable_yieldValue(props.children);
<ide> return props.children;
<ide> }
<ide> function Parent(props) {
<ide> describe('ReactTestRendererAsync', () => {
<ide>
<ide> it('flushThrough flushes until the expected values is yielded', () => {
<ide> function Child(props) {
<del> Scheduler.yieldValue(props.children);
<add> Scheduler.unstable_yieldValue(props.children);
<ide> return props.children;
<ide> }
<ide> function Parent(props) {
<ide> describe('ReactTestRendererAsync', () => {
<ide>
<ide> it('supports high priority interruptions', () => {
<ide> function Child(props) {
<del> Scheduler.yieldValue(props.children);
<add> Scheduler.unstable_yieldValue(props.children);
<ide> return props.children;
<ide> }
<ide>
<ide> describe('ReactTestRendererAsync', () => {
<ide> describe('Jest matchers', () => {
<ide> it('toFlushAndYieldThrough', () => {
<ide> const Yield = ({id}) => {
<del> Scheduler.yieldValue(id);
<add> Scheduler.unstable_yieldValue(id);
<ide> return id;
<ide> };
<ide>
<ide> describe('ReactTestRendererAsync', () => {
<ide>
<ide> it('toFlushAndYield', () => {
<ide> const Yield = ({id}) => {
<del> Scheduler.yieldValue(id);
<add> Scheduler.unstable_yieldValue(id);
<ide> return id;
<ide> };
<ide>
<ide> describe('ReactTestRendererAsync', () => {
<ide>
<ide> it('toFlushAndThrow', () => {
<ide> const Yield = ({id}) => {
<del> Scheduler.yieldValue(id);
<add> Scheduler.unstable_yieldValue(id);
<ide> return id;
<ide> };
<ide>
<ide> describe('ReactTestRendererAsync', () => {
<ide>
<ide> it('toHaveYielded', () => {
<ide> const Yield = ({id}) => {
<del> Scheduler.yieldValue(id);
<add> Scheduler.unstable_yieldValue(id);
<ide> return id;
<ide> };
<ide>
<ide> describe('ReactTestRendererAsync', () => {
<ide> ReactTestRenderer.create(<div />, {
<ide> unstable_isConcurrent: true,
<ide> });
<del> Scheduler.yieldValue('Something');
<add> Scheduler.unstable_yieldValue('Something');
<ide> expect(() => expect(Scheduler).toFlushWithoutYielding()).toThrow(
<ide> 'Log of yielded values is not empty.',
<ide> );
<ide><path>packages/react/src/__tests__/ReactDOMTracing-test.internal.js
<ide> describe('ReactDOMTracing', () => {
<ide> it('traces interaction through hidden subtree', () => {
<ide> const Child = () => {
<ide> const [didMount, setDidMount] = React.useState(false);
<del> Scheduler.yieldValue('Child');
<add> Scheduler.unstable_yieldValue('Child');
<ide> React.useEffect(
<ide> () => {
<ide> if (didMount) {
<del> Scheduler.yieldValue('Child:update');
<add> Scheduler.unstable_yieldValue('Child:update');
<ide> } else {
<del> Scheduler.yieldValue('Child:mount');
<add> Scheduler.unstable_yieldValue('Child:mount');
<ide> setDidMount(true);
<ide> }
<ide> },
<ide> describe('ReactDOMTracing', () => {
<ide> };
<ide>
<ide> const App = () => {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> React.useEffect(() => {
<del> Scheduler.yieldValue('App:mount');
<add> Scheduler.unstable_yieldValue('App:mount');
<ide> }, []);
<ide> return (
<ide> <div hidden={true}>
<ide> describe('ReactDOMTracing', () => {
<ide>
<ide> it('traces interaction through hidden subtree when there is other pending traced work', () => {
<ide> const Child = () => {
<del> Scheduler.yieldValue('Child');
<add> Scheduler.unstable_yieldValue('Child');
<ide> return <div />;
<ide> };
<ide>
<ide> let wrapped = null;
<ide>
<ide> const App = () => {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> React.useEffect(() => {
<ide> wrapped = SchedulerTracing.unstable_wrap(() => {});
<del> Scheduler.yieldValue('App:mount');
<add> Scheduler.unstable_yieldValue('App:mount');
<ide> }, []);
<ide> return (
<ide> <div hidden={true}>
<ide> describe('ReactDOMTracing', () => {
<ide> it('traces interaction through hidden subtree that schedules more idle/never work', () => {
<ide> const Child = () => {
<ide> const [didMount, setDidMount] = React.useState(false);
<del> Scheduler.yieldValue('Child');
<add> Scheduler.unstable_yieldValue('Child');
<ide> React.useLayoutEffect(
<ide> () => {
<ide> if (didMount) {
<del> Scheduler.yieldValue('Child:update');
<add> Scheduler.unstable_yieldValue('Child:update');
<ide> } else {
<del> Scheduler.yieldValue('Child:mount');
<add> Scheduler.unstable_yieldValue('Child:mount');
<ide> Scheduler.unstable_runWithPriority(
<ide> Scheduler.unstable_IdlePriority,
<ide> () => setDidMount(true),
<ide> describe('ReactDOMTracing', () => {
<ide> };
<ide>
<ide> const App = () => {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> React.useEffect(() => {
<del> Scheduler.yieldValue('App:mount');
<add> Scheduler.unstable_yieldValue('App:mount');
<ide> }, []);
<ide> return (
<ide> <div hidden={true}>
<ide> describe('ReactDOMTracing', () => {
<ide>
<ide> it('does not continue interactions across pre-existing idle work', () => {
<ide> const Child = () => {
<del> Scheduler.yieldValue('Child');
<add> Scheduler.unstable_yieldValue('Child');
<ide> return <div />;
<ide> };
<ide>
<ide> let update = null;
<ide>
<ide> const WithHiddenWork = () => {
<del> Scheduler.yieldValue('WithHiddenWork');
<add> Scheduler.unstable_yieldValue('WithHiddenWork');
<ide> return (
<ide> <div hidden={true}>
<ide> <Child />
<ide> describe('ReactDOMTracing', () => {
<ide> };
<ide>
<ide> const Updater = () => {
<del> Scheduler.yieldValue('Updater');
<add> Scheduler.unstable_yieldValue('Updater');
<ide> React.useEffect(() => {
<del> Scheduler.yieldValue('Updater:effect');
<add> Scheduler.unstable_yieldValue('Updater:effect');
<ide> });
<ide>
<ide> const setCount = React.useState(0)[1];
<ide> describe('ReactDOMTracing', () => {
<ide> };
<ide>
<ide> const App = () => {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> React.useEffect(() => {
<del> Scheduler.yieldValue('App:effect');
<add> Scheduler.unstable_yieldValue('App:effect');
<ide> });
<ide>
<ide> return (
<ide> describe('ReactDOMTracing', () => {
<ide>
<ide> it('should properly trace interactions when there is work of interleaved priorities', () => {
<ide> const Child = () => {
<del> Scheduler.yieldValue('Child');
<add> Scheduler.unstable_yieldValue('Child');
<ide> return <div />;
<ide> };
<ide>
<ide> describe('ReactDOMTracing', () => {
<ide> const MaybeHiddenWork = () => {
<ide> const [flag, setFlag] = React.useState(false);
<ide> scheduleUpdateWithHidden = () => setFlag(true);
<del> Scheduler.yieldValue('MaybeHiddenWork');
<add> Scheduler.unstable_yieldValue('MaybeHiddenWork');
<ide> React.useEffect(() => {
<del> Scheduler.yieldValue('MaybeHiddenWork:effect');
<add> Scheduler.unstable_yieldValue('MaybeHiddenWork:effect');
<ide> });
<ide> return flag ? (
<ide> <div hidden={true}>
<ide> describe('ReactDOMTracing', () => {
<ide> };
<ide>
<ide> const Updater = () => {
<del> Scheduler.yieldValue('Updater');
<add> Scheduler.unstable_yieldValue('Updater');
<ide> React.useEffect(() => {
<del> Scheduler.yieldValue('Updater:effect');
<add> Scheduler.unstable_yieldValue('Updater:effect');
<ide> });
<ide>
<ide> const setCount = React.useState(0)[1];
<ide> describe('ReactDOMTracing', () => {
<ide> };
<ide>
<ide> const App = () => {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> React.useEffect(() => {
<del> Scheduler.yieldValue('App:effect');
<add> Scheduler.unstable_yieldValue('App:effect');
<ide> });
<ide>
<ide> return (
<ide> describe('ReactDOMTracing', () => {
<ide> const SuspenseList = React.unstable_SuspenseList;
<ide> const Suspense = React.Suspense;
<ide> function Text({text}) {
<del> Scheduler.yieldValue(text);
<add> Scheduler.unstable_yieldValue(text);
<ide> React.useEffect(() => {
<del> Scheduler.yieldValue('Commit ' + text);
<add> Scheduler.unstable_yieldValue('Commit ' + text);
<ide> });
<ide> return <span>{text}</span>;
<ide> }
<ide> describe('ReactDOMTracing', () => {
<ide>
<ide> expect(Scheduler).toFlushAndYieldThrough(['A']);
<ide>
<del> Scheduler.advanceTime(300);
<add> Scheduler.unstable_advanceTime(300);
<ide> jest.advanceTimersByTime(300);
<ide>
<ide> expect(Scheduler).toFlushAndYieldThrough(['B']);
<ide>
<del> Scheduler.advanceTime(300);
<add> Scheduler.unstable_advanceTime(300);
<ide> jest.advanceTimersByTime(300);
<ide>
<ide> // Time has now elapsed for so long that we're just going to give up
<ide> describe('ReactDOMTracing', () => {
<ide>
<ide> root.render(<App />);
<ide> });
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> expect(ref.current).not.toBe(null);
<ide> describe('ReactDOMTracing', () => {
<ide>
<ide> root.render(<App />);
<ide> });
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> expect(ref.current).toBe(null);
<ide> describe('ReactDOMTracing', () => {
<ide> suspend = false;
<ide> resolve();
<ide> await promise;
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.runAllTimers();
<ide>
<ide> expect(ref.current).not.toBe(null);
<ide><path>packages/react/src/__tests__/ReactProfiler-test.internal.js
<ide> function loadModules({
<ide> }
<ide> render() {
<ide> // Simulate time passing when this component is rendered
<del> Scheduler.advanceTime(this.props.byAmount);
<add> Scheduler.unstable_advanceTime(this.props.byAmount);
<ide> return this.props.children || null;
<ide> }
<ide> };
<ide> function loadModules({
<ide> TextResource = ReactCache.unstable_createResource(([text, ms = 0]) => {
<ide> resourcePromise = new Promise((resolve, reject) =>
<ide> setTimeout(() => {
<del> Scheduler.yieldValue(`Promise resolved [${text}]`);
<add> Scheduler.unstable_yieldValue(`Promise resolved [${text}]`);
<ide> resolve(text);
<ide> }, ms),
<ide> );
<ide> function loadModules({
<ide> AsyncText = ({ms, text}) => {
<ide> try {
<ide> TextResource.read([text, ms]);
<del> Scheduler.yieldValue(`AsyncText [${text}]`);
<add> Scheduler.unstable_yieldValue(`AsyncText [${text}]`);
<ide> return text;
<ide> } catch (promise) {
<ide> if (typeof promise.then === 'function') {
<del> Scheduler.yieldValue(`Suspend [${text}]`);
<add> Scheduler.unstable_yieldValue(`Suspend [${text}]`);
<ide> } else {
<del> Scheduler.yieldValue(`Error [${text}]`);
<add> Scheduler.unstable_yieldValue(`Error [${text}]`);
<ide> }
<ide> throw promise;
<ide> }
<ide> };
<ide>
<ide> Text = ({text}) => {
<del> Scheduler.yieldValue(`Text [${text}]`);
<add> Scheduler.unstable_yieldValue(`Text [${text}]`);
<ide> return text;
<ide> };
<ide> }
<ide> describe('Profiler', () => {
<ide> const callback = jest.fn();
<ide>
<ide> const Yield = ({value}) => {
<del> Scheduler.yieldValue(value);
<add> Scheduler.unstable_yieldValue(value);
<ide> return null;
<ide> };
<ide>
<ide> describe('Profiler', () => {
<ide> return {
<ide> ...ActualScheduler,
<ide> unstable_now: function mockUnstableNow() {
<del> ActualScheduler.yieldValue('read current time');
<add> ActualScheduler.unstable_yieldValue('read current time');
<ide> return ActualScheduler.unstable_now();
<ide> },
<ide> };
<ide> describe('Profiler', () => {
<ide> it('logs render times for both mount and update', () => {
<ide> const callback = jest.fn();
<ide>
<del> Scheduler.advanceTime(5); // 0 -> 5
<add> Scheduler.unstable_advanceTime(5); // 0 -> 5
<ide>
<ide> const renderer = ReactTestRenderer.create(
<ide> <React.Profiler id="test" onRender={callback}>
<ide> describe('Profiler', () => {
<ide>
<ide> callback.mockReset();
<ide>
<del> Scheduler.advanceTime(20); // 15 -> 35
<add> Scheduler.unstable_advanceTime(20); // 15 -> 35
<ide>
<ide> renderer.update(
<ide> <React.Profiler id="test" onRender={callback}>
<ide> describe('Profiler', () => {
<ide>
<ide> callback.mockReset();
<ide>
<del> Scheduler.advanceTime(20); // 45 -> 65
<add> Scheduler.unstable_advanceTime(20); // 45 -> 65
<ide>
<ide> renderer.update(
<ide> <React.Profiler id="test" onRender={callback}>
<ide> describe('Profiler', () => {
<ide> it('includes render times of nested Profilers in their parent times', () => {
<ide> const callback = jest.fn();
<ide>
<del> Scheduler.advanceTime(5); // 0 -> 5
<add> Scheduler.unstable_advanceTime(5); // 0 -> 5
<ide>
<ide> ReactTestRenderer.create(
<ide> <React.Fragment>
<ide> describe('Profiler', () => {
<ide> it('traces sibling Profilers separately', () => {
<ide> const callback = jest.fn();
<ide>
<del> Scheduler.advanceTime(5); // 0 -> 5
<add> Scheduler.unstable_advanceTime(5); // 0 -> 5
<ide>
<ide> ReactTestRenderer.create(
<ide> <React.Fragment>
<ide> describe('Profiler', () => {
<ide> it('does not include time spent outside of profile root', () => {
<ide> const callback = jest.fn();
<ide>
<del> Scheduler.advanceTime(5); // 0 -> 5
<add> Scheduler.unstable_advanceTime(5); // 0 -> 5
<ide>
<ide> ReactTestRenderer.create(
<ide> <React.Fragment>
<ide> describe('Profiler', () => {
<ide> it('decreases actual time but not base time when sCU prevents an update', () => {
<ide> const callback = jest.fn();
<ide>
<del> Scheduler.advanceTime(5); // 0 -> 5
<add> Scheduler.unstable_advanceTime(5); // 0 -> 5
<ide>
<ide> const renderer = ReactTestRenderer.create(
<ide> <React.Profiler id="test" onRender={callback}>
<ide> describe('Profiler', () => {
<ide>
<ide> expect(callback).toHaveBeenCalledTimes(1);
<ide>
<del> Scheduler.advanceTime(30); // 28 -> 58
<add> Scheduler.unstable_advanceTime(30); // 28 -> 58
<ide>
<ide> renderer.update(
<ide> <React.Profiler id="test" onRender={callback}>
<ide> describe('Profiler', () => {
<ide> class WithLifecycles extends React.Component {
<ide> state = {};
<ide> static getDerivedStateFromProps() {
<del> Scheduler.advanceTime(3);
<add> Scheduler.unstable_advanceTime(3);
<ide> return null;
<ide> }
<ide> shouldComponentUpdate() {
<del> Scheduler.advanceTime(7);
<add> Scheduler.unstable_advanceTime(7);
<ide> return true;
<ide> }
<ide> render() {
<del> Scheduler.advanceTime(5);
<add> Scheduler.unstable_advanceTime(5);
<ide> return null;
<ide> }
<ide> }
<ide>
<ide> const callback = jest.fn();
<ide>
<del> Scheduler.advanceTime(5); // 0 -> 5
<add> Scheduler.unstable_advanceTime(5); // 0 -> 5
<ide>
<ide> const renderer = ReactTestRenderer.create(
<ide> <React.Profiler id="test" onRender={callback}>
<ide> <WithLifecycles />
<ide> </React.Profiler>,
<ide> );
<ide>
<del> Scheduler.advanceTime(15); // 13 -> 28
<add> Scheduler.unstable_advanceTime(15); // 13 -> 28
<ide>
<ide> renderer.update(
<ide> <React.Profiler id="test" onRender={callback}>
<ide> describe('Profiler', () => {
<ide> const callback = jest.fn();
<ide>
<ide> const Yield = ({renderTime}) => {
<del> Scheduler.advanceTime(renderTime);
<del> Scheduler.yieldValue('Yield:' + renderTime);
<add> Scheduler.unstable_advanceTime(renderTime);
<add> Scheduler.unstable_yieldValue('Yield:' + renderTime);
<ide> return null;
<ide> };
<ide>
<del> Scheduler.advanceTime(5); // 0 -> 5
<add> Scheduler.unstable_advanceTime(5); // 0 -> 5
<ide>
<ide> // Render partially, but run out of time before completing.
<ide> ReactTestRenderer.create(
<ide> describe('Profiler', () => {
<ide> const callback = jest.fn();
<ide>
<ide> const Yield = ({renderTime}) => {
<del> Scheduler.advanceTime(renderTime);
<del> Scheduler.yieldValue('Yield:' + renderTime);
<add> Scheduler.unstable_advanceTime(renderTime);
<add> Scheduler.unstable_yieldValue('Yield:' + renderTime);
<ide> return null;
<ide> };
<ide>
<del> Scheduler.advanceTime(5); // 0 -> 5
<add> Scheduler.unstable_advanceTime(5); // 0 -> 5
<ide>
<ide> // Render partially, but don't finish.
<ide> // This partial render should take 5ms of simulated time.
<ide> describe('Profiler', () => {
<ide> expect(callback).toHaveBeenCalledTimes(0);
<ide>
<ide> // Simulate time moving forward while frame is paused.
<del> Scheduler.advanceTime(50); // 10 -> 60
<add> Scheduler.unstable_advanceTime(50); // 10 -> 60
<ide>
<ide> // Flush the remaining work,
<ide> // Which should take an additional 10ms of simulated time.
<ide> describe('Profiler', () => {
<ide> const callback = jest.fn();
<ide>
<ide> const Yield = ({renderTime}) => {
<del> Scheduler.advanceTime(renderTime);
<del> Scheduler.yieldValue('Yield:' + renderTime);
<add> Scheduler.unstable_advanceTime(renderTime);
<add> Scheduler.unstable_yieldValue('Yield:' + renderTime);
<ide> return null;
<ide> };
<ide>
<del> Scheduler.advanceTime(5); // 0 -> 5
<add> Scheduler.unstable_advanceTime(5); // 0 -> 5
<ide>
<ide> // Render a partially update, but don't finish.
<ide> // This partial render should take 10ms of simulated time.
<ide> describe('Profiler', () => {
<ide> expect(callback).toHaveBeenCalledTimes(0);
<ide>
<ide> // Simulate time moving forward while frame is paused.
<del> Scheduler.advanceTime(100); // 15 -> 115
<add> Scheduler.unstable_advanceTime(100); // 15 -> 115
<ide>
<ide> // Interrupt with higher priority work.
<ide> // The interrupted work simulates an additional 5ms of time.
<ide> describe('Profiler', () => {
<ide> const callback = jest.fn();
<ide>
<ide> const Yield = ({renderTime}) => {
<del> Scheduler.advanceTime(renderTime);
<del> Scheduler.yieldValue('Yield:' + renderTime);
<add> Scheduler.unstable_advanceTime(renderTime);
<add> Scheduler.unstable_yieldValue('Yield:' + renderTime);
<ide> return null;
<ide> };
<ide>
<del> Scheduler.advanceTime(5); // 0 -> 5
<add> Scheduler.unstable_advanceTime(5); // 0 -> 5
<ide>
<ide> const renderer = ReactTestRenderer.create(
<ide> <React.Profiler id="test" onRender={callback}>
<ide> describe('Profiler', () => {
<ide>
<ide> callback.mockReset();
<ide>
<del> Scheduler.advanceTime(30); // 26 -> 56
<add> Scheduler.unstable_advanceTime(30); // 26 -> 56
<ide>
<ide> // Render a partially update, but don't finish.
<ide> // This partial render should take 3ms of simulated time.
<ide> describe('Profiler', () => {
<ide> expect(callback).toHaveBeenCalledTimes(0);
<ide>
<ide> // Simulate time moving forward while frame is paused.
<del> Scheduler.advanceTime(100); // 59 -> 159
<add> Scheduler.unstable_advanceTime(100); // 59 -> 159
<ide>
<ide> // Render another 5ms of simulated time.
<ide> expect(Scheduler).toFlushAndYieldThrough(['Yield:5']);
<ide> expect(callback).toHaveBeenCalledTimes(0);
<ide>
<ide> // Simulate time moving forward while frame is paused.
<del> Scheduler.advanceTime(100); // 164 -> 264
<add> Scheduler.unstable_advanceTime(100); // 164 -> 264
<ide>
<ide> // Interrupt with higher priority work.
<ide> // The interrupted work simulates an additional 11ms of time.
<ide> describe('Profiler', () => {
<ide> const callback = jest.fn();
<ide>
<ide> const Yield = ({renderTime}) => {
<del> Scheduler.advanceTime(renderTime);
<del> Scheduler.yieldValue('Yield:' + renderTime);
<add> Scheduler.unstable_advanceTime(renderTime);
<add> Scheduler.unstable_yieldValue('Yield:' + renderTime);
<ide> return null;
<ide> };
<ide>
<ide> describe('Profiler', () => {
<ide> state = {renderTime: 1};
<ide> render() {
<ide> first = this;
<del> Scheduler.advanceTime(this.state.renderTime);
<del> Scheduler.yieldValue('FirstComponent:' + this.state.renderTime);
<add> Scheduler.unstable_advanceTime(this.state.renderTime);
<add> Scheduler.unstable_yieldValue(
<add> 'FirstComponent:' + this.state.renderTime,
<add> );
<ide> return <Yield renderTime={4} />;
<ide> }
<ide> }
<ide> describe('Profiler', () => {
<ide> state = {renderTime: 2};
<ide> render() {
<ide> second = this;
<del> Scheduler.advanceTime(this.state.renderTime);
<del> Scheduler.yieldValue('SecondComponent:' + this.state.renderTime);
<add> Scheduler.unstable_advanceTime(this.state.renderTime);
<add> Scheduler.unstable_yieldValue(
<add> 'SecondComponent:' + this.state.renderTime,
<add> );
<ide> return <Yield renderTime={7} />;
<ide> }
<ide> }
<ide>
<del> Scheduler.advanceTime(5); // 0 -> 5
<add> Scheduler.unstable_advanceTime(5); // 0 -> 5
<ide>
<ide> const renderer = ReactTestRenderer.create(
<ide> <React.Profiler id="test" onRender={callback}>
<ide> describe('Profiler', () => {
<ide>
<ide> callback.mockClear();
<ide>
<del> Scheduler.advanceTime(100); // 19 -> 119
<add> Scheduler.unstable_advanceTime(100); // 19 -> 119
<ide>
<ide> // Render a partially update, but don't finish.
<ide> // This partial render will take 10ms of actual render time.
<ide> describe('Profiler', () => {
<ide> expect(callback).toHaveBeenCalledTimes(0);
<ide>
<ide> // Simulate time moving forward while frame is paused.
<del> Scheduler.advanceTime(100); // 129 -> 229
<add> Scheduler.unstable_advanceTime(100); // 129 -> 229
<ide>
<ide> // Interrupt with higher priority work.
<ide> // This simulates a total of 37ms of actual render time.
<ide> describe('Profiler', () => {
<ide> callback.mockClear();
<ide>
<ide> // Simulate time moving forward while frame is paused.
<del> Scheduler.advanceTime(100); // 266 -> 366
<add> Scheduler.unstable_advanceTime(100); // 266 -> 366
<ide>
<ide> // Resume the original low priority update, with rebased state.
<ide> // This simulates a total of 14ms of actual render time,
<ide> describe('Profiler', () => {
<ide> const callback = jest.fn();
<ide>
<ide> const ThrowsError = () => {
<del> Scheduler.advanceTime(3);
<add> Scheduler.unstable_advanceTime(3);
<ide> throw Error('expected error');
<ide> };
<ide>
<ide> describe('Profiler', () => {
<ide> this.setState({error});
<ide> }
<ide> render() {
<del> Scheduler.advanceTime(2);
<add> Scheduler.unstable_advanceTime(2);
<ide> return this.state.error === null ? (
<ide> this.props.children
<ide> ) : (
<ide> describe('Profiler', () => {
<ide> }
<ide> }
<ide>
<del> Scheduler.advanceTime(5); // 0 -> 5
<add> Scheduler.unstable_advanceTime(5); // 0 -> 5
<ide>
<ide> ReactTestRenderer.create(
<ide> <React.Profiler id="test" onRender={callback}>
<ide> describe('Profiler', () => {
<ide> const callback = jest.fn();
<ide>
<ide> const ThrowsError = () => {
<del> Scheduler.advanceTime(10);
<add> Scheduler.unstable_advanceTime(10);
<ide> throw Error('expected error');
<ide> };
<ide>
<ide> describe('Profiler', () => {
<ide> return {error};
<ide> }
<ide> render() {
<del> Scheduler.advanceTime(2);
<add> Scheduler.unstable_advanceTime(2);
<ide> return this.state.error === null ? (
<ide> this.props.children
<ide> ) : (
<ide> describe('Profiler', () => {
<ide> }
<ide> }
<ide>
<del> Scheduler.advanceTime(5); // 0 -> 5
<add> Scheduler.unstable_advanceTime(5); // 0 -> 5
<ide>
<ide> ReactTestRenderer.create(
<ide> <React.Profiler id="test" onRender={callback}>
<ide> describe('Profiler', () => {
<ide> it('reflects the most recently rendered id value', () => {
<ide> const callback = jest.fn();
<ide>
<del> Scheduler.advanceTime(5); // 0 -> 5
<add> Scheduler.unstable_advanceTime(5); // 0 -> 5
<ide>
<ide> const renderer = ReactTestRenderer.create(
<ide> <React.Profiler id="one" onRender={callback}>
<ide> describe('Profiler', () => {
<ide>
<ide> expect(callback).toHaveBeenCalledTimes(1);
<ide>
<del> Scheduler.advanceTime(20); // 7 -> 27
<add> Scheduler.unstable_advanceTime(20); // 7 -> 27
<ide>
<ide> renderer.update(
<ide> <React.Profiler id="two" onRender={callback}>
<ide> describe('Profiler', () => {
<ide>
<ide> class ClassComponent extends React.Component {
<ide> componentDidMount() {
<del> Scheduler.advanceTime(5);
<add> Scheduler.unstable_advanceTime(5);
<ide> classComponentMounted = true;
<ide> }
<ide> render() {
<del> Scheduler.advanceTime(2);
<add> Scheduler.unstable_advanceTime(2);
<ide> return null;
<ide> }
<ide> }
<ide> describe('Profiler', () => {
<ide> loadModules({useNoopRenderer: true});
<ide>
<ide> const Child = ({duration, id}) => {
<del> Scheduler.advanceTime(duration);
<del> Scheduler.yieldValue(`Child:render:${id}`);
<add> Scheduler.unstable_advanceTime(duration);
<add> Scheduler.unstable_yieldValue(`Child:render:${id}`);
<ide> return null;
<ide> };
<ide>
<ide> class Parent extends React.Component {
<ide> componentDidMount() {
<del> Scheduler.yieldValue(`Parent:componentDidMount:${this.props.id}`);
<add> Scheduler.unstable_yieldValue(
<add> `Parent:componentDidMount:${this.props.id}`,
<add> );
<ide> }
<ide> render() {
<ide> const {duration, id} = this.props;
<ide> describe('Profiler', () => {
<ide> }
<ide> }
<ide>
<del> Scheduler.advanceTime(50);
<add> Scheduler.unstable_advanceTime(50);
<ide>
<ide> ReactNoop.renderToRootWithID(<Parent duration={3} id="one" />, 'one');
<ide>
<ide> describe('Profiler', () => {
<ide>
<ide> expect(ReactNoop.getRoot('one').current.actualDuration).toBe(0);
<ide>
<del> Scheduler.advanceTime(100);
<add> Scheduler.unstable_advanceTime(100);
<ide>
<ide> // Process some async work, but yield before committing it.
<ide> ReactNoop.renderToRootWithID(<Parent duration={7} id="two" />, 'two');
<ide> expect(Scheduler).toFlushAndYieldThrough(['Child:render:two']);
<ide>
<del> Scheduler.advanceTime(150);
<add> Scheduler.unstable_advanceTime(150);
<ide>
<ide> // Commit the previously paused, batched work.
<ide> commitFirstRender(['Parent:componentDidMount:one']);
<ide>
<ide> expect(ReactNoop.getRoot('one').current.actualDuration).toBe(6);
<ide> expect(ReactNoop.getRoot('two').current.actualDuration).toBe(0);
<ide>
<del> Scheduler.advanceTime(200);
<add> Scheduler.unstable_advanceTime(200);
<ide>
<ide> expect(Scheduler).toFlushAndYield([
<ide> 'Child:render:two',
<ide> describe('Profiler', () => {
<ide> describe('error handling', () => {
<ide> it('should cover errors thrown in onWorkScheduled', () => {
<ide> function Component({children}) {
<del> Scheduler.yieldValue('Component:' + children);
<add> Scheduler.unstable_yieldValue('Component:' + children);
<ide> return children;
<ide> }
<ide>
<ide> describe('Profiler', () => {
<ide>
<ide> it('should cover errors thrown in onWorkStarted', () => {
<ide> function Component({children}) {
<del> Scheduler.yieldValue('Component:' + children);
<add> Scheduler.unstable_yieldValue('Component:' + children);
<ide> return children;
<ide> }
<ide>
<ide> describe('Profiler', () => {
<ide>
<ide> it('should cover errors thrown in onWorkStopped', () => {
<ide> function Component({children}) {
<del> Scheduler.yieldValue('Component:' + children);
<add> Scheduler.unstable_yieldValue('Component:' + children);
<ide> return children;
<ide> }
<ide>
<ide> describe('Profiler', () => {
<ide>
<ide> it('should cover errors thrown in onInteractionScheduledWorkCompleted', () => {
<ide> function Component({children}) {
<del> Scheduler.yieldValue('Component:' + children);
<add> Scheduler.unstable_yieldValue('Component:' + children);
<ide> return children;
<ide> }
<ide>
<ide> describe('Profiler', () => {
<ide> let instance = null;
<ide>
<ide> const Yield = ({duration = 10, value}) => {
<del> Scheduler.advanceTime(duration);
<del> Scheduler.yieldValue(value);
<add> Scheduler.unstable_advanceTime(duration);
<add> Scheduler.unstable_yieldValue(value);
<ide> return null;
<ide> };
<ide>
<ide> describe('Profiler', () => {
<ide> }
<ide> }
<ide>
<del> Scheduler.advanceTime(1);
<add> Scheduler.unstable_advanceTime(1);
<ide>
<ide> const interactionCreation = {
<ide> id: 0,
<ide> describe('Profiler', () => {
<ide> onWorkStarted.mockClear();
<ide> onWorkStopped.mockClear();
<ide>
<del> Scheduler.advanceTime(3);
<add> Scheduler.unstable_advanceTime(3);
<ide>
<ide> let didRunCallback = false;
<ide>
<ide> describe('Profiler', () => {
<ide> onWorkStarted.mockClear();
<ide> onWorkStopped.mockClear();
<ide>
<del> Scheduler.advanceTime(17);
<add> Scheduler.unstable_advanceTime(17);
<ide>
<ide> // Verify that updating state again does not re-log our interaction.
<ide> instance.setState({count: 3});
<ide> describe('Profiler', () => {
<ide>
<ide> onRender.mockClear();
<ide>
<del> Scheduler.advanceTime(3);
<add> Scheduler.unstable_advanceTime(3);
<ide>
<ide> // Verify that root updates are also associated with traced events.
<ide> const interactionTwo = {
<ide> describe('Profiler', () => {
<ide> state = {count: 0};
<ide> render() {
<ide> first = this;
<del> Scheduler.yieldValue('FirstComponent');
<add> Scheduler.unstable_yieldValue('FirstComponent');
<ide> return null;
<ide> }
<ide> }
<ide> describe('Profiler', () => {
<ide> state = {count: 0};
<ide> render() {
<ide> second = this;
<del> Scheduler.yieldValue('SecondComponent');
<add> Scheduler.unstable_yieldValue('SecondComponent');
<ide> return null;
<ide> }
<ide> }
<ide>
<del> Scheduler.advanceTime(5);
<add> Scheduler.unstable_advanceTime(5);
<ide>
<ide> const renderer = ReactTestRenderer.create(
<ide> <React.Profiler id="test" onRender={onRender}>
<ide> describe('Profiler', () => {
<ide>
<ide> onRender.mockClear();
<ide>
<del> Scheduler.advanceTime(100);
<add> Scheduler.unstable_advanceTime(100);
<ide>
<ide> const interactionLowPri = {
<ide> id: 0,
<ide> describe('Profiler', () => {
<ide> ).toMatchInteractions([interactionLowPri]);
<ide> expect(getWorkForReactThreads(onWorkStopped)).toHaveLength(0);
<ide>
<del> Scheduler.advanceTime(100);
<add> Scheduler.unstable_advanceTime(100);
<ide>
<ide> const interactionHighPri = {
<ide> id: 1,
<ide> describe('Profiler', () => {
<ide>
<ide> onRender.mockClear();
<ide>
<del> Scheduler.advanceTime(100);
<add> Scheduler.unstable_advanceTime(100);
<ide>
<ide> // Resume the original low priority update, with rebased state.
<ide> // Verify the low priority update was retained.
<ide> describe('Profiler', () => {
<ide> count: 0,
<ide> };
<ide> componentDidMount() {
<del> Scheduler.advanceTime(10); // Advance timer to keep commits separate
<add> Scheduler.unstable_advanceTime(10); // Advance timer to keep commits separate
<ide> this.setState({count: 1}); // Intentional cascading update
<ide> }
<ide> componentDidUpdate(prevProps, prevState) {
<ide> if (this.state.count === 2 && prevState.count === 1) {
<del> Scheduler.advanceTime(10); // Advance timer to keep commits separate
<add> Scheduler.unstable_advanceTime(10); // Advance timer to keep commits separate
<ide> this.setState({count: 3}); // Intentional cascading update
<ide> }
<ide> }
<ide> render() {
<ide> instance = this;
<del> Scheduler.yieldValue('Example:' + this.state.count);
<add> Scheduler.unstable_yieldValue('Example:' + this.state.count);
<ide> return null;
<ide> }
<ide> }
<ide> describe('Profiler', () => {
<ide> expect(getWorkForReactThreads(onWorkStarted)).toHaveLength(2);
<ide> expect(getWorkForReactThreads(onWorkStopped)).toHaveLength(2);
<ide>
<del> Scheduler.advanceTime(5);
<add> Scheduler.unstable_advanceTime(5);
<ide>
<ide> // Flush async work (outside of traced scope)
<ide> // This will cause an intentional cascading update from did-update
<ide> describe('Profiler', () => {
<ide>
<ide> class Child extends React.Component {
<ide> render() {
<del> Scheduler.yieldValue('Child:' + this.props.count);
<add> Scheduler.unstable_yieldValue('Child:' + this.props.count);
<ide> return null;
<ide> }
<ide> }
<ide> describe('Profiler', () => {
<ide> }
<ide> }
<ide>
<del> Scheduler.advanceTime(1);
<add> Scheduler.unstable_advanceTime(1);
<ide>
<ide> ReactTestRenderer.create(<Parent />, {
<ide> unstable_isConcurrent: true,
<ide> describe('Profiler', () => {
<ide> const monkey = React.createRef();
<ide> class Monkey extends React.Component {
<ide> render() {
<del> Scheduler.yieldValue('Monkey');
<add> Scheduler.unstable_yieldValue('Monkey');
<ide> return null;
<ide> }
<ide> }
<ide> describe('Profiler', () => {
<ide> },
<ide> );
<ide>
<del> Scheduler.advanceTime(400);
<add> Scheduler.unstable_advanceTime(400);
<ide> await awaitableAdvanceTimers(400);
<ide>
<ide> expect(Scheduler).toFlushAndYield([
<ide> describe('Profiler', () => {
<ide> ]);
<ide> expect(onInteractionScheduledWorkCompleted).not.toHaveBeenCalled();
<ide>
<del> Scheduler.advanceTime(500);
<add> Scheduler.unstable_advanceTime(500);
<ide> await awaitableAdvanceTimers(500);
<ide>
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [loaded]']);
<ide> describe('Profiler', () => {
<ide> ).toMatchInteraction(highPriUpdateInteraction);
<ide> onInteractionScheduledWorkCompleted.mockClear();
<ide>
<del> Scheduler.advanceTime(100);
<add> Scheduler.unstable_advanceTime(100);
<ide> jest.advanceTimersByTime(100);
<ide> await originalPromise;
<ide>
<ide> describe('Profiler', () => {
<ide> expect(onInteractionScheduledWorkCompleted).not.toHaveBeenCalled();
<ide> expect(onRender).not.toHaveBeenCalled();
<ide>
<del> Scheduler.advanceTime(50);
<add> Scheduler.unstable_advanceTime(50);
<ide> jest.advanceTimersByTime(50);
<ide>
<ide> const highPriUpdateInteraction = {
<ide> describe('Profiler', () => {
<ide>
<ide> expect(onInteractionScheduledWorkCompleted).toHaveBeenCalledTimes(0);
<ide>
<del> Scheduler.advanceTime(50);
<add> Scheduler.unstable_advanceTime(50);
<ide> jest.advanceTimersByTime(50);
<ide> await originalPromise;
<ide> expect(Scheduler).toHaveYielded(['Promise resolved [loaded]']);
<ide><path>packages/react/src/__tests__/ReactProfilerDOM-test.internal.js
<ide> describe('ProfilerDOM', () => {
<ide> resourcePromise.then(
<ide> SchedulerTracing.unstable_wrap(() => {
<ide> jest.runAllTimers();
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide>
<ide> expect(element.textContent).toBe('Text');
<ide> expect(onInteractionTraced).toHaveBeenCalledTimes(1);
<ide> describe('ProfilerDOM', () => {
<ide> }),
<ide> );
<ide>
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> });
<ide>
<ide> expect(onInteractionTraced).toHaveBeenCalledTimes(1);
<ide> expect(onInteractionTraced).toHaveBeenLastNotifiedOfInteraction(
<ide> interaction,
<ide> );
<ide> expect(onInteractionScheduledWorkCompleted).not.toHaveBeenCalled();
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> jest.advanceTimersByTime(500);
<ide> });
<ide> });
<ide><path>packages/react/src/__tests__/ReactProfilerDevToolsIntegration-test.internal.js
<ide> describe('ReactProfiler DevTools integration', () => {
<ide> }
<ide> render() {
<ide> // Simulate time passing when this component is rendered
<del> Scheduler.advanceTime(this.props.byAmount);
<add> Scheduler.unstable_advanceTime(this.props.byAmount);
<ide> return this.props.children || null;
<ide> }
<ide> };
<ide> });
<ide>
<ide> it('should auto-Profile all fibers if the DevTools hook is detected', () => {
<ide> const App = ({multiplier}) => {
<del> Scheduler.advanceTime(2);
<add> Scheduler.unstable_advanceTime(2);
<ide> return (
<ide> <React.Profiler id="Profiler" onRender={onRender}>
<ide> <AdvanceTime byAmount={3 * multiplier} shouldComponentUpdate={true} />
<ide> describe('ReactProfiler DevTools integration', () => {
<ide> });
<ide>
<ide> it('should reset the fiber stack correctly after an error when profiling host roots', () => {
<del> Scheduler.advanceTime(20);
<add> Scheduler.unstable_advanceTime(20);
<ide>
<ide> const rendered = ReactTestRenderer.create(
<ide> <div>
<ide> <AdvanceTime byAmount={2} />
<ide> </div>,
<ide> );
<ide>
<del> Scheduler.advanceTime(20);
<add> Scheduler.unstable_advanceTime(20);
<ide>
<ide> expect(() => {
<ide> rendered.update(
<ide> describe('ReactProfiler DevTools integration', () => {
<ide> );
<ide> }).toThrow();
<ide>
<del> Scheduler.advanceTime(20);
<add> Scheduler.unstable_advanceTime(20);
<ide>
<ide> // But this should render correctly, if the profiler's fiber stack has been reset.
<ide> rendered.update(
<ide> describe('ReactProfiler DevTools integration', () => {
<ide> const root = rendered.root._currentFiber().return;
<ide> expect(root.stateNode.memoizedInteractions).toContainNoInteractions();
<ide>
<del> Scheduler.advanceTime(10);
<add> Scheduler.unstable_advanceTime(10);
<ide>
<ide> const eventTime = Scheduler.unstable_now();
<ide>
<ide><path>packages/react/src/__tests__/ReactStrictMode-test.internal.js
<ide> describe('ReactStrictMode', () => {
<ide> unstable_isConcurrent: true,
<ide> });
<ide> root.update(<AsyncRoot />);
<del> expect(() => Scheduler.flushAll()).toWarnDev(
<add> expect(() => Scheduler.unstable_flushAll()).toWarnDev(
<ide> 'Unsafe lifecycle methods were found within a strict-mode tree:' +
<ide> '\n\ncomponentWillMount: Please update the following components ' +
<ide> 'to use componentDidMount instead: AsyncRoot' +
<ide> describe('ReactStrictMode', () => {
<ide>
<ide> // Dedupe
<ide> root.update(<AsyncRoot />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> });
<ide>
<ide> it('should coalesce warnings by lifecycle name', () => {
<ide> describe('ReactStrictMode', () => {
<ide> root.update(<AsyncRoot />);
<ide>
<ide> expect(() => {
<del> expect(() => Scheduler.flushAll()).toWarnDev(
<add> expect(() => Scheduler.unstable_flushAll()).toWarnDev(
<ide> 'Unsafe lifecycle methods were found within a strict-mode tree:' +
<ide> '\n\ncomponentWillMount: Please update the following components ' +
<ide> 'to use componentDidMount instead: AsyncRoot, Parent' +
<ide> describe('ReactStrictMode', () => {
<ide>
<ide> // Dedupe
<ide> root.update(<AsyncRoot />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> });
<ide>
<ide> it('should warn about components not present during the initial render', () => {
<ide> describe('ReactStrictMode', () => {
<ide> unstable_isConcurrent: true,
<ide> });
<ide> root.update(<AsyncRoot foo={true} />);
<del> expect(() => Scheduler.flushAll()).toWarnDev(
<add> expect(() => Scheduler.unstable_flushAll()).toWarnDev(
<ide> 'Unsafe lifecycle methods were found within a strict-mode tree:' +
<ide> '\n\ncomponentWillMount: Please update the following components ' +
<ide> 'to use componentDidMount instead: Foo' +
<ide> describe('ReactStrictMode', () => {
<ide> );
<ide>
<ide> root.update(<AsyncRoot foo={false} />);
<del> expect(() => Scheduler.flushAll()).toWarnDev(
<add> expect(() => Scheduler.unstable_flushAll()).toWarnDev(
<ide> 'Unsafe lifecycle methods were found within a strict-mode tree:' +
<ide> '\n\ncomponentWillMount: Please update the following components ' +
<ide> 'to use componentDidMount instead: Bar' +
<ide> describe('ReactStrictMode', () => {
<ide>
<ide> // Dedupe
<ide> root.update(<AsyncRoot foo={true} />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> root.update(<AsyncRoot foo={false} />);
<del> Scheduler.flushAll();
<add> Scheduler.unstable_flushAll();
<ide> });
<ide>
<ide> it('should also warn inside of "strict" mode trees', () => {
<ide><path>packages/react/src/__tests__/forwardRef-test.internal.js
<ide> describe('forwardRef', () => {
<ide> it('should work without a ref to be forwarded', () => {
<ide> class Child extends React.Component {
<ide> render() {
<del> Scheduler.yieldValue(this.props.value);
<add> Scheduler.unstable_yieldValue(this.props.value);
<ide> return null;
<ide> }
<ide> }
<ide> describe('forwardRef', () => {
<ide> it('should forward a ref for a single child', () => {
<ide> class Child extends React.Component {
<ide> render() {
<del> Scheduler.yieldValue(this.props.value);
<add> Scheduler.unstable_yieldValue(this.props.value);
<ide> return null;
<ide> }
<ide> }
<ide> describe('forwardRef', () => {
<ide> it('should forward a ref for multiple children', () => {
<ide> class Child extends React.Component {
<ide> render() {
<del> Scheduler.yieldValue(this.props.value);
<add> Scheduler.unstable_yieldValue(this.props.value);
<ide> return null;
<ide> }
<ide> }
<ide> describe('forwardRef', () => {
<ide> super(props);
<ide> }
<ide> render() {
<del> Scheduler.yieldValue(this.props.value);
<add> Scheduler.unstable_yieldValue(this.props.value);
<ide> return null;
<ide> }
<ide> }
<ide> describe('forwardRef', () => {
<ide> class ErrorBoundary extends React.Component {
<ide> state = {error: null};
<ide> componentDidCatch(error) {
<del> Scheduler.yieldValue('ErrorBoundary.componentDidCatch');
<add> Scheduler.unstable_yieldValue('ErrorBoundary.componentDidCatch');
<ide> this.setState({error});
<ide> }
<ide> render() {
<ide> if (this.state.error) {
<del> Scheduler.yieldValue('ErrorBoundary.render: catch');
<add> Scheduler.unstable_yieldValue('ErrorBoundary.render: catch');
<ide> return null;
<ide> }
<del> Scheduler.yieldValue('ErrorBoundary.render: try');
<add> Scheduler.unstable_yieldValue('ErrorBoundary.render: try');
<ide> return this.props.children;
<ide> }
<ide> }
<ide>
<ide> class BadRender extends React.Component {
<ide> render() {
<del> Scheduler.yieldValue('BadRender throw');
<add> Scheduler.unstable_yieldValue('BadRender throw');
<ide> throw new Error('oops!');
<ide> }
<ide> }
<ide>
<ide> function Wrapper(props) {
<del> Scheduler.yieldValue('Wrapper');
<add> Scheduler.unstable_yieldValue('Wrapper');
<ide> return <BadRender {...props} ref={props.forwardedRef} />;
<ide> }
<ide>
<ide> describe('forwardRef', () => {
<ide>
<ide> class Inner extends React.Component {
<ide> render() {
<del> Scheduler.yieldValue('Inner');
<add> Scheduler.unstable_yieldValue('Inner');
<ide> inst = this;
<ide> return <div ref={this.props.forwardedRef} />;
<ide> }
<ide> }
<ide>
<ide> function Middle(props) {
<del> Scheduler.yieldValue('Middle');
<add> Scheduler.unstable_yieldValue('Middle');
<ide> return <Inner {...props} />;
<ide> }
<ide>
<ide> const Forward = React.forwardRef((props, ref) => {
<del> Scheduler.yieldValue('Forward');
<add> Scheduler.unstable_yieldValue('Forward');
<ide> return <Middle {...props} forwardedRef={ref} />;
<ide> });
<ide>
<ide> function App() {
<del> Scheduler.yieldValue('App');
<add> Scheduler.unstable_yieldValue('App');
<ide> return <Forward />;
<ide> }
<ide>
<ide><path>packages/scheduler/src/__tests__/Scheduler-test.js
<ide> describe('Scheduler', () => {
<ide> });
<ide>
<ide> it('flushes work incrementally', () => {
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('A'));
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('B'));
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('C'));
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('D'));
<add> scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('A'));
<add> scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('B'));
<add> scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('C'));
<add> scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('D'));
<ide>
<ide> expect(Scheduler).toFlushAndYieldThrough(['A', 'B']);
<ide> expect(Scheduler).toFlushAndYieldThrough(['C']);
<ide> expect(Scheduler).toFlushAndYield(['D']);
<ide> });
<ide>
<ide> it('cancels work', () => {
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('A'));
<add> scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('A'));
<ide> const callbackHandleB = scheduleCallback(NormalPriority, () =>
<del> Scheduler.yieldValue('B'),
<add> Scheduler.unstable_yieldValue('B'),
<ide> );
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('C'));
<add> scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('C'));
<ide>
<ide> cancelCallback(callbackHandleB);
<ide>
<ide> describe('Scheduler', () => {
<ide> });
<ide>
<ide> it('executes the highest priority callbacks first', () => {
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('A'));
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('B'));
<add> scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('A'));
<add> scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('B'));
<ide>
<ide> // Yield before B is flushed
<ide> expect(Scheduler).toFlushAndYieldThrough(['A']);
<ide>
<del> scheduleCallback(UserBlockingPriority, () => Scheduler.yieldValue('C'));
<del> scheduleCallback(UserBlockingPriority, () => Scheduler.yieldValue('D'));
<add> scheduleCallback(UserBlockingPriority, () =>
<add> Scheduler.unstable_yieldValue('C'),
<add> );
<add> scheduleCallback(UserBlockingPriority, () =>
<add> Scheduler.unstable_yieldValue('D'),
<add> );
<ide>
<ide> // C and D should come first, because they are higher priority
<ide> expect(Scheduler).toFlushAndYield(['C', 'D', 'B']);
<ide> });
<ide>
<ide> it('expires work', () => {
<ide> scheduleCallback(NormalPriority, didTimeout => {
<del> Scheduler.advanceTime(100);
<del> Scheduler.yieldValue(`A (did timeout: ${didTimeout})`);
<add> Scheduler.unstable_advanceTime(100);
<add> Scheduler.unstable_yieldValue(`A (did timeout: ${didTimeout})`);
<ide> });
<ide> scheduleCallback(UserBlockingPriority, didTimeout => {
<del> Scheduler.advanceTime(100);
<del> Scheduler.yieldValue(`B (did timeout: ${didTimeout})`);
<add> Scheduler.unstable_advanceTime(100);
<add> Scheduler.unstable_yieldValue(`B (did timeout: ${didTimeout})`);
<ide> });
<ide> scheduleCallback(UserBlockingPriority, didTimeout => {
<del> Scheduler.advanceTime(100);
<del> Scheduler.yieldValue(`C (did timeout: ${didTimeout})`);
<add> Scheduler.unstable_advanceTime(100);
<add> Scheduler.unstable_yieldValue(`C (did timeout: ${didTimeout})`);
<ide> });
<ide>
<ide> // Advance time, but not by enough to expire any work
<del> Scheduler.advanceTime(249);
<add> Scheduler.unstable_advanceTime(249);
<ide> expect(Scheduler).toHaveYielded([]);
<ide>
<ide> // Schedule a few more callbacks
<ide> scheduleCallback(NormalPriority, didTimeout => {
<del> Scheduler.advanceTime(100);
<del> Scheduler.yieldValue(`D (did timeout: ${didTimeout})`);
<add> Scheduler.unstable_advanceTime(100);
<add> Scheduler.unstable_yieldValue(`D (did timeout: ${didTimeout})`);
<ide> });
<ide> scheduleCallback(NormalPriority, didTimeout => {
<del> Scheduler.advanceTime(100);
<del> Scheduler.yieldValue(`E (did timeout: ${didTimeout})`);
<add> Scheduler.unstable_advanceTime(100);
<add> Scheduler.unstable_yieldValue(`E (did timeout: ${didTimeout})`);
<ide> });
<ide>
<ide> // Advance by just a bit more to expire the user blocking callbacks
<del> Scheduler.advanceTime(1);
<add> Scheduler.unstable_advanceTime(1);
<ide> expect(Scheduler).toHaveYielded([
<ide> 'B (did timeout: true)',
<ide> 'C (did timeout: true)',
<ide> ]);
<ide>
<ide> // Expire A
<del> Scheduler.advanceTime(4600);
<add> Scheduler.unstable_advanceTime(4600);
<ide> expect(Scheduler).toHaveYielded(['A (did timeout: true)']);
<ide>
<ide> // Flush the rest without expiring
<ide> describe('Scheduler', () => {
<ide> });
<ide>
<ide> it('has a default expiration of ~5 seconds', () => {
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('A'));
<add> scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('A'));
<ide>
<del> Scheduler.advanceTime(4999);
<add> Scheduler.unstable_advanceTime(4999);
<ide> expect(Scheduler).toHaveYielded([]);
<ide>
<del> Scheduler.advanceTime(1);
<add> Scheduler.unstable_advanceTime(1);
<ide> expect(Scheduler).toHaveYielded(['A']);
<ide> });
<ide>
<ide> it('continues working on same task after yielding', () => {
<ide> scheduleCallback(NormalPriority, () => {
<del> Scheduler.advanceTime(100);
<del> Scheduler.yieldValue('A');
<add> Scheduler.unstable_advanceTime(100);
<add> Scheduler.unstable_yieldValue('A');
<ide> });
<ide> scheduleCallback(NormalPriority, () => {
<del> Scheduler.advanceTime(100);
<del> Scheduler.yieldValue('B');
<add> Scheduler.unstable_advanceTime(100);
<add> Scheduler.unstable_yieldValue('B');
<ide> });
<ide>
<ide> let didYield = false;
<ide> const tasks = [['C1', 100], ['C2', 100], ['C3', 100]];
<ide> const C = () => {
<ide> while (tasks.length > 0) {
<ide> const [label, ms] = tasks.shift();
<del> Scheduler.advanceTime(ms);
<del> Scheduler.yieldValue(label);
<add> Scheduler.unstable_advanceTime(ms);
<add> Scheduler.unstable_yieldValue(label);
<ide> if (shouldYield()) {
<ide> didYield = true;
<ide> return C;
<ide> describe('Scheduler', () => {
<ide> scheduleCallback(NormalPriority, C);
<ide>
<ide> scheduleCallback(NormalPriority, () => {
<del> Scheduler.advanceTime(100);
<del> Scheduler.yieldValue('D');
<add> Scheduler.unstable_advanceTime(100);
<add> Scheduler.unstable_yieldValue('D');
<ide> });
<ide> scheduleCallback(NormalPriority, () => {
<del> Scheduler.advanceTime(100);
<del> Scheduler.yieldValue('E');
<add> Scheduler.unstable_advanceTime(100);
<add> Scheduler.unstable_yieldValue('E');
<ide> });
<ide>
<ide> // Flush, then yield while in the middle of C.
<ide> describe('Scheduler', () => {
<ide> const work = () => {
<ide> while (tasks.length > 0) {
<ide> const [label, ms] = tasks.shift();
<del> Scheduler.advanceTime(ms);
<del> Scheduler.yieldValue(label);
<add> Scheduler.unstable_advanceTime(ms);
<add> Scheduler.unstable_yieldValue(label);
<ide> if (shouldYield()) {
<ide> return work;
<ide> }
<ide> describe('Scheduler', () => {
<ide> expect(Scheduler).toFlushAndYieldThrough(['A', 'B']);
<ide>
<ide> // Advance time by just a bit more. This should expire all the remaining work.
<del> Scheduler.advanceTime(1);
<add> Scheduler.unstable_advanceTime(1);
<ide> expect(Scheduler).toHaveYielded(['C', 'D']);
<ide> });
<ide>
<ide> describe('Scheduler', () => {
<ide> const work = () => {
<ide> while (tasks.length > 0) {
<ide> const [label, ms] = tasks.shift();
<del> Scheduler.advanceTime(ms);
<del> Scheduler.yieldValue(label);
<add> Scheduler.unstable_advanceTime(ms);
<add> Scheduler.unstable_yieldValue(label);
<ide> if (tasks.length > 0 && shouldYield()) {
<ide> return work;
<ide> }
<ide> describe('Scheduler', () => {
<ide> expect(Scheduler).toFlushAndYieldThrough(['A']);
<ide>
<ide> scheduleCallback(UserBlockingPriority, () => {
<del> Scheduler.advanceTime(100);
<del> Scheduler.yieldValue('High pri');
<add> Scheduler.unstable_advanceTime(100);
<add> Scheduler.unstable_yieldValue('High pri');
<ide> });
<ide>
<ide> expect(Scheduler).toFlushAndYield(['High pri', 'B', 'C', 'D']);
<ide> describe('Scheduler', () => {
<ide> while (tasks.length > 0) {
<ide> const task = tasks.shift();
<ide> const [label, ms] = task;
<del> Scheduler.advanceTime(ms);
<del> Scheduler.yieldValue(label);
<add> Scheduler.unstable_advanceTime(ms);
<add> Scheduler.unstable_yieldValue(label);
<ide> if (label === 'B') {
<ide> // Schedule high pri work from inside another callback
<del> Scheduler.yieldValue('Schedule high pri');
<add> Scheduler.unstable_yieldValue('Schedule high pri');
<ide> scheduleCallback(UserBlockingPriority, () => {
<del> Scheduler.advanceTime(100);
<del> Scheduler.yieldValue('High pri');
<add> Scheduler.unstable_advanceTime(100);
<add> Scheduler.unstable_yieldValue('High pri');
<ide> });
<ide> }
<ide> if (tasks.length > 0 && shouldYield()) {
<del> Scheduler.yieldValue('Yield!');
<add> Scheduler.unstable_yieldValue('Yield!');
<ide> return work;
<ide> }
<ide> }
<ide> describe('Scheduler', () => {
<ide> );
<ide>
<ide> it('top-level immediate callbacks fire in a subsequent task', () => {
<del> scheduleCallback(ImmediatePriority, () => Scheduler.yieldValue('A'));
<del> scheduleCallback(ImmediatePriority, () => Scheduler.yieldValue('B'));
<del> scheduleCallback(ImmediatePriority, () => Scheduler.yieldValue('C'));
<del> scheduleCallback(ImmediatePriority, () => Scheduler.yieldValue('D'));
<add> scheduleCallback(ImmediatePriority, () =>
<add> Scheduler.unstable_yieldValue('A'),
<add> );
<add> scheduleCallback(ImmediatePriority, () =>
<add> Scheduler.unstable_yieldValue('B'),
<add> );
<add> scheduleCallback(ImmediatePriority, () =>
<add> Scheduler.unstable_yieldValue('C'),
<add> );
<add> scheduleCallback(ImmediatePriority, () =>
<add> Scheduler.unstable_yieldValue('D'),
<add> );
<ide> // Immediate callback hasn't fired, yet.
<ide> expect(Scheduler).toHaveYielded([]);
<ide> // They all flush immediately within the subsequent task.
<ide> expect(Scheduler).toFlushExpired(['A', 'B', 'C', 'D']);
<ide> });
<ide>
<ide> it('nested immediate callbacks are added to the queue of immediate callbacks', () => {
<del> scheduleCallback(ImmediatePriority, () => Scheduler.yieldValue('A'));
<add> scheduleCallback(ImmediatePriority, () =>
<add> Scheduler.unstable_yieldValue('A'),
<add> );
<ide> scheduleCallback(ImmediatePriority, () => {
<del> Scheduler.yieldValue('B');
<add> Scheduler.unstable_yieldValue('B');
<ide> // This callback should go to the end of the queue
<del> scheduleCallback(ImmediatePriority, () => Scheduler.yieldValue('C'));
<add> scheduleCallback(ImmediatePriority, () =>
<add> Scheduler.unstable_yieldValue('C'),
<add> );
<ide> });
<del> scheduleCallback(ImmediatePriority, () => Scheduler.yieldValue('D'));
<add> scheduleCallback(ImmediatePriority, () =>
<add> Scheduler.unstable_yieldValue('D'),
<add> );
<ide> expect(Scheduler).toHaveYielded([]);
<ide> // C should flush at the end
<ide> expect(Scheduler).toFlushExpired(['A', 'B', 'D', 'C']);
<ide> describe('Scheduler', () => {
<ide> it('wrapped callbacks inherit the current priority', () => {
<ide> const wrappedCallback = runWithPriority(NormalPriority, () =>
<ide> wrapCallback(() => {
<del> Scheduler.yieldValue(getCurrentPriorityLevel());
<add> Scheduler.unstable_yieldValue(getCurrentPriorityLevel());
<ide> }),
<ide> );
<ide>
<ide> const wrappedUserBlockingCallback = runWithPriority(
<ide> UserBlockingPriority,
<ide> () =>
<ide> wrapCallback(() => {
<del> Scheduler.yieldValue(getCurrentPriorityLevel());
<add> Scheduler.unstable_yieldValue(getCurrentPriorityLevel());
<ide> }),
<ide> );
<ide>
<ide> describe('Scheduler', () => {
<ide>
<ide> runWithPriority(NormalPriority, () => {
<ide> wrappedCallback = wrapCallback(() => {
<del> Scheduler.yieldValue(getCurrentPriorityLevel());
<add> Scheduler.unstable_yieldValue(getCurrentPriorityLevel());
<ide> });
<ide> wrappedUserBlockingCallback = runWithPriority(UserBlockingPriority, () =>
<ide> wrapCallback(() => {
<del> Scheduler.yieldValue(getCurrentPriorityLevel());
<add> Scheduler.unstable_yieldValue(getCurrentPriorityLevel());
<ide> }),
<ide> );
<ide> });
<ide> describe('Scheduler', () => {
<ide>
<ide> it("immediate callbacks fire even if there's an error", () => {
<ide> scheduleCallback(ImmediatePriority, () => {
<del> Scheduler.yieldValue('A');
<add> Scheduler.unstable_yieldValue('A');
<ide> throw new Error('Oops A');
<ide> });
<ide> scheduleCallback(ImmediatePriority, () => {
<del> Scheduler.yieldValue('B');
<add> Scheduler.unstable_yieldValue('B');
<ide> });
<ide> scheduleCallback(ImmediatePriority, () => {
<del> Scheduler.yieldValue('C');
<add> Scheduler.unstable_yieldValue('C');
<ide> throw new Error('Oops C');
<ide> });
<ide>
<ide> describe('Scheduler', () => {
<ide> scheduleCallback(ImmediatePriority, () => {
<ide> throw new Error('Second error');
<ide> });
<del> expect(() => Scheduler.flushAll()).toThrow('First error');
<add> expect(() => Scheduler.unstable_flushAll()).toThrow('First error');
<ide> // The next error is thrown in the subsequent event
<del> expect(() => Scheduler.flushAll()).toThrow('Second error');
<add> expect(() => Scheduler.unstable_flushAll()).toThrow('Second error');
<ide> });
<ide>
<ide> it('exposes the current priority level', () => {
<del> Scheduler.yieldValue(getCurrentPriorityLevel());
<add> Scheduler.unstable_yieldValue(getCurrentPriorityLevel());
<ide> runWithPriority(ImmediatePriority, () => {
<del> Scheduler.yieldValue(getCurrentPriorityLevel());
<add> Scheduler.unstable_yieldValue(getCurrentPriorityLevel());
<ide> runWithPriority(NormalPriority, () => {
<del> Scheduler.yieldValue(getCurrentPriorityLevel());
<add> Scheduler.unstable_yieldValue(getCurrentPriorityLevel());
<ide> runWithPriority(UserBlockingPriority, () => {
<del> Scheduler.yieldValue(getCurrentPriorityLevel());
<add> Scheduler.unstable_yieldValue(getCurrentPriorityLevel());
<ide> });
<ide> });
<del> Scheduler.yieldValue(getCurrentPriorityLevel());
<add> Scheduler.unstable_yieldValue(getCurrentPriorityLevel());
<ide> });
<ide>
<ide> expect(Scheduler).toHaveYielded([
<ide> describe('Scheduler', () => {
<ide>
<ide> describe('delayed tasks', () => {
<ide> it('schedules a delayed task', () => {
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('A'), {
<del> delay: 1000,
<del> });
<add> scheduleCallback(
<add> NormalPriority,
<add> () => Scheduler.unstable_yieldValue('A'),
<add> {
<add> delay: 1000,
<add> },
<add> );
<ide>
<ide> // Should flush nothing, because delay hasn't elapsed
<ide> expect(Scheduler).toFlushAndYield([]);
<ide>
<ide> // Advance time until right before the threshold
<del> Scheduler.advanceTime(999);
<add> Scheduler.unstable_advanceTime(999);
<ide> // Still nothing
<ide> expect(Scheduler).toFlushAndYield([]);
<ide>
<ide> // Advance time past the threshold
<del> Scheduler.advanceTime(1);
<add> Scheduler.unstable_advanceTime(1);
<ide>
<ide> // Now it should flush like normal
<ide> expect(Scheduler).toFlushAndYield(['A']);
<ide> });
<ide>
<ide> it('schedules multiple delayed tasks', () => {
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('C'), {
<del> delay: 300,
<del> });
<add> scheduleCallback(
<add> NormalPriority,
<add> () => Scheduler.unstable_yieldValue('C'),
<add> {
<add> delay: 300,
<add> },
<add> );
<ide>
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('B'), {
<del> delay: 200,
<del> });
<add> scheduleCallback(
<add> NormalPriority,
<add> () => Scheduler.unstable_yieldValue('B'),
<add> {
<add> delay: 200,
<add> },
<add> );
<ide>
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('D'), {
<del> delay: 400,
<del> });
<add> scheduleCallback(
<add> NormalPriority,
<add> () => Scheduler.unstable_yieldValue('D'),
<add> {
<add> delay: 400,
<add> },
<add> );
<ide>
<del> scheduleCallback(NormalPriority, () => Scheduler.yieldValue('A'), {
<del> delay: 100,
<del> });
<add> scheduleCallback(
<add> NormalPriority,
<add> () => Scheduler.unstable_yieldValue('A'),
<add> {
<add> delay: 100,
<add> },
<add> );
<ide>
<ide> // Should flush nothing, because delay hasn't elapsed
<ide> expect(Scheduler).toFlushAndYield([]);
<ide>
<ide> // Advance some time.
<del> Scheduler.advanceTime(200);
<add> Scheduler.unstable_advanceTime(200);
<ide> // Both A and B are no longer delayed. They can now flush incrementally.
<ide> expect(Scheduler).toFlushAndYieldThrough(['A']);
<ide> expect(Scheduler).toFlushAndYield(['B']);
<ide>
<ide> // Advance the rest
<del> Scheduler.advanceTime(200);
<add> Scheduler.unstable_advanceTime(200);
<ide> expect(Scheduler).toFlushAndYield(['C', 'D']);
<ide> });
<ide>
<ide> describe('Scheduler', () => {
<ide> // elapses, they will be the most important callback in the queue.
<ide> scheduleCallback(
<ide> UserBlockingPriority,
<del> () => Scheduler.yieldValue('Timer 2'),
<add> () => Scheduler.unstable_yieldValue('Timer 2'),
<ide> {delay: 300},
<ide> );
<ide> scheduleCallback(
<ide> UserBlockingPriority,
<del> () => Scheduler.yieldValue('Timer 1'),
<add> () => Scheduler.unstable_yieldValue('Timer 1'),
<ide> {delay: 100},
<ide> );
<ide>
<ide> // Schedule some tasks at default priority.
<ide> scheduleCallback(NormalPriority, () => {
<del> Scheduler.yieldValue('A');
<del> Scheduler.advanceTime(100);
<add> Scheduler.unstable_yieldValue('A');
<add> Scheduler.unstable_advanceTime(100);
<ide> });
<ide> scheduleCallback(NormalPriority, () => {
<del> Scheduler.yieldValue('B');
<del> Scheduler.advanceTime(100);
<add> Scheduler.unstable_yieldValue('B');
<add> Scheduler.unstable_advanceTime(100);
<ide> });
<ide> scheduleCallback(NormalPriority, () => {
<del> Scheduler.yieldValue('C');
<del> Scheduler.advanceTime(100);
<add> Scheduler.unstable_yieldValue('C');
<add> Scheduler.unstable_advanceTime(100);
<ide> });
<ide> scheduleCallback(NormalPriority, () => {
<del> Scheduler.yieldValue('D');
<del> Scheduler.advanceTime(100);
<add> Scheduler.unstable_yieldValue('D');
<add> Scheduler.unstable_advanceTime(100);
<ide> });
<ide>
<ide> // Flush all the work. The timers should be interleaved with the
<ide> describe('Scheduler', () => {
<ide> // elapses, they will be the most important callback in the queue.
<ide> scheduleCallback(
<ide> UserBlockingPriority,
<del> () => Scheduler.yieldValue('Timer 2'),
<add> () => Scheduler.unstable_yieldValue('Timer 2'),
<ide> {delay: 300},
<ide> );
<ide> scheduleCallback(
<ide> UserBlockingPriority,
<del> () => Scheduler.yieldValue('Timer 1'),
<add> () => Scheduler.unstable_yieldValue('Timer 1'),
<ide> {delay: 100},
<ide> );
<ide>
<ide> describe('Scheduler', () => {
<ide> while (tasks.length > 0) {
<ide> const task = tasks.shift();
<ide> const [label, ms] = task;
<del> Scheduler.advanceTime(ms);
<del> Scheduler.yieldValue(label);
<add> Scheduler.unstable_advanceTime(ms);
<add> Scheduler.unstable_yieldValue(label);
<ide> if (tasks.length > 0 && shouldYield()) {
<ide> return work;
<ide> }
<ide> describe('Scheduler', () => {
<ide> scheduleCallback(
<ide> NormalPriority,
<ide> () => {
<del> Scheduler.yieldValue('A');
<del> Scheduler.advanceTime(100);
<add> Scheduler.unstable_yieldValue('A');
<add> Scheduler.unstable_advanceTime(100);
<ide> },
<ide> {delay: 100, timeout: 900},
<ide> );
<ide>
<del> Scheduler.advanceTime(99);
<add> Scheduler.unstable_advanceTime(99);
<ide> // Does not flush because delay has not elapsed
<ide> expect(Scheduler).toFlushAndYield([]);
<ide>
<ide> // Delay has elapsed but task has not expired
<del> Scheduler.advanceTime(1);
<add> Scheduler.unstable_advanceTime(1);
<ide> expect(Scheduler).toFlushExpired([]);
<ide>
<ide> // Still not expired
<del> Scheduler.advanceTime(899);
<add> Scheduler.unstable_advanceTime(899);
<ide> expect(Scheduler).toFlushExpired([]);
<ide>
<ide> // Now it expires
<del> Scheduler.advanceTime(1);
<add> Scheduler.unstable_advanceTime(1);
<ide> expect(Scheduler).toHaveYielded(['A']);
<ide> });
<ide>
<ide> describe('Scheduler', () => {
<ide>
<ide> scheduleCallback(
<ide> NormalPriority,
<del> () => Scheduler.yieldValue('A'),
<add> () => Scheduler.unstable_yieldValue('A'),
<ide> options,
<ide> );
<ide> const taskB = scheduleCallback(
<ide> NormalPriority,
<del> () => Scheduler.yieldValue('B'),
<add> () => Scheduler.unstable_yieldValue('B'),
<ide> options,
<ide> );
<ide> const taskC = scheduleCallback(
<ide> NormalPriority,
<del> () => Scheduler.yieldValue('C'),
<add> () => Scheduler.unstable_yieldValue('C'),
<ide> options,
<ide> );
<ide>
<ide> describe('Scheduler', () => {
<ide> cancelCallback(taskB);
<ide>
<ide> // Cancel C after its delay has elapsed
<del> Scheduler.advanceTime(500);
<add> Scheduler.unstable_advanceTime(500);
<ide> cancelCallback(taskC);
<ide>
<ide> // Only A should flush
<ide><path>packages/scheduler/src/forks/SchedulerHostConfig.mock.js
<ide> export function unstable_flushExpired() {
<ide> }
<ide> }
<ide>
<del>export function unstable_flushWithoutYielding(): boolean {
<add>export function unstable_flushAllWithoutAsserting(): boolean {
<ide> // Returns false if no work was flushed.
<ide> if (isFlushing) {
<ide> throw new Error('Already flushing work.');
<ide> export function unstable_clearYields(): Array<mixed> {
<ide> return values;
<ide> }
<ide>
<del>export function flushAll(): void {
<add>export function unstable_flushAll(): void {
<ide> if (yieldedValues !== null) {
<ide> throw new Error(
<ide> 'Log is not empty. Assert on the log of yielded values before ' +
<ide> 'flushing additional work.',
<ide> );
<ide> }
<del> unstable_flushWithoutYielding();
<add> unstable_flushAllWithoutAsserting();
<ide> if (yieldedValues !== null) {
<ide> throw new Error(
<ide> 'While flushing work, something yielded a value. Use an ' +
<ide> export function flushAll(): void {
<ide> }
<ide> }
<ide>
<del>export function yieldValue(value: mixed): void {
<add>export function unstable_yieldValue(value: mixed): void {
<ide> if (yieldedValues === null) {
<ide> yieldedValues = [value];
<ide> } else {
<ide> yieldedValues.push(value);
<ide> }
<ide> }
<ide>
<del>export function advanceTime(ms: number) {
<add>export function unstable_advanceTime(ms: number) {
<ide> currentTime += ms;
<ide> if (!isFlushing) {
<ide> if (scheduledTimeout !== null && timeoutTime <= currentTime) {
<ide><path>packages/scheduler/unstable_mock.js
<ide> export * from './src/Scheduler';
<ide>
<ide> export {
<del> unstable_flushWithoutYielding,
<add> unstable_flushAllWithoutAsserting,
<ide> unstable_flushNumberOfYields,
<ide> unstable_flushExpired,
<ide> unstable_clearYields,
<ide> unstable_flushUntilNextPaint,
<del> flushAll,
<del> yieldValue,
<del> advanceTime,
<add> unstable_flushAll,
<add> unstable_yieldValue,
<add> unstable_advanceTime,
<ide> } from './src/SchedulerHostConfig.js';
<ide><path>packages/shared/forks/Scheduler.umd.js
<ide> const {
<ide>
<ide> // this doesn't actually exist on the scheduler, but it *does*
<ide> // on scheduler/unstable_mock, which we'll need inside act().
<del> unstable_flushWithoutYielding,
<add> unstable_flushAllWithoutAsserting,
<ide> } = ReactInternals.Scheduler;
<ide>
<ide> export {
<ide> export {
<ide> unstable_LowPriority,
<ide> unstable_IdlePriority,
<ide> unstable_forceFrameRate,
<del> unstable_flushWithoutYielding,
<add> unstable_flushAllWithoutAsserting,
<ide> };
<ide><path>scripts/jest/matchers/schedulerTestMatchers.js
<ide> function assertYieldsWereCleared(Scheduler) {
<ide>
<ide> function toFlushAndYield(Scheduler, expectedYields) {
<ide> assertYieldsWereCleared(Scheduler);
<del> Scheduler.unstable_flushWithoutYielding();
<add> Scheduler.unstable_flushAllWithoutAsserting();
<ide> const actualYields = Scheduler.unstable_clearYields();
<ide> return captureAssertion(() => {
<ide> expect(actualYields).toEqual(expectedYields);
<ide> function toFlushAndThrow(Scheduler, ...rest) {
<ide> assertYieldsWereCleared(Scheduler);
<ide> return captureAssertion(() => {
<ide> expect(() => {
<del> Scheduler.unstable_flushWithoutYielding();
<add> Scheduler.unstable_flushAllWithoutAsserting();
<ide> }).toThrow(...rest);
<ide> });
<ide> }
| 60
|
Javascript
|
Javascript
|
add ability to reset a form to pristine state
|
733a97adf87bf8f7ec6be22b37c4676cf7b5fc2b
|
<ide><path>src/ng/directive/form.js
<ide> var nullFormCtrl = {
<ide> $addControl: noop,
<ide> $removeControl: noop,
<ide> $setValidity: noop,
<del> $setDirty: noop
<add> $setDirty: noop,
<add> $setPristine: noop
<ide> };
<ide>
<ide> /**
<ide> function FormController(element, attrs) {
<ide> var form = this,
<ide> parentForm = element.parent().controller('form') || nullFormCtrl,
<ide> invalidCount = 0, // used to easily determine if we are valid
<del> errors = form.$error = {};
<add> errors = form.$error = {},
<add> controls = [];
<ide>
<ide> // init state
<ide> form.$name = attrs.name;
<ide> function FormController(element, attrs) {
<ide> }
<ide>
<ide> form.$addControl = function(control) {
<add> controls.push(control);
<add>
<ide> if (control.$name && !form.hasOwnProperty(control.$name)) {
<ide> form[control.$name] = control;
<ide> }
<ide> function FormController(element, attrs) {
<ide> forEach(errors, function(queue, validationToken) {
<ide> form.$setValidity(validationToken, true, control);
<ide> });
<add>
<add> arrayRemove(controls, control);
<ide> };
<ide>
<ide> form.$setValidity = function(validationToken, isValid, control) {
<ide> function FormController(element, attrs) {
<ide> parentForm.$setDirty();
<ide> };
<ide>
<add> /**
<add> * @ngdoc function
<add> * @name ng.directive:form.FormController#$setPristine
<add> * @methodOf ng.directive:form.FormController
<add> *
<add> * @description
<add> * Sets the form to its pristine state.
<add> *
<add> * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
<add> * state (ng-pristine class). This method will also propagate to all the controls contained
<add> * in this form.
<add> *
<add> * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
<add> * saving or resetting it.
<add> */
<add> form.$setPristine = function () {
<add> element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
<add> form.$dirty = false;
<add> form.$pristine = true;
<add> forEach(controls, function(control) {
<add> control.$setPristine();
<add> });
<add> };
<ide> }
<ide>
<ide>
<ide><path>src/ng/directive/input.js
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
<ide> parentForm.$setValidity(validationErrorKey, isValid, this);
<ide> };
<ide>
<add> /**
<add> * @ngdoc function
<add> * @name ng.directive:ngModel.NgModelController#$setPristine
<add> * @methodOf ng.directive:ngModel.NgModelController
<add> *
<add> * @description
<add> * Sets the control to its pristine state.
<add> *
<add> * This method can be called to remove the 'ng-dirty' class and set the control to its pristine
<add> * state (ng-pristine class).
<add> */
<add> this.$setPristine = function () {
<add> this.$dirty = false;
<add> this.$pristine = true;
<add> $element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
<add> };
<ide>
<ide> /**
<ide> * @ngdoc function
<ide><path>test/ng/directive/formSpec.js
<ide> describe('form', function() {
<ide> expect(doc).toBeDirty();
<ide> });
<ide> });
<add>
<add>
<add> describe('$setPristine', function() {
<add>
<add> it('should reset pristine state of form and controls', function() {
<add>
<add> doc = $compile(
<add> '<form name="testForm">' +
<add> '<input ng-model="named1" name="foo">' +
<add> '<input ng-model="named2" name="bar">' +
<add> '</form>')(scope);
<add>
<add> scope.$digest();
<add>
<add> var form = doc,
<add> formCtrl = scope.testForm,
<add> input1 = form.find('input').eq(0),
<add> input1Ctrl = input1.controller('ngModel'),
<add> input2 = form.find('input').eq(1),
<add> input2Ctrl = input2.controller('ngModel');
<add>
<add> input1Ctrl.$setViewValue('xx');
<add> input2Ctrl.$setViewValue('yy');
<add> scope.$apply();
<add> expect(form).toBeDirty();
<add> expect(input1).toBeDirty();
<add> expect(input2).toBeDirty();
<add>
<add> formCtrl.$setPristine();
<add> expect(form).toBePristine();
<add> expect(formCtrl.$pristine).toBe(true);
<add> expect(formCtrl.$dirty).toBe(false);
<add> expect(input1).toBePristine();
<add> expect(input1Ctrl.$pristine).toBe(true);
<add> expect(input1Ctrl.$dirty).toBe(false);
<add> expect(input2).toBePristine();
<add> expect(input2Ctrl.$pristine).toBe(true);
<add> expect(input2Ctrl.$dirty).toBe(false);
<add> });
<add>
<add>
<add> it('should reset pristine state of anonymous form controls', function() {
<add>
<add> doc = $compile(
<add> '<form name="testForm">' +
<add> '<input ng-model="anonymous">' +
<add> '</form>')(scope);
<add>
<add> scope.$digest();
<add>
<add> var form = doc,
<add> formCtrl = scope.testForm,
<add> input = form.find('input').eq(0),
<add> inputCtrl = input.controller('ngModel');
<add>
<add> inputCtrl.$setViewValue('xx');
<add> scope.$apply();
<add> expect(form).toBeDirty();
<add> expect(input).toBeDirty();
<add>
<add> formCtrl.$setPristine();
<add> expect(form).toBePristine();
<add> expect(formCtrl.$pristine).toBe(true);
<add> expect(formCtrl.$dirty).toBe(false);
<add> expect(input).toBePristine();
<add> expect(inputCtrl.$pristine).toBe(true);
<add> expect(inputCtrl.$dirty).toBe(false);
<add> });
<add>
<add>
<add> it('should reset pristine state of nested forms', function() {
<add>
<add> doc = $compile(
<add> '<form name="testForm">' +
<add> '<div ng-form>' +
<add> '<input ng-model="named" name="foo">' +
<add> '</div>' +
<add> '</form>')(scope);
<add>
<add> scope.$digest();
<add>
<add> var form = doc,
<add> formCtrl = scope.testForm,
<add> nestedForm = form.find('div'),
<add> nestedFormCtrl = nestedForm.controller('form'),
<add> nestedInput = form.find('input').eq(0),
<add> nestedInputCtrl = nestedInput.controller('ngModel');
<add>
<add> nestedInputCtrl.$setViewValue('xx');
<add> scope.$apply();
<add> expect(form).toBeDirty();
<add> expect(nestedForm).toBeDirty();
<add> expect(nestedInput).toBeDirty();
<add>
<add> formCtrl.$setPristine();
<add> expect(form).toBePristine();
<add> expect(formCtrl.$pristine).toBe(true);
<add> expect(formCtrl.$dirty).toBe(false);
<add> expect(nestedForm).toBePristine();
<add> expect(nestedFormCtrl.$pristine).toBe(true);
<add> expect(nestedFormCtrl.$dirty).toBe(false);
<add> expect(nestedInput).toBePristine();
<add> expect(nestedInputCtrl.$pristine).toBe(true);
<add> expect(nestedInputCtrl.$dirty).toBe(false);
<add> });
<add> });
<ide> });
<ide><path>test/ng/directive/inputSpec.js
<ide> describe('NgModelController', function() {
<ide> });
<ide> });
<ide>
<add> describe('setPristine', function() {
<add>
<add> it('should set control to its pristine state', function() {
<add> ctrl.$setViewValue('edit');
<add> expect(ctrl.$dirty).toBe(true);
<add> expect(ctrl.$pristine).toBe(false);
<add>
<add> ctrl.$setPristine();
<add> expect(ctrl.$dirty).toBe(false);
<add> expect(ctrl.$pristine).toBe(true);
<add> });
<add> });
<ide>
<ide> describe('view -> model', function() {
<ide>
| 4
|
Ruby
|
Ruby
|
convert duration to an attr_reader
|
cfca55949f51bf3970bae7c506807db97dbcf05f
|
<ide><path>activesupport/lib/active_support/notifications/instrumenter.rb
<ide> def unique_id
<ide> end
<ide>
<ide> class Event
<del> attr_reader :name, :time, :end, :transaction_id, :payload
<add> attr_reader :name, :time, :end, :transaction_id, :payload, :duration
<ide>
<ide> def initialize(name, start, ending, transaction_id, payload)
<ide> @name = name
<ide> @payload = payload.dup
<ide> @time = start
<ide> @transaction_id = transaction_id
<ide> @end = ending
<del> end
<del>
<del> def duration
<del> @duration ||= 1000.0 * (@end - @time)
<add> @duration = 1000.0 * (@end - @time)
<ide> end
<ide>
<ide> def parent_of?(event)
<del> start = (self.time - event.time) * 1000
<add> start = (time - event.time) * 1000
<ide> start <= 0 && (start + duration >= event.duration)
<ide> end
<ide> end
| 1
|
Javascript
|
Javascript
|
fix parentel tech option
|
eda21b7b2212cf1c9b4d5db10e1ad86a334bb046
|
<ide><path>src/js/player.js
<ide> vjs.Player.prototype.loadTech = function(techName, source){
<ide> };
<ide>
<ide> // Grab tech-specific options from player options and add source and parent element to use.
<del> var techOptions = vjs.obj.merge({ source: source, parentEl: this.el_ }, this.options_[techName.toLowerCase()]);
<add> var techOptions = vjs.obj.merge({ 'source': source, 'parentEl': this.el_ }, this.options_[techName.toLowerCase()]);
<ide>
<ide> if (source) {
<ide> if (source.src == this.cache_.src && this.cache_.currentTime > 0) {
| 1
|
Python
|
Python
|
remove unused key in the process list
|
1292150478c53a5bd29bef5dd4f17b6184fadbb5
|
<ide><path>glances/processes.py
<ide> class GlancesProcesses(object):
<ide> def __init__(self, cache_timeout=60):
<ide> """Init the class to collect stats about processes."""
<ide> # Add internals caches because psutil do not cache all the stats
<del> # See: https://code.google.com/p/psutil/issues/detail?id=462
<add> # See: https://github.com/giampaolo/psutil/issues/462
<ide> self.username_cache = {}
<ide> self.cmdline_cache = {}
<ide>
<ide> def __init__(self, cache_timeout=60):
<ide> # First iteration, no cache
<ide> self.cache_timer = Timer(0)
<ide>
<del> # Init the io dict
<add> # Init the io_old dict used to compute the IO bitrate
<ide> # key = pid
<ide> # value = [ read_bytes_old, write_bytes_old ]
<ide> self.io_old = {}
<ide> def update(self):
<ide>
<ide> # Grab standard stats
<ide> #####################
<del> sorted_attrs = ['cpu_percent', 'cpu_times', 'memory_percent', 'name', 'status', 'status', 'num_threads']
<del> displayed_attr = ['memory_info', 'nice', 'pid', 'ppid']
<add> sorted_attrs = ['cpu_percent', 'cpu_times', 'memory_percent', 'name', 'status', 'num_threads']
<add> displayed_attr = ['memory_info', 'nice', 'pid']
<ide> cached_attrs = ['cmdline', 'username']
<ide>
<ide> # Some stats are optional
| 1
|
PHP
|
PHP
|
improve variable naming
|
dd8ffbd269ce5f0d0f593ed7f0dac23d8671f25e
|
<ide><path>src/ORM/Association/BelongsToMany.php
<ide> protected function _diffLinks(
<ide> $assocForeignKey = (array)$belongsTo->getForeignKey();
<ide>
<ide> $keys = array_merge($foreignKey, $assocForeignKey);
<del> $deletes = $indexed = $present = [];
<add> $deletes = $unmatchedEntityKeys = $present = [];
<ide>
<ide> foreach ($jointEntities as $i => $entity) {
<del> $indexed[$i] = $entity->extract($keys);
<add> $unmatchedEntityKeys[$i] = $entity->extract($keys);
<ide> $present[$i] = array_values($entity->extract($assocForeignKey));
<ide> }
<ide>
<del> foreach ($existing as $result) {
<del> $fields = $result->extract($keys);
<add> foreach ($existing as $existingLink) {
<add> $existingKeys = $existingLink->extract($keys);
<ide> $found = false;
<del> foreach ($indexed as $i => $data) {
<add> foreach ($unmatchedEntityKeys as $i => $unmatchedKeys) {
<ide> $matched = false;
<ide> foreach ($keys as $key) {
<del> if (!array_key_exists($key, $data) || !array_key_exists($key, $fields)) {
<add> if (!array_key_exists($key, $unmatchedKeys) || !array_key_exists($key, $existingKeys)) {
<ide> // Either side missing is no match.
<ide> $matched = false;
<del> } elseif (is_object($data[$key]) && is_object($fields[$key])) {
<add> } elseif (is_object($unmatchedKeys[$key]) && is_object($existingKeys[$key])) {
<ide> // If both sides are an object then use == so that value objects
<ide> // are seen as equivalent.
<del> $matched = $fields[$key] == $data[$key];
<add> $matched = $existingKeys[$key] == $unmatchedKeys[$key];
<ide> } else {
<ide> // Use strict equality for all other values.
<del> $matched = $fields[$key] === $data[$key];
<add> $matched = $existingKeys[$key] === $unmatchedKeys[$key];
<ide> }
<ide> // Stop checks on first failure.
<ide> if (!$matched) {
<ide> break;
<ide> }
<ide> }
<ide> if ($matched) {
<del> unset($indexed[$i]);
<add> // Remove the unmatched entity so we don't look at it again.
<add> unset($unmatchedEntityKeys[$i]);
<ide> $found = true;
<ide> break;
<ide> }
<ide> }
<ide>
<ide> if (!$found) {
<del> $deletes[] = $result;
<add> $deletes[] = $existingLink;
<ide> }
<ide> }
<ide>
| 1
|
Ruby
|
Ruby
|
add test for `variable_size_secure_compare`
|
02bb4c55fdf04ce64bdbf155c66991d80837fe73
|
<ide><path>activesupport/test/security_utils_test.rb
<ide> class SecurityUtilsTest < ActiveSupport::TestCase
<ide> def test_secure_compare_should_perform_string_comparison
<ide> assert ActiveSupport::SecurityUtils.secure_compare("a", "a")
<del> assert !ActiveSupport::SecurityUtils.secure_compare("a", "b")
<add> assert_not ActiveSupport::SecurityUtils.secure_compare("a", "b")
<add> end
<add>
<add> def test_variable_size_secure_compare_should_perform_string_comparison
<add> assert ActiveSupport::SecurityUtils.variable_size_secure_compare("a", "a")
<add> assert_not ActiveSupport::SecurityUtils.variable_size_secure_compare("a", "b")
<ide> end
<ide> end
| 1
|
Ruby
|
Ruby
|
fix conflicting symlink advice
|
f6b5c83482b9ebbd390831f41767f9dd9b33162f
|
<ide><path>Library/Homebrew/extend/pathname.rb
<ide> def make_relative_symlink src
<ide> # NOTE only system ln -s will create RELATIVE symlinks
<ide> quiet_system 'ln', '-s', src.relative_path_from(self.dirname), self.basename
<ide> if not $?.success?
<del> if self.exist?
<add> if symlink? && exist? || symlink?
<ide> raise <<-EOS.undent
<ide> Could not symlink file: #{src.expand_path}
<del> Target #{self} already exists. You may need to delete it.
<add> Target #{self} already exists as a symlink to #{readlink}.
<add> If this file is from another formula, you may need to
<add> `brew unlink` it. Otherwise, you may want to delete it.
<ide> To force the link and overwrite all other conflicting files, do:
<ide> brew link --overwrite formula_name
<ide>
<ide> To list all files that would be deleted:
<ide> brew link --overwrite --dry-run formula_name
<ide> EOS
<del> # #exist? will return false for symlinks whose target doesn't exist
<del> elsif self.symlink?
<add> elsif exist?
<ide> raise <<-EOS.undent
<ide> Could not symlink file: #{src.expand_path}
<del> Target #{self} already exists as a symlink to #{readlink}.
<del> If this file is from another formula, you may need to
<del> `brew unlink` it. Otherwise, you may want to delete it.
<add> Target #{self} already exists. You may need to delete it.
<ide> To force the link and overwrite all other conflicting files, do:
<ide> brew link --overwrite formula_name
<ide>
| 1
|
Ruby
|
Ruby
|
add macos 12
|
d7d9a256a13727fee0f802a2f3e22062a6d68774
|
<ide><path>Library/Homebrew/os/mac/version.rb
<ide> class Version < ::Version
<ide> extend T::Sig
<ide>
<ide> SYMBOLS = {
<add> monterey: "12"
<ide> big_sur: "11",
<ide> catalina: "10.15",
<ide> mojave: "10.14",
| 1
|
Javascript
|
Javascript
|
use strict equality in extension check
|
8d1c00395bc97b91deeddcda97fde80e4d00e614
|
<ide><path>src/renderers/webgl/WebGLLights.js
<ide> function WebGLLights( extensions, capabilities ) {
<ide>
<ide> // WebGL 1
<ide>
<del> if ( extensions.has( 'OES_texture_float_linear' ) == true ) {
<add> if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
<ide>
<ide> state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
<ide> state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
<ide>
<del> } else if ( extensions.has( 'OES_texture_half_float_linear' ) == true ) {
<add> } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
<ide>
<ide> state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
<ide> state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
| 1
|
PHP
|
PHP
|
add logo support to notification email
|
bc656ad451d99a83432d02b165beb70da51e68c5
|
<ide><path>src/Illuminate/Notifications/RoutesNotifications.php
<ide> public function notify($instance)
<ide> );
<ide>
<ide> foreach ($notifications as $notification) {
<del> $manager->send($notification->application(config('app.name')));
<add> $manager->send($notification->application(
<add> config('app.name'), config('app.logo')
<add> ));
<ide> }
<ide> }
<ide>
<ide><path>src/Illuminate/Notifications/TransportManager.php
<ide> class TransportManager extends Manager
<ide> public function to($notifiables)
<ide> {
<ide> return (new Transports\Notification($this, $notifiables))->application(
<del> $this->app['config']['app.name']
<add> $this->app['config']['app.name'],
<add> $this->app['config']['app.logo']
<ide> );
<ide> }
<ide>
<ide><path>src/Illuminate/Notifications/Transports/Notification.php
<ide> class Notification implements Arrayable
<ide> */
<ide> public $application;
<ide>
<add> /**
<add> * The URL to the application's logo.
<add> *
<add> * @var string
<add> */
<add> public $logoUrl;
<add>
<ide> /**
<ide> * The "level" of the notification (info, success, error).
<ide> *
<ide> public function __construct($notifiables)
<ide> * Specify the name of the application sending the notification.
<ide> *
<ide> * @param string $application
<add> * @param string $logoUrl
<ide> * @return $this
<ide> */
<del> public function application($application)
<add> public function application($application, $logoUrl = null)
<ide> {
<ide> $this->application = $application;
<add> $this->logoUrl = $logoUrl;
<ide>
<ide> return $this;
<ide> }
<ide> public function toArray()
<ide> return [
<ide> 'notifiables' => $this->notifiables,
<ide> 'application' => $this->application,
<add> 'logoUrl' => $this->logoUrl,
<ide> 'level' => $this->level,
<ide> 'subject' => $this->subject,
<ide> 'introLines' => $this->introLines,
<ide><path>src/Illuminate/Notifications/resources/views/email.blade.php
<ide> <tr>
<ide> <td class="email-masthead">
<ide> <a class="email-masthead_name" href="{{ url('/') }}" target="_blank">
<del> <!-- <img src="logo" class="email-logo" /> -->
<del> {{ $application }}
<add> @if (isset($logoUrl))
<add> <img src="{{ $logoUrl }}" class="email-logo" />
<add> @else
<add> {{ $application }}
<add> @endif
<ide> </a>
<ide> </td>
<ide> </tr>
| 4
|
Javascript
|
Javascript
|
remove unnecessary whitespace from code frames
|
03766d6a08b0244ebb142e7ce33f4fd7091af0ae
|
<ide><path>Libraries/LogBox/UI/AnsiHighlight.js
<ide> export default function Ansi({
<ide> text: string,
<ide> style: TextStyleProp,
<ide> }): React.Node {
<add> let commonWhitespaceLength = Infinity;
<add> const parsedLines = text.split(/\n/).map(line =>
<add> ansiToJson(line, {
<add> json: true,
<add> remove_empty: true,
<add> use_classes: true,
<add> }),
<add> );
<add>
<add> parsedLines.map(lines => {
<add> // The third item on each line includes the whitespace of the source code.
<add> // We are looking for the least amount of common whitespace to trim all lines.
<add> // Example: Array [" ", " 96 |", " text", ...]
<add> const match = lines[2] && lines[2]?.content?.match(/^ +/);
<add> const whitespaceLength = (match && match[0]?.length) || Infinity;
<add> if (whitespaceLength < commonWhitespaceLength) {
<add> commonWhitespaceLength = whitespaceLength;
<add> }
<add> });
<add>
<add> const getText = (content, key) => {
<add> if (key === 1) {
<add> // Remove the vertical bar after line numbers
<add> return content.replace(/\| $/, ' ');
<add> } else if (key === 2 && commonWhitespaceLength < Infinity) {
<add> // Remove common whitespace at the beginning of the line
<add> return content.substr(commonWhitespaceLength);
<add> } else {
<add> return content;
<add> }
<add> };
<add>
<ide> return (
<ide> <View style={{flexDirection: 'column'}}>
<del> {text.split(/\n/).map((line, i) => (
<add> {parsedLines.map((items, i) => (
<ide> <View style={{flexDirection: 'row'}} key={i}>
<del> {ansiToJson(line, {
<del> json: true,
<del> remove_empty: true,
<del> use_classes: true,
<del> }).map((bundle, key) => {
<del> // Remove the vertical bar after line numbers
<del> const content =
<del> key === 1 ? bundle.content.replace(/\| $/, ' ') : bundle.content;
<add> {items.map((bundle, key) => {
<ide> const textStyle =
<ide> bundle.fg && COLORS[bundle.fg]
<ide> ? {
<ide> export default function Ansi({
<ide> };
<ide> return (
<ide> <Text style={[style, textStyle]} key={key}>
<del> {content}
<add> {getText(bundle.content, key)}
<ide> </Text>
<ide> );
<ide> })}
| 1
|
Javascript
|
Javascript
|
fix gizmo overall scale hover
|
57801e6c4693a675c4d96bea86895fe1ba7d3c09
|
<ide><path>examples/js/controls/TransformControls.js
<ide> THREE.TransformControlsGizmo = function () {
<ide> [ new THREE.Line( lineGeometry, matLineBlue ), null, [ 0, - Math.PI / 2, 0 ]]
<ide> ],
<ide> XYZ: [
<del> [ new THREE.Mesh( new THREE.OctahedronBufferGeometry( 0.1, 0 ), matWhiteTransperent ), [ 0, 0, 0 ], [ 0, 0, 0 ]]
<add> [ new THREE.Mesh( new THREE.OctahedronBufferGeometry( 0.1, 0 ), matWhiteTransperent.clone() ), [ 0, 0, 0 ], [ 0, 0, 0 ]]
<ide> ],
<ide> XY: [
<del> [ new THREE.Mesh( new THREE.PlaneBufferGeometry( 0.295, 0.295 ), matYellowTransparent ), [ 0.15, 0.15, 0 ]],
<add> [ new THREE.Mesh( new THREE.PlaneBufferGeometry( 0.295, 0.295 ), matYellowTransparent.clone() ), [ 0.15, 0.15, 0 ]],
<ide> [ new THREE.Line( lineGeometry, matLineYellow ), [ 0.18, 0.3, 0 ], null, [ 0.125, 1, 1 ]],
<ide> [ new THREE.Line( lineGeometry, matLineYellow ), [ 0.3, 0.18, 0 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]]
<ide> ],
<ide> YZ: [
<del> [ new THREE.Mesh( new THREE.PlaneBufferGeometry( 0.295, 0.295 ), matCyanTransparent ), [ 0, 0.15, 0.15 ], [ 0, Math.PI / 2, 0 ]],
<add> [ new THREE.Mesh( new THREE.PlaneBufferGeometry( 0.295, 0.295 ), matCyanTransparent.clone() ), [ 0, 0.15, 0.15 ], [ 0, Math.PI / 2, 0 ]],
<ide> [ new THREE.Line( lineGeometry, matLineCyan ), [ 0, 0.18, 0.3 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]],
<ide> [ new THREE.Line( lineGeometry, matLineCyan ), [ 0, 0.3, 0.18 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
<ide> ],
<ide> XZ: [
<del> [ new THREE.Mesh( new THREE.PlaneBufferGeometry( 0.295, 0.295 ), matMagentaTransparent ), [ 0.15, 0, 0.15 ], [ - Math.PI / 2, 0, 0 ]],
<add> [ new THREE.Mesh( new THREE.PlaneBufferGeometry( 0.295, 0.295 ), matMagentaTransparent.clone() ), [ 0.15, 0, 0.15 ], [ - Math.PI / 2, 0, 0 ]],
<ide> [ new THREE.Line( lineGeometry, matLineMagenta ), [ 0.18, 0, 0.3 ], null, [ 0.125, 1, 1 ]],
<ide> [ new THREE.Line( lineGeometry, matLineMagenta ), [ 0.3, 0, 0.18 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
<ide> ]
<ide><path>examples/jsm/controls/TransformControls.js
<ide> var TransformControlsGizmo = function () {
<ide> [ new Line( lineGeometry, matLineBlue ), null, [ 0, - Math.PI / 2, 0 ]]
<ide> ],
<ide> XYZ: [
<del> [ new Mesh( new OctahedronBufferGeometry( 0.1, 0 ), matWhiteTransperent ), [ 0, 0, 0 ], [ 0, 0, 0 ]]
<add> [ new Mesh( new OctahedronBufferGeometry( 0.1, 0 ), matWhiteTransperent.clone() ), [ 0, 0, 0 ], [ 0, 0, 0 ]]
<ide> ],
<ide> XY: [
<ide> [ new Mesh( new PlaneBufferGeometry( 0.295, 0.295 ), matYellowTransparent ), [ 0.15, 0.15, 0 ]],
<ide> var TransformControlsGizmo = function () {
<ide> [ new Line( lineGeometry, matLineMagenta ), [ 0.98, 0, 0.855 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
<ide> ],
<ide> XYZX: [
<del> [ new Mesh( new BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransperent ), [ 1.1, 0, 0 ]],
<add> [ new Mesh( new BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransperent.clone() ), [ 1.1, 0, 0 ]],
<ide> ],
<ide> XYZY: [
<del> [ new Mesh( new BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransperent ), [ 0, 1.1, 0 ]],
<add> [ new Mesh( new BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransperent.clone() ), [ 0, 1.1, 0 ]],
<ide> ],
<ide> XYZZ: [
<del> [ new Mesh( new BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransperent ), [ 0, 0, 1.1 ]],
<add> [ new Mesh( new BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransperent.clone() ), [ 0, 0, 1.1 ]],
<ide> ]
<ide> };
<ide>
| 2
|
Mixed
|
Python
|
add nasnet models
|
dc95ceca57cbfada596a10a72f0cb30e1f2ed53b
|
<ide><path>docs/templates/applications.md
<ide> Weights are downloaded automatically when instantiating a model. They are stored
<ide> - [InceptionV3](#inceptionv3)
<ide> - [InceptionResNetV2](#inceptionresnetv2)
<ide> - [MobileNet](#mobilenet)
<add>- [NASNet](#nasnet)
<ide>
<ide> All of these architectures (except Xception and MobileNet) are compatible with both TensorFlow and Theano, and upon instantiation the models will be built according to the image data format set in your Keras configuration file at `~/.keras/keras.json`. For instance, if you have set `image_data_format=channels_last`, then any model loaded from this repository will get built according to the TensorFlow data format convention, "Height-Width-Depth".
<ide>
<ide> A Keras `Model` instance.
<ide> ### License
<ide>
<ide> These weights are released under [the Apache License](https://github.com/tensorflow/models/blob/master/LICENSE).
<add>
<add>-----
<add>
<add>## NASNet
<add>
<add>
<add>```python
<add>keras.applications.nasnet.NASNetLarge(input_shape=None, include_top=True, weights='imagenet', input_tensor=None, pooling=None, classes=1000)
<add>keras.applications.nasnet.NASNetMobile(input_shape=None, include_top=True, weights='imagenet', input_tensor=None, pooling=None, classes=1000)
<add>```
<add>
<add>Neural Architecture Search Network (NASNet) model, with weights pre-trained on ImageNet.
<add>
<add>Note that only TensorFlow is supported for now,
<add>therefore it only works with the data format
<add>`image_data_format='channels_last'` in your Keras config at `~/.keras/keras.json`.
<add>
<add>
<add>The default input size for the NASNetLarge model is 331x331 and for the
<add>NASNetMobile model is 224x224.
<add>
<add>### Arguments
<add>
<add>- input_shape: optional shape tuple, only to be specified
<add> if `include_top` is `False` (otherwise the input shape
<add> has to be `(224, 224, 3)` (with `'channels_last'` data format)
<add> or (3, 224, 224) (with `'channels_first'` data format)
<add> for NASNetMobile or `(331, 331, 3)` (with `'channels_last'`
<add> data format) or (3, 331, 331) (with `'channels_first'`
<add> data format) for NASNetLarge.
<add> It should have exactly 3 inputs channels,
<add> and width and height should be no smaller than 32.
<add> E.g. `(200, 200, 3)` would be one valid value.
<add>- include_top: whether to include the fully-connected
<add> layer at the top of the network.
<add>- weights: `None` (random initialization) or
<add> `'imagenet'` (ImageNet weights)
<add>- input_tensor: optional Keras tensor (i.e. output of
<add> `layers.Input()`)
<add> to use as image input for the model.
<add>- pooling: Optional pooling mode for feature extraction
<add> when `include_top` is `False`.
<add> - `None` means that the output of the model
<add> will be the 4D tensor output of the
<add> last convolutional layer.
<add> - `'avg'` means that global average pooling
<add> will be applied to the output of the
<add> last convolutional layer, and thus
<add> the output of the model will be a
<add> 2D tensor.
<add> - `'max'` means that global max pooling will
<add> be applied.
<add>- classes: optional number of classes to classify images
<add> into, only to be specified if `include_top` is `True`, and
<add> if no `weights` argument is specified.
<add>
<add>### Returns
<add>
<add>A Keras `Model` instance.
<add>
<add>### References
<add>
<add>- [Learning Transferable Architectures for Scalable Image Recognition](https://arxiv.org/abs/1707.07012)
<add>
<add>### License
<add>
<add>These weights are released under [the Apache License](https://github.com/tensorflow/models/blob/master/LICENSE).
<ide><path>keras/applications/__init__.py
<ide> from .inception_resnet_v2 import InceptionResNetV2
<ide> from .xception import Xception
<ide> from .mobilenet import MobileNet
<add>from .nasnet import NASNetMobile, NASNetLarge
<ide><path>keras/applications/nasnet.py
<add>'''NASNet-A models for Keras
<add>
<add>NASNet refers to Neural Architecture Search Network, a family of models
<add>that were designed automatically by learning the model architectures
<add>directly on the dataset of interest.
<add>
<add>Here we consider NASNet-A, the highest performance model that was found
<add>for the CIFAR-10 dataset, and then extended to ImageNet 2012 dataset,
<add>obtaining state of the art performance on CIFAR-10 and ImageNet 2012.
<add>Only the NASNet-A models, and their respective weights, which are suited
<add>for ImageNet 2012 are provided.
<add>
<add>The below table describes the performance on ImageNet 2012:
<add>--------------------------------------------------------------------------------
<add> Architecture | Top-1 Acc | Top-5 Acc | Multiply-Adds | Params (M)
<add>--------------------------------------------------------------------------------
<add>| NASNet-A (4 @ 1056) | 74.0 % | 91.6 % | 564 M | 5.3 |
<add>| NASNet-A (6 @ 4032) | 82.7 % | 96.2 % | 23.8 B | 88.9 |
<add>--------------------------------------------------------------------------------
<add>
<add>Weights obtained from the official Tensorflow repository found at
<add>https://github.com/tensorflow/models/tree/master/research/slim/nets/nasnet
<add>
<add># References:
<add> - [Learning Transferable Architectures for Scalable Image Recognition]
<add> (https://arxiv.org/abs/1707.07012)
<add>
<add>Based on the following implementations:
<add> - [TF Slim Implementation]
<add> (https://github.com/tensorflow/models/blob/master/research/slim/nets/nasnet/nasnet.py)
<add> - [TensorNets implementation]
<add> (https://github.com/taehoonlee/tensornets/blob/master/tensornets/nasnets.py)
<add>'''
<add>from __future__ import print_function
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>
<add>import os
<add>import warnings
<add>
<add>from ..models import Model
<add>from ..layers import Input
<add>from ..layers import Activation
<add>from ..layers import Dense
<add>from ..layers import BatchNormalization
<add>from ..layers import MaxPooling2D
<add>from ..layers import AveragePooling2D
<add>from ..layers import GlobalAveragePooling2D
<add>from ..layers import GlobalMaxPooling2D
<add>from ..layers import Conv2D
<add>from ..layers import SeparableConv2D
<add>from ..layers import ZeroPadding2D
<add>from ..layers import Cropping2D
<add>from ..layers import concatenate
<add>from ..layers import add
<add>from ..utils.data_utils import get_file
<add>from ..engine.topology import get_source_inputs
<add>from ..applications.imagenet_utils import _obtain_input_shape
<add>from ..applications.inception_v3 import preprocess_input
<add>from ..applications.imagenet_utils import decode_predictions
<add>from .. import backend as K
<add>
<add>NASNET_MOBILE_WEIGHT_PATH = 'https://github.com/titu1994/Keras-NASNet/releases/download/v1.2/NASNet-mobile.h5'
<add>NASNET_MOBILE_WEIGHT_PATH_NO_TOP = 'https://github.com/titu1994/Keras-NASNet/releases/download/v1.2/NASNet-mobile-no-top.h5'
<add>NASNET_LARGE_WEIGHT_PATH = 'https://github.com/titu1994/Keras-NASNet/releases/download/v1.2/NASNet-large.h5'
<add>NASNET_LARGE_WEIGHT_PATH_NO_TOP = 'https://github.com/titu1994/Keras-NASNet/releases/download/v1.2/NASNet-large-no-top.h5'
<add>
<add>
<add>def NASNet(input_shape=None,
<add> penultimate_filters=4032,
<add> num_blocks=6,
<add> stem_block_filters=96,
<add> skip_reduction=True,
<add> filter_multiplier=2,
<add> include_top=True,
<add> weights=None,
<add> input_tensor=None,
<add> pooling=None,
<add> classes=1000,
<add> default_size=None):
<add> '''Instantiates a NASNet model.
<add>
<add> Note that only TensorFlow is supported for now,
<add> therefore it only works with the data format
<add> `image_data_format='channels_last'` in your Keras config
<add> at `~/.keras/keras.json`.
<add>
<add> # Arguments
<add> input_shape: optional shape tuple, only to be specified
<add> if `include_top` is False (otherwise the input shape
<add> has to be `(331, 331, 3)` for NASNetLarge or
<add> `(224, 224, 3)` for NASNetMobile
<add> It should have exactly 3 inputs channels,
<add> and width and height should be no smaller than 32.
<add> E.g. `(224, 224, 3)` would be one valid value.
<add> penultimate_filters: number of filters in the penultimate layer.
<add> NASNet models use the notation `NASNet (N @ P)`, where:
<add> - N is the number of blocks
<add> - P is the number of penultimate filters
<add> num_blocks: number of repeated blocks of the NASNet model.
<add> NASNet models use the notation `NASNet (N @ P)`, where:
<add> - N is the number of blocks
<add> - P is the number of penultimate filters
<add> stem_block_filters: number of filters in the initial stem block
<add> skip_reduction: Whether to skip the reduction step at the tail
<add> end of the network. Set to `False` for CIFAR models.
<add> filter_multiplier: controls the width of the network.
<add> - If `filter_multiplier` < 1.0, proportionally decreases the number
<add> of filters in each layer.
<add> - If `filter_multiplier` > 1.0, proportionally increases the number
<add> of filters in each layer.
<add> - If `filter_multiplier` = 1, default number of filters from the
<add> paper are used at each layer.
<add> include_top: whether to include the fully-connected
<add> layer at the top of the network.
<add> weights: `None` (random initialization) or
<add> `imagenet` (ImageNet weights)
<add> input_tensor: optional Keras tensor (i.e. output of
<add> `layers.Input()`)
<add> to use as image input for the model.
<add> pooling: Optional pooling mode for feature extraction
<add> when `include_top` is `False`.
<add> - `None` means that the output of the model
<add> will be the 4D tensor output of the
<add> last convolutional layer.
<add> - `avg` means that global average pooling
<add> will be applied to the output of the
<add> last convolutional layer, and thus
<add> the output of the model will be a
<add> 2D tensor.
<add> - `max` means that global max pooling will
<add> be applied.
<add> classes: optional number of classes to classify images
<add> into, only to be specified if `include_top` is True, and
<add> if no `weights` argument is specified.
<add> default_size: specifies the default image size of the model
<add>
<add> # Returns
<add> A Keras model instance.
<add>
<add> # Raises
<add> ValueError: in case of invalid argument for `weights`,
<add> invalid input shape or invalid `penultimate_filters` value.
<add> RuntimeError: If attempting to run this model with a
<add> backend that does not support separable convolutions.
<add> '''
<add> if K.backend() != 'tensorflow':
<add> raise RuntimeError('Only Tensorflow backend is currently supported, '
<add> 'as other backends do not support '
<add> 'separable convolution.')
<add>
<add> if not (weights in {'imagenet', None} or os.path.exists(weights)):
<add> raise ValueError('The `weights` argument should be either '
<add> '`None` (random initialization), `imagenet` '
<add> '(pre-training on ImageNet), '
<add> 'or the path to the weights file to be loaded.')
<add>
<add> if weights == 'imagenet' and include_top and classes != 1000:
<add> raise ValueError('If using `weights` as ImageNet with `include_top` '
<add> 'as true, `classes` should be 1000')
<add>
<add> if default_size is None:
<add> default_size = 331
<add>
<add> # Determine proper input shape and default size.
<add> input_shape = _obtain_input_shape(input_shape,
<add> default_size=default_size,
<add> min_size=32,
<add> data_format=K.image_data_format(),
<add> require_flatten=include_top or weights,
<add> weights=weights)
<add>
<add> if K.image_data_format() != 'channels_last':
<add> warnings.warn('The NASNet family of models is only available '
<add> 'for the input data format "channels_last" '
<add> '(width, height, channels). '
<add> 'However your settings specify the default '
<add> 'data format "channels_first" (channels, width, height).'
<add> ' You should set `image_data_format="channels_last"` '
<add> 'in your Keras config located at ~/.keras/keras.json. '
<add> 'The model being returned right now will expect inputs '
<add> 'to follow the "channels_last" data format.')
<add> K.set_image_data_format('channels_last')
<add> old_data_format = 'channels_first'
<add> else:
<add> old_data_format = None
<add>
<add> if input_tensor is None:
<add> img_input = Input(shape=input_shape)
<add> else:
<add> if not K.is_keras_tensor(input_tensor):
<add> img_input = Input(tensor=input_tensor, shape=input_shape)
<add> else:
<add> img_input = input_tensor
<add>
<add> if penultimate_filters % 24 != 0:
<add> raise ValueError(
<add> 'For NASNet-A models, the value of `penultimate_filters` '
<add> 'needs to be divisible by 24. Current value: %d' %
<add> penultimate_filters)
<add>
<add> channel_dim = 1 if K.image_data_format() == 'channels_first' else -1
<add> filters = penultimate_filters // 24
<add>
<add> if not skip_reduction:
<add> x = Conv2D(stem_block_filters, (3, 3), strides=(2, 2), padding='valid',
<add> use_bias=False, name='stem_conv1',
<add> kernel_initializer='he_normal')(img_input)
<add> else:
<add> x = Conv2D(stem_block_filters, (3, 3), strides=(1, 1), padding='same',
<add> use_bias=False, name='stem_conv1',
<add> kernel_initializer='he_normal')(img_input)
<add>
<add> x = BatchNormalization(axis=channel_dim, momentum=0.9997,
<add> epsilon=1e-3, name='stem_bn1')(x)
<add>
<add> p = None
<add> if not skip_reduction: # imagenet / mobile mode
<add> x, p = _reduction_a_cell(x, p, filters // (filter_multiplier ** 2),
<add> block_id='stem_1')
<add> x, p = _reduction_a_cell(x, p, filters // filter_multiplier,
<add> block_id='stem_2')
<add>
<add> for i in range(num_blocks):
<add> x, p = _normal_a_cell(x, p, filters, block_id='%d' % (i))
<add>
<add> x, p0 = _reduction_a_cell(x, p, filters * filter_multiplier,
<add> block_id='reduce_%d' % (num_blocks))
<add>
<add> p = p0 if not skip_reduction else p
<add>
<add> for i in range(num_blocks):
<add> x, p = _normal_a_cell(x, p, filters * filter_multiplier,
<add> block_id='%d' % (num_blocks + i + 1))
<add>
<add> x, p0 = _reduction_a_cell(x, p, filters * filter_multiplier ** 2,
<add> block_id='reduce_%d' % (2 * num_blocks))
<add>
<add> p = p0 if not skip_reduction else p
<add>
<add> for i in range(num_blocks):
<add> x, p = _normal_a_cell(x, p, filters * filter_multiplier ** 2,
<add> block_id='%d' % (2 * num_blocks + i + 1))
<add>
<add> x = Activation('relu')(x)
<add>
<add> if include_top:
<add> x = GlobalAveragePooling2D()(x)
<add> x = Dense(classes, activation='softmax', name='predictions')(x)
<add> else:
<add> if pooling == 'avg':
<add> x = GlobalAveragePooling2D()(x)
<add> elif pooling == 'max':
<add> x = GlobalMaxPooling2D()(x)
<add>
<add> # Ensure that the model takes into account
<add> # any potential predecessors of `input_tensor`.
<add> if input_tensor is not None:
<add> inputs = get_source_inputs(input_tensor)
<add> else:
<add> inputs = img_input
<add>
<add> model = Model(inputs, x, name='NASNet')
<add>
<add> # load weights
<add> if weights == 'imagenet':
<add> if default_size == 224: # mobile version
<add> if include_top:
<add> weight_path = NASNET_MOBILE_WEIGHT_PATH
<add> model_name = 'nasnet_mobile.h5'
<add> else:
<add> weight_path = NASNET_MOBILE_WEIGHT_PATH_NO_TOP
<add> model_name = 'nasnet_mobile_no_top.h5'
<add>
<add> weights_file = get_file(model_name, weight_path,
<add> cache_subdir='models')
<add> model.load_weights(weights_file)
<add>
<add> elif default_size == 331: # large version
<add> if include_top:
<add> weight_path = NASNET_LARGE_WEIGHT_PATH
<add> model_name = 'nasnet_large.h5'
<add> else:
<add> weight_path = NASNET_LARGE_WEIGHT_PATH_NO_TOP
<add> model_name = 'nasnet_large_no_top.h5'
<add>
<add> weights_file = get_file(model_name, weight_path,
<add> cache_subdir='models')
<add> model.load_weights(weights_file)
<add> else:
<add> raise ValueError(
<add> 'ImageNet weights can only be loaded with NASNetLarge'
<add> ' or NASNetMobile')
<add> elif weights is not None:
<add> model.load_weights(weights)
<add>
<add> if old_data_format:
<add> K.set_image_data_format(old_data_format)
<add>
<add> return model
<add>
<add>
<add>def NASNetLarge(input_shape=None,
<add> include_top=True,
<add> weights='imagenet',
<add> input_tensor=None,
<add> pooling=None,
<add> classes=1000):
<add> '''Instantiates a NASNet model in ImageNet mode.
<add>
<add> Note that only TensorFlow is supported for now,
<add> therefore it only works with the data format
<add> `image_data_format='channels_last'` in your Keras config
<add> at `~/.keras/keras.json`.
<add>
<add> # Arguments
<add> input_shape: optional shape tuple, only to be specified
<add> if `include_top` is False (otherwise the input shape
<add> has to be `(331, 331, 3)` for NASNetLarge.
<add> It should have exactly 3 inputs channels,
<add> and width and height should be no smaller than 32.
<add> E.g. `(224, 224, 3)` would be one valid value.
<add> include_top: whether to include the fully-connected
<add> layer at the top of the network.
<add> weights: `None` (random initialization) or
<add> `imagenet` (ImageNet weights)
<add> input_tensor: optional Keras tensor (i.e. output of
<add> `layers.Input()`)
<add> to use as image input for the model.
<add> pooling: Optional pooling mode for feature extraction
<add> when `include_top` is `False`.
<add> - `None` means that the output of the model
<add> will be the 4D tensor output of the
<add> last convolutional layer.
<add> - `avg` means that global average pooling
<add> will be applied to the output of the
<add> last convolutional layer, and thus
<add> the output of the model will be a
<add> 2D tensor.
<add> - `max` means that global max pooling will
<add> be applied.
<add> classes: optional number of classes to classify images
<add> into, only to be specified if `include_top` is True, and
<add> if no `weights` argument is specified.
<add> default_size: specifies the default image size of the model
<add>
<add> # Returns
<add> A Keras model instance.
<add>
<add> # Raises
<add> ValueError: in case of invalid argument for `weights`,
<add> or invalid input shape.
<add> RuntimeError: If attempting to run this model with a
<add> backend that does not support separable convolutions.
<add> '''
<add> return NASNet(input_shape,
<add> penultimate_filters=4032,
<add> num_blocks=6,
<add> stem_block_filters=96,
<add> skip_reduction=False,
<add> filter_multiplier=2,
<add> include_top=include_top,
<add> weights=weights,
<add> input_tensor=input_tensor,
<add> pooling=pooling,
<add> classes=classes,
<add> default_size=331)
<add>
<add>
<add>def NASNetMobile(input_shape=None,
<add> include_top=True,
<add> weights='imagenet',
<add> input_tensor=None,
<add> pooling=None,
<add> classes=1000):
<add> '''Instantiates a Mobile NASNet model in ImageNet mode.
<add>
<add> Note that only TensorFlow is supported for now,
<add> therefore it only works with the data format
<add> `image_data_format='channels_last'` in your Keras config
<add> at `~/.keras/keras.json`.
<add>
<add> # Arguments
<add> input_shape: optional shape tuple, only to be specified
<add> if `include_top` is False (otherwise the input shape
<add> has to be `(224, 224, 3)` for NASNetMobile
<add> It should have exactly 3 inputs channels,
<add> and width and height should be no smaller than 32.
<add> E.g. `(224, 224, 3)` would be one valid value.
<add> include_top: whether to include the fully-connected
<add> layer at the top of the network.
<add> weights: `None` (random initialization) or
<add> `imagenet` (ImageNet weights)
<add> input_tensor: optional Keras tensor (i.e. output of
<add> `layers.Input()`)
<add> to use as image input for the model.
<add> pooling: Optional pooling mode for feature extraction
<add> when `include_top` is `False`.
<add> - `None` means that the output of the model
<add> will be the 4D tensor output of the
<add> last convolutional layer.
<add> - `avg` means that global average pooling
<add> will be applied to the output of the
<add> last convolutional layer, and thus
<add> the output of the model will be a
<add> 2D tensor.
<add> - `max` means that global max pooling will
<add> be applied.
<add> classes: optional number of classes to classify images
<add> into, only to be specified if `include_top` is True, and
<add> if no `weights` argument is specified.
<add> default_size: specifies the default image size of the model
<add>
<add> # Returns
<add> A Keras model instance.
<add>
<add> # Raises
<add> ValueError: in case of invalid argument for `weights`,
<add> or invalid input shape.
<add> RuntimeError: If attempting to run this model with a
<add> backend that does not support separable convolutions.
<add> '''
<add> return NASNet(input_shape,
<add> penultimate_filters=1056,
<add> num_blocks=4,
<add> stem_block_filters=32,
<add> skip_reduction=False,
<add> filter_multiplier=2,
<add> include_top=include_top,
<add> weights=weights,
<add> input_tensor=input_tensor,
<add> pooling=pooling,
<add> classes=classes,
<add> default_size=224)
<add>
<add>
<add>def _separable_conv_block(ip, filters, kernel_size=(3, 3), strides=(1, 1),
<add> block_id=None):
<add> '''Adds 2 blocks of [relu-separable conv-batchnorm]
<add>
<add> # Arguments:
<add> ip: input tensor
<add> filters: number of output filters per layer
<add> kernel_size: kernel size of separable convolutions
<add> strides: strided convolution for downsampling
<add> block_id: string block_id
<add>
<add> # Returns:
<add> a Keras tensor
<add> '''
<add> channel_dim = 1 if K.image_data_format() == 'channels_first' else -1
<add>
<add> with K.name_scope('separable_conv_block_%s' % block_id):
<add> x = Activation('relu')(ip)
<add> x = SeparableConv2D(filters, kernel_size, strides=strides,
<add> name='separable_conv_1_%s' % block_id,
<add> padding='same', use_bias=False,
<add> kernel_initializer='he_normal')(x)
<add> x = BatchNormalization(axis=channel_dim, momentum=0.9997,
<add> epsilon=1e-3,
<add> name='separable_conv_1_bn_%s' % (block_id))(x)
<add> x = Activation('relu')(x)
<add> x = SeparableConv2D(filters, kernel_size,
<add> name='separable_conv_2_%s' % block_id,
<add> padding='same', use_bias=False,
<add> kernel_initializer='he_normal')(x)
<add> x = BatchNormalization(axis=channel_dim, momentum=0.9997,
<add> epsilon=1e-3,
<add> name='separable_conv_2_bn_%s' % (block_id))(x)
<add> return x
<add>
<add>
<add>def _adjust_block(p, ip, filters, block_id=None):
<add> '''
<add> Adjusts the input `previou path` to match the shape of the `input`
<add> or situations where the output number of filters needs to be changed
<add>
<add> # Arguments:
<add> p: input tensor which needs to be modified
<add> ip: input tensor whose shape needs to be matched
<add> filters: number of output filters to be matched
<add> block_id: string block_id
<add>
<add> # Returns:
<add> an adjusted Keras tensor
<add> '''
<add> channel_dim = 1 if K.image_data_format() == 'channels_first' else -1
<add> img_dim = 2 if K.image_data_format() == 'channels_first' else -2
<add>
<add> ip_shape = K.int_shape(ip)
<add>
<add> if p is not None:
<add> p_shape = K.int_shape(p)
<add>
<add> with K.name_scope('adjust_block'):
<add> if p is None:
<add> p = ip
<add>
<add> elif p_shape[img_dim] != ip_shape[img_dim]:
<add> with K.name_scope('adjust_reduction_block_%s' % block_id):
<add> p = Activation('relu', name='adjust_relu_1_%s' % block_id)(p)
<add>
<add> p1 = AveragePooling2D((1, 1), strides=(2, 2), padding='valid',
<add> name='adjust_avg_pool_1_%s' % block_id)(p)
<add> p1 = Conv2D(filters // 2, (1, 1), padding='same',
<add> use_bias=False, name='adjust_conv_1_%s' % block_id,
<add> kernel_initializer='he_normal')(p1)
<add>
<add> p2 = ZeroPadding2D(padding=((0, 1), (0, 1)))(p)
<add> p2 = Cropping2D(cropping=((1, 0), (1, 0)))(p2)
<add> p2 = AveragePooling2D((1, 1), strides=(2, 2), padding='valid',
<add> name='adjust_avg_pool_2_%s' % block_id)(
<add> p2)
<add> p2 = Conv2D(filters // 2, (1, 1), padding='same',
<add> use_bias=False, name='adjust_conv_2_%s' % block_id,
<add> kernel_initializer='he_normal')(p2)
<add>
<add> p = concatenate([p1, p2], axis=channel_dim)
<add> p = BatchNormalization(axis=channel_dim, momentum=0.9997,
<add> epsilon=1e-3,
<add> name='adjust_bn_%s' % block_id)(p)
<add>
<add> elif p_shape[channel_dim] != filters:
<add> with K.name_scope('adjust_projection_block_%s' % block_id):
<add> p = Activation('relu')(p)
<add> p = Conv2D(filters, (1, 1), strides=(1, 1), padding='same',
<add> name='adjust_conv_projection_%s' % block_id,
<add> use_bias=False, kernel_initializer='he_normal')(p)
<add> p = BatchNormalization(axis=channel_dim, momentum=0.9997,
<add> epsilon=1e-3,
<add> name='adjust_bn_%s' % block_id)(p)
<add> return p
<add>
<add>
<add>def _normal_a_cell(ip, p, filters, block_id=None):
<add> '''Adds a Normal cell for NASNet-A (Fig. 4 in the paper)
<add>
<add> # Arguments:
<add> ip: input tensor `x`
<add> p: input tensor `p`
<add> filters: number of output filters
<add> block_id: string block_id
<add>
<add> # Returns:
<add> a Keras tensor
<add> '''
<add> channel_dim = 1 if K.image_data_format() == 'channels_first' else -1
<add>
<add> with K.name_scope('normal_A_block_%s' % block_id):
<add> p = _adjust_block(p, ip, filters, block_id)
<add>
<add> h = Activation('relu')(ip)
<add> h = Conv2D(filters, (1, 1), strides=(1, 1), padding='same',
<add> name='normal_conv_1_%s' % block_id,
<add> use_bias=False, kernel_initializer='he_normal')(h)
<add> h = BatchNormalization(axis=channel_dim, momentum=0.9997,
<add> epsilon=1e-3,
<add> name='normal_bn_1_%s' % block_id)(h)
<add>
<add> with K.name_scope('block_1'):
<add> x1_1 = _separable_conv_block(h, filters, kernel_size=(5, 5),
<add> block_id='normal_left1_%s' % block_id)
<add> x1_2 = _separable_conv_block(p, filters,
<add> block_id='normal_right1_%s' % block_id)
<add> x1 = add([x1_1, x1_2], name='normal_add_1_%s' % block_id)
<add>
<add> with K.name_scope('block_2'):
<add> x2_1 = _separable_conv_block(p, filters, (5, 5),
<add> block_id='normal_left2_%s' % block_id)
<add> x2_2 = _separable_conv_block(p, filters, (3, 3),
<add> block_id='normal_right2_%s' % block_id)
<add> x2 = add([x2_1, x2_2], name='normal_add_2_%s' % block_id)
<add>
<add> with K.name_scope('block_3'):
<add> x3 = AveragePooling2D((3, 3), strides=(1, 1), padding='same',
<add> name='normal_left3_%s' % (block_id))(h)
<add> x3 = add([x3, p], name='normal_add_3_%s' % block_id)
<add>
<add> with K.name_scope('block_4'):
<add> x4_1 = AveragePooling2D((3, 3), strides=(1, 1), padding='same',
<add> name='normal_left4_%s' % (block_id))(p)
<add> x4_2 = AveragePooling2D((3, 3), strides=(1, 1), padding='same',
<add> name='normal_right4_%s' % (block_id))(p)
<add> x4 = add([x4_1, x4_2], name='normal_add_4_%s' % block_id)
<add>
<add> with K.name_scope('block_5'):
<add> x5 = _separable_conv_block(h, filters,
<add> block_id='normal_left5_%s' % block_id)
<add> x5 = add([x5, h], name='normal_add_5_%s' % block_id)
<add>
<add> x = concatenate([p, x1, x2, x3, x4, x5], axis=channel_dim,
<add> name='normal_concat_%s' % block_id)
<add> return x, ip
<add>
<add>
<add>def _reduction_a_cell(ip, p, filters, block_id=None):
<add> '''Adds a Reduction cell for NASNet-A (Fig. 4 in the paper)
<add>
<add> # Arguments:
<add> ip: input tensor `x`
<add> p: input tensor `p`
<add> filters: number of output filters
<add> block_id: string block_id
<add>
<add> # Returns:
<add> a Keras tensor
<add> '''
<add> channel_dim = 1 if K.image_data_format() == 'channels_first' else -1
<add>
<add> with K.name_scope('reduction_A_block_%s' % block_id):
<add> p = _adjust_block(p, ip, filters, block_id)
<add>
<add> h = Activation('relu')(ip)
<add> h = Conv2D(filters, (1, 1), strides=(1, 1), padding='same',
<add> name='reduction_conv_1_%s' % block_id,
<add> use_bias=False, kernel_initializer='he_normal')(h)
<add> h = BatchNormalization(axis=channel_dim, momentum=0.9997,
<add> epsilon=1e-3,
<add> name='reduction_bn_1_%s' % block_id)(h)
<add>
<add> with K.name_scope('block_1'):
<add> x1_1 = _separable_conv_block(h, filters, (5, 5), strides=(2, 2),
<add> block_id='reduction_left1_%s' % block_id)
<add> x1_2 = _separable_conv_block(p, filters, (7, 7), strides=(2, 2),
<add> block_id='reduction_1_%s' % block_id)
<add> x1 = add([x1_1, x1_2], name='reduction_add_1_%s' % block_id)
<add>
<add> with K.name_scope('block_2'):
<add> x2_1 = MaxPooling2D((3, 3), strides=(2, 2), padding='same',
<add> name='reduction_left2_%s' % block_id)(h)
<add> x2_2 = _separable_conv_block(p, filters, (7, 7), strides=(2, 2),
<add> block_id='reduction_right2_%s' % block_id)
<add> x2 = add([x2_1, x2_2], name='reduction_add_2_%s' % block_id)
<add>
<add> with K.name_scope('block_3'):
<add> x3_1 = AveragePooling2D((3, 3), strides=(2, 2), padding='same',
<add> name='reduction_left3_%s' % block_id)(h)
<add> x3_2 = _separable_conv_block(p, filters, (5, 5), strides=(2, 2),
<add> block_id='reduction_right3_%s' % block_id)
<add> x3 = add([x3_1, x3_2], name='reduction_add3_%s' % block_id)
<add>
<add> with K.name_scope('block_4'):
<add> x4 = AveragePooling2D((3, 3), strides=(1, 1), padding='same',
<add> name='reduction_left4_%s' % block_id)(x1)
<add> x4 = add([x2, x4])
<add>
<add> with K.name_scope('block_5'):
<add> x5_1 = _separable_conv_block(x1, filters, (3, 3),
<add> block_id='reduction_left4_%s' % block_id)
<add> x5_2 = MaxPooling2D((3, 3), strides=(2, 2), padding='same',
<add> name='reduction_right5_%s' % block_id)(h)
<add> x5 = add([x5_1, x5_2], name='reduction_add4_%s' % block_id)
<add>
<add> x = concatenate([x2, x3, x4, x5], axis=channel_dim,
<add> name='reduction_concat_%s' % block_id)
<add> return x, ip
<ide><path>tests/keras/applications/applications_test.py
<ide> def test_mobilenet_image_size():
<ide> model = applications.MobileNet(input_shape=invalid_image_shape, weights='imagenet', include_top=True)
<ide>
<ide>
<add>@keras_test
<add>@pytest.mark.skipif((K.backend() != 'tensorflow'),
<add> reason='NASNets are supported only on TensorFlow')
<add>def test_nasnet():
<add> model = applications.NASNetMobile(weights=None)
<add> assert model.output_shape == (None, 1000)
<add>
<add> model = applications.NASNetLarge(weights=None)
<add> assert model.output_shape == (None, 1000)
<add>
<add>
<add>@keras_test
<add>@pytest.mark.skipif((K.backend() != 'tensorflow'),
<add> reason='NASNets are supported only on TensorFlow')
<add>def test_nasnet_no_top():
<add> model = applications.NASNetMobile(weights=None, include_top=False)
<add> assert model.output_shape == (None, None, None, 1056)
<add>
<add> model = applications.NASNetLarge(weights=None, include_top=False)
<add> assert model.output_shape == (None, None, None, 4032)
<add>
<add>
<add>@keras_test
<add>@pytest.mark.skipif((K.backend() != 'tensorflow'),
<add> reason='NASNets are supported only on TensorFlow')
<add>def test_nasnet_pooling():
<add> model = applications.NASNetMobile(weights=None, include_top=False, pooling='avg')
<add> assert model.output_shape == (None, 1056)
<add>
<add> model = applications.NASNetLarge(weights=None, include_top=False, pooling='avg')
<add> assert model.output_shape == (None, 4032)
<add>
<add>
<add>@keras_test
<add>@pytest.mark.skipif((K.backend() != 'tensorflow'),
<add> reason='NASNets are supported only on TensorFlow')
<add>def test_nasnet_variable_input_channels():
<add> input_shape = (1, None, None) if K.image_data_format() == 'channels_first' else (None, None, 1)
<add> model = applications.NASNetMobile(weights=None, include_top=False, input_shape=input_shape)
<add> assert model.output_shape == (None, None, None, 1056)
<add>
<add> model = applications.NASNetLarge(weights=None, include_top=False, input_shape=input_shape)
<add> assert model.output_shape == (None, None, None, 4032)
<add>
<add> input_shape = (4, None, None) if K.image_data_format() == 'channels_first' else (None, None, 4)
<add> model = applications.NASNetMobile(weights=None, include_top=False, input_shape=input_shape)
<add> assert model.output_shape == (None, None, None, 1056)
<add>
<add> model = applications.NASNetLarge(weights=None, include_top=False, input_shape=input_shape)
<add> assert model.output_shape == (None, None, None, 4032)
<add>
<add>
<ide> @pytest.mark.skipif(K.backend() != 'tensorflow', reason='Requires TF backend')
<ide> @keras_test
<ide> def test_depthwise_conv_2d():
| 4
|
PHP
|
PHP
|
fix lint error
|
765f072892b0f354215efcf78a383a5552ae5209
|
<ide><path>src/Database/Schema/MysqlSchema.php
<ide> */
<ide> namespace Cake\Database\Schema;
<ide>
<del>use Cake\Database\Schema\TableSchema;
<ide> use Cake\Database\Exception;
<add>use Cake\Database\Schema\TableSchema;
<ide>
<ide> /**
<ide> * Schema generation/reflection features for MySQL
| 1
|
Text
|
Text
|
add missing item in 3.9.1 release notes
|
c049777dc7d7f6ec36bfd3bc5b5f853c20246997
|
<ide><path>docs/community/release-notes.md
<ide> You can determine your currently installed version using `pip show`:
<ide> **Date**: [16th Janurary 2019][3.9.1-milestone]
<ide>
<ide> * Resolve XSS issue in browsable API. [#6330][gh6330]
<add>* Upgrade Bootstrap to 3.4.0 to resolve XSS issue.
<ide> * Resolve issues with composable permissions. [#6299][gh6299]
<ide> * Respect `limit_choices_to` on foreign keys. [#6371][gh6371]
<ide>
| 1
|
Go
|
Go
|
add unit tests
|
2a303dab8594420b6b7908183a73c5d744b1e66b
|
<ide><path>api.go
<ide> func postContainersStop(srv *Server, w http.ResponseWriter, r *http.Request, var
<ide> if err != nil || t < 0 {
<ide> t = 10
<ide> }
<add>
<ide> if vars == nil {
<ide> return nil, fmt.Errorf("Missing parameter")
<ide> }
<ide><path>api_test.go
<ide> import (
<ide> "github.com/dotcloud/docker/auth"
<ide> "net/http"
<ide> "net/http/httptest"
<add> "os"
<add> "path"
<ide> "testing"
<add> "time"
<ide> )
<ide>
<ide> func TestAuth(t *testing.T) {
<ide> func TestGetImage(t *testing.T) {
<ide> }
<ide> }
<ide>
<del>func TestCreateListStartStopRestartKillWaitDelete(t *testing.T) {
<del>
<add>func TestPostContainersCreate(t *testing.T) {
<ide> runtime, err := newTestRuntime()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestCreateListStartStopRestartKillWaitDelete(t *testing.T) {
<ide>
<ide> srv := &Server{runtime: runtime}
<ide>
<del> containers := testListContainers(t, srv, -1)
<del> for _, container := range containers {
<del> testDeleteContainer(t, srv, container.Id)
<del> }
<del> testCreateContainer(t, srv)
<del> id := testListContainers(t, srv, 1)[0].Id
<del> testContainerStart(t, srv, id)
<del> testContainerStop(t, srv, id)
<del> testContainerRestart(t, srv, id)
<del> testContainerKill(t, srv, id)
<del> testContainerWait(t, srv, id)
<del> testDeleteContainer(t, srv, id)
<del> testListContainers(t, srv, 0)
<del>}
<del>
<del>func testCreateContainer(t *testing.T, srv *Server) {
<del>
<ide> r := httptest.NewRecorder()
<ide>
<del> config, _, err := ParseRun([]string{unitTestImageName, "touch test"}, nil)
<add> configJson, err := json.Marshal(&Config{
<add> Image: GetTestImage(runtime).Id,
<add> Memory: 33554432,
<add> Cmd: []string{"touch", "/test"},
<add> })
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> configJson, err := json.Marshal(config)
<add> req, err := http.NewRequest("POST", "/containers/create", bytes.NewReader(configJson))
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> req, err := http.NewRequest("POST", "/containers", bytes.NewReader(configJson))
<add> body, err := postContainersCreate(srv, r, req, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<add> if r.Code != http.StatusCreated {
<add> t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code)
<add> }
<ide>
<del> body, err := postContainersCreate(srv, r, req, nil)
<del> if err != nil {
<add> apiRun := &ApiRun{}
<add> if err := json.Unmarshal(body, apiRun); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> if body == nil {
<del> t.Fatalf("Body expected, received: nil\n")
<add> container := srv.runtime.Get(apiRun.Id)
<add> if container == nil {
<add> t.Fatalf("Container not created")
<ide> }
<ide>
<del> if r.Code != http.StatusCreated {
<del> t.Fatalf("%d Created expected, received %d\n", http.StatusNoContent, r.Code)
<add> if err := container.Run(); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if _, err := os.Stat(path.Join(container.rwPath(), "test")); err != nil {
<add> if os.IsNotExist(err) {
<add> Debugf("Err: %s", err)
<add> t.Fatalf("The test file has not been created")
<add> }
<add> t.Fatal(err)
<ide> }
<ide> }
<ide>
<del>func testListContainers(t *testing.T, srv *Server, expected int) []ApiContainers {
<add>func TestGetContainersPs(t *testing.T) {
<add> runtime, err := newTestRuntime()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer nuke(runtime)
<ide>
<del> r := httptest.NewRecorder()
<add> srv := &Server{runtime: runtime}
<ide>
<del> req, err := http.NewRequest("GET", "/containers?quiet=1&all=1", nil)
<add> container, err := NewBuilder(runtime).Create(&Config{
<add> Image: GetTestImage(runtime).Id,
<add> Cmd: []string{"echo", "test"},
<add> })
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<add> defer runtime.Destroy(container)
<ide>
<del> body, err := getContainersPs(srv, r, req, nil)
<add> req, err := http.NewRequest("GET", "/containers?quiet=1&all=1", nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> var outs []ApiContainers
<del> err = json.Unmarshal(body, &outs)
<add> body, err := getContainersPs(srv, nil, req, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> containers := []ApiContainers{}
<add> err = json.Unmarshal(body, &containers)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if expected >= 0 && len(outs) != expected {
<del> t.Errorf("Excepted %d container, %d found", expected, len(outs))
<add> if len(containers) != 1 {
<add> t.Fatalf("Excepted %d container, %d found", 1, len(containers))
<add> }
<add> if containers[0].Id != container.ShortId() {
<add> t.Fatalf("Container ID mismatch. Expected: %s, received: %s\n", container.ShortId(), containers[0].Id)
<ide> }
<del> return outs
<ide> }
<ide>
<del>func testContainerStart(t *testing.T, srv *Server, id string) {
<add>func TestPostContainersStart(t *testing.T) {
<add> runtime, err := newTestRuntime()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer nuke(runtime)
<ide>
<del> r := httptest.NewRecorder()
<add> srv := &Server{runtime: runtime}
<ide>
<del> req, err := http.NewRequest("POST", "/containers/"+id+"/start", nil)
<add> container, err := NewBuilder(runtime).Create(
<add> &Config{
<add> Image: GetTestImage(runtime).Id,
<add> Cmd: []string{"/bin/cat"},
<add> OpenStdin: true,
<add> },
<add> )
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<add> defer runtime.Destroy(container)
<add>
<add> r := httptest.NewRecorder()
<ide>
<del> body, err := postContainersStart(srv, r, req, nil)
<add> body, err := postContainersStart(srv, r, nil, map[string]string{"name": container.Id})
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del>
<ide> if body != nil {
<ide> t.Fatalf("No body expected, received: %s\n", body)
<ide> }
<del>
<ide> if r.Code != http.StatusNoContent {
<ide> t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
<ide> }
<add>
<add> // Give some time to the process to start
<add> container.WaitTimeout(500 * time.Millisecond)
<add>
<add> if !container.State.Running {
<add> t.Errorf("Container should be running")
<add> }
<add>
<add> if _, err = postContainersStart(srv, r, nil, map[string]string{"name": container.Id}); err == nil {
<add> t.Fatalf("A running containter should be able to be started")
<add> }
<add>
<add> if err := container.Kill(); err != nil {
<add> t.Fatal(err)
<add> }
<ide> }
<ide>
<ide> func testContainerRestart(t *testing.T, srv *Server, id string) {
<ide> func testContainerRestart(t *testing.T, srv *Server, id string) {
<ide> }
<ide> }
<ide>
<del>func testContainerStop(t *testing.T, srv *Server, id string) {
<add>// testContainerRestart(t, srv, id)
<add>// testContainerKill(t, srv, id)
<add>// testContainerWait(t, srv, id)
<add>// testDeleteContainer(t, srv, id)
<add>// testListContainers(t, srv, 0)
<add>func TestPostContainersStop(t *testing.T) {
<add> runtime, err := newTestRuntime()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer nuke(runtime)
<ide>
<del> r := httptest.NewRecorder()
<add> srv := &Server{runtime: runtime}
<ide>
<del> req, err := http.NewRequest("POST", "/containers/"+id+"/stop?t=1", nil)
<add> container, err := NewBuilder(runtime).Create(
<add> &Config{
<add> Image: GetTestImage(runtime).Id,
<add> Cmd: []string{"/bin/cat"},
<add> OpenStdin: true,
<add> },
<add> )
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<add> defer runtime.Destroy(container)
<ide>
<del> body, err := postContainersStop(srv, r, req, nil)
<del> if err != nil {
<add> if err := container.Start(); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<add> // Give some time to the process to start
<add> container.WaitTimeout(500 * time.Millisecond)
<add>
<add> if !container.State.Running {
<add> t.Errorf("Container should be running")
<add> }
<add>
<add> r := httptest.NewRecorder()
<add>
<add> // Note: as it is a POST request, it requires a body.
<add> req, err := http.NewRequest("POST", "/containers/"+container.Id+"/stop?t=1", bytes.NewReader([]byte{}))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> body, err := postContainersStop(srv, r, req, map[string]string{"name": container.Id})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<ide> if body != nil {
<ide> t.Fatalf("No body expected, received: %s\n", body)
<ide> }
<del>
<ide> if r.Code != http.StatusNoContent {
<ide> t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
<ide> }
<add> if container.State.Running {
<add> t.Fatalf("The container hasn't been stopped")
<add> }
<ide> }
<ide>
<ide> func testContainerKill(t *testing.T, srv *Server, id string) {
<ide> func testContainerWait(t *testing.T, srv *Server, id string) {
<ide> }
<ide> }
<ide>
<del>func testDeleteContainer(t *testing.T, srv *Server, id string) {
<add>// FIXME: Test deleting runnign container
<add>// FIXME: Test deleting container with volume
<add>// FIXME: Test deleting volume in use by other container
<add>func TestDeleteContainers(t *testing.T) {
<add> runtime, err := newTestRuntime()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer nuke(runtime)
<ide>
<del> r := httptest.NewRecorder()
<add> srv := &Server{runtime: runtime}
<ide>
<del> req, err := http.NewRequest("DELETE", "/containers/"+id, nil)
<add> container, err := NewBuilder(runtime).Create(&Config{
<add> Image: GetTestImage(runtime).Id,
<add> Cmd: []string{"touch", "/test"},
<add> })
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<add> defer runtime.Destroy(container)
<add>
<add> if err := container.Run(); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> r := httptest.NewRecorder()
<ide>
<del> body, err := deleteContainers(srv, r, req, nil)
<add> req, err := http.NewRequest("DELETE", "/containers/"+container.Id, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<add> body, err := deleteContainers(srv, r, req, map[string]string{"name": container.Id})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<ide> if body != nil {
<ide> t.Fatalf("No body expected, received: %s\n", body)
<ide> }
<del>
<ide> if r.Code != http.StatusNoContent {
<ide> t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
<ide> }
<add>
<add> if c := runtime.Get(container.Id); c != nil {
<add> t.Fatalf("The container as not been deleted")
<add> }
<add>
<add> if _, err := os.Stat(path.Join(container.rwPath(), "test")); err == nil {
<add> t.Fatalf("The test file has not been deleted")
<add> }
<ide> }
<ide>
<ide> func testContainerChanges(t *testing.T, srv *Server, id string) {
<ide><path>container_test.go
<ide> func TestStart(t *testing.T) {
<ide> }
<ide> defer runtime.Destroy(container)
<ide>
<add> cStdin, err := container.StdinPipe()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<ide> if err := container.Start(); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestStart(t *testing.T) {
<ide> }
<ide>
<ide> // Try to avoid the timeoout in destroy. Best effort, don't check error
<del> cStdin, _ := container.StdinPipe()
<ide> cStdin.Close()
<ide> container.WaitTimeout(2 * time.Second)
<ide> }
| 3
|
Ruby
|
Ruby
|
add `stderr` output to exception
|
aaddce4743dd67f569703daba27d72b5bbfbfadf
|
<ide><path>Library/Homebrew/style.rb
<ide> def check_style_impl(files, output_type, options = {})
<ide> system(cache_env, "rubocop", "_#{HOMEBREW_RUBOCOP_VERSION}_", *args)
<ide> !$CHILD_STATUS.success?
<ide> when :json
<del> json, _, status = Open3.capture3(cache_env, "rubocop", "_#{HOMEBREW_RUBOCOP_VERSION}_", "--format", "json", *args)
<add> json, err, status = Open3.capture3(cache_env, "rubocop", "_#{HOMEBREW_RUBOCOP_VERSION}_", "--format", "json", *args)
<ide> # exit status of 1 just means violations were found; other numbers mean
<ide> # execution errors.
<ide> # exitstatus can also be nil if RuboCop process crashes, e.g. due to
<ide> # native extension problems.
<ide> # JSON needs to be at least 2 characters.
<ide> if !(0..1).cover?(status.exitstatus) || json.to_s.length < 2
<del> raise "Error running `rubocop --format json #{args.join " "}`"
<add> raise "Error running `rubocop --format json #{args.join " "}`\n#{err}"
<ide> end
<ide> RubocopResults.new(JSON.parse(json))
<ide> else
| 1
|
Javascript
|
Javascript
|
use type from manifest
|
56a4af04f5e49c921939d8beca5100a18cfbabc4
|
<ide><path>lib/DllReferencePlugin.js
<ide> class DllReferencePlugin {
<ide> manifest = params["dll reference " + manifest];
<ide> }
<ide> const name = this.options.name || manifest.name;
<del> const sourceType = this.options.sourceType || "var";
<add> const sourceType = this.options.sourceType || (manifest && manifest.type) || "var";
<ide> const externals = {};
<ide> const source = "dll-reference " + name;
<ide> externals[source] = name;
| 1
|
PHP
|
PHP
|
remove redundant code
|
b8fbd466c29c442a36f4f7481e7890a8b1cdaa83
|
<ide><path>src/View/Helper/FormHelper.php
<ide> protected function _getInput($fieldName, $options)
<ide> $opts = $options['options'];
<ide> unset($options['options']);
<ide> return $this->multicheckbox($fieldName, $opts, $options);
<del> case 'url':
<del> $options = $this->_initInputField($fieldName, $options);
<del> return $this->widget($options['type'], $options);
<ide> default:
<ide> return $this->{$options['type']}($fieldName, $options);
<ide> }
<ide><path>src/View/Widget/FileWidget.php
<ide> public function render(array $data, ContextInterface $context)
<ide> 'templateVars' => $data['templateVars'],
<ide> 'attrs' => $this->_templates->formatAttributes(
<ide> $data,
<del> ['name', 'val']
<add> ['name']
<ide> )
<ide> ]);
<ide> }
| 2
|
Text
|
Text
|
add blurb about implications of abi stability
|
7033fc771a1832d678cbcd7ec48b848f7acc647c
|
<ide><path>doc/api/addons.md
<ide> set of APIs that are used by the native code. Instead of using the V8
<ide> or [Native Abstractions for Node.js][] APIs, the functions available
<ide> in the N-API are used.
<ide>
<add>Creating and maintaining an addon that benefits from the ABI stability
<add>provided by N-API carries with it certain
<add>[implementation considerations](n-api.html#n_api_implications_of_abi_stability).
<add>
<ide> To use N-API in the above "Hello world" example, replace the content of
<ide> `hello.cc` with the following. All other instructions remain the same.
<ide>
<ide><path>doc/api/n-api.md
<ide> for the N-API C based functions exported by Node.js. These wrappers are not
<ide> part of N-API, nor will they be maintained as part of Node.js. One such
<ide> example is: [node-addon-api](https://github.com/nodejs/node-addon-api).
<ide>
<add>## Implications of ABI Stability
<add>
<add>Although N-API provides an ABI stability guarantee, other parts of Node.js do
<add>not, and any external libraries used from the addon may not. In particular,
<add>none of the following APIs provide an ABI stability guarantee across major
<add>versions:
<add>* the Node.js C++ APIs available via any of
<add> ```C++
<add> #include <node.h>
<add> #include <node_buffer.h>
<add> #include <node_version.h>
<add> #include <node_object_wrap.h>
<add> ```
<add>* the libuv APIs which are also included with Node.js and available via
<add> ```C++
<add> #include <uv.h>
<add> ```
<add>* the V8 API available via
<add> ```C++
<add> #include <v8.h>
<add> ```
<add>
<add>Thus, for an addon to remain ABI-compatible across Node.js major versions, it
<add>must make use exclusively of N-API by restricting itself to using
<add>```C
<add>#include <node_api.h>
<add>```
<add>and by checking, for all external libraries that it uses, that the external
<add>library makes ABI stability guarantees similar to N-API.
<add>
<ide> ## Usage
<ide>
<ide> In order to use the N-API functions, include the file
| 2
|
Ruby
|
Ruby
|
add more tests for `shared_library`
|
1d710047a5e4e4ab5e8855f6aa6a3394b386573d
|
<ide><path>Library/Homebrew/test/os/linux/formula_spec.rb
<ide> f = Testball.new
<ide> expect(f.shared_library("foobar")).to eq("foobar.so")
<ide> expect(f.shared_library("foobar", 2)).to eq("foobar.so.2")
<add> expect(f.shared_library("foobar", nil)).to eq("foobar.so")
<add> expect(f.shared_library("foobar", "*")).to eq("foobar.so{,.*}")
<add> expect(f.shared_library("*")).to eq("*.so{,.*}")
<add> expect(f.shared_library("*", 2)).to eq("*.so.2")
<add> expect(f.shared_library("*", nil)).to eq("*.so{,.*}")
<add> expect(f.shared_library("*", "*")).to eq("*.so{,.*}")
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/os/mac/formula_spec.rb
<ide> f = Testball.new
<ide> expect(f.shared_library("foobar")).to eq("foobar.dylib")
<ide> expect(f.shared_library("foobar", 2)).to eq("foobar.2.dylib")
<add> expect(f.shared_library("foobar", nil)).to eq("foobar.dylib")
<add> expect(f.shared_library("foobar", "*")).to eq("foobar{,.*}.dylib")
<add> expect(f.shared_library("*")).to eq("*.dylib")
<add> expect(f.shared_library("*", 2)).to eq("*.2.dylib")
<add> expect(f.shared_library("*", nil)).to eq("*.dylib")
<add> expect(f.shared_library("*", "*")).to eq("*.dylib")
<ide> end
<ide> end
<ide> end
| 2
|
Ruby
|
Ruby
|
replace space/hyphen in enum scope names
|
1eb977489645ed99d2791abf4ce8f46571e06901
|
<ide><path>activerecord/lib/active_record/enum.rb
<ide> def enum(definitions)
<ide> suffix = "_#{enum_suffix}"
<ide> end
<ide>
<del> value_method_name = "#{prefix}#{label}#{suffix}"
<add> method_friendly_label = label.to_s.gsub(/\W+/, "_")
<add> value_method_name = "#{prefix}#{method_friendly_label}#{suffix}"
<ide> enum_values[label] = value
<ide> label = label.to_s
<ide>
<ide><path>activerecord/test/cases/enum_test.rb
<ide> def self.name; "Book"; end
<ide> assert_raises(NoMethodError) { klass.proposed }
<ide> end
<ide>
<add> test "scopes are named like methods" do
<add> klass = Class.new(ActiveRecord::Base) do
<add> self.table_name = "cats"
<add> enum breed: { "American Bobtail" => 0, "Balinese-Javanese" => 1 }
<add> end
<add>
<add> assert_respond_to klass, :American_Bobtail
<add> assert_respond_to klass, :Balinese_Javanese
<add> end
<add>
<ide> test "capital characters for enum names" do
<ide> klass = Class.new(ActiveRecord::Base) do
<ide> self.table_name = "computers"
| 2
|
Ruby
|
Ruby
|
use tap class
|
44383fecb865014142c8934eacf2c90837a5b57c
|
<ide><path>Library/Homebrew/cmd/readall.rb
<ide> def readall
<ide> if ARGV.named.empty?
<ide> formulae = Formula.full_names
<ide> else
<del> user, repo = tap_args
<del> user.downcase!
<del> repo.downcase!
<del> tap = HOMEBREW_LIBRARY/"Taps/#{user}/homebrew-#{repo}"
<del> raise "#{tap} does not exist!" unless tap.directory?
<del> tap.find_formula { |f| formulae << f }
<add> tap = Tap.new(*tap_args)
<add> raise "#{tap} does not exist!" unless tap.installed?
<add> formulae = tap.formula_files
<ide> end
<ide>
<ide> formulae.sort.each do |n|
<ide><path>Library/Homebrew/cmd/tap.rb
<add>require "tap"
<add>
<ide> module Homebrew
<ide> def tap
<ide> if ARGV.empty?
<del> each_tap do |user, repo|
<del> puts "#{user.basename}/#{repo.basename.sub("homebrew-", "")}" if (repo/".git").directory?
<del> end
<add> puts Tap.names
<ide> elsif ARGV.first == "--repair"
<ide> migrate_taps :force => true
<ide> else
<ide> def tap
<ide> end
<ide>
<ide> def install_tap user, repo, clone_target=nil
<del> # we special case homebrew so users don't have to shift in a terminal
<del> repouser = if user == "homebrew" then "Homebrew" else user end
<del> user = "homebrew" if user == "Homebrew"
<del>
<del> # we downcase to avoid case-insensitive filesystem issues
<del> tapd = HOMEBREW_LIBRARY/"Taps/#{user.downcase}/homebrew-#{repo.downcase}"
<del> return false if tapd.directory?
<del> ohai "Tapping #{repouser}/#{repo}"
<del> if clone_target
<del> args = %W[clone #{clone_target} #{tapd}]
<del> else
<del> args = %W[clone https://github.com/#{repouser}/homebrew-#{repo} #{tapd}]
<del> end
<add> tap = Tap.new user, repo, clone_target
<add> return false if tap.installed?
<add> ohai "Tapping #{tap}"
<add> args = %W[clone #{tap.remote} #{tap.path}]
<ide> args << "--depth=1" unless ARGV.include?("--full")
<ide> safe_system "git", *args
<ide>
<del> files = []
<del> tapd.find_formula { |file| files << file }
<del> puts "Tapped #{files.length} formula#{plural(files.length, 'e')} (#{tapd.abv})"
<add> formula_count = tap.formula_files.size
<add> puts "Tapped #{formula_count} formula#{plural(formula_count, 'e')} (#{tap.path.abv})"
<ide>
<del> if check_private?(clone_target, repouser, repo)
<add> if !clone_target && tap.private?
<ide> puts <<-EOS.undent
<ide> It looks like you tapped a private repository. To avoid entering your
<ide> credentials each time you update, you can use git HTTP credential
<ide> caching or issue the following command:
<ide>
<del> cd #{tapd}
<del> git remote set-url origin git@github.com:#{repouser}/homebrew-#{repo}.git
<del> EOS
<add> cd #{tap.path}
<add> git remote set-url origin git@github.com:#{tap.user}/homebrew-#{tap.repo}.git
<add> EOS
<ide> end
<ide>
<ide> true
<ide> def migrate_taps(options={})
<ide>
<ide> private
<ide>
<del> def each_tap
<del> taps = HOMEBREW_LIBRARY.join("Taps")
<del>
<del> if taps.directory?
<del> taps.subdirs.each do |user|
<del> user.subdirs.each do |repo|
<del> yield user, repo
<del> end
<del> end
<del> end
<del> end
<del>
<ide> def tap_args(tap_name=ARGV.named.first)
<ide> tap_name =~ HOMEBREW_TAP_ARGS_REGEX
<ide> raise "Invalid tap name" unless $1 && $3
<ide> [$1, $3]
<ide> end
<del>
<del> def private_tap?(user, repo)
<del> GitHub.private_repo?(user, "homebrew-#{repo}")
<del> rescue GitHub::HTTPNotFoundError
<del> true
<del> rescue GitHub::Error
<del> false
<del> end
<del>
<del> def check_private?(clone_target, user, repo)
<del> !clone_target && private_tap?(user, repo)
<del> end
<ide> end
<ide><path>Library/Homebrew/cmd/untap.rb
<ide> module Homebrew
<ide> def untap
<ide> raise "Usage is `brew untap <tap-name>`" if ARGV.empty?
<ide>
<del> ARGV.each do |tapname|
<del> user, repo = tap_args(tapname)
<add> ARGV.named.each do |tapname|
<add> tap = Tap.new(*tap_args(tapname))
<ide>
<del> # We consistently downcase in tap to ensure we are not bitten by
<del> # case-insensitive filesystem issues, which is the default on mac. The
<del> # problem being the filesystem cares, but our regexps don't. So unless we
<del> # resolve *every* path we will get bitten.
<del> user.downcase!
<del> repo.downcase!
<add> raise "No such tap!" unless tap.installed?
<add> puts "Untapping #{tap}... (#{tap.path.abv})"
<ide>
<del> tapd = HOMEBREW_LIBRARY/"Taps/#{user}/homebrew-#{repo}"
<del>
<del> raise "No such tap!" unless tapd.directory?
<del> puts "Untapping #{tapname}... (#{tapd.abv})"
<del>
<del> files = []
<del> tapd.find_formula { |file| files << file }
<del> tapd.rmtree
<del> tapd.dirname.rmdir_if_possible
<del> puts "Untapped #{files.length} formula#{plural(files.length, 'e')}"
<add> formula_count = tap.formula_files.size
<add> tap.path.rmtree
<add> tap.path.dirname.rmdir_if_possible
<add> puts "Untapped #{formula_count} formula#{plural(formula_count, 'e')}"
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/cmd/update.rb
<ide> def update
<ide> # this procedure will be removed in the future if it seems unnecessasry
<ide> rename_taps_dir_if_necessary
<ide>
<del> each_tap do |user, repo|
<del> repo.cd do
<del> updater = Updater.new(repo)
<add> Tap.each do |tap|
<add> tap.path.cd do
<add> updater = Updater.new(tap.path)
<ide>
<ide> begin
<ide> updater.pull!
<ide> rescue
<del> onoe "Failed to update tap: #{user.basename}/#{repo.basename.sub("homebrew-", "")}"
<add> onoe "Failed to update tap: #{tap}"
<ide> else
<ide> report.update(updater.report) do |key, oldval, newval|
<ide> oldval.concat(newval)
| 4
|
PHP
|
PHP
|
fix route caching attempt
|
90b0167d97e61eb06fce9cfc58527f4e09cd2a5e
|
<ide><path>src/Illuminate/Routing/CompiledRouteCollection.php
<ide> public function mapAttributesToRoutes()
<ide> */
<ide> protected function newRoute(array $attributes)
<ide> {
<del> $baseUri = ltrim(Str::replaceFirst(
<del> ltrim($attributes['action']['prefix'] ?? '', '/'),
<del> '',
<del> $attributes['uri']
<del> ), '/');
<add> if (! empty($attributes['action']['prefix'] ?? '')) {
<add> $prefixSegments = explode('/', trim($attributes['action']['prefix'], '/'));
<add>
<add> $baseUri = trim(implode(
<add> '/', array_slice(explode('/', trim($attributes['uri'], '/')), count($prefixSegments))
<add> ), '/');
<add> } else {
<add> $baseUri = $attributes['uri'];
<add> }
<ide>
<ide> return (new Route($attributes['methods'], $baseUri == '' ? '/' : $baseUri, $attributes['action']))
<ide> ->setFallback($attributes['fallback'])
| 1
|
Ruby
|
Ruby
|
fix jar detection
|
979e6674cf8684ffbf7fbff7c8e2b70043e8c6af
|
<ide><path>Library/Homebrew/unpack_strategy.rb
<ide> def self.can_extract?(path:, magic_number:)
<ide> return false unless ZipUnpackStrategy.can_extract?(path: path, magic_number: magic_number)
<ide>
<ide> # Check further if the ZIP is a LuaRocks package.
<del> out, _, status = Open3.capture3("zipinfo", "-1", path)
<del> status.success? && out.split("\n").any? { |line| line.match?(%r{\A[^/]+.rockspec\Z}) }
<add> out, = Open3.capture3("zipinfo", "-1", path)
<add> out.encode(Encoding::UTF_8, invalid: :replace)
<add> .split("\n")
<add> .any? { |line| line.match?(%r{\A[^/]+.rockspec\Z}) }
<ide> end
<ide> end
<ide>
<ide> def self.can_extract?(path:, magic_number:)
<ide> return false unless ZipUnpackStrategy.can_extract?(path: path, magic_number: magic_number)
<ide>
<ide> # Check further if the ZIP is a JAR/WAR.
<del> out, _, status = Open3.capture3("zipinfo", "-1", path)
<del> status.success? && out.split("\n").include?("META-INF/MANIFEST.MF")
<add> out, = Open3.capture3("zipinfo", "-1", path)
<add> out.encode(Encoding::UTF_8, invalid: :replace)
<add> .split("\n")
<add> .include?("META-INF/MANIFEST.MF")
<ide> end
<ide> end
<ide>
| 1
|
Ruby
|
Ruby
|
add gcc-5 to compilers support c++11
|
3649b31765d94cd0e0f0cdfc1acae60951702b9b
|
<ide><path>Library/Homebrew/extend/ENV/std.rb
<ide> def cxx11
<ide> if compiler == :clang
<ide> append 'CXX', '-std=c++11'
<ide> append 'CXX', '-stdlib=libc++'
<del> elsif compiler =~ /gcc-4\.(8|9)/
<add> elsif compiler =~ /gcc-(4\.(8|9)|5)/
<ide> append 'CXX', '-std=c++11'
<ide> else
<ide> raise "The selected compiler doesn't support C++11: #{compiler}"
<ide><path>Library/Homebrew/extend/ENV/super.rb
<ide> def cxx11
<ide> when "clang"
<ide> append 'HOMEBREW_CCCFG', "x", ''
<ide> append 'HOMEBREW_CCCFG', "g", ''
<del> when /gcc-4\.(8|9)/
<add> when /gcc-(4\.(8|9)|5)/
<ide> append 'HOMEBREW_CCCFG', "x", ''
<ide> else
<ide> raise "The selected compiler doesn't support C++11: #{homebrew_cc}"
| 2
|
Ruby
|
Ruby
|
remove use of mocha from active model
|
5a6ae7f7539216931f2b3f4aa53394ac4136c74e
|
<ide><path>activemodel/test/cases/errors_test.rb
<ide> def self.lookup_ancestors
<ide> end
<ide> end
<ide>
<add> def setup
<add> @mock_generator = MiniTest::Mock.new
<add> end
<add>
<add> def teardown
<add> @mock_generator.verify
<add> end
<add>
<ide> def test_delete
<ide> errors = ActiveModel::Errors.new(self)
<ide> errors[:foo] << 'omg'
<ide> def test_no_key
<ide>
<ide> test "add_on_empty generates message" do
<ide> person = Person.new
<del> person.errors.expects(:generate_message).with(:name, :empty, {})
<del> assert_deprecated do
<del> person.errors.add_on_empty :name
<add> @mock_generator.expect(:call, nil, [:name, :empty, {}])
<add> person.errors.stub(:generate_message, @mock_generator) do
<add> assert_deprecated do
<add> person.errors.add_on_empty :name
<add> end
<ide> end
<ide> end
<ide>
<ide> test "add_on_empty generates message for multiple attributes" do
<ide> person = Person.new
<del> person.errors.expects(:generate_message).with(:name, :empty, {})
<del> person.errors.expects(:generate_message).with(:age, :empty, {})
<del> assert_deprecated do
<del> person.errors.add_on_empty [:name, :age]
<add> @mock_generator.expect(:call, nil, [:name, :empty, {}])
<add> @mock_generator.expect(:call, nil, [:age, :empty, {}])
<add> person.errors.stub(:generate_message, @mock_generator) do
<add> assert_deprecated do
<add> person.errors.add_on_empty [:name, :age]
<add> end
<ide> end
<ide> end
<ide>
<ide> test "add_on_empty generates message with custom default message" do
<ide> person = Person.new
<del> person.errors.expects(:generate_message).with(:name, :empty, { message: 'custom' })
<del> assert_deprecated do
<del> person.errors.add_on_empty :name, message: 'custom'
<add> @mock_generator.expect(:call, nil, [:name, :empty, { message: 'custom' }])
<add> person.errors.stub(:generate_message, @mock_generator) do
<add> assert_deprecated do
<add> person.errors.add_on_empty :name, message: 'custom'
<add> end
<ide> end
<ide> end
<ide>
<ide> test "add_on_empty generates message with empty string value" do
<ide> person = Person.new
<ide> person.name = ''
<del> person.errors.expects(:generate_message).with(:name, :empty, {})
<del> assert_deprecated do
<del> person.errors.add_on_empty :name
<add> @mock_generator.expect(:call, nil, [:name, :empty, {}])
<add> person.errors.stub(:generate_message, @mock_generator) do
<add> assert_deprecated do
<add> person.errors.add_on_empty :name
<add> end
<ide> end
<ide> end
<ide>
<ide> test "add_on_blank generates message" do
<ide> person = Person.new
<del> person.errors.expects(:generate_message).with(:name, :blank, {})
<del> assert_deprecated do
<del> person.errors.add_on_blank :name
<add> @mock_generator.expect(:call, nil, [:name, :blank, {}])
<add> person.errors.stub(:generate_message, @mock_generator) do
<add> assert_deprecated do
<add> person.errors.add_on_blank :name
<add> end
<ide> end
<ide> end
<ide>
<ide> test "add_on_blank generates message for multiple attributes" do
<ide> person = Person.new
<del> person.errors.expects(:generate_message).with(:name, :blank, {})
<del> person.errors.expects(:generate_message).with(:age, :blank, {})
<del> assert_deprecated do
<del> person.errors.add_on_blank [:name, :age]
<add> @mock_generator.expect(:call, nil, [:name, :blank, {}])
<add> @mock_generator.expect(:call, nil, [:age, :blank, {}])
<add> person.errors.stub(:generate_message, @mock_generator) do
<add> assert_deprecated do
<add> person.errors.add_on_blank [:name, :age]
<add> end
<ide> end
<ide> end
<ide>
<ide> test "add_on_blank generates message with custom default message" do
<ide> person = Person.new
<del> person.errors.expects(:generate_message).with(:name, :blank, { message: 'custom' })
<del> assert_deprecated do
<del> person.errors.add_on_blank :name, message: 'custom'
<add> @mock_generator.expect(:call, nil, [:name, :blank, { message: 'custom' }])
<add> person.errors.stub(:generate_message, @mock_generator) do
<add> assert_deprecated do
<add> person.errors.add_on_blank :name, message: 'custom'
<add> end
<ide> end
<ide> end
<ide>
<ide><path>activemodel/test/cases/helper.rb
<ide>
<ide> require 'active_support/testing/autorun'
<ide>
<del>require 'mocha/setup' # FIXME: stop using mocha
<add>require 'minitest/mock'
<ide>
<ide> # Skips the current run on Rubinius using Minitest::Assertions#skip
<ide> def rubinius_skip(message = '')
<ide><path>activemodel/test/cases/validations/i18n_validation_test.rb
<ide> def setup
<ide> I18n.load_path.clear
<ide> I18n.backend = I18n::Backend::Simple.new
<ide> I18n.backend.store_translations('en', errors: { messages: { custom: nil } })
<add> @mock_generator = MiniTest::Mock.new
<ide> end
<ide>
<ide> def teardown
<ide> Person.clear_validators!
<ide> I18n.load_path.replace @old_load_path
<ide> I18n.backend = @old_backend
<ide> I18n.backend.reload!
<add> @mock_generator.verify
<ide> end
<ide>
<ide> def test_full_message_encoding
<ide> def test_full_message_encoding
<ide>
<ide> def test_errors_full_messages_translates_human_attribute_name_for_model_attributes
<ide> @person.errors.add(:name, 'not found')
<del> Person.expects(:human_attribute_name).with(:name, default: 'Name').returns("Person's name")
<del> assert_equal ["Person's name not found"], @person.errors.full_messages
<add> @mock_generator.expect(:call, "Person's name", [:name, default: 'Name'])
<add> Person.stub(:human_attribute_name, @mock_generator) do
<add> assert_equal ["Person's name not found"], @person.errors.full_messages
<add> end
<ide> end
<ide>
<ide> def test_errors_full_messages_uses_format
<ide> def test_errors_full_messages_uses_format
<ide> test "validates_confirmation_of on generated message #{name}" do
<ide> Person.validates_confirmation_of :title, validation_options
<ide> @person.title_confirmation = 'foo'
<del> @person.errors.expects(:generate_message).with(:title_confirmation, :confirmation, generate_message_options.merge(attribute: 'Title'))
<del> @person.valid?
<add> @mock_generator.expect(:call, nil, [:title_confirmation, :confirmation, generate_message_options.merge(attribute: 'Title')])
<add> @person.errors.stub(:generate_message, @mock_generator) do
<add> @person.valid?
<add> end
<ide> end
<ide> end
<ide>
<ide> def test_errors_full_messages_uses_format
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<ide> test "validates_acceptance_of on generated message #{name}" do
<ide> Person.validates_acceptance_of :title, validation_options.merge(allow_nil: false)
<del> @person.errors.expects(:generate_message).with(:title, :accepted, generate_message_options)
<del> @person.valid?
<add> @mock_generator.expect(:call, nil, [:title, :accepted, generate_message_options])
<add> @person.errors.stub(:generate_message, @mock_generator) do
<add> @person.valid?
<add> end
<ide> end
<ide> end
<ide>
<ide> def test_errors_full_messages_uses_format
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<ide> test "validates_presence_of on generated message #{name}" do
<ide> Person.validates_presence_of :title, validation_options
<del> @person.errors.expects(:generate_message).with(:title, :blank, generate_message_options)
<del> @person.valid?
<add> @mock_generator.expect(:call, nil, [:title, :blank, generate_message_options])
<add> @person.errors.stub(:generate_message, @mock_generator) do
<add> @person.valid?
<add> end
<ide> end
<ide> end
<ide>
<ide> def test_errors_full_messages_uses_format
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<ide> test "validates_length_of for :withing on generated message when too short #{name}" do
<ide> Person.validates_length_of :title, validation_options.merge(within: 3..5)
<del> @person.errors.expects(:generate_message).with(:title, :too_short, generate_message_options.merge(count: 3))
<del> @person.valid?
<add> @mock_generator.expect(:call, nil, [:title, :too_short, generate_message_options.merge(count: 3)])
<add> @person.errors.stub(:generate_message, @mock_generator) do
<add> @person.valid?
<add> end
<ide> end
<ide> end
<ide>
<ide> def test_errors_full_messages_uses_format
<ide> test "validates_length_of for :too_long generated message #{name}" do
<ide> Person.validates_length_of :title, validation_options.merge(within: 3..5)
<ide> @person.title = 'this title is too long'
<del> @person.errors.expects(:generate_message).with(:title, :too_long, generate_message_options.merge(count: 5))
<del> @person.valid?
<add> @mock_generator.expect(:call, nil, [:title, :too_long, generate_message_options.merge(count: 5)])
<add> @person.errors.stub(:generate_message, @mock_generator) do
<add> @person.valid?
<add> end
<ide> end
<ide> end
<ide>
<ide> def test_errors_full_messages_uses_format
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<ide> test "validates_length_of for :is on generated message #{name}" do
<ide> Person.validates_length_of :title, validation_options.merge(is: 5)
<del> @person.errors.expects(:generate_message).with(:title, :wrong_length, generate_message_options.merge(count: 5))
<del> @person.valid?
<add> @mock_generator.expect(:call, nil, [:title, :wrong_length, generate_message_options.merge(count: 5)])
<add> @person.errors.stub(:generate_message, @mock_generator) do
<add> @person.valid?
<add> end
<ide> end
<ide> end
<ide>
<ide> def test_errors_full_messages_uses_format
<ide> test "validates_format_of on generated message #{name}" do
<ide> Person.validates_format_of :title, validation_options.merge(with: /\A[1-9][0-9]*\z/)
<ide> @person.title = '72x'
<del> @person.errors.expects(:generate_message).with(:title, :invalid, generate_message_options.merge(value: '72x'))
<del> @person.valid?
<add> @mock_generator.expect(:call, nil, [:title, :invalid, generate_message_options.merge(value: '72x')])
<add> @person.errors.stub(:generate_message, @mock_generator) do
<add> @person.valid?
<add> end
<ide> end
<ide> end
<ide>
<ide> def test_errors_full_messages_uses_format
<ide> test "validates_inclusion_of on generated message #{name}" do
<ide> Person.validates_inclusion_of :title, validation_options.merge(in: %w(a b c))
<ide> @person.title = 'z'
<del> @person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(value: 'z'))
<del> @person.valid?
<add> @mock_generator.expect(:call, nil, [:title, :inclusion, generate_message_options.merge(value: 'z')])
<add> @person.errors.stub(:generate_message, @mock_generator) do
<add> @person.valid?
<add> end
<ide> end
<ide> end
<ide>
<ide> def test_errors_full_messages_uses_format
<ide> test "validates_inclusion_of using :within on generated message #{name}" do
<ide> Person.validates_inclusion_of :title, validation_options.merge(within: %w(a b c))
<ide> @person.title = 'z'
<del> @person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(value: 'z'))
<del> @person.valid?
<add> @mock_generator.expect(:call, nil, [:title, :inclusion, generate_message_options.merge(value: 'z')])
<add> @person.errors.stub(:generate_message, @mock_generator) do
<add> @person.valid?
<add> end
<ide> end
<ide> end
<ide>
<ide> def test_errors_full_messages_uses_format
<ide> test "validates_exclusion_of generated message #{name}" do
<ide> Person.validates_exclusion_of :title, validation_options.merge(in: %w(a b c))
<ide> @person.title = 'a'
<del> @person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(value: 'a'))
<del> @person.valid?
<add> @mock_generator.expect(:call, nil, [:title, :exclusion, generate_message_options.merge(value: 'a')])
<add> @person.errors.stub(:generate_message, @mock_generator) do
<add> @person.valid?
<add> end
<ide> end
<ide> end
<ide>
<ide> def test_errors_full_messages_uses_format
<ide> test "validates_exclusion_of using :within generated message #{name}" do
<ide> Person.validates_exclusion_of :title, validation_options.merge(within: %w(a b c))
<ide> @person.title = 'a'
<del> @person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(value: 'a'))
<del> @person.valid?
<add> @mock_generator.expect(:call, nil, [:title, :exclusion, generate_message_options.merge(value: 'a')])
<add> @person.errors.stub(:generate_message, @mock_generator) do
<add> @person.valid?
<add> end
<ide> end
<ide> end
<ide>
<ide> def test_errors_full_messages_uses_format
<ide> test "validates_numericality_of generated message #{name}" do
<ide> Person.validates_numericality_of :title, validation_options
<ide> @person.title = 'a'
<del> @person.errors.expects(:generate_message).with(:title, :not_a_number, generate_message_options.merge(value: 'a'))
<del> @person.valid?
<add> @mock_generator.expect(:call, nil, [:title, :not_a_number, generate_message_options.merge(value: 'a')])
<add> @person.errors.stub(:generate_message, @mock_generator) do
<add> @person.valid?
<add> end
<ide> end
<ide> end
<ide>
<ide> def test_errors_full_messages_uses_format
<ide> test "validates_numericality_of for :only_integer on generated message #{name}" do
<ide> Person.validates_numericality_of :title, validation_options.merge(only_integer: true)
<ide> @person.title = '0.0'
<del> @person.errors.expects(:generate_message).with(:title, :not_an_integer, generate_message_options.merge(value: '0.0'))
<del> @person.valid?
<add> @mock_generator.expect(:call, nil, [:title, :not_an_integer, generate_message_options.merge(value: '0.0')])
<add> @person.errors.stub(:generate_message, @mock_generator) do
<add> @person.valid?
<add> end
<ide> end
<ide> end
<ide>
<ide> def test_errors_full_messages_uses_format
<ide> test "validates_numericality_of for :odd on generated message #{name}" do
<ide> Person.validates_numericality_of :title, validation_options.merge(only_integer: true, odd: true)
<ide> @person.title = 0
<del> @person.errors.expects(:generate_message).with(:title, :odd, generate_message_options.merge(value: 0))
<del> @person.valid?
<add> @mock_generator.expect(:call, nil, [:title, :odd, generate_message_options.merge(value: 0)])
<add> @person.errors.stub(:generate_message, @mock_generator) do
<add> @person.valid?
<add> end
<ide> end
<ide> end
<ide>
<ide> def test_errors_full_messages_uses_format
<ide> test "validates_numericality_of for :less_than on generated message #{name}" do
<ide> Person.validates_numericality_of :title, validation_options.merge(only_integer: true, less_than: 0)
<ide> @person.title = 1
<del> @person.errors.expects(:generate_message).with(:title, :less_than, generate_message_options.merge(value: 1, count: 0))
<del> @person.valid?
<add> @mock_generator.expect(:call, nil, [:title, :less_than, generate_message_options.merge(value: 1, count: 0)])
<add> @person.errors.stub(:generate_message, @mock_generator) do
<add> @person.valid?
<add> end
<ide> end
<ide> end
<ide>
<ide><path>activemodel/test/cases/validations/with_validation_test.rb
<ide> def check_validity!
<ide>
<ide> test "passes all configuration options to the validator class" do
<ide> topic = Topic.new
<del> validator = mock()
<del> validator.expects(:new).with(foo: :bar, if: "1 == 1", class: Topic).returns(validator)
<del> validator.expects(:validate).with(topic)
<add> validator = MiniTest::Mock.new
<add> validator.expect(:new, validator, [{foo: :bar, if: "1 == 1", class: Topic}])
<add> validator.expect(:validate, nil, [topic])
<add> validator.expect(:is_a?, false, [Symbol])
<ide>
<ide> Topic.validates_with(validator, if: "1 == 1", foo: :bar)
<ide> assert topic.valid?
<add> validator.verify
<ide> end
<ide>
<ide> test "validates_with with options" do
| 4
|
Text
|
Text
|
change plain text in sample code to be comments
|
8f20aaf0b9b55983a967c5212c35ebef4419efae
|
<ide><path>guide/english/css/background-opacity/index.md
<ide> You have to add the following CSS property to achieve the transparency levels.
<ide> opacity:1;
<ide> }
<ide>
<del>OR
<add>/* OR */
<ide>
<ide> .class-name {
<ide> opacity:1.0;
<ide> OR
<ide> .class-name {
<ide> opacity:0.5;
<ide> }
<del>Opacity value can be anything between 0 and 1;
<add>/* Opacity value can be anything between 0 and 1; */
<ide> ```
<ide>
<ide> #### Transparent
<ide> Opacity value can be anything between 0 and 1;
<ide> opacity:0;
<ide> }
<ide>
<del>OR
<add>/* OR */
<ide>
<ide> .class-name {
<ide> opacity:0.0;
| 1
|
Java
|
Java
|
add missing check to avoid re-initialization
|
007bdede4693332eb9fb857085fd87c389c3ebfa
|
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/WebSocketConfigurationSupport.java
<ide> protected void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
<ide> @Bean
<ide> @Nullable
<ide> public TaskScheduler defaultSockJsTaskScheduler() {
<del> if (initHandlerRegistry().requiresTaskScheduler()) {
<del> ThreadPoolTaskScheduler threadPoolScheduler = new ThreadPoolTaskScheduler();
<del> threadPoolScheduler.setThreadNamePrefix("SockJS-");
<del> threadPoolScheduler.setPoolSize(Runtime.getRuntime().availableProcessors());
<del> threadPoolScheduler.setRemoveOnCancelPolicy(true);
<del> this.scheduler = threadPoolScheduler;
<add> if (this.scheduler == null) {
<add> if (initHandlerRegistry().requiresTaskScheduler()) {
<add> ThreadPoolTaskScheduler threadPoolScheduler = new ThreadPoolTaskScheduler();
<add> threadPoolScheduler.setThreadNamePrefix("SockJS-");
<add> threadPoolScheduler.setPoolSize(Runtime.getRuntime().availableProcessors());
<add> threadPoolScheduler.setRemoveOnCancelPolicy(true);
<add> this.scheduler = threadPoolScheduler;
<add> }
<ide> }
<ide> return this.scheduler;
<ide> }
| 1
|
PHP
|
PHP
|
remove locks from file system
|
89d1b87fde7cc37f6a0ab164ccb4037acde2ac0e
|
<ide><path>src/Illuminate/Filesystem/Filesystem.php
<ide> public function requireOnce($file)
<ide> */
<ide> public function put($path, $contents)
<ide> {
<del> return file_put_contents($path, $contents, LOCK_EX);
<add> return file_put_contents($path, $contents);
<ide> }
<ide>
<ide> /**
<ide> public function put($path, $contents)
<ide> */
<ide> public function append($path, $data)
<ide> {
<del> return file_put_contents($path, $data, LOCK_EX | FILE_APPEND);
<add> return file_put_contents($path, $data, FILE_APPEND);
<ide> }
<ide>
<ide> /**
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.