content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Text | Text | fix typo in changelog [ci skip] | 4aa25d4c76b5487caf2b35e677b72ece595f400f | <ide><path>activemodel/CHANGELOG.md
<del>* Remove deprecated `Validatior#setup` without replacement.
<add>* Remove deprecated `Validator#setup` without replacement.
<ide>
<ide> See #10716.
<ide> | 1 |
Text | Text | modify url because installation directory removed | 56cca9292252efbcecad69fc965d63d99fda5e5e | <ide><path>docs/reference/commandline/run.md
<ide> specified volumes for the container.
<ide>
<ide> By bind-mounting the docker unix socket and statically linked docker
<ide> binary (refer to [get the linux binary](
<del>../../installation/binaries.md#get-the-linux-binary)),
<add>https://docs.docker.com/engine/installation/binaries/#/get-the-linux-binary)),
<ide> you give the container the full access to create and manipulate the host's
<ide> Docker daemon.
<ide> | 1 |
Javascript | Javascript | add @scope so properties are picked up by jsdoc | bc75b1ac96b5c675aa27397250c5c02b1e0e46a7 | <ide><path>packages/ember-viewstates/lib/view_state.js
<ide> var get = Ember.get, set = Ember.set;
<ide> `view` that references the `Ember.View` object that was interacted with.
<ide>
<ide> **/
<del>Ember.ViewState = Ember.State.extend({
<add>Ember.ViewState = Ember.State.extend(
<add>/** @scope Ember.ViewState.prototype */ {
<ide> isViewState: true,
<ide>
<ide> enter: function(stateManager) { | 1 |
Text | Text | fix inaccurate callback documentation | a441eabc25a129d1137c0584c52428d905c1f464 | <ide><path>guides/source/active_record_callbacks.md
<ide> WARNING. When a transaction completes, the `after_commit` or `after_rollback` ca
<ide>
<ide> WARNING. The code executed within `after_commit` or `after_rollback` callbacks is itself not enclosed within a transaction.
<ide>
<del>WARNING. Using both `after_create_commit` and `after_update_commit` in the same model will only allow the last callback defined to take effect, and will override all others.
<add>WARNING. Using both `after_create_commit` and `after_update_commit` with the same method name will only allow the last callback defined to take effect, as they both internally alias to `after_commit` which overrides previously defined callbacks with the same method name.
<ide>
<ide> ```ruby
<ide> class User < ApplicationRecord | 1 |
PHP | PHP | add assertsessionhasinput to testresponse | 422754fb7b28fe6c75ee57f1dd476eaadc2a4c40 | <ide><path>src/Illuminate/Foundation/Testing/TestResponse.php
<ide> public function assertSessionHasAll(array $bindings)
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Assert that the session has a given value in the flashed input array.
<add> *
<add> * @param string|array $key
<add> * @param mixed $value
<add> * @return $this
<add> */
<add> public function assertSessionHasInput($key, $value = null)
<add> {
<add> if (is_array($key)) {
<add> foreach ($key as $k => $v) {
<add> if (is_int($k)) {
<add> $this->assertSessionHasInput($v);
<add> } else {
<add> $this->assertSessionHasInput($k, $v);
<add> }
<add> }
<add>
<add> return $this;
<add> }
<add>
<add> if (is_null($value)) {
<add> PHPUnit::assertTrue(
<add> $this->session()->getOldInput($key),
<add> "Session is missing expected key [{$key}]."
<add> );
<add> } elseif ($value instanceof Closure) {
<add> PHPUnit::assertTrue($value($this->session()->getOldInput($key)));
<add> } else {
<add> PHPUnit::assertEquals($value, $this->session()->getOldInput($key));
<add> }
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Assert that the session has the given errors.
<ide> * | 1 |
Go | Go | move imageservice to new package | 2b1a2b10afce6ba251d096cfdbd642fc436120ef | <ide><path>daemon/cluster/executor/backend.go
<ide> type Backend interface {
<ide> GetAttachmentStore() *networkSettings.AttachmentStore
<ide> }
<ide>
<add>// ImageBackend is used by an executor to perform image operations
<ide> type ImageBackend interface {
<ide> PullImage(ctx context.Context, image, tag, platform string, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error
<ide> GetRepository(context.Context, reference.Named, *types.AuthConfig) (distribution.Repository, bool, error)
<ide><path>daemon/container_operations_windows.go
<ide> func (daemon *Daemon) setupConfigDir(c *container.Container) (setupErr error) {
<ide> return nil
<ide> }
<ide>
<del>// getSize returns real size & virtual size
<del>func (daemon *Daemon) getSize(containerID string) (int64, int64) {
<del> // TODO Windows
<del> return 0, 0
<del>}
<del>
<ide> func (daemon *Daemon) setupIpcDirs(container *container.Container) error {
<ide> return nil
<ide> }
<ide><path>daemon/create.go
<ide> func (daemon *Daemon) create(params types.ContainerCreateConfig, managed bool) (
<ide> }
<ide>
<ide> // Set RWLayer for container after mount labels have been set
<del> rwLayer, err := daemon.imageService.GetRWLayer(container, setupInitLayer(daemon.idMappings))
<add> rwLayer, err := daemon.imageService.CreateLayer(container, setupInitLayer(daemon.idMappings))
<ide> if err != nil {
<ide> return nil, errdefs.System(err)
<ide> }
<ide><path>daemon/daemon.go
<ide> import (
<ide> "github.com/docker/docker/api/types"
<ide> containertypes "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/api/types/swarm"
<add> "github.com/docker/docker/builder"
<ide> "github.com/docker/docker/container"
<ide> "github.com/docker/docker/daemon/config"
<ide> "github.com/docker/docker/daemon/discovery"
<ide> "github.com/docker/docker/daemon/events"
<ide> "github.com/docker/docker/daemon/exec"
<add> "github.com/docker/docker/daemon/images"
<ide> "github.com/docker/docker/daemon/logger"
<ide> "github.com/docker/docker/daemon/network"
<ide> "github.com/docker/docker/errdefs"
<ide> "github.com/sirupsen/logrus"
<ide> // register graph drivers
<del> "github.com/docker/docker/builder"
<ide> _ "github.com/docker/docker/daemon/graphdriver/register"
<ide> "github.com/docker/docker/daemon/stats"
<ide> dmetadata "github.com/docker/docker/distribution/metadata"
<del> "github.com/docker/docker/distribution/xfer"
<ide> "github.com/docker/docker/dockerversion"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/layer"
<ide> type Daemon struct {
<ide> containers container.Store
<ide> containersReplica container.ViewDB
<ide> execCommands *exec.Store
<del>
<del> imageService *imageService
<del>
<del> idIndex *truncindex.TruncIndex
<del> configStore *config.Config
<del> statsCollector *stats.Collector
<del> defaultLogConfig containertypes.LogConfig
<del> RegistryService registry.Service
<del> EventsService *events.Events
<del> netController libnetwork.NetworkController
<del> volumes *store.VolumeStore
<del> discoveryWatcher discovery.Reloader
<del> root string
<del> seccompEnabled bool
<del> apparmorEnabled bool
<del> shutdown bool
<del> idMappings *idtools.IDMappings
<add> imageService *images.ImageService
<add> idIndex *truncindex.TruncIndex
<add> configStore *config.Config
<add> statsCollector *stats.Collector
<add> defaultLogConfig containertypes.LogConfig
<add> RegistryService registry.Service
<add> EventsService *events.Events
<add> netController libnetwork.NetworkController
<add> volumes *store.VolumeStore
<add> discoveryWatcher discovery.Reloader
<add> root string
<add> seccompEnabled bool
<add> apparmorEnabled bool
<add> shutdown bool
<add> idMappings *idtools.IDMappings
<ide> // TODO: move graphDrivers field to an InfoService
<ide> graphDrivers map[string]string // By operating system
<ide>
<ide> func (daemon *Daemon) restore() error {
<ide> // Ignore the container if it does not support the current driver being used by the graph
<ide> currentDriverForContainerOS := daemon.graphDrivers[container.OS]
<ide> if (container.Driver == "" && currentDriverForContainerOS == "aufs") || container.Driver == currentDriverForContainerOS {
<del> rwlayer, err := daemon.imageService.GetRWLayerByID(container.ID, container.OS)
<add> rwlayer, err := daemon.imageService.GetLayerByID(container.ID, container.OS)
<ide> if err != nil {
<ide> logrus.Errorf("Failed to load container mount %v: %v", id, err)
<ide> continue
<ide> func NewDaemon(config *config.Config, registryService registry.Service, containe
<ide> return nil, err
<ide> }
<ide>
<del> eventsService := events.New()
<del>
<ide> // We have a single tag/reference store for the daemon globally. However, it's
<ide> // stored under the graphdriver. On host platforms which only support a single
<ide> // container OS, but multiple selectable graphdrivers, this means depending on which
<ide> func NewDaemon(config *config.Config, registryService registry.Service, containe
<ide> d.idIndex = truncindex.NewTruncIndex([]string{})
<ide> d.statsCollector = d.newStatsCollector(1 * time.Second)
<ide>
<del> d.EventsService = eventsService
<add> d.EventsService = events.New()
<ide> d.volumes = volStore
<ide> d.root = config.Root
<ide> d.idMappings = idMappings
<ide> func NewDaemon(config *config.Config, registryService registry.Service, containe
<ide>
<ide> d.linkIndex = newLinkIndex()
<ide>
<del> logrus.Debugf("Max Concurrent Downloads: %d", *config.MaxConcurrentDownloads)
<del> logrus.Debugf("Max Concurrent Uploads: %d", *config.MaxConcurrentUploads)
<del> d.imageService = &imageService{
<del> trustKey: trustKey,
<del> uploadManager: xfer.NewLayerUploadManager(*config.MaxConcurrentUploads),
<del> downloadManager: xfer.NewLayerDownloadManager(layerStores, *config.MaxConcurrentDownloads),
<del> registryService: registryService,
<del> referenceStore: rs,
<del> distributionMetadataStore: distributionMetadataStore,
<del> imageStore: imageStore,
<del> eventsService: eventsService,
<del> containers: d.containers,
<del> }
<add> // TODO: imageStore, distributionMetadataStore, and ReferenceStore are only
<add> // used above to run migration. They could be initialized in ImageService
<add> // if migration is called from daemon/images. layerStore might move as well.
<add> d.imageService = images.NewImageService(images.ImageServiceConfig{
<add> ContainerStore: d.containers,
<add> DistributionMetadataStore: distributionMetadataStore,
<add> EventsService: d.EventsService,
<add> ImageStore: imageStore,
<add> LayerStores: layerStores,
<add> MaxConcurrentDownloads: *config.MaxConcurrentDownloads,
<add> MaxConcurrentUploads: *config.MaxConcurrentUploads,
<add> ReferenceStore: rs,
<add> RegistryService: registryService,
<add> TrustKey: trustKey,
<add> })
<ide>
<ide> go d.execCommandGC()
<ide>
<ide> func (daemon *Daemon) Shutdown() error {
<ide> logrus.Errorf("Stop container error: %v", err)
<ide> return
<ide> }
<del> if mountid, err := daemon.imageService.GetContainerMountID(c.ID, c.OS); err == nil {
<add> if mountid, err := daemon.imageService.GetLayerMountID(c.ID, c.OS); err == nil {
<ide> daemon.cleanupMountsByID(mountid)
<ide> }
<ide> logrus.Debugf("container stopped %s", c.ID)
<ide> func (daemon *Daemon) Shutdown() error {
<ide> }
<ide> }
<ide>
<del> daemon.imageService.Cleanup()
<add> if daemon.imageService != nil {
<add> daemon.imageService.Cleanup()
<add> }
<ide>
<ide> // If we are part of a cluster, clean up cluster's stuff
<ide> if daemon.clusterProvider != nil {
<ide> func (daemon *Daemon) IDMappings() *idtools.IDMappings {
<ide> return daemon.idMappings
<ide> }
<ide>
<del>func (daemon *Daemon) ImageService() *imageService {
<add>// ImageService returns the Daemon's ImageService
<add>func (daemon *Daemon) ImageService() *images.ImageService {
<ide> return daemon.imageService
<ide> }
<ide>
<del>// TODO: tmp hack to merge interfaces
<add>// BuilderBackend returns the backend used by builder
<ide> func (daemon *Daemon) BuilderBackend() builder.Backend {
<ide> return struct {
<ide> *Daemon
<del> *imageService
<add> *images.ImageService
<ide> }{daemon, daemon.imageService}
<ide> }
<ide><path>daemon/delete.go
<ide> func (daemon *Daemon) cleanupContainer(container *container.Container, forceRemo
<ide> // When container creation fails and `RWLayer` has not been created yet, we
<ide> // do not call `ReleaseRWLayer`
<ide> if container.RWLayer != nil {
<del> err := daemon.imageService.ReleaseContainerLayer(container.RWLayer, container.OS)
<add> err := daemon.imageService.ReleaseLayer(container.RWLayer, container.OS)
<ide> if err != nil {
<ide> err = errors.Wrapf(err, "container %s", container.ID)
<ide> container.SetRemovalError(err)
<ide><path>daemon/export.go
<ide> func (daemon *Daemon) containerExport(container *container.Container) (arch io.R
<ide> if !system.IsOSSupported(container.OS) {
<ide> return nil, fmt.Errorf("cannot export %s: %s ", container.ID, system.ErrNotSupportedOperatingSystem)
<ide> }
<del> rwlayer, err := daemon.imageService.GetRWLayerByID(container.ID, container.OS)
<add> rwlayer, err := daemon.imageService.GetLayerByID(container.ID, container.OS)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> defer func() {
<ide> if err != nil {
<del> daemon.imageService.ReleaseContainerLayer(rwlayer, container.OS)
<add> daemon.imageService.ReleaseLayer(rwlayer, container.OS)
<ide> }
<ide> }()
<ide>
<ide> func (daemon *Daemon) containerExport(container *container.Container) (arch io.R
<ide> arch = ioutils.NewReadCloserWrapper(archive, func() error {
<ide> err := archive.Close()
<ide> rwlayer.Unmount()
<del> daemon.imageService.ReleaseContainerLayer(rwlayer, container.OS)
<add> daemon.imageService.ReleaseLayer(rwlayer, container.OS)
<ide> return err
<ide> })
<ide> daemon.LogContainerEvent(container, "export")
<ide><path>daemon/image.go
<del>package daemon // import "github.com/docker/docker/daemon"
<del>
<del>import (
<del> "context"
<del> "fmt"
<del> "os"
<del>
<del> "github.com/docker/distribution/reference"
<del> "github.com/docker/docker/api/types/events"
<del> "github.com/docker/docker/container"
<del> daemonevents "github.com/docker/docker/daemon/events"
<del> "github.com/docker/docker/distribution/metadata"
<del> "github.com/docker/docker/distribution/xfer"
<del> "github.com/docker/docker/errdefs"
<del> "github.com/docker/docker/image"
<del> "github.com/docker/docker/layer"
<del> dockerreference "github.com/docker/docker/reference"
<del> "github.com/docker/docker/registry"
<del> "github.com/docker/libtrust"
<del> "github.com/opencontainers/go-digest"
<del> "github.com/pkg/errors"
<del> "github.com/sirupsen/logrus"
<del>)
<del>
<del>// errImageDoesNotExist is error returned when no image can be found for a reference.
<del>type errImageDoesNotExist struct {
<del> ref reference.Reference
<del>}
<del>
<del>func (e errImageDoesNotExist) Error() string {
<del> ref := e.ref
<del> if named, ok := ref.(reference.Named); ok {
<del> ref = reference.TagNameOnly(named)
<del> }
<del> return fmt.Sprintf("No such image: %s", reference.FamiliarString(ref))
<del>}
<del>
<del>func (e errImageDoesNotExist) NotFound() {}
<del>
<del>// GetImageIDAndOS returns an image ID and operating system corresponding to the image referred to by
<del>// refOrID.
<del>// called from list.go foldFilter()
<del>func (i imageService) GetImageIDAndOS(refOrID string) (image.ID, string, error) {
<del> ref, err := reference.ParseAnyReference(refOrID)
<del> if err != nil {
<del> return "", "", errdefs.InvalidParameter(err)
<del> }
<del> namedRef, ok := ref.(reference.Named)
<del> if !ok {
<del> digested, ok := ref.(reference.Digested)
<del> if !ok {
<del> return "", "", errImageDoesNotExist{ref}
<del> }
<del> id := image.IDFromDigest(digested.Digest())
<del> if img, err := i.imageStore.Get(id); err == nil {
<del> return id, img.OperatingSystem(), nil
<del> }
<del> return "", "", errImageDoesNotExist{ref}
<del> }
<del>
<del> if digest, err := i.referenceStore.Get(namedRef); err == nil {
<del> // Search the image stores to get the operating system, defaulting to host OS.
<del> id := image.IDFromDigest(digest)
<del> if img, err := i.imageStore.Get(id); err == nil {
<del> return id, img.OperatingSystem(), nil
<del> }
<del> }
<del>
<del> // Search based on ID
<del> if id, err := i.imageStore.Search(refOrID); err == nil {
<del> img, err := i.imageStore.Get(id)
<del> if err != nil {
<del> return "", "", errImageDoesNotExist{ref}
<del> }
<del> return id, img.OperatingSystem(), nil
<del> }
<del>
<del> return "", "", errImageDoesNotExist{ref}
<del>}
<del>
<del>// GetImage returns an image corresponding to the image referred to by refOrID.
<del>func (i *imageService) GetImage(refOrID string) (*image.Image, error) {
<del> imgID, _, err := i.GetImageIDAndOS(refOrID)
<del> if err != nil {
<del> return nil, err
<del> }
<del> return i.imageStore.Get(imgID)
<del>}
<del>
<del>type containerStore interface {
<del> // used by image delete
<del> First(container.StoreFilter) *container.Container
<del> // used by image prune, and image list
<del> List() []*container.Container
<del> // TODO: remove, only used for CommitBuildStep
<del> Get(string) *container.Container
<del>}
<del>
<del>type imageService struct {
<del> eventsService *daemonevents.Events
<del> containers containerStore
<del> downloadManager *xfer.LayerDownloadManager
<del> uploadManager *xfer.LayerUploadManager
<del>
<del> // TODO: should accept a trust service instead of a key
<del> trustKey libtrust.PrivateKey
<del>
<del> registryService registry.Service
<del> referenceStore dockerreference.Store
<del> distributionMetadataStore metadata.Store
<del> imageStore image.Store
<del> layerStores map[string]layer.Store // By operating system
<del>
<del> pruneRunning int32
<del>}
<del>
<del>// called from info.go
<del>func (i *imageService) CountImages() int {
<del> return len(i.imageStore.Map())
<del>}
<del>
<del>// called from list.go to filter containers
<del>func (i *imageService) Children(id image.ID) []image.ID {
<del> return i.imageStore.Children(id)
<del>}
<del>
<del>// TODO: accept an opt struct instead of container?
<del>// called from create.go
<del>func (i *imageService) GetRWLayer(container *container.Container, initFunc layer.MountInit) (layer.RWLayer, error) {
<del> var layerID layer.ChainID
<del> if container.ImageID != "" {
<del> img, err := i.imageStore.Get(container.ImageID)
<del> if err != nil {
<del> return nil, err
<del> }
<del> layerID = img.RootFS.ChainID()
<del> }
<del>
<del> rwLayerOpts := &layer.CreateRWLayerOpts{
<del> MountLabel: container.MountLabel,
<del> InitFunc: initFunc,
<del> StorageOpt: container.HostConfig.StorageOpt,
<del> }
<del>
<del> // Indexing by OS is safe here as validation of OS has already been performed in create() (the only
<del> // caller), and guaranteed non-nil
<del> return i.layerStores[container.OS].CreateRWLayer(container.ID, layerID, rwLayerOpts)
<del>}
<del>
<del>// called from daemon.go Daemon.restore(), and Daemon.containerExport()
<del>func (i *imageService) GetRWLayerByID(cid string, os string) (layer.RWLayer, error) {
<del> return i.layerStores[os].GetRWLayer(cid)
<del>}
<del>
<del>// called from info.go
<del>func (i *imageService) GraphDriverStatuses() map[string][][2]string {
<del> result := make(map[string][][2]string)
<del> for os, store := range i.layerStores {
<del> result[os] = store.DriverStatus()
<del> }
<del> return result
<del>}
<del>
<del>// called from daemon.go Daemon.Shutdown(), and Daemon.Cleanup() (cleanup is actually continerCleanup)
<del>func (i *imageService) GetContainerMountID(cid string, os string) (string, error) {
<del> return i.layerStores[os].GetMountID(cid)
<del>}
<del>
<del>// called from daemon.go Daemon.Shutdown()
<del>func (i *imageService) Cleanup() {
<del> for os, ls := range i.layerStores {
<del> if ls != nil {
<del> if err := ls.Cleanup(); err != nil {
<del> logrus.Errorf("Error during layer Store.Cleanup(): %v %s", err, os)
<del> }
<del> }
<del> }
<del>}
<del>
<del>// moved from Daemon.GraphDriverName, multiple calls
<del>func (i *imageService) GraphDriverForOS(os string) string {
<del> return i.layerStores[os].DriverName()
<del>}
<del>
<del>// called from delete.go Daemon.cleanupContainer(), and Daemon.containerExport()
<del>func (i *imageService) ReleaseContainerLayer(rwlayer layer.RWLayer, containerOS string) error {
<del> metadata, err := i.layerStores[containerOS].ReleaseRWLayer(rwlayer)
<del> layer.LogReleaseMetadata(metadata)
<del> if err != nil && err != layer.ErrMountDoesNotExist && !os.IsNotExist(errors.Cause(err)) {
<del> return errors.Wrapf(err, "driver %q failed to remove root filesystem",
<del> i.layerStores[containerOS].DriverName())
<del> }
<del> return nil
<del>}
<del>
<del>// called from disk_usage.go
<del>func (i *imageService) LayerDiskUsage(ctx context.Context) (int64, error) {
<del> var allLayersSize int64
<del> layerRefs := i.getLayerRefs()
<del> for _, ls := range i.layerStores {
<del> allLayers := ls.Map()
<del> for _, l := range allLayers {
<del> select {
<del> case <-ctx.Done():
<del> return allLayersSize, ctx.Err()
<del> default:
<del> size, err := l.DiffSize()
<del> if err == nil {
<del> if _, ok := layerRefs[l.ChainID()]; ok {
<del> allLayersSize += size
<del> } else {
<del> logrus.Warnf("found leaked image layer %v", l.ChainID())
<del> }
<del> } else {
<del> logrus.Warnf("failed to get diff size for layer %v", l.ChainID())
<del> }
<del> }
<del> }
<del> }
<del> return allLayersSize, nil
<del>}
<del>
<del>func (i *imageService) getLayerRefs() map[layer.ChainID]int {
<del> tmpImages := i.imageStore.Map()
<del> layerRefs := map[layer.ChainID]int{}
<del> for id, img := range tmpImages {
<del> dgst := digest.Digest(id)
<del> if len(i.referenceStore.References(dgst)) == 0 && len(i.imageStore.Children(id)) != 0 {
<del> continue
<del> }
<del>
<del> rootFS := *img.RootFS
<del> rootFS.DiffIDs = nil
<del> for _, id := range img.RootFS.DiffIDs {
<del> rootFS.Append(id)
<del> chid := rootFS.ChainID()
<del> layerRefs[chid]++
<del> }
<del> }
<del>
<del> return layerRefs
<del>}
<del>
<del>// LogImageEvent generates an event related to an image with only the default attributes.
<del>func (i *imageService) LogImageEvent(imageID, refName, action string) {
<del> i.LogImageEventWithAttributes(imageID, refName, action, map[string]string{})
<del>}
<del>
<del>// LogImageEventWithAttributes generates an event related to an image with specific given attributes.
<del>func (i *imageService) LogImageEventWithAttributes(imageID, refName, action string, attributes map[string]string) {
<del> img, err := i.GetImage(imageID)
<del> if err == nil && img.Config != nil {
<del> // image has not been removed yet.
<del> // it could be missing if the event is `delete`.
<del> copyAttributes(attributes, img.Config.Labels)
<del> }
<del> if refName != "" {
<del> attributes["name"] = refName
<del> }
<del> actor := events.Actor{
<del> ID: imageID,
<del> Attributes: attributes,
<del> }
<del>
<del> i.eventsService.Log(action, events.ImageEventType, actor)
<del>}
<ide><path>daemon/image_events.go
<del>package daemon // import "github.com/docker/docker/daemon"
<del>
<del>import (
<del> "github.com/docker/docker/api/types/events"
<del>)
<del>
<del>// LogImageEvent generates an event related to an image with only the default attributes.
<del>func (daemon *Daemon) LogImageEvent(imageID, refName, action string) {
<del> daemon.LogImageEventWithAttributes(imageID, refName, action, map[string]string{})
<del>}
<del>
<del>// LogImageEventWithAttributes generates an event related to an image with specific given attributes.
<del>func (daemon *Daemon) LogImageEventWithAttributes(imageID, refName, action string, attributes map[string]string) {
<del> img, err := daemon.GetImage(imageID)
<del> if err == nil && img.Config != nil {
<del> // image has not been removed yet.
<del> // it could be missing if the event is `delete`.
<del> copyAttributes(attributes, img.Config.Labels)
<del> }
<del> if refName != "" {
<del> attributes["name"] = refName
<del> }
<del> actor := events.Actor{
<del> ID: imageID,
<del> Attributes: attributes,
<del> }
<del>
<del> daemon.EventsService.Log(action, events.ImageEventType, actor)
<del>}
<add><path>daemon/images/cache.go
<del><path>daemon/cache.go
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "github.com/docker/docker/builder"
<ide> import (
<ide> )
<ide>
<ide> // MakeImageCache creates a stateful image cache.
<del>func (i *imageService) MakeImageCache(sourceRefs []string) builder.ImageCache {
<add>func (i *ImageService) MakeImageCache(sourceRefs []string) builder.ImageCache {
<ide> if len(sourceRefs) == 0 {
<ide> return cache.NewLocal(i.imageStore)
<ide> }
<ide><path>daemon/images/image.go
<add>package images // import "github.com/docker/docker/daemon/images"
<add>
<add>import (
<add> "fmt"
<add>
<add> "github.com/docker/distribution/reference"
<add> "github.com/docker/docker/errdefs"
<add> "github.com/docker/docker/image"
<add>)
<add>
<add>// ErrImageDoesNotExist is error returned when no image can be found for a reference.
<add>type ErrImageDoesNotExist struct {
<add> ref reference.Reference
<add>}
<add>
<add>func (e ErrImageDoesNotExist) Error() string {
<add> ref := e.ref
<add> if named, ok := ref.(reference.Named); ok {
<add> ref = reference.TagNameOnly(named)
<add> }
<add> return fmt.Sprintf("No such image: %s", reference.FamiliarString(ref))
<add>}
<add>
<add>// NotFound implements the NotFound interface
<add>func (e ErrImageDoesNotExist) NotFound() {}
<add>
<add>// GetImageIDAndOS returns an image ID and operating system corresponding to the image referred to by
<add>// refOrID.
<add>// called from list.go foldFilter()
<add>func (i ImageService) GetImageIDAndOS(refOrID string) (image.ID, string, error) {
<add> ref, err := reference.ParseAnyReference(refOrID)
<add> if err != nil {
<add> return "", "", errdefs.InvalidParameter(err)
<add> }
<add> namedRef, ok := ref.(reference.Named)
<add> if !ok {
<add> digested, ok := ref.(reference.Digested)
<add> if !ok {
<add> return "", "", ErrImageDoesNotExist{ref}
<add> }
<add> id := image.IDFromDigest(digested.Digest())
<add> if img, err := i.imageStore.Get(id); err == nil {
<add> return id, img.OperatingSystem(), nil
<add> }
<add> return "", "", ErrImageDoesNotExist{ref}
<add> }
<add>
<add> if digest, err := i.referenceStore.Get(namedRef); err == nil {
<add> // Search the image stores to get the operating system, defaulting to host OS.
<add> id := image.IDFromDigest(digest)
<add> if img, err := i.imageStore.Get(id); err == nil {
<add> return id, img.OperatingSystem(), nil
<add> }
<add> }
<add>
<add> // Search based on ID
<add> if id, err := i.imageStore.Search(refOrID); err == nil {
<add> img, err := i.imageStore.Get(id)
<add> if err != nil {
<add> return "", "", ErrImageDoesNotExist{ref}
<add> }
<add> return id, img.OperatingSystem(), nil
<add> }
<add>
<add> return "", "", ErrImageDoesNotExist{ref}
<add>}
<add>
<add>// GetImage returns an image corresponding to the image referred to by refOrID.
<add>func (i *ImageService) GetImage(refOrID string) (*image.Image, error) {
<add> imgID, _, err := i.GetImageIDAndOS(refOrID)
<add> if err != nil {
<add> return nil, err
<add> }
<add> return i.imageStore.Get(imgID)
<add>}
<add><path>daemon/images/image_builder.go
<del><path>daemon/image_builder.go
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "io"
<ide> import (
<ide> "github.com/docker/docker/api/types/backend"
<ide> "github.com/docker/docker/builder"
<ide> "github.com/docker/docker/image"
<del> "github.com/docker/docker/image/cache"
<ide> "github.com/docker/docker/layer"
<ide> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/stringid"
<ide> func newROLayerForImage(img *image.Image, layerStore layer.Store) (builder.ROLay
<ide> }
<ide>
<ide> // TODO: could this use the regular daemon PullImage ?
<del>func (i *imageService) pullForBuilder(ctx context.Context, name string, authConfigs map[string]types.AuthConfig, output io.Writer, os string) (*image.Image, error) {
<add>func (i *ImageService) pullForBuilder(ctx context.Context, name string, authConfigs map[string]types.AuthConfig, output io.Writer, os string) (*image.Image, error) {
<ide> ref, err := reference.ParseNormalizedNamed(name)
<ide> if err != nil {
<ide> return nil, err
<ide> func (i *imageService) pullForBuilder(ctx context.Context, name string, authConf
<ide> // GetImageAndReleasableLayer returns an image and releaseable layer for a reference or ID.
<ide> // Every call to GetImageAndReleasableLayer MUST call releasableLayer.Release() to prevent
<ide> // leaking of layers.
<del>func (i *imageService) GetImageAndReleasableLayer(ctx context.Context, refOrID string, opts backend.GetImageAndLayerOptions) (builder.Image, builder.ROLayer, error) {
<add>func (i *ImageService) GetImageAndReleasableLayer(ctx context.Context, refOrID string, opts backend.GetImageAndLayerOptions) (builder.Image, builder.ROLayer, error) {
<ide> if refOrID == "" {
<ide> if !system.IsOSSupported(opts.OS) {
<ide> return nil, nil, system.ErrNotSupportedOperatingSystem
<ide> func (i *imageService) GetImageAndReleasableLayer(ctx context.Context, refOrID s
<ide> // CreateImage creates a new image by adding a config and ID to the image store.
<ide> // This is similar to LoadImage() except that it receives JSON encoded bytes of
<ide> // an image instead of a tar archive.
<del>func (i *imageService) CreateImage(config []byte, parent string) (builder.Image, error) {
<add>func (i *ImageService) CreateImage(config []byte, parent string) (builder.Image, error) {
<ide> id, err := i.imageStore.Create(config)
<ide> if err != nil {
<ide> return nil, errors.Wrapf(err, "failed to create image")
<add><path>daemon/images/image_commit.go
<del><path>daemon/image_commit.go
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "encoding/json"
<ide> import (
<ide> )
<ide>
<ide> // CommitImage creates a new image from a commit config
<del>func (i *imageService) CommitImage(c backend.CommitConfig) (image.ID, error) {
<add>func (i *ImageService) CommitImage(c backend.CommitConfig) (image.ID, error) {
<ide> layerStore, ok := i.layerStores[c.ContainerOS]
<ide> if !ok {
<ide> return "", system.ErrNotSupportedOperatingSystem
<ide> func exportContainerRw(layerStore layer.Store, id, mountLabel string) (arch io.R
<ide> // * it doesn't log a container commit event
<ide> //
<ide> // This is a temporary shim. Should be removed when builder stops using commit.
<del>func (i *imageService) CommitBuildStep(c backend.CommitConfig) (image.ID, error) {
<add>func (i *ImageService) CommitBuildStep(c backend.CommitConfig) (image.ID, error) {
<ide> container := i.containers.Get(c.ContainerID)
<ide> if container == nil {
<ide> // TODO: use typed error
<add><path>daemon/images/image_delete.go
<del><path>daemon/image_delete.go
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "fmt"
<ide> const (
<ide> // meaning any delete conflicts will cause the image to not be deleted and the
<ide> // conflict will not be reported.
<ide> //
<del>func (i *imageService) ImageDelete(imageRef string, force, prune bool) ([]types.ImageDeleteResponseItem, error) {
<add>func (i *ImageService) ImageDelete(imageRef string, force, prune bool) ([]types.ImageDeleteResponseItem, error) {
<ide> start := time.Now()
<ide> records := []types.ImageDeleteResponseItem{}
<ide>
<ide> func isImageIDPrefix(imageID, possiblePrefix string) bool {
<ide> // repositoryRef must not be an image ID but a repository name followed by an
<ide> // optional tag or digest reference. If tag or digest is omitted, the default
<ide> // tag is used. Returns the resolved image reference and an error.
<del>func (i *imageService) removeImageRef(ref reference.Named) (reference.Named, error) {
<add>func (i *ImageService) removeImageRef(ref reference.Named) (reference.Named, error) {
<ide> ref = reference.TagNameOnly(ref)
<ide>
<ide> // Ignore the boolean value returned, as far as we're concerned, this
<ide> func (i *imageService) removeImageRef(ref reference.Named) (reference.Named, err
<ide> // on the first encountered error. Removed references are logged to this
<ide> // daemon's event service. An "Untagged" types.ImageDeleteResponseItem is added to the
<ide> // given list of records.
<del>func (i *imageService) removeAllReferencesToImageID(imgID image.ID, records *[]types.ImageDeleteResponseItem) error {
<add>func (i *ImageService) removeAllReferencesToImageID(imgID image.ID, records *[]types.ImageDeleteResponseItem) error {
<ide> imageRefs := i.referenceStore.References(imgID.Digest())
<ide>
<ide> for _, imageRef := range imageRefs {
<ide> func (idc *imageDeleteConflict) Conflict() {}
<ide> // conflict is encountered, it will be returned immediately without deleting
<ide> // the image. If quiet is true, any encountered conflicts will be ignored and
<ide> // the function will return nil immediately without deleting the image.
<del>func (i *imageService) imageDeleteHelper(imgID image.ID, records *[]types.ImageDeleteResponseItem, force, prune, quiet bool) error {
<add>func (i *ImageService) imageDeleteHelper(imgID image.ID, records *[]types.ImageDeleteResponseItem, force, prune, quiet bool) error {
<ide> // First, determine if this image has any conflicts. Ignore soft conflicts
<ide> // if force is true.
<ide> c := conflictHard
<ide> func (i *imageService) imageDeleteHelper(imgID image.ID, records *[]types.ImageD
<ide> // using the image. A soft conflict is any tags/digest referencing the given
<ide> // image or any stopped container using the image. If ignoreSoftConflicts is
<ide> // true, this function will not check for soft conflict conditions.
<del>func (i *imageService) checkImageDeleteConflict(imgID image.ID, mask conflictType) *imageDeleteConflict {
<add>func (i *ImageService) checkImageDeleteConflict(imgID image.ID, mask conflictType) *imageDeleteConflict {
<ide> // Check if the image has any descendant images.
<ide> if mask&conflictDependentChild != 0 && len(i.imageStore.Children(imgID)) > 0 {
<ide> return &imageDeleteConflict{
<ide> func (i *imageService) checkImageDeleteConflict(imgID image.ID, mask conflictTyp
<ide> // imageIsDangling returns whether the given image is "dangling" which means
<ide> // that there are no repository references to the given image and it has no
<ide> // child images.
<del>func (i *imageService) imageIsDangling(imgID image.ID) bool {
<add>func (i *ImageService) imageIsDangling(imgID image.ID) bool {
<ide> return !(len(i.referenceStore.References(imgID.Digest())) > 0 || len(i.imageStore.Children(imgID)) > 0)
<ide> }
<ide><path>daemon/images/image_events.go
<add>package images // import "github.com/docker/docker/daemon/images"
<add>
<add>import (
<add> "github.com/docker/docker/api/types/events"
<add>)
<add>
<add>// LogImageEvent generates an event related to an image with only the default attributes.
<add>func (i *ImageService) LogImageEvent(imageID, refName, action string) {
<add> i.LogImageEventWithAttributes(imageID, refName, action, map[string]string{})
<add>}
<add>
<add>// LogImageEventWithAttributes generates an event related to an image with specific given attributes.
<add>func (i *ImageService) LogImageEventWithAttributes(imageID, refName, action string, attributes map[string]string) {
<add> img, err := i.GetImage(imageID)
<add> if err == nil && img.Config != nil {
<add> // image has not been removed yet.
<add> // it could be missing if the event is `delete`.
<add> copyAttributes(attributes, img.Config.Labels)
<add> }
<add> if refName != "" {
<add> attributes["name"] = refName
<add> }
<add> actor := events.Actor{
<add> ID: imageID,
<add> Attributes: attributes,
<add> }
<add>
<add> i.eventsService.Log(action, events.ImageEventType, actor)
<add>}
<add>
<add>// copyAttributes guarantees that labels are not mutated by event triggers.
<add>func copyAttributes(attributes, labels map[string]string) {
<add> if labels == nil {
<add> return
<add> }
<add> for k, v := range labels {
<add> attributes[k] = v
<add> }
<add>}
<add><path>daemon/images/image_exporter.go
<del><path>daemon/image_exporter.go
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "io"
<ide> import (
<ide> // stream. All images with the given tag and all versions containing
<ide> // the same tag are exported. names is the set of tags to export, and
<ide> // outStream is the writer which the images are written to.
<del>func (i *imageService) ExportImage(names []string, outStream io.Writer) error {
<add>func (i *ImageService) ExportImage(names []string, outStream io.Writer) error {
<ide> imageExporter := tarexport.NewTarExporter(i.imageStore, i.layerStores, i.referenceStore, i)
<ide> return imageExporter.Save(names, outStream)
<ide> }
<ide>
<ide> // LoadImage uploads a set of images into the repository. This is the
<ide> // complement of ImageExport. The input stream is an uncompressed tar
<ide> // ball containing images and metadata.
<del>func (i *imageService) LoadImage(inTar io.ReadCloser, outStream io.Writer, quiet bool) error {
<add>func (i *ImageService) LoadImage(inTar io.ReadCloser, outStream io.Writer, quiet bool) error {
<ide> imageExporter := tarexport.NewTarExporter(i.imageStore, i.layerStores, i.referenceStore, i)
<ide> return imageExporter.Load(inTar, outStream, quiet)
<ide> }
<add><path>daemon/images/image_history.go
<del><path>daemon/image_history.go
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "fmt"
<ide> import (
<ide>
<ide> // ImageHistory returns a slice of ImageHistory structures for the specified image
<ide> // name by walking the image lineage.
<del>func (i *imageService) ImageHistory(name string) ([]*image.HistoryResponseItem, error) {
<add>func (i *ImageService) ImageHistory(name string) ([]*image.HistoryResponseItem, error) {
<ide> start := time.Now()
<ide> img, err := i.GetImage(name)
<ide> if err != nil {
<add><path>daemon/images/image_import.go
<del><path>daemon/image_import.go
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "encoding/json"
<ide> import (
<ide> // inConfig (if src is "-"), or from a URI specified in src. Progress output is
<ide> // written to outStream. Repository and tag names can optionally be given in
<ide> // the repo and tag arguments, respectively.
<del>func (i *imageService) ImportImage(src string, repository, os string, tag string, msg string, inConfig io.ReadCloser, outStream io.Writer, changes []string) error {
<add>func (i *ImageService) ImportImage(src string, repository, os string, tag string, msg string, inConfig io.ReadCloser, outStream io.Writer, changes []string) error {
<ide> var (
<ide> rc io.ReadCloser
<ide> resp *http.Response
<add><path>daemon/images/image_inspect.go
<del><path>daemon/image_inspect.go
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "time"
<ide> import (
<ide>
<ide> // LookupImage looks up an image by name and returns it as an ImageInspect
<ide> // structure.
<del>func (i *imageService) LookupImage(name string) (*types.ImageInspect, error) {
<add>func (i *ImageService) LookupImage(name string) (*types.ImageInspect, error) {
<ide> img, err := i.GetImage(name)
<ide> if err != nil {
<ide> return nil, errors.Wrapf(err, "no such image: %s", name)
<ide> func (i *imageService) LookupImage(name string) (*types.ImageInspect, error) {
<ide> },
<ide> }
<ide>
<del> imageInspect.GraphDriver.Name = i.GraphDriverForOS(img.OperatingSystem())
<add> imageInspect.GraphDriver.Name = i.layerStores[img.OperatingSystem()].DriverName()
<ide> imageInspect.GraphDriver.Data = layerMetadata
<ide>
<ide> return imageInspect, nil
<add><path>daemon/images/image_prune.go
<del><path>daemon/image_prune.go
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<add> "fmt"
<ide> "sync/atomic"
<add> "time"
<ide>
<ide> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/filters"
<add> timetypes "github.com/docker/docker/api/types/time"
<ide> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/layer"
<ide> var imagesAcceptedFilters = map[string]bool{
<ide> "until": true,
<ide> }
<ide>
<add>// errPruneRunning is returned when a prune request is received while
<add>// one is in progress
<add>var errPruneRunning = fmt.Errorf("a prune operation is already running")
<add>
<ide> // ImagesPrune removes unused images
<del>func (i *imageService) ImagesPrune(ctx context.Context, pruneFilters filters.Args) (*types.ImagesPruneReport, error) {
<add>func (i *ImageService) ImagesPrune(ctx context.Context, pruneFilters filters.Args) (*types.ImagesPruneReport, error) {
<ide> if !atomic.CompareAndSwapInt32(&i.pruneRunning, 0, 1) {
<ide> return nil, errPruneRunning
<ide> }
<ide> deleteImagesLoop:
<ide> }
<ide>
<ide> deletedImages := []types.ImageDeleteResponseItem{}
<del> refs := i.referenceStore.References(dgst)
<add> refs := i.referenceStore.References(id.Digest())
<ide> if len(refs) > 0 {
<ide> shouldDelete := !danglingOnly
<ide> if !shouldDelete {
<ide> func imageDeleteFailed(ref string, err error) bool {
<ide> return true
<ide> }
<ide> }
<add>
<add>func matchLabels(pruneFilters filters.Args, labels map[string]string) bool {
<add> if !pruneFilters.MatchKVList("label", labels) {
<add> return false
<add> }
<add> // By default MatchKVList will return true if field (like 'label!') does not exist
<add> // So we have to add additional Contains("label!") check
<add> if pruneFilters.Contains("label!") {
<add> if pruneFilters.MatchKVList("label!", labels) {
<add> return false
<add> }
<add> }
<add> return true
<add>}
<add>
<add>func getUntilFromPruneFilters(pruneFilters filters.Args) (time.Time, error) {
<add> until := time.Time{}
<add> if !pruneFilters.Contains("until") {
<add> return until, nil
<add> }
<add> untilFilters := pruneFilters.Get("until")
<add> if len(untilFilters) > 1 {
<add> return until, fmt.Errorf("more than one until filter specified")
<add> }
<add> ts, err := timetypes.GetTimestamp(untilFilters[0], time.Now())
<add> if err != nil {
<add> return until, err
<add> }
<add> seconds, nanoseconds, err := timetypes.ParseTimestamps(ts, 0)
<add> if err != nil {
<add> return until, err
<add> }
<add> until = time.Unix(seconds, nanoseconds)
<add> return until, nil
<add>}
<add><path>daemon/images/image_pull.go
<del><path>daemon/image_pull.go
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "io"
<ide> import (
<ide>
<ide> // PullImage initiates a pull operation. image is the repository name to pull, and
<ide> // tag may be either empty, or indicate a specific tag to pull.
<del>func (i *imageService) PullImage(ctx context.Context, image, tag, os string, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error {
<add>func (i *ImageService) PullImage(ctx context.Context, image, tag, os string, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error {
<ide> // Special case: "pull -a" may send an image name with a
<ide> // trailing :. This is ugly, but let's not break API
<ide> // compatibility.
<ide> func (i *imageService) PullImage(ctx context.Context, image, tag, os string, met
<ide> return i.pullImageWithReference(ctx, ref, os, metaHeaders, authConfig, outStream)
<ide> }
<ide>
<del>func (i *imageService) pullImageWithReference(ctx context.Context, ref reference.Named, os string, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error {
<add>func (i *ImageService) pullImageWithReference(ctx context.Context, ref reference.Named, os string, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error {
<ide> // Include a buffer so that slow client connections don't affect
<ide> // transfer performance.
<ide> progressChan := make(chan progress.Progress, 100)
<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, bool, error) {
<ide> // get repository info
<ide> repoInfo, err := i.registryService.ResolveRepository(ref)
<ide> if err != nil {
<add><path>daemon/images/image_push.go
<del><path>daemon/image_push.go
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "io"
<ide> import (
<ide> )
<ide>
<ide> // PushImage initiates a push operation on the repository named localName.
<del>func (i *imageService) PushImage(ctx context.Context, image, tag string, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error {
<add>func (i *ImageService) PushImage(ctx context.Context, image, tag string, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error {
<ide> ref, err := reference.ParseNormalizedNamed(image)
<ide> if err != nil {
<ide> return err
<add><path>daemon/images/image_search.go
<del><path>daemon/image_search.go
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "strconv"
<ide> var acceptedSearchFilterTags = map[string]bool{
<ide> //
<ide> // TODO: this could be implemented in a registry service instead of the image
<ide> // service.
<del>func (i *imageService) SearchRegistryForImages(ctx context.Context, filtersArgs string, term string, limit int,
<add>func (i *ImageService) SearchRegistryForImages(ctx context.Context, filtersArgs string, term string, limit int,
<ide> authConfig *types.AuthConfig,
<ide> headers map[string][]string) (*registrytypes.SearchResults, error) {
<ide>
<add><path>daemon/images/image_search_test.go
<del><path>daemon/search_test.go
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "errors"
<ide> func TestSearchRegistryForImagesErrors(t *testing.T) {
<ide> },
<ide> }
<ide> for index, e := range errorCases {
<del> daemon := &Daemon{
<del> RegistryService: &FakeService{
<add> daemon := &ImageService{
<add> registryService: &FakeService{
<ide> shouldReturnError: e.shouldReturnError,
<ide> },
<ide> }
<ide> func TestSearchRegistryForImages(t *testing.T) {
<ide> },
<ide> }
<ide> for index, s := range successCases {
<del> daemon := &Daemon{
<del> RegistryService: &FakeService{
<add> daemon := &ImageService{
<add> registryService: &FakeService{
<ide> term: term,
<ide> results: s.registryResults,
<ide> },
<add><path>daemon/images/image_tag.go
<del><path>daemon/image_tag.go
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "github.com/docker/distribution/reference"
<ide> import (
<ide>
<ide> // TagImage creates the tag specified by newTag, pointing to the image named
<ide> // imageName (alternatively, imageName can also be an image ID).
<del>func (i *imageService) TagImage(imageName, repository, tag string) (string, error) {
<add>func (i *ImageService) TagImage(imageName, repository, tag string) (string, error) {
<ide> imageID, _, err := i.GetImageIDAndOS(imageName)
<ide> if err != nil {
<ide> return "", err
<ide> func (i *imageService) TagImage(imageName, repository, tag string) (string, erro
<ide> }
<ide>
<ide> // TagImageWithReference adds the given reference to the image ID provided.
<del>func (i *imageService) TagImageWithReference(imageID image.ID, newTag reference.Named) error {
<add>func (i *ImageService) TagImageWithReference(imageID image.ID, newTag reference.Named) error {
<ide> if err := i.referenceStore.AddTag(newTag, imageID.Digest(), true); err != nil {
<ide> return err
<ide> }
<add><path>daemon/images/image_unix.go
<del><path>daemon/image_getsize_unix.go
<ide> // +build linux freebsd
<ide>
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "runtime"
<ide>
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide>
<del>// getSize returns the real size & virtual size of the container.
<del>func (i *imageService) GetContainerLayerSize(containerID string) (int64, int64) {
<add>// GetContainerLayerSize returns the real size & virtual size of the container.
<add>func (i *ImageService) GetContainerLayerSize(containerID string) (int64, int64) {
<ide> var (
<ide> sizeRw, sizeRootfs int64
<ide> err error
<add><path>daemon/images/image_windows.go
<del><path>daemon/image_windows.go
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images
<ide>
<ide> import (
<ide> "github.com/docker/docker/image"
<ide> import (
<ide> "github.com/pkg/errors"
<ide> )
<ide>
<add>// GetContainerLayerSize returns real size & virtual size
<add>func (i *ImageService) GetContainerLayerSize(containerID string) (int64, int64) {
<add> // TODO Windows
<add> return 0, 0
<add>}
<add>
<ide> // GetLayerFolders returns the layer folders from an image RootFS
<del>func (daemon *Daemon) GetLayerFolders(img *image.Image, rwLayer layer.RWLayer) ([]string, error) {
<add>func (i *ImageService) GetLayerFolders(img *image.Image, rwLayer layer.RWLayer) ([]string, error) {
<ide> folders := []string{}
<ide> max := len(img.RootFS.DiffIDs)
<ide> for index := 1; index <= max; index++ {
<ide> func (daemon *Daemon) GetLayerFolders(img *image.Image, rwLayer layer.RWLayer) (
<ide> if !system.IsOSSupported(img.OperatingSystem()) {
<ide> return nil, errors.Wrapf(system.ErrNotSupportedOperatingSystem, "cannot get layerpath for ImageID %s", img.RootFS.ChainID())
<ide> }
<del> layerPath, err := layer.GetLayerPath(daemon.layerStores[img.OperatingSystem()], img.RootFS.ChainID())
<add> layerPath, err := layer.GetLayerPath(i.layerStores[img.OperatingSystem()], img.RootFS.ChainID())
<ide> if err != nil {
<del> return nil, errors.Wrapf(err, "failed to get layer path from graphdriver %s for ImageID %s", daemon.layerStores[img.OperatingSystem()], img.RootFS.ChainID())
<add> return nil, errors.Wrapf(err, "failed to get layer path from graphdriver %s for ImageID %s", i.layerStores[img.OperatingSystem()], img.RootFS.ChainID())
<ide> }
<ide> // Reverse order, expecting parent first
<ide> folders = append([]string{layerPath}, folders...)
<add><path>daemon/images/images.go
<del><path>daemon/images.go
<del>package daemon // import "github.com/docker/docker/daemon"
<add>package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "encoding/json"
<ide> func (r byCreated) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
<ide> func (r byCreated) Less(i, j int) bool { return r[i].Created < r[j].Created }
<ide>
<ide> // Map returns a map of all images in the ImageStore
<del>func (i *imageService) Map() map[image.ID]*image.Image {
<add>func (i *ImageService) Map() map[image.ID]*image.Image {
<ide> return i.imageStore.Map()
<ide> }
<ide>
<ide> func (i *imageService) Map() map[image.ID]*image.Image {
<ide> // filter is a shell glob string applied to repository names. The argument
<ide> // named all controls whether all images in the graph are filtered, or just
<ide> // the heads.
<del>func (i *imageService) Images(imageFilters filters.Args, all bool, withExtraAttrs bool) ([]*types.ImageSummary, error) {
<add>func (i *ImageService) Images(imageFilters filters.Args, all bool, withExtraAttrs bool) ([]*types.ImageSummary, error) {
<ide> var (
<ide> allImages map[image.ID]*image.Image
<ide> err error
<ide> func (i *imageService) Images(imageFilters filters.Args, all bool, withExtraAttr
<ide> // This new image contains only the layers from it's parent + 1 extra layer which contains the diff of all the layers in between.
<ide> // The existing image(s) is not destroyed.
<ide> // If no parent is specified, a new image with the diff of all the specified image's layers merged into a new layer that has no parents.
<del>func (i *imageService) SquashImage(id, parent string) (string, error) {
<add>func (i *ImageService) SquashImage(id, parent string) (string, error) {
<ide>
<ide> var (
<ide> img *image.Image
<ide><path>daemon/images/locals.go
<add>package images // import "github.com/docker/docker/daemon/images"
<add>
<add>import (
<add> "fmt"
<add>
<add> metrics "github.com/docker/go-metrics"
<add>)
<add>
<add>type invalidFilter struct {
<add> filter string
<add> value interface{}
<add>}
<add>
<add>func (e invalidFilter) Error() string {
<add> msg := "Invalid filter '" + e.filter
<add> if e.value != nil {
<add> msg += fmt.Sprintf("=%s", e.value)
<add> }
<add> return msg + "'"
<add>}
<add>
<add>func (e invalidFilter) InvalidParameter() {}
<add>
<add>var imageActions metrics.LabeledTimer
<add>
<add>func init() {
<add> ns := metrics.NewNamespace("engine", "daemon", nil)
<add> imageActions = ns.NewLabeledTimer("image_actions", "The number of seconds it takes to process each image action", "action")
<add> // TODO: is it OK to register a namespace with the same name? Or does this
<add> // need to be exported from somewhere?
<add> metrics.Register(ns)
<add>}
<ide><path>daemon/images/service.go
<add>package images // import "github.com/docker/docker/daemon/images"
<add>
<add>import (
<add> "context"
<add> "os"
<add>
<add> "github.com/docker/docker/container"
<add> daemonevents "github.com/docker/docker/daemon/events"
<add> "github.com/docker/docker/distribution/metadata"
<add> "github.com/docker/docker/distribution/xfer"
<add> "github.com/docker/docker/image"
<add> "github.com/docker/docker/layer"
<add> dockerreference "github.com/docker/docker/reference"
<add> "github.com/docker/docker/registry"
<add> "github.com/docker/libtrust"
<add> "github.com/opencontainers/go-digest"
<add> "github.com/pkg/errors"
<add> "github.com/sirupsen/logrus"
<add>)
<add>
<add>type containerStore interface {
<add> // used by image delete
<add> First(container.StoreFilter) *container.Container
<add> // used by image prune, and image list
<add> List() []*container.Container
<add> // TODO: remove, only used for CommitBuildStep
<add> Get(string) *container.Container
<add>}
<add>
<add>// ImageServiceConfig is the configuration used to create a new ImageService
<add>type ImageServiceConfig struct {
<add> ContainerStore containerStore
<add> DistributionMetadataStore metadata.Store
<add> EventsService *daemonevents.Events
<add> ImageStore image.Store
<add> LayerStores map[string]layer.Store
<add> MaxConcurrentDownloads int
<add> MaxConcurrentUploads int
<add> ReferenceStore dockerreference.Store
<add> RegistryService registry.Service
<add> TrustKey libtrust.PrivateKey
<add>}
<add>
<add>// NewImageService returns a new ImageService from a configuration
<add>func NewImageService(config ImageServiceConfig) *ImageService {
<add> logrus.Debugf("Max Concurrent Downloads: %d", config.MaxConcurrentDownloads)
<add> logrus.Debugf("Max Concurrent Uploads: %d", config.MaxConcurrentUploads)
<add> return &ImageService{
<add> containers: config.ContainerStore,
<add> distributionMetadataStore: config.DistributionMetadataStore,
<add> downloadManager: xfer.NewLayerDownloadManager(config.LayerStores, config.MaxConcurrentDownloads),
<add> eventsService: config.EventsService,
<add> imageStore: config.ImageStore,
<add> layerStores: config.LayerStores,
<add> referenceStore: config.ReferenceStore,
<add> registryService: config.RegistryService,
<add> trustKey: config.TrustKey,
<add> uploadManager: xfer.NewLayerUploadManager(config.MaxConcurrentUploads),
<add> }
<add>}
<add>
<add>// ImageService provides a backend for image management
<add>type ImageService struct {
<add> containers containerStore
<add> distributionMetadataStore metadata.Store
<add> downloadManager *xfer.LayerDownloadManager
<add> eventsService *daemonevents.Events
<add> imageStore image.Store
<add> layerStores map[string]layer.Store // By operating system
<add> pruneRunning int32
<add> referenceStore dockerreference.Store
<add> registryService registry.Service
<add> trustKey libtrust.PrivateKey
<add> uploadManager *xfer.LayerUploadManager
<add>}
<add>
<add>// CountImages returns the number of images stored by ImageService
<add>// called from info.go
<add>func (i *ImageService) CountImages() int {
<add> return len(i.imageStore.Map())
<add>}
<add>
<add>// Children returns the children image.IDs for a parent image.
<add>// called from list.go to filter containers
<add>// TODO: refactor to expose an ancestry for image.ID?
<add>func (i *ImageService) Children(id image.ID) []image.ID {
<add> return i.imageStore.Children(id)
<add>}
<add>
<add>// CreateLayer creates a filesystem layer for a container.
<add>// called from create.go
<add>// TODO: accept an opt struct instead of container?
<add>func (i *ImageService) CreateLayer(container *container.Container, initFunc layer.MountInit) (layer.RWLayer, error) {
<add> var layerID layer.ChainID
<add> if container.ImageID != "" {
<add> img, err := i.imageStore.Get(container.ImageID)
<add> if err != nil {
<add> return nil, err
<add> }
<add> layerID = img.RootFS.ChainID()
<add> }
<add>
<add> rwLayerOpts := &layer.CreateRWLayerOpts{
<add> MountLabel: container.MountLabel,
<add> InitFunc: initFunc,
<add> StorageOpt: container.HostConfig.StorageOpt,
<add> }
<add>
<add> // Indexing by OS is safe here as validation of OS has already been performed in create() (the only
<add> // caller), and guaranteed non-nil
<add> return i.layerStores[container.OS].CreateRWLayer(container.ID, layerID, rwLayerOpts)
<add>}
<add>
<add>// GetLayerByID returns a layer by ID and operating system
<add>// called from daemon.go Daemon.restore(), and Daemon.containerExport()
<add>func (i *ImageService) GetLayerByID(cid string, os string) (layer.RWLayer, error) {
<add> return i.layerStores[os].GetRWLayer(cid)
<add>}
<add>
<add>// LayerStoreStatus returns the status for each layer store
<add>// called from info.go
<add>func (i *ImageService) LayerStoreStatus() map[string][][2]string {
<add> result := make(map[string][][2]string)
<add> for os, store := range i.layerStores {
<add> result[os] = store.DriverStatus()
<add> }
<add> return result
<add>}
<add>
<add>// GetLayerMountID returns the mount ID for a layer
<add>// called from daemon.go Daemon.Shutdown(), and Daemon.Cleanup() (cleanup is actually continerCleanup)
<add>// TODO: needs to be refactored to Unmount (see callers), or removed and replaced
<add>// with GetLayerByID
<add>func (i *ImageService) GetLayerMountID(cid string, os string) (string, error) {
<add> return i.layerStores[os].GetMountID(cid)
<add>}
<add>
<add>// Cleanup resources before the process is shutdown.
<add>// called from daemon.go Daemon.Shutdown()
<add>func (i *ImageService) Cleanup() {
<add> for os, ls := range i.layerStores {
<add> if ls != nil {
<add> if err := ls.Cleanup(); err != nil {
<add> logrus.Errorf("Error during layer Store.Cleanup(): %v %s", err, os)
<add> }
<add> }
<add> }
<add>}
<add>
<add>// GraphDriverForOS returns the name of the graph drvier
<add>// moved from Daemon.GraphDriverName, used by:
<add>// - newContainer
<add>// - to report an error in Daemon.Mount(container)
<add>func (i *ImageService) GraphDriverForOS(os string) string {
<add> return i.layerStores[os].DriverName()
<add>}
<add>
<add>// ReleaseLayer releases a layer allowing it to be removed
<add>// called from delete.go Daemon.cleanupContainer(), and Daemon.containerExport()
<add>func (i *ImageService) ReleaseLayer(rwlayer layer.RWLayer, containerOS string) error {
<add> metadata, err := i.layerStores[containerOS].ReleaseRWLayer(rwlayer)
<add> layer.LogReleaseMetadata(metadata)
<add> if err != nil && err != layer.ErrMountDoesNotExist && !os.IsNotExist(errors.Cause(err)) {
<add> return errors.Wrapf(err, "driver %q failed to remove root filesystem",
<add> i.layerStores[containerOS].DriverName())
<add> }
<add> return nil
<add>}
<add>
<add>// LayerDiskUsage returns the number of bytes used by layer stores
<add>// called from disk_usage.go
<add>func (i *ImageService) LayerDiskUsage(ctx context.Context) (int64, error) {
<add> var allLayersSize int64
<add> layerRefs := i.getLayerRefs()
<add> for _, ls := range i.layerStores {
<add> allLayers := ls.Map()
<add> for _, l := range allLayers {
<add> select {
<add> case <-ctx.Done():
<add> return allLayersSize, ctx.Err()
<add> default:
<add> size, err := l.DiffSize()
<add> if err == nil {
<add> if _, ok := layerRefs[l.ChainID()]; ok {
<add> allLayersSize += size
<add> } else {
<add> logrus.Warnf("found leaked image layer %v", l.ChainID())
<add> }
<add> } else {
<add> logrus.Warnf("failed to get diff size for layer %v", l.ChainID())
<add> }
<add> }
<add> }
<add> }
<add> return allLayersSize, nil
<add>}
<add>
<add>func (i *ImageService) getLayerRefs() map[layer.ChainID]int {
<add> tmpImages := i.imageStore.Map()
<add> layerRefs := map[layer.ChainID]int{}
<add> for id, img := range tmpImages {
<add> dgst := digest.Digest(id)
<add> if len(i.referenceStore.References(dgst)) == 0 && len(i.imageStore.Children(id)) != 0 {
<add> continue
<add> }
<add>
<add> rootFS := *img.RootFS
<add> rootFS.DiffIDs = nil
<add> for _, id := range img.RootFS.DiffIDs {
<add> rootFS.Append(id)
<add> chid := rootFS.ChainID()
<add> layerRefs[chid]++
<add> }
<add> }
<add>
<add> return layerRefs
<add>}
<add>
<add>// UpdateConfig values
<add>//
<add>// called from reload.go
<add>func (i *ImageService) UpdateConfig(maxDownloads, maxUploads *int) {
<add> if i.downloadManager != nil && maxDownloads != nil {
<add> i.downloadManager.SetConcurrency(*maxDownloads)
<add> }
<add> if i.uploadManager != nil && maxUploads != nil {
<add> i.uploadManager.SetConcurrency(*maxUploads)
<add> }
<add>}
<ide><path>daemon/info.go
<ide> func (daemon *Daemon) SystemInfo() (*types.Info, error) {
<ide>
<ide> var ds [][2]string
<ide> drivers := ""
<del> statuses := daemon.imageService.GraphDriverStatuses()
<add> statuses := daemon.imageService.LayerStoreStatus()
<ide> for os, gd := range daemon.graphDrivers {
<ide> ds = append(ds, statuses[os]...)
<ide> drivers += gd
<ide><path>daemon/list.go
<ide> import (
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/filters"
<ide> "github.com/docker/docker/container"
<add> "github.com/docker/docker/daemon/images"
<ide> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/volume"
<ide> func (daemon *Daemon) refreshImage(s *container.Snapshot, ctx *listContext) (*ty
<ide> image := s.Image // keep the original ref if still valid (hasn't changed)
<ide> if image != s.ImageID {
<ide> id, _, err := daemon.imageService.GetImageIDAndOS(image)
<del> if _, isDNE := err.(errImageDoesNotExist); err != nil && !isDNE {
<add> if _, isDNE := err.(images.ErrImageDoesNotExist); err != nil && !isDNE {
<ide> return nil, err
<ide> }
<ide> if err != nil || id.String() != s.ImageID {
<ide><path>daemon/metrics.go
<ide> const metricsPluginType = "MetricsCollector"
<ide>
<ide> var (
<ide> containerActions metrics.LabeledTimer
<del> imageActions metrics.LabeledTimer
<ide> networkActions metrics.LabeledTimer
<ide> engineInfo metrics.LabeledGauge
<ide> engineCpus metrics.Gauge
<ide> func init() {
<ide> engineMemory = ns.NewGauge("engine_memory", "The number of bytes of memory that the host system of the engine has", metrics.Bytes)
<ide> healthChecksCounter = ns.NewCounter("health_checks", "The total number of health checks")
<ide> healthChecksFailedCounter = ns.NewCounter("health_checks_failed", "The total number of failed health checks")
<del> imageActions = ns.NewLabeledTimer("image_actions", "The number of seconds it takes to process each image action", "action")
<ide>
<ide> stateCtr = newStateCounter(ns.NewDesc("container_states", "The count of containers in various states", metrics.Unit("containers"), "state"))
<ide> ns.Add(stateCtr)
<ide><path>daemon/oci_windows.go
<ide> func (daemon *Daemon) createSpec(c *container.Container) (*specs.Spec, error) {
<ide> }
<ide> }
<ide> s.Process.User.Username = c.Config.User
<del> s.Windows.LayerFolders, err = daemon.GetLayerFolders(img, c.RWLayer)
<add> s.Windows.LayerFolders, err = daemon.imageService.GetLayerFolders(img, c.RWLayer)
<ide> if err != nil {
<ide> return nil, errors.Wrapf(err, "container %s", c.ID)
<ide> }
<ide><path>daemon/reload.go
<ide> func (daemon *Daemon) reloadMaxConcurrentDownloadsAndUploads(conf *config.Config
<ide> daemon.configStore.MaxConcurrentDownloads = &maxConcurrentDownloads
<ide> }
<ide> logrus.Debugf("Reset Max Concurrent Downloads: %d", *daemon.configStore.MaxConcurrentDownloads)
<del> if daemon.imageService.downloadManager != nil {
<del> daemon.imageService.downloadManager.SetConcurrency(*daemon.configStore.MaxConcurrentDownloads)
<del> }
<del>
<del> // prepare reload event attributes with updatable configurations
<del> attributes["max-concurrent-downloads"] = fmt.Sprintf("%d", *daemon.configStore.MaxConcurrentDownloads)
<ide>
<ide> // If no value is set for max-concurrent-upload we assume it is the default value
<ide> // We always "reset" as the cost is lightweight and easy to maintain.
<ide> func (daemon *Daemon) reloadMaxConcurrentDownloadsAndUploads(conf *config.Config
<ide> daemon.configStore.MaxConcurrentUploads = &maxConcurrentUploads
<ide> }
<ide> logrus.Debugf("Reset Max Concurrent Uploads: %d", *daemon.configStore.MaxConcurrentUploads)
<del> if daemon.imageService.uploadManager != nil {
<del> daemon.imageService.uploadManager.SetConcurrency(*daemon.configStore.MaxConcurrentUploads)
<del> }
<ide>
<add> daemon.imageService.UpdateConfig(conf.MaxConcurrentDownloads, conf.MaxConcurrentUploads)
<add> // prepare reload event attributes with updatable configurations
<add> attributes["max-concurrent-downloads"] = fmt.Sprintf("%d", *daemon.configStore.MaxConcurrentDownloads)
<ide> // prepare reload event attributes with updatable configurations
<ide> attributes["max-concurrent-uploads"] = fmt.Sprintf("%d", *daemon.configStore.MaxConcurrentUploads)
<ide> }
<ide><path>daemon/reload_test.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/daemon/config"
<add> "github.com/docker/docker/daemon/images"
<ide> "github.com/docker/docker/pkg/discovery"
<ide> _ "github.com/docker/docker/pkg/discovery/memory"
<ide> "github.com/docker/docker/registry"
<ide> func TestDaemonReloadLabels(t *testing.T) {
<ide> Labels: []string{"foo:bar"},
<ide> },
<ide> },
<del> imageService: &imageService{},
<add> imageService: images.NewImageService(images.ImageServiceConfig{}),
<ide> }
<ide>
<ide> valuesSets := make(map[string]interface{})
<ide> func TestDaemonReloadLabels(t *testing.T) {
<ide> func TestDaemonReloadAllowNondistributableArtifacts(t *testing.T) {
<ide> daemon := &Daemon{
<ide> configStore: &config.Config{},
<del> imageService: &imageService{},
<add> imageService: images.NewImageService(images.ImageServiceConfig{}),
<ide> }
<ide>
<ide> var err error
<ide> func TestDaemonReloadAllowNondistributableArtifacts(t *testing.T) {
<ide>
<ide> func TestDaemonReloadMirrors(t *testing.T) {
<ide> daemon := &Daemon{
<del> imageService: &imageService{},
<add> imageService: images.NewImageService(images.ImageServiceConfig{}),
<ide> }
<ide> var err error
<ide> daemon.RegistryService, err = registry.NewService(registry.ServiceOptions{
<ide> func TestDaemonReloadMirrors(t *testing.T) {
<ide>
<ide> func TestDaemonReloadInsecureRegistries(t *testing.T) {
<ide> daemon := &Daemon{
<del> imageService: &imageService{},
<add> imageService: images.NewImageService(images.ImageServiceConfig{}),
<ide> }
<ide> var err error
<ide> // initialize daemon with existing insecure registries: "127.0.0.0/8", "10.10.1.11:5000", "10.10.1.22:5000"
<ide> func TestDaemonReloadInsecureRegistries(t *testing.T) {
<ide>
<ide> func TestDaemonReloadNotAffectOthers(t *testing.T) {
<ide> daemon := &Daemon{
<del> imageService: &imageService{},
<add> imageService: images.NewImageService(images.ImageServiceConfig{}),
<ide> }
<ide> daemon.configStore = &config.Config{
<ide> CommonConfig: config.CommonConfig{
<ide> func TestDaemonReloadNotAffectOthers(t *testing.T) {
<ide>
<ide> func TestDaemonDiscoveryReload(t *testing.T) {
<ide> daemon := &Daemon{
<del> imageService: &imageService{},
<add> imageService: images.NewImageService(images.ImageServiceConfig{}),
<ide> }
<ide> daemon.configStore = &config.Config{
<ide> CommonConfig: config.CommonConfig{
<ide> func TestDaemonDiscoveryReload(t *testing.T) {
<ide>
<ide> func TestDaemonDiscoveryReloadFromEmptyDiscovery(t *testing.T) {
<ide> daemon := &Daemon{
<del> imageService: &imageService{},
<add> imageService: images.NewImageService(images.ImageServiceConfig{}),
<ide> }
<ide> daemon.configStore = &config.Config{}
<ide>
<ide> func TestDaemonDiscoveryReloadFromEmptyDiscovery(t *testing.T) {
<ide>
<ide> func TestDaemonDiscoveryReloadOnlyClusterAdvertise(t *testing.T) {
<ide> daemon := &Daemon{
<del> imageService: &imageService{},
<add> imageService: images.NewImageService(images.ImageServiceConfig{}),
<ide> }
<ide> daemon.configStore = &config.Config{
<ide> CommonConfig: config.CommonConfig{
<ide> func TestDaemonDiscoveryReloadOnlyClusterAdvertise(t *testing.T) {
<ide>
<ide> func TestDaemonReloadNetworkDiagnosticPort(t *testing.T) {
<ide> daemon := &Daemon{
<del> imageService: &imageService{},
<add> imageService: images.NewImageService(images.ImageServiceConfig{}),
<ide> }
<ide> daemon.configStore = &config.Config{}
<ide>
<ide><path>daemon/start.go
<ide> func (daemon *Daemon) Cleanup(container *container.Container) {
<ide> if err := daemon.conditionalUnmountOnCleanup(container); err != nil {
<ide> // FIXME: remove once reference counting for graphdrivers has been refactored
<ide> // Ensure that all the mounts are gone
<del> if mountid, err := daemon.imageService.GetContainerMountID(container.ID, container.OS); err == nil {
<add> if mountid, err := daemon.imageService.GetLayerMountID(container.ID, container.OS); err == nil {
<ide> daemon.cleanupMountsByID(mountid)
<ide> }
<ide> } | 36 |
PHP | PHP | remove obsolete statement | 86147568a4c8be0fa7643fca7fc70a585e371e05 | <ide><path>src/Http/Cookie/CookieInterface.php
<ide> public function getExpiry();
<ide> /**
<ide> * Get the timestamp from the expiration time
<ide> *
<del> * Timestamps are integer as large timestamps can overflow MAX_INT
<del> * in 32bit systems.
<del> *
<ide> * @return int|null The expiry time as a string timestamp.
<ide> */
<ide> public function getExpiresTimestamp(): ?int; | 1 |
PHP | PHP | add addhttpcookie to verifycsrftoken | 76af90b50ca98c9fcafb0f33552ee5c7a9f8ff58 | <ide><path>app/Http/Middleware/VerifyCsrfToken.php
<ide> class VerifyCsrfToken extends Middleware
<ide> protected $except = [
<ide> //
<ide> ];
<add>
<add> /**
<add> * Indicates whether the XSRF-TOKEN cookie should be set on the response.
<add> *
<add> * @var bool
<add> */
<add> protected $addHttpCookie = true;
<ide> } | 1 |
Javascript | Javascript | increase test timeout | 086a4c17803d0efe288f127844c305166f634a1f | <ide><path>test/Stats.test.js
<ide> describe("Stats", () => {
<ide> actual.should.be.eql(expected);
<ide> done();
<ide> });
<del> });
<add> }, 10000);
<ide> });
<ide> describe("Error Handling", () => {
<ide> describe("does have", () => { | 1 |
Javascript | Javascript | remove comment about missing android support | eef56de3763258739977ec2b3148c9b364953869 | <ide><path>Libraries/CameraRoll/CameraRoll.js
<ide> var ASSET_TYPE_OPTIONS = [
<ide> 'Photos', // default
<ide> ];
<ide>
<del>
<ide> // Flow treats Object and Array as disjoint types, currently.
<ide> deepFreezeAndThrowOnMutationInDev((GROUP_TYPES_OPTIONS: any));
<ide> deepFreezeAndThrowOnMutationInDev((ASSET_TYPE_OPTIONS: any));
<ide> class CameraRoll {
<ide> /**
<ide> * Saves the image to the camera roll / gallery.
<ide> *
<del> * The CameraRoll API is not yet implemented for Android.
<del> *
<ide> * @param {string} tag On Android, this is a local URI, such
<ide> * as `"file:///sdcard/img.png"`.
<ide> * | 1 |
Javascript | Javascript | fix broken example tabs | 666137d6359c9474c9912fc81ebc4d8f478cc1b5 | <ide><path>docs/app/assets/js/angular-bootstrap/bootstrap.js
<ide> directive.runnableExample = ['$templateCache', '$document', function($templateCa
<ide>
<ide> return {
<ide> restrict: 'C',
<add> scope : true,
<ide> controller : ['$scope', function($scope) {
<ide> $scope.setTab = function(index) {
<ide> var tab = $scope.tabs[index];
<ide> directive.runnableExample = ['$templateCache', '$document', function($templateCa
<ide> compile : function(element) {
<ide> element.html(tpl + element.html());
<ide> return function(scope, element) {
<add> var node = element[0];
<add> var examples = node.querySelectorAll(exampleClassNameSelector);
<ide> var tabs = [], now = Date.now();
<del> angular.forEach(doc.querySelectorAll(exampleClassNameSelector),
<del> function(child, index) {
<del>
<add> angular.forEach(examples, function(child, index) {
<ide> tabs.push(child.getAttribute('name'));
<ide> });
<ide>
<ide> if(tabs.length > 0) {
<ide> scope.tabs = tabs;
<ide> scope.$on('tabChange', function(e, index, title) {
<del> var elements = doc.querySelectorAll(exampleClassNameSelector);
<del> angular.forEach(elements, function(child) {
<add> angular.forEach(examples, function(child) {
<ide> child.style.display = 'none';
<ide> });
<del> var selected = elements[index];
<add> var selected = examples[index];
<ide> selected.style.display = 'block';
<ide> });
<ide> scope.setTab(0); | 1 |
Ruby | Ruby | use tap with block parameter | 02902e00ab9fc67812accf72d61847c65cd25615 | <ide><path>railties/lib/rails/info.rb
<ide> def to_s
<ide> alias inspect to_s
<ide>
<ide> def to_html
<del> (table = '<table>').tap do
<add> '<table>'.tap do |table|
<ide> properties.each do |(name, value)|
<ide> table << %(<tr><td class="name">#{CGI.escapeHTML(name.to_s)}</td>)
<ide> formatted_value = if value.kind_of?(Array) | 1 |
Java | Java | remove setjsentrypoint from reactrootview | de09fd53bd41716142364e769e72b363bb3d3405 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java
<ide> private void attachRootViewToInstance(
<ide> UIManager uiManagerModule = UIManagerHelper.getUIManager(mCurrentReactContext, rootView.getUIManagerType());
<ide> final int rootTag = uiManagerModule.addRootView(rootView);
<ide> rootView.setRootViewTag(rootTag);
<del> rootView.invokeJSEntryPoint();
<add> rootView.runApplication();
<ide> Systrace.beginAsyncSection(
<ide> TRACE_TAG_REACT_JAVA_BRIDGE,
<ide> "pre_rootView.onAttachedToReactInstance",
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java
<ide>
<ide> package com.facebook.react;
<ide>
<del>import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE;
<del>import static com.facebook.react.uimanager.common.UIManagerType.FABRIC;
<ide> import static com.facebook.react.uimanager.common.UIManagerType.DEFAULT;
<add>import static com.facebook.react.uimanager.common.UIManagerType.FABRIC;
<add>import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE;
<ide>
<ide> import android.content.Context;
<ide> import android.graphics.Canvas;
<ide> import com.facebook.react.uimanager.UIManagerModule;
<ide> import com.facebook.react.uimanager.common.MeasureSpecProvider;
<ide> import com.facebook.react.uimanager.common.SizeMonitoringFrameLayout;
<add>import com.facebook.react.uimanager.common.UIManagerType;
<ide> import com.facebook.react.uimanager.events.EventDispatcher;
<ide> import com.facebook.systrace.Systrace;
<del>import com.facebook.react.uimanager.common.UIManagerType;
<ide> import javax.annotation.Nullable;
<ide>
<ide> /**
<ide> public interface ReactRootViewEventListener {
<ide> private boolean mWasMeasured = false;
<ide> private int mWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
<ide> private int mHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
<del> private @Nullable Runnable mJSEntryPoint;
<ide> private @UIManagerType int mUIManagerType = DEFAULT;
<ide>
<ide> public ReactRootView(Context context) {
<ide> public void setAppProperties(@Nullable Bundle appProperties) {
<ide> UiThreadUtil.assertOnUiThread();
<ide> mAppProperties = appProperties;
<ide> if (getRootViewTag() != 0) {
<del> invokeJSEntryPoint();
<add> runApplication();
<ide> }
<ide> }
<ide>
<ide> /**
<ide> * Calls into JS to start the React application. Can be called multiple times with the
<ide> * same rootTag, which will re-render the application from the root.
<ide> */
<del> /*package */ void invokeJSEntryPoint() {
<del> if (mJSEntryPoint == null) {
<del> defaultJSEntryPoint();
<del> } else {
<del> mJSEntryPoint.run();
<del> }
<del> }
<del>
<del> /**
<del> * Set a custom entry point for invoking JS. By default, this is AppRegistry.runApplication
<del> * @param jsEntryPoint
<del> */
<del> public void setJSEntryPoint(Runnable jsEntryPoint) {
<del> mJSEntryPoint = jsEntryPoint;
<del> }
<del>
<del> public void invokeDefaultJSEntryPoint(@Nullable Bundle appProperties) {
<del> UiThreadUtil.assertOnUiThread();
<del> if (appProperties != null) {
<del> mAppProperties = appProperties;
<del> }
<del> defaultJSEntryPoint();
<del> }
<del>
<del> /**
<del> * Calls the default entry point into JS which is AppRegistry.runApplication()
<del> */
<del> private void defaultJSEntryPoint() {
<add> /* package */ void runApplication() {
<ide> Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactRootView.runApplication");
<ide> try {
<ide> if (mReactInstanceManager == null || !mIsAttachedToInstance) { | 2 |
Text | Text | use offsetheight to get height value | 316d56ba11a95cb16982d9a86382f8d00ea5e099 | <ide><path>curriculum/challenges/english/01-responsive-web-design/applied-visual-design/adjust-the-height-of-an-element-using-the-height-property.english.md
<ide> Add a <code>height</code> property to the <code>h4</code> tag and set it to 25px
<ide> ```yml
<ide> tests:
<ide> - text: Your code should change the <code>h4</code> <code>height</code> property to a value of 25 pixels.
<del> testString: assert($('h4').css('height') === '25px' && /h4{\S*height:25px(;\S*}|})/.test($('style').text().replace(/\s/g ,'')));
<add> testString: assert(document.querySelector('h4').offsetHeight === 25 && /h4{\S*height:25px(;\S*}|})/.test($('style').text().replace(/\s/g ,'')));
<ide>
<ide> ```
<ide> | 1 |
Javascript | Javascript | show first component stack in context warning | 57333ca33a0619ff2334e4eb19139b4c7e9830f7 | <ide><path>packages/react-reconciler/src/ReactStrictModeWarnings.js
<ide> if (__DEV__) {
<ide> ReactStrictModeWarnings.flushLegacyContextWarning = () => {
<ide> ((pendingLegacyContextWarning: any): FiberToFiberComponentsMap).forEach(
<ide> (fiberArray: FiberArray, strictRoot) => {
<add> if (fiberArray.length === 0) {
<add> return;
<add> }
<add> const firstFiber = fiberArray[0];
<add>
<ide> const uniqueNames = new Set();
<ide> fiberArray.forEach(fiber => {
<ide> uniqueNames.add(getComponentName(fiber.type) || 'Component');
<ide> didWarnAboutLegacyContext.add(fiber.type);
<ide> });
<ide>
<ide> const sortedNames = setToSortedString(uniqueNames);
<del> const strictRootComponentStack = getStackByFiberInDevAndProd(
<del> strictRoot,
<del> );
<add> const firstComponentStack = getStackByFiberInDevAndProd(firstFiber);
<ide>
<ide> console.error(
<ide> 'Legacy context API has been detected within a strict-mode tree.' +
<ide> if (__DEV__) {
<ide> '\n\nLearn more about this warning here: https://fb.me/react-legacy-context' +
<ide> '%s',
<ide> sortedNames,
<del> strictRootComponentStack,
<add> firstComponentStack,
<ide> );
<ide> },
<ide> );
<ide><path>packages/react-reconciler/src/__tests__/ReactIncremental-test.internal.js
<ide> describe('ReactIncremental', () => {
<ide> 'The old API will be supported in all 16.x releases, but applications ' +
<ide> 'using it should migrate to the new version.\n\n' +
<ide> 'Please update the following components: Intl, ShowBoth, ShowLocale',
<del> {withoutStack: true},
<ide> );
<ide>
<ide> ReactNoop.render(
<ide> describe('ReactIncremental', () => {
<ide> 'The old API will be supported in all 16.x releases, but applications ' +
<ide> 'using it should migrate to the new version.\n\n' +
<ide> 'Please update the following components: Router, ShowRoute',
<del> {withoutStack: true},
<ide> );
<ide> });
<ide>
<ide> describe('ReactIncremental', () => {
<ide> }
<ide>
<ide> ReactNoop.render(<Recurse />);
<del> expect(() =>
<del> expect(Scheduler).toFlushWithoutYielding(),
<del> ).toErrorDev(
<add> expect(() => expect(Scheduler).toFlushWithoutYielding()).toErrorDev(
<ide> 'Legacy context API has been detected within a strict-mode tree.\n\n' +
<ide> 'The old API will be supported in all 16.x releases, but applications ' +
<ide> 'using it should migrate to the new version.\n\n' +
<ide> 'Please update the following components: Recurse',
<del> {withoutStack: true},
<ide> );
<ide> expect(ops).toEqual([
<ide> 'Recurse {}',
<ide> describe('ReactIncremental', () => {
<ide> };
<ide>
<ide> ReactNoop.render(<Recurse />);
<del> expect(() => expect(Scheduler).toFlushWithoutYielding()).toErrorDev(
<del> [
<del> 'Warning: The <Recurse /> component appears to be a function component that returns a class instance. ' +
<del> 'Change Recurse to a class that extends React.Component instead. ' +
<del> "If you can't use a class try assigning the prototype on the function as a workaround. " +
<del> '`Recurse.prototype = React.Component.prototype`. ' +
<del> "Don't use an arrow function since it cannot be called with `new` by React.",
<del> 'Legacy context API has been detected within a strict-mode tree.\n\n' +
<del> 'The old API will be supported in all 16.x releases, but applications ' +
<del> 'using it should migrate to the new version.\n\n' +
<del> 'Please update the following components: Recurse',
<del> ],
<del> {withoutStack: 1},
<del> );
<add> expect(() => expect(Scheduler).toFlushWithoutYielding()).toErrorDev([
<add> 'Warning: The <Recurse /> component appears to be a function component that returns a class instance. ' +
<add> 'Change Recurse to a class that extends React.Component instead. ' +
<add> "If you can't use a class try assigning the prototype on the function as a workaround. " +
<add> '`Recurse.prototype = React.Component.prototype`. ' +
<add> "Don't use an arrow function since it cannot be called with `new` by React.",
<add> 'Legacy context API has been detected within a strict-mode tree.\n\n' +
<add> 'The old API will be supported in all 16.x releases, but applications ' +
<add> 'using it should migrate to the new version.\n\n' +
<add> 'Please update the following components: Recurse',
<add> ]);
<ide> expect(ops).toEqual([
<ide> 'Recurse {}',
<ide> 'Recurse {"n":2}',
<ide> describe('ReactIncremental', () => {
<ide> 'The old API will be supported in all 16.x releases, but applications ' +
<ide> 'using it should migrate to the new version.\n\n' +
<ide> 'Please update the following components: Intl, ShowLocale',
<del> {withoutStack: true},
<ide> );
<ide> });
<ide>
<ide> describe('ReactIncremental', () => {
<ide> </IndirectionFn>
<ide> </Intl>,
<ide> );
<del> expect(() =>
<del> expect(Scheduler).toFlushWithoutYielding(),
<del> ).toErrorDev(
<add> expect(() => expect(Scheduler).toFlushWithoutYielding()).toErrorDev(
<ide> 'Legacy context API has been detected within a strict-mode tree.\n\n' +
<ide> 'The old API will be supported in all 16.x releases, but applications ' +
<ide> 'using it should migrate to the new version.\n\n' +
<ide> 'Please update the following components: Intl, ShowLocaleClass, ShowLocaleFn',
<del> {withoutStack: true},
<ide> );
<ide> expect(ops).toEqual([
<ide> 'Intl:read {}',
<ide> describe('ReactIncremental', () => {
<ide> </IndirectionFn>
<ide> </Stateful>,
<ide> );
<del> expect(() =>
<del> expect(Scheduler).toFlushWithoutYielding(),
<del> ).toErrorDev(
<add> expect(() => expect(Scheduler).toFlushWithoutYielding()).toErrorDev(
<ide> 'Legacy context API has been detected within a strict-mode tree.\n\n' +
<ide> 'The old API will be supported in all 16.x releases, but applications ' +
<ide> 'using it should migrate to the new version.\n\n' +
<ide> 'Please update the following components: Intl, ShowLocaleClass, ShowLocaleFn',
<del> {withoutStack: true},
<ide> );
<ide> expect(ops).toEqual([
<ide> 'Intl:read {}',
<ide> describe('ReactIncremental', () => {
<ide>
<ide> // Init
<ide> ReactNoop.render(<Root />);
<del> expect(() =>
<del> expect(Scheduler).toFlushWithoutYielding(),
<del> ).toErrorDev(
<add> expect(() => expect(Scheduler).toFlushWithoutYielding()).toErrorDev(
<ide> 'Legacy context API has been detected within a strict-mode tree.\n\n' +
<ide> 'The old API will be supported in all 16.x releases, but applications ' +
<ide> 'using it should migrate to the new version.\n\n' +
<ide> 'Please update the following components: Child',
<del> {withoutStack: true},
<ide> );
<ide>
<ide> // Trigger an update in the middle of the tree
<ide> describe('ReactIncremental', () => {
<ide>
<ide> // Init
<ide> ReactNoop.render(<Root />);
<del> expect(() =>
<del> expect(Scheduler).toFlushWithoutYielding(),
<del> ).toErrorDev(
<add> expect(() => expect(Scheduler).toFlushWithoutYielding()).toErrorDev(
<ide> 'Legacy context API has been detected within a strict-mode tree.\n\n' +
<ide> 'The old API will be supported in all 16.x releases, but applications ' +
<ide> 'using it should migrate to the new version.\n\n' +
<ide> 'Please update the following components: ContextProvider',
<del> {withoutStack: true},
<ide> );
<ide>
<ide> // Trigger an update in the middle of the tree
<ide> describe('ReactIncremental', () => {
<ide> 'using it should migrate to the new version.\n\n' +
<ide> 'Please update the following components: MyComponent',
<ide> ],
<del> {withoutStack: true},
<add> {withoutStack: 1},
<ide> );
<ide>
<ide> expect(ops).toEqual([
<ide> describe('ReactIncremental', () => {
<ide> </TopContextProvider>,
<ide> );
<ide>
<del> expect(() =>
<del> expect(Scheduler).toFlushWithoutYielding(),
<del> ).toErrorDev(
<add> expect(() => expect(Scheduler).toFlushWithoutYielding()).toErrorDev(
<ide> 'Legacy context API has been detected within a strict-mode tree.\n\n' +
<ide> 'The old API will be supported in all 16.x releases, but applications ' +
<ide> 'using it should migrate to the new version.\n\n' +
<ide> 'Please update the following components: Child, TopContextProvider',
<del> {withoutStack: true},
<ide> );
<ide> expect(rendered).toEqual(['count:0']);
<ide> instance.updateCount();
<ide> describe('ReactIncremental', () => {
<ide> </TopContextProvider>,
<ide> );
<ide>
<del> expect(() =>
<del> expect(Scheduler).toFlushWithoutYielding(),
<del> ).toErrorDev(
<add> expect(() => expect(Scheduler).toFlushWithoutYielding()).toErrorDev(
<ide> 'Legacy context API has been detected within a strict-mode tree.\n\n' +
<ide> 'The old API will be supported in all 16.x releases, but applications ' +
<ide> 'using it should migrate to the new version.\n\n' +
<ide> 'Please update the following components: Child, MiddleContextProvider, TopContextProvider',
<del> {withoutStack: true},
<ide> );
<ide> expect(rendered).toEqual(['count:0']);
<ide> instance.updateCount();
<ide> describe('ReactIncremental', () => {
<ide> </TopContextProvider>,
<ide> );
<ide>
<del> expect(() =>
<del> expect(Scheduler).toFlushWithoutYielding(),
<del> ).toErrorDev(
<add> expect(() => expect(Scheduler).toFlushWithoutYielding()).toErrorDev(
<ide> 'Legacy context API has been detected within a strict-mode tree.\n\n' +
<ide> 'The old API will be supported in all 16.x releases, but applications ' +
<ide> 'using it should migrate to the new version.\n\n' +
<ide> 'Please update the following components: Child, MiddleContextProvider, TopContextProvider',
<del> {withoutStack: true},
<ide> );
<ide> expect(rendered).toEqual(['count:0']);
<ide> instance.updateCount();
<ide> describe('ReactIncremental', () => {
<ide> </TopContextProvider>,
<ide> );
<ide>
<del> expect(() =>
<del> expect(Scheduler).toFlushWithoutYielding(),
<del> ).toErrorDev(
<add> expect(() => expect(Scheduler).toFlushWithoutYielding()).toErrorDev(
<ide> 'Legacy context API has been detected within a strict-mode tree.\n\n' +
<ide> 'The old API will be supported in all 16.x releases, but applications ' +
<ide> 'using it should migrate to the new version.\n\n' +
<ide> 'Please update the following components: Child, MiddleContextProvider, TopContextProvider',
<del> {withoutStack: true},
<ide> );
<ide> expect(rendered).toEqual(['count:0, name:brian']);
<ide> topInstance.updateCount();
<ide> describe('ReactIncremental', () => {
<ide> ReactNoop.render(<Boundary />);
<ide> expect(() => {
<ide> expect(Scheduler).toFlushWithoutYielding();
<del> }).toErrorDev(
<del> ['Legacy context API has been detected within a strict-mode tree'],
<del> {withoutStack: true},
<del> );
<add> }).toErrorDev([
<add> 'Legacy context API has been detected within a strict-mode tree',
<add> ]);
<ide> }
<ide>
<ide> // First, verify that this code path normally receives Fibers as keys,
<ide><path>packages/react-reconciler/src/__tests__/ReactIncrementalErrorHandling-test.internal.js
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> <Connector />
<ide> </Provider>,
<ide> );
<del> expect(() =>
<del> expect(Scheduler).toFlushWithoutYielding(),
<del> ).toErrorDev(
<add> expect(() => expect(Scheduler).toFlushWithoutYielding()).toErrorDev(
<ide> 'Legacy context API has been detected within a strict-mode tree.\n\n' +
<ide> 'The old API will be supported in all 16.x releases, but ' +
<ide> 'applications using it should migrate to the new version.\n\n' +
<ide> 'Please update the following components: Connector, Provider',
<del> {withoutStack: true},
<ide> );
<ide>
<ide> // If the context stack does not unwind, span will get 'abcde'
<ide> describe('ReactIncrementalErrorHandling', () => {
<ide> ReactNoop.render(<Provider />);
<ide> expect(() => {
<ide> expect(Scheduler).toFlushAndThrow('Oops!');
<del> }).toErrorDev(
<del> [
<del> 'Warning: The <Provider /> component appears to be a function component that returns a class instance. ' +
<del> 'Change Provider to a class that extends React.Component instead. ' +
<del> "If you can't use a class try assigning the prototype on the function as a workaround. " +
<del> '`Provider.prototype = React.Component.prototype`. ' +
<del> "Don't use an arrow function since it cannot be called with `new` by React.",
<del> 'Legacy context API has been detected within a strict-mode tree.\n\n' +
<del> 'The old API will be supported in all 16.x releases, but ' +
<del> 'applications using it should migrate to the new version.\n\n' +
<del> 'Please update the following components: Provider',
<del> ],
<del> {withoutStack: 1},
<del> );
<add> }).toErrorDev([
<add> 'Warning: The <Provider /> component appears to be a function component that returns a class instance. ' +
<add> 'Change Provider to a class that extends React.Component instead. ' +
<add> "If you can't use a class try assigning the prototype on the function as a workaround. " +
<add> '`Provider.prototype = React.Component.prototype`. ' +
<add> "Don't use an arrow function since it cannot be called with `new` by React.",
<add> 'Legacy context API has been detected within a strict-mode tree.\n\n' +
<add> 'The old API will be supported in all 16.x releases, but ' +
<add> 'applications using it should migrate to the new version.\n\n' +
<add> 'Please update the following components: Provider',
<add> ]);
<ide> });
<ide> });
<ide><path>packages/react-reconciler/src/__tests__/ReactIncrementalPerf-test.internal.js
<ide> describe('ReactDebugFiberPerf', () => {
<ide> 'Using UNSAFE_componentWillUpdate in strict mode is not recommended',
<ide> 'Legacy context API has been detected within a strict-mode tree',
<ide> ],
<del> {withoutStack: true},
<add> {withoutStack: 3},
<ide> );
<ide> ReactNoop.render(<AllLifecycles />);
<ide> addComment('Update');
<ide><path>packages/react-reconciler/src/__tests__/ReactNewContext-test.internal.js
<ide> describe('ReactNewContext', () => {
<ide> 'The old API will be supported in all 16.x releases, but applications ' +
<ide> 'using it should migrate to the new version.\n\n' +
<ide> 'Please update the following components: LegacyProvider',
<del> {withoutStack: true},
<ide> );
<ide> expect(ReactNoop.getChildren()).toEqual([span('Child')]);
<ide>
<ide><path>packages/react/src/__tests__/ReactStrictMode-test.js
<ide> describe('context legacy', () => {
<ide> 'FunctionalLegacyContextConsumer, LegacyContextConsumer, LegacyContextProvider' +
<ide> '\n\nLearn more about this warning here: ' +
<ide> 'https://fb.me/react-legacy-context' +
<add> '\n in LegacyContextProvider (at **)' +
<ide> '\n in StrictMode (at **)' +
<ide> '\n in div (at **)' +
<ide> '\n in Root (at **)', | 6 |
Text | Text | update virtualenv notes | ebbaff0853d49cd436b416beeb28220922bfc977 | <ide><path>docs/tutorial/1-serialization.md
<ide>
<ide> This tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together.
<ide>
<del>## Getting started
<add>## Setting up a new environment
<ide>
<ide> Before we do anything else we'll create a new virtual environment, using [virtualenv]. This will make sure our package configuration is keep nicely isolated from any other projects we're working on.
<ide>
<del> mkdir -p ~/.env
<del> virtualenv --no-site-packages ~/.env/djangorestframework
<del> source ~/.env/djangorestframework/env/bin/activate
<add> mkdir ~/env
<add> virtualenv --no-site-packages ~/env/djangorestframework
<add> source ~/env/djangorestframework/bin/activate
<ide>
<del>Now that we're inside a virtualenv environment, we can install our packages requirements.
<add>Now that we're inside a virtualenv environment, we can install our package requirements.
<ide>
<ide> pip install django
<ide> pip install djangorestframework
<ide>
<del>Now we're ready to get coding.
<add>***Note:** To exit the virtualenv environment at any time, just type `deactivate`. For more information see the [virtualenv documentation][virtualenv].*
<add>
<add>## Getting started
<add>
<add>Okay, we're ready to get coding.
<ide> To get started, let's create a new project to work with.
<ide>
<ide> django-admin.py startproject tutorial | 1 |
Javascript | Javascript | delete an unused field | a8964649bb6332cf1f8d723f81ce97cc5a1886ff | <ide><path>packages/react-reconciler/src/ReactFiberNewContext.new.js
<ide> export function readContext<T>(context: ReactContext<T>): T {
<ide> currentlyRenderingFiber.dependencies = {
<ide> lanes: NoLanes,
<ide> firstContext: contextItem,
<del>
<del> // TODO: This is an old field. Delete it.
<del> responders: null,
<ide> };
<ide> if (enableLazyContextPropagation) {
<ide> currentlyRenderingFiber.flags |= NeedsPropagation;
<ide><path>packages/react-reconciler/src/ReactFiberNewContext.old.js
<ide> export function readContext<T>(context: ReactContext<T>): T {
<ide> currentlyRenderingFiber.dependencies = {
<ide> lanes: NoLanes,
<ide> firstContext: contextItem,
<del>
<del> // TODO: This is an old field. Delete it.
<del> responders: null,
<ide> };
<ide> if (enableLazyContextPropagation) {
<ide> currentlyRenderingFiber.flags |= NeedsPropagation; | 2 |
Ruby | Ruby | fix rubocop violations | 12ddee0ce80458ea0217e82798c0ff2a02f7a7fc | <ide><path>railties/lib/rails/application/dummy_erb_compiler.rb
<ide> def make_compiler(trim_mode)
<ide> class DummyCompiler < ERB::Compiler # :nodoc:
<ide> def compile_content(stag, out)
<ide> case stag
<del> when '<%='
<add> when "<%="
<ide> out.push "_erbout << 'dummy_compiler'"
<ide> end
<ide> end | 1 |
Javascript | Javascript | report stats in benchmark/net-pipe | d1556fbdd298b58774f8560ac990cebb3e2875a6 | <ide><path>benchmark/net-pipe.js
<ide> // test the speed of .pipe() with sockets
<ide>
<ide> var net = require('net');
<add>var N = parseInt(process.argv[2]) || 100;
<ide> var start;
<ide>
<ide> function Writer() {
<ide> Writer.prototype.on = function() {};
<ide> Writer.prototype.once = function() {};
<ide> Writer.prototype.emit = function() {};
<ide>
<add>var rates = [];
<ide> var statCounter = 0;
<ide> Writer.prototype.printStats = function() {
<ide> if (!this.start || !this.received)
<ide> Writer.prototype.printStats = function() {
<ide> elapsed = elapsed[0] * 1E9 + elapsed[1];
<ide> var bits = this.received * 8;
<ide> var gbits = bits / (1024 * 1024 * 1024);
<del> var rate = (gbits / elapsed * 1E9).toFixed(4);
<del> console.log('%s Gbits/sec (%d bits / %d ns)', rate, bits, elapsed);
<add> var rate = gbits / elapsed * 1E9;
<add> rates.push(rate);
<add> console.log('%s Gbits/sec (%d bits / %d ns)', rate.toFixed(4), bits, elapsed);
<ide>
<ide> // reset to keep getting instant time.
<ide> this.start = process.hrtime();
<ide> this.received = 0;
<ide>
<del> // 100 seconds is enough time to get a few GC runs and stabilize.
<del> if (statCounter++ === 100)
<add> if (++statCounter === N) {
<add> report();
<ide> process.exit(0);
<add> }
<ide> };
<ide>
<add>function report() {
<add> rates.sort();
<add> var min = rates[0];
<add> var max = rates[rates.length - 1];
<add> var median = rates[rates.length >> 1];
<add> var avg = 0;
<add> rates.forEach(function(rate) { avg += rate });
<add> avg /= rates.length;
<add> console.error('min:%s avg:%s max:%s median:%s',
<add> min.toFixed(2),
<add> avg.toFixed(2),
<add> max.toFixed(2),
<add> median.toFixed(2));
<add>}
<add>
<ide> var len = process.env.LENGTH || 16 * 1024 * 1024;
<ide> var chunk = new Buffer(len);
<ide> for (var i = 0; i < len; i++) { | 1 |
Javascript | Javascript | remove unused variable | aefbd6f9f34a325a36c2c57c96904f15d06c3d51 | <ide><path>src/scales/scale.time.js
<ide> class TimeScale extends Scale {
<ide> : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));
<ide> me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined
<ide> : determineMajorUnit(me._unit);
<del> me._numIndices = ticks.length;
<ide> me._table = buildLookupTable(getTimestampsForTable(me), min, max, distribution);
<ide> me._offsets = computeOffsets(me._table, ticks, min, max, options);
<ide> | 1 |
Javascript | Javascript | remove showcase submission callout | ac92d3e81e0e6b65e159c0d2b50f04c789e8e34d | <ide><path>website/src/react-native/showcase.js
<ide> const showcase = React.createClass({
<ide> </div>
<ide>
<ide> <div className="inner-content">
<del> <p>Some of these are hybrid native/React Native apps. If you built a popular application using React Native, we'd love to have your app on this showcase. Check out the <a href="https://github.com/facebook/react-native/blob/master/website/src/react-native/showcase.js">guidelines on GitHub</a> to update this page.</p>
<add> <p>
<add> Some of these are hybrid native/React Native apps.
<add> </p>
<ide> </div>
<ide>
<ide> <div className="inner-content">
<del> <p>Also, <a href="https://github.com/ReactNativeNews/React-Native-Apps">a curated list of open source React Native apps</a> is being kept by React Native News.</p>
<add> <p>
<add> A curated list of <a href="https://github.com/ReactNativeNews/React-Native-Apps">open source React Native apps</a> is also being kept by React Native News.
<add> </p>
<ide> </div>
<ide>
<ide> </div> | 1 |
Javascript | Javascript | add test for pr | a2ea7a4962ba677d74baaf8b850bf6e9d17877ef | <ide><path>test/integration/render-error-on-module-error/pages/_error.js
<add>export default function Error() {
<add> return <p id="error-p">Error Rendered</p>
<add>}
<ide><path>test/integration/render-error-on-module-error/pages/index.js
<add>if (typeof window !== 'undefined') {
<add> throw new Error('fail module evaluation')
<add>}
<add>
<add>const Index = () => 'hi'
<add>
<add>Index.getInitialProps = () => ({})
<add>
<add>export default Index
<ide><path>test/integration/render-error-on-module-error/test/index.test.js
<add>/* eslint-env jest */
<add>/* global jasmine */
<add>import {
<add> nextBuild,
<add> nextServer,
<add> startApp,
<add> stopApp,
<add> waitFor,
<add>} from 'next-test-utils'
<add>import webdriver from 'next-webdriver'
<add>import { join } from 'path'
<add>
<add>jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2
<add>
<add>const appDir = join(__dirname, '..')
<add>
<add>let appPort
<add>let app
<add>let server
<add>
<add>describe('Module Init Error', () => {
<add> beforeAll(async () => {
<add> await nextBuild(appDir)
<add> app = nextServer({
<add> dir: join(__dirname, '../'),
<add> dev: false,
<add> quiet: true,
<add> })
<add>
<add> server = await startApp(app)
<add> appPort = server.address().port
<add> })
<add> afterAll(() => stopApp(server))
<add>
<add> it('should render error page', async () => {
<add> const browser = await webdriver(appPort, '/')
<add> try {
<add> await waitFor(2000)
<add> const text = await browser.elementByCss('#error-p').text()
<add> expect(text).toBe('Error Rendered')
<add> } finally {
<add> await browser.close()
<add> }
<add> })
<add>}) | 3 |
Javascript | Javascript | run all $log tests in ie9 & non-ie9 logging mode | 667d4734fcf7a58a58d29bd87fac32a7831df184 | <ide><path>test/ng/logSpec.js
<ide> describe('$log', function() {
<ide> var $window, logger, log, warn, info, error, debug;
<ide>
<del>
<del>
<ide> beforeEach(module(function($provide) {
<ide> $window = {
<ide> navigator: {userAgent: window.navigator.userAgent},
<ide> describe('$log', function() {
<ide> }
<ide> ));
<ide>
<del> it('should work if $window.navigator not defined', inject(
<del> function() {
<del> delete $window.navigator;
<del> },
<del> function($log) {}
<del> ));
<add> runTests({ie9Mode: false});
<add> runTests({ie9Mode: true});
<add>
<add> function runTests(options) {
<add> var ie9Mode = options.ie9Mode;
<ide>
<del> describe('IE logging behavior', function() {
<del> function removeApplyFunctionForIE() {
<del> log.apply = log.call =
<add> function attachMockConsoleTo$window() {
<add> // Support: IE 9 only
<add> // Simulate missing apply on console methods in IE 9.
<add> if (ie9Mode) {
<add> log.apply = log.call =
<ide> warn.apply = warn.call =
<ide> info.apply = info.call =
<ide> error.apply = error.call =
<ide> debug.apply = debug.call = null;
<add> }
<ide>
<del> $window.console = {log: log,
<add> $window.console = {
<add> log: log,
<ide> warn: warn,
<ide> info: info,
<ide> error: error,
<del> debug: debug};
<add> debug: debug
<add> };
<ide> }
<ide>
<del> it('should work in IE where console.error doesn\'t have an apply method', inject(
<del> removeApplyFunctionForIE,
<del> function($log) {
<add> describe(ie9Mode ? 'IE 9 logging behavior' : 'Modern browsers\' logging behavior', function() {
<add> beforeEach(module(attachMockConsoleTo$window));
<add>
<add> it('should work if $window.navigator not defined', inject(
<add> function() {
<add> delete $window.navigator;
<add> },
<add> function($log) {}
<add> ));
<add>
<add> it('should have a working apply method', inject(function($log) {
<ide> $log.log.apply($log);
<ide> $log.warn.apply($log);
<ide> $log.info.apply($log);
<ide> $log.error.apply($log);
<ide> $log.debug.apply($log);
<ide> expect(logger).toEqual('log;warn;info;error;debug;');
<del> })
<del> );
<del>
<del> // Support: Safari 9.1 only, iOS 9.3 only
<del> // For some reason Safari thinks there is always 1 parameter passed here.
<del> if (!/\b9\.\d(\.\d+)* safari/i.test(window.navigator.userAgent) &&
<del> !/\biphone os 9_/i.test(window.navigator.userAgent)) {
<del> it('should not attempt to log the second argument in IE if it is not specified', inject(
<del> function() {
<del> log = function(arg1, arg2) { logger += 'log,' + arguments.length + ';'; };
<del> warn = function(arg1, arg2) { logger += 'warn,' + arguments.length + ';'; };
<del> info = function(arg1, arg2) { logger += 'info,' + arguments.length + ';'; };
<del> error = function(arg1, arg2) { logger += 'error,' + arguments.length + ';'; };
<del> debug = function(arg1, arg2) { logger += 'debug,' + arguments.length + ';'; };
<del> },
<del> removeApplyFunctionForIE,
<del> function($log) {
<del> $log.log();
<del> $log.warn();
<del> $log.info();
<del> $log.error();
<del> $log.debug();
<del> expect(logger).toEqual('log,0;warn,0;info,0;error,0;debug,0;');
<del> })
<del> );
<del> }
<del> });
<del>
<del> describe('$log.debug', function() {
<del>
<del> beforeEach(initService(false));
<del>
<del> it('should skip debugging output if disabled', inject(
<del> function() {
<del> $window.console = {log: log,
<del> warn: warn,
<del> info: info,
<del> error: error,
<del> debug: debug};
<del> },
<del> function($log) {
<del> $log.log();
<del> $log.warn();
<del> $log.info();
<del> $log.error();
<del> $log.debug();
<del> expect(logger).toEqual('log;warn;info;error;');
<add> }));
<add>
<add> // Support: Safari 9.1 only, iOS 9.3 only
<add> // For some reason Safari thinks there is always 1 parameter passed here.
<add> if (!/\b9\.\d(\.\d+)* safari/i.test(window.navigator.userAgent) &&
<add> !/\biphone os 9_/i.test(window.navigator.userAgent)) {
<add> it('should not attempt to log the second argument in IE if it is not specified', inject(
<add> function() {
<add> log = function(arg1, arg2) { logger += 'log,' + arguments.length + ';'; };
<add> warn = function(arg1, arg2) { logger += 'warn,' + arguments.length + ';'; };
<add> info = function(arg1, arg2) { logger += 'info,' + arguments.length + ';'; };
<add> error = function(arg1, arg2) { logger += 'error,' + arguments.length + ';'; };
<add> debug = function(arg1, arg2) { logger += 'debug,' + arguments.length + ';'; };
<add> },
<add> attachMockConsoleTo$window,
<add> function($log) {
<add> $log.log();
<add> $log.warn();
<add> $log.info();
<add> $log.error();
<add> $log.debug();
<add> expect(logger).toEqual('log,0;warn,0;info,0;error,0;debug,0;');
<add> })
<add> );
<ide> }
<del> ));
<del>
<del> });
<ide>
<del> describe('$log.error', function() {
<del> var e, $log;
<del>
<del> function TestError() {
<del> Error.prototype.constructor.apply(this, arguments);
<del> this.message = undefined;
<del> this.sourceURL = undefined;
<del> this.line = undefined;
<del> this.stack = undefined;
<del> }
<del> TestError.prototype = Object.create(Error.prototype);
<del> TestError.prototype.constructor = TestError;
<del>
<del> beforeEach(inject(
<del> function() {
<del> e = new TestError('');
<del> $window.console = {
<del> error: jasmine.createSpy('error')
<del> };
<del> },
<del>
<del> function(_$log_) {
<del> $log = _$log_;
<del> }
<del> ));
<del>
<del> it('should pass error if does not have trace', function() {
<del> $log.error('abc', e);
<del> expect($window.console.error).toHaveBeenCalledWith('abc', e);
<del> });
<add> describe('$log.debug', function() {
<add>
<add> beforeEach(initService(false));
<add>
<add> it('should skip debugging output if disabled', inject(
<add> function() {
<add> $window.console = {log: log,
<add> warn: warn,
<add> info: info,
<add> error: error,
<add> debug: debug};
<add> },
<add> function($log) {
<add> $log.log();
<add> $log.warn();
<add> $log.info();
<add> $log.error();
<add> $log.debug();
<add> expect(logger).toEqual('log;warn;info;error;');
<add> }
<add> ));
<ide>
<del> if (msie || /\bEdge\//.test(window.navigator.userAgent)) {
<del> it('should print stack', function() {
<del> e.stack = 'stack';
<del> $log.error('abc', e);
<del> expect($window.console.error).toHaveBeenCalledWith('abc', 'stack');
<ide> });
<del> } else {
<del> it('should print a raw error', function() {
<del> e.stack = 'stack';
<del> $log.error('abc', e);
<del> expect($window.console.error).toHaveBeenCalledWith('abc', e);
<del> });
<del> }
<ide>
<del> it('should print line', function() {
<del> e.message = 'message';
<del> e.sourceURL = 'sourceURL';
<del> e.line = '123';
<del> $log.error('abc', e);
<del> expect($window.console.error).toHaveBeenCalledWith('abc', 'message\nsourceURL:123');
<add> describe('$log.error', function() {
<add> var e, $log;
<add>
<add> function TestError() {
<add> Error.prototype.constructor.apply(this, arguments);
<add> this.message = undefined;
<add> this.sourceURL = undefined;
<add> this.line = undefined;
<add> this.stack = undefined;
<add> }
<add> TestError.prototype = Object.create(Error.prototype);
<add> TestError.prototype.constructor = TestError;
<add>
<add> beforeEach(inject(
<add> function() {
<add> e = new TestError('');
<add> $window.console = {
<add> error: jasmine.createSpy('error')
<add> };
<add> },
<add>
<add> function(_$log_) {
<add> $log = _$log_;
<add> }
<add> ));
<add>
<add> it('should pass error if does not have trace', function() {
<add> $log.error('abc', e);
<add> expect($window.console.error).toHaveBeenCalledWith('abc', e);
<add> });
<add>
<add> if (msie || /\bEdge\//.test(window.navigator.userAgent)) {
<add> it('should print stack', function() {
<add> e.stack = 'stack';
<add> $log.error('abc', e);
<add> expect($window.console.error).toHaveBeenCalledWith('abc', 'stack');
<add> });
<add> } else {
<add> it('should print a raw error', function() {
<add> e.stack = 'stack';
<add> $log.error('abc', e);
<add> expect($window.console.error).toHaveBeenCalledWith('abc', e);
<add> });
<add> }
<add>
<add> it('should print line', function() {
<add> e.message = 'message';
<add> e.sourceURL = 'sourceURL';
<add> e.line = '123';
<add> $log.error('abc', e);
<add> expect($window.console.error).toHaveBeenCalledWith('abc', 'message\nsourceURL:123');
<add> });
<add> });
<ide> });
<del> });
<add> }
<add>
<ide>
<ide> function initService(debugEnabled) {
<ide> return module(function($logProvider) {
<ide> $logProvider.debugEnabled(debugEnabled);
<ide> });
<ide> }
<del>
<ide> }); | 1 |
Python | Python | add basic support for tf optimizers | 650c2c8cf9d711d35ab0ca7d1653ef53cbedaab3 | <ide><path>keras/optimizers.py
<ide> def optimizer_from_config(config, custom_objects={}):
<ide> 'adam': Adam,
<ide> 'adamax': Adamax,
<ide> 'nadam': Nadam,
<add> 'tfoptimizer': TFOptimizer,
<ide> }
<ide> class_name = config['class_name']
<ide> if class_name in custom_objects:
<ide> def __init__(self, **kwargs):
<ide> self.updates = []
<ide> self.weights = []
<ide>
<del> def get_state(self):
<del> return [K.get_value(u[0]) for u in self.updates]
<del>
<del> def set_state(self, value_list):
<del> assert len(self.updates) == len(value_list)
<del> for u, v in zip(self.updates, value_list):
<del> K.set_value(u[0], v)
<del>
<ide> def get_updates(self, params, constraints, loss):
<ide> raise NotImplementedError
<ide>
<ide> def get_config(self):
<ide> return dict(list(base_config.items()) + list(config.items()))
<ide>
<ide>
<add>class TFOptimizer(Optimizer):
<add>
<add> def __init__(self, optimizer):
<add> self.optimizer = optimizer
<add> self.iterations = K.variable(0.)
<add> self.updates = []
<add>
<add> def get_updates(self, params, constraints, loss):
<add> if constraints:
<add> raise ValueError('TF optimizers do not support '
<add> 'weights constraints. Either remove '
<add> 'all weights constraints in your model, '
<add> 'or use a Keras optimizer.')
<add> grads = self.optimizer.compute_gradients(loss, params)
<add> self.updates.append(K.update_add(self.iterations, 1))
<add> opt_update = self.optimizer.apply_gradients(
<add> grads, global_step=self.iterations)
<add> self.updates.append(opt_update)
<add> return self.updates
<add>
<add> @property
<add> def weights(self):
<add> raise NotImplementedError
<add>
<add> def get_config(self):
<add> raise NotImplementedError
<add>
<add> def from_config(self, config):
<add> raise NotImplementedError
<add>
<add>
<ide> # aliases
<ide> sgd = SGD
<ide> rmsprop = RMSprop
<ide> def get_config(self):
<ide>
<ide>
<ide> def get(identifier, kwargs=None):
<add> if K.backend() == 'tensorflow':
<add> # Wrap TF optimizer instances
<add> import tensorflow as tf
<add> if isinstance(identifier, tf.train.Optimizer):
<add> return TFOptimizer(identifier)
<add> # Instantiate a Keras optimizer
<ide> return get_from_module(identifier, globals(), 'optimizer',
<ide> instantiate=True, kwargs=kwargs) | 1 |
Javascript | Javascript | improve `readfile` performance | e65308053c871352be948b9001737df01aad1965 | <ide><path>lib/fs.js
<ide>
<ide> 'use strict';
<ide>
<add>const SlowBuffer = require('buffer').SlowBuffer;
<ide> const util = require('util');
<ide> const pathModule = require('path');
<ide>
<ide> fs.existsSync = function(path) {
<ide> fs.readFile = function(path, options, callback_) {
<ide> var callback = maybeCallback(arguments[arguments.length - 1]);
<ide>
<del> if (!options || typeof options === 'function') {
<add> if (!options || typeof options === 'function')
<ide> options = { encoding: null, flag: 'r' };
<del> } else if (typeof options === 'string') {
<add> else if (typeof options === 'string')
<ide> options = { encoding: options, flag: 'r' };
<del> } else if (typeof options !== 'object') {
<add> else if (typeof options !== 'object')
<ide> throw new TypeError('Bad arguments');
<del> }
<ide>
<ide> var encoding = options.encoding;
<ide> assertEncoding(encoding);
<ide>
<del> // first, stat the file, so we know the size.
<del> var size;
<del> var buffer; // single buffer with file data
<del> var buffers; // list for when size is unknown
<del> var pos = 0;
<del> var fd;
<del>
<ide> var flag = options.flag || 'r';
<del> fs.open(path, flag, 0o666, function(er, fd_) {
<del> if (er) return callback(er);
<del> fd = fd_;
<ide>
<del> fs.fstat(fd, function(er, st) {
<del> if (er) {
<del> return fs.close(fd, function() {
<del> callback(er);
<del> });
<del> }
<add> if (!nullCheck(path, callback))
<add> return;
<ide>
<del> size = st.size;
<del> if (size === 0) {
<del> // the kernel lies about many files.
<del> // Go ahead and try to read some bytes.
<del> buffers = [];
<del> return read();
<del> }
<add> var context = new ReadFileContext(callback, encoding);
<add> var req = new FSReqWrap();
<add> req.context = context;
<add> req.oncomplete = readFileAfterOpen;
<ide>
<del> if (size > kMaxLength) {
<del> var err = new RangeError('File size is greater than possible Buffer: ' +
<del> '0x3FFFFFFF bytes');
<del> return fs.close(fd, function() {
<del> callback(err);
<del> });
<del> }
<del> buffer = new Buffer(size);
<del> read();
<del> });
<del> });
<add> binding.open(pathModule._makeLong(path),
<add> stringToFlags(flag),
<add> 0o666,
<add> req);
<add>};
<ide>
<del> function read() {
<del> if (size === 0) {
<del> buffer = new Buffer(8192);
<del> fs.read(fd, buffer, 0, 8192, -1, afterRead);
<del> } else {
<del> fs.read(fd, buffer, pos, size - pos, -1, afterRead);
<del> }
<add>const kReadFileBufferLength = 8 * 1024;
<add>
<add>function ReadFileContext(callback, encoding) {
<add> this.fd = undefined;
<add> this.size = undefined;
<add> this.callback = callback;
<add> this.buffers = null;
<add> this.buffer = null;
<add> this.pos = 0;
<add> this.encoding = encoding;
<add> this.err = null;
<add>}
<add>
<add>ReadFileContext.prototype.read = function() {
<add> var fd = this.fd;
<add> var size = this.size;
<add> var buffer;
<add> var offset;
<add> var length;
<add>
<add> if (size === 0) {
<add> buffer = this.buffer = new SlowBuffer(kReadFileBufferLength);
<add> offset = 0;
<add> length = kReadFileBufferLength;
<add> } else {
<add> buffer = this.buffer;
<add> offset = this.pos;
<add> length = size - this.pos;
<ide> }
<ide>
<del> function afterRead(er, bytesRead) {
<del> if (er) {
<del> return fs.close(fd, function(er2) {
<del> return callback(er);
<del> });
<del> }
<add> var req = new FSReqWrap();
<add> req.oncomplete = readFileAfterRead;
<add> req.context = this;
<ide>
<del> if (bytesRead === 0) {
<del> return close();
<del> }
<add> binding.read(fd, buffer, offset, length, -1, req);
<add>};
<ide>
<del> pos += bytesRead;
<del> if (size !== 0) {
<del> if (pos === size) close();
<del> else read();
<del> } else {
<del> // unknown size, just read until we don't get bytes.
<del> buffers.push(buffer.slice(0, bytesRead));
<del> read();
<del> }
<add>ReadFileContext.prototype.close = function(err) {
<add> var req = new FSReqWrap();
<add> req.oncomplete = readFileAfterClose;
<add> req.context = this;
<add> this.err = err;
<add> binding.close(this.fd, req);
<add>};
<add>
<add>function readFileAfterOpen(err, fd) {
<add> var context = this.context;
<add>
<add> if (err) {
<add> var callback = context.callback;
<add> callback(err);
<add> return;
<ide> }
<ide>
<del> function close() {
<del> fs.close(fd, function(er) {
<del> if (size === 0) {
<del> // collected the data into the buffers list.
<del> buffer = Buffer.concat(buffers, pos);
<del> } else if (pos < size) {
<del> buffer = buffer.slice(0, pos);
<del> }
<add> context.fd = fd;
<ide>
<del> if (encoding) buffer = buffer.toString(encoding);
<del> return callback(er, buffer);
<del> });
<add> var req = new FSReqWrap();
<add> req.oncomplete = readFileAfterStat;
<add> req.context = context;
<add> binding.fstat(fd, req);
<add>}
<add>
<add>function readFileAfterStat(err, st) {
<add> var context = this.context;
<add>
<add> if (err)
<add> return context.close(err);
<add>
<add> var size = context.size = st.size;
<add>
<add> if (size === 0) {
<add> context.buffers = [];
<add> context.read();
<add> return;
<ide> }
<del>};
<add>
<add> if (size > kMaxLength) {
<add> err = new RangeError('File size is greater than possible Buffer: ' +
<add> `0x${kMaxLength.toString(16)} bytes`);
<add> return context.close(err);
<add> }
<add>
<add> context.buffer = new SlowBuffer(size);
<add> context.read();
<add>}
<add>
<add>function readFileAfterRead(err, bytesRead) {
<add> var context = this.context;
<add>
<add> if (err)
<add> return context.close(err);
<add>
<add> if (bytesRead === 0)
<add> return context.close();
<add>
<add> context.pos += bytesRead;
<add>
<add> if (context.size !== 0) {
<add> if (context.pos === context.size)
<add> context.close();
<add> else
<add> context.read();
<add> } else {
<add> // unknown size, just read until we don't get bytes.
<add> context.buffers.push(context.buffer.slice(0, bytesRead));
<add> context.read();
<add> }
<add>}
<add>
<add>function readFileAfterClose(err) {
<add> var context = this.context;
<add> var buffer = null;
<add> var callback = context.callback;
<add>
<add> if (context.err)
<add> return callback(context.err);
<add>
<add> if (context.size === 0)
<add> buffer = Buffer.concat(context.buffers, context.pos);
<add> else if (context.pos < context.size)
<add> buffer = context.buffer.slice(0, context.pos);
<add> else
<add> buffer = context.buffer;
<add>
<add> if (context.encoding)
<add> buffer = buffer.toString(context.encoding);
<add>
<add> callback(err, buffer);
<add>}
<add>
<ide>
<ide> fs.readFileSync = function(path, options) {
<ide> if (!options) { | 1 |
Go | Go | remove redundant file close | 3dca62cfb1e7c6404cb4730425919f66c680b409 | <ide><path>profiles/apparmor/apparmor.go
<ide> func InstallDefault(name string) error {
<ide> defer os.Remove(profilePath)
<ide>
<ide> if err := p.generateDefault(f); err != nil {
<del> f.Close()
<ide> return err
<ide> }
<ide> | 1 |
Javascript | Javascript | use animated.event implementation in animatedmock | fc9c326912d9b76f3db9390aaffbf4b1570c73a8 | <ide><path>Libraries/Animated/AnimatedMock.js
<ide> const {AnimatedEvent, attachNativeEvent} = require('./AnimatedEvent');
<ide> const AnimatedImplementation = require('./AnimatedImplementation');
<ide> const AnimatedInterpolation = require('./nodes/AnimatedInterpolation');
<ide> const AnimatedNode = require('./nodes/AnimatedNode');
<del>const AnimatedProps = require('./nodes/AnimatedProps');
<ide> const AnimatedValue = require('./nodes/AnimatedValue');
<ide> const AnimatedValueXY = require('./nodes/AnimatedValueXY');
<ide>
<ide> import type {EndCallback} from './animations/Animation';
<ide> import type {TimingAnimationConfig} from './animations/TimingAnimation';
<ide> import type {DecayAnimationConfig} from './animations/DecayAnimation';
<ide> import type {SpringAnimationConfig} from './animations/SpringAnimation';
<del>import type {Mapping, EventConfig} from './AnimatedEvent';
<ide>
<ide> /**
<ide> * Animations are a source of flakiness in snapshot testing. This mock replaces
<ide> const loop = function(
<ide> return emptyAnimation;
<ide> };
<ide>
<del>const event = function(argMapping: Array<?Mapping>, config: EventConfig): any {
<del> return null;
<del>};
<del>
<ide> module.exports = {
<ide> Value: AnimatedValue,
<ide> ValueXY: AnimatedValueXY,
<ide> module.exports = {
<ide> parallel,
<ide> stagger,
<ide> loop,
<del> event,
<add> event: AnimatedImplementation.event,
<ide> createAnimatedComponent,
<ide> attachNativeEvent,
<ide> forkEvent: AnimatedImplementation.forkEvent, | 1 |
Python | Python | check weights length | 531a8eabe222c3831cc5b55bafc81d2aa36f0672 | <ide><path>keras/optimizers.py
<ide> def set_weights(self, weights):
<ide> ValueError: in case of incompatible weight shapes.
<ide> """
<ide> params = self.weights
<add> if len(params) != len(weights):
<add> raise ValueError('Length of the specified weight list (' +
<add> str(len(weights)) +
<add> ') does not match the number of weights ' +
<add> 'of the optimizer (' + str(len(params)) + ')')
<ide> weight_value_tuples = []
<ide> param_values = K.batch_get_value(params)
<ide> for pv, p, w in zip(param_values, params, weights): | 1 |
Text | Text | carry man page for 14637 | ae45ffc1feef4f2d859f7083a8d64a42c0e74c73 | <ide><path>man/docker-load.1.md
<ide> Restores both images and tags.
<ide> Print usage statement
<ide>
<ide> **-i**, **--input**=""
<del> Read from a tar archive file, instead of STDIN
<add> Read from a tar archive file, instead of STDIN. The tarball may be compressed with gzip, bzip, or xz.
<ide>
<ide> # EXAMPLES
<ide>
<ide> Restores both images and tags.
<ide> April 2014, Originally compiled by William Henry (whenry at redhat dot com)
<ide> based on docker.com source material and internal work.
<ide> June 2014, updated by Sven Dowideit <[email protected]>
<add>July 2015 update by Mary Anthony <[email protected]> | 1 |
Javascript | Javascript | fix normalized cid fonts for direct write 6.1 | dc914fe7ce8f362cfddfa5bb58877043d55dfe1b | <ide><path>src/fonts.js
<ide> var CFFFont = (function CFFFontClosure() {
<ide> this.properties = properties;
<ide>
<ide> var parser = new CFFParser(file, properties);
<del> var cff = parser.parse(true);
<add> var cff = parser.parse();
<ide> var compiler = new CFFCompiler(cff);
<ide> this.readExtra(cff);
<ide> try {
<ide> var CFFParser = (function CFFParserClosure() {
<ide> this.properties = properties;
<ide> }
<ide> CFFParser.prototype = {
<del> parse: function CFFParser_parse(normalizeCIDData) {
<add> parse: function CFFParser_parse() {
<ide> var properties = this.properties;
<ide> var cff = new CFF();
<ide> this.cff = cff;
<ide> var CFFParser = (function CFFParserClosure() {
<ide> cff.charset = charset;
<ide> cff.encoding = encoding;
<ide>
<del> if (!cff.isCIDFont || !normalizeCIDData)
<del> return cff;
<del>
<del> // DirectWrite does not like CID fonts data. Trying to convert/flatten
<del> // the font data and remove CID properties.
<del> if (cff.fdArray.length !== 1) {
<del> warn('Unable to normalize CID font in CFF data -- using font as is');
<del> return cff;
<del> }
<del>
<del> var fontDict = cff.fdArray[0];
<del> // Make the sanitizer happy and remove anything that is only for CID
<del> // fonts.
<del> fontDict.setByKey(17, topDict.getByName('CharStrings'));
<del> fontDict.removeByName('CIDFontVersion');
<del> fontDict.removeByName('CIDFontRevision');
<del> fontDict.removeByName('CIDFontType');
<del> fontDict.removeByName('CIDCount');
<del> fontDict.removeByName('UIDBase');
<del> cff.topDict = fontDict;
<del> cff.isCIDFont = false;
<del> delete cff.fdArray;
<del> delete cff.fdSelect;
<del>
<ide> return cff;
<ide> },
<ide> parseHeader: function CFFParser_parseHeader() {
<ide> var CFFTopDict = (function CFFTopDictClosure() {
<ide> [[12, 33], 'CIDFontType', 'num', 0],
<ide> [[12, 34], 'CIDCount', 'num', 8720],
<ide> [[12, 35], 'UIDBase', 'num', null],
<del> [[12, 36], 'FDArray', 'offset', null],
<add> // XXX: CID Fonts on DirectWrite 6.1 only seem to work if FDSelect comes
<add> // before FDArray.
<ide> [[12, 37], 'FDSelect', 'offset', null],
<del> [[12, 38], 'FontName', 'sid', null]];
<add> [[12, 36], 'FDArray', 'offset', null],
<add> [[12, 38], 'FontName', 'sid', null]
<add> ];
<ide> var tables = null;
<ide> function CFFTopDict(strings) {
<ide> if (tables === null)
<ide> var CFFCompiler = (function CFFCompilerClosure() {
<ide> var nameIndex = this.compileNameIndex(cff.names);
<ide> output.add(nameIndex);
<ide>
<del> var compiled = this.compileTopDicts([cff.topDict], output.length);
<add> var compiled = this.compileTopDicts([cff.topDict],
<add> output.length,
<add> cff.isCIDFont);
<ide> output.add(compiled.output);
<ide> var topDictTracker = compiled.trackers[0];
<ide>
<ide> var CFFCompiler = (function CFFCompilerClosure() {
<ide> topDictTracker.setEntryLocation('FDSelect', [output.length], output);
<ide> var fdSelect = this.compileFDSelect(cff.fdSelect.raw);
<ide> output.add(fdSelect);
<del>
<del> var compiled = this.compileTopDicts(cff.fdArray, output.length);
<add> // It is unclear if the sub font dictionary can have CID related
<add> // dictionary keys, but the sanitizer doesn't like them so remove them.
<add> var compiled = this.compileTopDicts(cff.fdArray, output.length, true);
<ide> topDictTracker.setEntryLocation('FDArray', [output.length], output);
<ide> output.add(compiled.output);
<ide> var fontDictTrackers = compiled.trackers;
<ide> var CFFCompiler = (function CFFCompilerClosure() {
<ide> nameIndex.add(stringToArray(names[i]));
<ide> return this.compileIndex(nameIndex);
<ide> },
<del> compileTopDicts: function CFFCompiler_compileTopDicts(dicts, length) {
<add> compileTopDicts: function CFFCompiler_compileTopDicts(dicts,
<add> length,
<add> removeCidKeys) {
<ide> var fontDictTrackers = [];
<ide> var fdArrayIndex = new CFFIndex();
<ide> for (var i = 0, ii = dicts.length; i < ii; ++i) {
<ide> var fontDict = dicts[i];
<add> if (removeCidKeys) {
<add> fontDict.removeByName('CIDFontVersion');
<add> fontDict.removeByName('CIDFontRevision');
<add> fontDict.removeByName('CIDFontType');
<add> fontDict.removeByName('CIDCount');
<add> fontDict.removeByName('UIDBase');
<add> }
<ide> var fontDictTracker = new CFFOffsetTracker();
<ide> var fontDictData = this.compileDict(fontDict, fontDictTracker);
<ide> fontDictTrackers.push(fontDictTracker); | 1 |
PHP | PHP | remove unused import | b1381f2d876ba4cec4dbdea84ae0fb6ccce0bb79 | <ide><path>src/Illuminate/Support/Stringable.php
<ide> use Illuminate\Support\Traits\Macroable;
<ide> use Illuminate\Support\Traits\Tappable;
<ide> use JsonSerializable;
<del>use League\CommonMark\GithubFlavoredMarkdownConverter;
<ide> use Symfony\Component\VarDumper\VarDumper;
<ide>
<ide> class Stringable implements JsonSerializable | 1 |
Text | Text | add a section on converting a selectlistview | ed9c62f883b5d303123ba3a2d09b733bba08df25 | <ide><path>docs/upgrading/upgrading-your-package.md
<ide> Sometimes it is as simple as converting the requires at the top of each view pag
<ide> {TextEditorView} = require 'atom-space-pen-views'
<ide> ```
<ide>
<add>If you are using the lifecycle hooks, you will need to update code as well.
<add>
<add>### Upgrading to space-pen's TextEditorView
<add>
<add>You should not need to change anything to use the new `TextEditorView`! See the [docs][TextEditorView] for more info.
<add>
<add>### Upgrading to space-pen's ScrollView
<add>
<add>See the [docs][ScrollView] for all the options.
<add>
<add>### Upgrading to space-pen's SelectListView
<add>
<add>Your SelectListView might look something like this:
<add>
<add>```coffee
<add>class CommandPaletteView extends SelectListView
<add> initialize: ->
<add> super
<add> @addClass('command-palette overlay from-top')
<add> atom.workspaceView.command 'command-palette:toggle', => @toggle()
<add>
<add> confirmed: ({name, jQuery}) ->
<add> @cancel()
<add> # do something with the result
<add>
<add> toggle: ->
<add> if @hasParent()
<add> @cancel()
<add> else
<add> @attach()
<add>
<add> attach: ->
<add> @storeFocusedElement()
<add>
<add> items = # build items
<add> @setItems(items)
<add>
<add> atom.workspaceView.append(this)
<add> @focusFilterEditor()
<add>
<add> confirmed: ({name, jQuery}) ->
<add> @cancel()
<add>```
<add>
<add>This attaches and detaches itself from the dom when toggled, canceling magically detaches it from the DOM, and it uses the classes `overlay` and `from-top`.
<add>
<add>Using the new APIs it should look like this:
<add>
<add>```coffee
<add>class CommandPaletteView extends SelectListView
<add> initialize: ->
<add> super
<add> # no more need for the `overlay` and `from-top` classes
<add> @addClass('command-palette')
<add> atom.workspaceView.command 'command-palette:toggle', => @toggle()
<add>
<add> # You need to implement the `cancelled` method and hide.
<add> cancelled: ->
<add> @hide()
<add>
<add> confirmed: ({name, jQuery}) ->
<add> @cancel()
<add> # do something with the result
<add>
<add> toggle: ->
<add> # Toggling now checks panel visibility,
<add> # and hides / shows rather than attaching to / detaching from the DOM.
<add> if @panel?.isVisible()
<add> @cancel()
<add> else
<add> @show()
<add>
<add> show: ->
<add> # Now you will add your select list as a modal panel to the workspace
<add> @panel ?= atom.workspace.addModalPanel(item: this)
<add> @panel.show()
<add>
<add> @storeFocusedElement()
<add>
<add> items = # build items
<add> @setItems(items)
<add>
<add> @focusFilterEditor()
<add>
<add> hide: ->
<add> @panel?.hide()
<add>```
<add>
<add>See the [SelectListView docs][SelectListView] for all the options.
<add>
<ide> ## Specs
<ide>
<del>TODO: come up with patterns for
<add>TODO: come up with patterns for converting away from using `workspaceView` and `editorView`s everywhere.
<add>
<add>
<add>[texteditorview]:https://github.com/atom/atom-space-pen-views#texteditorview
<add>[scrollview]:https://github.com/atom/atom-space-pen-views#scrollview
<add>[selectlistview]:https://github.com/atom/atom-space-pen-views#selectlistview | 1 |
Mixed | Javascript | return worker reference from disconnect() | 5d146021811c41def88208e60977eddbf0d6f125 | <ide><path>doc/api/cluster.md
<ide> It is not emitted in the worker.
<ide> added: v0.7.7
<ide> -->
<ide>
<add>* Returns: {Worker} A reference to `worker`.
<add>
<ide> In a worker, this function will close all servers, wait for the `'close'` event on
<ide> those servers, and then disconnect the IPC channel.
<ide>
<ide><path>lib/cluster.js
<ide> function masterInit() {
<ide> send(this, { act: 'disconnect' });
<ide> removeHandlesForWorker(this);
<ide> removeWorker(this);
<add> return this;
<ide> };
<ide>
<ide> Worker.prototype.destroy = function(signo) {
<ide> function workerInit() {
<ide>
<ide> Worker.prototype.disconnect = function() {
<ide> _disconnect.call(this);
<add> return this;
<ide> };
<ide>
<ide> Worker.prototype.destroy = function() {
<ide><path>test/parallel/test-cluster-worker-destroy.js
<ide> */
<ide>
<ide> const common = require('../common');
<add>const assert = require('assert');
<ide> var cluster = require('cluster');
<ide> var worker1, worker2;
<ide>
<ide> if (cluster.isMaster) {
<ide> cluster.worker.destroy();
<ide> });
<ide>
<del> cluster.worker.disconnect();
<add> const w = cluster.worker.disconnect();
<add> assert.strictEqual(w, cluster.worker, 'did not return a reference');
<ide> } else {
<ide> // Call destroy when worker is not disconnected yet
<ide> cluster.worker.destroy();
<ide><path>test/parallel/test-cluster-worker-disconnect.js
<ide> if (cluster.isWorker) {
<ide>
<ide> // Disconnect worker when it is ready
<ide> worker.once('listening', common.mustCall(() => {
<del> worker.disconnect();
<add> const w = worker.disconnect();
<add> assert.strictEqual(worker, w, 'did not return a reference');
<ide> }));
<ide>
<ide> // Check cluster events
<ide><path>test/parallel/test-cluster-worker-init.js
<ide> if (cluster.isMaster) {
<ide>
<ide> worker.on('message', common.mustCall((message) => {
<ide> assert.strictEqual(message, true, 'did not receive expected message');
<del> worker.disconnect();
<add> const w = worker.disconnect();
<add> assert.strictEqual(worker, w, 'did not return a reference');
<ide> }));
<ide>
<ide> worker.on('online', () => { | 5 |
Ruby | Ruby | handle non-tty stdin | 2cf2c020ba04f57ac9e77712df6a25525744715b | <ide><path>Library/Homebrew/utils/tty.rb
<ide> def strip_ansi(string)
<ide> end
<ide>
<ide> def width
<del> (`/bin/stty size`.split[1] || 80).to_i
<add> width = `/bin/stty size 2>/dev/null`.split[1]
<add> width ||= `/usr/bin/tput cols 2>/dev/null`.split[0]
<add> width ||= 80
<add> width.to_i
<ide> end
<ide>
<ide> def truncate(string) | 1 |
Text | Text | add a note about production mode for npm installs | 9ddb4d4a78bde6ecdd7bf87c4beffb910b4d51d0 | <ide><path>docs/downloads.md
<ide> React.renderComponent(...);
<ide>
<ide> If you'd like to use any [add-ons](/react/docs/addons.html), use `var React = require('react/addons');` instead.
<ide>
<add>**Note:** by default, React will be in development mode. To use React in production mode, set the environment variable `NODE_ENV` to `production`. For use in node, this is sufficient; if you are using browserify, the [envify](https://github.com/hughsk/envify) transform is needed to make use of environment variables. A minifier that performs dead-code elimination such as [UglifyJS](https://github.com/mishoo/UglifyJS2) is recommended to completely remove the extra code present in development mode.
<add>
<ide> ## Bower
<ide>
<ide> ```sh
<ide><path>npm-react/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>**Note:** by default, React will be in development mode. The development version includes extra warnings about common mistakes, whereas the production version includes extra performance optimizations and strips all error messages.
<add>
<add>To use React in production mode, set the environment variable `NODE_ENV` to `production`. For use in node, this is sufficient; if you are using browserify, the [envify](https://github.com/hughsk/envify) transform is needed to make use of environment variables. A minifier that performs dead-code elimination such as [UglifyJS](https://github.com/mishoo/UglifyJS2) is recommended to completely remove the extra code present in development mode.
<ide>
<ide> ## Example Usage
<ide> | 2 |
PHP | PHP | stop event propagation when returning response | 7f2d68172fa1c6d520a556ff1e841a3048bbb0a5 | <ide><path>src/Controller/Component/AuthComponent.php
<ide> public function initialize(Event $event) {
<ide> * of login form data.
<ide> *
<ide> * @param Event $event The startup event.
<del> * @return bool
<add> * @return bool|\Cake\Network\Response
<ide> */
<ide> public function startup(Event $event) {
<ide> $controller = $event->subject();
<ide> public function startup(Event $event) {
<ide> }
<ide>
<ide> if (!$this->_getUser()) {
<del> return $this->_unauthenticated($controller);
<add> $result = $this->_unauthenticated($controller);
<add> if ($result instanceof Response) {
<add> $event->stopPropagation();
<add> }
<add> return $result;
<ide> }
<ide>
<ide> if ($this->_isLoginAction($controller) ||
<ide> public function startup(Event $event) {
<ide> return true;
<ide> }
<ide>
<del> return $this->_unauthorized($controller);
<add> $result = $this->_unauthorized($controller);
<add> if ($result instanceof Response) {
<add> $event->stopPropagation();
<add> }
<add> return $result;
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php
<ide> public function testAuthorizeFalse() {
<ide>
<ide> $this->Auth->Session->delete('Auth');
<ide> $result = $this->Controller->Auth->startup($event);
<add> $this->assertTrue($event->isStopped());
<ide> $this->assertInstanceOf('Cake\Network\Response', $result);
<ide> $this->assertTrue($this->Auth->Session->check('Message.auth'));
<ide>
<ide> public function testAllowDenyAll() {
<ide> $this->Controller->request['action'] = 'camelCase';
<ide> $this->assertInstanceOf('Cake\Network\Response', $this->Controller->Auth->startup($event));
<ide>
<del> $this->Controller->Auth->allow('*');
<add> $this->Controller->Auth->allow();
<ide> $this->Controller->Auth->deny();
<ide>
<ide> $this->Controller->request['action'] = 'camelCase';
<ide> public function testAjaxLogin() {
<ide>
<ide> $response = $this->Auth->startup($event);
<ide>
<add> $this->assertTrue($event->isStopped());
<ide> $this->assertEquals(403, $response->statusCode());
<ide> $this->assertEquals(
<ide> "Ajax!\nthis is the test element", | 2 |
Javascript | Javascript | remove ai_v4mapped hint flag on freebsd" | df1994fe53754bd0a191239a704c6a656f210392 | <ide><path>lib/dns.js
<ide> exports.lookup = function lookup(hostname, options, callback) {
<ide> hints !== (exports.ADDRCONFIG | exports.V4MAPPED)) {
<ide> throw new TypeError('invalid argument: hints must use valid flags');
<ide> }
<del>
<del> // FIXME(indutny): V4MAPPED on FreeBSD results in EAI_BADFLAGS, because
<del> // the libc does not support it
<del> if (process.platform === 'freebsd' && family !== 6)
<del> hints &= ~exports.V4MAPPED;
<ide> } else {
<ide> family = options >>> 0;
<ide> } | 1 |
PHP | PHP | add test case for assertnoredirect | 76468c67fa9702db77ce255e9028cf528f8843db | <ide><path>tests/TestCase/TestSuite/IntegrationTestCaseTest.php
<ide> public function testAssertRedirect() {
<ide> $this->assertRedirect(['controller' => 'Tasks', 'action' => 'index']);
<ide> }
<ide>
<add>/**
<add> * Test the location header assertion.
<add> *
<add> * @return void
<add> */
<add> public function testAssertNoRedirect() {
<add> $this->_response = new Response();
<add>
<add> $this->assertNoRedirect();
<add> }
<add>
<ide> /**
<ide> * Test the header assertion.
<ide> * | 1 |
Ruby | Ruby | update rack fixture to be ruby 1.9 compat | 4185a4a5f5e53b55c9ba3757a837d33fb91f4091 | <ide><path>actionpack/test/controller/integration_test.rb
<ide> class MetalTest < ActionController::IntegrationTest
<ide> class Poller
<ide> def self.call(env)
<ide> if env["PATH_INFO"] =~ /^\/success/
<del> [200, {"Content-Type" => "text/plain", "Content-Length" => "12"}, "Hello World!"]
<add> [200, {"Content-Type" => "text/plain", "Content-Length" => "12"}, ["Hello World!"]]
<ide> else
<del> [404, {"Content-Type" => "text/plain", "Content-Length" => "0"}, '']
<add> [404, {"Content-Type" => "text/plain", "Content-Length" => "0"}, []]
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | add feature to trigger an error boundary | 8b4201535c6068147d61d0ed3f02d21d6dcd6927 | <ide><path>packages/react-devtools-shared/src/__tests__/inspectedElement-test.js
<ide> describe('InspectedElement', () => {
<ide> `);
<ide> });
<ide> });
<add>
<add> describe('error boundary', () => {
<add> it('can toggle error', async () => {
<add> class ErrorBoundary extends React.Component<any> {
<add> state = {hasError: false};
<add> static getDerivedStateFromError(error) {
<add> return {hasError: true};
<add> }
<add> render() {
<add> const {hasError} = this.state;
<add> return hasError ? 'has-error' : this.props.children;
<add> }
<add> }
<add> const Example = () => 'example';
<add>
<add> await utils.actAsync(() =>
<add> ReactDOM.render(
<add> <ErrorBoundary>
<add> <Example />
<add> </ErrorBoundary>,
<add> document.createElement('div'),
<add> ),
<add> );
<add>
<add> const targetErrorBoundaryID = ((store.getElementIDAtIndex(
<add> 0,
<add> ): any): number);
<add> const inspect = index => {
<add> // HACK: Recreate TestRenderer instance so we can inspect different
<add> // elements
<add> testRendererInstance = TestRenderer.create(null, {
<add> unstable_isConcurrent: true,
<add> });
<add> return inspectElementAtIndex(index);
<add> };
<add> const toggleError = async forceError => {
<add> await withErrorsOrWarningsIgnored(['ErrorBoundary'], async () => {
<add> await utils.actAsync(() => {
<add> bridge.send('overrideError', {
<add> id: targetErrorBoundaryID,
<add> rendererID: store.getRendererIDForElement(targetErrorBoundaryID),
<add> forceError,
<add> });
<add> });
<add> });
<add>
<add> TestUtilsAct(() => {
<add> jest.runOnlyPendingTimers();
<add> });
<add> };
<add>
<add> // Inspect <ErrorBoundary /> and see that we cannot toggle error state
<add> // on error boundary itself
<add> let inspectedElement = await inspect(0);
<add> expect(inspectedElement.canToggleError).toBe(false);
<add> expect(inspectedElement.targetErrorBoundaryID).toBe(null);
<add>
<add> // Inspect <Example />
<add> inspectedElement = await inspect(1);
<add> expect(inspectedElement.canToggleError).toBe(true);
<add> expect(inspectedElement.isErrored).toBe(false);
<add> expect(inspectedElement.targetErrorBoundaryID).toBe(
<add> targetErrorBoundaryID,
<add> );
<add>
<add> // now force error state on <Example />
<add> await toggleError(true);
<add>
<add> // we are in error state now, <Example /> won't show up
<add> expect(store.getElementIDAtIndex(1)).toBe(null);
<add>
<add> // Inpsect <ErrorBoundary /> to toggle off the error state
<add> inspectedElement = await inspect(0);
<add> expect(inspectedElement.canToggleError).toBe(true);
<add> expect(inspectedElement.isErrored).toBe(true);
<add> // its error boundary ID is itself because it's caught the error
<add> expect(inspectedElement.targetErrorBoundaryID).toBe(
<add> targetErrorBoundaryID,
<add> );
<add>
<add> await toggleError(false);
<add>
<add> // We can now inspect <Example /> with ability to toggle again
<add> inspectedElement = await inspect(1);
<add> expect(inspectedElement.canToggleError).toBe(true);
<add> expect(inspectedElement.isErrored).toBe(false);
<add> expect(inspectedElement.targetErrorBoundaryID).toBe(
<add> targetErrorBoundaryID,
<add> );
<add> });
<add> });
<ide> });
<ide><path>packages/react-devtools-shared/src/__tests__/inspectedElementSerializer.js
<ide> export function test(maybeInspectedElement) {
<ide> hasOwnProperty('canEditFunctionProps') &&
<ide> hasOwnProperty('canEditHooks') &&
<ide> hasOwnProperty('canToggleSuspense') &&
<add> hasOwnProperty('canToggleError') &&
<ide> hasOwnProperty('canViewSource')
<ide> );
<ide> }
<ide><path>packages/react-devtools-shared/src/backend/agent.js
<ide> type OverrideValueAtPathParams = {|
<ide> value: any,
<ide> |};
<ide>
<add>type OverrideErrorParams = {|
<add> id: number,
<add> rendererID: number,
<add> forceError: boolean,
<add>|};
<add>
<ide> type OverrideSuspenseParams = {|
<ide> id: number,
<ide> rendererID: number,
<ide> export default class Agent extends EventEmitter<{|
<ide> bridge.addListener('getOwnersList', this.getOwnersList);
<ide> bridge.addListener('inspectElement', this.inspectElement);
<ide> bridge.addListener('logElementToConsole', this.logElementToConsole);
<add> bridge.addListener('overrideError', this.overrideError);
<ide> bridge.addListener('overrideSuspense', this.overrideSuspense);
<ide> bridge.addListener('overrideValueAtPath', this.overrideValueAtPath);
<ide> bridge.addListener('reloadAndProfile', this.reloadAndProfile);
<ide> export default class Agent extends EventEmitter<{|
<ide> }
<ide> };
<ide>
<add> overrideError = ({id, rendererID, forceError}: OverrideErrorParams) => {
<add> const renderer = this._rendererInterfaces[rendererID];
<add> if (renderer == null) {
<add> console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`);
<add> } else {
<add> renderer.overrideError(id, forceError);
<add> }
<add> };
<add>
<ide> overrideSuspense = ({
<ide> id,
<ide> rendererID,
<ide><path>packages/react-devtools-shared/src/backend/legacy/renderer.js
<ide> export function attach(
<ide> canEditFunctionPropsDeletePaths: false,
<ide> canEditFunctionPropsRenamePaths: false,
<ide>
<add> // Toggle error boundary did not exist in legacy versions
<add> canToggleError: false,
<add> isErrored: false,
<add> targetErrorBoundaryID: null,
<add>
<ide> // Suspense did not exist in legacy versions
<ide> canToggleSuspense: false,
<ide>
<ide> export function attach(
<ide> const handlePostCommitFiberRoot = () => {
<ide> throw new Error('handlePostCommitFiberRoot not supported by this renderer');
<ide> };
<add> const overrideError = () => {
<add> throw new Error('overrideError not supported by this renderer');
<add> };
<ide> const overrideSuspense = () => {
<ide> throw new Error('overrideSuspense not supported by this renderer');
<ide> };
<ide> export function attach(
<ide> handlePostCommitFiberRoot,
<ide> inspectElement,
<ide> logElementToConsole,
<add> overrideError,
<ide> overrideSuspense,
<ide> overrideValueAtPath,
<ide> renamePath,
<ide><path>packages/react-devtools-shared/src/backend/renderer.js
<ide> type ReactPriorityLevelsType = {|
<ide> |};
<ide>
<ide> type ReactTypeOfSideEffectType = {|
<add> DidCapture: number,
<ide> NoFlags: number,
<ide> PerformedWork: number,
<ide> Placement: number,
<ide> export function getInternalReactConstants(
<ide> ReactTypeOfWork: WorkTagMap,
<ide> |} {
<ide> const ReactTypeOfSideEffect: ReactTypeOfSideEffectType = {
<add> DidCapture: 0b10000000,
<ide> NoFlags: 0b00,
<ide> PerformedWork: 0b01,
<ide> Placement: 0b10,
<ide> export function attach(
<ide> ReactTypeOfWork,
<ide> ReactTypeOfSideEffect,
<ide> } = getInternalReactConstants(version);
<del> const {Incomplete, NoFlags, PerformedWork, Placement} = ReactTypeOfSideEffect;
<add> const {
<add> DidCapture,
<add> Incomplete,
<add> NoFlags,
<add> PerformedWork,
<add> Placement,
<add> } = ReactTypeOfSideEffect;
<ide> const {
<ide> CacheComponent,
<ide> ClassComponent,
<ide> export function attach(
<ide> overrideProps,
<ide> overridePropsDeletePath,
<ide> overridePropsRenamePath,
<add> setErrorHandler,
<ide> setSuspenseHandler,
<ide> scheduleUpdate,
<ide> } = renderer;
<add> const supportsTogglingError =
<add> typeof setErrorHandler === 'function' &&
<add> typeof scheduleUpdate === 'function';
<ide> const supportsTogglingSuspense =
<ide> typeof setSuspenseHandler === 'function' &&
<ide> typeof scheduleUpdate === 'function';
<ide> export function attach(
<ide> type: 'error' | 'warn',
<ide> args: $ReadOnlyArray<any>,
<ide> ): void {
<add> if (type === 'error') {
<add> const maybeID = getFiberIDUnsafe(fiber);
<add> // if this is an error simulated by us to trigger error boundary, ignore
<add> if (maybeID != null && forceErrorForFiberIDs.get(maybeID) === true) {
<add> return;
<add> }
<add> }
<ide> const message = format(...args);
<ide> if (__DEBUG__) {
<ide> debug('onErrorOrWarning', fiber, null, `${type}: "${message}"`);
<ide> export function attach(
<ide> if (alternate !== null) {
<ide> fiberToIDMap.delete(alternate);
<ide> }
<add>
<add> if (forceErrorForFiberIDs.has(fiberID)) {
<add> forceErrorForFiberIDs.delete(fiberID);
<add> if (forceErrorForFiberIDs.size === 0 && setErrorHandler != null) {
<add> setErrorHandler(shouldErrorFiberAlwaysNull);
<add> }
<add> }
<ide> });
<ide> untrackFibersSet.clear();
<ide> }
<ide> export function attach(
<ide> return {instance, style};
<ide> }
<ide>
<add> function isErrorBoundary(fiber: Fiber): boolean {
<add> const {tag, type} = fiber;
<add>
<add> switch (tag) {
<add> case ClassComponent:
<add> case IncompleteClassComponent:
<add> const instance = fiber.stateNode;
<add> return (
<add> typeof type.getDerivedStateFromError === 'function' ||
<add> (instance !== null &&
<add> typeof instance.componentDidCatch === 'function')
<add> );
<add> default:
<add> return false;
<add> }
<add> }
<add>
<add> function getNearestErrorBoundaryID(fiber: Fiber): number | null {
<add> let parent = fiber.return;
<add> while (parent !== null) {
<add> if (isErrorBoundary(parent)) {
<add> return getFiberIDUnsafe(parent);
<add> }
<add> parent = parent.return;
<add> }
<add> return null;
<add> }
<add>
<ide> function inspectElementRaw(id: number): InspectedElement | null {
<ide> const fiber = findCurrentFiberUsingSlowPathById(id);
<ide> if (fiber == null) {
<ide> export function attach(
<ide> const errors = fiberIDToErrorsMap.get(id) || new Map();
<ide> const warnings = fiberIDToWarningsMap.get(id) || new Map();
<ide>
<add> const isErrored =
<add> (fiber.flags & DidCapture) !== NoFlags ||
<add> forceErrorForFiberIDs.get(id) === true;
<add>
<add> let targetErrorBoundaryID;
<add> if (isErrorBoundary(fiber)) {
<add> // if the current inspected element is an error boundary,
<add> // either that we want to use it to toggle off error state
<add> // or that we allow to force error state on it if it's within another
<add> // error boundary
<add> targetErrorBoundaryID = isErrored ? id : getNearestErrorBoundaryID(fiber);
<add> } else {
<add> targetErrorBoundaryID = getNearestErrorBoundaryID(fiber);
<add> }
<add>
<ide> return {
<ide> id,
<ide>
<ide> export function attach(
<ide> canEditFunctionPropsRenamePaths:
<ide> typeof overridePropsRenamePath === 'function',
<ide>
<add> canToggleError: supportsTogglingError && targetErrorBoundaryID != null,
<add> // Is this error boundary in error state.
<add> isErrored,
<add> targetErrorBoundaryID,
<add>
<ide> canToggleSuspense:
<ide> supportsTogglingSuspense &&
<ide> // If it's showing the real content, we can always flip fallback.
<ide> export function attach(
<ide> }
<ide>
<ide> // React will switch between these implementations depending on whether
<del> // we have any manually suspended Fibers or not.
<add> // we have any manually suspended/errored-out Fibers or not.
<add> function shouldErrorFiberAlwaysNull() {
<add> return null;
<add> }
<add>
<add> // Map of id and its force error status: true (error), false (toggled off),
<add> // null (do nothing)
<add> const forceErrorForFiberIDs = new Map();
<add> function shouldErrorFiberAccordingToMap(fiber) {
<add> if (typeof setErrorHandler !== 'function') {
<add> throw new Error(
<add> 'Expected overrideError() to not get called for earlier React versions.',
<add> );
<add> }
<add>
<add> const id = getFiberIDUnsafe(fiber);
<add> if (id === null) {
<add> return null;
<add> }
<add>
<add> let status = null;
<add> if (forceErrorForFiberIDs.has(id)) {
<add> status = forceErrorForFiberIDs.get(id);
<add> if (status === false) {
<add> // TRICKY overrideError adds entries to this Map,
<add> // so ideally it would be the method that clears them too,
<add> // but that would break the functionality of the feature,
<add> // since DevTools needs to tell React to act differently than it normally would
<add> // (don't just re-render the failed boundary, but reset its errored state too).
<add> // So we can only clear it after telling React to reset the state.
<add> // Technically this is premature and we should schedule it for later,
<add> // since the render could always fail without committing the updated error boundary,
<add> // but since this is a DEV-only feature, the simplicity is worth the trade off.
<add> forceErrorForFiberIDs.delete(id);
<add>
<add> if (forceErrorForFiberIDs.size === 0) {
<add> // Last override is gone. Switch React back to fast path.
<add> setErrorHandler(shouldErrorFiberAlwaysNull);
<add> }
<add> }
<add> }
<add> return status;
<add> }
<add>
<add> function overrideError(id, forceError) {
<add> if (
<add> typeof setErrorHandler !== 'function' ||
<add> typeof scheduleUpdate !== 'function'
<add> ) {
<add> throw new Error(
<add> 'Expected overrideError() to not get called for earlier React versions.',
<add> );
<add> }
<add>
<add> forceErrorForFiberIDs.set(id, forceError);
<add>
<add> if (forceErrorForFiberIDs.size === 1) {
<add> // First override is added. Switch React to slower path.
<add> setErrorHandler(shouldErrorFiberAccordingToMap);
<add> }
<add>
<add> const fiber = idToArbitraryFiberMap.get(id);
<add> if (fiber != null) {
<add> scheduleUpdate(fiber);
<add> }
<add> }
<ide>
<ide> function shouldSuspendFiberAlwaysFalse() {
<ide> return false;
<ide> export function attach(
<ide> logElementToConsole,
<ide> prepareViewAttributeSource,
<ide> prepareViewElementSource,
<add> overrideError,
<ide> overrideSuspense,
<ide> overrideValueAtPath,
<ide> renamePath,
<ide><path>packages/react-devtools-shared/src/backend/types.js
<ide> export type ReactRenderer = {
<ide> ComponentTree?: any,
<ide> // Present for React DOM v12 (possibly earlier) through v15.
<ide> Mount?: any,
<add> // Only injected by React v17.0.3+ in DEV mode
<add> setErrorHandler?: ?(shouldError: (fiber: Object) => ?boolean) => void,
<ide> ...
<ide> };
<ide>
<ide> export type InspectedElement = {|
<ide> canEditFunctionPropsDeletePaths: boolean,
<ide> canEditFunctionPropsRenamePaths: boolean,
<ide>
<add> // Is this Error, and can its value be overridden now?
<add> canToggleError: boolean,
<add> isErrored: boolean,
<add> targetErrorBoundaryID: ?number,
<add>
<ide> // Is this Suspense, and can its value be overridden now?
<ide> canToggleSuspense: boolean,
<ide>
<ide> export type RendererInterface = {
<ide> inspectedPaths: Object,
<ide> ) => InspectedElementPayload,
<ide> logElementToConsole: (id: number) => void,
<add> overrideError: (id: number, forceError: boolean) => void,
<ide> overrideSuspense: (id: number, forceFallback: boolean) => void,
<ide> overrideValueAtPath: (
<ide> type: Type,
<ide><path>packages/react-devtools-shared/src/backendAPI.js
<ide> export function convertInspectedElementBackendToFrontend(
<ide> canEditHooks,
<ide> canEditHooksAndDeletePaths,
<ide> canEditHooksAndRenamePaths,
<add> canToggleError,
<add> isErrored,
<add> targetErrorBoundaryID,
<ide> canToggleSuspense,
<ide> canViewSource,
<ide> hasLegacyContext,
<ide> export function convertInspectedElementBackendToFrontend(
<ide> canEditHooks,
<ide> canEditHooksAndDeletePaths,
<ide> canEditHooksAndRenamePaths,
<add> canToggleError,
<add> isErrored,
<add> targetErrorBoundaryID,
<ide> canToggleSuspense,
<ide> canViewSource,
<ide> hasLegacyContext,
<ide><path>packages/react-devtools-shared/src/bridge.js
<ide> type OverrideValueAtPath = {|
<ide> value: any,
<ide> |};
<ide>
<add>type OverrideError = {|
<add> ...ElementAndRendererID,
<add> forceError: boolean,
<add>|};
<add>
<ide> type OverrideSuspense = {|
<ide> ...ElementAndRendererID,
<ide> forceFallback: boolean,
<ide> type FrontendEvents = {|
<ide> highlightNativeElement: [HighlightElementInDOM],
<ide> inspectElement: [InspectElementParams],
<ide> logElementToConsole: [ElementAndRendererID],
<add> overrideError: [OverrideError],
<ide> overrideSuspense: [OverrideSuspense],
<ide> overrideValueAtPath: [OverrideValueAtPath],
<ide> profilingData: [ProfilingDataBackend],
<ide><path>packages/react-devtools-shared/src/devtools/views/ButtonIcon.js
<ide> export type IconType =
<ide> | 'save'
<ide> | 'search'
<ide> | 'settings'
<add> | 'error'
<ide> | 'suspend'
<ide> | 'undo'
<ide> | 'up'
<ide> export default function ButtonIcon({className = '', type}: Props) {
<ide> case 'settings':
<ide> pathData = PATH_SETTINGS;
<ide> break;
<add> case 'error':
<add> pathData = PATH_ERROR;
<add> break;
<ide> case 'suspend':
<ide> pathData = PATH_SUSPEND;
<ide> break;
<ide> const PATH_LOG_DATA = `
<ide> `;
<ide>
<ide> const PATH_MORE = `
<del> M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9
<add> M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9
<ide> 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z
<ide> `;
<ide>
<ide> const PATH_SETTINGS = `
<ide> 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z
<ide> `;
<ide>
<add>const PATH_ERROR =
<add> 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z';
<add>
<ide> const PATH_SUSPEND = `
<ide> M15 1H9v2h6V1zm-4 13h2V8h-2v6zm8.03-6.61l1.42-1.42c-.43-.51-.9-.99-1.41-1.41l-1.42 1.42C16.07 4.74 14.12 4 12 4c-4.97
<ide> 0-9 4.03-9 9s4.02 9 9 9 9-4.03 9-9c0-2.12-.74-4.07-1.97-5.61zM12 20c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/InspectedElement.js
<ide> export default function InspectedElementWrapper(_: Props) {
<ide> (canViewElementSourceFunction === null ||
<ide> canViewElementSourceFunction(inspectedElement));
<ide>
<add> const isErrored = inspectedElement != null && inspectedElement.isErrored;
<add> const targetErrorBoundaryID =
<add> inspectedElement != null ? inspectedElement.targetErrorBoundaryID : null;
<add>
<ide> const isSuspended =
<ide> element !== null &&
<ide> element.type === ElementTypeSuspense &&
<ide> inspectedElement != null &&
<ide> inspectedElement.state != null;
<ide>
<add> const canToggleError =
<add> inspectedElement != null && inspectedElement.canToggleError;
<add>
<ide> const canToggleSuspense =
<ide> inspectedElement != null && inspectedElement.canToggleSuspense;
<ide>
<add> const toggleErrored = useCallback(() => {
<add> if (inspectedElement == null || targetErrorBoundaryID == null) {
<add> return;
<add> }
<add>
<add> const rendererID = store.getRendererIDForElement(targetErrorBoundaryID);
<add> if (rendererID !== null) {
<add> if (targetErrorBoundaryID !== inspectedElement.id) {
<add> // Update tree selection so that if we cause a component to error,
<add> // the nearest error boundary will become the newly selected thing.
<add> dispatch({
<add> type: 'SELECT_ELEMENT_BY_ID',
<add> payload: targetErrorBoundaryID,
<add> });
<add> }
<add>
<add> // Toggle error.
<add> bridge.send('overrideError', {
<add> id: targetErrorBoundaryID,
<add> rendererID,
<add> forceError: !isErrored,
<add> });
<add> }
<add> }, [bridge, dispatch, isErrored, targetErrorBoundaryID]);
<add>
<ide> // TODO (suspense toggle) Would be nice to eventually use a two setState pattern here as well.
<ide> const toggleSuspended = useCallback(() => {
<ide> let nearestSuspenseElement = null;
<ide> export default function InspectedElementWrapper(_: Props) {
<ide> </div>
<ide> </div>
<ide>
<add> {canToggleError && (
<add> <Toggle
<add> className={styles.IconButton}
<add> isChecked={isErrored}
<add> onChange={toggleErrored}
<add> title={
<add> isErrored
<add> ? 'Clear the forced error'
<add> : 'Force the selected component into an errored state'
<add> }>
<add> <ButtonIcon type="error" />
<add> </Toggle>
<add> )}
<ide> {canToggleSuspense && (
<ide> <Toggle
<ide> className={styles.IconButton}
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/types.js
<ide> export type InspectedElement = {|
<ide> canEditFunctionPropsDeletePaths: boolean,
<ide> canEditFunctionPropsRenamePaths: boolean,
<ide>
<add> // Is this Error, and can its value be overridden now?
<add> isErrored: boolean,
<add> canToggleError: boolean,
<add> targetErrorBoundaryID: ?number,
<add>
<ide> // Is this Suspense, and can its value be overridden now?
<ide> canToggleSuspense: boolean,
<ide>
<ide><path>packages/react-devtools-shell/src/app/ErrorBoundaries/index.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> */
<add>
<add>import * as React from 'react';
<add>import {Fragment} from 'react';
<add>
<add>class ErrorBoundary extends React.Component {
<add> state = {hasError: false};
<add>
<add> static getDerivedStateFromError(error) {
<add> return {hasError: true};
<add> }
<add>
<add> render() {
<add> const {hasError} = this.state;
<add> if (hasError) {
<add> return (
<add> <div
<add> style={{
<add> color: 'red',
<add> border: '1px solid red',
<add> borderRadius: '0.25rem',
<add> margin: '0.5rem',
<add> padding: '0.5rem',
<add> }}>
<add> An error was thrown.
<add> </div>
<add> );
<add> }
<add>
<add> const {children} = this.props;
<add> return (
<add> <div
<add> style={{
<add> border: '1px solid gray',
<add> borderRadius: '0.25rem',
<add> margin: '0.5rem',
<add> padding: '0.5rem',
<add> }}>
<add> {children}
<add> </div>
<add> );
<add> }
<add>}
<add>
<add>function Component({label}) {
<add> return <div>{label}</div>;
<add>}
<add>
<add>export default function ErrorBoundaries() {
<add> return (
<add> <Fragment>
<add> <h1>Nested error boundaries demo</h1>
<add> <ErrorBoundary>
<add> <Component label="Outer component" />
<add> <ErrorBoundary>
<add> <Component label="Inner component" />
<add> </ErrorBoundary>
<add> </ErrorBoundary>
<add> <ErrorBoundary>
<add> <Component label="Neighbour component" />
<add> </ErrorBoundary>
<add> </Fragment>
<add> );
<add>}
<ide><path>packages/react-devtools-shell/src/app/index.js
<ide> import InspectableElements from './InspectableElements';
<ide> import ReactNativeWeb from './ReactNativeWeb';
<ide> import ToDoList from './ToDoList';
<ide> import Toggle from './Toggle';
<add>import ErrorBoundaries from './ErrorBoundaries';
<ide> import SuspenseTree from './SuspenseTree';
<ide> import {ignoreErrors, ignoreWarnings} from './console';
<ide>
<ide> function mountTestApp() {
<ide> mountHelper(InlineWarnings);
<ide> mountHelper(ReactNativeWeb);
<ide> mountHelper(Toggle);
<add> mountHelper(ErrorBoundaries);
<ide> mountHelper(SuspenseTree);
<ide> mountHelper(DeeplyNestedComponents);
<ide> mountHelper(Iframe);
<ide><path>packages/react-reconciler/src/ReactFiberBeginWork.new.js
<ide> import {
<ide> ChildDeletion,
<ide> ForceUpdateForLegacySuspense,
<ide> StaticMask,
<add> ShouldCapture,
<ide> } from './ReactFiberFlags';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> import {
<ide> import {
<ide> processUpdateQueue,
<ide> cloneUpdateQueue,
<ide> initializeUpdateQueue,
<add> enqueueCapturedUpdate,
<ide> } from './ReactUpdateQueue.new';
<ide> import {
<ide> NoLane,
<ide> import {
<ide> removeLanes,
<ide> mergeLanes,
<ide> getBumpedLaneForHydration,
<add> pickArbitraryLane,
<ide> } from './ReactFiberLane.new';
<ide> import {
<ide> ConcurrentMode,
<ide> import {
<ide> isPrimaryRenderer,
<ide> } from './ReactFiberHostConfig';
<ide> import type {SuspenseInstance} from './ReactFiberHostConfig';
<del>import {shouldSuspend} from './ReactFiberReconciler';
<add>import {shouldError, shouldSuspend} from './ReactFiberReconciler';
<ide> import {pushHostContext, pushHostContainer} from './ReactFiberHostContext.new';
<ide> import {
<ide> suspenseStackCursor,
<ide> import {
<ide> restoreSpawnedCachePool,
<ide> getOffscreenDeferredCachePool,
<ide> } from './ReactFiberCacheComponent.new';
<add>import {createCapturedValue} from './ReactCapturedValue';
<add>import {createClassErrorUpdate} from './ReactFiberThrow.new';
<ide> import is from 'shared/objectIs';
<ide>
<ide> import {disableLogs, reenableLogs} from 'shared/ConsolePatchingDev';
<ide> function updateClassComponent(
<ide> renderLanes: Lanes,
<ide> ) {
<ide> if (__DEV__) {
<add> // This is used by DevTools to force a boundary to error.
<add> switch (shouldError(workInProgress)) {
<add> case false: {
<add> const instance = workInProgress.stateNode;
<add> const ctor = workInProgress.type;
<add> // TODO This way of resetting the error boundary state is a hack.
<add> // Is there a better way to do this?
<add> const tempInstance = new ctor(
<add> workInProgress.memoizedProps,
<add> instance.context,
<add> );
<add> const state = tempInstance.state;
<add> instance.updater.enqueueSetState(instance, state, null);
<add> break;
<add> }
<add> case true: {
<add> workInProgress.flags |= DidCapture;
<add> workInProgress.flags |= ShouldCapture;
<add> const error = new Error('Simulated error coming from DevTools');
<add> const lane = pickArbitraryLane(renderLanes);
<add> workInProgress.lanes = mergeLanes(workInProgress.lanes, lane);
<add> // Schedule the error boundary to re-render using updated state
<add> const update = createClassErrorUpdate(
<add> workInProgress,
<add> createCapturedValue(error, workInProgress),
<add> lane,
<add> );
<add> enqueueCapturedUpdate(workInProgress, update);
<add> break;
<add> }
<add> }
<add>
<ide> if (workInProgress.type !== workInProgress.elementType) {
<ide> // Lazy component props can't be validated in createElement
<ide> // because they're only guaranteed to be resolved here.
<ide><path>packages/react-reconciler/src/ReactFiberBeginWork.old.js
<ide> import {
<ide> ChildDeletion,
<ide> ForceUpdateForLegacySuspense,
<ide> StaticMask,
<add> ShouldCapture,
<ide> } from './ReactFiberFlags';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> import {
<ide> import {
<ide> processUpdateQueue,
<ide> cloneUpdateQueue,
<ide> initializeUpdateQueue,
<add> enqueueCapturedUpdate,
<ide> } from './ReactUpdateQueue.old';
<ide> import {
<ide> NoLane,
<ide> import {
<ide> removeLanes,
<ide> mergeLanes,
<ide> getBumpedLaneForHydration,
<add> pickArbitraryLane,
<ide> } from './ReactFiberLane.old';
<ide> import {
<ide> ConcurrentMode,
<ide> import {
<ide> isPrimaryRenderer,
<ide> } from './ReactFiberHostConfig';
<ide> import type {SuspenseInstance} from './ReactFiberHostConfig';
<del>import {shouldSuspend} from './ReactFiberReconciler';
<add>import {shouldError, shouldSuspend} from './ReactFiberReconciler';
<ide> import {pushHostContext, pushHostContainer} from './ReactFiberHostContext.old';
<ide> import {
<ide> suspenseStackCursor,
<ide> import {
<ide> restoreSpawnedCachePool,
<ide> getOffscreenDeferredCachePool,
<ide> } from './ReactFiberCacheComponent.old';
<add>import {createCapturedValue} from './ReactCapturedValue';
<add>import {createClassErrorUpdate} from './ReactFiberThrow.old';
<ide> import is from 'shared/objectIs';
<ide>
<ide> import {disableLogs, reenableLogs} from 'shared/ConsolePatchingDev';
<ide> function updateClassComponent(
<ide> renderLanes: Lanes,
<ide> ) {
<ide> if (__DEV__) {
<add> // This is used by DevTools to force a boundary to error.
<add> switch (shouldError(workInProgress)) {
<add> case false: {
<add> const instance = workInProgress.stateNode;
<add> const ctor = workInProgress.type;
<add> // TODO This way of resetting the error boundary state is a hack.
<add> // Is there a better way to do this?
<add> const tempInstance = new ctor(
<add> workInProgress.memoizedProps,
<add> instance.context,
<add> );
<add> const state = tempInstance.state;
<add> instance.updater.enqueueSetState(instance, state, null);
<add> break;
<add> }
<add> case true: {
<add> workInProgress.flags |= DidCapture;
<add> workInProgress.flags |= ShouldCapture;
<add> const error = new Error('Simulated error coming from DevTools');
<add> const lane = pickArbitraryLane(renderLanes);
<add> workInProgress.lanes = mergeLanes(workInProgress.lanes, lane);
<add> // Schedule the error boundary to re-render using updated state
<add> const update = createClassErrorUpdate(
<add> workInProgress,
<add> createCapturedValue(error, workInProgress),
<add> lane,
<add> );
<add> enqueueCapturedUpdate(workInProgress, update);
<add> break;
<add> }
<add> }
<add>
<ide> if (workInProgress.type !== workInProgress.elementType) {
<ide> // Lazy component props can't be validated in createElement
<ide> // because they're only guaranteed to be resolved here.
<ide><path>packages/react-reconciler/src/ReactFiberReconciler.js
<ide> import {
<ide> findHostInstance as findHostInstance_old,
<ide> findHostInstanceWithWarning as findHostInstanceWithWarning_old,
<ide> findHostInstanceWithNoPortals as findHostInstanceWithNoPortals_old,
<add> shouldError as shouldError_old,
<ide> shouldSuspend as shouldSuspend_old,
<ide> injectIntoDevTools as injectIntoDevTools_old,
<ide> act as act_old,
<ide> import {
<ide> findHostInstance as findHostInstance_new,
<ide> findHostInstanceWithWarning as findHostInstanceWithWarning_new,
<ide> findHostInstanceWithNoPortals as findHostInstanceWithNoPortals_new,
<add> shouldError as shouldError_new,
<ide> shouldSuspend as shouldSuspend_new,
<ide> injectIntoDevTools as injectIntoDevTools_new,
<ide> act as act_new,
<ide> export const findHostInstanceWithWarning = enableNewReconciler
<ide> export const findHostInstanceWithNoPortals = enableNewReconciler
<ide> ? findHostInstanceWithNoPortals_new
<ide> : findHostInstanceWithNoPortals_old;
<add>export const shouldError = enableNewReconciler
<add> ? shouldError_new
<add> : shouldError_old;
<ide> export const shouldSuspend = enableNewReconciler
<ide> ? shouldSuspend_new
<ide> : shouldSuspend_old;
<ide><path>packages/react-reconciler/src/ReactFiberReconciler.new.js
<ide> export function findHostInstanceWithNoPortals(
<ide> return hostFiber.stateNode;
<ide> }
<ide>
<add>let shouldErrorImpl = fiber => null;
<add>
<add>export function shouldError(fiber: Fiber): ?boolean {
<add> return shouldErrorImpl(fiber);
<add>}
<add>
<ide> let shouldSuspendImpl = fiber => false;
<ide>
<ide> export function shouldSuspend(fiber: Fiber): boolean {
<ide> let overrideProps = null;
<ide> let overridePropsDeletePath = null;
<ide> let overridePropsRenamePath = null;
<ide> let scheduleUpdate = null;
<add>let setErrorHandler = null;
<ide> let setSuspenseHandler = null;
<ide>
<ide> if (__DEV__) {
<ide> if (__DEV__) {
<ide> scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
<ide> };
<ide>
<add> setErrorHandler = (newShouldErrorImpl: Fiber => ?boolean) => {
<add> shouldErrorImpl = newShouldErrorImpl;
<add> };
<add>
<ide> setSuspenseHandler = (newShouldSuspendImpl: Fiber => boolean) => {
<ide> shouldSuspendImpl = newShouldSuspendImpl;
<ide> };
<ide> export function injectIntoDevTools(devToolsConfig: DevToolsConfig): boolean {
<ide> overrideProps,
<ide> overridePropsDeletePath,
<ide> overridePropsRenamePath,
<add> setErrorHandler,
<ide> setSuspenseHandler,
<ide> scheduleUpdate,
<ide> currentDispatcherRef: ReactCurrentDispatcher,
<ide><path>packages/react-reconciler/src/ReactFiberReconciler.old.js
<ide> export function findHostInstanceWithNoPortals(
<ide> return hostFiber.stateNode;
<ide> }
<ide>
<add>let shouldErrorImpl = fiber => null;
<add>
<add>export function shouldError(fiber: Fiber): ?boolean {
<add> return shouldErrorImpl(fiber);
<add>}
<add>
<ide> let shouldSuspendImpl = fiber => false;
<ide>
<ide> export function shouldSuspend(fiber: Fiber): boolean {
<ide> let overrideProps = null;
<ide> let overridePropsDeletePath = null;
<ide> let overridePropsRenamePath = null;
<ide> let scheduleUpdate = null;
<add>let setErrorHandler = null;
<ide> let setSuspenseHandler = null;
<ide>
<ide> if (__DEV__) {
<ide> if (__DEV__) {
<ide> scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
<ide> };
<ide>
<add> setErrorHandler = (newShouldErrorImpl: Fiber => ?boolean) => {
<add> shouldErrorImpl = newShouldErrorImpl;
<add> };
<add>
<ide> setSuspenseHandler = (newShouldSuspendImpl: Fiber => boolean) => {
<ide> shouldSuspendImpl = newShouldSuspendImpl;
<ide> };
<ide> export function injectIntoDevTools(devToolsConfig: DevToolsConfig): boolean {
<ide> overrideProps,
<ide> overridePropsDeletePath,
<ide> overridePropsRenamePath,
<add> setErrorHandler,
<ide> setSuspenseHandler,
<ide> scheduleUpdate,
<ide> currentDispatcherRef: ReactCurrentDispatcher, | 18 |
Javascript | Javascript | fix missing tooltip value in radar charts | 89af7b1383fffd477e0f6245770920e36450ac58 | <ide><path>src/controllers/controller.radar.js
<ide> defaults._set('radar', {
<ide> });
<ide>
<ide> module.exports = DatasetController.extend({
<add> /**
<add> * @private
<add> */
<add> _getValueScaleId: function() {
<add> return this.chart.scale.id;
<add> },
<add>
<add> /**
<add> * @private
<add> */
<add> _getIndexScaleId: function() {
<add> return this.chart.scale.id;
<add> },
<ide>
<ide> datasetElementType: elements.Line,
<ide>
<ide><path>test/specs/controller.radar.tests.js
<ide> describe('Chart.controllers.radar', function() {
<ide> expect(meta0.data[0]._model.radius).toBe(10);
<ide> expect(meta1.data[0]._model.radius).toBe(20);
<ide> });
<add>
<add> it('should return same id for index and value scale', function() {
<add> var chart = window.acquireChart({
<add> type: 'radar',
<add> data: {
<add> datasets: [{
<add> data: [10, 15, 0, 4],
<add> pointBorderWidth: 0
<add> }],
<add> labels: ['label1', 'label2', 'label3', 'label4']
<add> },
<add> options: {
<add> scale: {id: 'test'}
<add> }
<add> });
<add>
<add> var controller = chart.getDatasetMeta(0).controller;
<add> expect(controller._getIndexScaleId()).toBe('test');
<add> expect(controller._getValueScaleId()).toBe('test');
<add> });
<ide> }); | 2 |
PHP | PHP | improve api docs for http client authentication | 34a6ec7d6025b4b108c40646754e6e856cf0ad83 | <ide><path>src/Http/Client.php
<ide> class Client implements ClientInterface
<ide> * @var array<string, mixed>
<ide> */
<ide> protected $_defaultConfig = [
<add> 'auth' => null,
<ide> 'adapter' => null,
<ide> 'host' => null,
<ide> 'port' => null,
<ide> class Client implements ClientInterface
<ide> * \Cake\Http\Client\Adapter\Curl if `curl` extension is loaded else
<ide> * \Cake\Http\Client\Adapter\Stream.
<ide> * - protocolVersion - The HTTP protocol version to use. Defaults to 1.1
<add> * - auth - The authentication credentials to use. If a `username` and `password`
<add> * key are provided without a `type` key Basic authentication will be assumed.
<add> * You can use the `type` key to define the authentication adapter classname
<add> * to use. Short class names are resolved to the `Http\Client\Auth` namespace.
<ide> *
<ide> * @param array<string, mixed> $config Config options for scoped clients.
<ide> * @throws \InvalidArgumentException | 1 |
Javascript | Javascript | update serialized format to new glimmer-vm output | 0627ae68cbbfbc7179f39ad0ed7eee670d5f371a | <ide><path>packages/ember-application/tests/system/visit_test.js
<ide> moduleFor('Application - visit()', class extends ApplicationTestCase {
<ide>
<ide> [`@test _renderMode: rehydrate`](assert) {
<ide>
<del> let initialHTML = `<!--%+block:0%--><!--%+block:1%--><!--%+block:2%--><!--%+block:3%--><!--%+block:4%--><!--%+block:5%--><!--%+block:6%--><div class=\"foo\">Hi, Mom!</div><!--%-block:6%--><!--%-block:5%--><!--%-block:4%--><!--%-block:3%--><!--%-block:2%--><!--%-block:1%--><!--%-block:0%-->`;
<add> let initialHTML = `<!--%+b:0%--><!--%+b:1%--><!--%+b:2%--><!--%+b:3%--><!--%+b:4%--><!--%+b:5%--><!--%+b:6%--><div class=\"foo\">Hi, Mom!</div><!--%-b:6%--><!--%-b:5%--><!--%-b:4%--><!--%-b:3%--><!--%-b:2%--><!--%-b:1%--><!--%-b:0%-->`;
<ide>
<ide> this.addTemplate('index', '<div class="foo">Hi, Mom!</div>');
<ide> let rootElement = document.createElement('div');
<ide> moduleFor('Application - visit()', class extends ApplicationTestCase {
<ide> return this.visit('/', bootOptions).then(()=> {
<ide> // The exact contents of this may change when the underlying
<ide> // implementation changes in the glimmer vm
<del> let expectedTemplate = `<!--%+block:0%--><!--%+block:1%--><!--%+block:2%--><!--%+block:3%--><!--%+block:4%--><!--%+block:5%--><!--%+block:6%--><div class=\"foo\">Hi, Mom!</div><!--%-block:6%--><!--%-block:5%--><!--%-block:4%--><!--%-block:3%--><!--%-block:2%--><!--%-block:1%--><!--%-block:0%-->`;
<add> let expectedTemplate = `<!--%+b:0%--><!--%+b:1%--><!--%+b:2%--><!--%+b:3%--><!--%+b:4%--><!--%+b:5%--><!--%+b:6%--><div class=\"foo\">Hi, Mom!</div><!--%-b:6%--><!--%-b:5%--><!--%-b:4%--><!--%-b:3%--><!--%-b:2%--><!--%-b:1%--><!--%-b:0%-->`;
<ide> assert.equal(rootElement.innerHTML, expectedTemplate, 'precond - without serialize flag renders as expected');
<ide> });
<ide> } | 1 |
Javascript | Javascript | reset hydration state after reentering | 6f3c8332d8b2f92784a731e6cc6a707a92495a23 | <ide><path>packages/react-dom/src/__tests__/ReactDOMServerPartialHydration-test.internal.js
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> expect(container.lastChild.nodeType).toBe(8);
<ide> expect(container.lastChild.data).toBe('unrelated comment');
<ide> });
<add>
<add> it('can hydrate TWO suspense boundaries', async () => {
<add> let ref1 = React.createRef();
<add> let ref2 = React.createRef();
<add>
<add> function App() {
<add> return (
<add> <div>
<add> <Suspense fallback="Loading 1...">
<add> <span ref={ref1}>1</span>
<add> </Suspense>
<add> <Suspense fallback="Loading 2...">
<add> <span ref={ref2}>2</span>
<add> </Suspense>
<add> </div>
<add> );
<add> }
<add>
<add> // First we render the final HTML. With the streaming renderer
<add> // this may have suspense points on the server but here we want
<add> // to test the completed HTML. Don't suspend on the server.
<add> let finalHTML = ReactDOMServer.renderToString(<App />);
<add>
<add> let container = document.createElement('div');
<add> container.innerHTML = finalHTML;
<add>
<add> let span1 = container.getElementsByTagName('span')[0];
<add> let span2 = container.getElementsByTagName('span')[1];
<add>
<add> // On the client we don't have all data yet but we want to start
<add> // hydrating anyway.
<add> let root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<add> root.render(<App />);
<add> Scheduler.unstable_flushAll();
<add> jest.runAllTimers();
<add>
<add> expect(ref1.current).toBe(span1);
<add> expect(ref2.current).toBe(span2);
<add> });
<ide> });
<ide><path>packages/react-reconciler/src/ReactFiberBeginWork.js
<ide> import {
<ide> reenterHydrationStateFromDehydratedSuspenseInstance,
<ide> resetHydrationState,
<ide> tryToClaimNextHydratableInstance,
<add> warnIfHydrating,
<ide> } from './ReactFiberHydrationContext';
<ide> import {
<ide> adoptClassInstance,
<ide> function updateDehydratedSuspenseComponent(
<ide> }
<ide> return null;
<ide> }
<add>
<ide> if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
<ide> // Something suspended. Leave the existing children in place.
<ide> // TODO: In non-concurrent mode, should we commit the nodes we have hydrated so far?
<ide> workInProgress.child = null;
<ide> return null;
<ide> }
<add>
<add> // We should never be hydrating at this point because it is the first pass,
<add> // but after we've already committed once.
<add> warnIfHydrating();
<add>
<ide> if (isSuspenseInstanceFallback(suspenseInstance)) {
<ide> // This boundary is in a permanent fallback state. In this case, we'll never
<ide> // get an update and we'll never be able to hydrate the final content. Let's just try the
<ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.js
<ide> import {
<ide> prepareToHydrateHostTextInstance,
<ide> skipPastDehydratedSuspenseInstance,
<ide> popHydrationState,
<add> resetHydrationState,
<ide> } from './ReactFiberHydrationContext';
<ide> import {
<ide> enableSchedulerTracing,
<ide> function completeWork(
<ide> markSpawnedWork(Never);
<ide> }
<ide> skipPastDehydratedSuspenseInstance(workInProgress);
<del> } else if ((workInProgress.effectTag & DidCapture) === NoEffect) {
<del> // This boundary did not suspend so it's now hydrated.
<del> // To handle any future suspense cases, we're going to now upgrade it
<del> // to a Suspense component. We detach it from the existing current fiber.
<del> current.alternate = null;
<del> workInProgress.alternate = null;
<del> workInProgress.tag = SuspenseComponent;
<del> workInProgress.memoizedState = null;
<del> workInProgress.stateNode = null;
<add> } else {
<add> // We should never have been in a hydration state if we didn't have a current.
<add> // However, in some of those paths, we might have reentered a hydration state
<add> // and then we might be inside a hydration state. In that case, we'll need to
<add> // exit out of it.
<add> resetHydrationState();
<add> if ((workInProgress.effectTag & DidCapture) === NoEffect) {
<add> // This boundary did not suspend so it's now hydrated.
<add> // To handle any future suspense cases, we're going to now upgrade it
<add> // to a Suspense component. We detach it from the existing current fiber.
<add> current.alternate = null;
<add> workInProgress.alternate = null;
<add> workInProgress.tag = SuspenseComponent;
<add> workInProgress.memoizedState = null;
<add> workInProgress.stateNode = null;
<add> }
<ide> }
<ide> }
<ide> break;
<ide><path>packages/react-reconciler/src/ReactFiberHydrationContext.js
<ide> import {
<ide> didNotFindHydratableSuspenseInstance,
<ide> } from './ReactFiberHostConfig';
<ide> import {enableSuspenseServerRenderer} from 'shared/ReactFeatureFlags';
<add>import warning from 'shared/warning';
<ide>
<ide> // The deepest Fiber on the stack involved in a hydration context.
<ide> // This may have been an insertion or a hydration.
<ide> let hydrationParentFiber: null | Fiber = null;
<ide> let nextHydratableInstance: null | HydratableInstance = null;
<ide> let isHydrating: boolean = false;
<ide>
<add>function warnIfHydrating() {
<add> if (__DEV__) {
<add> warning(
<add> !isHydrating,
<add> 'We should not be hydrating here. This is a bug in React. Please file a bug.',
<add> );
<add> }
<add>}
<add>
<ide> function enterHydrationState(fiber: Fiber): boolean {
<ide> if (!supportsHydration) {
<ide> return false;
<ide> function resetHydrationState(): void {
<ide> }
<ide>
<ide> export {
<add> warnIfHydrating,
<ide> enterHydrationState,
<ide> reenterHydrationStateFromDehydratedSuspenseInstance,
<ide> resetHydrationState,
<ide><path>packages/react-reconciler/src/ReactFiberUnwindWork.js
<ide> import {enableSuspenseServerRenderer} from 'shared/ReactFeatureFlags';
<ide>
<ide> import {popHostContainer, popHostContext} from './ReactFiberHostContext';
<ide> import {popSuspenseContext} from './ReactFiberSuspenseContext';
<add>import {resetHydrationState} from './ReactFiberHydrationContext';
<ide> import {
<ide> isContextProvider as isLegacyContextProvider,
<ide> popContext as popLegacyContext,
<ide> function unwindWork(
<ide> }
<ide> case DehydratedSuspenseComponent: {
<ide> if (enableSuspenseServerRenderer) {
<del> // TODO: popHydrationState
<ide> popSuspenseContext(workInProgress);
<add> if (workInProgress.alternate === null) {
<add> // TODO: popHydrationState
<add> } else {
<add> resetHydrationState();
<add> }
<ide> const effectTag = workInProgress.effectTag;
<ide> if (effectTag & ShouldCapture) {
<ide> workInProgress.effectTag = (effectTag & ~ShouldCapture) | DidCapture;
<ide> function unwindInterruptedWork(interruptedWork: Fiber) {
<ide> break;
<ide> case DehydratedSuspenseComponent:
<ide> if (enableSuspenseServerRenderer) {
<del> // TODO: popHydrationState
<ide> popSuspenseContext(interruptedWork);
<ide> }
<ide> break; | 5 |
Javascript | Javascript | define ember.coreobject#willdestroy. fixes | 711740794ec5cebd20f3783f723ba5ce4d30570a | <ide><path>packages/ember-runtime/lib/system/core_object.js
<ide> CoreObject.PrototypeMixin = Mixin.create({
<ide> return this;
<ide> },
<ide>
<add> willDestroy: Ember.K,
<add>
<ide> /**
<ide> @private
<ide> | 1 |
Javascript | Javascript | simplify flushing mechanism | e688fe6b7e60d3dd50f0aa922a1ab74d85cb39b5 | <ide><path>lib/zlib.js
<ide> function Zlib(opts, mode) {
<ide> this._level = level;
<ide> this._strategy = strategy;
<ide> this._chunkSize = chunkSize;
<del> this._flushFlag = flush;
<del> this._scheduledFlushFlag = Z_NO_FLUSH;
<del> this._origFlushFlag = flush;
<add> this._defaultFlushFlag = flush;
<ide> this._finishFlushFlag = finishFlush;
<add> this._nextFlush = -1;
<ide> this._info = opts && opts.info;
<ide> this.once('end', this.close);
<ide> }
<ide> function maxFlush(a, b) {
<ide> return flushiness[a] > flushiness[b] ? a : b;
<ide> }
<ide>
<add>const flushBuffer = Buffer.alloc(0);
<ide> Zlib.prototype.flush = function flush(kind, callback) {
<ide> var ws = this._writableState;
<ide>
<ide> Zlib.prototype.flush = function flush(kind, callback) {
<ide> } else if (ws.ending) {
<ide> if (callback)
<ide> this.once('end', callback);
<del> } else if (ws.needDrain) {
<del> const alreadyHadFlushScheduled = this._scheduledFlushFlag !== Z_NO_FLUSH;
<del> this._scheduledFlushFlag = maxFlush(kind, this._scheduledFlushFlag);
<del>
<del> // If a callback was passed, always register a new `drain` + flush handler,
<del> // mostly because that's simpler and flush callbacks piling up is a rare
<del> // thing anyway.
<del> if (!alreadyHadFlushScheduled || callback) {
<del> const drainHandler = () => this.flush(this._scheduledFlushFlag, callback);
<del> this.once('drain', drainHandler);
<del> }
<add> } else if (this._nextFlush !== -1) {
<add> // This means that there is a flush currently in the write queue.
<add> // We currently coalesce this flush into the pending one.
<add> this._nextFlush = maxFlush(this._nextFlush, kind);
<ide> } else {
<del> this._flushFlag = kind;
<del> this.write(Buffer.alloc(0), '', callback);
<del> this._scheduledFlushFlag = Z_NO_FLUSH;
<add> this._nextFlush = kind;
<add> this.write(flushBuffer, '', callback);
<ide> }
<ide> };
<ide>
<ide> Zlib.prototype.close = function close(callback) {
<ide> };
<ide>
<ide> Zlib.prototype._transform = function _transform(chunk, encoding, cb) {
<del> // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag
<del> // (or whatever flag was provided using opts.finishFlush).
<del> // If it's explicitly flushing at some other time, then we use
<del> // Z_FULL_FLUSH. Otherwise, use the original opts.flush flag.
<del> var flushFlag;
<add> var flushFlag = this._defaultFlushFlag;
<add> // We use a 'fake' zero-length chunk to carry information about flushes from
<add> // the public API to the actual stream implementation.
<add> if (chunk === flushBuffer) {
<add> flushFlag = this._nextFlush;
<add> this._nextFlush = -1;
<add> }
<add>
<add> // For the last chunk, also apply `_finishFlushFlag`.
<ide> var ws = this._writableState;
<ide> if ((ws.ending || ws.ended) && ws.length === chunk.byteLength) {
<del> flushFlag = this._finishFlushFlag;
<del> } else {
<del> flushFlag = this._flushFlag;
<del> // once we've flushed the last of the queue, stop flushing and
<del> // go back to the normal behavior.
<del> if (chunk.byteLength >= ws.length)
<del> this._flushFlag = this._origFlushFlag;
<add> flushFlag = maxFlush(flushFlag, this._finishFlushFlag);
<ide> }
<ide> processChunk(this, chunk, flushFlag, cb);
<ide> };
<ide><path>test/parallel/test-zlib-flush-drain.js
<ide> process.once('exit', function() {
<ide> assert.strictEqual(
<ide> drainCount, 1);
<ide> assert.strictEqual(
<del> flushCount, 2);
<add> flushCount, 1);
<ide> });
<ide><path>test/parallel/test-zlib-write-after-flush.js
<ide> gunz.setEncoding('utf8');
<ide> gunz.on('data', (c) => output += c);
<ide> gunz.on('end', common.mustCall(() => {
<ide> assert.strictEqual(output, input);
<del> assert.strictEqual(gzip._flushFlag, zlib.constants.Z_NO_FLUSH);
<add> assert.strictEqual(gzip._nextFlush, -1);
<ide> }));
<ide>
<ide> // make sure that flush/write doesn't trigger an assert failure | 3 |
Python | Python | release version 2.1.1 | c6f297719e43380011e76ad6d070b7a27d4d1dce | <ide><path>src/flask/__init__.py
<ide> from .templating import render_template as render_template
<ide> from .templating import render_template_string as render_template_string
<ide>
<del>__version__ = "2.1.1.dev0"
<add>__version__ = "2.1.1" | 1 |
Java | Java | add api to register collection converters | 0579e61a653ea81a3a5ef3dffd94fb5c4579028d | <ide><path>spring-core/src/main/java/org/springframework/core/convert/support/DefaultConversionService.java
<ide> public static void addDefaultConverters(ConverterRegistry converterRegistry) {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Add collection converters.
<add> * @param converterRegistry the registry of converters to add to (must also be castable to ConversionService,
<add> * e.g. being a {@link ConfigurableConversionService})
<add> * @throws ClassCastException if the given ConverterRegistry could not be cast to a ConversionService
<add> * @since 4.2.3
<add> */
<add> public static void addCollectionConverters(ConverterRegistry converterRegistry) {
<add> ConversionService conversionService = (ConversionService) converterRegistry;
<add>
<add> converterRegistry.addConverter(new ArrayToCollectionConverter(conversionService));
<add> converterRegistry.addConverter(new CollectionToArrayConverter(conversionService));
<add>
<add> converterRegistry.addConverter(new ArrayToArrayConverter(conversionService));
<add> converterRegistry.addConverter(new CollectionToCollectionConverter(conversionService));
<add> converterRegistry.addConverter(new MapToMapConverter(conversionService));
<add>
<add> converterRegistry.addConverter(new ArrayToStringConverter(conversionService));
<add> converterRegistry.addConverter(new StringToArrayConverter(conversionService));
<add>
<add> converterRegistry.addConverter(new ArrayToObjectConverter(conversionService));
<add> converterRegistry.addConverter(new ObjectToArrayConverter(conversionService));
<add>
<add> converterRegistry.addConverter(new CollectionToStringConverter(conversionService));
<add> converterRegistry.addConverter(new StringToCollectionConverter(conversionService));
<add>
<add> converterRegistry.addConverter(new CollectionToObjectConverter(conversionService));
<add> converterRegistry.addConverter(new ObjectToCollectionConverter(conversionService));
<add>
<add> if (streamAvailable) {
<add> converterRegistry.addConverter(new StreamConverter(conversionService));
<add> }
<add> }
<add>
<add>
<ide> // internal helpers
<ide>
<ide> private static void addScalarConverters(ConverterRegistry converterRegistry) {
<ide> private static void addScalarConverters(ConverterRegistry converterRegistry) {
<ide> converterRegistry.addConverter(UUID.class, String.class, new ObjectToStringConverter());
<ide> }
<ide>
<del> private static void addCollectionConverters(ConverterRegistry converterRegistry) {
<del> ConversionService conversionService = (ConversionService) converterRegistry;
<del>
<del> converterRegistry.addConverter(new ArrayToCollectionConverter(conversionService));
<del> converterRegistry.addConverter(new CollectionToArrayConverter(conversionService));
<del>
<del> converterRegistry.addConverter(new ArrayToArrayConverter(conversionService));
<del> converterRegistry.addConverter(new CollectionToCollectionConverter(conversionService));
<del> converterRegistry.addConverter(new MapToMapConverter(conversionService));
<del>
<del> converterRegistry.addConverter(new ArrayToStringConverter(conversionService));
<del> converterRegistry.addConverter(new StringToArrayConverter(conversionService));
<del>
<del> converterRegistry.addConverter(new ArrayToObjectConverter(conversionService));
<del> converterRegistry.addConverter(new ObjectToArrayConverter(conversionService));
<del>
<del> converterRegistry.addConverter(new CollectionToStringConverter(conversionService));
<del> converterRegistry.addConverter(new StringToCollectionConverter(conversionService));
<del>
<del> converterRegistry.addConverter(new CollectionToObjectConverter(conversionService));
<del> converterRegistry.addConverter(new ObjectToCollectionConverter(conversionService));
<del>
<del> if (streamAvailable) {
<del> converterRegistry.addConverter(new StreamConverter(conversionService));
<del> }
<del> }
<del>
<ide>
<ide> /**
<ide> * Inner class to avoid a hard-coded dependency on Java 8's {@code java.time} package. | 1 |
Javascript | Javascript | add a clear error when renderers clash in tests | 0442e8275f02d500cdc2e8b8b703286a67d7ad1d | <ide><path>scripts/jest/setupHostConfigs.js
<ide> inlinedHostConfigs.forEach(rendererInfo => {
<ide> return;
<ide> }
<ide> jest.mock(`react-reconciler/inline.${rendererInfo.shortName}`, () => {
<del> jest.mock(shimHostConfigPath, () =>
<del> require.requireActual(
<add> let hasImportedShimmedConfig = false;
<add>
<add> // We want the reconciler to pick up the host config for this renderer.
<add> jest.mock(shimHostConfigPath, () => {
<add> hasImportedShimmedConfig = true;
<add> return require.requireActual(
<ide> `react-reconciler/src/forks/ReactFiberHostConfig.${
<ide> rendererInfo.shortName
<ide> }.js`
<del> )
<del> );
<del> return require.requireActual('react-reconciler');
<add> );
<add> });
<add>
<add> const renderer = require.requireActual('react-reconciler');
<add> // If the shimmed config factory function above has not run,
<add> // it means this test file loads more than one renderer
<add> // but doesn't reset modules between them. This won't work.
<add> if (!hasImportedShimmedConfig) {
<add> throw new Error(
<add> `Could not import the "${rendererInfo.shortName}" renderer ` +
<add> `in this suite because another renderer has already been ` +
<add> `loaded earlier. Call jest.resetModules() before importing any ` +
<add> `of the following entry points:\n\n` +
<add> rendererInfo.entryPoints.map(entry => ` * ${entry}`)
<add> );
<add> }
<add>
<add> return renderer;
<ide> });
<ide> }); | 1 |
Javascript | Javascript | remove unused code in module.js | 3b9cc424a4240c10003dca71c5a7478232e3d0d8 | <ide><path>lib/module.js
<ide> function readPackage(requestPath) {
<ide> return false;
<ide> }
<ide>
<del> if (json === '')
<del> return packageMainCache[requestPath] = undefined;
<del>
<ide> try {
<ide> var pkg = packageMainCache[requestPath] = JSON.parse(json).main;
<ide> } catch (e) { | 1 |
Javascript | Javascript | add makerist app | 9e8f194dffb8069b2647b6ccad9124a42583040c | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> link: 'https://itunes.apple.com/us/app/lumpen-radio/id1002193127?mt=8',
<ide> author: 'Joshua Habdas',
<ide> },
<add> {
<add> name: 'Makerist Mediathek',
<add> icon: 'http://a5.mzstatic.com/eu/r30/Purple3/v4/fa/5f/4c/fa5f4ce8-5aaa-5a4b-ddcc-a0c6f681d08a/icon175x175.png',
<add> link: 'https://itunes.apple.com/de/app/makerist-mediathek/id1019504544',
<add> author: 'Railslove',
<add> },
<ide> {
<ide> name: 'MinTrain',
<ide> icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple5/v4/51/51/68/51516875-1323-3100-31a8-cd1853d9a2c0/mzl.gozwmstp.png', | 1 |
Javascript | Javascript | add filtering to e2e tests | 34ee8250b5f81ebf79f9903aa4868c6c0d0d9959 | <ide><path>RNTester/e2e/__tests__/Button-test.js
<ide> */
<ide>
<ide> /* global device, element, by, expect */
<add>const {
<add> openComponentWithLabel,
<add> openExampleWithTitle,
<add>} = require('../e2e-helpers');
<ide>
<ide> describe('Button', () => {
<ide> beforeAll(async () => {
<ide> await device.reloadReactNative();
<del> await element(by.id('explorer_search')).replaceText('<Button>');
<del> await element(
<del> by.label('<Button> Simple React Native button component.'),
<del> ).tap();
<del> });
<del>
<del> afterAll(async () => {
<del> //TODO - remove app state persistency, till then, we must go back to main screen,
<del> await element(by.label('Back')).tap();
<add> await openComponentWithLabel(
<add> '<Button>',
<add> '<Button> Simple React Native button component.',
<add> );
<ide> });
<ide>
<ide> it('Simple button should be tappable', async () => {
<add> await openExampleWithTitle('Simple Button');
<ide> await element(by.id('simple_button')).tap();
<ide> await expect(element(by.text('Simple has been pressed!'))).toBeVisible();
<ide> await element(by.text('OK')).tap();
<ide> });
<ide>
<ide> it('Adjusted color button should be tappable', async () => {
<add> await openExampleWithTitle('Adjusted color');
<ide> await element(by.id('purple_button')).tap();
<ide> await expect(element(by.text('Purple has been pressed!'))).toBeVisible();
<ide> await element(by.text('OK')).tap();
<ide> });
<ide>
<ide> it("Two buttons with JustifyContent:'space-between' should be tappable", async () => {
<add> await openExampleWithTitle('Fit to text layout');
<ide> await element(by.id('left_button')).tap();
<ide> await expect(element(by.text('Left has been pressed!'))).toBeVisible();
<ide> await element(by.text('OK')).tap();
<ide> describe('Button', () => {
<ide> });
<ide>
<ide> it('Disabled button should not interact', async () => {
<add> await openExampleWithTitle('Disabled Button');
<ide> await element(by.id('disabled_button')).tap();
<ide> await expect(
<ide> element(by.text('Disabled has been pressed!')),
<ide><path>RNTester/e2e/__tests__/DatePickerIOS-test.js
<ide> * @format
<ide> */
<ide>
<del>/* global element, by, expect */
<add>/* global element, by, expect, device */
<add>
<add>const {
<add> openComponentWithLabel,
<add> openExampleWithTitle,
<add>} = require('../e2e-helpers');
<ide>
<ide> describe('DatePickerIOS', () => {
<ide> beforeAll(async () => {
<del> await element(by.id('explorer_search')).replaceText('<DatePickerIOS>');
<del> await element(
<del> by.label(
<del> '<DatePickerIOS> Select dates and times using the native UIDatePicker.',
<del> ),
<del> ).tap();
<del> });
<del>
<del> afterAll(async () => {
<del> await element(by.label('Back')).tap();
<add> await device.reloadReactNative();
<add> await openComponentWithLabel(
<add> '<DatePickerIOS>',
<add> '<DatePickerIOS> Select dates and times using the native UIDatePicker.',
<add> );
<ide> });
<ide>
<ide> it('Should change indicator with datetime picker', async () => {
<add> await openExampleWithTitle('Date and time picker');
<ide> const testID = 'date-and-time';
<ide> const indicatorID = 'date-and-time-indicator';
<ide>
<ide> describe('DatePickerIOS', () => {
<ide> });
<ide>
<ide> it('Should change indicator with date-only picker', async () => {
<add> await openExampleWithTitle('Date only');
<ide> const testID = 'date-only';
<ide> const indicatorID = 'date-and-time-indicator';
<ide>
<ide><path>RNTester/e2e/__tests__/Picker-test.js
<ide> * @format
<ide> */
<ide>
<del>/* global element, by, expect */
<add>/* global device, element, by, expect */
<add>const {
<add> openComponentWithLabel,
<add> openExampleWithTitle,
<add>} = require('../e2e-helpers');
<ide>
<ide> describe('Picker', () => {
<ide> beforeAll(async () => {
<del> await element(by.id('explorer_search')).replaceText('<Picker>');
<del> await element(
<del> by.label(
<del> '<Picker> Provides multiple options to choose from, using either a dropdown menu or a dialog.',
<del> ),
<del> ).tap();
<del> });
<del>
<del> afterAll(async () => {
<del> await element(by.label('Back')).tap();
<add> await device.reloadReactNative();
<add> await openComponentWithLabel(
<add> '<Picker>',
<add> '<Picker> Provides multiple options to choose from, using either a dropdown menu or a dialog.',
<add> );
<ide> });
<ide>
<ide> it('should be selectable by ID', async () => {
<add> await openExampleWithTitle('Basic picker');
<ide> await expect(element(by.id('basic-picker'))).toBeVisible();
<ide> });
<ide> });
<ide><path>RNTester/e2e/__tests__/Switch-test.js
<ide> /* global device, element, by, expect */
<ide>
<ide> const jestExpect = require('expect');
<add>const {
<add> openComponentWithLabel,
<add> openExampleWithTitle,
<add>} = require('../e2e-helpers');
<ide>
<ide> describe('Switch', () => {
<del> beforeEach(async () => {
<add> beforeAll(async () => {
<ide> await device.reloadReactNative();
<del> await element(by.id('explorer_search')).replaceText('<Switch>');
<del> await element(by.label('<Switch> Native boolean input')).tap();
<add> await openComponentWithLabel('<Switch>', '<Switch> Native boolean input');
<ide> });
<ide>
<del> it('Switch that starts off should switch', async () => {
<del> const testID = 'on-off-initial-off';
<del> const indicatorID = 'on-off-initial-off-indicator';
<add> describe('Switches can be set to true or false', () => {
<add> beforeAll(async () => {
<add> await openExampleWithTitle('Switches can be set to true or false');
<add> });
<ide>
<del> await expect(element(by.id(testID))).toHaveValue('0');
<del> await expect(element(by.id(indicatorID))).toHaveText('Off');
<del> await element(by.id(testID)).tap();
<del> await expect(element(by.id(testID))).toHaveValue('1');
<del> await expect(element(by.id(indicatorID))).toHaveText('On');
<del> });
<add> it('Switch that starts off should switch', async () => {
<add> const testID = 'on-off-initial-off';
<add> const indicatorID = 'on-off-initial-off-indicator';
<add>
<add> await expect(element(by.id(testID))).toHaveValue('0');
<add> await expect(element(by.id(indicatorID))).toHaveText('Off');
<add> await element(by.id(testID)).tap();
<add> await expect(element(by.id(testID))).toHaveValue('1');
<add> await expect(element(by.id(indicatorID))).toHaveText('On');
<add> });
<ide>
<del> it('Switch that starts on should switch', async () => {
<del> const testID = 'on-off-initial-on';
<del> const indicatorID = 'on-off-initial-on-indicator';
<add> it('Switch that starts on should switch', async () => {
<add> const testID = 'on-off-initial-on';
<add> const indicatorID = 'on-off-initial-on-indicator';
<ide>
<del> await expect(element(by.id(testID))).toHaveValue('1');
<del> await expect(element(by.id(indicatorID))).toHaveText('On');
<del> await element(by.id(testID)).tap();
<del> await expect(element(by.id(testID))).toHaveValue('0');
<del> await expect(element(by.id(indicatorID))).toHaveText('Off');
<add> await expect(element(by.id(testID))).toHaveValue('1');
<add> await expect(element(by.id(indicatorID))).toHaveText('On');
<add> await element(by.id(testID)).tap();
<add> await expect(element(by.id(testID))).toHaveValue('0');
<add> await expect(element(by.id(indicatorID))).toHaveText('Off');
<add> });
<ide> });
<ide>
<del> it('disabled switch should not toggle', async () => {
<del> const onTestID = 'disabled-initial-on';
<del> const offTestID = 'disabled-initial-off';
<del> const onIndicatorID = 'disabled-initial-on-indicator';
<del> const offIndicatorID = 'disabled-initial-off-indicator';
<add> describe('Switches can be disabled', () => {
<add> beforeAll(async () => {
<add> await openExampleWithTitle('Switches can be disabled');
<add> });
<add>
<add> it('disabled switch should not toggle', async () => {
<add> const onTestID = 'disabled-initial-on';
<add> const offTestID = 'disabled-initial-off';
<add> const onIndicatorID = 'disabled-initial-on-indicator';
<add> const offIndicatorID = 'disabled-initial-off-indicator';
<ide>
<del> await expect(element(by.id(onTestID))).toHaveValue('1');
<del> await expect(element(by.id(onIndicatorID))).toHaveText('On');
<add> await expect(element(by.id(onTestID))).toHaveValue('1');
<add> await expect(element(by.id(onIndicatorID))).toHaveText('On');
<ide>
<del> try {
<del> await element(by.id(onTestID)).tap();
<del> throw new Error('Does not match');
<del> } catch (err) {
<del> jestExpect(err.message.message).toEqual(
<del> jestExpect.stringContaining(
<del> 'Cannot perform action due to constraint(s) failure',
<del> ),
<del> );
<del> }
<del> await expect(element(by.id(onTestID))).toHaveValue('1');
<del> await expect(element(by.id(onIndicatorID))).toHaveText('On');
<add> try {
<add> await element(by.id(onTestID)).tap();
<add> throw new Error('Does not match');
<add> } catch (err) {
<add> jestExpect(err.message.message).toEqual(
<add> jestExpect.stringContaining(
<add> 'Cannot perform action due to constraint(s) failure',
<add> ),
<add> );
<add> }
<add> await expect(element(by.id(onTestID))).toHaveValue('1');
<add> await expect(element(by.id(onIndicatorID))).toHaveText('On');
<ide>
<del> await expect(element(by.id(offTestID))).toHaveValue('0');
<del> await expect(element(by.id(offIndicatorID))).toHaveText('Off');
<del> try {
<del> await element(by.id(offTestID)).tap();
<del> throw new Error('Does not match');
<del> } catch (err) {
<del> jestExpect(err.message.message).toEqual(
<del> jestExpect.stringContaining(
<del> 'Cannot perform action due to constraint(s) failure',
<del> ),
<del> );
<del> }
<del> await expect(element(by.id(offTestID))).toHaveValue('0');
<del> await expect(element(by.id(offIndicatorID))).toHaveText('Off');
<add> await expect(element(by.id(offTestID))).toHaveValue('0');
<add> await expect(element(by.id(offIndicatorID))).toHaveText('Off');
<add> try {
<add> await element(by.id(offTestID)).tap();
<add> throw new Error('Does not match');
<add> } catch (err) {
<add> jestExpect(err.message.message).toEqual(
<add> jestExpect.stringContaining(
<add> 'Cannot perform action due to constraint(s) failure',
<add> ),
<add> );
<add> }
<add> await expect(element(by.id(offTestID))).toHaveValue('0');
<add> await expect(element(by.id(offIndicatorID))).toHaveText('Off');
<add> });
<ide> });
<ide> });
<ide><path>RNTester/e2e/__tests__/Touchable-test.js
<ide> * @format
<ide> */
<ide>
<del>/* global element, by, expect */
<add>/* global device, element, by, expect */
<add>const {
<add> openComponentWithLabel,
<add> openExampleWithTitle,
<add>} = require('../e2e-helpers');
<ide>
<ide> describe('Touchable', () => {
<ide> beforeAll(async () => {
<del> await element(by.id('explorer_search')).replaceText('<Touchable*');
<del> await element(
<del> by.label('<Touchable*> and onPress Touchable and onPress examples.'),
<del> ).tap();
<del> });
<del>
<del> afterAll(async () => {
<del> //TODO - remove app state persistency, till then, we must go back to main screen,
<del> await element(by.label('Back')).tap();
<add> await device.reloadReactNative();
<add> await openComponentWithLabel(
<add> '<Touchable*',
<add> '<Touchable*> and onPress Touchable and onPress examples.',
<add> );
<ide> });
<ide>
<ide> it('Touchable Highlight should be tappable', async () => {
<add> await openExampleWithTitle('<TouchableHighlight>');
<ide> const buttonID = 'touchable_highlight_image_button';
<ide> const button2ID = 'touchable_highlight_text_button';
<ide> const consoleID = 'touchable_highlight_console';
<ide> describe('Touchable', () => {
<ide> });
<ide>
<ide> it('Touchable Without Feedback should be tappable', async () => {
<add> await openExampleWithTitle('<TouchableWithoutFeedback>');
<add>
<ide> const buttonID = 'touchable_without_feedback_button';
<ide> const consoleID = 'touchable_without_feedback_console';
<ide>
<ide> describe('Touchable', () => {
<ide> });
<ide>
<ide> it('Text should be tappable', async () => {
<add> await openExampleWithTitle('<Text onPress={fn}> with highlight');
<add>
<ide> const buttonID = 'tappable_text';
<ide> const consoleID = 'tappable_text_console';
<ide>
<ide><path>RNTester/e2e/e2e-helpers.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @emails oncall+react_native
<add> * @format
<add> */
<add>
<add>/* global element, by, expect */
<add>
<add>// Will open a component example from the root list
<add>// by filtering by component and then tapping on the label
<add>exports.openComponentWithLabel = async (component, label) => {
<add> await element(by.id('explorer_search')).replaceText(component);
<add> await element(by.label(label)).tap();
<add>};
<add>
<add>// Will open an individual example for a component
<add>// by filtering on the example title
<add>exports.openExampleWithTitle = async title => {
<add> await element(by.id('example_search')).replaceText(title);
<add>};
<ide><path>RNTester/js/DatePickerIOSExample.js
<ide> const React = require('react');
<ide> const ReactNative = require('react-native');
<ide> const {DatePickerIOS, StyleSheet, Text, TextInput, View} = ReactNative;
<ide>
<del>class DatePickerExample extends React.Component<
<del> $FlowFixMeProps,
<del> $FlowFixMeState,
<del>> {
<del> static defaultProps = {
<del> date: new Date(),
<del> timeZoneOffsetInHours: (-1 * new Date().getTimezoneOffset()) / 60,
<del> };
<add>type State = {|
<add> date: Date,
<add> timeZoneOffsetInHours: number,
<add>|};
<ide>
<add>type Props = {|
<add> children: (State, (Date) => void) => React.Node,
<add>|};
<add>
<add>class WithDatePickerData extends React.Component<Props, State> {
<ide> state = {
<del> date: this.props.date,
<del> timeZoneOffsetInHours: this.props.timeZoneOffsetInHours,
<add> date: new Date(),
<add> timeZoneOffsetInHours: (-1 * new Date().getTimezoneOffset()) / 60,
<ide> };
<ide>
<ide> onDateChange = date => {
<ide> class DatePickerExample extends React.Component<
<ide> />
<ide> <Text> hours from UTC</Text>
<ide> </WithLabel>
<del> <Heading label="Date + time picker" />
<del> <DatePickerIOS
<del> testID="date-and-time"
<del> date={this.state.date}
<del> mode="datetime"
<del> timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60}
<del> onDateChange={this.onDateChange}
<del> />
<del> <Heading label="Date picker" />
<del> <DatePickerIOS
<del> testID="date-only"
<del> date={this.state.date}
<del> mode="date"
<del> timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60}
<del> onDateChange={this.onDateChange}
<del> />
<del> <Heading label="Time picker, 10-minute interval" />
<del> <DatePickerIOS
<del> testID="time-only"
<del> date={this.state.date}
<del> mode="time"
<del> timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60}
<del> onDateChange={this.onDateChange}
<del> minuteInterval={10}
<del> />
<add> {this.props.children(this.state, this.onDateChange)}
<ide> </View>
<ide> );
<ide> }
<ide> }
<ide>
<del>class WithLabel extends React.Component<$FlowFixMeProps> {
<add>type LabelProps = {|
<add> label: string,
<add> children: React.Node,
<add>|};
<add>
<add>class WithLabel extends React.Component<LabelProps> {
<ide> render() {
<ide> return (
<ide> <View style={styles.labelContainer}>
<ide> class WithLabel extends React.Component<$FlowFixMeProps> {
<ide> }
<ide> }
<ide>
<del>class Heading extends React.Component<$FlowFixMeProps> {
<del> render() {
<del> return (
<del> <View style={styles.headingContainer}>
<del> <Text style={styles.heading}>{this.props.label}</Text>
<del> </View>
<del> );
<del> }
<del>}
<del>
<del>exports.displayName = (undefined: ?string);
<del>exports.title = '<DatePickerIOS>';
<del>exports.description = 'Select dates and times using the native UIDatePicker.';
<del>exports.examples = [
<del> {
<del> title: '<DatePickerIOS>',
<del> render: function(): React.Element<any> {
<del> return <DatePickerExample />;
<del> },
<del> },
<del>];
<del>
<ide> const styles = StyleSheet.create({
<ide> textinput: {
<ide> height: 26,
<ide> const styles = StyleSheet.create({
<ide> label: {
<ide> fontWeight: '500',
<ide> },
<del> headingContainer: {
<del> padding: 4,
<del> backgroundColor: '#f6f7f8',
<add>});
<add>
<add>exports.title = '<DatePickerIOS>';
<add>exports.description = 'Select dates and times using the native UIDatePicker.';
<add>exports.examples = [
<add> {
<add> title: 'Date and time picker',
<add> render: function(): React.Element<any> {
<add> return (
<add> <WithDatePickerData>
<add> {(state, onDateChange) => (
<add> <DatePickerIOS
<add> testID="date-and-time"
<add> date={state.date}
<add> mode="datetime"
<add> timeZoneOffsetInMinutes={state.timeZoneOffsetInHours * 60}
<add> onDateChange={onDateChange}
<add> />
<add> )}
<add> </WithDatePickerData>
<add> );
<add> },
<ide> },
<del> heading: {
<del> fontWeight: '500',
<del> fontSize: 14,
<add> {
<add> title: 'Date only picker',
<add> render: function(): React.Element<any> {
<add> return (
<add> <WithDatePickerData>
<add> {(state, onDateChange) => (
<add> <DatePickerIOS
<add> testID="date-only"
<add> date={state.date}
<add> mode="date"
<add> timeZoneOffsetInMinutes={state.timeZoneOffsetInHours * 60}
<add> onDateChange={onDateChange}
<add> />
<add> )}
<add> </WithDatePickerData>
<add> );
<add> },
<ide> },
<del>});
<add> {
<add> title: 'Time only picker, 10-minute interval',
<add> render: function(): React.Element<any> {
<add> return (
<add> <WithDatePickerData>
<add> {(state, onDateChange) => (
<add> <DatePickerIOS
<add> testID="time-only"
<add> date={state.date}
<add> mode="time"
<add> timeZoneOffsetInMinutes={state.timeZoneOffsetInHours * 60}
<add> onDateChange={onDateChange}
<add> />
<add> )}
<add> </WithDatePickerData>
<add> );
<add> },
<add> },
<add>];
<ide><path>RNTester/js/PickerExample.js
<ide> const React = require('react');
<ide> const ReactNative = require('react-native');
<ide> const StyleSheet = require('StyleSheet');
<del>const RNTesterBlock = require('RNTesterBlock');
<del>const RNTesterPage = require('RNTesterPage');
<ide>
<ide> const {Picker, Text} = ReactNative;
<ide>
<ide> const Item = Picker.Item;
<ide>
<del>class PickerExample extends React.Component<{}, $FlowFixMeState> {
<del> static title = '<Picker>';
<del> static description =
<del> 'Provides multiple options to choose from, using either a dropdown menu or a dialog.';
<add>type State = {
<add> value: string | number,
<add>};
<ide>
<add>class BasicPickerExample extends React.Component<{}, State> {
<ide> state = {
<del> selected1: 'key1',
<del> selected2: 'key1',
<del> selected3: 'key1',
<del> color: 'red',
<del> mode: Picker.MODE_DIALOG,
<add> value: 'key1',
<ide> };
<ide>
<ide> render() {
<ide> return (
<del> <RNTesterPage title="<Picker>">
<del> <RNTesterBlock title="Basic Picker">
<del> <Picker
<del> testID="basic-picker"
<del> style={styles.picker}
<del> selectedValue={this.state.selected1}
<del> onValueChange={this.onValueChange.bind(this, 'selected1')}>
<del> <Item label="hello" value="key0" />
<del> <Item label="world" value="key1" />
<del> </Picker>
<del> </RNTesterBlock>
<del> <RNTesterBlock title="Disabled picker">
<del> <Picker
<del> style={styles.picker}
<del> enabled={false}
<del> selectedValue={this.state.selected1}>
<del> <Item label="hello" value="key0" />
<del> <Item label="world" value="key1" />
<del> </Picker>
<del> </RNTesterBlock>
<del> <RNTesterBlock title="Dropdown Picker">
<del> <Picker
<del> style={styles.picker}
<del> selectedValue={this.state.selected2}
<del> onValueChange={this.onValueChange.bind(this, 'selected2')}
<del> mode="dropdown">
<del> <Item label="hello" value="key0" />
<del> <Item label="world" value="key1" />
<del> </Picker>
<del> </RNTesterBlock>
<del> <RNTesterBlock title="Picker with prompt message">
<del> <Picker
<del> style={styles.picker}
<del> selectedValue={this.state.selected3}
<del> onValueChange={this.onValueChange.bind(this, 'selected3')}
<del> prompt="Pick one, just one">
<del> <Item label="hello" value="key0" />
<del> <Item label="world" value="key1" />
<del> </Picker>
<del> </RNTesterBlock>
<del> <RNTesterBlock title="Picker with no listener">
<del> <Picker style={styles.picker}>
<del> <Item label="hello" value="key0" />
<del> <Item label="world" value="key1" />
<del> </Picker>
<del> <Text>
<del> Cannot change the value of this picker because it doesn't update
<del> selectedValue.
<del> </Text>
<del> </RNTesterBlock>
<del> <RNTesterBlock title="Colorful pickers">
<del> <Picker
<del> style={[styles.picker, {color: 'white', backgroundColor: '#333'}]}
<del> selectedValue={this.state.color}
<del> onValueChange={this.onValueChange.bind(this, 'color')}
<del> mode="dropdown">
<del> <Item label="red" color="red" value="red" />
<del> <Item label="green" color="green" value="green" />
<del> <Item label="blue" color="blue" value="blue" />
<del> </Picker>
<del> <Picker
<del> style={styles.picker}
<del> selectedValue={this.state.color}
<del> onValueChange={this.onValueChange.bind(this, 'color')}
<del> mode="dialog">
<del> <Item label="red" color="red" value="red" />
<del> <Item label="green" color="green" value="green" />
<del> <Item label="blue" color="blue" value="blue" />
<del> </Picker>
<del> </RNTesterBlock>
<del> </RNTesterPage>
<add> <Picker
<add> testID="basic-picker"
<add> style={styles.picker}
<add> selectedValue={this.state.value}
<add> onValueChange={v => this.setState({value: v})}>
<add> <Item label="hello" value="key0" />
<add> <Item label="world" value="key1" />
<add> </Picker>
<ide> );
<ide> }
<add>}
<ide>
<del> changeMode = () => {
<del> const newMode =
<del> this.state.mode === Picker.MODE_DIALOG
<del> ? Picker.MODE_DROPDOWN
<del> : Picker.MODE_DIALOG;
<del> this.setState({mode: newMode});
<add>class DisabledPickerExample extends React.Component<{}, State> {
<add> state = {
<add> value: 'key1',
<ide> };
<ide>
<del> onValueChange = (key: string, value: string | number) => {
<del> const newState = {};
<del> newState[key] = value;
<del> this.setState(newState);
<add> render() {
<add> return (
<add> <Picker
<add> style={styles.picker}
<add> enabled={false}
<add> selectedValue={this.state.value}>
<add> <Item label="hello" value="key0" />
<add> <Item label="world" value="key1" />
<add> </Picker>
<add> );
<add> }
<add>}
<add>
<add>class DropdownPickerExample extends React.Component<{}, State> {
<add> state = {
<add> value: 'key1',
<ide> };
<add>
<add> render() {
<add> return (
<add> <Picker
<add> style={styles.picker}
<add> selectedValue={this.state.value}
<add> onValueChange={v => this.setState({value: v})}
<add> mode="dropdown">
<add> <Item label="hello" value="key0" />
<add> <Item label="world" value="key1" />
<add> </Picker>
<add> );
<add> }
<add>}
<add>
<add>class PromptPickerExample extends React.Component<{}, State> {
<add> state = {
<add> value: 'key1',
<add> };
<add>
<add> render() {
<add> return (
<add> <Picker
<add> style={styles.picker}
<add> selectedValue={this.state.value}
<add> onValueChange={v => this.setState({value: v})}
<add> prompt="Pick one, just one">
<add> <Item label="hello" value="key0" />
<add> <Item label="world" value="key1" />
<add> </Picker>
<add> );
<add> }
<add>}
<add>
<add>type ColorState = {
<add> color: string | number,
<add>};
<add>
<add>class ColorPickerExample extends React.Component<{}, ColorState> {
<add> state = {
<add> color: 'red',
<add> };
<add>
<add> render() {
<add> return (
<add> <>
<add> <Picker
<add> style={[styles.picker, {color: 'white', backgroundColor: '#333'}]}
<add> selectedValue={this.state.color}
<add> onValueChange={v => this.setState({color: v})}
<add> mode="dropdown">
<add> <Item label="red" color="red" value="red" />
<add> <Item label="green" color="green" value="green" />
<add> <Item label="blue" color="blue" value="blue" />
<add> </Picker>
<add> <Picker
<add> style={styles.picker}
<add> selectedValue={this.state.color}
<add> onValueChange={v => this.setState({color: v})}
<add> mode="dialog">
<add> <Item label="red" color="red" value="red" />
<add> <Item label="green" color="green" value="green" />
<add> <Item label="blue" color="blue" value="blue" />
<add> </Picker>
<add> </>
<add> );
<add> }
<ide> }
<ide>
<ide> const styles = StyleSheet.create({
<ide> const styles = StyleSheet.create({
<ide> },
<ide> });
<ide>
<del>module.exports = PickerExample;
<add>exports.title = '<Picker>';
<add>exports.description =
<add> 'Provides multiple options to choose from, using either a dropdown menu or a dialog.';
<add>exports.examples = [
<add> {
<add> title: 'Basic Picker',
<add> render: function(): React.Element<typeof BasicPickerExample> {
<add> return <BasicPickerExample />;
<add> },
<add> },
<add> {
<add> title: 'Disabled Picker',
<add> render: function(): React.Element<typeof DisabledPickerExample> {
<add> return <DisabledPickerExample />;
<add> },
<add> },
<add> {
<add> title: 'Dropdown Picker',
<add> render: function(): React.Element<typeof DropdownPickerExample> {
<add> return <DropdownPickerExample />;
<add> },
<add> },
<add> {
<add> title: 'Picker with prompt message',
<add> render: function(): React.Element<typeof PromptPickerExample> {
<add> return <PromptPickerExample />;
<add> },
<add> },
<add> {
<add> title: 'Picker with no listener',
<add> render: function(): React.Element<typeof PromptPickerExample> {
<add> return (
<add> <>
<add> <Picker style={styles.picker}>
<add> <Item label="hello" value="key0" />
<add> <Item label="world" value="key1" />
<add> </Picker>
<add> <Text>
<add> Cannot change the value of this picker because it doesn't update
<add> selectedValue.
<add> </Text>
<add> </>
<add> );
<add> },
<add> },
<add> {
<add> title: 'Colorful pickers',
<add> render: function(): React.Element<typeof ColorPickerExample> {
<add> return <ColorPickerExample />;
<add> },
<add> },
<add>];
<ide><path>RNTester/js/RNTesterExampleContainer.js
<ide> class RNTesterExampleContainer extends React.Component {
<ide> return (
<ide> <RNTesterPage title={this.props.title}>
<ide> <RNTesterExampleFilter
<add> testID="example_search"
<ide> sections={sections}
<ide> filter={filter}
<ide> render={({filteredSections}) =>
<ide><path>RNTester/js/RNTesterExampleFilter.js
<ide> type Props = {
<ide> render: Function,
<ide> sections: Object,
<ide> disableSearch?: boolean,
<add> testID?: string,
<ide> };
<ide>
<ide> type State = {
<ide> class RNTesterExampleFilter extends React.Component<Props, State> {
<ide> placeholder="Search..."
<ide> underlineColorAndroid="transparent"
<ide> style={styles.searchTextInput}
<del> testID="explorer_search"
<add> testID={this.props.testID}
<ide> value={this.state.filter}
<ide> />
<ide> </View>
<ide><path>RNTester/js/RNTesterExampleList.js
<ide> class RNTesterExampleList extends React.Component<Props, $FlowFixMeState> {
<ide> <View style={[styles.listContainer, this.props.style]}>
<ide> {this._renderTitleRow()}
<ide> <RNTesterExampleFilter
<add> testID="explorer_search"
<ide> sections={sections}
<ide> filter={filter}
<ide> render={({filteredSections}) => (
<ide><path>RNTester/js/SwitchExample.js
<ide> class EventSwitchExample extends React.Component<{}, $FlowFixMeState> {
<ide> }
<ide> }
<ide>
<del>const examples = [
<add>exports.title = '<Switch>';
<add>exports.displayName = 'SwitchExample';
<add>exports.description = 'Native boolean input';
<add>exports.examples = [
<ide> {
<ide> title: 'Switches can be set to true or false',
<ide> render(): React.Element<any> {
<ide> const examples = [
<ide> },
<ide> },
<ide> ];
<del>
<del>exports.title = '<Switch>';
<del>exports.displayName = 'SwitchExample';
<del>exports.description = 'Native boolean input';
<del>exports.examples = examples;
<ide><path>RNTester/js/TouchableExample.js
<ide> const forceTouchAvailable =
<ide> NativeModules.PlatformConstants.forceTouchAvailable) ||
<ide> false;
<ide>
<del>exports.displayName = (undefined: ?string);
<del>exports.description = 'Touchable and onPress examples.';
<del>exports.title = '<Touchable*> and onPress';
<del>exports.examples = [
<del> {
<del> title: '<TouchableHighlight>',
<del> description:
<del> 'TouchableHighlight works by adding an extra view with a ' +
<del> 'black background under the single child view. This works best when the ' +
<del> 'child view is fully opaque, although it can be made to work as a simple ' +
<del> 'background color change as well with the activeOpacity and ' +
<del> 'underlayColor props.',
<del> render: function() {
<del> return <TouchableHighlightBox />;
<del> },
<del> },
<del> {
<del> title: '<TouchableWithoutFeedback>',
<del> render: function() {
<del> return <TouchableWithoutFeedbackBox />;
<del> },
<del> },
<del> {
<del> title: 'TouchableNativeFeedback with Animated child',
<del> description:
<del> 'TouchableNativeFeedback can have an AnimatedComponent as a' +
<del> 'direct child.',
<del> platform: 'android',
<del> render: function() {
<del> const mScale = new Animated.Value(1);
<del> Animated.timing(mScale, {toValue: 0.3, duration: 1000}).start();
<del> const style = {
<del> backgroundColor: 'rgb(180, 64, 119)',
<del> width: 200,
<del> height: 100,
<del> transform: [{scale: mScale}],
<del> };
<del> return (
<del> <View>
<del> <View style={styles.row}>
<del> <TouchableNativeFeedback>
<del> <Animated.View style={style} />
<del> </TouchableNativeFeedback>
<del> </View>
<del> </View>
<del> );
<del> },
<del> },
<del> {
<del> title: '<Text onPress={fn}> with highlight',
<del> render: function(): React.Element<any> {
<del> return <TextOnPressBox />;
<del> },
<del> },
<del> {
<del> title: 'Touchable feedback events',
<del> description:
<del> '<Touchable*> components accept onPress, onPressIn, ' +
<del> 'onPressOut, and onLongPress as props.',
<del> render: function(): React.Element<any> {
<del> return <TouchableFeedbackEvents />;
<del> },
<del> },
<del> {
<del> title: 'Touchable delay for events',
<del> description:
<del> '<Touchable*> components also accept delayPressIn, ' +
<del> 'delayPressOut, and delayLongPress as props. These props impact the ' +
<del> 'timing of feedback events.',
<del> render: function(): React.Element<any> {
<del> return <TouchableDelayEvents />;
<del> },
<del> },
<del> {
<del> title: '3D Touch / Force Touch',
<del> description:
<del> 'iPhone 6s and 6s plus support 3D touch, which adds a force property to touches',
<del> render: function(): React.Element<any> {
<del> return <ForceTouchExample />;
<del> },
<del> platform: 'ios',
<del> },
<del> {
<del> title: 'Touchable Hit Slop',
<del> description:
<del> '<Touchable*> components accept hitSlop prop which extends the touch area ' +
<del> 'without changing the view bounds.',
<del> render: function(): React.Element<any> {
<del> return <TouchableHitSlop />;
<del> },
<del> },
<del> {
<del> title: 'Disabled Touchable*',
<del> description:
<del> '<Touchable*> components accept disabled prop which prevents ' +
<del> 'any interaction with component',
<del> render: function(): React.Element<any> {
<del> return <TouchableDisabled />;
<del> },
<del> },
<del>];
<del>
<ide> class TouchableHighlightBox extends React.Component<{}, $FlowFixMeState> {
<ide> state = {
<ide> timesPressed: 0,
<ide> const styles = StyleSheet.create({
<ide> color: 'blue',
<ide> },
<ide> });
<add>
<add>exports.displayName = (undefined: ?string);
<add>exports.description = 'Touchable and onPress examples.';
<add>exports.title = '<Touchable*> and onPress';
<add>exports.examples = [
<add> {
<add> title: '<TouchableHighlight>',
<add> description:
<add> 'TouchableHighlight works by adding an extra view with a ' +
<add> 'black background under the single child view. This works best when the ' +
<add> 'child view is fully opaque, although it can be made to work as a simple ' +
<add> 'background color change as well with the activeOpacity and ' +
<add> 'underlayColor props.',
<add> render: function() {
<add> return <TouchableHighlightBox />;
<add> },
<add> },
<add> {
<add> title: '<TouchableWithoutFeedback>',
<add> render: function() {
<add> return <TouchableWithoutFeedbackBox />;
<add> },
<add> },
<add> {
<add> title: 'TouchableNativeFeedback with Animated child',
<add> description:
<add> 'TouchableNativeFeedback can have an AnimatedComponent as a' +
<add> 'direct child.',
<add> platform: 'android',
<add> render: function() {
<add> const mScale = new Animated.Value(1);
<add> Animated.timing(mScale, {toValue: 0.3, duration: 1000}).start();
<add> const style = {
<add> backgroundColor: 'rgb(180, 64, 119)',
<add> width: 200,
<add> height: 100,
<add> transform: [{scale: mScale}],
<add> };
<add> return (
<add> <View>
<add> <View style={styles.row}>
<add> <TouchableNativeFeedback>
<add> <Animated.View style={style} />
<add> </TouchableNativeFeedback>
<add> </View>
<add> </View>
<add> );
<add> },
<add> },
<add> {
<add> title: '<Text onPress={fn}> with highlight',
<add> render: function(): React.Element<any> {
<add> return <TextOnPressBox />;
<add> },
<add> },
<add> {
<add> title: 'Touchable feedback events',
<add> description:
<add> '<Touchable*> components accept onPress, onPressIn, ' +
<add> 'onPressOut, and onLongPress as props.',
<add> render: function(): React.Element<any> {
<add> return <TouchableFeedbackEvents />;
<add> },
<add> },
<add> {
<add> title: 'Touchable delay for events',
<add> description:
<add> '<Touchable*> components also accept delayPressIn, ' +
<add> 'delayPressOut, and delayLongPress as props. These props impact the ' +
<add> 'timing of feedback events.',
<add> render: function(): React.Element<any> {
<add> return <TouchableDelayEvents />;
<add> },
<add> },
<add> {
<add> title: '3D Touch / Force Touch',
<add> description:
<add> 'iPhone 6s and 6s plus support 3D touch, which adds a force property to touches',
<add> render: function(): React.Element<any> {
<add> return <ForceTouchExample />;
<add> },
<add> platform: 'ios',
<add> },
<add> {
<add> title: 'Touchable Hit Slop',
<add> description:
<add> '<Touchable*> components accept hitSlop prop which extends the touch area ' +
<add> 'without changing the view bounds.',
<add> render: function(): React.Element<any> {
<add> return <TouchableHitSlop />;
<add> },
<add> },
<add> {
<add> title: 'Disabled Touchable*',
<add> description:
<add> '<Touchable*> components accept disabled prop which prevents ' +
<add> 'any interaction with component',
<add> render: function(): React.Element<any> {
<add> return <TouchableDisabled />;
<add> },
<add> },
<add>]; | 13 |
PHP | PHP | remove redundant listtablesandviews method | 2dcd35c3aaf858c6f0456aa276d89a3482bd4440 | <ide><path>src/Database/Schema/Collection.php
<ide> *
<ide> * Used to access information about the tables,
<ide> * and other data in a database.
<del> *
<del> * @method array<string> listTablesAndViews() Get the list of tables available in the current connection.
<del> * This will include any views in the schema.
<del> * @method array<string> listTablesWithoutViews() Get the list of tables available in the current connection.
<del> * This will exclude any views in the schema.
<ide> */
<ide> class Collection implements CollectionInterface
<ide> {
<ide> public function listTablesWithoutViews(): array
<ide> }
<ide>
<ide> /**
<del> * Get the list of tables available in the current connection.
<add> * Get the list of tables and views available in the current connection.
<ide> *
<del> * @deprecated in 4.3.3 Use {@link listTablesAndViews()} instead.
<del> * @return array<string> The list of tables in the connected database/schema.
<add> * @return array<string> The list of tables and views in the connected database/schema.
<ide> */
<ide> public function listTables(): array
<ide> {
<ide> public function listTables(): array
<ide> return $result;
<ide> }
<ide>
<del> /**
<del> * Get the list of tables available in the current connection.
<del> *
<del> * @return array<string> The list of tables in the connected database/schema.
<del> */
<del> public function listTablesAndViews(): array
<del> {
<del> [$sql, $params] = $this->_dialect->listTablesAndViewsSql($this->_connection->config());
<del> $result = [];
<del> $statement = $this->_connection->execute($sql, $params);
<del> while ($row = $statement->fetch()) {
<del> $result[] = $row[0];
<del> }
<del> $statement->closeCursor();
<del>
<del> return $result;
<del> }
<del>
<ide> /**
<ide> * Get the column metadata for a table.
<ide> *
<ide><path>src/Database/Schema/CollectionInterface.php
<ide> * Used to access information about the tables,
<ide> * and other data in a database.
<ide> *
<del> * @method array<string> listTablesAndViews() Get the list of tables available in the current connection.
<del> * This will include any views in the schema.
<ide> * @method array<string> listTablesWithoutViews() Get the list of tables available in the current connection.
<ide> * This will exclude any views in the schema.
<ide> */
<ide> interface CollectionInterface
<ide> /**
<ide> * Get the list of tables available in the current connection.
<ide> *
<del> * @deprecated in 4.3.3
<ide> * @return array<string> The list of tables in the connected database/schema.
<ide> */
<ide> public function listTables(): array;
<ide><path>src/Database/Schema/MysqlSchemaDialect.php
<ide> class MysqlSchemaDialect extends SchemaDialect
<ide> /**
<ide> * Generate the SQL to list the tables and views.
<ide> *
<del> * @deprecated 4.3.3 Use {@link listTablesAndViewsSql()} instead.
<ide> * @param array<string, mixed> $config The connection configuration to use for
<ide> * getting tables from.
<ide> * @return array<mixed> An array of (sql, params) to execute.
<ide> */
<ide> public function listTablesSql(array $config): array
<ide> {
<del> return $this->listTablesAndViewsSql($config);
<add> return ['SHOW FULL TABLES FROM ' . $this->_driver->quoteIdentifier($config['database']), []];
<ide> }
<ide>
<ide> /**
<ide> public function listTablesWithoutViewsSql(array $config): array
<ide> , []];
<ide> }
<ide>
<del> /**
<del> * Generate the SQL to list the tables and views.
<del> *
<del> * @param array<string, mixed> $config The connection configuration to use for
<del> * getting tables from.
<del> * @return array<mixed> An array of (sql, params) to execute.
<del> */
<del> public function listTablesAndViewsSql(array $config): array
<del> {
<del> return ['SHOW FULL TABLES FROM ' . $this->_driver->quoteIdentifier($config['database']), []];
<del> }
<del>
<ide> /**
<ide> * @inheritDoc
<ide> */
<ide><path>src/Database/Schema/PostgresSchemaDialect.php
<ide> class PostgresSchemaDialect extends SchemaDialect
<ide> /**
<ide> * Generate the SQL to list the tables and views.
<ide> *
<del> * @deprecated 4.3.3 Use {@link listTablesAndViewsSql()} instead.
<ide> * @param array<string, mixed> $config The connection configuration to use for
<ide> * getting tables from.
<ide> * @return array An array of (sql, params) to execute.
<ide> */
<ide> public function listTablesSql(array $config): array
<del> {
<del> return $this->listTablesAndViewsSql($config);
<del> }
<del>
<del> /**
<del> * Generate the SQL to list the tables, excluding all views.
<del> *
<del> * @param array<string, mixed> $config The connection configuration to use for
<del> * getting tables from.
<del> * @return array<mixed> An array of (sql, params) to execute.
<del> */
<del> public function listTablesWithoutViewsSql(array $config): array
<ide> {
<ide> $sql = 'SELECT table_name as name FROM information_schema.tables
<del> WHERE table_schema = ? AND table_type = \'BASE TABLE\' ORDER BY name';
<add> WHERE table_schema = ? ORDER BY name';
<ide> $schema = empty($config['schema']) ? 'public' : $config['schema'];
<ide>
<ide> return [$sql, [$schema]];
<ide> }
<ide>
<ide> /**
<del> * Generate the SQL to list the tables and views.
<add> * Generate the SQL to list the tables, excluding all views.
<ide> *
<ide> * @param array<string, mixed> $config The connection configuration to use for
<ide> * getting tables from.
<ide> * @return array<mixed> An array of (sql, params) to execute.
<ide> */
<del> public function listTablesAndViewsSql(array $config): array
<add> public function listTablesWithoutViewsSql(array $config): array
<ide> {
<ide> $sql = 'SELECT table_name as name FROM information_schema.tables
<del> WHERE table_schema = ? ORDER BY name';
<add> WHERE table_schema = ? AND table_type = \'BASE TABLE\' ORDER BY name';
<ide> $schema = empty($config['schema']) ? 'public' : $config['schema'];
<ide>
<ide> return [$sql, [$schema]];
<ide><path>src/Database/Schema/SchemaDialect.php
<ide> * This class contains methods that are common across
<ide> * the various SQL dialects.
<ide> *
<del> * @method array<mixed> listTablesAndViewsSql(array $config) Generate the SQL to list the tables and views.
<ide> * @method array<mixed> listTablesWithoutViewsSql(array $config) Generate the SQL to list the tables, excluding all views.
<ide> */
<ide> abstract class SchemaDialect
<ide> public function dropTableSql(TableSchema $schema): array
<ide> /**
<ide> * Generate the SQL to list the tables.
<ide> *
<del> * @deprecated 4.3.3
<ide> * @param array<string, mixed> $config The connection configuration to use for
<ide> * getting tables from.
<ide> * @return array An array of (sql, params) to execute.
<ide><path>src/Database/Schema/SqliteSchemaDialect.php
<ide> protected function _convertColumn(string $column): array
<ide> /**
<ide> * Generate the SQL to list the tables and views.
<ide> *
<del> * @deprecated 4.3.3 Use {@link listTablesAndViewsSql()} instead.
<ide> * @param array<string, mixed> $config The connection configuration to use for
<ide> * getting tables from.
<ide> * @return array An array of (sql, params) to execute.
<ide> */
<ide> public function listTablesSql(array $config): array
<del> {
<del> return $this->listTablesWithoutViewsSql($config);
<del> }
<del>
<del> /**
<del> * Generate the SQL to list the tables and views.
<del> *
<del> * @param array<string, mixed> $config The connection configuration to use for
<del> * getting tables from.
<del> * @return array<mixed> An array of (sql, params) to execute.
<del> */
<del> public function listTablesAndViewsSql(array $config): array
<ide> {
<ide> return [
<ide> 'SELECT name FROM sqlite_master ' .
<ide><path>src/Database/Schema/SqlserverSchemaDialect.php
<ide> class SqlserverSchemaDialect extends SchemaDialect
<ide> /**
<ide> * Generate the SQL to list the tables and views.
<ide> *
<del> * @deprecated 4.3.3 Use {@link listTablesAndViewsSql()} instead.
<ide> * @param array<string, mixed> $config The connection configuration to use for
<ide> * getting tables from.
<ide> * @return array An array of (sql, params) to execute.
<ide> */
<ide> public function listTablesSql(array $config): array
<del> {
<del> return $this->listTablesAndViewsSql($config);
<del> }
<del>
<del> /**
<del> * Generate the SQL to list the tables and views.
<del> *
<del> * @param array<string, mixed> $config The connection configuration to use for
<del> * getting tables from.
<del> * @return array<mixed> An array of (sql, params) to execute.
<del> */
<del> public function listTablesAndViewsSql(array $config): array
<ide> {
<ide> $sql = "SELECT TABLE_NAME
<ide> FROM INFORMATION_SCHEMA.TABLES
<ide><path>src/TestSuite/ConnectionHelper.php
<ide> public function dropTables(string $connectionName, ?array $tables = null): void
<ide> $connection = ConnectionManager::get($connectionName);
<ide> $collection = $connection->getSchemaCollection();
<ide>
<del> $allTables = [];
<ide> if (method_exists($collection, 'listTablesWithoutViews')) {
<ide> $allTables = $collection->listTablesWithoutViews();
<add> } else {
<add> $allTables = $collection->listTables();
<ide> }
<ide>
<ide> $tables = $tables !== null ? array_intersect($tables, $allTables) : $allTables;
<ide><path>src/TestSuite/Fixture/FixtureManager.php
<ide> public function load(TestCase $test): void
<ide> try {
<ide> $createTables = function (ConnectionInterface $db, array $fixtures) use ($test): void {
<ide> /** @var array<\Cake\Datasource\FixtureInterface> $fixtures */
<del> $tables = $db->getSchemaCollection()->listTablesAndViews();
<add> $tables = $db->getSchemaCollection()->listTables();
<ide> $configName = $db->configName();
<ide> $this->_insertionMap[$configName] = $this->_insertionMap[$configName] ?? [];
<ide>
<ide> public function loadSingle(string $name, ?ConnectionInterface $connection = null
<ide> }
<ide>
<ide> if (!$this->isFixtureSetup($connection->configName(), $fixture)) {
<del> $sources = $connection->getSchemaCollection()->listTablesAndViews();
<add> $sources = $connection->getSchemaCollection()->listTables();
<ide> $this->_setupTable($fixture, $connection, $sources, $dropTables);
<ide> }
<ide>
<ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> public function testListTables(): void
<ide> $this->assertContains('schema_articles_v', $result);
<ide> $this->assertContains('schema_authors', $result);
<ide>
<del> $resultAll = $schema->listTablesAndViews();
<ide> $resultNoViews = $schema->listTablesWithoutViews();
<del>
<del> $this->assertIsArray($resultAll);
<del> $this->assertContains('schema_articles', $resultAll);
<del> $this->assertContains('schema_articles_v', $resultAll);
<del> $this->assertContains('schema_authors', $resultAll);
<ide> $this->assertIsArray($resultNoViews);
<ide> $this->assertNotContains('schema_articles_v', $resultNoViews);
<ide> $this->assertContains('schema_articles', $resultNoViews);
<ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php
<ide> public function testListTables(): void
<ide> $this->assertContains('schema_articles_v', $result);
<ide> $this->assertContains('schema_authors', $result);
<ide>
<del> $resultAll = $schema->listTablesAndViews();
<ide> $resultNoViews = $schema->listTablesWithoutViews();
<del>
<del> $this->assertIsArray($resultAll);
<del> $this->assertContains('schema_articles', $resultAll);
<del> $this->assertContains('schema_articles_v', $resultAll);
<del> $this->assertContains('schema_authors', $resultAll);
<ide> $this->assertIsArray($resultNoViews);
<ide> $this->assertNotContains('schema_articles_v', $resultNoViews);
<ide> $this->assertContains('schema_articles', $resultNoViews);
<ide><path>tests/TestCase/Database/Schema/SqliteSchemaTest.php
<ide> public function testListTables(): void
<ide> $this->assertContains('schema_authors', $result);
<ide> $this->assertContains('view_schema_articles', $result);
<ide>
<del> $resultAll = $schema->listTablesAndViews();
<ide> $resultNoViews = $schema->listTablesWithoutViews();
<del>
<ide> $this->assertIsArray($resultNoViews);
<add> $this->assertContains('schema_authors', $resultNoViews);
<ide> $this->assertContains('schema_articles', $resultNoViews);
<ide> $this->assertNotContains('view_schema_articles', $resultNoViews);
<del>
<del> $this->assertIsArray($resultAll);
<del> $this->assertContains('schema_articles', $resultAll);
<del> $this->assertContains('schema_authors', $resultAll);
<del> $this->assertContains('view_schema_articles', $resultAll);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/Schema/SqlserverSchemaTest.php
<ide> public function testListTables(): void
<ide> $this->assertContains('schema_articles_v', $result);
<ide> $this->assertContains('schema_authors', $result);
<ide>
<del> $resultAll = $schema->listTablesAndViews();
<ide> $resultNoViews = $schema->listTablesWithoutViews();
<del>
<del> $this->assertIsArray($resultAll);
<del> $this->assertContains('schema_articles', $resultAll);
<del> $this->assertContains('schema_articles_v', $resultAll);
<del> $this->assertContains('schema_authors', $resultAll);
<ide> $this->assertIsArray($resultNoViews);
<ide> $this->assertNotContains('schema_articles_v', $resultNoViews);
<ide> $this->assertContains('schema_articles', $resultNoViews); | 13 |
Javascript | Javascript | add simpler failing tls throttle test | 33e8e3d799f7b04991728218bb1c411e01ffcfe2 | <ide><path>test/simple/test-tls-throttle.js
<add>// Server sends a large string. Client counts bytes and pauses every few
<add>// seconds. Makes sure that pause and resume work properly.
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var tls = require('tls');
<add>var fs = require('fs');
<add>
<add>
<add>var body = '';
<add>
<add>process.stdout.write('build body...');
<add>for (var i = 0; i < 1024*1024; i++) {
<add> body += 'hello world\n';
<add>}
<add>process.stdout.write('done\n');
<add>
<add>
<add>var options = {
<add> key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'),
<add> cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem')
<add>};
<add>
<add>var connections = 0;
<add>
<add>
<add>var server = tls.Server(options, function(socket) {
<add> socket.end(body);
<add> connections++;
<add>});
<add>
<add>var recvCount = 0;
<add>
<add>server.listen(common.PORT, function() {
<add> var client = tls.connect(common.PORT);
<add>
<add> client.on('data', function(d) {
<add> recvCount += d.length;
<add>
<add> client.pause();
<add> process.nextTick(function () {
<add> client.resume();
<add> });
<add> });
<add>
<add>
<add> client.on('close', function() {
<add> server.close();
<add> clearTimeout(timeout);
<add> });
<add>});
<add>
<add>
<add>var timeout = setTimeout(function() {
<add> process.exit(1);
<add>}, 10*1000);
<add>
<add>
<add>process.on('exit', function() {
<add> assert.equal(1, connections);
<add> assert.equal(body.length, recvCount);
<add>}); | 1 |
Javascript | Javascript | fix fatal error | 5a8c0286933507a05a85d2595d3b31d0934610fa | <ide><path>scripts/locales.js
<ide> var args = process.argv.slice(2);
<ide> function help() {
<ide> console.log(process.argv[1], '[list|mention|find-commenters] ARGS');
<ide> console.log();
<del> console.log(" list show all authors in all locales");
<del> console.log(" mention show all authors in all locales, ready to copy-paste in github issue");
<del> console.log(" find-commenters #ID finds all people that participated in a github conversation");
<add> console.log(' list show all authors in all locales');
<add> console.log(' mention show all authors in all locales, ready to copy-paste in github issue');
<add> console.log(' find-commenters #ID finds all people that participated in a github conversation');
<ide> }
<ide>
<ide> function extract() {
<ide> function extract() {
<ide> content.split('\n').forEach(function (line) {
<ide> var match = line.match(/^\/\/! author(.*)$/);
<ide> if (match !== null) {
<del> // console.log(" ", line);
<ide> localeAuthors.push('---' + match[1]);
<ide> }
<ide> });
<ide> function list() {
<ide> function mention() {
<ide> var authors = extract();
<ide> Object.keys(authors).forEach(function (localeCode) {
<del> console.log('- [ ]', localeCode, authors[localeCode].map(function (author) { return "@" + author; }).join(" "));
<add> console.log('- [ ]', localeCode, authors[localeCode].map(function (author) { return '@' + author; }).join(' '));
<ide> });
<ide> }
<ide>
<ide> switch (args[0]) {
<ide> findCommenters(args[1]);
<ide> break;
<ide> default:
<del> console.log("unknown argument", args[0]);
<add> console.log('unknown argument', args[0]);
<ide> break;
<ide> } | 1 |
Javascript | Javascript | pick all the nits!!!1! | fe8008e67c7264f7ba4f0f2841622f42ca61dea3 | <ide><path>Gruntfile.js
<ide> module.exports = function(grunt) {
<ide> 'webdriver-jasmine:local',
<ide>
<ide> 'sauce-tunnel',
<del> // 'webdriver-jasmine:saucelabs_ios', // uncomment once tests pass on iOS
<ide> 'webdriver-jasmine:saucelabs_android',
<ide> 'webdriver-jasmine:saucelabs_firefox',
<del> 'webdriver-jasmine:saucelabs_chrome',
<del> // 'webdriver-jasmine:saucelabs_safari' // uncomment once tests pass in Safari
<add> 'webdriver-jasmine:saucelabs_chrome'
<ide> ]);
<ide>
<ide> grunt.registerTask('test:webdriver:saucelabs', [
<ide> module.exports = function(grunt) {
<ide>
<ide> 'connect',
<ide> 'sauce-tunnel',
<del> 'webdriver-jasmine:saucelabs_' + (process.env.BROWSER_NAME || 'ie8'),
<add> 'webdriver-jasmine:saucelabs_' + (process.env.BROWSER_NAME || 'ie8')
<ide> ]);
<ide>
<ide> grunt.registerTask('test:webdriver:saucelabs:ie', [ | 1 |
Python | Python | fix imagedatagenerator preprocessing_function | 738819de0b7e6bc45abed8d0640f02b81c6ac4e9 | <ide><path>keras/preprocessing/image.py
<ide> def standardize(self, x):
<ide> # Returns
<ide> The inputs, normalized.
<ide> """
<del> if self.preprocessing_function:
<del> x = self.preprocessing_function(x)
<ide> if self.rescale:
<ide> x *= self.rescale
<ide> if self.samplewise_center:
<ide> def _get_batches_of_transformed_samples(self, index_array):
<ide> dtype=K.floatx())
<ide> for i, j in enumerate(index_array):
<ide> x = self.x[j]
<add> if self.image_data_generator.preprocessing_function:
<add> x = self.image_data_generator.preprocessing_function(x)
<ide> x = self.image_data_generator.random_transform(x.astype(K.floatx()))
<ide> x = self.image_data_generator.standardize(x)
<ide> batch_x[i] = x
<ide> def _get_batches_of_transformed_samples(self, index_array):
<ide> fname = self.filenames[j]
<ide> img = load_img(os.path.join(self.directory, fname),
<ide> grayscale=grayscale,
<del> target_size=self.target_size,
<add> target_size=None,
<ide> interpolation=self.interpolation)
<add> if self.image_data_generator.preprocessing_function:
<add> img = self.image_data_generator.preprocessing_function(img)
<add> if self.target_size is not None:
<add> width_height_tuple = (self.target_size[1], self.target_size[0])
<add> if img.size != width_height_tuple:
<add> if self.interpolation not in _PIL_INTERPOLATION_METHODS:
<add> raise ValueError(
<add> 'Invalid interpolation method {} specified. Supported '
<add> 'methods are {}'.format(
<add> self.interpolation,
<add> ", ".join(_PIL_INTERPOLATION_METHODS.keys())))
<add> resample = _PIL_INTERPOLATION_METHODS[self.interpolation]
<add> img = img.resize(width_height_tuple, resample)
<ide> x = img_to_array(img, data_format=self.data_format)
<ide> x = self.image_data_generator.random_transform(x)
<ide> x = self.image_data_generator.standardize(x)
<ide><path>tests/keras/preprocessing/image_test.py
<ide> def test_directory_iterator(self, tmpdir):
<ide> with pytest.raises(ValueError):
<ide> x1, y1 = dir_seq[9]
<ide>
<add> # Test Preprocessing before resize
<add> def preprocess_test(img):
<add> return img.resize((1, 1))
<add>
<add> generator = image.ImageDataGenerator(preprocessing_function=preprocess_test)
<add> dir_seq = generator.flow_from_directory(str(tmpdir),
<add> target_size=(26, 26),
<add> color_mode='rgb',
<add> batch_size=1,
<add> class_mode='categorical')
<add>
<add> gen_x1, gen_y1 = dir_seq[1]
<add>
<add> test_x1 = image.load_img(os.path.join(dir_seq.directory, dir_seq.filenames[1]),
<add> grayscale=False)
<add> test_x1 = preprocess_test(test_x1)
<add> test_x1 = test_x1.resize((26, 26))
<add> test_x1 = image.img_to_array(test_x1)
<add> test_x1 = dir_seq.image_data_generator.random_transform(test_x1)
<add> test_x1 = dir_seq.image_data_generator.standardize(test_x1)
<add>
<add> assert gen_x1.shape[1:] == test_x1.shape
<add>
<ide> def test_directory_iterator_class_mode_input(self, tmpdir):
<ide> tmpdir.join('class-1').mkdir()
<ide> | 2 |
Ruby | Ruby | add modify_build_environment method | 5a62582b39b7df44c8068970728f0a2f800bf39f | <ide><path>Library/Homebrew/build.rb
<ide> end
<ide>
<ide> def install f
<del> ENV.x11 if f.external_deps.any? { |dep| dep.is_a? X11Dependency }
<add> f.external_deps.each { |dep| dep.modify_build_environment }
<ide>
<ide> f.recursive_deps.uniq.each do |dep|
<ide> dep = Formula.factory dep
<ide><path>Library/Homebrew/dependencies.rb
<ide> class Requirement
<ide> def satisfied?; false; end
<ide> def fatal?; false; end
<ide> def message; ""; end
<add> def modify_build_environment; nil end
<ide> end
<ide>
<ide>
<ide> def message; <<-EOS.undent
<ide> EOS
<ide> end
<ide>
<add> def modify_build_environment
<add> ENV.x11
<add> end
<add>
<ide> end | 2 |
Javascript | Javascript | fix deprecation for ember.handlebars.safestring | 8c341bc1d3f311cadcddd61d021c1908e75e86e4 | <ide><path>packages/ember-htmlbars/lib/compat.js
<ide> import Ember from 'ember-metal/core';
<del>import { deprecateFunc } from 'ember-metal/debug';
<add>import { htmlSafe } from 'ember-htmlbars/utils/string';
<add>import { deprecate } from 'ember-metal/debug';
<ide> import {
<del> SafeString,
<ide> escapeExpression
<ide> } from 'ember-htmlbars/utils/string';
<ide>
<ide> var EmberHandlebars = Ember.Handlebars = Ember.Handlebars || {};
<ide>
<del>EmberHandlebars.SafeString = deprecateFunc(
<del> 'Ember.Handlebars.SafeString is deprecated in favor of Ember.String.htmlSafe',
<del> {
<del> id: 'ember-htmlbars.ember-handlebars-safestring',
<del> until: '3.0.0',
<del> url: 'http://emberjs.com/deprecations/v2.x#toc_use-ember-string-htmlsafe-over-ember-handlebars-safestring'
<del> },
<del> SafeString);
<add>EmberHandlebars.SafeString = function(value) {
<add> deprecate(
<add> 'Ember.Handlebars.SafeString is deprecated in favor of Ember.String.htmlSafe',
<add> false,
<add> {
<add> id: 'ember-htmlbars.ember-handlebars-safestring',
<add> until: '3.0.0',
<add> url: 'http://emberjs.com/deprecations/v2.x#toc_use-ember-string-htmlsafe-over-ember-handlebars-safestring'
<add> }
<add> );
<add>
<add> return htmlSafe(value);
<add>};
<ide>
<ide> EmberHandlebars.Utils = {
<ide> escapeExpression: escapeExpression
<ide><path>packages/ember-htmlbars/tests/compat/safe_string_test.js
<ide> import EmberHandlebars from 'ember-htmlbars/compat';
<ide> QUnit.module('ember-htmlbars: compat - SafeString');
<ide>
<ide> QUnit.test('using new results in a deprecation', function(assert) {
<add> let result;
<add>
<ide> expectDeprecation(function() {
<del> new EmberHandlebars.SafeString('test');
<add> result = new EmberHandlebars.SafeString('<b>test</b>');
<ide> }, 'Ember.Handlebars.SafeString is deprecated in favor of Ember.String.htmlSafe');
<add>
<add> assert.equal(result.toHTML(), '<b>test</b>');
<ide> }); | 2 |
Ruby | Ruby | generate master.key even when require_master_key | 1740b1f2cb8104435b6041ec6bfaabe58a6d74e6 | <ide><path>activesupport/lib/active_support/encrypted_file.rb
<ide> def key
<ide> read_env_key || read_key_file || handle_missing_key
<ide> end
<ide>
<add> # Returns truthy if #key is truthy. Returns falsy otherwise. Unlike #key,
<add> # does not raise MissingKeyError when +raise_if_missing_key+ is true.
<add> def key?
<add> read_env_key || read_key_file
<add> end
<add>
<ide> # Reads the file and returns the decrypted content.
<ide> #
<ide> # Raises:
<ide><path>activesupport/test/encrypted_file_test.rb
<ide>
<ide> class EncryptedFileTest < ActiveSupport::TestCase
<ide> setup do
<add> @original_env_content_key = ENV["CONTENT_KEY"]
<add> ENV["CONTENT_KEY"] = nil
<add>
<ide> @content = "One little fox jumped over the hedge"
<ide>
<ide> @tmpdir = Dir.mktmpdir("encrypted-file-test-")
<ide> class EncryptedFileTest < ActiveSupport::TestCase
<ide> FileUtils.rm_rf @content_path
<ide> FileUtils.rm_rf @key_path
<ide> FileUtils.rm_rf @tmpdir
<add>
<add> ENV["CONTENT_KEY"] = @original_env_content_key
<ide> end
<ide>
<ide> test "reading content by env key" do
<ide> FileUtils.rm_rf @key_path
<ide>
<del> begin
<del> ENV["CONTENT_KEY"] = @key
<del> @encrypted_file.write @content
<add> ENV["CONTENT_KEY"] = @key
<add> @encrypted_file.write @content
<ide>
<del> assert_equal @content, @encrypted_file.read
<del> ensure
<del> ENV["CONTENT_KEY"] = nil
<del> end
<add> assert_equal @content, @encrypted_file.read
<ide> end
<ide>
<ide> test "reading content by key file" do
<ide> class EncryptedFileTest < ActiveSupport::TestCase
<ide> test "raise MissingKeyError when env key is blank" do
<ide> FileUtils.rm_rf @key_path
<ide>
<del> begin
<del> ENV["CONTENT_KEY"] = ""
<del> raised = assert_raise ActiveSupport::EncryptedFile::MissingKeyError do
<del> @encrypted_file.write @content
<del> @encrypted_file.read
<del> end
<del>
<del> assert_match(/Missing encryption key to decrypt file/, raised.message)
<del> ensure
<del> ENV["CONTENT_KEY"] = nil
<add> ENV["CONTENT_KEY"] = ""
<add> raised = assert_raise ActiveSupport::EncryptedFile::MissingKeyError do
<add> @encrypted_file.write @content
<add> @encrypted_file.read
<ide> end
<add>
<add> assert_match(/Missing encryption key to decrypt file/, raised.message)
<ide> end
<ide>
<ide> test "key can be added after MissingKeyError raised" do
<ide> class EncryptedFileTest < ActiveSupport::TestCase
<ide> end
<ide> end
<ide>
<add> test "key? is true when key file exists" do
<add> assert @encrypted_file.key?
<add> end
<add>
<add> test "key? is true when env key is present" do
<add> FileUtils.rm_rf @key_path
<add> ENV["CONTENT_KEY"] = @key
<add>
<add> assert @encrypted_file.key?
<add> end
<add>
<add> test "key? is false and does not raise when the key is missing" do
<add> FileUtils.rm_rf @key_path
<add>
<add> assert_nothing_raised do
<add> assert_not @encrypted_file.key?
<add> end
<add> end
<add>
<ide> test "raise InvalidKeyLengthError when key is too short" do
<ide> File.write(@key_path, ActiveSupport::EncryptedFile.generate_key[0..-2])
<ide>
<ide><path>railties/lib/rails/commands/credentials/credentials_command.rb
<ide> def edit
<ide>
<ide> ensure_editor_available(command: "bin/rails credentials:edit") || (return)
<ide>
<del> ensure_encryption_key_has_been_added if credentials.key.nil?
<add> ensure_encryption_key_has_been_added
<ide> ensure_credentials_have_been_added
<ide> ensure_diffing_driver_is_configured
<ide>
<ide> def credentials
<ide> end
<ide>
<ide> def ensure_encryption_key_has_been_added
<add> return if credentials.key?
<add>
<ide> require "rails/generators/rails/encryption_key_file/encryption_key_file_generator"
<ide>
<ide> encryption_key_file_generator = Rails::Generators::EncryptionKeyFileGenerator.new
<ide> def change_credentials_in_system_editor
<ide> end
<ide>
<ide> def missing_credentials_message
<del> if credentials.key.nil?
<add> if !credentials.key?
<ide> "Missing '#{key_path}' to decrypt credentials. See `bin/rails credentials:help`"
<ide> else
<ide> "File '#{content_path}' does not exist. Use `bin/rails credentials:edit` to change that."
<ide><path>railties/lib/rails/commands/encrypted/encrypted_command.rb
<ide> def edit(*)
<ide> require_application!
<ide>
<ide> ensure_editor_available(command: "bin/rails encrypted:edit") || (return)
<del> ensure_encryption_key_has_been_added if encrypted_configuration.key.nil?
<add> ensure_encryption_key_has_been_added
<ide> ensure_encrypted_configuration_has_been_added
<ide>
<ide> catch_editing_exceptions do
<ide> def encrypted_configuration
<ide> end
<ide>
<ide> def ensure_encryption_key_has_been_added
<add> return if encrypted_configuration.key?
<ide> encryption_key_file_generator.add_key_file(key_path)
<ide> encryption_key_file_generator.ignore_key_file(key_path)
<ide> end
<ide> def encrypted_file_generator
<ide> end
<ide>
<ide> def missing_encrypted_configuration_message
<del> if encrypted_configuration.key.nil?
<add> if !encrypted_configuration.key?
<ide> "Missing '#{key_path}' to decrypt data. See `bin/rails encrypted:help`"
<ide> else
<ide> "File '#{content_path}' does not exist. Use `bin/rails encrypted:edit #{content_path}` to change that."
<ide><path>railties/test/commands/credentials_test.rb
<ide> class Rails::Command::CredentialsCommandTest < ActiveSupport::TestCase
<ide> assert_equal 1, read_file(".gitignore").scan("config/master.key").length
<ide> end
<ide>
<add> test "edit command can add master key when require_master_key is true" do
<add> remove_file "config/credentials.yml.enc"
<add> remove_file "config/master.key"
<add> add_to_config "config.require_master_key = true"
<add>
<add> assert_nothing_raised { run_edit_command }
<add> assert_file "config/master.key"
<add> end
<add>
<ide> test "edit command does not add master key when `RAILS_MASTER_KEY` env specified" do
<ide> master_key = read_file("config/master.key")
<ide> remove_file "config/master.key"
<ide><path>railties/test/commands/encrypted_test.rb
<ide> class Rails::Command::EncryptedCommandTest < ActiveSupport::TestCase
<ide> assert_equal 1, read_file(".gitignore").scan("config/master.key").length
<ide> end
<ide>
<add> test "edit command can add master key when require_master_key is true" do
<add> remove_file "config/master.key"
<add> add_to_config "config.require_master_key = true"
<add>
<add> assert_nothing_raised { run_edit_command }
<add> assert_file "config/master.key"
<add> end
<add>
<ide> test "edit command does not add master key when `RAILS_MASTER_KEY` env specified" do
<ide> master_key = read_file("config/master.key")
<ide> remove_file "config/master.key" | 6 |
Text | Text | add key value pairs to javascript objects | 893ac48f25820d34d7d4962fa68c7e6c3c77d05a | <ide><path>curriculum/challenges/portuguese/02-javascript-algorithms-and-data-structures/basic-data-structures/add-key-value-pairs-to-javascript-objects.portuguese.md
<ide> console.log(foods);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>foods.bananas = 13;
<add>foods.grapes = 35;
<add>foods.strawberries = 27;
<ide> ```
<ide> </section> | 1 |
Javascript | Javascript | improve crypto test coverage | 0ab98f1e603cc580fce94818bd75ee0295a6a99e | <ide><path>test/parallel/test-crypto-sign-verify.js
<ide> const certPem = fixtures.readSync('test_cert.pem', 'ascii');
<ide> const keyPem = fixtures.readSync('test_key.pem', 'ascii');
<ide> const modSize = 1024;
<ide>
<add>{
<add> const Sign = crypto.Sign;
<add> const instance = Sign('SHA256');
<add> assert(instance instanceof Sign, 'Sign is expected to return a new ' +
<add> 'instance when called without `new`');
<add>}
<add>
<add>{
<add> const Verify = crypto.Verify;
<add> const instance = Verify('SHA256');
<add> assert(instance instanceof Verify, 'Verify is expected to return a new ' +
<add> 'instance when called without `new`');
<add>}
<add>
<add>common.expectsError(
<add> () => crypto.createVerify('SHA256').verify({
<add> key: certPem,
<add> padding: undefined,
<add> }, ''),
<add> {
<add> code: 'ERR_INVALID_OPT_VALUE',
<add> type: Error,
<add> message: 'The value "undefined" is invalid for option "padding"'
<add> });
<add>
<add>common.expectsError(
<add> () => crypto.createVerify('SHA256').verify({
<add> key: certPem,
<add> saltLength: undefined,
<add> }, ''),
<add> {
<add> code: 'ERR_INVALID_OPT_VALUE',
<add> type: Error,
<add> message: 'The value "undefined" is invalid for option "saltLength"'
<add> });
<add>
<ide> // Test signing and verifying
<ide> {
<ide> const s1 = crypto.createSign('SHA1') | 1 |
Javascript | Javascript | add test for negative stream drain counter | 5d3c51d937fe887b3bc16344b519d1ad20fa9ff6 | <ide><path>test/simple/test-stream2-readable-legacy-drain.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>
<add>var Stream = require('stream');
<add>var Readable = Stream.Readable;
<add>
<add>var r = new Readable();
<add>var N = 256;
<add>var reads = 0;
<add>r._read = function(n, cb) {
<add> return cb(null, ++reads === N ? null : new Buffer(1));
<add>};
<add>
<add>var rended = false;
<add>r.on('end', function() {
<add> rended = true;
<add>});
<add>
<add>var w = new Stream();
<add>w.writable = true;
<add>var writes = 0;
<add>var buffered = 0;
<add>w.write = function(c) {
<add> writes += c.length;
<add> buffered += c.length;
<add> process.nextTick(drain);
<add> return false;
<add>};
<add>
<add>function drain() {
<add> assert(buffered <= 2);
<add> buffered = 0;
<add> w.emit('drain');
<add>}
<add>
<add>
<add>var wended = false;
<add>w.end = function() {
<add> wended = true;
<add>};
<add>
<add>// Just for kicks, let's mess with the drain count.
<add>// This verifies that even if it gets negative in the
<add>// pipe() cleanup function, we'll still function properly.
<add>r.on('readable', function() {
<add> w.emit('drain');
<add>});
<add>
<add>r.pipe(w);
<add>process.on('exit', function() {
<add> assert(rended);
<add> assert(wended);
<add> console.error('ok');
<add>}); | 1 |
Javascript | Javascript | run crypto benchmark only once in tests | 6168959546f84449f6c12efbc65189c9b45a4130 | <ide><path>benchmark/crypto/aes-gcm-throughput.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ n, len, cipher }) {
<add> // Default cipher for tests.
<add> if (cipher === '')
<add> cipher = 'aes-128-gcm';
<ide> const message = Buffer.alloc(len, 'b');
<ide> const key = crypto.randomBytes(keylen[cipher]);
<ide> const iv = crypto.randomBytes(12);
<ide><path>benchmark/crypto/cipher-stream.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ api, cipher, type, len, writes }) {
<add> // Default cipher for tests.
<add> if (cipher === '')
<add> cipher = 'AES192';
<ide> if (api === 'stream' && /^v0\.[0-8]\./.test(process.version)) {
<ide> console.error('Crypto streams not available until v0.10');
<ide> // use the legacy, just so that we can compare them.
<ide><path>test/parallel/test-benchmark-crypto.js
<ide> const runBenchmark = require('../common/benchmark');
<ide>
<ide> runBenchmark('crypto',
<ide> [
<del> 'n=1',
<ide> 'algo=sha256',
<ide> 'api=stream',
<add> 'cipher=',
<ide> 'keylen=1024',
<ide> 'len=1',
<add> 'n=1',
<ide> 'out=buffer',
<ide> 'type=buf',
<ide> 'v=crypto',
<del> 'writes=1'
<add> 'writes=1',
<ide> ],
<ide> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); | 3 |
Java | Java | fix non-deterministic unit test | be9841a2925b02e893e48f7ab3e9d04f6964326b | <ide><path>rxjava-core/src/test/java/rx/operators/OperationParallelMergeTest.java
<ide> public void testParallelMerge() {
<ide>
<ide> @Test
<ide> public void testNumberOfThreads() {
<del> final ConcurrentHashMap<String, String> threads = new ConcurrentHashMap<String, String>();
<del> Observable.merge(getStreams())
<del> .toBlockingObservable().forEach(new Action1<String>() {
<del>
<del> @Override
<del> public void call(String o) {
<del> System.out.println("o: " + o + " Thread: " + Thread.currentThread());
<del> threads.put(Thread.currentThread().getName(), Thread.currentThread().getName());
<del> }
<del> });
<del>
<del> // without injecting anything, the getStream() method uses Interval which runs on a default scheduler
<del> assertEquals(Runtime.getRuntime().availableProcessors(), threads.keySet().size());
<del>
<del> // clear
<del> threads.clear();
<del>
<del> // now we parallelMerge into 3 streams and observeOn for each
<add> final ConcurrentHashMap<Long, Long> threads = new ConcurrentHashMap<Long, Long>();
<add> // parallelMerge into 3 streams and observeOn for each
<ide> // we expect 3 threads in the output
<ide> OperationParallelMerge.parallelMerge(getStreams(), 3)
<ide> .flatMap(new Func1<Observable<String>, Observable<String>>() {
<ide> public Observable<String> call(Observable<String> o) {
<ide>
<ide> @Override
<ide> public void call(String o) {
<del> System.out.println("o: " + o + " Thread: " + Thread.currentThread());
<del> threads.put(Thread.currentThread().getName(), Thread.currentThread().getName());
<add> System.out.println("o: " + o + " Thread: " + Thread.currentThread().getId());
<add> threads.put(Thread.currentThread().getId(), Thread.currentThread().getId());
<ide> }
<ide> });
<ide>
<ide> public void call(String o) {
<ide>
<ide> @Test
<ide> public void testNumberOfThreadsOnScheduledMerge() {
<del> final ConcurrentHashMap<String, String> threads = new ConcurrentHashMap<String, String>();
<add> final ConcurrentHashMap<Long, Long> threads = new ConcurrentHashMap<Long, Long>();
<ide>
<ide> // now we parallelMerge into 3 streams and observeOn for each
<ide> // we expect 3 threads in the output
<ide> public void testNumberOfThreadsOnScheduledMerge() {
<ide>
<ide> @Override
<ide> public void call(String o) {
<del> System.out.println("o: " + o + " Thread: " + Thread.currentThread());
<del> threads.put(Thread.currentThread().getName(), Thread.currentThread().getName());
<add> System.out.println("o: " + o + " Thread: " + Thread.currentThread().getId());
<add> threads.put(Thread.currentThread().getId(), Thread.currentThread().getId());
<ide> }
<ide> });
<ide> | 1 |
Python | Python | add note about mailing list | 60b1591efa7ddcf3ae7fa2982102d457fb74b388 | <ide><path>setup.py
<ide> def get_package_data(package):
<ide> license='BSD',
<ide> description='A lightweight REST framework for Django.',
<ide> author='Tom Christie',
<del> author_email='[email protected]',
<add> author_email='[email protected]', # SEE NOTE BELOW (*)
<ide> packages=get_packages('rest_framework'),
<ide> package_data=get_package_data('rest_framework'),
<ide> test_suite='rest_framework.runtests.runtests.main',
<ide> def get_package_data(package):
<ide> 'Topic :: Internet :: WWW/HTTP',
<ide> ]
<ide> )
<add>
<add># (*) Please direct queries to the discussion group, rather than to me directly
<add># Doing so helps ensure your question is helpful to other users.
<add># Queries directly to my email are likely to receive a canned response.
<add>#
<add># Many thanks for your understanding. | 1 |
Go | Go | remove import of opencontainers/runc in windows | 4d1d486202a7c3977e51275c2efdba922375b0cd | <ide><path>daemon/daemon_windows.go
<ide> import (
<ide> winlibnetwork "github.com/docker/libnetwork/drivers/windows"
<ide> "github.com/docker/libnetwork/netlabel"
<ide> "github.com/docker/libnetwork/options"
<del> blkiodev "github.com/opencontainers/runc/libcontainer/configs"
<add> specs "github.com/opencontainers/runtime-spec/specs-go"
<ide> "github.com/pkg/errors"
<ide> "github.com/sirupsen/logrus"
<ide> "golang.org/x/sys/windows"
<ide> func getPluginExecRoot(root string) string {
<ide> return filepath.Join(root, "plugins")
<ide> }
<ide>
<del>func getBlkioWeightDevices(config *containertypes.HostConfig) ([]blkiodev.WeightDevice, error) {
<add>func getBlkioWeightDevices(config containertypes.Resources) ([]specs.LinuxWeightDevice, error) {
<ide> return nil, nil
<ide> }
<ide> | 1 |
Javascript | Javascript | provide buffer to connection.setsession | 4266f5cf2ebe171b5b32ce780bed3c307d3a1a94 | <ide><path>lib/tls.js
<ide> exports.connect = function(/* [port, host], options, cb */) {
<ide> });
<ide>
<ide> if (options.session) {
<del> pair.ssl.setSession(options.session);
<add> var session = options.session;
<add> if (typeof session === 'string')
<add> session = new Buffer(session, 'binary');
<add> pair.ssl.setSession(session);
<ide> }
<ide>
<ide> var cleartext = pipe(pair, socket); | 1 |
Ruby | Ruby | simplify curlgithubpackagesdownloadstrategy usage | 8144fdef783623e3501eb475cf14414ec3dc3dad | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def curl(*args, **options)
<ide> #
<ide> # @api public
<ide> class CurlGitHubPackagesDownloadStrategy < CurlDownloadStrategy
<del> attr_accessor :checksum, :name
<add> attr_writer :resolved_basename
<ide>
<del> private
<del>
<del> def _fetch(url:, resolved_url:)
<del> raise CurlDownloadStrategyError, "Empty checksum" if checksum.blank?
<del> raise CurlDownloadStrategyError, "Empty name" if name.blank?
<add> def initialize(url, name, version, **meta)
<add> meta ||= {}
<add> meta[:header] = "Authorization: Bearer"
<add> super(url, name, version, meta)
<add> end
<ide>
<del> _, org, repo, = *url.match(GitHubPackages::URL_REGEX)
<add> private
<ide>
<del> # remove redundant repo prefix for a shorter name
<del> repo = repo.delete_prefix("homebrew-")
<del> blob_url = "#{GitHubPackages::URL_PREFIX}#{org}/#{repo}/#{name}/blobs/sha256:#{checksum}"
<del> curl_download(blob_url, "--header", "Authorization: Bearer", to: temporary_path)
<add> def resolved_basename
<add> @resolved_basename.presence || super
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/software_spec.rb
<ide> def initialize(formula, spec)
<ide>
<ide> checksum, tag, cellar = spec.checksum_for(Utils::Bottles.tag)
<ide>
<del> filename = Filename.create(formula, tag, spec.rebuild)
<del> @resource.url("#{spec.root_url}/#{filename.bintray}",
<del> select_download_strategy(spec.root_url_specs))
<add> filename = Filename.create(formula, tag, spec.rebuild).bintray
<add>
<add> # TODO: this will need adjusted when if we use GitHub Packages by default
<add> path, resolved_basename = if (bottle_domain = Homebrew::EnvConfig.bottle_domain.presence) &&
<add> bottle_domain.start_with?(GitHubPackages::URL_PREFIX)
<add> ["#{@name}/blobs/sha256:#{checksum}", filename]
<add> else
<add> filename
<add> end
<add>
<add> @resource.url("#{spec.root_url}/#{path}", select_download_strategy(spec.root_url_specs))
<add> @resource.downloader.resolved_basename = resolved_basename if resolved_basename.present?
<ide> @resource.version = formula.pkg_version
<ide> @resource.checksum = checksum
<ide> @prefix = spec.prefix
<ide> def initialize(formula, spec)
<ide>
<ide> def fetch(verify_download_integrity: true)
<ide> # add the default bottle domain as a fallback mirror
<del> # TODO: this may need adjusted when if we use GitHub Packages by default
<ide> if @resource.download_strategy == CurlDownloadStrategy &&
<ide> @resource.url.start_with?(Homebrew::EnvConfig.bottle_domain)
<ide> fallback_url = @resource.url
<ide> .sub(/^#{Regexp.escape(Homebrew::EnvConfig.bottle_domain)}/,
<ide> HOMEBREW_BOTTLE_DEFAULT_DOMAIN)
<ide> @resource.mirror(fallback_url) if [@resource.url, *@resource.mirrors].exclude?(fallback_url)
<del> elsif @resource.download_strategy == CurlGitHubPackagesDownloadStrategy
<del> @resource.downloader.name = @name
<del> @resource.downloader.checksum = @resource.checksum.hexdigest
<ide> end
<ide> @resource.fetch(verify_download_integrity: verify_download_integrity)
<ide> end
<ide> def prefix=(prefix)
<ide> def root_url(var = nil, specs = {})
<ide> if var.nil?
<ide> @root_url ||= if Homebrew::EnvConfig.bottle_domain.start_with?(GitHubPackages::URL_PREFIX)
<del> "#{GitHubPackages::URL_PREFIX}#{tap.full_name}"
<add> GitHubPackages.root_url(tap.user, tap.repo).to_s
<ide> else
<ide> "#{Homebrew::EnvConfig.bottle_domain}/#{Utils::Bottles::Bintray.repository(tap)}"
<ide> end | 2 |
Python | Python | fix fab install command | eaef36e4a50e46a81904afafcbf90edef6736a13 | <ide><path>fabfile.py
<ide> def install():
<ide> def make():
<ide> with lcd(path.dirname(__file__)):
<ide> with virtualenv(VENV_DIR) as venv_local:
<add> venv_local('pip install wheel')
<ide> venv_local('pip install cython')
<ide> venv_local('pip install murmurhash')
<del> venv_local('pip install wheel')
<ide> venv_local('pip install -r requirements.txt')
<ide> venv_local('python setup.py build_ext --inplace')
<ide> | 1 |
PHP | PHP | escape path in sendoutputto() | 6b5571b08d7696b02844f8b211fa2cd52c46c585 | <ide><path>src/Illuminate/Console/Scheduling/Event.php
<ide> use GuzzleHttp\Client as HttpClient;
<ide> use Illuminate\Contracts\Mail\Mailer;
<ide> use Symfony\Component\Process\Process;
<add>use Symfony\Component\Process\ProcessUtils;
<ide> use Illuminate\Contracts\Container\Container;
<ide> use Illuminate\Contracts\Foundation\Application;
<ide>
<ide> public function skip(Closure $callback)
<ide> */
<ide> public function sendOutputTo($location, $append = false)
<ide> {
<del> $this->output = $location;
<add> $this->output = ProcessUtils::escapeArgument($location);
<ide>
<ide> $this->shouldAppendOutput = $append;
<ide>
<ide><path>tests/Console/Scheduling/EventTest.php
<ide> public function testBuildCommand()
<ide> $this->assertSame("php -i > {$defaultOutput} 2>&1 &", $event->buildCommand());
<ide> }
<ide>
<add> public function testBuildCommandSendOutputTo()
<add> {
<add> $event = new Event('php -i');
<add>
<add> $event->sendOutputTo('/dev/null');
<add> $this->assertSame("php -i > '/dev/null' 2>&1 &", $event->buildCommand());
<add>
<add> $event = new Event('php -i');
<add>
<add> $event->sendOutputTo('/my folder/foo.log');
<add> $this->assertSame("php -i > '/my folder/foo.log' 2>&1 &", $event->buildCommand());
<add> }
<add>
<ide> public function testBuildCommandAppendOutput()
<ide> {
<ide> $event = new Event('php -i');
<ide>
<ide> $event->appendOutputTo('/dev/null');
<del> $this->assertSame('php -i >> /dev/null 2>&1 &', $event->buildCommand());
<add> $this->assertSame("php -i >> '/dev/null' 2>&1 &", $event->buildCommand());
<ide> }
<ide> } | 2 |
Text | Text | add notable-change to onboarding.md exercise | 77d3f141cf465613f0bcd270c6bd2bcd9c962f92 | <ide><path>doc/onboarding.md
<ide> needs to be pointed out separately during the onboarding.
<ide> -1`
<ide> * Collaborators are in alphabetical order by GitHub username.
<ide> * Optionally, include your personal pronouns.
<del>* Label your pull request with the `doc` subsystem label.
<add>* Label your pull request with the `doc` and `notable-change` labels.
<ide> * Run CI on the PR. Because the PR does not affect any code, use the
<ide> `node-test-pull-request-lite` CI task. Alternatively, use the usual
<ide> `node-test-pull-request` CI task and cancel it after the linter and one other | 1 |
Javascript | Javascript | move call to fs.realpathsync to compilecache | 00a020d1750c89bf3f65eafaa7e0649664452ba8 | <ide><path>spec/package-transpilation-registry-spec.js
<ide> describe("PackageTranspilationRegistry", () => {
<ide> jsSpec._transpilerSource = "js-transpiler-source"
<ide> coffeeSpec._transpilerSource = "coffee-transpiler-source"
<ide>
<del> const oldFsRealpathSync = fs.realpathSync.bind(fs)
<del> spyOn(fs, 'realpathSync').andCallFake(thePath => {
<del> if (thePath === '/path/to') return thePath
<del> if (thePath === '/path/other') return thePath
<del> return oldFsRealpathSync(thePath)
<del> })
<del>
<ide> spyOn(registry, "getTranspiler").andCallFake(spec => {
<ide> if (spec.transpiler === './transpiler-js') return jsTranspiler
<ide> if (spec.transpiler === './transpiler-coffee') return coffeeTranspiler
<ide><path>src/compile-cache.js
<ide> var COMPILERS = {
<ide> }
<ide>
<ide> exports.addTranspilerConfigForPath = function (packagePath, config) {
<add> packagePath = fs.realpathSync(packagePath)
<ide> packageTranspilationRegistry.addTranspilerConfigForPath(packagePath, config)
<ide> }
<ide>
<ide> exports.removeTranspilerConfigForPath = function (packagePath) {
<add> packagePath = fs.realpathSync(packagePath)
<ide> packageTranspilationRegistry.removeTranspilerConfigForPath(packagePath)
<ide> }
<ide>
<ide><path>src/package-transpilation-registry.js
<ide> function PackageTranspilationRegistry () {
<ide>
<ide> Object.assign(PackageTranspilationRegistry.prototype, {
<ide> addTranspilerConfigForPath: function (packagePath, config) {
<del> packagePath = fs.realpathSync(packagePath)
<ide> this.configByPackagePath[packagePath] = {
<ide> specs: config,
<ide> path: packagePath
<ide> }
<ide> },
<ide>
<ide> removeTranspilerConfigForPath: function (packagePath) {
<del> packagePath = fs.realpathSync(packagePath)
<ide> delete this.configByPackagePath[packagePath]
<ide> },
<ide> | 3 |
Ruby | Ruby | support implicit render and blank render | 49834e088bf8d02a4f75793a42868f2aea8749a4 | <ide><path>actionpack/lib/action_controller/abstract/base.rb
<ide> def process(action_name)
<ide>
<ide> private
<ide>
<add> # It is possible for respond_to?(action_name) to be false and
<add> # respond_to?(:action_missing) to be false if respond_to_action?
<add> # is overridden in a subclass. For instance, ActionController::Base
<add> # overrides it to include the case where a template matching the
<add> # action_name is found.
<ide> def process_action
<del> respond_to?(action_name) ? send(action_name) : send(:action_missing, action_name)
<add> if respond_to?(action_name) then send(action_name)
<add> elsif respond_to?(:action_missing, true) then send(:action_missing, action_name)
<add> end
<ide> end
<ide>
<add> # Override this to change the conditions that will raise an
<add> # ActionNotFound error. If you accept a difference case,
<add> # you must handle it by also overriding process_action and
<add> # handling the case.
<ide> def respond_to_action?(action_name)
<ide> respond_to?(action_name) || respond_to?(:action_missing, true)
<ide> end
<ide><path>actionpack/lib/action_controller/abstract/renderer.rb
<ide> def render(options = {})
<ide> def render_to_body(options = {})
<ide> name = options[:_template_name] || action_name
<ide>
<del> template = options[:_template] || view_paths.find_by_parts(name.to_s, {:formats => formats}, options[:_prefix])
<add> options[:_template] ||= view_paths.find_by_parts(name.to_s, {:formats => formats}, options[:_prefix])
<ide>
<del> _render_template(template, options)
<add> _render_template(options[:_template], options)
<ide> end
<ide>
<ide> # Raw rendering of a template to a string.
<ide><path>actionpack/lib/action_controller/new_base/renderer.rb
<ide> def initialize(*)
<ide> super
<ide> end
<ide>
<del> def render(action, options = {})
<del> # TODO: Move this into #render_to_body
<del> if action.is_a?(Hash)
<del> options, action = action, nil
<del> else
<del> options.merge! :action => action
<del> end
<del>
<add> def render(options = {})
<ide> _process_options(options)
<ide>
<ide> super(options)
<ide><path>actionpack/test/new_base/render_implicit_action_test.rb
<ide> module RenderImplicitAction
<ide> class SimpleController < ::ApplicationController
<ide> self.view_paths = [ActionView::Template::FixturePath.new(
<ide> "render_implicit_action/simple/hello_world.html.erb" => "Hello world!",
<del> "render_implicit_action/simple/hyphen-ated.html.erb" => "Hello hyphen-ated"
<add> "render_implicit_action/simple/hyphen-ated.html.erb" => "Hello hyphen-ated!"
<ide> )]
<ide>
<ide> def hello_world() end
<ide> end
<ide>
<del> # class TestImplicitRender < SimpleRouteCase
<del> # describe "render a simple action with new explicit call to render"
<del> #
<del> # get "/render_implicit_action/simple/hello_world"
<del> # assert_body "Hello world!"
<del> # assert_status 200
<del> # end
<del> #
<del> # class TestImplicitWithSpecialCharactersRender < SimpleRouteCase
<del> # describe "render an action with a missing method and has special characters"
<del> #
<del> # get "/render_implicit_action/simple/hyphen-ated"
<del> # assert_body "Hello hyphen-ated!"
<del> # assert_status 200
<del> # end
<add> class TestImplicitRender < SimpleRouteCase
<add> describe "render a simple action with new explicit call to render"
<add>
<add> get "/render_implicit_action/simple/hello_world"
<add> assert_body "Hello world!"
<add> assert_status 200
<add> end
<add>
<add> class TestImplicitWithSpecialCharactersRender < SimpleRouteCase
<add> describe "render an action with a missing method and has special characters"
<add>
<add> get "/render_implicit_action/simple/hyphen-ated"
<add> assert_body "Hello hyphen-ated!"
<add> assert_status 200
<add> end
<ide> end
<ide>\ No newline at end of file
<ide><path>actionpack/test/new_base/render_test.rb
<ide> require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
<ide>
<ide> module Render
<add> class BlankRenderController < ActionController::Base2
<add> self.view_paths = [ActionView::Template::FixturePath.new(
<add> "render/blank_render/index.html.erb" => "Hello world!"
<add> )]
<add>
<add> def index
<add> render
<add> end
<add> end
<add>
<add> class TestBlankRender < SimpleRouteCase
<add> describe "Render with blank"
<add>
<add> get "/render/blank_render"
<add> assert_body "Hello world!"
<add> assert_status 200
<add> end
<add>
<ide> class DoubleRenderController < ActionController::Base2
<ide> def index
<ide> render :text => "hello"
<ide><path>actionpack/test/new_base/test_helper.rb
<ide> def self.app_loaded!
<ide> end
<ide> end
<ide>
<add> def render(action = action_name, options = {})
<add> if action.is_a?(Hash)
<add> options, action = action, nil
<add> else
<add> options.merge! :action => action
<add> end
<add>
<add> super(options)
<add> end
<add>
<ide> def render_to_body(options = {})
<ide> options = {:template => options} if options.is_a?(String)
<ide> super
<ide> end
<ide>
<add> def process_action
<add> ret = super
<add> render if response_body.nil?
<add> ret
<add> end
<add>
<add> def respond_to_action?(action_name)
<add> super || view_paths.find_by_parts(action_name, {:formats => formats, :locales => [I18n.locale]}, controller_path)
<add> end
<add>
<ide> # append_view_path File.join(File.dirname(__FILE__), '..', 'fixtures')
<ide>
<ide> CORE_METHODS = self.public_instance_methods | 6 |
Go | Go | add todos for driver changes | 5c30c4379af20b3cbd2d20cc9f0ccb6f04ac63ab | <ide><path>execdriver/driver.go
<ide> type Info interface {
<ide> type Driver interface {
<ide> Run(c *Process, startCallback StartCallback) (int, error) // Run executes the process and blocks until the process exits and returns the exit code
<ide> Kill(c *Process, sig int) error
<del> Wait(id string) error // Wait on an out of process...process - lxc ghosts
<add> Wait(id string) error // Wait on an out of process...process - lxc ghosts TODO: Rename to reattach, reconnect
<ide> Name() string // Driver name
<ide> Info(id string) Info // "temporary" hack (until we move state from core to plugins)
<ide> }
<ide> type Network struct {
<ide> }
<ide>
<ide> // Process wrapps an os/exec.Cmd to add more metadata
<add>// TODO: Rename to Command
<ide> type Process struct {
<ide> exec.Cmd
<ide> | 1 |
Ruby | Ruby | fix class_eval without __file__ and __line__ | 414008f98e6eefb6efe14a93b6a969fbae3d339f | <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb
<ide> def define_mounted_helper(name)
<ide> end
<ide> end
<ide>
<del> MountedHelpers.class_eval <<-RUBY
<add> MountedHelpers.class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
<ide> def #{name}
<ide> @#{name} ||= _#{name}
<ide> end
<ide><path>activerecord/test/cases/associations/has_many_associations_test.rb
<ide> def test_creating_using_primary_key
<ide>
<ide> def test_defining_has_many_association_with_delete_all_dependency_lazily_evaluates_target_class
<ide> ActiveRecord::Reflection::AssociationReflection.any_instance.expects(:class_name).never
<del> class_eval <<-EOF
<add> class_eval(<<-EOF, __FILE__, __LINE__ + 1)
<ide> class DeleteAllModel < ActiveRecord::Base
<ide> has_many :nonentities, :dependent => :delete_all
<ide> end
<ide> class DeleteAllModel < ActiveRecord::Base
<ide>
<ide> def test_defining_has_many_association_with_nullify_dependency_lazily_evaluates_target_class
<ide> ActiveRecord::Reflection::AssociationReflection.any_instance.expects(:class_name).never
<del> class_eval <<-EOF
<add> class_eval(<<-EOF, __FILE__, __LINE__ + 1)
<ide> class NullifyModel < ActiveRecord::Base
<ide> has_many :nonentities, :dependent => :nullify
<ide> end
<ide><path>activerecord/test/cases/attribute_methods_test.rb
<ide> def in_time_zone(zone)
<ide> end
<ide>
<ide> def privatize(method_signature)
<del> @target.class_eval <<-private_method
<add> @target.class_eval(<<-private_method, __FILE__, __LINE__ + 1)
<ide> private
<ide> def #{method_signature}
<ide> "I'm private"
<ide><path>activesupport/test/multibyte_chars_test.rb
<ide> def test_split_should_return_an_array_of_chars_instances
<ide> end
<ide>
<ide> %w{capitalize downcase lstrip reverse rstrip swapcase upcase}.each do |method|
<del> class_eval(<<-EOTESTS)
<add> class_eval(<<-EOTESTS, __FILE__, __LINE__ + 1)
<ide> def test_#{method}_bang_should_return_self_when_modifying_wrapped_string
<ide> chars = ' él piDió Un bUen café '
<ide> assert_equal chars.object_id, chars.send("#{method}!").object_id
<ide><path>railties/test/generators_test.rb
<ide> def test_nested_fallbacks_for_generators
<ide> def test_developer_options_are_overwriten_by_user_options
<ide> Rails::Generators.options[:with_options] = { :generate => false }
<ide>
<del> self.class.class_eval <<-end_eval
<add> self.class.class_eval(<<-end_eval, __FILE__, __LINE__ + 1)
<ide> class WithOptionsGenerator < Rails::Generators::Base
<ide> class_option :generate, :default => true
<ide> end | 5 |
Python | Python | fix a bag merge | e4defb886a27a45d4dd84760d868341d16b68a9b | <ide><path>libcloud/compute/drivers/vcloud.py
<ide> def __new__(cls, key, secret=None, secure=True, host=None, port=None,
<ide> elif api_version == '1.5':
<ide> cls = VCloud_1_5_NodeDriver
<ide> elif api_version == '5.1':
<del> cls = VCloud_1_5_NodeDriver
<add> cls = VCloud_5_1_NodeDriver
<ide> else:
<ide> raise NotImplementedError(
<ide> "No VCloudNodeDriver found for API version %s" % | 1 |
Javascript | Javascript | remove trailing whitespace | c1576fcf9744882fa59c2876fb4fd44720140307 | <ide><path>src/core/React.js
<ide> ReactDefaultInjection.inject();
<ide>
<ide> var React = {
<ide> DOM: ReactDOM,
<del> Props: ReactProps,
<add> Props: ReactProps,
<ide> initializeTouchEvents: function(shouldUseTouch) {
<ide> ReactMount.useTouchEvents = shouldUseTouch;
<ide> }, | 1 |
Go | Go | fix some issues in logfile reader and rotation | e87e9e6ad6ba501cc42a2ef47ac18c88a68f258f | <ide><path>daemon/logger/loggerutils/logfile.go
<ide> type LogFile struct {
<ide>
<ide> type makeDecoderFunc func(rdr io.Reader) func() (*logger.Message, error)
<ide>
<del>//NewLogFile creates new LogFile
<add>// NewLogFile creates new LogFile
<ide> func NewLogFile(logPath string, capacity int64, maxFiles int, compress bool, marshaller logger.MarshalFunc, decodeFunc makeDecoderFunc, perms os.FileMode) (*LogFile, error) {
<ide> log, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, perms)
<ide> if err != nil {
<ide> func rotate(name string, maxFiles int, compress bool) error {
<ide> if compress {
<ide> extension = ".gz"
<ide> }
<add>
<add> lastFile := fmt.Sprintf("%s.%d%s", name, maxFiles-1, extension)
<add> err := os.Remove(lastFile)
<add> if err != nil && !os.IsNotExist(err) {
<add> return errors.Wrap(err, "error removing oldest log file")
<add> }
<add>
<ide> for i := maxFiles - 1; i > 1; i-- {
<ide> toPath := name + "." + strconv.Itoa(i) + extension
<ide> fromPath := name + "." + strconv.Itoa(i-1) + extension
<ide> func compressFile(fileName string, lastTimestamp time.Time) {
<ide> }
<ide> }()
<ide>
<del> outFile, err := os.OpenFile(fileName+".gz", os.O_CREATE|os.O_RDWR, 0640)
<add> outFile, err := os.OpenFile(fileName+".gz", os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0640)
<ide> if err != nil {
<ide> logrus.Errorf("Failed to open or create gzip log file: %v", err)
<ide> return
<ide> func compressFile(fileName string, lastTimestamp time.Time) {
<ide> compressWriter.Header.Extra, err = json.Marshal(&extra)
<ide> if err != nil {
<ide> // Here log the error only and don't return since this is just an optimization.
<del> logrus.Warningf("Failed to marshal JSON: %v", err)
<add> logrus.Warningf("Failed to marshal gzip header as JSON: %v", err)
<ide> }
<ide>
<ide> _, err = pools.Copy(compressWriter, file)
<ide> func (w *LogFile) Close() error {
<ide> }
<ide>
<ide> // ReadLogs decodes entries from log files and sends them the passed in watcher
<add>//
<add>// Note: Using the follow option can become inconsistent in cases with very frequent rotations and max log files is 1.
<add>// TODO: Consider a different implementation which can effectively follow logs under frequent rotations.
<ide> func (w *LogFile) ReadLogs(config logger.ReadConfig, watcher *logger.LogWatcher) {
<ide> w.mu.RLock()
<ide> currentFile, err := os.Open(w.f.Name())
<ide> func (w *LogFile) openRotatedFiles(config logger.ReadConfig) (files []*os.File,
<ide> f, err := os.Open(fmt.Sprintf("%s.%d", w.f.Name(), i-1))
<ide> if err != nil {
<ide> if !os.IsNotExist(err) {
<del> return nil, err
<add> return nil, errors.Wrap(err, "error opening rotated log file")
<ide> }
<ide>
<ide> fileName := fmt.Sprintf("%s.%d.gz", w.f.Name(), i-1)
<ide> func (w *LogFile) openRotatedFiles(config logger.ReadConfig) (files []*os.File,
<ide> })
<ide>
<ide> if err != nil {
<del> if !os.IsNotExist(err) {
<del> return nil, err
<add> if !os.IsNotExist(errors.Cause(err)) {
<add> return nil, errors.Wrap(err, "error getting reference to decompressed log file")
<ide> }
<ide> continue
<ide> }
<ide> func (w *LogFile) openRotatedFiles(config logger.ReadConfig) (files []*os.File,
<ide> func decompressfile(fileName, destFileName string, since time.Time) (*os.File, error) {
<ide> cf, err := os.Open(fileName)
<ide> if err != nil {
<del> return nil, err
<add> return nil, errors.Wrap(err, "error opening file for decompression")
<ide> }
<ide> defer cf.Close()
<ide>
<ide> rc, err := gzip.NewReader(cf)
<ide> if err != nil {
<del> return nil, err
<add> return nil, errors.Wrap(err, "error making gzip reader for compressed log file")
<ide> }
<ide> defer rc.Close()
<ide>
<ide> func decompressfile(fileName, destFileName string, since time.Time) (*os.File, e
<ide>
<ide> rs, err := os.OpenFile(destFileName, os.O_CREATE|os.O_RDWR, 0640)
<ide> if err != nil {
<del> return nil, err
<add> return nil, errors.Wrap(err, "error creating file for copying decompressed log stream")
<ide> }
<ide>
<ide> _, err = pools.Copy(rs, rc)
<ide> if err != nil {
<ide> rs.Close()
<ide> rErr := os.Remove(rs.Name())
<del> if rErr != nil && os.IsNotExist(rErr) {
<add> if rErr != nil && !os.IsNotExist(rErr) {
<ide> logrus.Errorf("Failed to remove the logfile %q: %v", rs.Name(), rErr)
<ide> }
<del> return nil, err
<add> return nil, errors.Wrap(err, "error while copying decompressed log stream to file")
<ide> }
<ide>
<ide> return rs, nil
<ide> func tailFile(f io.ReadSeeker, watcher *logger.LogWatcher, createDecoder makeDec
<ide> for {
<ide> msg, err := decodeLogLine()
<ide> if err != nil {
<del> if err != io.EOF {
<add> if errors.Cause(err) != io.EOF {
<ide> watcher.Err <- err
<ide> }
<ide> return
<ide> func followLogs(f *os.File, logWatcher *logger.LogWatcher, notifyRotate chan int
<ide> }
<ide>
<ide> handleDecodeErr := func(err error) error {
<del> if err != io.EOF {
<add> if errors.Cause(err) != io.EOF {
<ide> return err
<ide> }
<ide> | 1 |
Text | Text | fix webcrypto hmac generatekey example | 29789f78b2dd929f0be5daf6a37f56ffe8ee111b | <ide><path>doc/api/webcrypto.md
<ide> const { subtle } = require('crypto').webcrypto;
<ide> (async function() {
<ide>
<ide> const key = await subtle.generateKey({
<del> name: 'hmac',
<del> length: 123
<add> name: 'HMAC',
<add> hash: 'SHA-256',
<add> length: 256
<ide> }, true, ['sign', 'verify']);
<ide>
<ide> const digest = await subtle.sign({
<del> name: 'hmac'
<add> name: 'HMAC'
<ide> }, key, 'I love cupcakes');
<ide>
<ide> })(); | 1 |
Javascript | Javascript | fix output path for the fabric provider | b174ccffad9da3e11336b4b8c82958e683b7e330 | <ide><path>scripts/generate-artifacts.js
<ide> function main(appRootDir, outputPath) {
<ide>
<ide> const schemaPaths = {};
<ide>
<add> const iosOutputDir = path.join(
<add> outputPath ? outputPath : appRootDir,
<add> 'build/generated/ios',
<add> );
<add>
<ide> // 5. For each codegen-enabled library, generate the native code spec files
<ide> libraries.forEach(library => {
<ide> if (!CODEGEN_FABRIC_ENABLED && library.config.type === 'components') {
<ide> function main(appRootDir, outputPath) {
<ide> library.config.jsSrcsDir,
<ide> );
<ide> const pathToOutputDirIOS = path.join(
<del> outputPath ? outputPath : appRootDir,
<del> 'build/generated/ios',
<add> iosOutputDir,
<ide> library.config.type === 'components'
<ide> ? 'react/renderer/components'
<ide> : './',
<ide> function main(appRootDir, outputPath) {
<ide>
<ide> // Generate FabricComponentProvider.
<ide> // Only for iOS at this moment.
<del> const providerOutputPathIOS = path.join(
<del> appRootDir,
<del> 'build',
<del> 'generated',
<del> 'ios',
<del> );
<ide> execSync(
<ide> `node ${path.join(
<ide> RN_ROOT,
<ide> 'scripts',
<ide> 'generate-provider-cli.js',
<del> )} --platform ios --schemaListPath "${schemaListTmpPath}" --outputDir ${providerOutputPathIOS}`,
<add> )} --platform ios --schemaListPath "${schemaListTmpPath}" --outputDir ${iosOutputDir}`,
<ide> );
<del> console.log(`Generated provider in: ${providerOutputPathIOS}`);
<add> console.log(`Generated provider in: ${iosOutputDir}`);
<ide> } catch (err) {
<ide> console.error(err);
<ide> process.exitCode = 1; | 1 |
Ruby | Ruby | remove is_a? check when ignoring tables | 17efb3b919e8eff1ca5da49b12e3c1f607eb93e3 | <ide><path>activerecord/lib/active_record/schema_dumper.rb
<ide> def remove_prefix_and_suffix(table)
<ide>
<ide> def ignored?(table_name)
<ide> ['schema_migrations', ignore_tables].flatten.any? do |ignored|
<del> case ignored
<del> when String; remove_prefix_and_suffix(table_name) == ignored
<del> when Regexp; remove_prefix_and_suffix(table_name) =~ ignored
<del> else
<del> raise StandardError, 'ActiveRecord::SchemaDumper.ignore_tables accepts an array of String and / or Regexp values.'
<del> end
<add> ignored === remove_prefix_and_suffix(table_name)
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/schema_dumper_test.rb
<ide> def test_schema_dump_with_regexp_ignored_table
<ide> assert_no_match %r{create_table "schema_migrations"}, output
<ide> end
<ide>
<del> def test_schema_dump_illegal_ignored_table_value
<del> stream = StringIO.new
<del> old_ignore_tables, ActiveRecord::SchemaDumper.ignore_tables = ActiveRecord::SchemaDumper.ignore_tables, [5]
<del> assert_raise(StandardError) do
<del> ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
<del> end
<del> ensure
<del> ActiveRecord::SchemaDumper.ignore_tables = old_ignore_tables
<del> end
<del>
<ide> def test_schema_dumps_index_columns_in_right_order
<ide> index_definition = standard_dump.split(/\n/).grep(/add_index.*companies/).first.strip
<ide> if current_adapter?(:MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter) | 2 |
Go | Go | add a check for size field in custom format string | 55cdb6dcd0f709301573ddb9f3348f9288572b91 | <ide><path>api/client/formatter/formatter.go
<ide> type ImageContext struct {
<ide> func (ctx ContainerContext) Write() {
<ide> switch ctx.Format {
<ide> case tableFormatKey:
<del> ctx.Format = defaultContainerTableFormat
<ide> if ctx.Quiet {
<ide> ctx.Format = defaultQuietFormat
<add> } else {
<add> ctx.Format = defaultContainerTableFormat
<add> if ctx.Size {
<add> ctx.Format += `\t{{.Size}}`
<add> }
<ide> }
<ide> case rawFormatKey:
<ide> if ctx.Quiet {
<ide> ctx.Format = `container_id: {{.ID}}`
<ide> } else {
<del> ctx.Format = `container_id: {{.ID}}
<del>image: {{.Image}}
<del>command: {{.Command}}
<del>created_at: {{.CreatedAt}}
<del>status: {{.Status}}
<del>names: {{.Names}}
<del>labels: {{.Labels}}
<del>ports: {{.Ports}}
<del>`
<add> ctx.Format = `container_id: {{.ID}}\nimage: {{.Image}}\ncommand: {{.Command}}\ncreated_at: {{.CreatedAt}}\nstatus: {{.Status}}\nnames: {{.Names}}\nlabels: {{.Labels}}\nports: {{.Ports}}\n`
<ide> if ctx.Size {
<del> ctx.Format += `size: {{.Size}}
<del>`
<add> ctx.Format += `size: {{.Size}}\n`
<ide> }
<ide> }
<ide> }
<ide>
<ide> ctx.buffer = bytes.NewBufferString("")
<ide> ctx.preformat()
<del> if ctx.table && ctx.Size {
<del> ctx.finalFormat += "\t{{.Size}}"
<del> }
<ide>
<ide> tmpl, err := ctx.parseFormat()
<ide> if err != nil {
<ide><path>api/client/formatter/formatter_test.go
<ide> containerID2 ubuntu "" 24 hours ago
<ide> },
<ide> Size: true,
<ide> },
<del> "IMAGE SIZE\nubuntu 0 B\nubuntu 0 B\n",
<add> "IMAGE\nubuntu\nubuntu\n",
<ide> },
<ide> {
<ide> ContainerContext{
<ide> func TestContainerContextWriteWithNoContainers(t *testing.T) {
<ide> },
<ide> Size: true,
<ide> },
<add> "IMAGE\n",
<add> },
<add> {
<add> ContainerContext{
<add> Context: Context{
<add> Format: "table {{.Image}}\t{{.Size}}",
<add> Output: out,
<add> },
<add> },
<add> "IMAGE SIZE\n",
<add> },
<add> {
<add> ContainerContext{
<add> Context: Context{
<add> Format: "table {{.Image}}\t{{.Size}}",
<add> Output: out,
<add> },
<add> Size: true,
<add> },
<ide> "IMAGE SIZE\n",
<ide> },
<ide> }
<ide><path>api/client/ps.go
<ide> package client
<ide>
<ide> import (
<ide> "golang.org/x/net/context"
<add> "io/ioutil"
<ide>
<ide> "github.com/docker/docker/api/client/formatter"
<ide> Cli "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/opts"
<ide> flag "github.com/docker/docker/pkg/mflag"
<add> "github.com/docker/docker/utils/templates"
<ide> "github.com/docker/engine-api/types"
<ide> "github.com/docker/engine-api/types/filters"
<ide> )
<ide>
<add>type preProcessor struct {
<add> opts *types.ContainerListOptions
<add>}
<add>
<add>// Size sets the size option when called by a template execution.
<add>func (p *preProcessor) Size() bool {
<add> p.opts.Size = true
<add> return true
<add>}
<add>
<ide> // CmdPs outputs a list of Docker containers.
<ide> //
<ide> // Usage: docker ps [OPTIONS]
<ide> func (cli *DockerCli) CmdPs(args ...string) error {
<ide> Filter: psFilterArgs,
<ide> }
<ide>
<add> pre := &preProcessor{opts: &options}
<add> tmpl, err := templates.Parse(*format)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> _ = tmpl.Execute(ioutil.Discard, pre)
<add>
<ide> containers, err := cli.client.ContainerList(context.Background(), options)
<ide> if err != nil {
<ide> return err
<ide><path>integration-cli/docker_cli_ps_test.go
<ide> func (s *DockerSuite) TestPsShowMounts(c *check.C) {
<ide> out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+prefix+slash+"this-path-was-never-mounted")
<ide> c.Assert(strings.TrimSpace(string(out)), checker.HasLen, 0)
<ide> }
<add>
<add>func (s *DockerSuite) TestPsFormatSize(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add> runSleepingContainer(c)
<add>
<add> out, _ := dockerCmd(c, "ps", "--format", "table {{.Size}}")
<add> lines := strings.Split(out, "\n")
<add> c.Assert(lines[1], checker.Not(checker.Equals), "0 B", check.Commentf("Should not display a size of 0 B"))
<add>
<add> out, _ = dockerCmd(c, "ps", "--size", "--format", "table {{.Size}}")
<add> lines = strings.Split(out, "\n")
<add> c.Assert(lines[0], checker.Equals, "SIZE", check.Commentf("Should only have one size column"))
<add>
<add> out, _ = dockerCmd(c, "ps", "--size", "--format", "raw")
<add> lines = strings.Split(out, "\n")
<add> c.Assert(lines[8], checker.HasPrefix, "size:", check.Commentf("Size should be appended on a newline"))
<add>} | 4 |
Javascript | Javascript | use missing validator | 826566e78a4f6248254b7dd6fb85f37ea3978530 | <ide><path>lib/vm.js
<ide> function getContextOptions(options) {
<ide> }
<ide>
<ide> function isContext(object) {
<del> if (typeof object !== 'object' || object === null) {
<del> throw new ERR_INVALID_ARG_TYPE('object', 'Object', object);
<del> }
<add> validateObject(object, 'object', { allowArray: true });
<add>
<ide> return _isContext(object);
<ide> }
<ide> | 1 |
Javascript | Javascript | support "jsonp" in output.librarytarget | 58424e0824e80d954c9741d0b28b38b3b6b96805 | <ide><path>lib/ExternalModule.js
<ide> ExternalModule.prototype.source = function(dependencyTemplates, outputOptions, r
<ide> var request = this.request;
<ide> if(typeof request === "object") request = request[this.type];
<ide> switch(this.type) {
<del> case "var":
<del> case "assign":
<del> str = "module.exports = " + request + ";";
<del> break;
<ide> case "this":
<ide> case "window":
<ide> case "global":
<ide> ExternalModule.prototype.source = function(dependencyTemplates, outputOptions, r
<ide> case "umd":
<ide> str = "module.exports = __WEBPACK_EXTERNAL_MODULE_" + this.id + "__;";
<ide> break;
<add> default:
<add> str = "module.exports = " + request + ";";
<add> break;
<ide> }
<ide> if(this.useSourceMap) {
<ide> return new OriginalSource(str, this.identifier());
<ide><path>lib/JsonpExportMainTemplateDecorator.js
<add>/*
<add> MIT License http://www.opensource.org/licenses/mit-license.php
<add> Author Tobias Koppers @sokra
<add>*/
<add>var ConcatSource = require("webpack-core/lib/ConcatSource");
<add>var Template = require("./Template");
<add>
<add>function JsonpExportMainTemplateDecorator(mainTemplate, name) {
<add> this.mainTemplate = mainTemplate;
<add> this.name = name;
<add>}
<add>module.exports = JsonpExportMainTemplateDecorator;
<add>JsonpExportMainTemplateDecorator.prototype.render = function(hash, chunk, moduleTemplate, dependencyTemplates) {
<add> var source = this.mainTemplate.render(hash, chunk, moduleTemplate, dependencyTemplates);
<add> var name = (this.name || "")
<add> .replace(Template.REGEXP_HASH, hash)
<add> .replace(Template.REGEXP_CHUNKHASH, chunk.renderedHash)
<add> .replace(Template.REGEXP_ID, chunk.id)
<add> .replace(Template.REGEXP_NAME, chunk.name || "");
<add> return new ConcatSource(name + "(", source, ");");
<add>};
<add>JsonpExportMainTemplateDecorator.prototype.updateHash = function(hash) {
<add> hash.update("jsonp export");
<add> hash.update(this.name + "");
<add> this.mainTemplate.updateHash(hash);
<add>};
<ide>\ No newline at end of file
<ide><path>lib/LibraryTemplatePlugin.js
<ide> LibraryTemplatePlugin.prototype.apply = function(compiler) {
<ide> var UmdMainTemplateDecorator = require("./UmdMainTemplateDecorator");
<ide> compiler.mainTemplate = new UmdMainTemplateDecorator(compiler.mainTemplate, this.name);
<ide> break;
<add> case "jsonp":
<add> var JsonpExportMainTemplateDecorator = require("./JsonpExportMainTemplateDecorator");
<add> compiler.mainTemplate = new JsonpExportMainTemplateDecorator(compiler.mainTemplate, this.name);
<add> break;
<ide> default:
<ide> throw new Error(this.target + " is not a valid Library target");
<ide> } | 3 |
Java | Java | introduce configurableconversionservice interface | 8227cb624308e68c34cc2140ea63e8fc4f5cbd9f | <ide><path>org.springframework.core/src/main/java/org/springframework/core/convert/support/ConfigurableConversionService.java
<add>/*
<add> * Copyright 2002-2011 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.core.convert.support;
<add>
<add>import org.springframework.core.convert.ConversionService;
<add>import org.springframework.core.convert.converter.ConverterRegistry;
<add>
<add>/**
<add> * Configuration interface to be implemented by most if not all {@link ConversionService}
<add> * types. Consolidates the read-only operations exposed by {@link ConversionService} and
<add> * the mutating operations of {@link ConverterRegistry} to allow for convenient ad-hoc
<add> * addition and removal of {@link org.springframework.core.convert.converter.Converter
<add> * Converters} through. The latter is particularly useful when working against a
<add> * {@link org.springframework.core.env.ConfigurableEnvironment ConfigurableEnvironment}
<add> * instance in application context bootstrapping code.
<add> *
<add> * @author Chris Beams
<add> * @since 3.1
<add> * @see org.springframework.core.env.ConfigurablePropertyResolver#getConversionService()
<add> * @see org.springframework.core.env.ConfigurableEnvironment
<add> * @see org.springframework.context.ConfigurableApplicationContext#getEnvironment()
<add> */
<add>public interface ConfigurableConversionService extends ConversionService, ConverterRegistry {
<add>
<add>}
<ide><path>org.springframework.core/src/main/java/org/springframework/core/convert/support/GenericConversionService.java
<ide>
<ide> /**
<ide> * Base {@link ConversionService} implementation suitable for use in most environments.
<del> * Implements {@link ConverterRegistry} as registration API.
<add> * Indirectly implements {@link ConverterRegistry} as registration API through the
<add> * {@link ConfigurableConversionService} interface.
<ide> *
<ide> * @author Keith Donald
<ide> * @author Juergen Hoeller
<add> * @author Chris Beams
<ide> * @since 3.0
<ide> */
<del>public class GenericConversionService implements ConversionService, ConverterRegistry {
<add>public class GenericConversionService implements ConfigurableConversionService {
<ide>
<ide> private static final GenericConverter NO_OP_CONVERTER = new GenericConverter() {
<ide> public Set<ConvertiblePair> getConvertibleTypes() {
<ide><path>org.springframework.core/src/main/java/org/springframework/core/env/AbstractEnvironment.java
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<del>import org.springframework.core.convert.ConversionService;
<add>import org.springframework.core.convert.support.ConfigurableConversionService;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> public String resolveRequiredPlaceholders(String text) throws IllegalArgumentExc
<ide> return this.propertyResolver.resolveRequiredPlaceholders(text);
<ide> }
<ide>
<del> public void setConversionService(ConversionService conversionService) {
<add> public void setConversionService(ConfigurableConversionService conversionService) {
<ide> this.propertyResolver.setConversionService(conversionService);
<ide> }
<ide>
<del> public ConversionService getConversionService() {
<add> public ConfigurableConversionService getConversionService() {
<ide> return this.propertyResolver.getConversionService();
<ide> }
<ide>
<ide><path>org.springframework.core/src/main/java/org/springframework/core/env/AbstractPropertyResolver.java
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<del>import org.springframework.core.convert.ConversionService;
<add>import org.springframework.core.convert.support.ConfigurableConversionService;
<ide> import org.springframework.core.convert.support.DefaultConversionService;
<ide> import org.springframework.util.PropertyPlaceholderHelper;
<ide> import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver;
<ide> public abstract class AbstractPropertyResolver implements ConfigurablePropertyRe
<ide>
<ide> protected final Log logger = LogFactory.getLog(getClass());
<ide>
<del> protected ConversionService conversionService = new DefaultConversionService();
<add> protected ConfigurableConversionService conversionService = new DefaultConversionService();
<ide>
<ide> private PropertyPlaceholderHelper nonStrictHelper;
<ide> private PropertyPlaceholderHelper strictHelper;
<ide> public abstract class AbstractPropertyResolver implements ConfigurablePropertyRe
<ide>
<ide> private final Set<String> requiredProperties = new LinkedHashSet<String>();
<ide>
<del> public ConversionService getConversionService() {
<add> public ConfigurableConversionService getConversionService() {
<ide> return this.conversionService;
<ide> }
<ide>
<del> public void setConversionService(ConversionService conversionService) {
<add> public void setConversionService(ConfigurableConversionService conversionService) {
<ide> this.conversionService = conversionService;
<ide> }
<ide>
<ide><path>org.springframework.core/src/main/java/org/springframework/core/env/ConfigurablePropertyResolver.java
<ide> /*
<del> * Copyright 2002-2010 the original author or authors.
<add> * Copyright 2002-2011 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.core.env;
<ide>
<del>import org.springframework.core.convert.ConversionService;
<del>
<add>import org.springframework.core.convert.support.ConfigurableConversionService;
<ide>
<ide> /**
<ide> * Configuration interface to be implemented by most if not all {@link PropertyResolver
<ide> * PropertyResolvers}. Provides facilities for accessing and customizing the
<del> * {@link ConversionService} used when converting property values from one type to
<del> * another.
<add> * {@link org.springframework.core.convert.ConversionService ConversionService} used when
<add> * converting property values from one type to another.
<ide> *
<ide> * @author Chris Beams
<ide> * @since 3.1
<ide> */
<ide> public interface ConfigurablePropertyResolver extends PropertyResolver {
<ide>
<ide> /**
<del> * @return the {@link ConversionService} used when performing type
<add> * @return the {@link ConfigurableConversionService} used when performing type
<ide> * conversions on properties.
<add> * <p>The configurable nature of the returned conversion service allows for
<add> * the convenient addition and removal of individual {@code Converter} instances:
<add> * <pre class="code">
<add> * ConfigurableConversionService cs = env.getConversionService();
<add> * cs.addConverter(new FooConverter());
<add> * </pre>
<ide> * @see PropertyResolver#getProperty(String, Class)
<add> * @see org.springframework.core.convert.converter.ConverterRegistry#addConverter
<ide> */
<del> ConversionService getConversionService();
<add> ConfigurableConversionService getConversionService();
<ide>
<ide> /**
<del> * Set the {@link ConversionService} to be used when performing type
<add> * Set the {@link ConfigurableConversionService} to be used when performing type
<ide> * conversions on properties.
<add> * <p><strong>Note:</strong> as an alternative to fully replacing the {@code
<add> * ConversionService}, consider adding or removing individual {@code Converter}
<add> * intstances by drilling into {@link #getConversionService()} and calling methods
<add> * such as {@code #addConverter}.
<ide> * @see PropertyResolver#getProperty(String, Class)
<add> * @see #getConversionService()
<add> * @see org.springframework.core.convert.converter.ConverterRegistry#addConverter
<ide> */
<del> void setConversionService(ConversionService conversionService);
<add> void setConversionService(ConfigurableConversionService conversionService);
<ide>
<ide> /**
<ide> * Set the prefix that placeholders replaced by this resolver must begin with. | 5 |
Javascript | Javascript | handle unknown message type in worker threads | e8f31191902a8304f77f7ed4377f10de91aca103 | <ide><path>test/parallel/test-worker-message-not-serializable.js
<ide> // expected.
<ide>
<ide> const common = require('../common');
<del>common.skipIfWorker();
<ide>
<ide> const assert = require('assert');
<ide>
<del>const { Worker, isMainThread } = require('worker_threads');
<del>if (isMainThread) {
<del> const worker = new Worker(__filename);
<del> worker.on('error', common.mustCall((e) => {
<del> assert.strictEqual(e.code, 'ERR_WORKER_UNSERIALIZABLE_ERROR');
<del> }));
<del>} else {
<add>const { Worker } = require('worker_threads');
<add>
<add>const worker = new Worker(`
<ide> const { internalBinding } = require('internal/test/binding');
<ide> const { getEnvMessagePort } = internalBinding('worker');
<ide> const { messageTypes } = require('internal/worker/io');
<ide> const messagePort = getEnvMessagePort();
<ide> messagePort.postMessage({ type: messageTypes.COULD_NOT_SERIALIZE_ERROR });
<del>}
<add>`, { eval: true });
<add>
<add>worker.on('error', common.mustCall((e) => {
<add> assert.strictEqual(e.code, 'ERR_WORKER_UNSERIALIZABLE_ERROR');
<add>}));
<ide><path>test/parallel/test-worker-message-type-unknown.js
<add>'use strict';
<add>
<add>// Check that main thread handles an unknown message type from a worker thread
<add>// as expected.
<add>
<add>require('../common');
<add>
<add>const assert = require('assert');
<add>const { spawnSync } = require('child_process');
<add>
<add>const { Worker } = require('worker_threads');
<add>if (process.argv[2] !== 'spawned') {
<add> const result = spawnSync(process.execPath,
<add> [ '--expose-internals', __filename, 'spawned'],
<add> { encoding: 'utf8' });
<add> assert.ok(result.stderr.includes('Unknown worker message type FHQWHGADS'),
<add> `Expected error not found in: ${result.stderr}`);
<add>} else {
<add> new Worker(`
<add> const { internalBinding } = require('internal/test/binding');
<add> const { getEnvMessagePort } = internalBinding('worker');
<add> const messagePort = getEnvMessagePort();
<add> messagePort.postMessage({ type: 'FHQWHGADS' });
<add> `, { eval: true });
<add>} | 2 |
Ruby | Ruby | ensure `foreign_keys` assertions after alter table | dc796a0d407dfaf84abd464fc1aa2966cddb51e0 | <ide><path>activerecord/test/cases/migration/foreign_key_test.rb
<ide> class Astronaut < ActiveRecord::Base
<ide> end
<ide>
<ide> def test_change_column_of_parent_table
<del> foreign_keys = ActiveRecord::Base.connection.foreign_keys("astronauts")
<ide> rocket = Rocket.create!(name: "myrocket")
<ide> rocket.astronauts << Astronaut.create!
<ide>
<ide> @connection.change_column_null :rockets, :name, false
<ide>
<add> foreign_keys = @connection.foreign_keys("astronauts")
<add> assert_equal 1, foreign_keys.size
<add>
<ide> fk = foreign_keys.first
<ide> assert_equal "myrocket", Rocket.first.name
<ide> assert_equal "astronauts", fk.from_table
<ide> def test_rename_column_of_child_table
<ide> @connection.rename_column :astronauts, :name, :astronaut_name
<ide>
<ide> foreign_keys = @connection.foreign_keys("astronauts")
<add> assert_equal 1, foreign_keys.size
<add>
<ide> fk = foreign_keys.first
<ide> assert_equal "myrocket", Rocket.first.name
<ide> assert_equal "astronauts", fk.from_table | 1 |
Javascript | Javascript | move tls-connect into benchmark/tls | bafc51c0f9bbd178e347ff2ea9d110e2f1a4202e | <ide><path>benchmark/tls-connect.js
<del>
<del>var assert = require('assert'),
<del> fs = require('fs'),
<del> path = require('path'),
<del> tls = require('tls');
<del>
<del>
<del>var target_connections = 10000,
<del> concurrency = 10;
<del>
<del>for (var i = 2; i < process.argv.length; i++) {
<del> switch (process.argv[i]) {
<del> case '-c':
<del> concurrency = ~~process.argv[++i];
<del> break;
<del>
<del> case '-n':
<del> target_connections = ~~process.argv[++i];
<del> break;
<del>
<del> default:
<del> throw new Error('Invalid flag: ' + process.argv[i]);
<del> }
<del>}
<del>
<del>
<del>var cert_dir = path.resolve(__dirname, '../test/fixtures'),
<del> options = { key: fs.readFileSync(cert_dir + '/test_key.pem'),
<del> cert: fs.readFileSync(cert_dir + '/test_cert.pem'),
<del> ca: [ fs.readFileSync(cert_dir + '/test_ca.pem') ] };
<del>
<del>var server = tls.createServer(options, onConnection);
<del>server.listen(8000);
<del>
<del>
<del>var initiated_connections = 0,
<del> server_connections = 0,
<del> client_connections = 0,
<del> start = Date.now();
<del>
<del>for (var i = 0; i < concurrency; i++)
<del> makeConnection();
<del>
<del>
<del>process.on('exit', onExit);
<del>
<del>
<del>function makeConnection() {
<del> if (initiated_connections >= target_connections)
<del> return;
<del>
<del> initiated_connections++;
<del>
<del> var conn = tls.connect(8000, function() {
<del> client_connections++;
<del>
<del> if (client_connections % 100 === 0)
<del> console.log(client_connections + ' of ' + target_connections +
<del> ' connections made');
<del>
<del> conn.end();
<del> makeConnection();
<del> });
<del>}
<del>
<del>
<del>function onConnection(conn) {
<del> server_connections++;
<del>
<del> if (server_connections === target_connections)
<del> server.close();
<del>}
<del>
<del>
<del>function onExit() {
<del> var end = Date.now(),
<del> s = (end - start) / 1000,
<del> persec = Math.round(target_connections / s);
<del>
<del> assert.equal(initiated_connections, target_connections);
<del> assert.equal(client_connections, target_connections);
<del> assert.equal(server_connections, target_connections);
<del>
<del> console.log('%d connections in %d s', target_connections, s);
<del> console.log('%d connections per second', persec);
<del>}
<ide><path>benchmark/tls/tls-connect.js
<add>var assert = require('assert'),
<add> fs = require('fs'),
<add> path = require('path'),
<add> tls = require('tls');
<add>
<add>var common = require('../common.js');
<add>var bench = common.createBenchmark(main, {
<add> concurrency: [1, 10],
<add> dur: [1, 3]
<add>});
<add>
<add>var clientConn = 0;
<add>var serverConn = 0;
<add>var server;
<add>var dur;
<add>var concurrency;
<add>var running = true;
<add>
<add>function main(conf) {
<add> dur = +conf.dur;
<add> concurrency = +conf.concurrency;
<add>
<add> var cert_dir = path.resolve(__dirname, '../../test/fixtures'),
<add> options = { key: fs.readFileSync(cert_dir + '/test_key.pem'),
<add> cert: fs.readFileSync(cert_dir + '/test_cert.pem'),
<add> ca: [ fs.readFileSync(cert_dir + '/test_ca.pem') ] };
<add>
<add> server = tls.createServer(options, onConnection);
<add> server.listen(common.PORT, onListening);
<add>}
<add>
<add>function onListening() {
<add> setTimeout(done, dur * 1000);
<add> bench.start();
<add> for (var i = 0; i < concurrency; i++)
<add> makeConnection();
<add>}
<add>
<add>function onConnection(conn) {
<add> serverConn++;
<add>}
<add>
<add>function makeConnection() {
<add> var conn = tls.connect({ port: common.PORT,
<add> rejectUnauthorized: false }, function() {
<add> clientConn++;
<add> conn.on('error', function(er) {
<add> console.error('client error', er);
<add> throw er;
<add> });
<add> conn.end();
<add> if (running) makeConnection();
<add> });
<add>}
<add>
<add>function done() {
<add> running = false;
<add> // it's only an established connection if they both saw it.
<add> // because we destroy the server somewhat abruptly, these
<add> // don't always match. Generally, serverConn will be
<add> // the smaller number, but take the min just to be sure.
<add> bench.end(Math.min(serverConn, clientConn));
<add>} | 2 |
Mixed | Ruby | send disconnect message during remote disconnect | 2d0f9c5844fb6f3ca3dbead71e5e641b8b561827 | <ide><path>actioncable/CHANGELOG.md
<add>* `ActionCable.server.remote_connections.where(...).disconnect` now sends `disconnect` message
<add> before closing the connection with the reconnection strategy specified (defaults to `true`).
<ide>
<add> *Vladimir Dementyev*
<ide>
<ide> Please check [7-0-stable](https://github.com/rails/rails/blob/7-0-stable/actioncable/CHANGELOG.md) for previous changes.
<ide><path>actioncable/app/assets/javascripts/action_cable.js
<ide> disconnect_reasons: {
<ide> unauthorized: "unauthorized",
<ide> invalid_request: "invalid_request",
<del> server_restart: "server_restart"
<add> server_restart: "server_restart",
<add> remote: "remote"
<ide> },
<ide> default_mount_path: "/cable",
<ide> protocols: [ "actioncable-v1-json", "actioncable-unsupported" ]
<ide><path>actioncable/app/javascript/action_cable/internal.js
<ide> export default {
<ide> "disconnect_reasons": {
<ide> "unauthorized": "unauthorized",
<ide> "invalid_request": "invalid_request",
<del> "server_restart": "server_restart"
<add> "server_restart": "server_restart",
<add> "remote": "remote"
<ide> },
<ide> "default_mount_path": "/cable",
<ide> "protocols": [
<ide><path>actioncable/lib/action_cable.rb
<ide> module ActionCable
<ide> disconnect_reasons: {
<ide> unauthorized: "unauthorized",
<ide> invalid_request: "invalid_request",
<del> server_restart: "server_restart"
<add> server_restart: "server_restart",
<add> remote: "remote"
<ide> },
<ide> default_mount_path: "/cable",
<ide> protocols: ["actioncable-v1-json", "actioncable-unsupported"].freeze
<ide><path>actioncable/lib/action_cable/connection/internal_channel.rb
<ide> def process_internal_message(message)
<ide> case message["type"]
<ide> when "disconnect"
<ide> logger.info "Removing connection (#{connection_identifier})"
<del> websocket.close
<add> close(reason: ActionCable::INTERNAL[:disconnect_reasons][:remote], reconnect: message.fetch("reconnect", true))
<ide> end
<ide> rescue Exception => e
<ide> logger.error "There was an exception - #{e.class}(#{e.message})"
<ide><path>actioncable/lib/action_cable/remote_connections.rb
<ide> module ActionCable
<ide> # This will disconnect all the connections established for
<ide> # <tt>User.find(1)</tt>, across all servers running on all machines, because
<ide> # it uses the internal channel that all of these servers are subscribed to.
<add> #
<add> # By default, server sends a "disconnect" message with "reconnect" flag set to true.
<add> # You can override it by specifying the `reconnect` option:
<add> #
<add> # ActionCable.server.remote_connections.where(current_user: User.find(1)).disconnect(reconnect: false)
<ide> class RemoteConnections
<ide> attr_reader :server
<ide>
<ide> def initialize(server, ids)
<ide> end
<ide>
<ide> # Uses the internal channel to disconnect the connection.
<del> def disconnect
<del> server.broadcast internal_channel, { type: "disconnect" }
<add> def disconnect(reconnect: true)
<add> server.broadcast internal_channel, { type: "disconnect", reconnect: reconnect }
<ide> end
<ide>
<ide> # Returns all the identifiers that were applied to this connection.
<ide><path>actioncable/test/client_test.rb
<ide> class ClientTest < ActionCable::TestCase
<ide> WAIT_WHEN_EXPECTING_EVENT = 2
<ide> WAIT_WHEN_NOT_EXPECTING_EVENT = 0.5
<ide>
<add> class Connection < ActionCable::Connection::Base
<add> identified_by :id
<add>
<add> def connect
<add> self.id = request.params["id"] || SecureRandom.hex(4)
<add> end
<add> end
<add>
<ide> class EchoChannel < ActionCable::Channel::Base
<ide> def subscribed
<ide> stream_from "global"
<ide> def setup
<ide> server.config.logger = Logger.new(StringIO.new).tap { |l| l.level = Logger::UNKNOWN }
<ide>
<ide> server.config.cable = ActiveSupport::HashWithIndifferentAccess.new(adapter: "async")
<add> server.config.connection_class = -> { ClientTest::Connection }
<ide>
<ide> # and now the "real" setup for our test:
<ide> server.config.disable_request_forgery_protection = true
<ide> def with_puma_server(rack_app = ActionCable.server, port = 3099)
<ide> class SyncClient
<ide> attr_reader :pings
<ide>
<del> def initialize(port)
<add> def initialize(port, path = "/")
<ide> messages = @messages = Queue.new
<ide> closed = @closed = Concurrent::Event.new
<ide> has_messages = @has_messages = Concurrent::Semaphore.new(0)
<ide> pings = @pings = Concurrent::AtomicFixnum.new(0)
<ide>
<ide> open = Concurrent::Promise.new
<ide>
<del> @ws = WebSocket::Client::Simple.connect("ws://127.0.0.1:#{port}/") do |ws|
<add> @ws = WebSocket::Client::Simple.connect("ws://127.0.0.1:#{port}#{path}") do |ws|
<ide> ws.on(:error) do |event|
<ide> event = RuntimeError.new(event.message) unless event.is_a?(Exception)
<ide>
<ide> def closed?
<ide> end
<ide> end
<ide>
<del> def websocket_client(port)
<del> SyncClient.new(port)
<add> def websocket_client(*args)
<add> SyncClient.new(*args)
<ide> end
<ide>
<ide> def concurrently(enum)
<ide> def test_unsubscribe_client
<ide> c.send_message command: "subscribe", identifier: identifier
<ide> assert_equal({ "identifier" => "{\"channel\":\"ClientTest::EchoChannel\"}", "type" => "confirm_subscription" }, c.read_message)
<ide> assert_equal(1, app.connections.count)
<del> assert(app.remote_connections.where(identifier: identifier))
<ide>
<ide> subscriptions = app.connections.first.subscriptions.send(:subscriptions)
<ide> assert_not_equal 0, subscriptions.size, "Missing EchoChannel subscription"
<ide> def test_unsubscribe_client
<ide> end
<ide> end
<ide>
<add> def test_remote_disconnect_client
<add> with_puma_server do |port|
<add> app = ActionCable.server
<add>
<add> c = websocket_client(port, "/?id=1")
<add> assert_equal({ "type" => "welcome" }, c.read_message)
<add>
<add> sleep 0.1 # make sure connections is registered
<add> app.remote_connections.where(id: "1").disconnect
<add>
<add> assert_equal({ "type" => "disconnect", "reason" => "remote", "reconnect" => true }, c.read_message)
<add>
<add> c.wait_for_close
<add> assert(c.closed?)
<add> end
<add> end
<add>
<add> def test_remote_disconnect_client_with_reconnect
<add> with_puma_server do |port|
<add> app = ActionCable.server
<add>
<add> c = websocket_client(port, "/?id=2")
<add> assert_equal({ "type" => "welcome" }, c.read_message)
<add>
<add> sleep 0.1 # make sure connections is registered
<add> app.remote_connections.where(id: "2").disconnect(reconnect: false)
<add>
<add> assert_equal({ "type" => "disconnect", "reason" => "remote", "reconnect" => false }, c.read_message)
<add>
<add> c.wait_for_close
<add> assert(c.closed?)
<add> end
<add> end
<add>
<ide> def test_server_restart
<ide> with_puma_server do |port|
<ide> c = websocket_client(port) | 7 |
Python | Python | remove batchwise metrics | a56b1a55182acf061b1eb2e2c86b48193a0e88f7 | <ide><path>keras/metrics.py
<ide> def poisson(y_true, y_pred):
<ide> def cosine_proximity(y_true, y_pred):
<ide> y_true = K.l2_normalize(y_true, axis=-1)
<ide> y_pred = K.l2_normalize(y_pred, axis=-1)
<del> return -K.mean(y_true * y_pred)
<add> return - K.mean(y_true * y_pred)
<ide>
<ide>
<del>def matthews_correlation(y_true, y_pred):
<del> """Matthews correlation metric.
<add># Aliases
<ide>
<del> It is only computed as a batch-wise average, not globally.
<del>
<del> Computes the Matthews correlation coefficient measure for quality
<del> of binary classification problems.
<del> """
<del> y_pred_pos = K.round(K.clip(y_pred, 0, 1))
<del> y_pred_neg = 1 - y_pred_pos
<del>
<del> y_pos = K.round(K.clip(y_true, 0, 1))
<del> y_neg = 1 - y_pos
<del>
<del> tp = K.sum(y_pos * y_pred_pos)
<del> tn = K.sum(y_neg * y_pred_neg)
<del>
<del> fp = K.sum(y_neg * y_pred_pos)
<del> fn = K.sum(y_pos * y_pred_neg)
<del>
<del> numerator = (tp * tn - fp * fn)
<del> denominator = K.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))
<del>
<del> return numerator / (denominator + K.epsilon())
<del>
<del>
<del>def precision(y_true, y_pred):
<del> """Precision metric.
<del>
<del> Only computes a batch-wise average of precision.
<del>
<del> Computes the precision, a metric for multi-label classification of
<del> how many selected items are relevant.
<del> """
<del> true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
<del> predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
<del> precision = true_positives / (predicted_positives + K.epsilon())
<del> return precision
<del>
<del>
<del>def recall(y_true, y_pred):
<del> """Recall metric.
<del>
<del> Only computes a batch-wise average of recall.
<del>
<del> Computes the recall, a metric for multi-label classification of
<del> how many relevant items are selected.
<del> """
<del> true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
<del> possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
<del> recall = true_positives / (possible_positives + K.epsilon())
<del> return recall
<del>
<del>
<del>def fbeta_score(y_true, y_pred, beta=1):
<del> """Computes the F score.
<del>
<del> The F score is the weighted harmonic mean of precision and recall.
<del> Here it is only computed as a batch-wise average, not globally.
<del>
<del> This is useful for multi-label classification, where input samples can be
<del> classified as sets of labels. By only using accuracy (precision) a model
<del> would achieve a perfect score by simply assigning every class to every
<del> input. In order to avoid this, a metric should penalize incorrect class
<del> assignments as well (recall). The F-beta score (ranged from 0.0 to 1.0)
<del> computes this, as a weighted mean of the proportion of correct class
<del> assignments vs. the proportion of incorrect class assignments.
<del>
<del> With beta = 1, this is equivalent to a F-measure. With beta < 1, assigning
<del> correct classes becomes more important, and with beta > 1 the metric is
<del> instead weighted towards penalizing incorrect class assignments.
<del> """
<del> if beta < 0:
<del> raise ValueError('The lowest choosable beta is zero (only precision).')
<del>
<del> # If there are no true positives, fix the F score at 0 like sklearn.
<del> if K.sum(K.round(K.clip(y_true, 0, 1))) == 0:
<del> return 0
<del>
<del> p = precision(y_true, y_pred)
<del> r = recall(y_true, y_pred)
<del> bb = beta ** 2
<del> fbeta_score = (1 + bb) * (p * r) / (bb * p + r + K.epsilon())
<del> return fbeta_score
<del>
<del>
<del>def fmeasure(y_true, y_pred):
<del> """Computes the f-measure, the harmonic mean of precision and recall.
<del>
<del> Here it is only computed as a batch-wise average, not globally.
<del> """
<del> return fbeta_score(y_true, y_pred, beta=1)
<del>
<del>
<del># aliases
<ide> mse = MSE = mean_squared_error
<ide> mae = MAE = mean_absolute_error
<ide> mape = MAPE = mean_absolute_percentage_error
<ide> msle = MSLE = mean_squared_logarithmic_error
<ide> cosine = cosine_proximity
<del>fscore = f1score = fmeasure
<ide>
<ide>
<ide> def get(identifier): | 1 |
Java | Java | generalize rsocketrequester data methods | d6b5c2005849e0676781ec1086bf8fc994e1a2c4 | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketRequester.java
<ide> public ResponseSpec data(Object data) {
<ide> }
<ide>
<ide> @Override
<del> public <T, P extends Publisher<T>> ResponseSpec data(P publisher, Class<T> dataType) {
<del> Assert.notNull(publisher, "'publisher' must not be null");
<del> Assert.notNull(dataType, "'dataType' must not be null");
<del> return toResponseSpec(publisher, ResolvableType.forClass(dataType));
<add> public ResponseSpec data(Object producer, Class<?> elementType) {
<add> Assert.notNull(producer, "'producer' must not be null");
<add> Assert.notNull(elementType, "'dataType' must not be null");
<add> ReactiveAdapter adapter = strategies.reactiveAdapterRegistry().getAdapter(producer.getClass());
<add> Assert.notNull(adapter, "'producer' type is unknown to ReactiveAdapterRegistry");
<add> return toResponseSpec(adapter.toPublisher(producer), ResolvableType.forClass(elementType));
<ide> }
<ide>
<ide> @Override
<del> public <T, P extends Publisher<T>> ResponseSpec data(P publisher, ParameterizedTypeReference<T> dataTypeRef) {
<del> Assert.notNull(publisher, "'publisher' must not be null");
<add> public ResponseSpec data(Object producer, ParameterizedTypeReference<?> dataTypeRef) {
<add> Assert.notNull(producer, "'producer' must not be null");
<ide> Assert.notNull(dataTypeRef, "'dataTypeRef' must not be null");
<del> return toResponseSpec(publisher, ResolvableType.forType(dataTypeRef));
<add> ReactiveAdapter adapter = strategies.reactiveAdapterRegistry().getAdapter(producer.getClass());
<add> Assert.notNull(adapter, "'producer' type is unknown to ReactiveAdapterRegistry");
<add> return toResponseSpec(adapter.toPublisher(producer), ResolvableType.forType(dataTypeRef));
<ide> }
<ide>
<ide> private ResponseSpec toResponseSpec(Object input, ResolvableType dataType) {
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/RSocketRequester.java
<ide> interface RequestSpec {
<ide> RequestSpec metadata(Object metadata, MimeType mimeType);
<ide>
<ide> /**
<del> * Provide request payload data. The given Object may be a synchronous
<del> * value, or a {@link Publisher} of values, or another async type that's
<del> * registered in the configured {@link ReactiveAdapterRegistry}.
<del> * <p>For multi-valued Publishers, prefer using
<del> * {@link #data(Publisher, Class)} or
<del> * {@link #data(Publisher, ParameterizedTypeReference)} since that makes
<del> * it possible to find a compatible {@code Encoder} up front vs looking
<del> * it up on every value.
<add> * Provide payload data. The data can be one of the following:
<add> * <ul>
<add> * <li>Concrete value
<add> * <li>{@link Publisher} of value(s)
<add> * <li>Any other producer of value(s) that can be adapted to a
<add> * {@link Publisher} via {@link ReactiveAdapterRegistry}
<add> * </ul>
<ide> * @param data the Object to use for payload data
<ide> * @return spec for declaring the expected response
<ide> */
<ide> ResponseSpec data(Object data);
<ide>
<ide> /**
<del> * Provide a {@link Publisher} of value(s) for request payload data.
<del> * <p>Publisher semantics determined through the configured
<del> * {@link ReactiveAdapterRegistry} influence which of the 4 RSocket
<del> * interactions to use. Publishers with unknown semantics are treated
<del> * as multi-valued. Consider registering a reactive type adapter, or
<del> * passing {@code Mono.from(publisher)}.
<del> * <p>If the publisher completes empty, possibly {@code Publisher<Void>},
<del> * the request will have an empty data Payload.
<del> * @param publisher source of payload data value(s)
<del> * @param dataType the type of values to be published
<del> * @param <T> the type of element values
<del> * @param <P> the type of publisher
<add> * Alternative of {@link #data(Object)} that accepts not only a producer
<add> * of value(s) but also a hint for the types of values that will be
<add> * produced. The class hint is used to find a compatible {@code Encoder}
<add> * once, up front, and used for all values.
<add> * @param producer the source of payload data value(s). This must be a
<add> * {@link Publisher} or another producer adaptable to a
<add> * {@code Publisher} via {@link ReactiveAdapterRegistry}
<add> * @param elementType the type of values to be produced
<ide> * @return spec for declaring the expected response
<ide> */
<del> <T, P extends Publisher<T>> ResponseSpec data(P publisher, Class<T> dataType);
<add> ResponseSpec data(Object producer, Class<?> elementType);
<ide>
<ide> /**
<del> * Variant of {@link #data(Publisher, Class)} for when the dataType has
<del> * to have a generic type. See {@link ParameterizedTypeReference}.
<add> * Alternative of {@link #data(Object, Class)} but with a
<add> * {@link ParameterizedTypeReference} hint which can provide generic
<add> * type information.
<add> * @param producer the source of payload data value(s). This must be a
<add> * {@link Publisher} or another producer adaptable to a
<add> * {@code Publisher} via {@link ReactiveAdapterRegistry}
<add> * @param elementTypeRef the type of values to be produced
<ide> */
<del> <T, P extends Publisher<T>> ResponseSpec data(P publisher, ParameterizedTypeReference<T> dataTypeRef);
<add> ResponseSpec data(Object producer, ParameterizedTypeReference<?> elementTypeRef);
<ide> }
<ide>
<ide> | 2 |
PHP | PHP | apply fixes from styleci | 4074394582767906b2e7b5939d34e1eb78e28ff4 | <ide><path>src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php
<ide> public function supportsSavepoints()
<ide> {
<ide> return true;
<ide> }
<del>
<add>
<ide> /**
<ide> * Compile the SQL statement to define a savepoint.
<ide> * | 1 |
PHP | PHP | fix eloquent model relation doc blocks | 15489ab9d8fb3287271c9f85ecf0c59886e11f38 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function belongsTo($related, $foreignKey = null, $otherKey = null, $relat
<ide> }
<ide>
<ide> /**
<del> * Define an polymorphic, inverse one-to-one or many relationship.
<add> * Define a polymorphic, inverse one-to-one or many relationship.
<ide> *
<ide> * @param string $name
<ide> * @param string $type
<ide> public function belongsToMany($related, $table = null, $foreignKey = null, $othe
<ide> }
<ide>
<ide> /**
<del> * Define a many-to-many relationship.
<add> * Define a polymorphic many-to-many relationship.
<ide> *
<ide> * @param string $related
<ide> * @param string $name
<ide> public function morphToMany($related, $name, $table = null, $foreignKey = null,
<ide> }
<ide>
<ide> /**
<del> * Define a many-to-many relationship.
<add> * Define a polymorphic many-to-many relationship.
<ide> *
<ide> * @param string $related
<ide> * @param string $name | 1 |
Ruby | Ruby | handle non-existent path | b54b022f73628360e109586013b6b22aacd92f5d | <ide><path>Library/Homebrew/keg.rb
<ide> def self.find_some_installed_dependents(kegs)
<ide>
<ide> # if path is a file in a keg then this will return the containing Keg object
<ide> def self.for(path)
<del> path = path.realpath
<del> until path.root?
<del> return Keg.new(path) if path.parent.parent == HOMEBREW_CELLAR.realpath
<add> original_path = path
<add> if original_path.exist? && (path = original_path.realpath)
<add> until path.root?
<add> return Keg.new(path) if path.parent.parent == HOMEBREW_CELLAR.realpath
<ide>
<del> path = path.parent.realpath # realpath() prevents root? failing
<add> path = path.parent.realpath # realpath() prevents root? failing
<add> end
<ide> end
<del> raise NotAKegError, "#{path} is not inside a keg"
<add> raise NotAKegError, "#{original_path} is not inside a keg"
<ide> end
<ide>
<ide> def self.all | 1 |
Javascript | Javascript | flow type refreshcontrol | 84c541661729dd20ab260c7468e48abbbe82affb | <ide><path>Libraries/Components/RefreshControl/RefreshControl.js
<ide> export type RefreshControlProps = $ReadOnly<{|
<ide> /**
<ide> * Called when the view starts refreshing.
<ide> */
<del> onRefresh?: ?Function,
<add> onRefresh?: ?() => void,
<ide>
<ide> /**
<ide> * Whether the view should be indicating an active refresh. | 1 |
Text | Text | remove cjihrig from tc | 6190a2236b3a9de49e2e6918ff32c601d15559dd | <ide><path>README.md
<ide> information about the governance of the io.js project, see
<ide> * **Trevor Norris** ([@trevnorris](https://github.com/trevnorris)) <[email protected]> (Technical Committee)
<ide> * **Chris Dickinson** ([@chrisdickinson](https://github.com/chrisdickinson)) <[email protected]> (Technical Committee)
<ide> <br>Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B
<del>* **Colin Ihrig** ([@cjihrig](https://github.com/cjihrig)) <[email protected]> (Technical Committee)
<add>* **Colin Ihrig** ([@cjihrig](https://github.com/cjihrig)) <[email protected]>
<ide> * **Mikeal Rogers** ([@mikeal](https://github.com/mikeal)) <[email protected]>
<ide> * **Rod Vagg** ([@rvagg](https://github.com/rvagg)) <[email protected]>
<ide> <br>Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D | 1 |
Mixed | Ruby | add request exclusion to host authorization | 1f767407cb46c847a528525d4fe01136428c16f8 | <ide><path>actionpack/CHANGELOG.md
<add>* Allow `ActionDispatch::HostAuthorization` to exclude specific requests.
<add>
<add> Host Authorization checks can be skipped for specific requests. This allows for health check requests to be permitted for requests with missing or non-matching host headers.
<add>
<add> *Chris Bisnett*
<add>
<ide> * Add `config.action_dispatch.request_id_header` to allow changing the name of
<ide> the unique X-Request-Id header
<ide>
<ide><path>actionpack/lib/action_dispatch/middleware/host_authorization.rb
<ide>
<ide> module ActionDispatch
<ide> # This middleware guards from DNS rebinding attacks by explicitly permitting
<del> # the hosts a request can be sent to.
<add> # the hosts a request can be sent to, and is passed the options set in
<add> # +config.host_authorization+.
<add> #
<add> # Requests can opt-out of Host Authorization with +exclude+:
<add> #
<add> # config.host_authorization = { exclude: ->(request) { request.path =~ /healthcheck/ } }
<ide> #
<ide> # When a request comes to an unauthorized host, the +response_app+
<ide> # application will be executed and rendered. If no +response_app+ is given, a
<ide> def sanitize_string(host)
<ide> }, [body]]
<ide> end
<ide>
<del> def initialize(app, hosts, response_app = nil)
<add> def initialize(app, hosts, deprecated_response_app = nil, exclude: nil, response_app: nil)
<ide> @app = app
<ide> @permissions = Permissions.new(hosts)
<add> @exclude = exclude
<add>
<add> unless deprecated_response_app.nil?
<add> ActiveSupport::Deprecation.warn(<<-MSG.squish)
<add> `action_dispatch.hosts_response_app` is deprecated and will be ignored in Rails 6.2.
<add> Use the Host Authorization `response_app` setting instead.
<add> MSG
<add>
<add> response_app ||= deprecated_response_app
<add> end
<add>
<ide> @response_app = response_app || DEFAULT_RESPONSE_APP
<ide> end
<ide>
<ide> def call(env)
<ide>
<ide> request = Request.new(env)
<ide>
<del> if authorized?(request)
<add> if authorized?(request) || excluded?(request)
<ide> mark_as_authorized(request)
<ide> @app.call(env)
<ide> else
<ide> def authorized?(request)
<ide> (forwarded_host.blank? || @permissions.allows?(forwarded_host))
<ide> end
<ide>
<add> def excluded?(request)
<add> @exclude && @exclude.call(request)
<add> end
<add>
<ide> def mark_as_authorized(request)
<ide> request.set_header("action_dispatch.authorized_host", request.host)
<ide> end
<ide><path>actionpack/test/dispatch/host_authorization_test.rb
<ide> class HostAuthorizationTest < ActionDispatch::IntegrationTest
<ide> end
<ide>
<ide> test "blocks requests to unallowed host supporting custom responses" do
<del> @app = ActionDispatch::HostAuthorization.new(App, ["w.example.co"], -> env do
<add> @app = ActionDispatch::HostAuthorization.new(App, ["w.example.co"], response_app: -> env do
<ide> [401, {}, %w(Custom)]
<ide> end)
<ide>
<ide> class HostAuthorizationTest < ActionDispatch::IntegrationTest
<ide> assert_response :ok
<ide> assert_equal "Success", body
<ide> end
<add>
<add> test "exclude matches allow any host" do
<add> @app = ActionDispatch::HostAuthorization.new(App, "only.com", exclude: ->(req) { req.path == "/foo" })
<add>
<add> get "/foo"
<add>
<add> assert_response :ok
<add> assert_equal "Success", body
<add> end
<add>
<add> test "exclude misses block unallowed hosts" do
<add> @app = ActionDispatch::HostAuthorization.new(App, "only.com", exclude: ->(req) { req.path == "/bar" })
<add>
<add> get "/foo"
<add>
<add> assert_response :forbidden
<add> assert_match "Blocked host: www.example.com", response.body
<add> end
<add>
<add> test "config setting action_dispatch.hosts_response_app is deprecated" do
<add> assert_deprecated do
<add> ActionDispatch::HostAuthorization.new(App, "example.com", ->(env) { true })
<add> end
<add> end
<ide> end
<ide><path>railties/lib/rails/application/configuration.rb
<ide> class Configuration < ::Rails::Engine::Configuration
<ide> attr_accessor :allow_concurrency, :asset_host, :autoflush_log,
<ide> :cache_classes, :cache_store, :consider_all_requests_local, :console,
<ide> :eager_load, :exceptions_app, :file_watcher, :filter_parameters,
<del> :force_ssl, :helpers_paths, :hosts, :logger, :log_formatter, :log_tags,
<del> :railties_order, :relative_url_root, :secret_key_base,
<add> :force_ssl, :helpers_paths, :hosts, :host_authorization, :logger, :log_formatter,
<add> :log_tags, :railties_order, :relative_url_root, :secret_key_base,
<ide> :ssl_options, :public_file_server,
<ide> :session_options, :time_zone, :reload_classes_only_on_change,
<ide> :beginning_of_week, :filter_redirect, :x, :enable_dependency_loading,
<ide> def initialize(*)
<ide> @filter_redirect = []
<ide> @helpers_paths = []
<ide> @hosts = Array(([".localhost", IPAddr.new("0.0.0.0/0"), IPAddr.new("::/0")] if Rails.env.development?))
<add> @host_authorization = {}
<ide> @public_file_server = ActiveSupport::OrderedOptions.new
<ide> @public_file_server.enabled = true
<ide> @public_file_server.index_name = "index"
<ide><path>railties/lib/rails/application/default_middleware_stack.rb
<ide> def initialize(app, config, paths)
<ide>
<ide> def build_stack
<ide> ActionDispatch::MiddlewareStack.new do |middleware|
<del> middleware.use ::ActionDispatch::HostAuthorization, config.hosts, config.action_dispatch.hosts_response_app
<add> middleware.use ::ActionDispatch::HostAuthorization, config.hosts, config.action_dispatch.hosts_response_app, **config.host_authorization
<ide>
<ide> if config.force_ssl
<ide> middleware.use ::ActionDispatch::SSL, **config.ssl_options, | 5 |
Java | Java | improve error messages in the test consumers | 7e7b223ccf4af4ef594677f04e731998914190b9 | <ide><path>src/main/java/io/reactivex/rxjava3/observers/BaseTestConsumer.java
<ide> public final U assertNoErrors() {
<ide> */
<ide> @NonNull
<ide> public final U assertError(@NonNull Throwable error) {
<del> return assertError(Functions.equalsWith(error));
<add> return assertError(Functions.equalsWith(error), true);
<ide> }
<ide>
<ide> /**
<ide> public final U assertError(@NonNull Throwable error) {
<ide> @SuppressWarnings({ "unchecked", "rawtypes" })
<ide> @NonNull
<ide> public final U assertError(@NonNull Class<? extends Throwable> errorClass) {
<del> return (U)assertError((Predicate)Functions.isInstanceOf(errorClass));
<add> return (U)assertError((Predicate)Functions.isInstanceOf(errorClass), true);
<ide> }
<ide>
<ide> /**
<ide> public final U assertError(@NonNull Class<? extends Throwable> errorClass) {
<ide> * and should return {@code true} for expected errors.
<ide> * @return this
<ide> */
<del> @SuppressWarnings("unchecked")
<ide> @NonNull
<ide> public final U assertError(@NonNull Predicate<Throwable> errorPredicate) {
<add> return assertError(errorPredicate, false);
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> @NonNull
<add> private U assertError(@NonNull Predicate<Throwable> errorPredicate, boolean exact) {
<ide> int s = errors.size();
<ide> if (s == 0) {
<ide> throw fail("No errors");
<ide> public final U assertError(@NonNull Predicate<Throwable> errorPredicate) {
<ide>
<ide> if (found) {
<ide> if (s != 1) {
<del> throw fail("Error present but other errors as well");
<add> if (exact) {
<add> throw fail("Error present but other errors as well");
<add> }
<add> throw fail("One error passed the predicate but other errors are present as well");
<ide> }
<ide> } else {
<del> throw fail("Error not present");
<add> if (exact) {
<add> throw fail("Error not present");
<add> }
<add> throw fail("No error(s) passed the predicate");
<ide> }
<ide> return (U)this;
<ide> }
<ide> public final U assertValue(@NonNull Predicate<T> valuePredicate) {
<ide> assertValueAt(0, valuePredicate);
<ide>
<ide> if (values.size() > 1) {
<del> throw fail("Value present but other values as well");
<add> throw fail("The first value passed the predicate but this consumer received more than one value");
<ide> }
<ide>
<ide> return (U)this;
<ide> public final U assertValueAt(int index, @NonNull T value) {
<ide> throw fail("No values");
<ide> }
<ide>
<del> if (index >= s) {
<del> throw fail("Invalid index: " + index);
<add> if (index < 0 || index >= s) {
<add> throw fail("Index " + index + " is out of range [0, " + s + ")");
<ide> }
<ide>
<ide> T v = values.get(index);
<ide> if (!Objects.equals(value, v)) {
<del> throw fail("expected: " + valueAndClass(value) + " but was: " + valueAndClass(v));
<add> throw fail("expected: " + valueAndClass(value) + " but was: " + valueAndClass(v) + " at position " + index);
<ide> }
<ide> return (U)this;
<ide> }
<ide> public final U assertValueAt(int index, @NonNull Predicate<T> valuePredicate) {
<ide> throw fail("No values");
<ide> }
<ide>
<del> if (index >= values.size()) {
<del> throw fail("Invalid index: " + index);
<add> if (index < 0 || index >= s) {
<add> throw fail("Index " + index + " is out of range [0, " + s + ")");
<ide> }
<ide>
<ide> boolean found = false;
<ide>
<add> T v = values.get(index);
<ide> try {
<del> if (valuePredicate.test(values.get(index))) {
<add> if (valuePredicate.test(v)) {
<ide> found = true;
<ide> }
<ide> } catch (Throwable ex) {
<ide> throw ExceptionHelper.wrapOrThrow(ex);
<ide> }
<ide>
<ide> if (!found) {
<del> throw fail("Value not present");
<add> throw fail("Value " + valueAndClass(v) + " at position " + index + " did not pass the predicate");
<ide> }
<ide> return (U)this;
<ide> }
<ide><path>src/test/java/io/reactivex/rxjava3/observers/TestObserverTest.java
<ide> import java.util.concurrent.TimeUnit;
<ide>
<ide> import org.junit.Test;
<add>import org.junit.function.ThrowingRunnable;
<ide> import org.mockito.InOrder;
<ide> import org.reactivestreams.Subscriber;
<ide>
<ide>
<ide> public class TestObserverTest extends RxJavaTest {
<ide>
<add> static void assertThrowsWithMessage(String message, Class<? extends Throwable> clazz, ThrowingRunnable run) {
<add> assertEquals(message, assertThrows(clazz, run).getMessage());
<add> }
<add>
<ide> @Test
<ide> public void assertTestObserver() {
<ide> Flowable<Integer> oi = Flowable.fromIterable(Arrays.asList(1, 2));
<ide> public void errorMeansDisposed() {
<ide>
<ide> @Test
<ide> public void assertValuePredicateEmpty() {
<del> assertThrows("No values", AssertionError.class, () -> {
<add> assertThrowsWithMessage("No values (latch = 0, values = 0, errors = 0, completions = 1)", AssertionError.class, () -> {
<ide> TestObserver<Object> to = new TestObserver<>();
<ide>
<ide> Observable.empty().subscribe(to);
<ide> public void assertValuePredicateMatch() {
<ide>
<ide> @Test
<ide> public void assertValuePredicateNoMatch() {
<del> assertThrows("Value not present", AssertionError.class, () -> {
<add> assertThrowsWithMessage("Value 1 (class: Integer) at position 0 did not pass the predicate (latch = 0, values = 1, errors = 0, completions = 1)", AssertionError.class, () -> {
<ide> TestObserver<Integer> to = new TestObserver<>();
<ide>
<ide> Observable.just(1).subscribe(to);
<ide> public void assertValuePredicateNoMatch() {
<ide>
<ide> @Test
<ide> public void assertValuePredicateMatchButMore() {
<del> assertThrows("Value present but other values as well", AssertionError.class, () -> {
<add> assertThrowsWithMessage("The first value passed the predicate but this consumer received more than one value (latch = 0, values = 2, errors = 0, completions = 1)", AssertionError.class, () -> {
<ide> TestObserver<Integer> to = new TestObserver<>();
<ide>
<ide> Observable.just(1, 2).subscribe(to);
<ide> public void assertValuePredicateMatchButMore() {
<ide>
<ide> @Test
<ide> public void assertValueAtPredicateEmpty() {
<del> assertThrows("No values", AssertionError.class, () -> {
<add> assertThrowsWithMessage("No values (latch = 0, values = 0, errors = 0, completions = 1)", AssertionError.class, () -> {
<ide> TestObserver<Object> to = new TestObserver<>();
<ide>
<ide> Observable.empty().subscribe(to);
<ide> public void assertValueAtPredicateMatch() {
<ide>
<ide> @Test
<ide> public void assertValueAtPredicateNoMatch() {
<del> assertThrows("Value not present", AssertionError.class, () -> {
<add> assertThrowsWithMessage("Value 3 (class: Integer) at position 2 did not pass the predicate (latch = 0, values = 3, errors = 0, completions = 1)", AssertionError.class, () -> {
<ide> TestObserver<Integer> to = new TestObserver<>();
<ide>
<ide> Observable.just(1, 2, 3).subscribe(to);
<ide> public void assertValueAtPredicateNoMatch() {
<ide>
<ide> @Test
<ide> public void assertValueAtInvalidIndex() {
<del> assertThrows("Invalid index: 2 (latch = 0, values = 2, errors = 0, completions = 1)", AssertionError.class, () -> {
<add> assertThrowsWithMessage("Index 2 is out of range [0, 2) (latch = 0, values = 2, errors = 0, completions = 1)", AssertionError.class, () -> {
<ide> TestObserver<Integer> to = new TestObserver<>();
<ide>
<ide> Observable.just(1, 2).subscribe(to);
<ide> public void assertValueAtInvalidIndex() {
<ide> });
<ide> }
<ide>
<add> @Test
<add> public void assertValueAtInvalidIndexNegative() {
<add> assertThrowsWithMessage("Index -2 is out of range [0, 2) (latch = 0, values = 2, errors = 0, completions = 1)", AssertionError.class, () -> {
<add> TestObserver<Integer> to = new TestObserver<>();
<add>
<add> Observable.just(1, 2).subscribe(to);
<add>
<add> to.assertValueAt(-2, new Predicate<Integer>() {
<add> @Override public boolean test(final Integer o) throws Exception {
<add> return o == 1;
<add> }
<add> });
<add> });
<add> }
<add>
<ide> @Test
<ide> public void assertValueAtIndexEmpty() {
<del> assertThrows("No values", AssertionError.class, () -> {
<add> assertThrowsWithMessage("No values (latch = 0, values = 0, errors = 0, completions = 1)", AssertionError.class, () -> {
<ide> TestObserver<Object> to = new TestObserver<>();
<ide>
<ide> Observable.empty().subscribe(to);
<ide> public void assertValueAtIndexMatch() {
<ide>
<ide> @Test
<ide> public void assertValueAtIndexNoMatch() {
<del> assertThrows("expected: b (class: String) but was: c (class: String) (latch = 0, values = 3, errors = 0, completions = 1)", AssertionError.class, () -> {
<add> assertThrowsWithMessage("expected: b (class: String) but was: c (class: String) at position 2 (latch = 0, values = 3, errors = 0, completions = 1)", AssertionError.class, () -> {
<ide> TestObserver<String> to = new TestObserver<>();
<ide>
<ide> Observable.just("a", "b", "c").subscribe(to);
<ide> public void assertValueAtIndexNoMatch() {
<ide>
<ide> @Test
<ide> public void assertValueAtIndexInvalidIndex() {
<del> assertThrows("Invalid index: 2 (latch = 0, values = 2, errors = 0, completions = 1)", AssertionError.class, () -> {
<add> assertThrowsWithMessage("Index 2 is out of range [0, 2) (latch = 0, values = 2, errors = 0, completions = 1)", AssertionError.class, () -> {
<ide> TestObserver<String> to = new TestObserver<>();
<ide>
<ide> Observable.just("a", "b").subscribe(to);
<ide> public void assertValueAtIndexInvalidIndex() {
<ide> });
<ide> }
<ide>
<add> @Test
<add> public void assertValueAtIndexInvalidIndexNegative() {
<add> assertThrowsWithMessage("Index -2 is out of range [0, 2) (latch = 0, values = 2, errors = 0, completions = 1)", AssertionError.class, () -> {
<add> TestObserver<String> to = new TestObserver<>();
<add>
<add> Observable.just("a", "b").subscribe(to);
<add>
<add> to.assertValueAt(-2, "c");
<add> });
<add> }
<add>
<ide> @Test
<ide> public void withTag() {
<ide> try {
<ide><path>src/test/java/io/reactivex/rxjava3/subscribers/TestSubscriberTest.java
<ide> import java.util.concurrent.atomic.AtomicBoolean;
<ide>
<ide> import org.junit.Test;
<add>import org.junit.function.ThrowingRunnable;
<ide> import org.mockito.InOrder;
<ide> import org.reactivestreams.*;
<ide>
<ide> public void assertValuePredicateMatch() {
<ide> });
<ide> }
<ide>
<add> static void assertThrowsWithMessage(String message, Class<? extends Throwable> clazz, ThrowingRunnable run) {
<add> assertEquals(message, assertThrows(clazz, run).getMessage());
<add> }
<add>
<ide> @Test
<ide> public void assertValuePredicateNoMatch() {
<del> assertThrows("Value not present", AssertionError.class, () -> {
<add> assertThrowsWithMessage("Value 1 (class: Integer) at position 0 did not pass the predicate (latch = 0, values = 1, errors = 0, completions = 1)", AssertionError.class, () -> {
<ide> TestSubscriber<Integer> ts = new TestSubscriber<>();
<ide>
<ide> Flowable.just(1).subscribe(ts);
<ide> public void assertValuePredicateNoMatch() {
<ide>
<ide> @Test
<ide> public void assertValuePredicateMatchButMore() {
<del> assertThrows("Value present but other values as well", AssertionError.class, () -> {
<add> assertThrowsWithMessage("The first value passed the predicate but this consumer received more than one value (latch = 0, values = 2, errors = 0, completions = 1)", AssertionError.class, () -> {
<ide> TestSubscriber<Integer> ts = new TestSubscriber<>();
<ide>
<ide> Flowable.just(1, 2).subscribe(ts);
<ide> public void assertValuePredicateMatchButMore() {
<ide>
<ide> @Test
<ide> public void assertValueAtPredicateEmpty() {
<del> assertThrows("No values", AssertionError.class, () -> {
<add> assertThrowsWithMessage("No values (latch = 0, values = 0, errors = 0, completions = 1)", AssertionError.class, () -> {
<ide> TestSubscriber<Object> ts = new TestSubscriber<>();
<ide>
<ide> Flowable.empty().subscribe(ts);
<ide> public void assertValueAtPredicateMatch() {
<ide>
<ide> @Test
<ide> public void assertValueAtPredicateNoMatch() {
<del> assertThrows("Value not present", AssertionError.class, () -> {
<add> assertThrowsWithMessage("Value 3 (class: Integer) at position 2 did not pass the predicate (latch = 0, values = 3, errors = 0, completions = 1)", AssertionError.class, () -> {
<ide> TestSubscriber<Integer> ts = new TestSubscriber<>();
<ide>
<ide> Flowable.just(1, 2, 3).subscribe(ts);
<ide> public void assertValueAtPredicateNoMatch() {
<ide>
<ide> @Test
<ide> public void assertValueAtInvalidIndex() {
<del> assertThrows("Invalid index: 2 (latch = 0, values = 2, errors = 0, completions = 1)", AssertionError.class, () -> {
<add> assertThrowsWithMessage("Index 2 is out of range [0, 2) (latch = 0, values = 2, errors = 0, completions = 1)", AssertionError.class, () -> {
<ide> TestSubscriber<Integer> ts = new TestSubscriber<>();
<ide>
<ide> Flowable.just(1, 2).subscribe(ts);
<ide> public void assertValueAtInvalidIndex() {
<ide> });
<ide> }
<ide>
<add> @Test
<add> public void assertValueAtIndexInvalidIndex() {
<add> assertThrowsWithMessage("Index 2 is out of range [0, 2) (latch = 0, values = 2, errors = 0, completions = 1)", AssertionError.class, () -> {
<add> TestSubscriber<Integer> ts = new TestSubscriber<>();
<add>
<add> Flowable.just(1, 2).subscribe(ts);
<add>
<add> ts.assertValueAt(2, 3);
<add> });
<add> }
<add>
<add> @Test
<add> public void assertValueAtIndexInvalidIndexNegative() {
<add> assertThrowsWithMessage("Index -2 is out of range [0, 2) (latch = 0, values = 2, errors = 0, completions = 1)", AssertionError.class, () -> {
<add> TestSubscriber<Integer> ts = new TestSubscriber<>();
<add>
<add> Flowable.just(1, 2).subscribe(ts);
<add>
<add> ts.assertValueAt(-2, 3);
<add> });
<add> }
<add>
<add> @Test
<add> public void assertValueAtInvalidIndexNegative() {
<add> assertThrowsWithMessage("Index -2 is out of range [0, 2) (latch = 0, values = 2, errors = 0, completions = 1)", AssertionError.class, () -> {
<add> TestSubscriber<Integer> ts = new TestSubscriber<>();
<add>
<add> Flowable.just(1, 2).subscribe(ts);
<add>
<add> ts.assertValueAt(-2, new Predicate<Integer>() {
<add> @Override public boolean test(final Integer o) throws Exception {
<add> return o == 1;
<add> }
<add> });
<add> });
<add> }
<add>
<ide> @Test
<ide> public void requestMore() {
<ide> Flowable.range(1, 5) | 3 |
Text | Text | add documentation about template partial caching | 49f6c47e418ff1626c6e8c408d11f839d28ceb31 | <ide><path>guides/source/caching_with_rails.md
<ide> With `touch` set to true, any action which changes `updated_at` for a game
<ide> record will also change it for the associated product, thereby expiring the
<ide> cache.
<ide>
<add>### Shared Partial Caching
<add>
<add>It is possible to share partials and associated caching between files with different mime types. For example shared partial caching allows template writers to share a partial between HTML and Javascript files. When templates are collected in the template resolver file paths they only include the template language extension and not the mime type. Because of this templates can be used for multiple mime types. Both HTML and JavaScript requests will respond to the following code:
<add>
<add>```ruby
<add>render(partial: 'hotels/hotel', collection: @hotels, cached: true)
<add>```
<add>
<add>Will load a file named `hotels/hotel.erb`.
<add>
<add>Another option is to include the full filename of the partial to render.
<add>
<add>```ruby
<add>render(partial: 'hotels/hotel.html.erb', collection: @hotels, cached: true)
<add>```
<add>
<add>Will load a file named `hotels/hotel.html.erb` in any file mime type, for example you could include this partial in a Javascript file.
<add>
<ide> ### Managing dependencies
<ide>
<ide> In order to correctly invalidate the cache, you need to properly define the
<ide> store is not appropriate for large application deployments. However, it can
<ide> work well for small, low traffic sites with only a couple of server processes,
<ide> as well as development and test environments.
<ide>
<del>New Rails projects are configured to use this implementation in development environment by default.
<add>New Rails projects are configured to use this implementation in development environment by default.
<ide>
<del>NOTE: Since processes will not share cache data when using `:memory_store`,
<add>NOTE: Since processes will not share cache data when using `:memory_store`,
<ide> it will not be possible to manually read, write or expire the cache via the Rails console.
<ide>
<ide> ### ActiveSupport::Cache::FileStore
<ide> Caching in Development
<ide> ----------------------
<ide>
<ide> It's common to want to test the caching strategy of your application
<del>in development mode. Rails provides the rake task `dev:cache` to
<add>in development mode. Rails provides the rake task `dev:cache` to
<ide> easily toggle caching on/off.
<ide>
<ide> ```bash | 1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.