content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
allow cleaning from non-cwd
5a840cc39e1b6f823978e3cd3a8dc8f3e7a65108
<ide><path>server/build/clean.js <ide> import getConfig from '../config' <ide> <ide> export default function clean (dir) { <ide> const dist = getConfig(dir).distDir <del> return del(resolve(dir, dist)) <add> return del(resolve(dir, dist), { force: true }) <ide> }
1
Go
Go
add new `local` log driver
a351b38e7217af059eb2f8fc3dba14dc03836a45
<ide><path>container/container.go <ide> import ( <ide> "github.com/docker/docker/daemon/exec" <ide> "github.com/docker/docker/daemon/logger" <ide> "github.com/docker/docker/daemon/logger/jsonfilelog" <add> "github.com/docker/docker/daemon/logger/local" <ide> "github.com/docker/docker/daemon/network" <add> "github.com/docker/docker/errdefs" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/layer" <ide> "github.com/docker/docker/pkg/containerfs" <ide> func (container *Container) StartLogger() (logger.Logger, error) { <ide> } <ide> <ide> // Set logging file for "json-logger" <del> if cfg.Type == jsonfilelog.Name { <add> // TODO(@cpuguy83): Setup here based on log driver is a little weird. <add> switch cfg.Type { <add> case jsonfilelog.Name: <ide> info.LogPath, err = container.GetRootResourcePath(fmt.Sprintf("%s-json.log", container.ID)) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <ide> container.LogPath = info.LogPath <add> case local.Name: <add> // Do not set container.LogPath for the local driver <add> // This would expose the value to the API, which should not be done as it means <add> // that the log file implementation would become a stable API that cannot change. <add> logDir, err := container.GetRootResourcePath("local-logs") <add> if err != nil { <add> return nil, err <add> } <add> if err := os.MkdirAll(logDir, 0700); err != nil { <add> return nil, errdefs.System(errors.Wrap(err, "error creating local logs dir")) <add> } <add> info.LogPath = filepath.Join(logDir, "container.log") <ide> } <ide> <ide> l, err := initDriver(info) <ide><path>daemon/logdrivers_linux.go <ide> import ( <ide> _ "github.com/docker/docker/daemon/logger/gelf" <ide> _ "github.com/docker/docker/daemon/logger/journald" <ide> _ "github.com/docker/docker/daemon/logger/jsonfilelog" <add> _ "github.com/docker/docker/daemon/logger/local" <ide> _ "github.com/docker/docker/daemon/logger/logentries" <ide> _ "github.com/docker/docker/daemon/logger/splunk" <ide> _ "github.com/docker/docker/daemon/logger/syslog" <ide><path>daemon/logger/local/config.go <add>package local <add> <add>import ( <add> "github.com/pkg/errors" <add>) <add> <add>// CreateConfig is used to configure new instances of driver <add>type CreateConfig struct { <add> DisableCompression bool <add> MaxFileSize int64 <add> MaxFileCount int <add>} <add> <add>func newDefaultConfig() *CreateConfig { <add> return &CreateConfig{ <add> MaxFileSize: defaultMaxFileSize, <add> MaxFileCount: defaultMaxFileCount, <add> DisableCompression: !defaultCompressLogs, <add> } <add>} <add> <add>func validateConfig(cfg *CreateConfig) error { <add> if cfg.MaxFileSize < 0 { <add> return errors.New("max size should be a positive number") <add> } <add> if cfg.MaxFileCount < 0 { <add> return errors.New("max file count cannot be less than 0") <add> } <add> <add> if !cfg.DisableCompression { <add> if cfg.MaxFileCount <= 1 { <add> return errors.New("compression cannot be enabled when max file count is 1") <add> } <add> } <add> return nil <add>} <ide><path>daemon/logger/local/doc.go <add>// Package local provides a logger implementation that stores logs on disk. <add>// <add>// Log messages are encoded as protobufs with a header and footer for each message. <add>// The header and footer are big-endian binary encoded uint32 values which indicate the size of the log message. <add>// The header and footer of each message allows you to efficiently read through a file either forwards or in <add>// backwards (such as is the case when tailing a file) <add>// <add>// Example log message format: [22][This is a log message.][22][28][This is another log message.][28] <add>package local // import "github.com/docker/docker/daemon/logger/local" <ide><path>daemon/logger/local/local.go <add>package local // import "github.com/docker/docker/daemon/logger/local" <add> <add>import ( <add> "encoding/binary" <add> "io" <add> "strconv" <add> "sync" <add> "time" <add> <add> "github.com/docker/docker/api/types/backend" <add> "github.com/docker/docker/api/types/plugins/logdriver" <add> "github.com/docker/docker/daemon/logger" <add> "github.com/docker/docker/daemon/logger/loggerutils" <add> "github.com/docker/docker/errdefs" <add> "github.com/docker/go-units" <add> "github.com/pkg/errors" <add> "github.com/sirupsen/logrus" <add>) <add> <add>const ( <add> // Name is the name of the driver <add> Name = "local" <add> <add> encodeBinaryLen = 4 <add> initialBufSize = 2048 <add> maxDecodeRetry = 20000 <add> <add> defaultMaxFileSize int64 = 20 * 1024 * 1024 <add> defaultMaxFileCount = 5 <add> defaultCompressLogs = true <add>) <add> <add>// LogOptKeys are the keys names used for log opts passed in to initialize the driver. <add>var LogOptKeys = map[string]bool{ <add> "max-file": true, <add> "max-size": true, <add> "compress": true, <add>} <add> <add>// ValidateLogOpt looks for log driver specific options. <add>func ValidateLogOpt(cfg map[string]string) error { <add> for key := range cfg { <add> if !LogOptKeys[key] { <add> return errors.Errorf("unknown log opt '%s' for log driver %s", key, Name) <add> } <add> } <add> return nil <add>} <add> <add>func init() { <add> if err := logger.RegisterLogDriver(Name, New); err != nil { <add> logrus.Fatal(err) <add> } <add> if err := logger.RegisterLogOptValidator(Name, ValidateLogOpt); err != nil { <add> logrus.Fatal(err) <add> } <add>} <add> <add>type driver struct { <add> mu sync.Mutex <add> closed bool <add> logfile *loggerutils.LogFile <add> readers map[*logger.LogWatcher]struct{} // stores the active log followers <add>} <add> <add>// New creates a new local logger <add>// You must provide the `LogPath` in the passed in info argument, this is the file path that logs are written to. <add>func New(info logger.Info) (logger.Logger, error) { <add> if info.LogPath == "" { <add> return nil, errdefs.System(errors.New("log path is missing -- this is a bug and should not happen")) <add> } <add> <add> cfg := newDefaultConfig() <add> if capacity, ok := info.Config["max-size"]; ok { <add> var err error <add> cfg.MaxFileSize, err = units.FromHumanSize(capacity) <add> if err != nil { <add> return nil, errdefs.InvalidParameter(errors.Wrapf(err, "invalid value for max-size: %s", capacity)) <add> } <add> } <add> <add> if userMaxFileCount, ok := info.Config["max-file"]; ok { <add> var err error <add> cfg.MaxFileCount, err = strconv.Atoi(userMaxFileCount) <add> if err != nil { <add> return nil, errdefs.InvalidParameter(errors.Wrapf(err, "invalid value for max-file: %s", userMaxFileCount)) <add> } <add> } <add> <add> if userCompress, ok := info.Config["compress"]; ok { <add> compressLogs, err := strconv.ParseBool(userCompress) <add> if err != nil { <add> return nil, errdefs.InvalidParameter(errors.Wrap(err, "error reading compress log option")) <add> } <add> cfg.DisableCompression = !compressLogs <add> } <add> return newDriver(info.LogPath, cfg) <add>} <add> <add>func makeMarshaller() func(m *logger.Message) ([]byte, error) { <add> buf := make([]byte, initialBufSize) <add> <add> // allocate the partial log entry separately, which allows for easier re-use <add> proto := &logdriver.LogEntry{} <add> md := &logdriver.PartialLogEntryMetadata{} <add> <add> return func(m *logger.Message) ([]byte, error) { <add> resetProto(proto) <add> <add> messageToProto(m, proto, md) <add> protoSize := proto.Size() <add> writeLen := protoSize + (2 * encodeBinaryLen) //+ len(messageDelimiter) <add> <add> if writeLen > len(buf) { <add> buf = make([]byte, writeLen) <add> } else { <add> // shrink the buffer back down <add> if writeLen <= initialBufSize { <add> buf = buf[:initialBufSize] <add> } else { <add> buf = buf[:writeLen] <add> } <add> } <add> <add> binary.BigEndian.PutUint32(buf[:encodeBinaryLen], uint32(protoSize)) <add> n, err := proto.MarshalTo(buf[encodeBinaryLen:writeLen]) <add> if err != nil { <add> return nil, errors.Wrap(err, "error marshaling log entry") <add> } <add> if n+(encodeBinaryLen*2) != writeLen { <add> return nil, io.ErrShortWrite <add> } <add> binary.BigEndian.PutUint32(buf[writeLen-encodeBinaryLen:writeLen], uint32(protoSize)) <add> return buf[:writeLen], nil <add> } <add>} <add> <add>func newDriver(logPath string, cfg *CreateConfig) (logger.Logger, error) { <add> if err := validateConfig(cfg); err != nil { <add> return nil, errdefs.InvalidParameter(err) <add> } <add> <add> lf, err := loggerutils.NewLogFile(logPath, cfg.MaxFileSize, cfg.MaxFileCount, !cfg.DisableCompression, makeMarshaller(), decodeFunc, 0640, getTailReader) <add> if err != nil { <add> return nil, err <add> } <add> return &driver{ <add> logfile: lf, <add> readers: make(map[*logger.LogWatcher]struct{}), <add> }, nil <add>} <add> <add>func (d *driver) Name() string { <add> return Name <add>} <add> <add>func (d *driver) Log(msg *logger.Message) error { <add> d.mu.Lock() <add> err := d.logfile.WriteLogEntry(msg) <add> d.mu.Unlock() <add> return err <add>} <add> <add>func (d *driver) Close() error { <add> d.mu.Lock() <add> d.closed = true <add> err := d.logfile.Close() <add> for r := range d.readers { <add> r.Close() <add> delete(d.readers, r) <add> } <add> d.mu.Unlock() <add> return err <add>} <add> <add>func messageToProto(msg *logger.Message, proto *logdriver.LogEntry, partial *logdriver.PartialLogEntryMetadata) { <add> proto.Source = msg.Source <add> proto.TimeNano = msg.Timestamp.UnixNano() <add> proto.Line = append(proto.Line[:0], msg.Line...) <add> proto.Partial = msg.PLogMetaData != nil <add> if proto.Partial { <add> partial.Ordinal = int32(msg.PLogMetaData.Ordinal) <add> partial.Last = msg.PLogMetaData.Last <add> partial.Id = msg.PLogMetaData.ID <add> proto.PartialLogMetadata = partial <add> } else { <add> proto.PartialLogMetadata = nil <add> } <add>} <add> <add>func protoToMessage(proto *logdriver.LogEntry) *logger.Message { <add> msg := &logger.Message{ <add> Source: proto.Source, <add> Timestamp: time.Unix(0, proto.TimeNano), <add> } <add> if proto.Partial { <add> var md backend.PartialLogMetaData <add> md.Last = proto.GetPartialLogMetadata().GetLast() <add> md.ID = proto.GetPartialLogMetadata().GetId() <add> md.Ordinal = int(proto.GetPartialLogMetadata().GetOrdinal()) <add> msg.PLogMetaData = &md <add> } <add> msg.Line = append(msg.Line[:0], proto.Line...) <add> return msg <add>} <add> <add>func resetProto(proto *logdriver.LogEntry) { <add> proto.Source = "" <add> proto.Line = proto.Line[:0] <add> proto.TimeNano = 0 <add> proto.Partial = false <add> if proto.PartialLogMetadata != nil { <add> proto.PartialLogMetadata.Id = "" <add> proto.PartialLogMetadata.Last = false <add> proto.PartialLogMetadata.Ordinal = 0 <add> } <add> proto.PartialLogMetadata = nil <add>} <ide><path>daemon/logger/local/local_test.go <add>package local <add> <add>import ( <add> "context" <add> "encoding/binary" <add> "io/ioutil" <add> "os" <add> "path/filepath" <add> "testing" <add> "time" <add> <add> "bytes" <add> "fmt" <add> <add> "strings" <add> <add> "io" <add> <add> "github.com/docker/docker/api/types/backend" <add> "github.com/docker/docker/api/types/plugins/logdriver" <add> "github.com/docker/docker/daemon/logger" <add> protoio "github.com/gogo/protobuf/io" <add> "gotest.tools/assert" <add> is "gotest.tools/assert/cmp" <add>) <add> <add>func TestWriteLog(t *testing.T) { <add> t.Parallel() <add> <add> dir, err := ioutil.TempDir("", t.Name()) <add> assert.Assert(t, err) <add> defer os.RemoveAll(dir) <add> <add> logPath := filepath.Join(dir, "test.log") <add> <add> l, err := New(logger.Info{LogPath: logPath}) <add> assert.Assert(t, err) <add> defer l.Close() <add> <add> m1 := logger.Message{Source: "stdout", Timestamp: time.Now().Add(-1 * 30 * time.Minute), Line: []byte("message 1")} <add> m2 := logger.Message{Source: "stdout", Timestamp: time.Now().Add(-1 * 20 * time.Minute), Line: []byte("message 2"), PLogMetaData: &backend.PartialLogMetaData{Last: true, ID: "0001", Ordinal: 1}} <add> m3 := logger.Message{Source: "stderr", Timestamp: time.Now().Add(-1 * 10 * time.Minute), Line: []byte("message 3")} <add> <add> // copy the log message because the underying log writer resets the log message and returns it to a buffer pool <add> err = l.Log(copyLogMessage(&m1)) <add> assert.Assert(t, err) <add> err = l.Log(copyLogMessage(&m2)) <add> assert.Assert(t, err) <add> err = l.Log(copyLogMessage(&m3)) <add> assert.Assert(t, err) <add> <add> f, err := os.Open(logPath) <add> assert.Assert(t, err) <add> defer f.Close() <add> dec := protoio.NewUint32DelimitedReader(f, binary.BigEndian, 1e6) <add> <add> var ( <add> proto logdriver.LogEntry <add> testProto logdriver.LogEntry <add> partial logdriver.PartialLogEntryMetadata <add> ) <add> <add> lenBuf := make([]byte, encodeBinaryLen) <add> seekMsgLen := func() { <add> io.ReadFull(f, lenBuf) <add> } <add> <add> err = dec.ReadMsg(&proto) <add> assert.Assert(t, err) <add> messageToProto(&m1, &testProto, &partial) <add> assert.Check(t, is.DeepEqual(testProto, proto), "expected:\n%+v\ngot:\n%+v", testProto, proto) <add> seekMsgLen() <add> <add> err = dec.ReadMsg(&proto) <add> assert.Assert(t, err) <add> messageToProto(&m2, &testProto, &partial) <add> assert.Check(t, is.DeepEqual(testProto, proto)) <add> seekMsgLen() <add> <add> err = dec.ReadMsg(&proto) <add> assert.Assert(t, err) <add> messageToProto(&m3, &testProto, &partial) <add> assert.Check(t, is.DeepEqual(testProto, proto), "expected:\n%+v\ngot:\n%+v", testProto, proto) <add>} <add> <add>func TestReadLog(t *testing.T) { <add> t.Parallel() <add> <add> dir, err := ioutil.TempDir("", t.Name()) <add> assert.Assert(t, err) <add> defer os.RemoveAll(dir) <add> <add> logPath := filepath.Join(dir, "test.log") <add> l, err := New(logger.Info{LogPath: logPath}) <add> assert.Assert(t, err) <add> defer l.Close() <add> <add> m1 := logger.Message{Source: "stdout", Timestamp: time.Now().Add(-1 * 30 * time.Minute), Line: []byte("a message")} <add> m2 := logger.Message{Source: "stdout", Timestamp: time.Now().Add(-1 * 20 * time.Minute), Line: []byte("another message"), PLogMetaData: &backend.PartialLogMetaData{Ordinal: 1, Last: true}} <add> longMessage := []byte("a really long message " + strings.Repeat("a", initialBufSize*2)) <add> m3 := logger.Message{Source: "stderr", Timestamp: time.Now().Add(-1 * 10 * time.Minute), Line: longMessage} <add> m4 := logger.Message{Source: "stderr", Timestamp: time.Now().Add(-1 * 10 * time.Minute), Line: []byte("just one more message")} <add> <add> // copy the log message because the underlying log writer resets the log message and returns it to a buffer pool <add> err = l.Log(copyLogMessage(&m1)) <add> assert.Assert(t, err) <add> err = l.Log(copyLogMessage(&m2)) <add> assert.Assert(t, err) <add> err = l.Log(copyLogMessage(&m3)) <add> assert.Assert(t, err) <add> err = l.Log(copyLogMessage(&m4)) <add> assert.Assert(t, err) <add> <add> lr := l.(logger.LogReader) <add> <add> testMessage := func(t *testing.T, lw *logger.LogWatcher, m *logger.Message) { <add> t.Helper() <add> ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) <add> defer cancel() <add> select { <add> case <-ctx.Done(): <add> assert.Assert(t, ctx.Err()) <add> case err := <-lw.Err: <add> assert.Assert(t, err) <add> case msg, open := <-lw.Msg: <add> if !open { <add> select { <add> case err := <-lw.Err: <add> assert.Assert(t, err) <add> default: <add> assert.Assert(t, m == nil) <add> return <add> } <add> } <add> assert.Assert(t, m != nil) <add> if m.PLogMetaData == nil { <add> // a `\n` is appended on read to make this work with the existing API's when the message is not a partial. <add> // make sure it's the last entry in the line, and then truncate it for the deep equal below. <add> assert.Check(t, msg.Line[len(msg.Line)-1] == '\n') <add> msg.Line = msg.Line[:len(msg.Line)-1] <add> } <add> assert.Check(t, is.DeepEqual(m, msg), fmt.Sprintf("\n%+v\n%+v", m, msg)) <add> } <add> } <add> <add> t.Run("tail exact", func(t *testing.T) { <add> lw := lr.ReadLogs(logger.ReadConfig{Tail: 4}) <add> <add> testMessage(t, lw, &m1) <add> testMessage(t, lw, &m2) <add> testMessage(t, lw, &m3) <add> testMessage(t, lw, &m4) <add> testMessage(t, lw, nil) // no more messages <add> }) <add> <add> t.Run("tail less than available", func(t *testing.T) { <add> lw := lr.ReadLogs(logger.ReadConfig{Tail: 2}) <add> <add> testMessage(t, lw, &m3) <add> testMessage(t, lw, &m4) <add> testMessage(t, lw, nil) // no more messages <add> }) <add> <add> t.Run("tail more than available", func(t *testing.T) { <add> lw := lr.ReadLogs(logger.ReadConfig{Tail: 100}) <add> <add> testMessage(t, lw, &m1) <add> testMessage(t, lw, &m2) <add> testMessage(t, lw, &m3) <add> testMessage(t, lw, &m4) <add> testMessage(t, lw, nil) // no more messages <add> }) <add>} <add> <add>func BenchmarkLogWrite(b *testing.B) { <add> f, err := ioutil.TempFile("", b.Name()) <add> assert.Assert(b, err) <add> defer os.Remove(f.Name()) <add> f.Close() <add> <add> local, err := New(logger.Info{LogPath: f.Name()}) <add> assert.Assert(b, err) <add> defer local.Close() <add> <add> t := time.Now().UTC() <add> for _, data := range [][]byte{ <add> []byte(""), <add> []byte("a short string"), <add> bytes.Repeat([]byte("a long string"), 100), <add> bytes.Repeat([]byte("a really long string"), 10000), <add> } { <add> b.Run(fmt.Sprintf("%d", len(data)), func(b *testing.B) { <add> entry := &logdriver.LogEntry{Line: data, Source: "stdout", TimeNano: t.UnixNano()} <add> b.SetBytes(int64(entry.Size() + encodeBinaryLen + encodeBinaryLen)) <add> b.ResetTimer() <add> for i := 0; i < b.N; i++ { <add> msg := logger.NewMessage() <add> msg.Line = data <add> msg.Timestamp = t <add> msg.Source = "stdout" <add> if err := local.Log(msg); err != nil { <add> b.Fatal(err) <add> } <add> } <add> }) <add> } <add>} <add> <add>func copyLogMessage(src *logger.Message) *logger.Message { <add> dst := logger.NewMessage() <add> dst.Source = src.Source <add> dst.Timestamp = src.Timestamp <add> dst.Attrs = src.Attrs <add> dst.Err = src.Err <add> dst.Line = append(dst.Line, src.Line...) <add> if src.PLogMetaData != nil { <add> dst.PLogMetaData = &(*src.PLogMetaData) <add> } <add> return dst <add>} <ide><path>daemon/logger/local/read.go <add>package local <add> <add>import ( <add> "context" <add> "encoding/binary" <add> "io" <add> <add> "bytes" <add> <add> "github.com/docker/docker/api/types/plugins/logdriver" <add> "github.com/docker/docker/daemon/logger" <add> "github.com/docker/docker/daemon/logger/loggerutils" <add> "github.com/docker/docker/errdefs" <add> "github.com/pkg/errors" <add>) <add> <add>func (d *driver) ReadLogs(config logger.ReadConfig) *logger.LogWatcher { <add> logWatcher := logger.NewLogWatcher() <add> <add> go d.readLogs(logWatcher, config) <add> return logWatcher <add>} <add> <add>func (d *driver) readLogs(watcher *logger.LogWatcher, config logger.ReadConfig) { <add> defer close(watcher.Msg) <add> <add> d.mu.Lock() <add> d.readers[watcher] = struct{}{} <add> d.mu.Unlock() <add> <add> d.logfile.ReadLogs(config, watcher) <add> <add> d.mu.Lock() <add> delete(d.readers, watcher) <add> d.mu.Unlock() <add>} <add> <add>func getTailReader(ctx context.Context, r loggerutils.SizeReaderAt, req int) (io.Reader, int, error) { <add> size := r.Size() <add> if req < 0 { <add> return nil, 0, errdefs.InvalidParameter(errors.Errorf("invalid number of lines to tail: %d", req)) <add> } <add> <add> if size < (encodeBinaryLen*2)+1 { <add> return bytes.NewReader(nil), 0, nil <add> } <add> <add> const encodeBinaryLen64 = int64(encodeBinaryLen) <add> var found int <add> <add> buf := make([]byte, encodeBinaryLen) <add> <add> offset := size <add> for { <add> select { <add> case <-ctx.Done(): <add> return nil, 0, ctx.Err() <add> default: <add> } <add> <add> n, err := r.ReadAt(buf, offset-encodeBinaryLen64) <add> if err != nil && err != io.EOF { <add> return nil, 0, errors.Wrap(err, "error reading log message footer") <add> } <add> <add> if n != encodeBinaryLen { <add> return nil, 0, errdefs.DataLoss(errors.New("unexpected number of bytes read from log message footer")) <add> } <add> <add> msgLen := binary.BigEndian.Uint32(buf) <add> <add> n, err = r.ReadAt(buf, offset-encodeBinaryLen64-encodeBinaryLen64-int64(msgLen)) <add> if err != nil && err != io.EOF { <add> return nil, 0, errors.Wrap(err, "error reading log message header") <add> } <add> <add> if n != encodeBinaryLen { <add> return nil, 0, errdefs.DataLoss(errors.New("unexpected number of bytes read from log message header")) <add> } <add> <add> if msgLen != binary.BigEndian.Uint32(buf) { <add> return nil, 0, errdefs.DataLoss(errors.Wrap(err, "log message header and footer indicate different message sizes")) <add> } <add> <add> found++ <add> offset -= int64(msgLen) <add> offset -= encodeBinaryLen64 * 2 <add> if found == req { <add> break <add> } <add> if offset <= 0 { <add> break <add> } <add> } <add> <add> return io.NewSectionReader(r, offset, size), found, nil <add>} <add> <add>func decodeFunc(rdr io.Reader) func() (*logger.Message, error) { <add> proto := &logdriver.LogEntry{} <add> buf := make([]byte, initialBufSize) <add> <add> return func() (*logger.Message, error) { <add> var ( <add> read int <add> err error <add> ) <add> <add> resetProto(proto) <add> <add> for i := 0; i < maxDecodeRetry; i++ { <add> var n int <add> n, err = io.ReadFull(rdr, buf[read:encodeBinaryLen]) <add> if err != nil { <add> if err != io.ErrUnexpectedEOF { <add> return nil, errors.Wrap(err, "error reading log message length") <add> } <add> read += n <add> continue <add> } <add> read += n <add> break <add> } <add> if err != nil { <add> return nil, errors.Wrapf(err, "could not read log message length: read: %d, expected: %d", read, encodeBinaryLen) <add> } <add> <add> msgLen := int(binary.BigEndian.Uint32(buf[:read])) <add> <add> if len(buf) < msgLen+encodeBinaryLen { <add> buf = make([]byte, msgLen+encodeBinaryLen) <add> } else { <add> if msgLen <= initialBufSize { <add> buf = buf[:initialBufSize] <add> } else { <add> buf = buf[:msgLen+encodeBinaryLen] <add> } <add> } <add> <add> return decodeLogEntry(rdr, proto, buf, msgLen) <add> } <add>} <add> <add>func decodeLogEntry(rdr io.Reader, proto *logdriver.LogEntry, buf []byte, msgLen int) (*logger.Message, error) { <add> var ( <add> read int <add> err error <add> ) <add> for i := 0; i < maxDecodeRetry; i++ { <add> var n int <add> n, err = io.ReadFull(rdr, buf[read:msgLen+encodeBinaryLen]) <add> if err != nil { <add> if err != io.ErrUnexpectedEOF { <add> return nil, errors.Wrap(err, "could not decode log entry") <add> } <add> read += n <add> continue <add> } <add> break <add> } <add> if err != nil { <add> return nil, errors.Wrapf(err, "could not decode entry: read %d, expected: %d", read, msgLen) <add> } <add> <add> if err := proto.Unmarshal(buf[:msgLen]); err != nil { <add> return nil, errors.Wrap(err, "error unmarshalling log entry") <add> } <add> <add> msg := protoToMessage(proto) <add> if msg.PLogMetaData == nil { <add> msg.Line = append(msg.Line, '\n') <add> } <add> return msg, nil <add>}
7
Go
Go
apply apparmor profile
94c07441c233ed4b738b97ca19774912f728075e
<ide><path>builder/builder-next/builder.go <ide> type Opt struct { <ide> Rootless bool <ide> IdentityMapping *idtools.IdentityMapping <ide> DNSConfig config.DNSConfig <add> ApparmorProfile string <ide> } <ide> <ide> // Builder can build using BuildKit backend <ide><path>builder/builder-next/controller.go <ide> func newController(rt http.RoundTripper, opt Opt) (*control.Controller, error) { <ide> <ide> dns := getDNSConfig(opt.DNSConfig) <ide> <del> exec, err := newExecutor(root, opt.DefaultCgroupParent, opt.NetworkController, dns, opt.Rootless, opt.IdentityMapping) <add> exec, err := newExecutor(root, opt.DefaultCgroupParent, opt.NetworkController, dns, opt.Rootless, opt.IdentityMapping, opt.ApparmorProfile) <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>builder/builder-next/executor_unix.go <ide> import ( <ide> <ide> const networkName = "bridge" <ide> <del>func newExecutor(root, cgroupParent string, net libnetwork.NetworkController, dnsConfig *oci.DNSConfig, rootless bool, idmap *idtools.IdentityMapping) (executor.Executor, error) { <add>func newExecutor(root, cgroupParent string, net libnetwork.NetworkController, dnsConfig *oci.DNSConfig, rootless bool, idmap *idtools.IdentityMapping, apparmorProfile string) (executor.Executor, error) { <ide> netRoot := filepath.Join(root, "net") <ide> networkProviders := map[pb.NetMode]network.Provider{ <ide> pb.NetMode_UNSET: &bridgeProvider{NetworkController: net, Root: netRoot}, <ide> func newExecutor(root, cgroupParent string, net libnetwork.NetworkController, dn <ide> NoPivot: os.Getenv("DOCKER_RAMDISK") != "", <ide> IdentityMapping: idmap, <ide> DNS: dnsConfig, <add> ApparmorProfile: apparmorProfile, <ide> }, networkProviders) <ide> } <ide> <ide><path>builder/builder-next/executor_windows.go <ide> import ( <ide> "github.com/moby/buildkit/executor/oci" <ide> ) <ide> <del>func newExecutor(_, _ string, _ libnetwork.NetworkController, _ *oci.DNSConfig, _ bool, _ *idtools.IdentityMapping) (executor.Executor, error) { <add>func newExecutor(_, _ string, _ libnetwork.NetworkController, _ *oci.DNSConfig, _ bool, _ *idtools.IdentityMapping, _ string) (executor.Executor, error) { <ide> return &winExecutor{}, nil <ide> } <ide> <ide><path>cmd/dockerd/daemon.go <ide> func newRouterOptions(config *config.Config, d *daemon.Daemon) (routerOptions, e <ide> Rootless: d.Rootless(), <ide> IdentityMapping: d.IdentityMapping(), <ide> DNSConfig: config.DNSConfig, <add> ApparmorProfile: daemon.DefaultApparmorProfile(), <ide> }) <ide> if err != nil { <ide> return opts, err <ide><path>daemon/apparmor_default.go <ide> const ( <ide> defaultAppArmorProfile = "docker-default" <ide> ) <ide> <add>// DefaultApparmorProfile returns the name of the default apparmor profile <add>func DefaultApparmorProfile() string { <add> if apparmor.IsEnabled() { <add> return defaultAppArmorProfile <add> } <add> return "" <add>} <add> <ide> func ensureDefaultAppArmorProfile() error { <ide> if apparmor.IsEnabled() { <ide> loaded, err := aaprofile.IsLoaded(defaultAppArmorProfile) <ide><path>daemon/apparmor_default_unsupported.go <ide> package daemon // import "github.com/docker/docker/daemon" <ide> func ensureDefaultAppArmorProfile() error { <ide> return nil <ide> } <add> <add>// DefaultApparmorProfile returns an empty string. <add>func DefaultApparmorProfile() string { <add> return "" <add>}
7
Javascript
Javascript
remove workaround for adreno
03f35a96ae36507a2d234f6f0726dd64393ee49d
<ide><path>examples/jsm/nodes/math/MathNode.js <ide> import TempNode from '../core/TempNode.js'; <ide> import ExpressionNode from '../core/ExpressionNode.js'; <del>import JoinNode from '../utils/JoinNode.js'; <ide> import SplitNode from '../utils/SplitNode.js'; <ide> import OperatorNode from './OperatorNode.js'; <ide> <ide> class MathNode extends TempNode { <ide> <ide> const isWebGL = builder.renderer.isWebGLRenderer === true; <ide> <del> if ( isWebGL && ( method === MathNode.DFDX || method === MathNode.DFDY ) && output === 'vec3' ) { <del> <del> // Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988 <del> <del> return new JoinNode( [ <del> new MathNode( method, new SplitNode( a, 'x' ) ), <del> new MathNode( method, new SplitNode( a, 'y' ) ), <del> new MathNode( method, new SplitNode( a, 'z' ) ) <del> ] ).build( builder ); <del> <del> } else if ( method === MathNode.TRANSFORM_DIRECTION ) { <add> if ( method === MathNode.TRANSFORM_DIRECTION ) { <ide> <ide> // dir can be either a direction vector or a normal vector <ide> // upper-left 3x3 of matrix is assumed to be orthogonal
1
Javascript
Javascript
remove unused code
025d3d0836b16be7eb970743c67b64d9cb670d23
<ide><path>lib/optimize/SideEffectsFlagPlugin.js <ide> <ide> const mm = require("micromatch"); <ide> const HarmonyExportImportedSpecifierDependency = require("../dependencies/HarmonyExportImportedSpecifierDependency"); <del>const HarmonyImportSideEffectDependency = require("../dependencies/HarmonyImportSideEffectDependency"); <ide> const HarmonyImportSpecifierDependency = require("../dependencies/HarmonyImportSpecifierDependency"); <ide> <ide> /** @typedef {import("../Module")} Module */ <ide> class SideEffectsFlagPlugin { <ide> <ide> // Capture reexports of sideEffectFree modules <ide> for (const module of modules) { <del> /** @type {Dependency[]} */ <del> const removeDependencies = []; <ide> for (const dep of module.dependencies) { <del> if (dep instanceof HarmonyImportSideEffectDependency) { <del> if (dep.module && dep.module.factoryMeta.sideEffectFree) { <del> removeDependencies.push(dep); <del> } <del> } else if ( <del> dep instanceof HarmonyExportImportedSpecifierDependency <del> ) { <add> if (dep instanceof HarmonyExportImportedSpecifierDependency) { <ide> if (module.factoryMeta.sideEffectFree) { <ide> const mode = dep.getMode(true); <ide> if (mode.type === "safe-reexport") {
1
Go
Go
adjust warning strings for cgroup v2
00225e220fb18283dcf9e4fa6625fad6746d8a50
<ide><path>daemon/info_unix.go <ide> func (daemon *Daemon) fillPlatformInfo(v *types.Info, sysInfo *sysinfo.SysInfo) <ide> // blkio weight is not available on cgroup v1 since kernel 5.0. <ide> // Warning is not printed on cgroup v1, because there is no action user can take. <ide> // On cgroup v2, blkio weight is implemented using io.weight <del> v.Warnings = append(v.Warnings, "WARNING: No blkio weight support") <add> v.Warnings = append(v.Warnings, "WARNING: No io.weight support") <ide> } <ide> if !sysInfo.BlkioWeightDevice && v.CgroupVersion == "2" { <del> v.Warnings = append(v.Warnings, "WARNING: No blkio weight_device support") <add> v.Warnings = append(v.Warnings, "WARNING: No io.weight (per device) support") <ide> } <ide> if !sysInfo.BlkioReadBpsDevice { <del> v.Warnings = append(v.Warnings, "WARNING: No blkio throttle.read_bps_device support") <add> if v.CgroupVersion == "2" { <add> v.Warnings = append(v.Warnings, "WARNING: No io.max (rbps) support") <add> } else { <add> v.Warnings = append(v.Warnings, "WARNING: No blkio throttle.read_bps_device support") <add> } <ide> } <ide> if !sysInfo.BlkioWriteBpsDevice { <del> v.Warnings = append(v.Warnings, "WARNING: No blkio throttle.write_bps_device support") <add> if v.CgroupVersion == "2" { <add> v.Warnings = append(v.Warnings, "WARNING: No io.max (wbps) support") <add> } else { <add> v.Warnings = append(v.Warnings, "WARNING: No blkio throttle.write_bps_device support") <add> } <ide> } <ide> if !sysInfo.BlkioReadIOpsDevice { <del> v.Warnings = append(v.Warnings, "WARNING: No blkio throttle.read_iops_device support") <add> if v.CgroupVersion == "2" { <add> v.Warnings = append(v.Warnings, "WARNING: No io.max (riops) support") <add> } else { <add> v.Warnings = append(v.Warnings, "WARNING: No blkio throttle.read_iops_device support") <add> } <ide> } <ide> if !sysInfo.BlkioWriteIOpsDevice { <del> v.Warnings = append(v.Warnings, "WARNING: No blkio throttle.write_iops_device support") <add> if v.CgroupVersion == "2" { <add> v.Warnings = append(v.Warnings, "WARNING: No io.max (wiops) support") <add> } else { <add> v.Warnings = append(v.Warnings, "WARNING: No blkio throttle.write_iops_device support") <add> } <ide> } <ide> } <ide> if !v.IPv4Forwarding {
1
Python
Python
remove dt_double from the t5 graph
babd7b1a92a12d88516f4081dd37a0df27259c35
<ide><path>src/transformers/models/t5/modeling_tf_t5.py <ide> def _relative_position_bucket(relative_position, bidirectional=True, num_buckets <ide> max_exact = num_buckets // 2 <ide> is_small = tf.math.less(relative_position, max_exact) <ide> relative_position_if_large = max_exact + tf.cast( <del> tf.math.log(relative_position / max_exact) <add> tf.math.log(tf.cast(relative_position, tf.float32) / tf.cast(max_exact, tf.float32)) <ide> / math.log(max_distance / max_exact) <ide> * (num_buckets - max_exact), <ide> dtype=relative_position.dtype,
1
PHP
PHP
fix memory leak in eagerloader
c5cb54cbe46ab8ff2cedceddd0d63d8672982a92
<ide><path>src/ORM/EagerLoader.php <ide> public function associationsMap($table) <ide> return $map; <ide> } <ide> <del> $visitor = function ($level, $matching = false) use (&$visitor, &$map) { <del> /* @var \Cake\ORM\EagerLoadable $meta */ <del> foreach ($level as $assoc => $meta) { <del> $canBeJoined = $meta->canBeJoined(); <del> $instance = $meta->instance(); <del> $associations = $meta->associations(); <del> $forMatching = $meta->forMatching(); <del> $map[] = [ <del> 'alias' => $assoc, <del> 'instance' => $instance, <del> 'canBeJoined' => $canBeJoined, <del> 'entityClass' => $instance->getTarget()->getEntityClass(), <del> 'nestKey' => $canBeJoined ? $assoc : $meta->aliasPath(), <del> 'matching' => $forMatching !== null ? $forMatching : $matching, <del> 'targetProperty' => $meta->targetProperty() <del> ]; <del> if ($canBeJoined && $associations) { <del> $visitor($associations, $matching); <del> } <add> $map = $this->_buildAssociationsMap($map, $this->_matching->normalized($table), true); <add> $map = $this->_buildAssociationsMap($map, $this->normalized($table)); <add> $map = $this->_buildAssociationsMap($map, $this->_joinsMap); <add> <add> return $map; <add> } <add> <add> /** <add> * An internal method to build a map which is used for the return value of the <add> * associationsMap() method. <add> * <add> * @param array $map An initial array for the map. <add> * @param array $level An array of EagerLoadable instances. <add> * @param bool $matching Whether or not it is an association loaded through `matching()`. <add> * @return array <add> */ <add> protected function _buildAssociationsMap(array $map, array $level, $matching = false) <add> { <add> /* @var \Cake\ORM\EagerLoadable $meta */ <add> foreach ($level as $assoc => $meta) { <add> $canBeJoined = $meta->canBeJoined(); <add> $instance = $meta->instance(); <add> $associations = $meta->associations(); <add> $forMatching = $meta->forMatching(); <add> $map[] = [ <add> 'alias' => $assoc, <add> 'instance' => $instance, <add> 'canBeJoined' => $canBeJoined, <add> 'entityClass' => $instance->getTarget()->getEntityClass(), <add> 'nestKey' => $canBeJoined ? $assoc : $meta->aliasPath(), <add> 'matching' => $forMatching !== null ? $forMatching : $matching, <add> 'targetProperty' => $meta->targetProperty() <add> ]; <add> if ($canBeJoined && $associations) { <add> $map = $this->_buildAssociationsMap($map, $associations, $matching); <ide> } <del> }; <del> $visitor($this->_matching->normalized($table), true); <del> $visitor($this->normalized($table)); <del> $visitor($this->_joinsMap); <add> } <ide> <ide> return $map; <ide> }
1
Python
Python
replace list creation with list literal"
571b9eb999e27df33681537af8a033d2320e3667
<ide><path>glances/plugins/glances_help.py <ide> def get_view_data(self, args=None): <ide> <ide> def msg_curse(self, args=None): <ide> """Return the list to display in the curse interface.""" <del> ret = [ <del> # Header <del> self.curse_add_line(self.view_data['version'], 'TITLE'), <del> self.curse_add_line(self.view_data['psutil_version']), <del> self.curse_new_line(), <del> # Configuration file <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['configuration_file']), <del> self.curse_new_line(), <del> # Keys <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['sort_auto']), <del> self.curse_add_line(self.view_data['sort_network']), <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['sort_cpu']), <del> self.curse_add_line(self.view_data['show_hide_alert']), <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['sort_mem']), <del> self.curse_add_line(self.view_data['delete_warning_alerts']), <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['sort_user']), <del> self.curse_add_line(self.view_data['delete_warning_critical_alerts']), <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['sort_proc']), <del> self.curse_add_line(self.view_data['percpu']), <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['sort_io']), <del> self.curse_add_line(self.view_data['show_hide_ip']), <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['sort_cpu_times']), <del> self.curse_add_line(self.view_data['enable_disable_docker']), <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['show_hide_diskio']), <del> self.curse_add_line(self.view_data['view_network_io_combination']), <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['show_hide_filesystem']), <del> self.curse_add_line(self.view_data['view_cumulative_network']), <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['show_hide_network']), <del> self.curse_add_line(self.view_data['show_hide_filesytem_freespace']), <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['show_hide_sensors']), <del> self.curse_add_line(self.view_data['generate_graphs']), <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['show_hide_left_sidebar']), <del> self.curse_add_line(self.view_data['reset_history']), <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['enable_disable_process_stats']), <del> self.curse_add_line(self.view_data['show_hide_help']), <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['enable_disable_quick_look']), <del> self.curse_add_line(self.view_data['quit']), <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['enable_disable_top_extends_stats']), <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['enable_disable_short_processname']), <del> self.curse_new_line(), <del> self.curse_new_line(), <del> self.curse_add_line(self.view_data['edit_pattern_filter'])] <add> # Init the return message <add> ret = [] <add> <add> # Build the string message <add> # Header <add> ret.append(self.curse_add_line(self.view_data['version'], 'TITLE')) <add> ret.append(self.curse_add_line(self.view_data['psutil_version'])) <add> ret.append(self.curse_new_line()) <add> <add> # Configuration file path <add> if 'configuration_file' in self.view_data: <add> ret.append(self.curse_new_line()) <add> ret.append(self.curse_add_line(self.view_data['configuration_file'])) <add> ret.append(self.curse_new_line()) <add> <add> # Keys <add> ret.append(self.curse_new_line()) <add> ret.append(self.curse_add_line(self.view_data['sort_auto'])) <add> ret.append(self.curse_add_line(self.view_data['sort_network'])) <add> ret.append(self.curse_new_line()) <add> ret.append(self.curse_add_line(self.view_data['sort_cpu'])) <add> ret.append(self.curse_add_line(self.view_data['show_hide_alert'])) <add> ret.append(self.curse_new_line()) <add> <add> ret.append(self.curse_add_line(self.view_data['sort_mem'])) <add> ret.append(self.curse_add_line(self.view_data['delete_warning_alerts'])) <add> ret.append(self.curse_new_line()) <add> ret.append(self.curse_add_line(self.view_data['sort_user'])) <add> ret.append(self.curse_add_line(self.view_data['delete_warning_critical_alerts'])) <add> ret.append(self.curse_new_line()) <add> ret.append(self.curse_add_line(self.view_data['sort_proc'])) <add> ret.append(self.curse_add_line(self.view_data['percpu'])) <add> ret.append(self.curse_new_line()) <add> ret.append(self.curse_add_line(self.view_data['sort_io'])) <add> ret.append(self.curse_add_line(self.view_data['show_hide_ip'])) <add> ret.append(self.curse_new_line()) <add> ret.append(self.curse_add_line(self.view_data['sort_cpu_times'])) <add> ret.append(self.curse_add_line(self.view_data['enable_disable_docker'])) <add> ret.append(self.curse_new_line()) <add> ret.append(self.curse_add_line(self.view_data['show_hide_diskio'])) <add> ret.append(self.curse_add_line(self.view_data['view_network_io_combination'])) <add> ret.append(self.curse_new_line()) <add> ret.append(self.curse_add_line(self.view_data['show_hide_filesystem'])) <add> ret.append(self.curse_add_line(self.view_data['view_cumulative_network'])) <add> ret.append(self.curse_new_line()) <add> ret.append(self.curse_add_line(self.view_data['show_hide_network'])) <add> ret.append(self.curse_add_line(self.view_data['show_hide_filesytem_freespace'])) <add> ret.append(self.curse_new_line()) <add> ret.append(self.curse_add_line(self.view_data['show_hide_sensors'])) <add> ret.append(self.curse_add_line(self.view_data['generate_graphs'])) <add> ret.append(self.curse_new_line()) <add> ret.append(self.curse_add_line(self.view_data['show_hide_left_sidebar'])) <add> ret.append(self.curse_add_line(self.view_data['reset_history'])) <add> ret.append(self.curse_new_line()) <add> ret.append(self.curse_add_line(self.view_data['enable_disable_process_stats'])) <add> ret.append(self.curse_add_line(self.view_data['show_hide_help'])) <add> ret.append(self.curse_new_line()) <add> ret.append(self.curse_add_line(self.view_data['enable_disable_quick_look'])) <add> ret.append(self.curse_add_line(self.view_data['quit'])) <add> ret.append(self.curse_new_line()) <add> ret.append(self.curse_add_line(self.view_data['enable_disable_top_extends_stats'])) <add> ret.append(self.curse_new_line()) <add> ret.append(self.curse_add_line(self.view_data['enable_disable_short_processname'])) <add> ret.append(self.curse_new_line()) <add> <add> ret.append(self.curse_new_line()) <add> <add> ret.append(self.curse_add_line(self.view_data['edit_pattern_filter'])) <ide> <ide> # Return the message with decoration <ide> return ret
1
Mixed
Javascript
replace validator and error
8c4b8b201ada6b76d5306c9c7f352e45087fb4a9
<ide><path>doc/api/crypto.md <ide> This property is deprecated. Please use `crypto.setFips()` and <ide> <ide> <!-- YAML <ide> added: v15.8.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `candidate` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint} <ide> Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` <ide> <ide> <!-- YAML <ide> added: v15.0.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `type`: {string} The intended use of the generated secret key. Currently <ide> generateKey('hmac', { length: 64 }, (err, key) => { <ide> <!-- YAML <ide> added: v10.12.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v16.10.0 <ide> pr-url: https://github.com/nodejs/node/pull/39927 <ide> description: Add ability to define `RSASSA-PSS-params` sequence parameters <ide> console.log(key.export().toString('hex')); // e89..........41e <ide> <ide> <!-- YAML <ide> added: v15.8.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `size` {number} The size (in bits) of the prime to generate. <ide> A convenient alias for [`crypto.webcrypto.getRandomValues()`][]. <ide> <ide> <!-- YAML <ide> added: v15.0.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `digest` {string} The digest algorithm to use. <ide> console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v15.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/35093 <ide> description: The password and salt arguments can also be ArrayBuffer <ide> be passed instead of a public key. <ide> <!-- YAML <ide> added: v0.5.8 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v9.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/16454 <ide> description: Passing `null` as the `callback` argument now throws <ide> added: <ide> - v7.10.0 <ide> - v6.13.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v9.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/15231 <ide> description: The `buffer` argument may be any `TypedArray` or `DataView`. <ide> request. <ide> added: <ide> - v14.10.0 <ide> - v12.19.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `min` {integer} Start of random range (inclusive). **Default:** `0`. <ide> cryptographic pseudorandom number generator. <ide> <!-- YAML <ide> added: v10.5.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v15.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/35093 <ide> description: The password and salt arguments can also be ArrayBuffer <ide> Throws an error if FIPS mode is not available. <ide> <!-- YAML <ide> added: v12.0.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v15.12.0 <ide> pr-url: https://github.com/nodejs/node/pull/37500 <ide> description: Optional callback argument added. <ide> not introduce timing vulnerabilities. <ide> <!-- YAML <ide> added: v12.0.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v15.12.0 <ide> pr-url: https://github.com/nodejs/node/pull/37500 <ide> description: Optional callback argument added. <ide><path>doc/api/deprecations.md <ide> This method was deprecated because it is not compatible with <ide> <ide> Use [`buffer.subarray`][] which does the same thing instead. <ide> <add>### DEP0159: `ERR_INVALID_CALLBACK` <add> <add><!-- YAML <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: End-of-Life. <add>--> <add> <add>Type: End-of-Life <add> <add>This error code was removed due to adding more confusion to <add>the errors used for value type validation. <add> <ide> [Legacy URL API]: url.md#legacy-url-api <ide> [NIST SP 800-38D]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf <ide> [RFC 6066]: https://tools.ietf.org/html/rfc6066#section-3 <ide><path>doc/api/dns.md <ide> section if a custom port is used. <ide> <!-- YAML <ide> added: v0.1.90 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v17.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/39987 <ide> description: The `verbatim` options defaults to `true` now. <ide> The following flags can be passed as hints to [`dns.lookup()`][]. <ide> <ide> <!-- YAML <ide> added: v0.11.14 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `address` {string} <ide> If this method is invoked as its [`util.promisify()`][]ed version, it returns a <ide> <ide> <!-- YAML <ide> added: v0.1.27 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `hostname` {string} Host name to resolve. <ide> On error, `err` is an [`Error`][] object, where `err.code` is one of the <ide> <!-- YAML <ide> added: v0.1.16 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v7.2.0 <ide> pr-url: https://github.com/nodejs/node/pull/9296 <ide> description: This method now supports passing `options`, <ide> will contain an array of IPv4 addresses (e.g. <ide> <!-- YAML <ide> added: v0.1.16 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v7.2.0 <ide> pr-url: https://github.com/nodejs/node/pull/9296 <ide> description: This method now supports passing `options`, <ide> will contain an array of IPv6 addresses. <ide> <ide> ## `dns.resolveAny(hostname, callback)` <ide> <add><!-- YAML <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <add>--> <add> <ide> * `hostname` {string} <ide> * `callback` {Function} <ide> * `err` {Error} <ide> queries. It may be better to call individual methods like [`dns.resolve4()`][], <ide> <ide> <!-- YAML <ide> added: v0.3.2 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `hostname` {string} <ide> will contain an array of canonical name records available for the `hostname` <ide> added: <ide> - v15.0.0 <ide> - v14.17.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `hostname` {string} <ide> available for the `hostname` (e.g. `[{critical: 0, iodef: <ide> <ide> <!-- YAML <ide> added: v0.1.27 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `hostname` {string} <ide> property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). <ide> <ide> <!-- YAML <ide> added: v0.9.12 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `hostname` {string} <ide> function will contain an array of objects with the following properties: <ide> <ide> <!-- YAML <ide> added: v0.1.90 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `hostname` {string} <ide> contain an array of name server records available for `hostname` <ide> <ide> <!-- YAML <ide> added: v6.0.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `hostname` {string} <ide> be an array of strings containing the reply records. <ide> <ide> <!-- YAML <ide> added: v0.11.10 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `hostname` {string} <ide> be an object with the following properties: <ide> <ide> <!-- YAML <ide> added: v0.1.27 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `hostname` {string} <ide> be an array of objects with the following properties: <ide> <ide> <!-- YAML <ide> added: v0.1.27 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> <!--lint disable no-undefined-references list-item-bullet-indent--> <ide><path>doc/api/errors.md <ide> less than -1 should never happen. <ide> A swap was performed on a `Buffer` but its size was not compatible with the <ide> operation. <ide> <del><a id="ERR_INVALID_CALLBACK"></a> <del> <del>### `ERR_INVALID_CALLBACK` <del> <del>A callback function was required but was not been provided to a Node.js API. <del> <ide> <a id="ERR_INVALID_CHAR"></a> <ide> <ide> ### `ERR_INVALID_CHAR` <ide><path>doc/api/fs.md <ide> concurrent modifications on the same file or data corruption may occur. <ide> <!-- YAML <ide> added: v0.11.15 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v7.6.0 <ide> pr-url: https://github.com/nodejs/node/pull/10739 <ide> description: The `path` parameter can be a WHATWG `URL` object using `file:` <ide> the user from reading or writing to it. <ide> <!-- YAML <ide> added: v0.6.7 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12562 <ide> description: The `callback` parameter is no longer optional. Not passing <ide> open('message.txt', 'a', (err, fd) => { <ide> <!-- YAML <ide> added: v0.1.30 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12562 <ide> description: The `callback` parameter is no longer optional. Not passing <ide> implemented. <ide> <!-- YAML <ide> added: v0.1.97 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12562 <ide> description: The `callback` parameter is no longer optional. Not passing <ide> See the POSIX chown(2) documentation for more detail. <ide> <!-- YAML <ide> added: v0.0.2 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: <ide> - v15.9.0 <ide> - v14.17.0 <ide> See the POSIX close(2) documentation for more detail. <ide> <!-- YAML <ide> added: v8.5.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v14.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/27044 <ide> description: Changed 'flags' argument to 'mode' and imposed <ide> copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); <ide> <ide> <!-- YAML <ide> added: v16.7.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> > Stability: 1 - Experimental <ide> If `options` is a string, then it specifies the encoding. <ide> added: v0.0.2 <ide> deprecated: v1.0.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v7.6.0 <ide> pr-url: https://github.com/nodejs/node/pull/10739 <ide> description: The `path` parameter can be a WHATWG `URL` object using <ide> process. <ide> <!-- YAML <ide> added: v0.4.7 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12562 <ide> description: The `callback` parameter is no longer optional. Not passing <ide> See the POSIX fchmod(2) documentation for more detail. <ide> <!-- YAML <ide> added: v0.4.7 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12562 <ide> description: The `callback` parameter is no longer optional. Not passing <ide> See the POSIX fchown(2) documentation for more detail. <ide> <!-- YAML <ide> added: v0.1.96 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12562 <ide> description: The `callback` parameter is no longer optional. Not passing <ide> exception are given to the completion callback. <ide> <!-- YAML <ide> added: v0.1.95 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.5.0 <ide> pr-url: https://github.com/nodejs/node/pull/20220 <ide> description: Accepts an additional `options` object to specify whether <ide> See the POSIX fstat(2) documentation for more detail. <ide> <!-- YAML <ide> added: v0.1.96 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12562 <ide> description: The `callback` parameter is no longer optional. Not passing <ide> than a possible exception are given to the completion callback. <ide> <!-- YAML <ide> added: v0.8.6 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12562 <ide> description: The `callback` parameter is no longer optional. Not passing <ide> If `len` is negative then `0` will be used. <ide> <!-- YAML <ide> added: v0.4.2 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12562 <ide> description: The `callback` parameter is no longer optional. Not passing <ide> descriptor. See [`fs.utimes()`][]. <ide> <!-- YAML <ide> deprecated: v0.4.7 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v16.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/37460 <ide> description: The error returned may be an `AggregateError` if more than one <ide> See the POSIX lchmod(2) documentation for more detail. <ide> <ide> <!-- YAML <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.6.0 <ide> pr-url: https://github.com/nodejs/node/pull/21498 <ide> description: This API is no longer deprecated. <ide> See the POSIX lchown(2) documentation for more detail. <ide> added: <ide> - v14.5.0 <ide> - v12.19.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `path` {string|Buffer|URL} <ide> callback. <ide> <!-- YAML <ide> added: v0.1.31 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12562 <ide> description: The `callback` parameter is no longer optional. Not passing <ide> exception are given to the completion callback. <ide> <!-- YAML <ide> added: v0.1.30 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.5.0 <ide> pr-url: https://github.com/nodejs/node/pull/20220 <ide> description: Accepts an additional `options` object to specify whether <ide> See the POSIX lstat(2) documentation for more details. <ide> <!-- YAML <ide> added: v0.1.8 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: <ide> - v13.11.0 <ide> - v12.17.0 <ide> See the POSIX mkdir(2) documentation for more details. <ide> <!-- YAML <ide> added: v5.10.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: <ide> - v16.5.0 <ide> - v14.18.0 <ide> mkdtemp(`${tmpDir}${sep}`, (err, directory) => { <ide> <!-- YAML <ide> added: v0.0.2 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v11.1.0 <ide> pr-url: https://github.com/nodejs/node/pull/23767 <ide> description: The `flags` argument is now optional and defaults to `'r'`. <ide> Functions based on `fs.open()` exhibit this behavior as well: <ide> <!-- YAML <ide> added: v12.12.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: <ide> - v13.1.0 <ide> - v12.16.0 <ide> directory and subsequent read operations. <ide> <!-- YAML <ide> added: v0.0.2 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.10.0 <ide> pr-url: https://github.com/nodejs/node/pull/22150 <ide> description: The `buffer` parameter can now be any `TypedArray`, or a <ide> above values. <ide> <!-- YAML <ide> added: v0.1.8 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.10.0 <ide> pr-url: https://github.com/nodejs/node/pull/22020 <ide> description: New option `withFileTypes` was added. <ide> If `options.withFileTypes` is set to `true`, the `files` array will contain <ide> <!-- YAML <ide> added: v0.1.29 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v16.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/37460 <ide> description: The error returned may be an `AggregateError` if more than one <ide> different Node.js versions. <ide> <!-- YAML <ide> added: v0.1.31 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12562 <ide> description: The `callback` parameter is no longer optional. Not passing <ide> the link path returned will be passed as a {Buffer} object. <ide> <ide> <!-- YAML <ide> added: <del> - v13.13.0 <del> - v12.17.0 <add> - v13.13.0 <add> - v12.17.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `fd` {integer} <ide> a promise for an `Object` with `bytesRead` and `buffers` properties. <ide> <!-- YAML <ide> added: v0.1.31 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12562 <ide> description: The `callback` parameter is no longer optional. Not passing <ide> dependent name for that object. <ide> <ide> <!-- YAML <ide> added: v9.2.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `path` {string|Buffer|URL} <ide> this restriction. <ide> <!-- YAML <ide> added: v0.0.2 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12562 <ide> description: The `callback` parameter is no longer optional. Not passing <ide> rename('oldFile.txt', 'newFile.txt', (err) => { <ide> <!-- YAML <ide> added: v0.0.2 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v16.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/37216 <ide> description: "Using `fs.rmdir(path, { recursive: true })` on a `path` that is <ide> completion callback. <ide> <!-- YAML <ide> added: v0.0.2 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.5.0 <ide> pr-url: https://github.com/nodejs/node/pull/20220 <ide> description: Accepts an additional `options` object to specify whether <ide> Stats { <ide> <!-- YAML <ide> added: v0.1.31 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v12.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/23724 <ide> description: If the `type` argument is left undefined, Node will autodetect <ide> $ tree . <ide> <!-- YAML <ide> added: v0.8.6 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v16.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/37460 <ide> description: The error returned may be an `AggregateError` if more than one <ide> See the POSIX truncate(2) documentation for more details. <ide> <!-- YAML <ide> added: v0.0.2 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12562 <ide> description: The `callback` parameter is no longer optional. Not passing <ide> and `fs.unwatchFile()` when possible. <ide> <!-- YAML <ide> added: v0.4.2 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v10.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12562 <ide> description: The `callback` parameter is no longer optional. Not passing <ide> This happens when: <ide> <!-- YAML <ide> added: v0.0.2 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v14.12.0 <ide> pr-url: https://github.com/nodejs/node/pull/34993 <ide> description: The `buffer` parameter will stringify an object with an <ide> details. <ide> <!-- YAML <ide> added: v0.1.29 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v16.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/37460 <ide> description: The error returned may be an `AggregateError` if more than one <ide> to contain only `', World'`. <ide> <ide> <!-- YAML <ide> added: v12.9.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `fd` {integer} <ide> closed. <ide> <ide> <!-- YAML <ide> added: v12.12.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `callback` {Function} <ide><path>doc/api/http2.md <ide> frames have been acknowledged. <ide> <ide> <!-- YAML <ide> added: v8.9.3 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `payload` {Buffer|TypedArray|DataView} Optional ping payload. <ide> server.on('connect', (session) => { <ide> <ide> <!-- YAML <ide> added: v8.4.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `msecs` {number} <ide> An object describing the current status of this `Http2Session`. <ide> <ide> <!-- YAML <ide> added: v8.4.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `settings` {HTTP/2 Settings Object} <ide> See [`net.Socket.bufferSize`][] for details. <ide> <ide> <!-- YAML <ide> added: v8.4.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `code` {number} Unsigned 32-bit integer identifying the error code. <ide> value will be `undefined` after the `Http2Stream` instance is destroyed. <ide> <ide> <!-- YAML <ide> added: v8.4.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `msecs` {number} <ide> accepts push streams, `false` otherwise. Settings are the same for every <ide> <ide> <!-- YAML <ide> added: v8.4.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `headers` {HTTP/2 Headers Object} <ide> closed, although the server has already stopped allowing new sessions. See <ide> <!-- YAML <ide> added: v8.4.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v13.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/27558 <ide> description: The default timeout changed from 120s to 0 (no timeout). <ide> on the `Http2Server` after `msecs` milliseconds. <ide> <ide> The given callback is registered as a listener on the `'timeout'` event. <ide> <del>In case if `callback` is not a function, a new `ERR_INVALID_CALLBACK` <add>In case if `callback` is not a function, a new `ERR_INVALID_ARG_TYPE` <ide> error will be thrown. <ide> <ide> #### `server.timeout` <ide> closed, although the server has already stopped allowing new sessions. See <ide> <ide> <!-- YAML <ide> added: v8.4.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `msecs` {number} **Default:** `120000` (2 minutes) <ide> on the `Http2SecureServer` after `msecs` milliseconds. <ide> <ide> The given callback is registered as a listener on the `'timeout'` event. <ide> <del>In case if `callback` is not a function, a new `ERR_INVALID_CALLBACK` <add>In case if `callback` is not a function, a new `ERR_INVALID_ARG_TYPE` <ide> error will be thrown. <ide> <ide> #### `server.timeout` <ide> See [`response.socket`][]. <ide> <ide> <!-- YAML <ide> added: v8.4.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `headers` {HTTP/2 Headers Object} An object describing the headers <ide><path>doc/api/inspector.md <ide> enabled agents or configured breakpoints. <ide> <ide> <!-- YAML <ide> added: v8.0.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `method` {string} <ide><path>doc/api/net.md <ide> algorithm. <ide> <ide> <!-- YAML <ide> added: v0.1.90 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `timeout` {number} <ide><path>doc/api/perf_hooks.md <ide> initialized. <ide> <ide> <!-- YAML <ide> added: v8.5.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `callback` {Function} <ide><path>doc/api/process.md <ide> console.log(memoryUsage.rss()); <ide> <!-- YAML <ide> added: v0.1.26 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v1.8.1 <ide> pr-url: https://github.com/nodejs/node/pull/1077 <ide> description: Additional arguments after `callback` are now supported. <ide><path>doc/api/readline.md <ide> questionExample(); <ide> <!-- YAML <ide> added: v0.7.7 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v12.7.0 <ide> pr-url: https://github.com/nodejs/node/pull/28674 <ide> description: The stream's write() callback and return value are exposed. <ide> in a specified direction identified by `dir`. <ide> <!-- YAML <ide> added: v0.7.7 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v12.7.0 <ide> pr-url: https://github.com/nodejs/node/pull/28641 <ide> description: The stream's write() callback and return value are exposed. <ide> function completer(linePartial, callback) { <ide> <!-- YAML <ide> added: v0.7.7 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v12.7.0 <ide> pr-url: https://github.com/nodejs/node/pull/28674 <ide> description: The stream's write() callback and return value are exposed. <ide> given [TTY][] `stream`. <ide> <!-- YAML <ide> added: v0.7.7 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v12.7.0 <ide> pr-url: https://github.com/nodejs/node/pull/28674 <ide> description: The stream's write() callback and return value are exposed. <ide><path>doc/api/stream.md <ide> const cleanup = finished(rs, (err) => { <ide> <!-- YAML <ide> added: v10.0.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> - version: v14.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/32158 <ide> description: The `pipeline(..., cb)` will wait for the `'close'` event <ide><path>doc/api/timers.md <ide> event loop is doing. <ide> <ide> <!-- YAML <ide> added: v0.9.1 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `callback` {Function} The function to call at the end of this turn of <ide> This method has a custom variant for promises that is available using <ide> <ide> <!-- YAML <ide> added: v0.0.1 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `callback` {Function} The function to call when the timer elapses. <ide> This method has a custom variant for promises that is available using <ide> <ide> <!-- YAML <ide> added: v0.0.1 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `callback` {Function} The function to call when the timer elapses. <ide><path>doc/api/tls.md <ide> Returns the numeric representation of the remote port. For example, `443`. <ide> <ide> <!-- YAML <ide> added: v0.11.8 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `callback` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <ide> --> <ide> <ide> * `options` {Object} <ide><path>doc/api/url.md <ide> Alias for [`urlSearchParams[iterator()`]. <ide> <ide> #### `urlSearchParams.forEach(fn[, thisArg])` <ide> <add><!-- YAML <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41678 <add> description: Passing an invalid callback to the `fn` argument <add> now throws `ERR_INVALID_ARG_TYPE` instead of <add> `ERR_INVALID_CALLBACK`. <add>--> <add> <ide> * `fn` {Function} Invoked for each name-value pair in the query <ide> * `thisArg` {Object} To be used as `this` value for when `fn` is called <ide> <ide><path>lib/_tls_wrap.js <ide> const { <ide> const { <ide> validateBoolean, <ide> validateBuffer, <del> validateCallback, <ide> validateFunction, <ide> validateInt32, <ide> validateNumber, <ide> TLSSocket.prototype._init = function(socket, wrap) { <ide> TLSSocket.prototype.renegotiate = function(options, callback) { <ide> validateObject(options, 'options'); <ide> if (callback !== undefined) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> } <ide> <ide> debug('%s renegotiate()', <ide><path>lib/dns.js <ide> const { <ide> ERR_MISSING_ARGS, <ide> } = errors.codes; <ide> const { <del> validateCallback, <add> validateFunction, <ide> validatePort, <ide> validateString, <ide> validateOneOf, <ide> function lookup(hostname, options, callback) { <ide> callback = options; <ide> family = 0; <ide> } else { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> if (options !== null && typeof options === 'object') { <ide> if (options.hints != null && typeof options.hints !== 'number') { <ide> function lookupService(address, port, callback) { <ide> <ide> validatePort(port); <ide> <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> port = +port; <ide> <ide> function resolver(bindingName) { <ide> } <ide> <ide> validateString(name, 'name'); <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> const req = new QueryReqWrap(); <ide> req.bindingName = bindingName; <ide><path>lib/fs.js <ide> const { <ide> parseFileMode, <ide> validateBoolean, <ide> validateBuffer, <del> validateCallback, <ide> validateEncoding, <ide> validateFunction, <ide> validateInteger, <ide> function showTruncateDeprecation() { <ide> } <ide> <ide> function maybeCallback(cb) { <del> validateCallback(cb); <add> validateFunction(cb, 'cb'); <ide> <ide> return cb; <ide> } <ide> function maybeCallback(cb) { <ide> // for callbacks that are passed to the binding layer, callbacks that are <ide> // invoked from JS already run in the proper scope. <ide> function makeCallback(cb) { <del> validateCallback(cb); <add> validateFunction(cb, 'cb'); <ide> <ide> return (...args) => ReflectApply(cb, this, args); <ide> } <ide> function makeCallback(cb) { <ide> // an optimization, since the data passed back to the callback needs to be <ide> // transformed anyway. <ide> function makeStatsCallback(cb) { <del> validateCallback(cb); <add> validateFunction(cb, 'cb'); <ide> <ide> return (err, stats) => { <ide> if (err) return cb(err); <ide><path>lib/inspector.js <ide> if (!hasInspector) <ide> const EventEmitter = require('events'); <ide> const { queueMicrotask } = require('internal/process/task_queues'); <ide> const { <del> validateCallback, <add> validateFunction, <ide> validateObject, <ide> validateString, <ide> } = require('internal/validators'); <ide> class Session extends EventEmitter { <ide> validateObject(params, 'params'); <ide> } <ide> if (callback) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> } <ide> <ide> if (!this[connectionSymbol]) { <ide><path>lib/internal/crypto/diffiehellman.js <ide> const { <ide> } = require('internal/errors'); <ide> <ide> const { <del> validateCallback, <add> validateFunction, <ide> validateInt32, <ide> validateObject, <ide> validateString, <ide> function deriveBitsECDH(name, publicKey, privateKey, callback) { <ide> validateString(name, 'name'); <ide> validateObject(publicKey, 'publicKey'); <ide> validateObject(privateKey, 'privateKey'); <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> const job = new ECDHBitsJob(kCryptoJobAsync, name, publicKey, privateKey); <ide> job.ondone = (error, bits) => { <ide> if (error) return FunctionPrototypeCall(callback, job, error); <ide> function deriveBitsECDH(name, publicKey, privateKey, callback) { <ide> function deriveBitsDH(publicKey, privateKey, callback) { <ide> validateObject(publicKey, 'publicKey'); <ide> validateObject(privateKey, 'privateKey'); <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> const job = new DHBitsJob(kCryptoJobAsync, publicKey, privateKey); <ide> job.ondone = (error, bits) => { <ide> if (error) return FunctionPrototypeCall(callback, job, error); <ide><path>lib/internal/crypto/hkdf.js <ide> const { <ide> } = internalBinding('crypto'); <ide> <ide> const { <del> validateCallback, <add> validateFunction, <ide> validateInteger, <ide> validateString, <ide> validateUint32, <ide> function hkdf(hash, key, salt, info, length, callback) { <ide> length, <ide> } = validateParameters(hash, key, salt, info, length)); <ide> <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> const job = new HKDFJob(kCryptoJobAsync, hash, key, salt, info, length); <ide> <ide><path>lib/internal/crypto/keygen.js <ide> const { customPromisifyArgs } = require('internal/util'); <ide> const { <ide> isInt32, <ide> isUint32, <del> validateCallback, <add> validateFunction, <ide> validateString, <ide> validateInteger, <ide> validateObject, <ide> function generateKeyPair(type, options, callback) { <ide> callback = options; <ide> options = undefined; <ide> } <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> const job = createJob(kCryptoJobAsync, type, options); <ide> <ide> function generateKey(type, options, callback) { <ide> options = undefined; <ide> } <ide> <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> const job = generateKeyJob(kCryptoJobAsync, type, options); <ide> <ide><path>lib/internal/crypto/pbkdf2.js <ide> const { <ide> } = internalBinding('crypto'); <ide> <ide> const { <del> validateCallback, <add> validateFunction, <ide> validateInteger, <ide> validateString, <ide> validateUint32, <ide> function pbkdf2(password, salt, iterations, keylen, digest, callback) { <ide> ({ password, salt, iterations, keylen, digest } = <ide> check(password, salt, iterations, keylen, digest)); <ide> <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> const job = new PBKDF2Job( <ide> kCryptoJobAsync, <ide><path>lib/internal/crypto/random.js <ide> const { <ide> const { <ide> validateNumber, <ide> validateBoolean, <del> validateCallback, <add> validateFunction, <ide> validateObject, <ide> validateUint32, <ide> } = require('internal/validators'); <ide> function assertSize(size, elementSize, offset, length) { <ide> function randomBytes(size, callback) { <ide> size = assertSize(size, 1, 0, Infinity); <ide> if (callback !== undefined) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> } <ide> <ide> const buf = new FastBuffer(size); <ide> function randomFill(buf, offset, size, callback) { <ide> callback = size; <ide> size = buf.length - offset; <ide> } else { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> } <ide> <ide> offset = assertOffset(offset, elementSize, buf.byteLength); <ide> function randomInt(min, max, callback) { <ide> <ide> const isSync = typeof callback === 'undefined'; <ide> if (!isSync) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> } <ide> if (!NumberIsSafeInteger(min)) { <ide> throw new ERR_INVALID_ARG_TYPE('min', 'a safe integer', min); <ide> function generatePrime(size, options, callback) { <ide> callback = options; <ide> options = {}; <ide> } <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> const job = createRandomPrimeJob(kCryptoJobAsync, size, options); <ide> job.ondone = (err, prime) => { <ide> function checkPrime(candidate, options = {}, callback) { <ide> callback = options; <ide> options = {}; <ide> } <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> validateObject(options, 'options'); <ide> const { <ide> checks = 0, <ide><path>lib/internal/crypto/scrypt.js <ide> const { <ide> } = internalBinding('crypto'); <ide> <ide> const { <del> validateCallback, <add> validateFunction, <ide> validateInteger, <ide> validateInt32, <ide> validateUint32, <ide> function scrypt(password, salt, keylen, options, callback = defaults) { <ide> const { N, r, p, maxmem } = options; <ide> ({ password, salt, keylen } = options); <ide> <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> const job = new ScryptJob( <ide> kCryptoJobAsync, password, salt, N, r, p, maxmem, keylen); <ide><path>lib/internal/crypto/sig.js <ide> const { <ide> } = require('internal/errors'); <ide> <ide> const { <del> validateCallback, <add> validateFunction, <ide> validateEncoding, <ide> validateString, <ide> } = require('internal/validators'); <ide> function signOneShot(algorithm, data, key, callback) { <ide> validateString(algorithm, 'algorithm'); <ide> <ide> if (callback !== undefined) <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> data = getArrayBufferOrView(data, 'data'); <ide> <ide> function verifyOneShot(algorithm, data, key, signature, callback) { <ide> validateString(algorithm, 'algorithm'); <ide> <ide> if (callback !== undefined) <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> data = getArrayBufferOrView(data, 'data'); <ide> <ide><path>lib/internal/errors.js <ide> E('ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => { <ide> E('ERR_INVALID_ASYNC_ID', 'Invalid %s value: %s', RangeError); <ide> E('ERR_INVALID_BUFFER_SIZE', <ide> 'Buffer size must be a multiple of %s', RangeError); <del>E('ERR_INVALID_CALLBACK', <del> 'Callback must be a function. Received %O', TypeError); <ide> E('ERR_INVALID_CHAR', <ide> // Using a default argument here is important so the argument is not counted <ide> // towards `Function#length`. <ide><path>lib/internal/fs/dir.js <ide> const { <ide> handleErrorFromBinding <ide> } = require('internal/fs/utils'); <ide> const { <del> validateCallback, <add> validateFunction, <ide> validateUint32 <ide> } = require('internal/validators'); <ide> <ide> class Dir { <ide> return this[kDirReadPromisified](); <ide> } <ide> <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> if (this[kDirOperationQueue] !== null) { <ide> ArrayPrototypePush(this[kDirOperationQueue], () => { <ide> class Dir { <ide> } <ide> <ide> // callback <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> if (this[kDirClosed] === true) { <ide> process.nextTick(callback, new ERR_DIR_CLOSED()); <ide> ObjectDefineProperty(Dir.prototype, SymbolAsyncIterator, { <ide> <ide> function opendir(path, options, callback) { <ide> callback = typeof options === 'function' ? options : callback; <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> path = getValidatedPath(path); <ide> options = getOptions(options, { <ide><path>lib/internal/http2/compat.js <ide> const { <ide> hideStackFrames <ide> } = require('internal/errors'); <ide> const { <del> validateCallback, <add> validateFunction, <ide> validateString, <ide> } = require('internal/validators'); <ide> const { <ide> class Http2ServerResponse extends Stream { <ide> } <ide> <ide> createPushResponse(headers, callback) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> if (this[kState].closed) { <ide> process.nextTick(callback, new ERR_HTTP2_INVALID_STREAM()); <ide> return; <ide><path>lib/internal/http2/core.js <ide> const { <ide> } = require('internal/errors'); <ide> const { <ide> isUint32, <del> validateCallback, <add> validateFunction, <ide> validateInt32, <ide> validateInteger, <ide> validateNumber, <ide> class Http2Session extends EventEmitter { <ide> if (payload && payload.length !== 8) { <ide> throw new ERR_HTTP2_PING_LENGTH(); <ide> } <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> const cb = pingCallback(callback); <ide> if (this.connecting || this.closed) { <ide> class Http2Session extends EventEmitter { <ide> validateSettings(settings); <ide> <ide> if (callback) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> } <ide> debugSessionObj(this, 'sending settings'); <ide> <ide> class Http2Stream extends Duplex { <ide> validateInteger(code, 'code', 0, kMaxInt); <ide> <ide> if (callback !== undefined) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> } <ide> <ide> if (this.closed) <ide> class ServerHttp2Stream extends Http2Stream { <ide> options = undefined; <ide> } <ide> <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> assertIsObject(options, 'options'); <ide> options = { ...options }; <ide> class Http2SecureServer extends TLSServer { <ide> setTimeout(msecs, callback) { <ide> this.timeout = msecs; <ide> if (callback !== undefined) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> this.on('timeout', callback); <ide> } <ide> return this; <ide> class Http2Server extends NETServer { <ide> setTimeout(msecs, callback) { <ide> this.timeout = msecs; <ide> if (callback !== undefined) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> this.on('timeout', callback); <ide> } <ide> return this; <ide><path>lib/internal/perf/observe.js <ide> const { <ide> } = require('internal/errors'); <ide> <ide> const { <del> validateCallback, <add> validateFunction, <ide> validateObject, <ide> } = require('internal/validators'); <ide> <ide> class PerformanceObserver { <ide> this[kBuffer] = []; <ide> this[kEntryTypes] = new SafeSet(); <ide> this[kType] = undefined; <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> this[kCallback] = callback; <ide> } <ide> <ide><path>lib/internal/process/task_queues.js <ide> const { <ide> const FixedQueue = require('internal/fixed_queue'); <ide> <ide> const { <del> validateCallback, <ide> validateFunction, <ide> } = require('internal/validators'); <ide> <ide> function processTicksAndRejections() { <ide> // `nextTick()` will not enqueue any callback when the process is about to <ide> // exit since the callback would not have a chance to be executed. <ide> function nextTick(callback) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> if (process._exiting) <ide> return; <ide><path>lib/internal/readline/callbacks.js <ide> const { <ide> } = require('internal/errors'); <ide> <ide> const { <del> validateCallback, <add> validateFunction, <ide> } = require('internal/validators'); <ide> const { <ide> CSI, <ide> const { <ide> <ide> function cursorTo(stream, x, y, callback) { <ide> if (callback !== undefined) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> } <ide> <ide> if (typeof y === 'function') { <ide> function cursorTo(stream, x, y, callback) { <ide> <ide> function moveCursor(stream, dx, dy, callback) { <ide> if (callback !== undefined) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> } <ide> <ide> if (stream == null || !(dx || dy)) { <ide> function moveCursor(stream, dx, dy, callback) { <ide> <ide> function clearLine(stream, dir, callback) { <ide> if (callback !== undefined) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> } <ide> <ide> if (stream === null || stream === undefined) { <ide> function clearLine(stream, dir, callback) { <ide> <ide> function clearScreenDown(stream, callback) { <ide> if (callback !== undefined) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> } <ide> <ide> if (stream === null || stream === undefined) { <ide><path>lib/internal/stream_base_commons.js <ide> const { <ide> } = require('internal/timers'); <ide> const { isUint8Array } = require('internal/util/types'); <ide> const { clearTimeout } = require('timers'); <del>const { validateCallback } = require('internal/validators'); <add>const { validateFunction } = require('internal/validators'); <ide> <ide> const kMaybeDestroy = Symbol('kMaybeDestroy'); <ide> const kUpdateTimer = Symbol('kUpdateTimer'); <ide> function setStreamTimeout(msecs, callback) { <ide> <ide> if (msecs === 0) { <ide> if (callback !== undefined) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> this.removeListener('timeout', callback); <ide> } <ide> } else { <ide> this[kTimeout] = setUnrefTimeout(this._onTimeout.bind(this), msecs); <ide> if (this[kSession]) this[kSession][kUpdateTimer](); <ide> <ide> if (callback !== undefined) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> this.once('timeout', callback); <ide> } <ide> } <ide><path>lib/internal/streams/pipeline.js <ide> const { <ide> } = require('internal/errors'); <ide> <ide> const { <del> validateCallback, <add> validateFunction, <ide> validateAbortSignal <ide> } = require('internal/validators'); <ide> <ide> function popCallback(streams) { <ide> // Streams should never be an empty array. It should always contain at least <ide> // a single stream. Therefore optimize for the average case instead of <ide> // checking for length === 0 as well. <del> validateCallback(streams[streams.length - 1]); <add> validateFunction(streams[streams.length - 1], 'streams[stream.length - 1]'); <ide> return streams.pop(); <ide> } <ide> <ide><path>lib/internal/timers.js <ide> const { <ide> ERR_OUT_OF_RANGE <ide> } = require('internal/errors').codes; <ide> const { <del> validateCallback, <add> validateFunction, <ide> validateNumber, <ide> } = require('internal/validators'); <ide> <ide> function insert(item, msecs, start = getLibuvNow()) { <ide> <ide> function setUnrefTimeout(callback, after) { <ide> // Type checking identical to setTimeout() <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> const timer = new Timeout(callback, after, undefined, false, false); <ide> insert(timer, timer._idleTimeout); <ide><path>lib/internal/url.js <ide> const { <ide> const path = require('path'); <ide> <ide> const { <del> validateCallback, <add> validateFunction, <ide> validateObject, <ide> } = require('internal/validators'); <ide> <ide> class URLSearchParams { <ide> if (!isURLSearchParams(this)) <ide> throw new ERR_INVALID_THIS('URLSearchParams'); <ide> <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> let list = this[searchParams]; <ide> <ide><path>lib/internal/validators.js <ide> const { <ide> ERR_INVALID_ARG_VALUE, <ide> ERR_OUT_OF_RANGE, <ide> ERR_UNKNOWN_SIGNAL, <del> ERR_INVALID_CALLBACK, <ide> } <ide> } = require('internal/errors'); <ide> const { normalizeEncoding } = require('internal/util'); <ide> function validatePort(port, name = 'Port', allowZero = true) { <ide> return port | 0; <ide> } <ide> <del>const validateCallback = hideStackFrames((callback) => { <del> if (typeof callback !== 'function') <del> throw new ERR_INVALID_CALLBACK(callback); <del>}); <del> <ide> const validateAbortSignal = hideStackFrames((signal, name) => { <ide> if (signal !== undefined && <ide> (signal === null || <ide> module.exports = { <ide> validateString, <ide> validateUint32, <ide> validateUndefined, <del> validateCallback, <ide> validateAbortSignal, <ide> }; <ide><path>lib/timers.js <ide> const { <ide> let debug = require('internal/util/debuglog').debuglog('timer', (fn) => { <ide> debug = fn; <ide> }); <del>const { validateCallback } = require('internal/validators'); <add>const { validateFunction } = require('internal/validators'); <ide> <ide> let timersPromises; <ide> <ide> function enroll(item, msecs) { <ide> * @returns {Timeout} <ide> */ <ide> function setTimeout(callback, after, arg1, arg2, arg3) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> let i, args; <ide> switch (arguments.length) { <ide> function clearTimeout(timer) { <ide> * @returns {Timeout} <ide> */ <ide> function setInterval(callback, repeat, arg1, arg2, arg3) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> let i, args; <ide> switch (arguments.length) { <ide> Timeout.prototype[SymbolToPrimitive] = function() { <ide> * @returns {Immediate} <ide> */ <ide> function setImmediate(callback, arg1, arg2, arg3) { <del> validateCallback(callback); <add> validateFunction(callback, 'callback'); <ide> <ide> let i, args; <ide> switch (arguments.length) { <ide><path>test/parallel/test-crypto-keygen.js <ide> const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher); <ide> privateKeyEncoding: { type: 'pkcs1', format: 'pem' } <ide> }, cb), { <ide> name: 'TypeError', <del> code: 'ERR_INVALID_CALLBACK' <add> code: 'ERR_INVALID_ARG_TYPE' <ide> }); <ide> } <ide> } <ide> const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher); <ide> }, <ide> { <ide> name: 'TypeError', <del> code: 'ERR_INVALID_CALLBACK', <del> message: 'Callback must be a function. Received undefined' <add> code: 'ERR_INVALID_ARG_TYPE', <ide> } <ide> ); <ide> <ide><path>test/parallel/test-crypto-pbkdf2.js <ide> testPBKDF2('password', 'salt', 32, 32, <ide> assert.throws( <ide> () => crypto.pbkdf2('password', 'salt', 1, 20, 'sha1'), <ide> { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> } <ide> ); <ide><path>test/parallel/test-crypto-prime.js <ide> const pCheckPrime = promisify(checkPrime); <ide> <ide> ['hello', false, 123].forEach((i) => { <ide> assert.throws(() => generatePrime(80, {}), { <del> code: 'ERR_INVALID_CALLBACK' <add> code: 'ERR_INVALID_ARG_TYPE' <ide> }); <ide> }); <ide> <ide><path>test/parallel/test-crypto-random.js <ide> const assert = require('assert'); <ide> const crypto = require('crypto'); <ide> const cryptop = require('crypto').webcrypto; <ide> const { kMaxLength } = require('buffer'); <del>const { inspect } = require('util'); <ide> <ide> const kMaxInt32 = 2 ** 31 - 1; <ide> const kMaxPossibleLength = Math.min(kMaxLength, kMaxInt32); <ide> assert.throws( <ide> assert.throws( <ide> () => crypto.randomFill(buf, 0, 10, i), <ide> { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError', <del> message: `Callback must be a function. Received ${inspect(i)}` <ide> }); <ide> }); <ide> <ide> [1, true, NaN, null, {}, []].forEach((i) => { <ide> assert.throws( <ide> () => crypto.randomBytes(1, i), <ide> { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError', <del> message: `Callback must be a function. Received ${inspect(i)}` <ide> } <ide> ); <ide> }); <ide> assert.throws( <ide> <ide> [true, NaN, null, {}, [], 10].forEach((i) => { <ide> const cbError = { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError', <del> message: `Callback must be a function. Received ${inspect(i)}` <ide> }; <ide> assert.throws(() => crypto.randomInt(0, 1, i), cbError); <ide> }); <ide><path>test/parallel/test-crypto-scrypt.js <ide> for (const { args, expected } of badargs) { <ide> } <ide> <ide> { <del> const expected = { code: 'ERR_INVALID_CALLBACK' }; <add> const expected = { code: 'ERR_INVALID_ARG_TYPE' }; <ide> assert.throws(() => crypto.scrypt('', '', 42, null), expected); <ide> assert.throws(() => crypto.scrypt('', '', 42, {}, null), expected); <ide> assert.throws(() => crypto.scrypt('', '', 42, {}), expected); <ide><path>test/parallel/test-crypto-secret-keygen.js <ide> const { <ide> }); <ide> <ide> assert.throws(() => generateKey('aes', { length: 256 }), { <del> code: 'ERR_INVALID_CALLBACK' <add> code: 'ERR_INVALID_ARG_TYPE' <ide> }); <ide> <ide> assert.throws(() => generateKey('hmac', { length: -1 }, common.mustNotCall()), { <ide><path>test/parallel/test-dns-lookup.js <ide> common.expectWarning({ <ide> assert.throws(() => { <ide> dns.lookup(false, 'cb'); <ide> }, { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> }); <ide> <ide> assert.throws(() => { <ide> dns.lookup(false, 'options', 'cb'); <ide> }, { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> }); <ide> <ide><path>test/parallel/test-dns-resolvens-typeerror.js <ide> assert.throws( <ide> assert.throws( <ide> () => dns.resolveNs(''), // bad callback <ide> { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> } <ide> ); <ide><path>test/parallel/test-dns.js <ide> assert.deepStrictEqual(dns.getServers(), []); <ide> } <ide> <ide> assert.throws(() => dns.lookup('nodejs.org'), { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> }); <ide> <ide> assert.throws(() => dns.lookup('nodejs.org', 4), { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> }); <ide> <ide> portErr('test'); <ide> assert.throws(() => { <ide> dns.lookupService('0.0.0.0', 80, null); <ide> }, { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> }); <ide> <ide><path>test/parallel/test-fs-access.js <ide> assert.throws( <ide> fs.access(__filename, fs.F_OK); <ide> }, <ide> { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> }); <ide> <ide> assert.throws( <ide> fs.access(__filename, fs.F_OK, {}); <ide> }, <ide> { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> }); <ide> <ide><path>test/parallel/test-fs-append-file.js <ide> const throwNextTick = (e) => { process.nextTick(() => { throw e; }); }; <ide> <ide> assert.throws( <ide> () => fs.appendFile(join(tmpdir.path, 'append6.txt'), console.log), <del> { code: 'ERR_INVALID_CALLBACK' }); <add> { code: 'ERR_INVALID_ARG_TYPE' }); <ide><path>test/parallel/test-fs-close-errors.js <ide> const fs = require('fs'); <ide> const fd = fs.openSync(__filename, 'r'); <ide> <ide> const errObj = { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> }; <ide> <ide><path>test/parallel/test-fs-copyfile.js <ide> fs.copyFile(src, dest, common.mustSucceed(() => { <ide> assert.throws(() => { <ide> fs.copyFile(src, dest, 0, 0); <ide> }, { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> }); <ide> <ide><path>test/parallel/test-fs-exists.js <ide> const assert = require('assert'); <ide> const fs = require('fs'); <ide> const f = __filename; <ide> <del>assert.throws(() => fs.exists(f), { code: 'ERR_INVALID_CALLBACK' }); <del>assert.throws(() => fs.exists(), { code: 'ERR_INVALID_CALLBACK' }); <del>assert.throws(() => fs.exists(f, {}), { code: 'ERR_INVALID_CALLBACK' }); <add>assert.throws(() => fs.exists(f), { code: 'ERR_INVALID_ARG_TYPE' }); <add>assert.throws(() => fs.exists(), { code: 'ERR_INVALID_ARG_TYPE' }); <add>assert.throws(() => fs.exists(f, {}), { code: 'ERR_INVALID_ARG_TYPE' }); <ide> <ide> fs.exists(f, common.mustCall(function(y) { <ide> assert.strictEqual(y, true); <ide><path>test/parallel/test-fs-lchmod.js <ide> if (!common.isOSX) { <ide> } <ide> <ide> // Check callback <del>assert.throws(() => fs.lchmod(f), { code: 'ERR_INVALID_CALLBACK' }); <del>assert.throws(() => fs.lchmod(), { code: 'ERR_INVALID_CALLBACK' }); <del>assert.throws(() => fs.lchmod(f, {}), { code: 'ERR_INVALID_CALLBACK' }); <add>assert.throws(() => fs.lchmod(f), { code: 'ERR_INVALID_ARG_TYPE' }); <add>assert.throws(() => fs.lchmod(), { code: 'ERR_INVALID_ARG_TYPE' }); <add>assert.throws(() => fs.lchmod(f, {}), { code: 'ERR_INVALID_ARG_TYPE' }); <ide> <ide> // Check path <ide> [false, 1, {}, [], null, undefined].forEach((i) => { <ide><path>test/parallel/test-fs-lchown.js <ide> const { promises } = fs; <ide> [false, 1, 'test', {}, [], null, undefined].forEach((i) => { <ide> assert.throws(() => fs.lchown('not_a_file_that_exists', 1, 1, i), { <ide> name: 'TypeError', <del> code: 'ERR_INVALID_CALLBACK' <add> code: 'ERR_INVALID_ARG_TYPE' <ide> }); <ide> }); <ide> <ide><path>test/parallel/test-fs-make-callback.js <ide> function testMakeCallback(cb) { <ide> function invalidCallbackThrowsTests() { <ide> callbackThrowValues.forEach((value) => { <ide> assert.throws(testMakeCallback(value), { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> }); <ide> }); <ide><path>test/parallel/test-fs-makeStatsCallback.js <ide> testMakeStatsCallback(common.mustCall())(); <ide> function invalidCallbackThrowsTests() { <ide> callbackThrowValues.forEach((value) => { <ide> assert.throws(testMakeStatsCallback(value), { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> }); <ide> }); <ide><path>test/parallel/test-fs-open.js <ide> for (const extra of [[], ['r'], ['r', 0], ['r', 0, 'bad callback']]) { <ide> assert.throws( <ide> () => fs.open(__filename, ...extra), <ide> { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> } <ide> ); <ide><path>test/parallel/test-fs-opendir.js <ide> const dirconcurrentError = { <ide> }; <ide> <ide> const invalidCallbackObj = { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> }; <ide> <ide> assert.throws(function() { <ide> <ide> assert.throws(function() { <ide> fs.opendir(__filename); <del>}, /TypeError \[ERR_INVALID_CALLBACK\]: Callback must be a function/); <add>}, /TypeError \[ERR_INVALID_ARG_TYPE\]: The "callback" argument must be of type function/); <ide> <ide> fs.opendir(__filename, common.mustCall(function(e) { <ide> assert.strictEqual(e.code, 'ENOTDIR'); <ide> doConcurrentAsyncAndSyncOps().then(common.mustCall()); <ide> // Check read throw exceptions on invalid callback <ide> { <ide> const dir = fs.opendirSync(testDir); <del> assert.throws(() => dir.read('INVALID_CALLBACK'), /ERR_INVALID_CALLBACK/); <add> assert.throws(() => dir.read('INVALID_CALLBACK'), /ERR_INVALID_ARG_TYPE/); <ide> } <ide> <ide> // Check that concurrent read() operations don't do weird things. <ide><path>test/parallel/test-fs-read.js <ide> assert.throws(() => new fs.Dir(), { <ide> assert.throws( <ide> () => fs.read(fd, Buffer.alloc(1), 0, 1, 0), <ide> { <del> message: 'Callback must be a function. Received undefined', <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> } <ide> ); <ide> <ide><path>test/parallel/test-http2-client-rststream-before-connect.js <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <ide> const assert = require('assert'); <ide> const h2 = require('http2'); <del>const { inspect } = require('util'); <ide> <ide> const server = h2.createServer(); <ide> server.on('stream', (stream) => { <ide> server.listen(0, common.mustCall(() => { <ide> () => req.close(closeCode, notFunction), <ide> { <ide> name: 'TypeError', <del> code: 'ERR_INVALID_CALLBACK', <del> message: `Callback must be a function. Received ${inspect(notFunction)}` <add> code: 'ERR_INVALID_ARG_TYPE', <ide> } <ide> ); <ide> assert.strictEqual(req.closed, false); <ide><path>test/parallel/test-http2-client-settings-before-connect.js <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <ide> const assert = require('assert'); <ide> const h2 = require('http2'); <del>const { inspect } = require('util'); <ide> <ide> const server = h2.createServer(); <ide> <ide> server.listen(0, common.mustCall(() => { <ide> () => client.settings({}, invalidCallback), <ide> { <ide> name: 'TypeError', <del> code: 'ERR_INVALID_CALLBACK', <del> message: <del> `Callback must be a function. Received ${inspect(invalidCallback)}` <add> code: 'ERR_INVALID_ARG_TYPE', <ide> } <ide> ) <ide> ); <ide><path>test/parallel/test-http2-compat-serverresponse-createpushresponse.js <ide> const server = h2.createServer((request, response) => { <ide> ':method': 'GET' <ide> }, undefined), <ide> { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError', <del> message: 'Callback must be a function. Received undefined' <ide> } <ide> ); <ide> <ide><path>test/parallel/test-http2-ping.js <ide> if (!common.hasCrypto) <ide> const async_hooks = require('async_hooks'); <ide> const assert = require('assert'); <ide> const http2 = require('http2'); <del>const { inspect } = require('util'); <ide> <ide> const pings = new Set(); <ide> const events = [0, 0, 0, 0]; <ide> server.listen(0, common.mustCall(() => { <ide> () => client.ping(payload, invalidCallback), <ide> { <ide> name: 'TypeError', <del> code: 'ERR_INVALID_CALLBACK', <del> message: 'Callback must be a function. ' + <del> `Received ${inspect(invalidCallback)}` <add> code: 'ERR_INVALID_ARG_TYPE', <ide> } <ide> ) <ide> ); <ide><path>test/parallel/test-http2-server-push-stream-errors-args.js <ide> server.on('stream', common.mustCall((stream, headers) => { <ide> ':authority': `localhost:${port}`, <ide> }, {}, 'callback'), <ide> { <del> code: 'ERR_INVALID_CALLBACK', <del> message: "Callback must be a function. Received 'callback'" <add> code: 'ERR_INVALID_ARG_TYPE', <ide> } <ide> ); <ide> <ide><path>test/parallel/test-http2-server-settimeout-no-callback.js <ide> if (!common.hasCrypto) <ide> <ide> const assert = require('assert'); <ide> const http2 = require('http2'); <del>const { inspect } = require('util'); <ide> <ide> // Verify that setTimeout callback verifications work correctly <ide> const verifyCallbacks = (server) => { <ide> const verifyCallbacks = (server) => { <ide> () => server.setTimeout(testTimeout, notFunction), <ide> { <ide> name: 'TypeError', <del> code: 'ERR_INVALID_CALLBACK', <del> message: 'Callback must be a function. ' + <del> `Received ${inspect(notFunction)}` <add> code: 'ERR_INVALID_ARG_TYPE', <ide> } <ide> ); <ide> }); <ide><path>test/parallel/test-http2-timeouts.js <ide> server.on('stream', common.mustCall((stream) => { <ide> assert.throws( <ide> () => stream.setTimeout(0, Symbol('test')), <ide> { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError', <del> message: 'Callback must be a function. Received Symbol(test)' <ide> } <ide> ); <ide> assert.throws( <ide> () => stream.setTimeout(100, {}), <ide> { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError', <del> message: 'Callback must be a function. Received {}' <ide> } <ide> ); <ide> })); <ide><path>test/parallel/test-inspector-module.js <ide> common.skipIfInspectorDisabled(); <ide> <ide> const assert = require('assert'); <ide> const { Session } = require('inspector'); <del>const { inspect } = require('util'); <ide> <ide> const session = new Session(); <ide> <ide> session.post('Runtime.evaluate', { expression: '2 + 2' }); <ide> assert.throws( <ide> () => session.post('test', {}, i), <ide> { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError', <del> message: `Callback must be a function. Received ${inspect(i)}` <ide> } <ide> ); <ide> }); <ide><path>test/parallel/test-net-socket-timeout.js <ide> const common = require('../common'); <ide> const net = require('net'); <ide> const assert = require('assert'); <del>const { inspect } = require('util'); <ide> <ide> // Verify that invalid delays throw <ide> const s = new net.Socket(); <ide> for (let i = 0; i < invalidCallbacks.length; i++) { <ide> assert.throws( <ide> () => s.setTimeout(mesc, invalidCallbacks[i]), <ide> { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError', <del> message: 'Callback must be a function. ' + <del> `Received ${inspect(invalidCallbacks[i])}` <ide> } <ide> ) <ide> ); <ide><path>test/parallel/test-next-tick-errors.js <ide> function testNextTickWith(val) { <ide> assert.throws(() => { <ide> process.nextTick(val); <ide> }, { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> }); <ide> } <ide><path>test/parallel/test-performanceobserver.js <ide> <ide> const common = require('../common'); <ide> const assert = require('assert'); <del>const { inspect } = require('util'); <ide> const { internalBinding } = require('internal/test/binding'); <ide> const { <ide> observerCounts: counts <ide> assert.strictEqual(counts[NODE_PERFORMANCE_ENTRY_TYPE_HTTP2], 0); <ide> assert.throws( <ide> () => new PerformanceObserver(i), <ide> { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError', <del> message: `Callback must be a function. Received ${inspect(i)}` <ide> } <ide> ); <ide> }); <ide><path>test/parallel/test-process-next-tick.js <ide> 'use strict'; <ide> const common = require('../common'); <ide> const assert = require('assert'); <del>const { inspect } = require('util'); <ide> const N = 2; <ide> <ide> function cb() { <ide> process.on('exit', function() { <ide> assert.throws( <ide> () => process.nextTick(i), <ide> { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError', <del> message: `Callback must be a function. Received ${inspect(i)}` <ide> } <ide> ); <ide> }); <ide><path>test/parallel/test-readline-csi.js <ide> assert.strictEqual(readline.clearScreenDown(writable, common.mustCall()), true); <ide> // Verify that clearScreenDown() throws on invalid callback. <ide> assert.throws(() => { <ide> readline.clearScreenDown(writable, null); <del>}, /ERR_INVALID_CALLBACK/); <add>}, /ERR_INVALID_ARG_TYPE/); <ide> <ide> // Verify that clearScreenDown() does not throw on null or undefined stream. <ide> assert.strictEqual(readline.clearScreenDown(null, common.mustCall((err) => { <ide> assert.deepStrictEqual(writable.data, CSI.kClearToLineBeginning); <ide> // Verify that clearLine() throws on invalid callback. <ide> assert.throws(() => { <ide> readline.clearLine(writable, 0, null); <del>}, /ERR_INVALID_CALLBACK/); <add>}, /ERR_INVALID_ARG_TYPE/); <ide> <ide> // Verify that clearLine() does not throw on null or undefined stream. <ide> assert.strictEqual(readline.clearLine(null, 0), true); <ide> assert.strictEqual(readline.clearLine(undefined, 0, common.mustCall()), true); <ide> // Verify that moveCursor() throws on invalid callback. <ide> assert.throws(() => { <ide> readline.moveCursor(writable, 1, 1, null); <del>}, /ERR_INVALID_CALLBACK/); <add>}, /ERR_INVALID_ARG_TYPE/); <ide> <ide> // Verify that moveCursor() does not throw on null or undefined stream. <ide> assert.strictEqual(readline.moveCursor(null, 1, 1), true); <ide> assert.strictEqual(writable.data, '\x1b[2G'); <ide> // Verify that cursorTo() throws on invalid callback. <ide> assert.throws(() => { <ide> readline.cursorTo(writable, 1, 1, null); <del>}, /ERR_INVALID_CALLBACK/); <add>}, /ERR_INVALID_ARG_TYPE/); <ide> <ide> // Verify that cursorTo() throws if x or y is NaN. <ide> assert.throws(() => { <ide><path>test/parallel/test-stream-pipeline.js <ide> const tsp = require('timers/promises'); <ide> }, /ERR_MISSING_ARGS/); <ide> assert.throws(() => { <ide> pipeline(); <del> }, /ERR_INVALID_CALLBACK/); <add> }, /ERR_INVALID_ARG_TYPE/); <ide> } <ide> <ide> { <ide> const tsp = require('timers/promises'); <ide> <ide> assert.throws( <ide> () => pipeline(read, transform, write), <del> { code: 'ERR_INVALID_CALLBACK' } <add> { code: 'ERR_INVALID_ARG_TYPE' } <ide> ); <ide> } <ide> <ide><path>test/parallel/test-timers-refresh.js <ide> const common = require('../common'); <ide> <ide> const { strictEqual, throws } = require('assert'); <ide> const { setUnrefTimeout } = require('internal/timers'); <del>const { inspect } = require('util'); <ide> <ide> // Schedule the unrefed cases first so that the later case keeps the event loop <ide> // active. <ide> const { inspect } = require('util'); <ide> throws( <ide> () => setUnrefTimeout(cb), <ide> { <del> code: 'ERR_INVALID_CALLBACK', <del> message: `Callback must be a function. Received ${inspect(cb)}` <add> code: 'ERR_INVALID_ARG_TYPE', <ide> } <ide> ); <ide> }); <ide><path>test/parallel/test-timers-throw-when-cb-not-function.js <ide> function doSetTimeout(callback, after) { <ide> } <ide> <ide> const errMessage = { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> }; <ide> <ide><path>test/parallel/test-tls-disable-renegotiation.js <ide> server.listen(0, common.mustCall(() => { <ide> }); <ide> <ide> assert.throws(() => client.renegotiate({}, false), { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError', <ide> }); <ide> <ide> assert.throws(() => client.renegotiate({}, null), { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError', <ide> }); <ide> <ide><path>test/parallel/test-whatwg-url-custom-searchparams.js <ide> sp.forEach(function() { <ide> <ide> { <ide> const callbackErr = { <del> code: 'ERR_INVALID_CALLBACK', <add> code: 'ERR_INVALID_ARG_TYPE', <ide> name: 'TypeError' <ide> }; <ide> assert.throws(() => sp.forEach(), callbackErr);
78
Python
Python
remove unused variable in parse_error
137d232aeeceab3bae17312048d54853d37b8319
<ide><path>libcloud/common/openstack.py <ide> def parse_body(self): <ide> return self.body <ide> <ide> def parse_error(self): <del> text = None <ide> body = self.parse_body() <ide> <ide> if self.has_content_type('application/xml'):
1
Ruby
Ruby
fix typo in the documentation
1a06f5dc09dcb71c3a8196c3905a3f6909a0f04e
<ide><path>actionview/lib/action_view/model_naming.rb <ide> <ide> module ActionView <ide> module ModelNaming # :nodoc: <del> # Converts the given object to an ActiveModel compliant one. <add> # Converts the given object to an Active Model compliant one. <ide> def convert_to_model(object) <ide> object.respond_to?(:to_model) ? object.to_model : object <ide> end
1
Go
Go
remove dead code
ee230d8fdda6a1901c2adc394b5fb8471ec7aa51
<ide><path>client/errors.go <ide> type notFound interface { <ide> // IsErrNotFound returns true if the error is a NotFound error, which is returned <ide> // by the API when some object is not found. <ide> func IsErrNotFound(err error) bool { <del> var e notFound <del> if errors.As(err, &e) { <add> if errdefs.IsNotFound(err) { <ide> return true <ide> } <del> return errdefs.IsNotFound(err) <add> var e notFound <add> return errors.As(err, &e) <ide> } <ide> <ide> type objectNotFoundError struct { <ide> func (e objectNotFoundError) Error() string { <ide> return fmt.Sprintf("Error: No such %s: %s", e.object, e.id) <ide> } <ide> <del>// unauthorizedError represents an authorization error in a remote registry. <del>type unauthorizedError struct { <del> cause error <del>} <del> <del>// Error returns a string representation of an unauthorizedError <del>func (u unauthorizedError) Error() string { <del> return u.cause.Error() <del>} <del> <ide> // IsErrUnauthorized returns true if the error is caused <ide> // when a remote registry authentication fails <add>// <add>// Deprecated: use errdefs.IsUnauthorized <ide> func IsErrUnauthorized(err error) bool { <del> if _, ok := err.(unauthorizedError); ok { <del> return ok <del> } <ide> return errdefs.IsUnauthorized(err) <ide> } <ide> <ide> func (e pluginPermissionDenied) Error() string { <ide> return "Permission denied while installing plugin " + e.name <ide> } <ide> <del>// IsErrPluginPermissionDenied returns true if the error is caused <del>// when a user denies a plugin's permissions <del>func IsErrPluginPermissionDenied(err error) bool { <del> _, ok := err.(pluginPermissionDenied) <del> return ok <del>} <del> <del>type notImplementedError struct { <del> message string <del>} <del> <del>func (e notImplementedError) Error() string { <del> return e.message <del>} <del> <del>func (e notImplementedError) NotImplemented() bool { <del> return true <del>} <del> <ide> // IsErrNotImplemented returns true if the error is a NotImplemented error. <ide> // This is returned by the API when a requested feature has not been <ide> // implemented. <add>// <add>// Deprecated: use errdefs.IsNotImplemented <ide> func IsErrNotImplemented(err error) bool { <del> if _, ok := err.(notImplementedError); ok { <del> return ok <del> } <ide> return errdefs.IsNotImplemented(err) <ide> } <ide> <ide><path>testutil/environment/clean.go <ide> import ( <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <ide> "github.com/docker/docker/client" <add> "github.com/docker/docker/errdefs" <ide> "gotest.tools/v3/assert" <ide> ) <ide> <ide> func deleteAllPlugins(t testing.TB, c client.PluginAPIClient, protectedPlugins m <ide> t.Helper() <ide> plugins, err := c.PluginList(context.Background(), filters.Args{}) <ide> // Docker EE does not allow cluster-wide plugin management. <del> if client.IsErrNotImplemented(err) { <add> if errdefs.IsNotImplemented(err) { <ide> return <ide> } <ide> assert.Check(t, err, "failed to list plugins") <ide><path>testutil/environment/protect.go <ide> import ( <ide> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <del> dclient "github.com/docker/docker/client" <add> "github.com/docker/docker/errdefs" <ide> "gotest.tools/v3/assert" <ide> ) <ide> <ide> func getExistingPlugins(t testing.TB, testEnv *Execution) []string { <ide> client := testEnv.APIClient() <ide> pluginList, err := client.PluginList(context.Background(), filters.Args{}) <ide> // Docker EE does not allow cluster-wide plugin management. <del> if dclient.IsErrNotImplemented(err) { <add> if errdefs.IsNotImplemented(err) { <ide> return []string{} <ide> } <ide> assert.NilError(t, err, "failed to list plugins")
3
Javascript
Javascript
resolve local route promises
885fb0dd0743859a8985c23e4d0c1855a2be711e
<ide><path>src/ng/directive/ngView.js <ide> var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$c <ide> restrict: 'ECA', <ide> terminal: true, <ide> link: function(scope, element, attr) { <del> var changeCounter = 0, <del> lastScope, <add> var lastScope, <ide> onloadExp = attr.onload || ''; <ide> <ide> scope.$on('$afterRouteChange', update); <ide> var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$c <ide> } <ide> } <ide> <add> function clearContent() { <add> element.html(''); <add> destroyLastScope(); <add> } <add> <ide> function update() { <del> var template = $route.current && $route.current.template, <del> thisChangeId = ++changeCounter; <del> <del> function clearContent() { <del> // ignore callback if another route change occured since <del> if (thisChangeId === changeCounter) { <del> element.html(''); <del> destroyLastScope(); <del> } <del> } <add> var locals = $route.current && $route.current.locals, <add> template = locals && locals.$template; <ide> <ide> if (template) { <del> $http.get(template, {cache: $templateCache}).success(function(response) { <del> // ignore callback if another route change occured since <del> if (thisChangeId === changeCounter) { <del> element.html(response); <del> destroyLastScope(); <del> <del> var link = $compile(element.contents()), <del> current = $route.current, <del> controller; <del> <del> lastScope = current.scope = scope.$new(); <del> if (current.controller) { <del> controller = $controller(current.controller, {$scope: lastScope}); <del> element.contents().data('$ngControllerController', controller); <del> } <del> <del> link(lastScope); <del> lastScope.$emit('$viewContentLoaded'); <del> lastScope.$eval(onloadExp); <del> <del> // $anchorScroll might listen on event... <del> $anchorScroll(); <del> } <del> }).error(clearContent); <add> element.html(template); <add> destroyLastScope(); <add> <add> var link = $compile(element.contents()), <add> current = $route.current, <add> controller; <add> <add> lastScope = current.scope = scope.$new(); <add> if (current.controller) { <add> locals.$scope = lastScope; <add> controller = $controller(current.controller, locals); <add> element.contents().data('$ngControllerController', controller); <add> } <add> <add> link(lastScope); <add> lastScope.$emit('$viewContentLoaded'); <add> lastScope.$eval(onloadExp); <add> <add> // $anchorScroll might listen on event... <add> $anchorScroll(); <ide> } else { <ide> clearContent(); <ide> } <ide><path>src/ng/route.js <ide> function $RouteProvider(){ <ide> * @methodOf angular.module.ng.$routeProvider <ide> * <ide> * @param {string} path Route path (matched against `$location.path`). If `$location.path` <del> * contains redudant trailing slash or is missing one, the route will still match and the <add> * contains redundant trailing slash or is missing one, the route will still match and the <ide> * `$location.path` will be updated to add or drop the trailing slash to exacly match the <ide> * route definition. <ide> * @param {Object} route Mapping information to be assigned to `$route.current` on route <ide> function $RouteProvider(){ <ide> * - `template` – `{string=}` – path to an html template that should be used by <ide> * {@link angular.module.ng.$compileProvider.directive.ngView ngView} or <ide> * {@link angular.module.ng.$compileProvider.directive.ngInclude ngInclude} directives. <add> * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should <add> * be injected into the controller. If any of these dependencies are promises, they will be <add> * resolved and converted to a value before the controller is instantiated and the <add> * `$aftreRouteChange` event is fired. The map object is: <add> * <add> * - `key` – `{string}`: a name of a dependency to be injected into the controller. <add> * - `factory` - `{string|function}`: If `string` then it is an alias for a service. <add> * Otherwise if function, then it is {@link api/angular.module.AUTO.$injector#invoke injected} <add> * and the return value is treated as the dependency. If the result is a promise, it is resolved <add> * before its value is injected into the controller. <add> * <ide> * - `redirectTo` – {(string|function())=} – value to update <ide> * {@link angular.module.ng.$location $location} path with and trigger route redirection. <ide> * <ide> function $RouteProvider(){ <ide> }; <ide> <ide> <del> this.$get = ['$rootScope', '$location', '$routeParams', <del> function( $rootScope, $location, $routeParams) { <add> this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache', <add> function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache) { <ide> <ide> /** <ide> * @ngdoc object <ide> function $RouteProvider(){ <ide> * @requires $routeParams <ide> * <ide> * @property {Object} current Reference to the current route definition. <add> * The route definition contains: <add> * <add> * - `controller`: The controller constructor as define in route definition. <add> * - `locals`: A map of locals which is used by {@link angular.module.ng.$controller $controller} service for <add> * controller instantiation. The `locals` contain <add> * the resolved values of the `resolve` map. Additionally the `locals` also contain: <add> * <add> * - `$scope` - The current route scope. <add> * - `$template` - The current route template HTML. <add> * <ide> * @property {Array.<Object>} routes Array of all configured routes. <ide> * <ide> * @description <ide> function $RouteProvider(){ <ide> angular.module('ngView', [], function($routeProvider, $locationProvider) { <ide> $routeProvider.when('/Book/:bookId', { <ide> template: 'book.html', <del> controller: BookCntl <add> controller: BookCntl, <add> resolve: { <add> // I will cause a 1 second delay <add> delay: function($q, $timeout) { <add> var delay = $q.defer(); <add> $timeout(delay.resolve, 1000); <add> return delay.promise; <add> } <add> } <ide> }); <ide> $routeProvider.when('/Book/:bookId/ch/:chapterId', { <ide> template: 'chapter.html', <ide> function $RouteProvider(){ <ide> expect(content).toMatch(/Chapter Id\: 1/); <ide> <ide> element('a:contains("Scarlet")').click(); <add> sleep(2); // promises are not part of scenario waiting <ide> content = element('.doc-example-live [ng-view]').text(); <ide> expect(content).toMatch(/controller\: BookCntl/); <ide> expect(content).toMatch(/Book Id\: Scarlet/); <ide> function $RouteProvider(){ <ide> * @eventOf angular.module.ng.$route <ide> * @eventType broadcast on root scope <ide> * @description <del> * Broadcasted before a route change. <add> * Broadcasted before a route change. At this point the route services starts <add> * resolving all of the dependencies needed for the route change to occurs. <add> * Typically this involves fetching the view template as well as any dependencies <add> * defined in `resolve` route property. Once all of the dependencies are resolved <add> * `$afterRouteChange` is fired. <ide> * <ide> * @param {Route} next Future route information. <ide> * @param {Route} current Current route information. <ide> function $RouteProvider(){ <ide> * @eventOf angular.module.ng.$route <ide> * @eventType broadcast on root scope <ide> * @description <del> * Broadcasted after a route change. <add> * Broadcasted after a route dependencies are resolved. <add> * {@link angular.module.ng.$compileProvider.directive.ngView ngView} listens for the directive <add> * to instantiate the controller and render the view. <ide> * <ide> * @param {Route} current Current route information. <ide> * @param {Route} previous Previous route information. <ide> */ <ide> <add> /** <add> * @ngdoc event <add> * @name angular.module.ng.$route#$routeChangeError <add> * @eventOf angular.module.ng.$route <add> * @eventType broadcast on root scope <add> * @description <add> * Broadcasted if any of the resolve promises are rejected. <add> * <add> * @param {Route} current Current route information. <add> * @param {Route} previous Previous route information. <add> * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. <add> */ <add> <ide> /** <ide> * @ngdoc event <ide> * @name angular.module.ng.$route#$routeUpdate <ide> function $RouteProvider(){ <ide> * @methodOf angular.module.ng.$route <ide> * <ide> * @description <del> * Causes `$route` service to reload theR current route even if <add> * Causes `$route` service to reload the current route even if <ide> * {@link angular.module.ng.$location $location} hasn't changed. <ide> * <ide> * As a result of that, {@link angular.module.ng.$compileProvider.directive.ngView ngView} <ide> function $RouteProvider(){ <ide> $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) <ide> .replace(); <ide> } <del> } else { <del> copy(next.params, $routeParams); <ide> } <ide> } <del> $rootScope.$broadcast('$afterRouteChange', next, last); <add> <add> $q.when(next). <add> then(function() { <add> if (next) { <add> var keys = [], <add> values = []; <add> <add> forEach(next.resolve || {}, function(value, key) { <add> keys.push(key); <add> values.push(isFunction(value) ? $injector.invoke(value) : $injector.get(value)); <add> }); <add> if (next.template) { <add> keys.push('$template'); <add> values.push($http. <add> get(next.template, {cache: $templateCache}). <add> then(function(response) { return response.data; })); <add> } <add> return $q.all(values).then(function(values) { <add> var locals = {}; <add> forEach(values, function(value, index) { <add> locals[keys[index]] = value; <add> }); <add> return locals; <add> }); <add> } <add> }). <add> // after route change <add> then(function(locals) { <add> if (next == $route.current) { <add> if (next) { <add> next.locals = locals; <add> copy(next.params, $routeParams); <add> } <add> $rootScope.$broadcast('$afterRouteChange', next, last); <add> } <add> }, function(error) { <add> if (next == $route.current) { <add> $rootScope.$broadcast('$routeChangeError', next, last, error); <add> } <add> }); <ide> } <ide> } <ide> <ide><path>test/ng/directive/ngViewSpec.js <ide> describe('ngView', function() { <ide> }); <ide> <ide> <del> it('should clear the content when error during xhr request', function() { <del> module(function($routeProvider) { <del> $routeProvider.when('/foo', {controller: noop, template: 'myUrl1'}); <del> }); <del> <del> inject(function($route, $location, $rootScope, $httpBackend) { <del> $location.path('/foo'); <del> $httpBackend.expect('GET', 'myUrl1').respond(404, ''); <del> element.text('content'); <del> <del> $rootScope.$digest(); <del> $httpBackend.flush(); <del> <del> expect(element.text()).toBe(''); <del> }); <del> }); <del> <del> <ide> it('should be async even if served from cache', function() { <ide> module(function($routeProvider) { <ide> $routeProvider.when('/foo', {controller: noop, template: 'myUrl1'}); <ide> describe('ngView', function() { <ide> $rootScope.$digest(); <ide> <ide> expect(element.text()).toBe('bound-value'); <del> expect(log).toEqual(['$beforeRouteChange', '$afterRouteChange', 'init-ctrl', <del> '$viewContentLoaded']); <add> expect(log).toEqual([ <add> '$beforeRouteChange', 'init-ctrl', '$viewContentLoaded', '$afterRouteChange' ]); <ide> }); <ide> }); <ide> <ide><path>test/ng/routeSpec.js <ide> 'use strict'; <ide> <ide> describe('$route', function() { <add> var $httpBackend; <add> <add> beforeEach(module(function() { <add> return function(_$httpBackend_) { <add> $httpBackend = _$httpBackend_; <add> $httpBackend.when('GET', 'Chapter.html').respond('chapter'); <add> $httpBackend.when('GET', 'test.html').respond('test'); <add> $httpBackend.when('GET', 'foo.html').respond('foo'); <add> $httpBackend.when('GET', 'baz.html').respond('baz'); <add> $httpBackend.when('GET', 'bar.html').respond('bar'); <add> $httpBackend.when('GET', '404.html').respond('not found'); <add> }; <add> })); <ide> <ide> it('should route and fire change event', function() { <ide> var log = '', <ide> describe('$route', function() { <ide> <ide> $location.path('/Book/Moby/Chapter/Intro').search('p=123'); <ide> $rootScope.$digest(); <add> $httpBackend.flush(); <ide> expect(log).toEqual('before();after();'); <ide> expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', p:'123'}); <ide> <ide> describe('$route', function() { <ide> }); <ide> <ide> <del> it('should not fire $after/beforeRouteChange during bootstrap (if no route)', function() { <del> var routeChangeSpy = jasmine.createSpy('route change'); <add> describe('events', function() { <add> it('should not fire $after/beforeRouteChange during bootstrap (if no route)', function() { <add> var routeChangeSpy = jasmine.createSpy('route change'); <ide> <del> module(function($routeProvider) { <del> $routeProvider.when('/one', {}); // no otherwise defined <add> module(function($routeProvider) { <add> $routeProvider.when('/one', {}); // no otherwise defined <add> }); <add> <add> inject(function($rootScope, $route, $location) { <add> $rootScope.$on('$beforeRouteChange', routeChangeSpy); <add> $rootScope.$on('$afterRouteChange', routeChangeSpy); <add> <add> $rootScope.$digest(); <add> expect(routeChangeSpy).not.toHaveBeenCalled(); <add> <add> $location.path('/no-route-here'); <add> $rootScope.$digest(); <add> expect(routeChangeSpy).not.toHaveBeenCalled(); <add> }); <ide> }); <ide> <del> inject(function($rootScope, $route, $location) { <del> $rootScope.$on('$beforeRouteChange', routeChangeSpy); <del> $rootScope.$on('$afterRouteChange', routeChangeSpy); <add> it('should fire $beforeRouteChange and resolve promises', function() { <add> var deferA, <add> deferB; <ide> <del> $rootScope.$digest(); <del> expect(routeChangeSpy).not.toHaveBeenCalled(); <add> module(function($provide, $routeProvider) { <add> $provide.factory('b', function($q) { <add> deferB = $q.defer(); <add> return deferB.promise; <add> }); <add> $routeProvider.when('/path', { template: 'foo.html', resolve: { <add> a: function($q) { <add> deferA = $q.defer(); <add> return deferA.promise; <add> }, <add> b: 'b' <add> } }); <add> }); <ide> <del> $location.path('/no-route-here'); <del> $rootScope.$digest(); <del> expect(routeChangeSpy).not.toHaveBeenCalled(); <add> inject(function($location, $route, $rootScope, $httpBackend) { <add> var log = ''; <add> <add> $httpBackend.expectGET('foo.html').respond('FOO'); <add> <add> $location.path('/path'); <add> $rootScope.$digest(); <add> expect(log).toEqual(''); <add> $httpBackend.flush(); <add> expect(log).toEqual(''); <add> deferA.resolve(); <add> $rootScope.$digest(); <add> expect(log).toEqual(''); <add> deferB.resolve(); <add> $rootScope.$digest(); <add> expect($route.current.locals.$template).toEqual('FOO'); <add> }); <ide> }); <del> }); <ide> <ide> <add> it('should fire $routeChangeError event on resolution error', function() { <add> var deferA; <add> <add> module(function($provide, $routeProvider) { <add> $routeProvider.when('/path', { template: 'foo', resolve: { <add> a: function($q) { <add> deferA = $q.defer(); <add> return deferA.promise; <add> } <add> } }); <add> }); <add> <add> inject(function($location, $route, $rootScope) { <add> var log = ''; <add> <add> $rootScope.$on('$beforeRouteChange', function() { log += 'before();'; }); <add> $rootScope.$on('$routeChangeError', function(e, n, l, reason) { log += 'failed(' + reason + ');'; }); <add> <add> $location.path('/path'); <add> $rootScope.$digest(); <add> expect(log).toEqual('before();'); <add> <add> deferA.reject('MyError'); <add> $rootScope.$digest(); <add> expect(log).toEqual('before();failed(MyError);'); <add> }); <add> }); <add> <add> <add> it('should fetch templates', function() { <add> module(function($routeProvider) { <add> $routeProvider. <add> when('/r1', { template: 'r1.html' }). <add> when('/r2', { template: 'r2.html' }); <add> }); <add> <add> inject(function($route, $httpBackend, $location, $rootScope) { <add> var log = ''; <add> $rootScope.$on('$beforeRouteChange', function(e, next) { log += '$before(' + next.template + ');'}); <add> $rootScope.$on('$afterRouteChange', function(e, next) { log += '$after(' + next.template + ');'}); <add> <add> $httpBackend.expectGET('r1.html').respond('R1'); <add> $httpBackend.expectGET('r2.html').respond('R2'); <add> <add> $location.path('/r1'); <add> $rootScope.$digest(); <add> expect(log).toBe('$before(r1.html);'); <add> <add> $location.path('/r2'); <add> $rootScope.$digest(); <add> expect(log).toBe('$before(r1.html);$before(r2.html);'); <add> <add> $httpBackend.flush(); <add> expect(log).toBe('$before(r1.html);$before(r2.html);$after(r2.html);'); <add> expect(log).not.toContain('$after(r1.html);'); <add> }); <add> }); <add> <add> <add> it('should not update $routeParams until $afterRouteChange', function() { <add> module(function($routeProvider) { <add> $routeProvider. <add> when('/r1/:id', { template: 'r1.html' }). <add> when('/r2/:id', { template: 'r2.html' }); <add> }); <add> <add> inject(function($route, $httpBackend, $location, $rootScope, $routeParams) { <add> var log = ''; <add> $rootScope.$on('$beforeRouteChange', function(e, next) { log += '$before' + toJson($routeParams) + ';'}); <add> $rootScope.$on('$afterRouteChange', function(e, next) { log += '$after' + toJson($routeParams) + ';'}); <add> <add> $httpBackend.whenGET('r1.html').respond('R1'); <add> $httpBackend.whenGET('r2.html').respond('R2'); <add> <add> $location.path('/r1/1'); <add> $rootScope.$digest(); <add> expect(log).toBe('$before{};'); <add> $httpBackend.flush(); <add> expect(log).toBe('$before{};$after{"id":"1"};'); <add> <add> log = ''; <add> <add> $location.path('/r2/2'); <add> $rootScope.$digest(); <add> expect(log).toBe('$before{"id":"1"};'); <add> $httpBackend.flush(); <add> expect(log).toBe('$before{"id":"1"};$after{"id":"2"};'); <add> }); <add> }); <add> <add> <add> it('should drop in progress route change when new route change occurs', function() { <add> module(function($routeProvider) { <add> $routeProvider. <add> when('/r1', { template: 'r1.html' }). <add> when('/r2', { template: 'r2.html' }); <add> }); <add> <add> inject(function($route, $httpBackend, $location, $rootScope) { <add> var log = ''; <add> $rootScope.$on('$beforeRouteChange', function(e, next) { log += '$before(' + next.template + ');'}); <add> $rootScope.$on('$afterRouteChange', function(e, next) { log += '$after(' + next.template + ');'}); <add> <add> $httpBackend.expectGET('r1.html').respond('R1'); <add> $httpBackend.expectGET('r2.html').respond('R2'); <add> <add> $location.path('/r1'); <add> $rootScope.$digest(); <add> expect(log).toBe('$before(r1.html);'); <add> <add> $location.path('/r2'); <add> $rootScope.$digest(); <add> expect(log).toBe('$before(r1.html);$before(r2.html);'); <add> <add> $httpBackend.flush(); <add> expect(log).toBe('$before(r1.html);$before(r2.html);$after(r2.html);'); <add> expect(log).not.toContain('$after(r1.html);'); <add> }); <add> }); <add> <add> <add> it('should drop in progress route change when new route change occurs and old fails', function() { <add> module(function($routeProvider) { <add> $routeProvider. <add> when('/r1', { templateUrl: 'r1.html' }). <add> when('/r2', { templateUrl: 'r2.html' }); <add> }); <add> <add> inject(function($route, $httpBackend, $location, $rootScope) { <add> var log = ''; <add> $rootScope.$on('$routeChangeError', function(e, next, last, error) { <add> log += '$failed(' + next.templateUrl + ', ' + error.status + ');'; <add> }); <add> $rootScope.$on('$beforeRouteChange', function(e, next) { log += '$before(' + next.templateUrl + ');'}); <add> $rootScope.$on('$afterRouteChange', function(e, next) { log += '$after(' + next.templateUrl + ');'}); <add> <add> $httpBackend.expectGET('r1.html').respond(404, 'R1'); <add> $httpBackend.expectGET('r2.html').respond('R2'); <add> <add> $location.path('/r1'); <add> $rootScope.$digest(); <add> expect(log).toBe('$before(r1.html);'); <add> <add> $location.path('/r2'); <add> $rootScope.$digest(); <add> expect(log).toBe('$before(r1.html);$before(r2.html);'); <add> <add> $httpBackend.flush(); <add> expect(log).toBe('$before(r1.html);$before(r2.html);$after(r2.html);'); <add> expect(log).not.toContain('$after(r1.html);'); <add> }); <add> }); <add> <add> <add> it('should catch local factory errors', function() { <add> var myError = new Error('MyError'); <add> module(function($routeProvider, $exceptionHandlerProvider) { <add> $exceptionHandlerProvider.mode('log'); <add> $routeProvider.when('/locals', { <add> resolve: { <add> a: function($q) { <add> throw myError; <add> } <add> } <add> }); <add> }); <add> <add> inject(function($location, $route, $rootScope, $exceptionHandler) { <add> $location.path('/locals'); <add> $rootScope.$digest(); <add> expect($exceptionHandler.errors).toEqual([myError]); <add> }); <add> }); <add> }); <add> <add> <ide> it('should match route with and without trailing slash', function() { <ide> module(function($routeProvider){ <ide> $routeProvider.when('/foo', {template: 'foo.html'});
4
Text
Text
add documentation for definition list helper
5942771ce9bd69d46ce2b84ac683681c322a776e
<ide><path>laravel/documentation/views/html.md <ide> The "mailto" method on the HTML class obfuscates the given e-mail address so it <ide> echo HTML::ol(array('Get Peanut Butter', 'Get Chocolate', 'Feast')); <ide> <ide> echo HTML::ul(array('Ubuntu', 'Snow Leopard', 'Windows')); <add> <add> echo HTML::dl(array('Ubuntu' => 'An operating system by Canonical', 'Windows' => 'An operating system by Microsoft')); <ide> <ide> <a name="custom-macros"></a> <ide> ## Custom Macros
1
Javascript
Javascript
use unique filenames in fs benchmarks
cfda245706249255b517c2c76252c50377f7c616
<ide><path>benchmark/fs/read-stream-throughput.js <ide> <ide> const path = require('path'); <ide> const common = require('../common.js'); <del>const filename = path.resolve(__dirname, '.removeme-benchmark-garbage'); <add>const filename = path.resolve(__dirname, <add> `.removeme-benchmark-garbage-${process.pid}`); <ide> const fs = require('fs'); <ide> const assert = require('assert'); <ide> <ide><path>benchmark/fs/readfile.js <ide> <ide> const path = require('path'); <ide> const common = require('../common.js'); <del>const filename = path.resolve(__dirname, '.removeme-benchmark-garbage'); <add>const filename = path.resolve(__dirname, <add> `.removeme-benchmark-garbage-${process.pid}`); <ide> const fs = require('fs'); <ide> <ide> const bench = common.createBenchmark(main, { <ide><path>benchmark/fs/write-stream-throughput.js <ide> <ide> const path = require('path'); <ide> const common = require('../common.js'); <del>const filename = path.resolve(__dirname, '.removeme-benchmark-garbage'); <add>const filename = path.resolve(__dirname, <add> `.removeme-benchmark-garbage-${process.pid}`); <ide> const fs = require('fs'); <ide> <ide> const bench = common.createBenchmark(main, {
3
Javascript
Javascript
improve readability of computetangents()
a9f43b83b9ac50b5eea047fa0c2359f79ef9c2a3
<ide><path>examples/js/utils/BufferGeometryUtils.js <ide> THREE.BufferGeometryUtils = { <ide> uvB.fromArray( uvs, b * 2 ); <ide> uvC.fromArray( uvs, c * 2 ); <ide> <del> var x1 = vB.x - vA.x; <del> var x2 = vC.x - vA.x; <add> vB.sub( vA ); <add> vC.sub( vA ); <ide> <del> var y1 = vB.y - vA.y; <del> var y2 = vC.y - vA.y; <add> uvB.sub( uvA ); <add> uvC.sub( uvA ); <ide> <del> var z1 = vB.z - vA.z; <del> var z2 = vC.z - vA.z; <add> var r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y ); <ide> <del> var s1 = uvB.x - uvA.x; <del> var s2 = uvC.x - uvA.x; <add> // silently ignore degenerate uv triangles having coincident or colinear vertices <ide> <del> var t1 = uvB.y - uvA.y; <del> var t2 = uvC.y - uvA.y; <add> if ( ! isFinite( r ) ) return; <ide> <del> var r = 1.0 / ( s1 * t2 - s2 * t1 ); <del> <del> sdir.set( <del> ( t2 * x1 - t1 * x2 ) * r, <del> ( t2 * y1 - t1 * y2 ) * r, <del> ( t2 * z1 - t1 * z2 ) * r <del> ); <del> <del> tdir.set( <del> ( s1 * x2 - s2 * x1 ) * r, <del> ( s1 * y2 - s2 * y1 ) * r, <del> ( s1 * z2 - s2 * z1 ) * r <del> ); <del> <del> // silently ignore degenerate uvs/triangles that yield NaN/Infinite intermediary values <del> if ( ! ( isFinite( sdir.x ) && isFinite( sdir.y ) && isFinite( sdir.z ) && <del> isFinite( tdir.x ) && isFinite( tdir.y ) && isFinite( tdir.z ) ) ) { <del> <del> return; <del> <del> } <add> sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r ); <add> tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r ); <ide> <ide> tan1[ a ].add( sdir ); <ide> tan1[ b ].add( sdir ); <ide><path>examples/jsm/utils/BufferGeometryUtils.js <ide> var BufferGeometryUtils = { <ide> uvB.fromArray( uvs, b * 2 ); <ide> uvC.fromArray( uvs, c * 2 ); <ide> <del> var x1 = vB.x - vA.x; <del> var x2 = vC.x - vA.x; <add> vB.sub( vA ); <add> vC.sub( vA ); <ide> <del> var y1 = vB.y - vA.y; <del> var y2 = vC.y - vA.y; <add> uvB.sub( uvA ); <add> uvC.sub( uvA ); <ide> <del> var z1 = vB.z - vA.z; <del> var z2 = vC.z - vA.z; <add> var r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y ); <ide> <del> var s1 = uvB.x - uvA.x; <del> var s2 = uvC.x - uvA.x; <add> // silently ignore degenerate uv triangles having coincident or colinear vertices <ide> <del> var t1 = uvB.y - uvA.y; <del> var t2 = uvC.y - uvA.y; <add> if ( ! isFinite( r ) ) return; <ide> <del> var r = 1.0 / ( s1 * t2 - s2 * t1 ); <del> <del> sdir.set( <del> ( t2 * x1 - t1 * x2 ) * r, <del> ( t2 * y1 - t1 * y2 ) * r, <del> ( t2 * z1 - t1 * z2 ) * r <del> ); <del> <del> tdir.set( <del> ( s1 * x2 - s2 * x1 ) * r, <del> ( s1 * y2 - s2 * y1 ) * r, <del> ( s1 * z2 - s2 * z1 ) * r <del> ); <del> <del> // silently ignore degenerate uvs/triangles that yield NaN/Infinite intermediary values <del> if ( ! ( isFinite( sdir.x ) && isFinite( sdir.y ) && isFinite( sdir.z ) && <del> isFinite( tdir.x ) && isFinite( tdir.y ) && isFinite( tdir.z ) ) ) { <del> <del> return; <del> <del> } <add> sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r ); <add> tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r ); <ide> <ide> tan1[ a ].add( sdir ); <ide> tan1[ b ].add( sdir );
2
Ruby
Ruby
use #prepend rather than using 2 aliases
d3684c4154df66059ba77d022eca285563b8f506
<ide><path>activesupport/lib/active_support/core_ext/range/each.rb <del>class Range #:nodoc: <add>module ActiveSupport <add> module EachTimeWithZone #:nodoc: <add> def each(&block) <add> ensure_iteration_allowed <add> super <add> end <ide> <del> def each_with_time_with_zone(&block) <del> ensure_iteration_allowed <del> each_without_time_with_zone(&block) <del> end <del> # TODO: change to Module#prepend as soon as the fix is backported to MRI 2.2: <del> # https://bugs.ruby-lang.org/issues/10847 <del> alias_method :each_without_time_with_zone, :each <del> alias_method :each, :each_with_time_with_zone <add> def step(n = 1, &block) <add> ensure_iteration_allowed <add> super <add> end <ide> <del> def step_with_time_with_zone(n = 1, &block) <del> ensure_iteration_allowed <del> step_without_time_with_zone(n, &block) <del> end <del> # TODO: change to Module#prepend as soon as the fix is backported to MRI 2.2: <del> # https://bugs.ruby-lang.org/issues/10847 <del> alias_method :step_without_time_with_zone, :step <del> alias_method :step, :step_with_time_with_zone <add> private <ide> <del> private <del> def ensure_iteration_allowed <del> if first.is_a?(Time) <del> raise TypeError, "can't iterate from #{first.class}" <del> end <add> def ensure_iteration_allowed <add> raise TypeError, "can't iterate from #{first.class}" if first.is_a?(Time) <add> end <ide> end <ide> end <add> <add>Range.prepend(ActiveSupport::EachTimeWithZone) <ide><path>activesupport/lib/active_support/core_ext/range/include_range.rb <del>class Range <del> # Extends the default Range#include? to support range comparisons. <del> # (1..5).include?(1..5) # => true <del> # (1..5).include?(2..3) # => true <del> # (1..5).include?(2..6) # => false <del> # <del> # The native Range#include? behavior is untouched. <del> # ('a'..'f').include?('c') # => true <del> # (5..9).include?(11) # => false <del> def include_with_range?(value) <del> if value.is_a?(::Range) <del> # 1...10 includes 1..9 but it does not include 1..10. <del> operator = exclude_end? && !value.exclude_end? ? :< : :<= <del> include_without_range?(value.first) && value.last.send(operator, last) <del> else <del> include_without_range?(value) <add>module ActiveSupport <add> module IncludeWithRange #:nodoc: <add> # Extends the default Range#include? to support range comparisons. <add> # (1..5).include?(1..5) # => true <add> # (1..5).include?(2..3) # => true <add> # (1..5).include?(2..6) # => false <add> # <add> # The native Range#include? behavior is untouched. <add> # ('a'..'f').include?('c') # => true <add> # (5..9).include?(11) # => false <add> def include?(value) <add> if value.is_a?(::Range) <add> # 1...10 includes 1..9 but it does not include 1..10. <add> operator = exclude_end? && !value.exclude_end? ? :< : :<= <add> super(value.first) && value.last.send(operator, last) <add> else <add> super <add> end <ide> end <ide> end <del> # TODO: change to Module#prepend as soon as the fix is backported to MRI 2.2: <del> # https://bugs.ruby-lang.org/issues/10847 <del> alias_method :include_without_range?, :include? <del> alias_method :include?, :include_with_range? <ide> end <add> <add>Range.prepend(ActiveSupport::IncludeWithRange)
2
PHP
PHP
add test case for quoted strings
bf0cd7ef2fb5fe6c0322323025e4e6b5ed698612
<ide><path>tests/TestCase/I18n/Parser/PoFileParserTest.php <ide> public function testParseMultiLine() { <ide> $this->assertCount(12, $messages); <ide> $this->assertTextEquals("v\nsecond line", $messages["valid\nsecond line"]); <ide> } <add> <add>/** <add> * Test parsing a file with quoted strings <add> * <add> * @return void <add> */ <add> public function testQuotedString() { <add> $parser = new PoFileParser; <add> $file = APP . 'Locale' . DS . 'en' . DS . 'default.po'; <add> $messages = $parser->parse($file); <add> <add> $this->assertTextEquals('this is a "quoted string" (translated)', $messages['this is a "quoted string"']); <add> } <ide> }
1
Python
Python
add acl_policy parameter to gcstos3operator
dd98b21494ff6036242b63268140abe1294b3657
<ide><path>airflow/providers/amazon/aws/transfers/gcs_to_s3.py <ide> class GCSToS3Operator(BaseOperator): <ide> Service Account Token Creator IAM role to the directly preceding identity, with first <ide> account from the list granting this role to the originating account (templated). <ide> :type google_impersonation_chain: Union[str, Sequence[str]] <add> :param s3_acl_policy: Optional The string to specify the canned ACL policy for the <add> object to be uploaded in S3 <add> :type s3_acl_policy: str <ide> """ <ide> <ide> template_fields: Iterable[str] = ( <ide> def __init__( <ide> replace=False, <ide> google_impersonation_chain: Optional[Union[str, Sequence[str]]] = None, <ide> dest_s3_extra_args: Optional[Dict] = None, <add> s3_acl_policy: Optional[str] = None, <ide> **kwargs, <ide> ): <ide> super().__init__(**kwargs) <ide> def __init__( <ide> self.replace = replace <ide> self.google_impersonation_chain = google_impersonation_chain <ide> self.dest_s3_extra_args = dest_s3_extra_args or {} <add> self.s3_acl_policy = s3_acl_policy <ide> <ide> def execute(self, context): <ide> # list all files in an Google Cloud Storage bucket <ide> def execute(self, context): <ide> dest_key = self.dest_s3_key + file <ide> self.log.info("Saving file to %s", dest_key) <ide> <del> s3_hook.load_bytes(file_bytes, key=dest_key, replace=self.replace) <add> s3_hook.load_bytes( <add> file_bytes, key=dest_key, replace=self.replace, acl_policy=self.s3_acl_policy <add> ) <ide> <ide> self.log.info("All done, uploaded %d files to S3", len(files)) <ide> else: <ide><path>tests/providers/amazon/aws/transfers/test_gcs_to_s3.py <ide> PREFIX = 'TEST' <ide> S3_BUCKET = 's3://bucket/' <ide> MOCK_FILES = ["TEST1.csv", "TEST2.csv", "TEST3.csv"] <add>S3_ACL_POLICY = "private-read" <ide> <ide> <ide> class TestGCSToS3Operator(unittest.TestCase): <ide> def test_execute_should_pass_dest_s3_extra_args_to_s3_hook(self, s3_mock_hook, m <ide> s3_mock_hook.assert_called_once_with( <ide> aws_conn_id='aws_default', extra_args={'ContentLanguage': 'value'}, verify=None <ide> ) <add> <add> # Test6: s3_acl_policy parameter is set <add> @mock_s3 <add> @mock.patch('airflow.providers.google.cloud.operators.gcs.GCSHook') <add> @mock.patch('airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSHook') <add> @mock.patch('airflow.providers.amazon.aws.hooks.s3.S3Hook.load_bytes') <add> def test_execute_with_s3_acl_policy(self, mock_load_bytes, mock_gcs_hook, mock_gcs_hook2): <add> mock_gcs_hook.return_value.list.return_value = MOCK_FILES <add> mock_gcs_hook.return_value.download.return_value = b"testing" <add> mock_gcs_hook2.return_value.list.return_value = MOCK_FILES <add> <add> operator = GCSToS3Operator( <add> task_id=TASK_ID, <add> bucket=GCS_BUCKET, <add> prefix=PREFIX, <add> delimiter=DELIMITER, <add> dest_aws_conn_id="aws_default", <add> dest_s3_key=S3_BUCKET, <add> replace=False, <add> s3_acl_policy=S3_ACL_POLICY, <add> ) <add> <add> # Create dest bucket without files <add> hook = S3Hook(aws_conn_id='airflow_gcs_test') <add> bucket = hook.get_bucket('bucket') <add> bucket.create() <add> <add> operator.execute(None) <add> <add> # Make sure the acl_policy parameter is passed to the upload method <add> self.assertEqual(mock_load_bytes.call_args.kwargs['acl_policy'], S3_ACL_POLICY)
2
Text
Text
add the text "необходимо" instead of "должен"
445b619515ec64f70715cef672c8542ad4eccf08
<ide><path>guide/russian/angular/animations/index.md <ide> localeTitle: Анимации <ide> <ide> #### Настройка анимаций <ide> <del>Перед анимацией `BrowserAnimationsModule` должен включать в массив импорта корневого модуля. Он доступен из `@angular/platform-browser/animations` . Этот NgModule обеспечивает работу анимации для данной платформы. Эта статья предполагает стандартный веб-браузер для каждого примера. <add>Перед анимацией `BrowserAnimationsModule` необходимо включать в массив импорта корневого модуля. Он доступен из `@angular/platform-browser/animations` . Этот NgModule обеспечивает работу анимации для данной платформы. Эта статья предполагает стандартный веб-браузер для каждого примера. <ide> <ide> Угловая анимация объявляется в метаданных `@Component` . `@Component` украшает класс, чтобы отличить его как компонент от углового. Его метаданные содержат конфигурации компонентов, включая поле `animations: []` . Каждый элемент массива из этого поля представляет триггер анимации ( `AnimationTriggerMetadata` ). <ide> <ide> import { Component, HostBinding } from '@angular/core'; <ide> * [Угловая анимация](https://angular.io/guide/animations) <ide> * [API угловой анимации](https://angular.io/api/animations) <ide> * [Угловой репозиторий GitHub](https://github.com/angular/angular) <del>* [Угловая CLI](https://cli.angular.io) <ide>\ No newline at end of file <add>* [Угловая CLI](https://cli.angular.io)
1
Python
Python
fix examples in docstring
6ec1ee9ec28ead1a7c065153df32271ead95b417
<ide><path>pytorch_transformers/modeling_bert.py <ide> class BertModel(BertPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') <del> >>> model = BertModel.from_pretrained('bert-base-uncased') <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <del> >>> outputs = model(input_ids) <del> >>> last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple <add> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') <add> model = BertModel.from_pretrained('bert-base-uncased') <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids) <add> last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple <ide> <ide> """ <ide> def __init__(self, config): <ide> class BertForPreTraining(BertPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') <del> >>> model = BertForPreTraining.from_pretrained('bert-base-uncased') <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <del> >>> outputs = model(input_ids) <del> >>> prediction_scores, seq_relationship_scores = outputs[:2] <add> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') <add> model = BertForPreTraining.from_pretrained('bert-base-uncased') <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids) <add> prediction_scores, seq_relationship_scores = outputs[:2] <ide> <ide> """ <ide> def __init__(self, config): <ide> class BertForMaskedLM(BertPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') <del> >>> model = BertForMaskedLM.from_pretrained('bert-base-uncased') <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <del> >>> outputs = model(input_ids, masked_lm_labels=input_ids) <del> >>> loss, prediction_scores = outputs[:2] <add> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') <add> model = BertForMaskedLM.from_pretrained('bert-base-uncased') <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids, masked_lm_labels=input_ids) <add> loss, prediction_scores = outputs[:2] <ide> <ide> """ <ide> def __init__(self, config): <ide> class BertForNextSentencePrediction(BertPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') <del> >>> model = BertForNextSentencePrediction.from_pretrained('bert-base-uncased') <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <del> >>> outputs = model(input_ids) <del> >>> seq_relationship_scores = outputs[0] <add> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') <add> model = BertForNextSentencePrediction.from_pretrained('bert-base-uncased') <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids) <add> seq_relationship_scores = outputs[0] <ide> <ide> """ <ide> def __init__(self, config): <ide> class BertForSequenceClassification(BertPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') <del> >>> model = BertForSequenceClassification.from_pretrained('bert-base-uncased') <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <del> >>> labels = torch.tensor([1]).unsqueeze(0) # Batch size 1 <del> >>> outputs = model(input_ids, labels=labels) <del> >>> loss, logits = outputs[:2] <add> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') <add> model = BertForSequenceClassification.from_pretrained('bert-base-uncased') <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <add> labels = torch.tensor([1]).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids, labels=labels) <add> loss, logits = outputs[:2] <ide> <ide> """ <ide> def __init__(self, config): <ide> class BertForMultipleChoice(BertPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') <del> >>> model = BertForMultipleChoice.from_pretrained('bert-base-uncased') <del> >>> choices = ["Hello, my dog is cute", "Hello, my cat is amazing"] <del> >>> input_ids = torch.tensor([tokenizer.encode(s) for s in choices]).unsqueeze(0) # Batch size 1, 2 choices <del> >>> labels = torch.tensor(1).unsqueeze(0) # Batch size 1 <del> >>> outputs = model(input_ids, labels=labels) <del> >>> loss, classification_scores = outputs[:2] <add> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') <add> model = BertForMultipleChoice.from_pretrained('bert-base-uncased') <add> choices = ["Hello, my dog is cute", "Hello, my cat is amazing"] <add> input_ids = torch.tensor([tokenizer.encode(s) for s in choices]).unsqueeze(0) # Batch size 1, 2 choices <add> labels = torch.tensor(1).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids, labels=labels) <add> loss, classification_scores = outputs[:2] <ide> <ide> """ <ide> def __init__(self, config): <ide> class BertForTokenClassification(BertPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') <del> >>> model = BertForTokenClassification.from_pretrained('bert-base-uncased') <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <del> >>> labels = torch.tensor([1] * input_ids.size(1)).unsqueeze(0) # Batch size 1 <del> >>> outputs = model(input_ids, labels=labels) <del> >>> loss, scores = outputs[:2] <add> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') <add> model = BertForTokenClassification.from_pretrained('bert-base-uncased') <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <add> labels = torch.tensor([1] * input_ids.size(1)).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids, labels=labels) <add> loss, scores = outputs[:2] <ide> <ide> """ <ide> def __init__(self, config): <ide> class BertForQuestionAnswering(BertPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') <del> >>> model = BertForQuestionAnswering.from_pretrained('bert-base-uncased') <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <del> >>> start_positions = torch.tensor([1]) <del> >>> end_positions = torch.tensor([3]) <del> >>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions) <del> >>> loss, start_scores, end_scores = outputs[:2] <add> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') <add> model = BertForQuestionAnswering.from_pretrained('bert-base-uncased') <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <add> start_positions = torch.tensor([1]) <add> end_positions = torch.tensor([3]) <add> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions) <add> loss, start_scores, end_scores = outputs[:2] <ide> <ide> """ <ide> def __init__(self, config): <ide><path>pytorch_transformers/modeling_openai.py <ide> class OpenAIGPTModel(OpenAIGPTPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = OpenAIGPTTokenizer.from_pretrained('openai-gpt') <del> >>> model = OpenAIGPTModel.from_pretrained('openai-gpt') <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <del> >>> outputs = model(input_ids) <del> >>> last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple <add> tokenizer = OpenAIGPTTokenizer.from_pretrained('openai-gpt') <add> model = OpenAIGPTModel.from_pretrained('openai-gpt') <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids) <add> last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple <ide> <ide> """ <ide> def __init__(self, config): <ide> class OpenAIGPTLMHeadModel(OpenAIGPTPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = OpenAIGPTTokenizer.from_pretrained('openai-gpt') <del> >>> model = OpenAIGPTLMHeadModel.from_pretrained('openai-gpt') <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <del> >>> outputs = model(input_ids, labels=input_ids) <del> >>> loss, logits = outputs[:2] <add> tokenizer = OpenAIGPTTokenizer.from_pretrained('openai-gpt') <add> model = OpenAIGPTLMHeadModel.from_pretrained('openai-gpt') <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids, labels=input_ids) <add> loss, logits = outputs[:2] <ide> <ide> """ <ide> def __init__(self, config): <ide> class OpenAIGPTDoubleHeadsModel(OpenAIGPTPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = OpenAIGPTTokenizer.from_pretrained('openai-gpt') <del> >>> model = OpenAIGPTDoubleHeadsModel.from_pretrained('openai-gpt') <del> >>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"] # Assume you've added [CLS] to the vocabulary <del> >>> input_ids = torch.tensor([tokenizer.encode(s) for s in choices]).unsqueeze(0) # Batch size 1, 2 choices <del> >>> mc_token_ids = torch.tensor([-1, -1]).unsqueeze(0) # Batch size 1 <del> >>> outputs = model(input_ids, mc_token_ids) <del> >>> lm_prediction_scores, mc_prediction_scores = outputs[:2] <add> tokenizer = OpenAIGPTTokenizer.from_pretrained('openai-gpt') <add> model = OpenAIGPTDoubleHeadsModel.from_pretrained('openai-gpt') <add> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"] # Assume you've added [CLS] to the vocabulary <add> input_ids = torch.tensor([tokenizer.encode(s) for s in choices]).unsqueeze(0) # Batch size 1, 2 choices <add> mc_token_ids = torch.tensor([-1, -1]).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids, mc_token_ids) <add> lm_prediction_scores, mc_prediction_scores = outputs[:2] <ide> <ide> """ <ide> def __init__(self, config): <ide><path>pytorch_transformers/modeling_xlm.py <ide> class XLMModel(XLMPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') <del> >>> model = XLMModel.from_pretrained('xlm-mlm-en-2048') <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <del> >>> outputs = model(input_ids) <del> >>> last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple <add> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') <add> model = XLMModel.from_pretrained('xlm-mlm-en-2048') <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids) <add> last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple <ide> <ide> """ <ide> ATTRIBUTES = ['encoder', 'eos_index', 'pad_index', # 'with_output', <ide> class XLMWithLMHeadModel(XLMPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') <del> >>> model = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048') <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <del> >>> outputs = model(input_ids) <del> >>> last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple <add> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') <add> model = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048') <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids) <add> last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple <ide> <ide> """ <ide> def __init__(self, config): <ide> class XLMForSequenceClassification(XLMPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') <del> >>> model = XLMForSequenceClassification.from_pretrained('xlm-mlm-en-2048') <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <del> >>> labels = torch.tensor([1]).unsqueeze(0) # Batch size 1 <del> >>> outputs = model(input_ids, labels=labels) <del> >>> loss, logits = outputs[:2] <add> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') <add> model = XLMForSequenceClassification.from_pretrained('xlm-mlm-en-2048') <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <add> labels = torch.tensor([1]).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids, labels=labels) <add> loss, logits = outputs[:2] <ide> <ide> """ <ide> def __init__(self, config): <ide> class XLMForQuestionAnswering(XLMPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') <del> >>> model = XLMForQuestionAnswering.from_pretrained('xlm-mlm-en-2048') <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <del> >>> start_positions = torch.tensor([1]) <del> >>> end_positions = torch.tensor([3]) <del> >>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions) <del> >>> loss, start_scores, end_scores = outputs[:2] <add> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') <add> model = XLMForQuestionAnswering.from_pretrained('xlm-mlm-en-2048') <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <add> start_positions = torch.tensor([1]) <add> end_positions = torch.tensor([3]) <add> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions) <add> loss, start_scores, end_scores = outputs[:2] <ide> <ide> """ <ide> def __init__(self, config): <ide><path>pytorch_transformers/modeling_xlnet.py <ide> class XLNetModel(XLNetPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-large-cased') <del> >>> model = XLNetModel.from_pretrained('xlnet-large-cased') <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <del> >>> outputs = model(input_ids) <del> >>> last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple <add> tokenizer = XLNetTokenizer.from_pretrained('xlnet-large-cased') <add> model = XLNetModel.from_pretrained('xlnet-large-cased') <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids) <add> last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple <ide> <ide> """ <ide> def __init__(self, config): <ide> class XLNetLMHeadModel(XLNetPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-large-cased') <del> >>> model = XLNetLMHeadModel.from_pretrained('xlnet-large-cased') <del> >>> # We show how to setup inputs to predict a next token using a bi-directional context. <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is very <mask>")).unsqueeze(0) # We will predict the masked token <del> >>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float) <del> >>> perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token <del> >>> target_mapping = torch.zeros((1, 1, input_ids.shape[1]), dtype=torch.float) # Shape [1, 1, seq_length] => let's predict one token <del> >>> target_mapping[0, 0, -1] = 1.0 # Our first (and only) prediction will be the last token of the sequence (the masked token) <del> >>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping) <del> >>> next_token_logits = outputs[0] # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size] <add> tokenizer = XLNetTokenizer.from_pretrained('xlnet-large-cased') <add> model = XLNetLMHeadModel.from_pretrained('xlnet-large-cased') <add> # We show how to setup inputs to predict a next token using a bi-directional context. <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is very <mask>")).unsqueeze(0) # We will predict the masked token <add> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float) <add> perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token <add> target_mapping = torch.zeros((1, 1, input_ids.shape[1]), dtype=torch.float) # Shape [1, 1, seq_length] => let's predict one token <add> target_mapping[0, 0, -1] = 1.0 # Our first (and only) prediction will be the last token of the sequence (the masked token) <add> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping) <add> next_token_logits = outputs[0] # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size] <ide> <ide> """ <ide> def __init__(self, config): <ide> class XLNetForSequenceClassification(XLNetPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-large-cased') <del> >>> model = XLNetForSequenceClassification.from_pretrained('xlnet-large-cased') <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <del> >>> labels = torch.tensor([1]).unsqueeze(0) # Batch size 1 <del> >>> outputs = model(input_ids, labels=labels) <del> >>> loss, logits = outputs[:2] <add> tokenizer = XLNetTokenizer.from_pretrained('xlnet-large-cased') <add> model = XLNetForSequenceClassification.from_pretrained('xlnet-large-cased') <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <add> labels = torch.tensor([1]).unsqueeze(0) # Batch size 1 <add> outputs = model(input_ids, labels=labels) <add> loss, logits = outputs[:2] <ide> <ide> """ <ide> def __init__(self, config): <ide> class XLNetForQuestionAnswering(XLNetPreTrainedModel): <ide> <ide> Examples:: <ide> <del> >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') <del> >>> model = XLMForQuestionAnswering.from_pretrained('xlnet-large-cased') <del> >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <del> >>> start_positions = torch.tensor([1]) <del> >>> end_positions = torch.tensor([3]) <del> >>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions) <del> >>> loss, start_scores, end_scores = outputs[:2] <add> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') <add> model = XLMForQuestionAnswering.from_pretrained('xlnet-large-cased') <add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 <add> start_positions = torch.tensor([1]) <add> end_positions = torch.tensor([3]) <add> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions) <add> loss, start_scores, end_scores = outputs[:2] <ide> <ide> """ <ide> def __init__(self, config):
4
PHP
PHP
fix bug in query string construction
92a1c709181c4680fc5746c61446e0a1637d4806
<ide><path>laravel/paginator.php <ide> protected function element($element, $text, $page, $disabler) <ide> */ <ide> protected function appendage($element, $page) <ide> { <del> if (is_null($this->appendage)) <add> $this->appendage = '?page=%s'; <add> <add> if (count($this->appends) > 0) <ide> { <del> $this->appendage = '?page=%s'.http_build_query((array) $this->appends); <add> $this->appendage = '&'.http_build_query($this->appends); <ide> } <ide> <ide> return sprintf($this->appendage, $page);
1
Go
Go
increase raft electiontick to 10xheartbeattick
6abee2008b314a65553202b15d9a333d171e3433
<ide><path>daemon/cluster/noderunner.go <ide> func (n *nodeRunner) start(conf nodeStartConfig) error { <ide> n.cluster.config.Backend, <ide> n.cluster.config.PluginBackend, <ide> n.cluster.config.ImageBackend), <del> HeartbeatTick: 1, <del> ElectionTick: 3, <add> HeartbeatTick: 1, <add> // Recommended value in etcd/raft is 10 x (HeartbeatTick). <add> // Lower values were seen to have caused instability because of <add> // frequent leader elections when running on flakey networks. <add> ElectionTick: 10, <ide> UnlockKey: conf.lockKey, <ide> AutoLockManagers: conf.autolock, <ide> PluginGetter: n.cluster.config.Backend.PluginGetter(),
1
Text
Text
move 5 collaborators to emeritus status
7a687624b4b5c7de1a2a33944dc44df76723309a
<ide><path>README.md <ide> For more information about the governance of the Node.js project, see <ide> **Yuta Hiroto** &lt;[email protected]&gt; (he/him) <ide> * [iarna](https://github.com/iarna) - <ide> **Rebecca Turner** &lt;[email protected]&gt; <del>* [imran-iq](https://github.com/imran-iq) - <del>**Imran Iqbal** &lt;[email protected]&gt; <ide> * [imyller](https://github.com/imyller) - <ide> **Ilkka Myller** &lt;[email protected]&gt; <ide> * [indutny](https://github.com/indutny) - <ide> For more information about the governance of the Node.js project, see <ide> **Matteo Collina** &lt;[email protected]&gt; (he/him) <ide> * [mhdawson](https://github.com/mhdawson) - <ide> **Michael Dawson** &lt;[email protected]&gt; (he/him) <del>* [micnic](https://github.com/micnic) - <del>**Nicu Micleușanu** &lt;[email protected]&gt; (he/him) <ide> * [misterdjules](https://github.com/misterdjules) - <ide> **Julien Gilli** &lt;[email protected]&gt; <ide> * [mmarchini](https://github.com/mmarchini) - <ide> For more information about the governance of the Node.js project, see <ide> **Refael Ackermann** &lt;[email protected]&gt; (he/him) <ide> * [richardlau](https://github.com/richardlau) - <ide> **Richard Lau** &lt;[email protected]&gt; <del>* [rmg](https://github.com/rmg) - <del>**Ryan Graham** &lt;[email protected]&gt; <del>* [robertkowalski](https://github.com/robertkowalski) - <del>**Robert Kowalski** &lt;[email protected]&gt; <del>* [romankl](https://github.com/romankl) - <del>**Roman Klauke** &lt;[email protected]&gt; <ide> * [ronkorving](https://github.com/ronkorving) - <ide> **Ron Korving** &lt;[email protected]&gt; <ide> * [RReverser](https://github.com/RReverser) - <ide> For more information about the governance of the Node.js project, see <ide> <ide> ### Collaborator Emeriti <ide> <add>* [imran-iq](https://github.com/imran-iq) - <add>**Imran Iqbal** &lt;[email protected]&gt; <ide> * [isaacs](https://github.com/isaacs) - <ide> **Isaac Z. Schlueter** &lt;[email protected]&gt; <ide> * [lxe](https://github.com/lxe) - <ide> **Aleksey Smolenchuk** &lt;[email protected]&gt; <ide> * [matthewloring](https://github.com/matthewloring) - <ide> **Matthew Loring** &lt;[email protected]&gt; <add>* [micnic](https://github.com/micnic) - <add>**Nicu Micleușanu** &lt;[email protected]&gt; (he/him) <ide> * [mikeal](https://github.com/mikeal) - <ide> **Mikeal Rogers** &lt;[email protected]&gt; <ide> * [monsanto](https://github.com/monsanto) - <ide> For more information about the governance of the Node.js project, see <ide> **Bert Belder** &lt;[email protected]&gt; <ide> * [rlidwka](https://github.com/rlidwka) - <ide> **Alex Kocharin** &lt;[email protected]&gt; <add>* [rmg](https://github.com/rmg) - <add>**Ryan Graham** &lt;[email protected]&gt; <add>* [robertkowalski](https://github.com/robertkowalski) - <add>**Robert Kowalski** &lt;[email protected]&gt; <add>* [romankl](https://github.com/romankl) - <add>**Roman Klauke** &lt;[email protected]&gt; <ide> * [tellnes](https://github.com/tellnes) - <ide> **Christian Tellnes** &lt;[email protected]&gt; <ide> * [tunniclm](https://github.com/tunniclm) -
1
Javascript
Javascript
fix email and refactor
58b883f06c8b0c6dd90e1302545a956ca7affea6
<ide><path>server/boot/certificate.js <ide> function sendCertifiedEmail( <ide> const notifyUser = { <ide> type: 'email', <ide> to: email, <del> from: '[email protected]', <del> subject: dedent`Congratulations on completing all of the <del> freeCodeCamp certificates!`, <add> from: '[email protected]', <add> subject: dedent` <add> Congratulations on completing all of the <add> freeCodeCamp certificates! <add> `, <ide> text: renderCertifedEmail({ <ide> username, <ide> name <ide> export default function certificate(app) { <ide> if (user.name === '') { <ide> return res.status(200).send( <ide> dedent` <del> We need your name so we can put it on your certificate. <add> We need your name so we can put it on your certificate. <ide> <a href="https://github.com/settings/profile">Add your <ide> name to your GitHub account</a>, then go to your <ide> <a href="https://www.freecodecamp.org/settings">settings
1
Javascript
Javascript
remove unnecessary bind
454757438670585d172c0c2129959daa7fcf25a2
<ide><path>lib/perf_hooks.js <ide> function getObserversList(type) { <ide> return list; <ide> } <ide> <del>function doNotify() { <del> this[kQueued] = false; <del> this.runInAsyncScope(this[kCallback], this, this[kBuffer], this); <del> this[kBuffer][kEntries] = []; <del> L.init(this[kBuffer][kEntries]); <add>function doNotify(observer) { <add> observer[kQueued] = false; <add> observer.runInAsyncScope(observer[kCallback], <add> observer, <add> observer[kBuffer], <add> observer); <add> observer[kBuffer][kEntries] = []; <add> L.init(observer[kBuffer][kEntries]); <ide> } <ide> <ide> // Set up the callback used to receive PerformanceObserver notifications <ide> function observersCallback(entry) { <ide> observer[kQueued] = true; <ide> // Use setImmediate instead of nextTick to give more time <ide> // for multiple entries to collect. <del> setImmediate(doNotify.bind(observer)); <add> setImmediate(doNotify, observer); <ide> } <ide> } else { <ide> // If not buffering, notify immediately <del> doNotify.call(observer); <add> doNotify(observer); <ide> } <ide> current = current._idlePrev; <ide> }
1
Python
Python
fix bugs in pep 3118 format string parsing
204efabe8d40e0ff8b7e81518476eb5253e4d09d
<ide><path>numpy/core/_internal.py <ide> def _dtype_from_pep3118(spec, byteorder='@', is_subdtype=False): <ide> # Not supported <ide> raise ValueError("Non item-size 1 structures not supported") <ide> elif spec[0] in type_map_chars: <del> j = 1 <del> for j in xrange(1, len(spec)): <del> if spec[j] not in type_map_chars: <del> break <add> if spec[0] == 'Z': <add> j = 2 <add> else: <add> j = 1 <ide> typechar = spec[:j] <ide> spec = spec[j:] <ide> is_padding = (typechar == 'x') <ide> def _dtype_from_pep3118(spec, byteorder='@', is_subdtype=False): <ide> # that the start of the array is *also* aligned. <ide> extra_offset = 0 <ide> if byteorder == '@': <del> start_padding = offset % value.alignment <del> intra_padding = value.itemsize % value.alignment <add> start_padding = (-offset) % value.alignment <add> intra_padding = (-value.itemsize) % value.alignment <ide> <ide> offset += start_padding <ide> <ide><path>numpy/core/tests/test_multiarray.py <ide> def test_export_endian(self): <ide> else: <ide> assert_equal(y.format, '<i') <ide> <add> def test_padding(self): <add> for j in xrange(8): <add> x = np.array([(1,),(2,)], dtype={'f0': (int, j)}) <add> self._check_roundtrip(x) <add> <ide> if __name__ == "__main__": <ide> run_module_suite()
2
Go
Go
fix some typos
34b82a69b94ef9c7913e2809ae918e6f4331201e
<ide><path>profiles/apparmor/apparmor.go <ide> func InstallDefault(name string) error { <ide> return nil <ide> } <ide> <del>// IsLoaded checks if a passed profile as been loaded into the kernel. <add>// IsLoaded checks if a passed profile has been loaded into the kernel. <ide> func IsLoaded(name string) error { <ide> file, err := os.Open("/sys/kernel/security/apparmor/profiles") <ide> if err != nil { <ide><path>profiles/seccomp/seccomp.go <ide> func GetDefaultProfile() (*configs.Seccomp, error) { <ide> return setupSeccomp(DefaultProfile) <ide> } <ide> <del>// LoadProfile takes a file path a decodes the seccomp profile. <add>// LoadProfile takes a file path and decodes the seccomp profile. <ide> func LoadProfile(body string) (*configs.Seccomp, error) { <ide> var config types.Seccomp <ide> if err := json.Unmarshal([]byte(body), &config); err != nil { <ide><path>registry/service.go <ide> func (s *Service) tlsConfigForMirror(mirrorURL *url.URL) (*tls.Config, error) { <ide> return s.TLSConfig(mirrorURL.Host) <ide> } <ide> <del>// LookupPullEndpoints creates an list of endpoints to try to pull from, in order of preference. <add>// LookupPullEndpoints creates a list of endpoints to try to pull from, in order of preference. <ide> // It gives preference to v2 endpoints over v1, mirrors over the actual <ide> // registry, and HTTPS over plain HTTP. <ide> func (s *Service) LookupPullEndpoints(hostname string) (endpoints []APIEndpoint, err error) { <ide> return s.lookupEndpoints(hostname) <ide> } <ide> <del>// LookupPushEndpoints creates an list of endpoints to try to push to, in order of preference. <add>// LookupPushEndpoints creates a list of endpoints to try to push to, in order of preference. <ide> // It gives preference to v2 endpoints over v1, and HTTPS over plain HTTP. <ide> // Mirrors are not included. <ide> func (s *Service) LookupPushEndpoints(hostname string) (endpoints []APIEndpoint, err error) { <ide><path>runconfig/config_unix.go <ide> import ( <ide> networktypes "github.com/docker/engine-api/types/network" <ide> ) <ide> <del>// ContainerConfigWrapper is a Config wrapper that hold the container Config (portable) <add>// ContainerConfigWrapper is a Config wrapper that holds the container Config (portable) <ide> // and the corresponding HostConfig (non-portable). <ide> type ContainerConfigWrapper struct { <ide> *container.Config <ide><path>runconfig/config_windows.go <ide> import ( <ide> networktypes "github.com/docker/engine-api/types/network" <ide> ) <ide> <del>// ContainerConfigWrapper is a Config wrapper that hold the container Config (portable) <add>// ContainerConfigWrapper is a Config wrapper that holds the container Config (portable) <ide> // and the corresponding HostConfig (non-portable). <ide> type ContainerConfigWrapper struct { <ide> *container.Config <ide><path>volume/drivers/extpoint.go <ide> func Register(extension volume.Driver, name string) bool { <ide> return true <ide> } <ide> <del>// Unregister dissociates the name from it's driver, if the association exists. <add>// Unregister dissociates the name from its driver, if the association exists. <ide> func Unregister(name string) bool { <ide> drivers.Lock() <ide> defer drivers.Unlock() <ide> func Lookup(name string) (volume.Driver, error) { <ide> return d, nil <ide> } <ide> <del>// GetDriver returns a volume driver by it's name. <add>// GetDriver returns a volume driver by its name. <ide> // If the driver is empty, it looks for the local driver. <ide> func GetDriver(name string) (volume.Driver, error) { <ide> if name == "" { <ide><path>volume/store/store.go <ide> type VolumeStore struct { <ide> } <ide> <ide> // List proxies to all registered volume drivers to get the full list of volumes <del>// If a driver returns a volume that has name which conflicts with a another volume from a different driver, <add>// If a driver returns a volume that has name which conflicts with another volume from a different driver, <ide> // the first volume is chosen and the conflicting volume is dropped. <ide> func (s *VolumeStore) List() ([]volume.Volume, []string, error) { <ide> vols, warnings, err := s.list() <ide> func (s *VolumeStore) Get(name string) (volume.Volume, error) { <ide> return v, nil <ide> } <ide> <del>// get requests the volume, if the driver info is stored it just access that driver, <add>// getVolume requests the volume, if the driver info is stored it just accesses that driver, <ide> // if the driver is unknown it probes all drivers until it finds the first volume with that name. <ide> // it is expected that callers of this function hold any necessary locks <ide> func (s *VolumeStore) getVolume(name string) (volume.Volume, error) { <ide><path>volume/volume.go <ide> func (m *MountPoint) Path() string { <ide> return m.Source <ide> } <ide> <del>// ParseVolumesFrom ensure that the supplied volumes-from is valid. <add>// ParseVolumesFrom ensures that the supplied volumes-from is valid. <ide> func ParseVolumesFrom(spec string) (string, string, error) { <ide> if len(spec) == 0 { <ide> return "", "", fmt.Errorf("malformed volumes-from specification: %s", spec) <ide><path>volume/volume_propagation_linux.go <ide> func GetPropagation(mode string) string { <ide> } <ide> <ide> // HasPropagation checks if there is a valid propagation mode present in <del>// passed string. Returns true if a valid propagatio mode specifier is <add>// passed string. Returns true if a valid propagation mode specifier is <ide> // present, false otherwise. <ide> func HasPropagation(mode string) bool { <ide> for _, o := range strings.Split(mode, ",") { <ide><path>volume/volume_propagation_unsupported.go <ide> func GetPropagation(mode string) string { <ide> } <ide> <ide> // HasPropagation checks if there is a valid propagation mode present in <del>// passed string. Returns true if a valid propagatio mode specifier is <add>// passed string. Returns true if a valid propagation mode specifier is <ide> // present, false otherwise. <ide> func HasPropagation(mode string) bool { <ide> return false <ide><path>volume/volume_unix.go <ide> func ValidMountMode(mode string) bool { <ide> <ide> // ReadWrite tells you if a mode string is a valid read-write mode or not. <ide> // If there are no specifications w.r.t read write mode, then by default <del>// it returs true. <add>// it returns true. <ide> func ReadWrite(mode string) bool { <ide> if !ValidMountMode(mode) { <ide> return false
11
PHP
PHP
fix cs error
dd12292cc8f83052d8c36412d77805ab311419a2
<ide><path>tests/TestCase/Http/ClientTest.php <ide> public function testGetSimpleWithHeadersAndCookies() <ide> 'split' => 'value', <ide> ]; <ide> <del> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream') <add> $mock = $this->getMockBuilder(Stream::class) <ide> ->setMethods(['send']) <ide> ->getMock(); <ide> $mock->expects($this->once()) <ide> public function testGetNoData() <ide> { <ide> $response = new Response(); <ide> <del> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream') <add> $mock = $this->getMockBuilder(Stream::class) <ide> ->setMethods(['send']) <ide> ->getMock(); <ide> $mock->expects($this->once()) <ide> public function testGetQuerystring() <ide> { <ide> $response = new Response(); <ide> <del> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream') <add> $mock = $this->getMockBuilder(Stream::class) <ide> ->setMethods(['send']) <ide> ->getMock(); <ide> $mock->expects($this->once()) <ide> public function testGetQuerystringString() <ide> { <ide> $response = new Response(); <ide> <del> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream') <add> $mock = $this->getMockBuilder(Stream::class) <ide> ->setMethods(['send']) <ide> ->getMock(); <ide> $mock->expects($this->once()) <ide> public function testGetWithContent() <ide> { <ide> $response = new Response(); <ide> <del> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream') <add> $mock = $this->getMockBuilder(Stream::class) <ide> ->setMethods(['send']) <ide> ->getMock(); <ide> $mock->expects($this->once()) <ide> public function testGetWithContent() <ide> public function testInvalidAuthenticationType() <ide> { <ide> $this->expectException(\Cake\Core\Exception\Exception::class); <del> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream') <add> $mock = $this->getMockBuilder(Stream::class) <ide> ->setMethods(['send']) <ide> ->getMock(); <ide> $mock->expects($this->never()) <ide> public function testGetWithAuthenticationAndProxy() <ide> { <ide> $response = new Response(); <ide> <del> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream') <add> $mock = $this->getMockBuilder(Stream::class) <ide> ->setMethods(['send']) <ide> ->getMock(); <ide> $headers = [ <ide> public function testMethodsSimple($method) <ide> { <ide> $response = new Response(); <ide> <del> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream') <add> $mock = $this->getMockBuilder(Stream::class) <ide> ->setMethods(['send']) <ide> ->getMock(); <ide> $mock->expects($this->once()) <ide> public function testPostWithTypeKey($type, $mime) <ide> 'Accept' => $mime, <ide> ]; <ide> <del> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream') <add> $mock = $this->getMockBuilder(Stream::class) <ide> ->setMethods(['send']) <ide> ->getMock(); <ide> $mock->expects($this->once()) <ide> public function testPostWithStringDataDefaultsToFormEncoding() <ide> $response = new Response(); <ide> $data = 'some=value&more=data'; <ide> <del> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream') <add> $mock = $this->getMockBuilder(Stream::class) <ide> ->setMethods(['send']) <ide> ->getMock(); <ide> $mock->expects($this->any()) <ide> public function testPostWithStringDataDefaultsToFormEncoding() <ide> public function testExceptionOnUnknownType() <ide> { <ide> $this->expectException(\Cake\Core\Exception\Exception::class); <del> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream') <add> $mock = $this->getMockBuilder(Stream::class) <ide> ->setMethods(['send']) <ide> ->getMock(); <ide> $mock->expects($this->never()) <ide> public function testExceptionOnUnknownType() <ide> */ <ide> public function testCookieStorage() <ide> { <del> $adapter = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream') <add> $adapter = $this->getMockBuilder(Stream::class) <ide> ->setMethods(['send']) <ide> ->getMock(); <ide> <ide> public function testHeadQuerystring() <ide> { <ide> $response = new Response(); <ide> <del> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream') <add> $mock = $this->getMockBuilder(Stream::class) <ide> ->setMethods(['send']) <ide> ->getMock(); <ide> $mock->expects($this->once()) <ide> public function testSendRequest() <ide> 'Content-Type' => 'application/x-www-form-urlencoded', <ide> ]; <ide> <del> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream') <add> $mock = $this->getMockBuilder(Stream::class) <ide> ->setMethods(['send']) <ide> ->getMock(); <ide> $mock->expects($this->once())
1
Python
Python
fix wrong checkpoint paths in doc examples
16870d114b652954bb0ccf069ad7433a93ac06fb
<ide><path>src/transformers/models/big_bird/modeling_big_bird.py <ide> def forward( <ide> >>> from transformers import BigBirdTokenizer, BigBirdForPreTraining <ide> >>> import torch <ide> <del> >>> tokenizer = BigBirdTokenizer.from_pretrained('bigbird-roberta-base') <del> >>> model = BigBirdForPreTraining.from_pretrained('bigbird-roberta-base') <add> >>> tokenizer = BigBirdTokenizer.from_pretrained('google/bigbird-roberta-base') <add> >>> model = BigBirdForPreTraining.from_pretrained('google/bigbird-roberta-base') <ide> <ide> >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") <ide> >>> outputs = model(**inputs) <ide> def forward( <ide> >>> import torch <ide> <ide> >>> tokenizer = BigBirdTokenizer.from_pretrained('google/bigbird-roberta-base') <del> >>> config = BigBirdConfig.from_pretrained("google/bigbird-base") <add> >>> config = BigBirdConfig.from_pretrained("google/bigbird-roberta-base") <ide> >>> config.is_decoder = True <ide> >>> model = BigBirdForCausalLM.from_pretrained('google/bigbird-roberta-base', config=config) <ide> <ide><path>src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py <ide> def dummy_inputs(self): <ide> <ide> >>> from transformers import PegasusTokenizer, BigBirdPegasusForConditionalGeneration, BigBirdPegasusConfig <ide> <del> >>> model = BigBirdPegasusForConditionalGeneration.from_pretrained('bigbird-pegasus-large-arxiv') <del> >>> tokenizer = PegasusTokenizer.from_pretrained('bigbird-pegasus-large-arxiv') <add> >>> model = BigBirdPegasusForConditionalGeneration.from_pretrained('google/bigbird-pegasus-large-arxiv') <add> >>> tokenizer = PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv') <ide> <ide> >>> ARTICLE_TO_SUMMARIZE = "My friends are cool but they eat too many carbs." <ide> >>> inputs = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=4096, return_tensors='pt', truncation=True) <ide><path>src/transformers/models/rembert/modeling_rembert.py <ide> def forward( <ide> >>> from transformers import RemBertTokenizer, RemBertForCausalLM, RemBertConfig <ide> >>> import torch <ide> <del> >>> tokenizer = RemBertTokenizer.from_pretrained('rembert') <del> >>> config = RemBertConfig.from_pretrained("rembert") <add> >>> tokenizer = RemBertTokenizer.from_pretrained('google/rembert') <add> >>> config = RemBertConfig.from_pretrained("google/rembert") <ide> >>> config.is_decoder = True <del> >>> model = RemBertForCausalLM.from_pretrained('rembert', config=config) <add> >>> model = RemBertForCausalLM.from_pretrained('google/rembert', config=config) <ide> <ide> >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") <ide> >>> outputs = model(**inputs) <ide><path>src/transformers/models/segformer/modeling_segformer.py <ide> def forward(self, pixel_values, output_attentions=None, output_hidden_states=Non <ide> >>> from PIL import Image <ide> >>> import requests <ide> <del> >>> feature_extractor = SegformerFeatureExtractor.from_pretrained("nvidia/segformer-b0") <del> >>> model = SegformerModel("nvidia/segformer-b0") <add> >>> feature_extractor = SegformerFeatureExtractor.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512") <add> >>> model = SegformerModel("nvidia/segformer-b0-finetuned-ade-512-512") <ide> <ide> >>> url = 'http://images.cocodataset.org/val2017/000000039769.jpg' <ide> >>> image = Image.open(requests.get(url, stream=True).raw) <ide> def forward( <ide> >>> import requests <ide> <ide> >>> feature_extractor = SegformerFeatureExtractor.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512") <del> >>> model = SegformerForSemanticSegmentation("nvidia/segformer-b0-finetuned-ade-512-512") <add> >>> model = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512") <ide> <ide> >>> url = 'http://images.cocodataset.org/val2017/000000039769.jpg' <ide> >>> image = Image.open(requests.get(url, stream=True).raw)
4
Javascript
Javascript
add unstable prefix to experimental apis
fe7163e73dadceda2655736d97cdd745d7abc8ea
<ide><path>fixtures/blocks/src/server/App.block.js <ide> /* eslint-disable import/first */ <ide> <ide> import * as React from 'react'; <del>import {block} from 'react'; <add>import {unstable_block as block} from 'react'; <ide> <ide> // Server <ide> <ide><path>fixtures/dom/src/__tests__/wrong-act-test.js <ide> it("doesn't warn if you use nested acts from different renderers", () => { <ide> <ide> if (__EXPERIMENTAL__) { <ide> it('warns when using createRoot() + .render', () => { <del> const root = ReactDOM.createRoot(document.createElement('div')); <add> const root = ReactDOM.unstable_createRoot(document.createElement('div')); <ide> expect(() => { <ide> TestRenderer.act(() => { <ide> root.render(<App />); <ide><path>packages/react-debug-tools/src/__tests__/ReactHooksInspectionIntegration-test.js <ide> describe('ReactHooksInspectionIntegration', () => { <ide> ]); <ide> }); <ide> <del> if (__EXPERIMENTAL__) { <del> it('should support composite useTransition hook', () => { <del> function Foo(props) { <del> React.useTransition(); <del> const memoizedValue = React.useMemo(() => 'hello', []); <del> return <div>{memoizedValue}</div>; <del> } <del> const renderer = ReactTestRenderer.create(<Foo />); <del> const childFiber = renderer.root.findByType(Foo)._currentFiber(); <del> const tree = ReactDebugTools.inspectHooksOfFiber(childFiber); <del> expect(tree).toEqual([ <del> { <del> id: 0, <del> isStateEditable: false, <del> name: 'Transition', <del> value: undefined, <del> subHooks: [], <del> }, <del> { <del> id: 1, <del> isStateEditable: false, <del> name: 'Memo', <del> value: 'hello', <del> subHooks: [], <del> }, <del> ]); <del> }); <del> <del> it('should support composite useDeferredValue hook', () => { <del> function Foo(props) { <del> React.useDeferredValue('abc', { <del> timeoutMs: 500, <del> }); <del> const [state] = React.useState(() => 'hello', []); <del> return <div>{state}</div>; <del> } <del> const renderer = ReactTestRenderer.create(<Foo />); <del> const childFiber = renderer.root.findByType(Foo)._currentFiber(); <del> const tree = ReactDebugTools.inspectHooksOfFiber(childFiber); <del> expect(tree).toEqual([ <del> { <del> id: 0, <del> isStateEditable: false, <del> name: 'DeferredValue', <del> value: 'abc', <del> subHooks: [], <del> }, <del> { <del> id: 1, <del> isStateEditable: true, <del> name: 'State', <del> value: 'hello', <del> subHooks: [], <del> }, <del> ]); <del> }); <del> <del> it('should support composite useOpaqueIdentifier hook', () => { <del> function Foo(props) { <del> const id = React.unstable_useOpaqueIdentifier(); <del> const [state] = React.useState(() => 'hello', []); <del> return <div id={id}>{state}</div>; <del> } <del> <del> const renderer = ReactTestRenderer.create(<Foo />); <del> const childFiber = renderer.root.findByType(Foo)._currentFiber(); <del> const tree = ReactDebugTools.inspectHooksOfFiber(childFiber); <del> <del> expect(tree.length).toEqual(2); <del> <del> expect(tree[0].id).toEqual(0); <del> expect(tree[0].isStateEditable).toEqual(false); <del> expect(tree[0].name).toEqual('OpaqueIdentifier'); <del> expect((tree[0].value + '').startsWith('c_')).toBe(true); <add> // @gate experimental <add> it('should support composite useTransition hook', () => { <add> function Foo(props) { <add> React.unstable_useTransition(); <add> const memoizedValue = React.useMemo(() => 'hello', []); <add> return <div>{memoizedValue}</div>; <add> } <add> const renderer = ReactTestRenderer.create(<Foo />); <add> const childFiber = renderer.root.findByType(Foo)._currentFiber(); <add> const tree = ReactDebugTools.inspectHooksOfFiber(childFiber); <add> expect(tree).toEqual([ <add> { <add> id: 0, <add> isStateEditable: false, <add> name: 'Transition', <add> value: undefined, <add> subHooks: [], <add> }, <add> { <add> id: 1, <add> isStateEditable: false, <add> name: 'Memo', <add> value: 'hello', <add> subHooks: [], <add> }, <add> ]); <add> }); <ide> <del> expect(tree[1]).toEqual({ <add> // @gate experimental <add> it('should support composite useDeferredValue hook', () => { <add> function Foo(props) { <add> React.unstable_useDeferredValue('abc', { <add> timeoutMs: 500, <add> }); <add> const [state] = React.useState(() => 'hello', []); <add> return <div>{state}</div>; <add> } <add> const renderer = ReactTestRenderer.create(<Foo />); <add> const childFiber = renderer.root.findByType(Foo)._currentFiber(); <add> const tree = ReactDebugTools.inspectHooksOfFiber(childFiber); <add> expect(tree).toEqual([ <add> { <add> id: 0, <add> isStateEditable: false, <add> name: 'DeferredValue', <add> value: 'abc', <add> subHooks: [], <add> }, <add> { <ide> id: 1, <ide> isStateEditable: true, <ide> name: 'State', <ide> value: 'hello', <ide> subHooks: [], <del> }); <add> }, <add> ]); <add> }); <add> <add> // @gate experimental <add> it('should support composite useOpaqueIdentifier hook', () => { <add> function Foo(props) { <add> const id = React.unstable_useOpaqueIdentifier(); <add> const [state] = React.useState(() => 'hello', []); <add> return <div id={id}>{state}</div>; <add> } <add> <add> const renderer = ReactTestRenderer.create(<Foo />); <add> const childFiber = renderer.root.findByType(Foo)._currentFiber(); <add> const tree = ReactDebugTools.inspectHooksOfFiber(childFiber); <add> <add> expect(tree.length).toEqual(2); <add> <add> expect(tree[0].id).toEqual(0); <add> expect(tree[0].isStateEditable).toEqual(false); <add> expect(tree[0].name).toEqual('OpaqueIdentifier'); <add> expect((tree[0].value + '').startsWith('c_')).toBe(true); <add> <add> expect(tree[1]).toEqual({ <add> id: 1, <add> isStateEditable: true, <add> name: 'State', <add> value: 'hello', <add> subHooks: [], <ide> }); <add> }); <ide> <del> it('should support composite useOpaqueIdentifier hook in concurrent mode', () => { <del> function Foo(props) { <del> const id = React.unstable_useOpaqueIdentifier(); <del> const [state] = React.useState(() => 'hello', []); <del> return <div id={id}>{state}</div>; <del> } <add> // @gate experimental <add> it('should support composite useOpaqueIdentifier hook in concurrent mode', () => { <add> function Foo(props) { <add> const id = React.unstable_useOpaqueIdentifier(); <add> const [state] = React.useState(() => 'hello', []); <add> return <div id={id}>{state}</div>; <add> } <ide> <del> const renderer = ReactTestRenderer.create(<Foo />, { <del> unstable_isConcurrent: true, <del> }); <del> expect(Scheduler).toFlushWithoutYielding(); <add> const renderer = ReactTestRenderer.create(<Foo />, { <add> unstable_isConcurrent: true, <add> }); <add> expect(Scheduler).toFlushWithoutYielding(); <ide> <del> const childFiber = renderer.root.findByType(Foo)._currentFiber(); <del> const tree = ReactDebugTools.inspectHooksOfFiber(childFiber); <add> const childFiber = renderer.root.findByType(Foo)._currentFiber(); <add> const tree = ReactDebugTools.inspectHooksOfFiber(childFiber); <ide> <del> expect(tree.length).toEqual(2); <add> expect(tree.length).toEqual(2); <ide> <del> expect(tree[0].id).toEqual(0); <del> expect(tree[0].isStateEditable).toEqual(false); <del> expect(tree[0].name).toEqual('OpaqueIdentifier'); <del> expect((tree[0].value + '').startsWith('c_')).toBe(true); <add> expect(tree[0].id).toEqual(0); <add> expect(tree[0].isStateEditable).toEqual(false); <add> expect(tree[0].name).toEqual('OpaqueIdentifier'); <add> expect((tree[0].value + '').startsWith('c_')).toBe(true); <ide> <del> expect(tree[1]).toEqual({ <del> id: 1, <del> isStateEditable: true, <del> name: 'State', <del> value: 'hello', <del> subHooks: [], <del> }); <add> expect(tree[1]).toEqual({ <add> id: 1, <add> isStateEditable: true, <add> name: 'State', <add> value: 'hello', <add> subHooks: [], <ide> }); <del> } <add> }); <ide> <ide> describe('useDebugValue', () => { <ide> it('should support inspectable values for multiple custom hooks', () => { <ide><path>packages/react-devtools-shared/src/__tests__/store-test.js <ide> describe('Store', () => { <ide> }; <ide> const Wrapper = ({shouldSuspense}) => ( <ide> <React.Fragment> <del> <React.SuspenseList revealOrder="forwards" tail="collapsed"> <add> <React.unstable_SuspenseList revealOrder="forwards" tail="collapsed"> <ide> <Component key="A" /> <ide> <React.Suspense fallback={<Loading />}> <ide> {shouldSuspense ? <SuspendingComponent /> : <Component key="B" />} <ide> </React.Suspense> <ide> <Component key="C" /> <del> </React.SuspenseList> <add> </React.unstable_SuspenseList> <ide> </React.Fragment> <ide> ); <ide> <ide> const container = document.createElement('div'); <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> act(() => { <ide> root.render(<Wrapper shouldSuspense={true} />); <ide> }); <ide><path>packages/react-devtools-shared/src/__tests__/storeStressTestConcurrent-test.js <ide> describe('StoreStressConcurrent', () => { <ide> // 1. Render a normal version of [a, b, c, d, e]. <ide> let container = document.createElement('div'); <ide> // $FlowFixMe <del> let root = ReactDOM.createRoot(container); <add> let root = ReactDOM.unstable_createRoot(container); <ide> act(() => root.render(<Parent>{[a, b, c, d, e]}</Parent>)); <ide> expect(store).toMatchInlineSnapshot( <ide> ` <ide> describe('StoreStressConcurrent', () => { <ide> // Ensure fresh mount. <ide> container = document.createElement('div'); <ide> // $FlowFixMe <del> root = ReactDOM.createRoot(container); <add> root = ReactDOM.unstable_createRoot(container); <ide> <ide> // Verify mounting 'abcde'. <ide> act(() => root.render(<Parent>{cases[i]}</Parent>)); <ide> describe('StoreStressConcurrent', () => { <ide> // There'll be no unmounting until the very end. <ide> container = document.createElement('div'); <ide> // $FlowFixMe <del> root = ReactDOM.createRoot(container); <add> root = ReactDOM.unstable_createRoot(container); <ide> for (let i = 0; i < cases.length; i++) { <ide> // Verify mounting 'abcde'. <ide> act(() => root.render(<Parent>{cases[i]}</Parent>)); <ide> describe('StoreStressConcurrent', () => { <ide> const snapshots = []; <ide> let container = document.createElement('div'); <ide> // $FlowFixMe <del> let root = ReactDOM.createRoot(container); <add> let root = ReactDOM.unstable_createRoot(container); <ide> for (let i = 0; i < steps.length; i++) { <ide> act(() => root.render(<Root>{steps[i]}</Root>)); <ide> // We snapshot each step once so it doesn't regress. <ide> describe('StoreStressConcurrent', () => { <ide> for (let j = 0; j < steps.length; j++) { <ide> container = document.createElement('div'); <ide> // $FlowFixMe <del> root = ReactDOM.createRoot(container); <add> root = ReactDOM.unstable_createRoot(container); <ide> act(() => root.render(<Root>{steps[i]}</Root>)); <ide> expect(print(store)).toMatch(snapshots[i]); <ide> act(() => root.render(<Root>{steps[j]}</Root>)); <ide> describe('StoreStressConcurrent', () => { <ide> for (let j = 0; j < steps.length; j++) { <ide> container = document.createElement('div'); <ide> // $FlowFixMe <del> root = ReactDOM.createRoot(container); <add> root = ReactDOM.unstable_createRoot(container); <ide> act(() => <ide> root.render( <ide> <Root> <ide> describe('StoreStressConcurrent', () => { <ide> const snapshots = []; <ide> let container = document.createElement('div'); <ide> // $FlowFixMe <del> let root = ReactDOM.createRoot(container); <add> let root = ReactDOM.unstable_createRoot(container); <ide> for (let i = 0; i < steps.length; i++) { <ide> act(() => <ide> root.render( <ide> describe('StoreStressConcurrent', () => { <ide> // Always start with a fresh container and steps[i]. <ide> container = document.createElement('div'); <ide> // $FlowFixMe <del> root = ReactDOM.createRoot(container); <add> root = ReactDOM.unstable_createRoot(container); <ide> act(() => <ide> root.render( <ide> <Root> <ide> describe('StoreStressConcurrent', () => { <ide> // Always start with a fresh container and steps[i]. <ide> container = document.createElement('div'); <ide> // $FlowFixMe <del> root = ReactDOM.createRoot(container); <add> root = ReactDOM.unstable_createRoot(container); <ide> act(() => <ide> root.render( <ide> <Root> <ide> describe('StoreStressConcurrent', () => { <ide> // Always start with a fresh container and steps[i]. <ide> container = document.createElement('div'); <ide> // $FlowFixMe <del> root = ReactDOM.createRoot(container); <add> root = ReactDOM.unstable_createRoot(container); <ide> act(() => <ide> root.render( <ide> <Root> <ide> describe('StoreStressConcurrent', () => { <ide> // Always start with a fresh container and steps[i]. <ide> container = document.createElement('div'); <ide> // $FlowFixMe <del> root = ReactDOM.createRoot(container); <add> root = ReactDOM.unstable_createRoot(container); <ide> act(() => <ide> root.render( <ide> <Root> <ide> describe('StoreStressConcurrent', () => { <ide> // Always start with a fresh container and steps[i]. <ide> container = document.createElement('div'); <ide> // $FlowFixMe <del> root = ReactDOM.createRoot(container); <add> root = ReactDOM.unstable_createRoot(container); <ide> act(() => <ide> root.render( <ide> <Root> <ide> describe('StoreStressConcurrent', () => { <ide> const snapshots = []; <ide> let container = document.createElement('div'); <ide> // $FlowFixMe <del> let root = ReactDOM.createRoot(container); <add> let root = ReactDOM.unstable_createRoot(container); <ide> for (let i = 0; i < steps.length; i++) { <ide> act(() => <ide> root.render( <ide> describe('StoreStressConcurrent', () => { <ide> // Always start with a fresh container and steps[i]. <ide> container = document.createElement('div'); <ide> // $FlowFixMe <del> root = ReactDOM.createRoot(container); <add> root = ReactDOM.unstable_createRoot(container); <ide> act(() => <ide> root.render( <ide> <Root> <ide> describe('StoreStressConcurrent', () => { <ide> // Always start with a fresh container and steps[i]. <ide> container = document.createElement('div'); <ide> // $FlowFixMe <del> root = ReactDOM.createRoot(container); <add> root = ReactDOM.unstable_createRoot(container); <ide> act(() => <ide> root.render( <ide> <Root> <ide> describe('StoreStressConcurrent', () => { <ide> // Always start with a fresh container and steps[i]. <ide> container = document.createElement('div'); <ide> // $FlowFixMe <del> root = ReactDOM.createRoot(container); <add> root = ReactDOM.unstable_createRoot(container); <ide> act(() => <ide> root.render( <ide> <Root> <ide> describe('StoreStressConcurrent', () => { <ide> // Always start with a fresh container and steps[i]. <ide> container = document.createElement('div'); <ide> // $FlowFixMe <del> root = ReactDOM.createRoot(container); <add> root = ReactDOM.unstable_createRoot(container); <ide> act(() => <ide> root.render( <ide> <Root> <ide> describe('StoreStressConcurrent', () => { <ide> // Always start with a fresh container and steps[i]. <ide> container = document.createElement('div'); <ide> // $FlowFixMe <del> root = ReactDOM.createRoot(container); <add> root = ReactDOM.unstable_createRoot(container); <ide> act(() => <ide> root.render( <ide> <Root> <ide><path>packages/react-dom/index.classic.fb.js <ide> export { <ide> render, <ide> unmountComponentAtNode, <ide> createRoot, <add> createRoot as unstable_createRoot, <ide> createBlockingRoot, <add> createBlockingRoot as unstable_createBlockingRoot, <ide> unstable_flushControlled, <ide> unstable_scheduleHydration, <ide> unstable_renderSubtreeIntoContainer, <ide><path>packages/react-dom/index.experimental.js <ide> export { <ide> render, <ide> unmountComponentAtNode, <ide> // exposeConcurrentModeAPIs <del> createRoot, <del> createBlockingRoot, <add> createRoot as unstable_createRoot, <add> createBlockingRoot as unstable_createBlockingRoot, <ide> unstable_flushControlled, <ide> unstable_scheduleHydration, <ide> // Disabled behind disableUnstableRenderSubtreeIntoContainer <ide><path>packages/react-dom/index.js <ide> * @flow <ide> */ <ide> <del>export * from './src/client/ReactDOM'; <add>// Export all exports so that they're available in tests. <add>// We can't use export * from in Flow for some reason. <add>export { <add> createPortal, <add> unstable_batchedUpdates, <add> flushSync, <add> __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, <add> version, <add> findDOMNode, <add> hydrate, <add> render, <add> unmountComponentAtNode, <add> createRoot, <add> createRoot as unstable_createRoot, <add> createBlockingRoot, <add> createBlockingRoot as unstable_createBlockingRoot, <add> unstable_flushControlled, <add> unstable_scheduleHydration, <add> unstable_renderSubtreeIntoContainer, <add> unstable_createPortal, <add>} from './src/client/ReactDOM'; <ide><path>packages/react-dom/index.modern.fb.js <ide> export { <ide> __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, <ide> version, <ide> createRoot, <add> createRoot as unstable_createRoot, <ide> createBlockingRoot, <add> createBlockingRoot as unstable_createBlockingRoot, <ide> unstable_flushControlled, <ide> unstable_scheduleHydration, <ide> } from './src/client/ReactDOM'; <ide><path>packages/react-dom/src/__tests__/ReactDOMFiberAsync-test.js <ide> describe('ReactDOMFiberAsync', () => { <ide> ); <ide> } <ide> } <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<Counter />); <ide> Scheduler.unstable_flushAll(); <ide> expect(asyncValueRef.current.textContent).toBe(''); <ide> describe('ReactDOMFiberAsync', () => { <ide> <ide> // @gate experimental <ide> it('top-level updates are concurrent', () => { <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<div>Hi</div>); <ide> expect(container.textContent).toEqual(''); <ide> Scheduler.unstable_flushAll(); <ide> describe('ReactDOMFiberAsync', () => { <ide> } <ide> } <ide> <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<Component />); <ide> expect(container.textContent).toEqual(''); <ide> Scheduler.unstable_flushAll(); <ide> describe('ReactDOMFiberAsync', () => { <ide> } <ide> } <ide> <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<Component />); <ide> Scheduler.unstable_flushAll(); <ide> <ide> describe('ReactDOMFiberAsync', () => { <ide> return this.state.counter; <ide> } <ide> } <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<Counter />); <ide> Scheduler.unstable_flushAll(); <ide> expect(container.textContent).toEqual('0'); <ide> describe('ReactDOMFiberAsync', () => { <ide> } <ide> } <ide> <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<Form />); <ide> // Flush <ide> Scheduler.unstable_flushAll(); <ide> describe('ReactDOMFiberAsync', () => { <ide> } <ide> } <ide> <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<Form />); <ide> // Flush <ide> Scheduler.unstable_flushAll(); <ide> describe('ReactDOMFiberAsync', () => { <ide> } <ide> } <ide> <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<Form />); <ide> // Flush <ide> Scheduler.unstable_flushAll(); <ide> describe('ReactDOMFiberAsync', () => { <ide> describe('createBlockingRoot', () => { <ide> // @gate experimental <ide> it('updates flush without yielding in the next event', () => { <del> const root = ReactDOM.createBlockingRoot(container); <add> const root = ReactDOM.unstable_createBlockingRoot(container); <ide> <ide> function Text(props) { <ide> Scheduler.unstable_yieldValue(props.text); <ide> describe('ReactDOMFiberAsync', () => { <ide> return <button ref={ref}>new</button>; <ide> } <ide> <del> const oldRoot = ReactDOM.createRoot(container); <add> const oldRoot = ReactDOM.unstable_createRoot(container); <ide> act(() => { <ide> oldRoot.render(<OldApp />); <ide> }); <ide> describe('ReactDOMFiberAsync', () => { <ide> expect(container.textContent).toBe(''); <ide> <ide> // We can now render a new one. <del> const newRoot = ReactDOM.createRoot(container); <add> const newRoot = ReactDOM.unstable_createRoot(container); <ide> ReactDOM.flushSync(() => { <ide> newRoot.render(<NewApp />); <ide> }); <ide><path>packages/react-dom/src/__tests__/ReactDOMHooks-test.js <ide> describe('ReactDOMHooks', () => { <ide> const inputRef = createRef(); <ide> const labelRef = createRef(); <ide> <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<Example inputRef={inputRef} labelRef={labelRef} />); <ide> <ide> Scheduler.unstable_flushAll(); <ide><path>packages/react-dom/src/__tests__/ReactDOMRoot-test.js <ide> describe('ReactDOMRoot', () => { <ide> <ide> if (!__EXPERIMENTAL__) { <ide> it('createRoot is not exposed in stable build', () => { <del> expect(ReactDOM.createRoot).toBe(undefined); <add> expect(ReactDOM.unstable_createRoot).toBe(undefined); <ide> }); <ide> return; <ide> } <ide> <ide> it('renders children', () => { <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<div>Hi</div>); <ide> Scheduler.unstable_flushAll(); <ide> expect(container.textContent).toEqual('Hi'); <ide> }); <ide> <ide> it('warns if a callback parameter is provided to render', () => { <ide> const callback = jest.fn(); <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> expect(() => <ide> root.render(<div>Hi</div>, callback), <ide> ).toErrorDev( <ide> describe('ReactDOMRoot', () => { <ide> <ide> it('warns if a callback parameter is provided to unmount', () => { <ide> const callback = jest.fn(); <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<div>Hi</div>); <ide> expect(() => <ide> root.unmount(callback), <ide> describe('ReactDOMRoot', () => { <ide> }); <ide> <ide> it('unmounts children', () => { <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<div>Hi</div>); <ide> Scheduler.unstable_flushAll(); <ide> expect(container.textContent).toEqual('Hi'); <ide> describe('ReactDOMRoot', () => { <ide> // Does not hydrate by default <ide> const container1 = document.createElement('div'); <ide> container1.innerHTML = markup; <del> const root1 = ReactDOM.createRoot(container1); <add> const root1 = ReactDOM.unstable_createRoot(container1); <ide> root1.render( <ide> <div> <ide> <span /> <ide> describe('ReactDOMRoot', () => { <ide> // Accepts `hydrate` option <ide> const container2 = document.createElement('div'); <ide> container2.innerHTML = markup; <del> const root2 = ReactDOM.createRoot(container2, {hydrate: true}); <add> const root2 = ReactDOM.unstable_createRoot(container2, {hydrate: true}); <ide> root2.render( <ide> <div> <ide> <span /> <ide> describe('ReactDOMRoot', () => { <ide> <ide> it('clears existing children', async () => { <ide> container.innerHTML = '<div>a</div><div>b</div>'; <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render( <ide> <div> <ide> <span>c</span> <ide> describe('ReactDOMRoot', () => { <ide> <ide> it('throws a good message on invalid containers', () => { <ide> expect(() => { <del> ReactDOM.createRoot(<div>Hi</div>); <add> ReactDOM.unstable_createRoot(<div>Hi</div>); <ide> }).toThrow('createRoot(...): Target container is not a DOM element.'); <ide> }); <ide> <ide> it('warns when rendering with legacy API into createRoot() container', () => { <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<div>Hi</div>); <ide> Scheduler.unstable_flushAll(); <ide> expect(container.textContent).toEqual('Hi'); <ide> describe('ReactDOMRoot', () => { <ide> }); <ide> <ide> it('warns when hydrating with legacy API into createRoot() container', () => { <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<div>Hi</div>); <ide> Scheduler.unstable_flushAll(); <ide> expect(container.textContent).toEqual('Hi'); <ide> describe('ReactDOMRoot', () => { <ide> }); <ide> <ide> it('warns when unmounting with legacy API (no previous content)', () => { <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<div>Hi</div>); <ide> Scheduler.unstable_flushAll(); <ide> expect(container.textContent).toEqual('Hi'); <ide> describe('ReactDOMRoot', () => { <ide> // Currently createRoot().render() doesn't clear this. <ide> container.appendChild(document.createElement('div')); <ide> // The rest is the same as test above. <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<div>Hi</div>); <ide> Scheduler.unstable_flushAll(); <ide> expect(container.textContent).toEqual('Hi'); <ide> describe('ReactDOMRoot', () => { <ide> it('warns when passing legacy container to createRoot()', () => { <ide> ReactDOM.render(<div>Hi</div>, container); <ide> expect(() => { <del> ReactDOM.createRoot(container); <add> ReactDOM.unstable_createRoot(container); <ide> }).toErrorDev( <ide> 'You are calling ReactDOM.createRoot() on a container that was previously ' + <ide> 'passed to ReactDOM.render(). This is not supported.', <ide> describe('ReactDOMRoot', () => { <ide> }); <ide> <ide> it('warns when creating two roots managing the same container', () => { <del> ReactDOM.createRoot(container); <add> ReactDOM.unstable_createRoot(container); <ide> expect(() => { <del> ReactDOM.createRoot(container); <add> ReactDOM.unstable_createRoot(container); <ide> }).toErrorDev( <ide> 'You are calling ReactDOM.createRoot() on a container that ' + <ide> 'has already been passed to createRoot() before. Instead, call ' + <ide> describe('ReactDOMRoot', () => { <ide> }); <ide> <ide> it('does not warn when creating second root after first one is unmounted', () => { <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.unmount(); <ide> Scheduler.unstable_flushAll(); <del> ReactDOM.createRoot(container); // No warning <add> ReactDOM.unstable_createRoot(container); // No warning <ide> }); <ide> <ide> it('warns if creating a root on the document.body', async () => { <ide> expect(() => { <del> ReactDOM.createRoot(document.body); <add> ReactDOM.unstable_createRoot(document.body); <ide> }).toErrorDev( <ide> 'createRoot(): Creating roots directly with document.body is ' + <ide> 'discouraged, since its children are often manipulated by third-party ' + <ide> describe('ReactDOMRoot', () => { <ide> }); <ide> <ide> it('warns if updating a root that has had its contents removed', async () => { <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<div>Hi</div>); <ide> Scheduler.unstable_flushAll(); <ide> container.innerHTML = ''; <ide><path>packages/react-dom/src/__tests__/ReactDOMServerIntegrationHooks-test.js <ide> describe('ReactDOMServerHooks', () => { <ide> document.body.append(container); <ide> <ide> container.innerHTML = ReactDOMServer.renderToString(<App />); <del> const root = ReactDOM.createRoot(container, {hydrate: true}); <add> const root = ReactDOM.unstable_createRoot(container, {hydrate: true}); <ide> root.render(<App />); <ide> Scheduler.unstable_flushAll(); <ide> jest.runAllTimers(); <ide> describe('ReactDOMServerHooks', () => { <ide> const container = document.createElement('div'); <ide> document.body.append(container); <ide> container.innerHTML = ReactDOMServer.renderToString(<App />); <del> const root = ReactDOM.createRoot(container, {hydrate: true}); <add> const root = ReactDOM.unstable_createRoot(container, {hydrate: true}); <ide> ReactTestUtils.act(() => { <ide> root.render(<App />); <ide> }); <ide> describe('ReactDOMServerHooks', () => { <ide> const container = document.createElement('div'); <ide> document.body.append(container); <ide> container.innerHTML = ReactDOMServer.renderToString(<App />); <del> const root = ReactDOM.createRoot(container, {hydrate: true}); <add> const root = ReactDOM.unstable_createRoot(container, {hydrate: true}); <ide> ReactTestUtils.act(() => { <ide> root.render(<App />); <ide> }); <ide> describe('ReactDOMServerHooks', () => { <ide> <ide> const childOneSpan = container.getElementsByTagName('span')[0]; <ide> <del> const root = ReactDOM.createRoot(container, {hydrate: true}); <add> const root = ReactDOM.unstable_createRoot(container, {hydrate: true}); <ide> root.render(<App show={false} />); <ide> expect(Scheduler).toHaveYielded([]); <ide> <ide> describe('ReactDOMServerHooks', () => { <ide> container.innerHTML = ReactDOMServer.renderToString(<App />); <ide> <ide> suspend = true; <del> const root = ReactDOM.createRoot(container, {hydrate: true}); <add> const root = ReactDOM.unstable_createRoot(container, {hydrate: true}); <ide> await ReactTestUtils.act(async () => { <ide> root.render(<App />); <ide> }); <ide> describe('ReactDOMServerHooks', () => { <ide> <ide> // This is the wrong HTML string <ide> container.innerHTML = '<span></span>'; <del> ReactDOM.createRoot(container, {hydrate: true}).render(<App />); <add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render( <add> <App />, <add> ); <ide> expect(() => <ide> expect(() => Scheduler.unstable_flushAll()).toThrow(), <ide> ).toErrorDev([ <ide> describe('ReactDOMServerHooks', () => { <ide> container.innerHTML = ReactDOMServer.renderToString(<App />); <ide> <ide> suspend = false; <del> const root = ReactDOM.createRoot(container, {hydrate: true}); <add> const root = ReactDOM.unstable_createRoot(container, {hydrate: true}); <ide> await ReactTestUtils.act(async () => { <ide> root.render(<App />); <ide> }); <ide> describe('ReactDOMServerHooks', () => { <ide> <ide> // This is the wrong HTML string <ide> container.innerHTML = '<span></span>'; <del> ReactDOM.createRoot(container, {hydrate: true}).render(<App />); <add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render( <add> <App />, <add> ); <ide> expect(() => <ide> expect(() => Scheduler.unstable_flushAll()).toThrow(), <ide> ).toErrorDev([ <ide> describe('ReactDOMServerHooks', () => { <ide> <ide> // This is the wrong HTML string <ide> container.innerHTML = '<span></span>'; <del> ReactDOM.createRoot(container, {hydrate: true}).render(<App />); <add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render( <add> <App />, <add> ); <ide> expect(() => <ide> expect(() => Scheduler.unstable_flushAll()).toThrow( <ide> 'The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. ' + <ide> describe('ReactDOMServerHooks', () => { <ide> <ide> // This is the wrong HTML string <ide> container.innerHTML = '<span></span>'; <del> ReactDOM.createRoot(container, {hydrate: true}).render(<App />); <add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render( <add> <App />, <add> ); <ide> expect(() => <ide> expect(() => Scheduler.unstable_flushAll()).toThrow( <ide> 'The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. ' + <ide> describe('ReactDOMServerHooks', () => { <ide> document.body.appendChild(container); <ide> <ide> container.innerHTML = ReactDOMServer.renderToString(<App />); <del> ReactDOM.createRoot(container, {hydrate: true}).render(<App />); <add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render( <add> <App />, <add> ); <ide> expect(() => <ide> expect(() => Scheduler.unstable_flushAll()).toThrow( <ide> 'The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. ' + <ide> describe('ReactDOMServerHooks', () => { <ide> document.body.appendChild(container); <ide> <ide> container.innerHTML = ReactDOMServer.renderToString(<App />); <del> ReactDOM.createRoot(container, {hydrate: true}).render(<App />); <add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render( <add> <App />, <add> ); <ide> expect(() => <ide> expect(() => Scheduler.unstable_flushAll()).toThrow( <ide> 'The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. ' + <ide> describe('ReactDOMServerHooks', () => { <ide> <ide> container.innerHTML = ReactDOMServer.renderToString(<App />); <ide> <del> ReactDOM.createRoot(container, {hydrate: true}).render(<App />); <add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render( <add> <App />, <add> ); <ide> <ide> if (gate(flags => flags.new)) { <ide> expect(() => Scheduler.unstable_flushAll()).toErrorDev([ <ide> describe('ReactDOMServerHooks', () => { <ide> <ide> container.innerHTML = ReactDOMServer.renderToString(<App />); <ide> <del> ReactDOM.createRoot(container, {hydrate: true}).render(<App />); <add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render( <add> <App />, <add> ); <ide> <ide> if (gate(flags => flags.new)) { <ide> expect(() => Scheduler.unstable_flushAll()).toErrorDev([ <ide> describe('ReactDOMServerHooks', () => { <ide> .getAttribute('aria-labelledby'), <ide> ).toEqual(serverID); <ide> <del> ReactDOM.createRoot(container, {hydrate: true}).render(<App />); <add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render( <add> <App />, <add> ); <ide> jest.runAllTimers(); <ide> expect(Scheduler).toHaveYielded([]); <ide> expect(Scheduler).toFlushAndYield([]); <ide><path>packages/react-dom/src/__tests__/ReactServerRenderingHydration-test.js <ide> describe('ReactDOMServerHydration', () => { <ide> const finalHTML = ReactDOMServer.renderToString(<div />); <ide> const container = document.createElement('div'); <ide> container.innerHTML = finalHTML; <del> const root = ReactDOM.createRoot(container, {hydrate: true}); <add> const root = ReactDOM.unstable_createRoot(container, {hydrate: true}); <ide> root.render(<div />); <ide> Scheduler.unstable_flushAll(); <ide> root.render(null); <ide><path>packages/react-dom/src/__tests__/ReactTestUtilsAct-test.js <ide> describe('ReactTestUtils.act()', () => { <ide> if (__EXPERIMENTAL__) { <ide> let concurrentRoot = null; <ide> const renderConcurrent = (el, dom) => { <del> concurrentRoot = ReactDOM.createRoot(dom); <add> concurrentRoot = ReactDOM.unstable_createRoot(dom); <ide> concurrentRoot.render(el); <ide> }; <ide> <ide> describe('ReactTestUtils.act()', () => { <ide> if (__EXPERIMENTAL__) { <ide> let blockingRoot = null; <ide> const renderBatched = (el, dom) => { <del> blockingRoot = ReactDOM.createBlockingRoot(dom); <add> blockingRoot = ReactDOM.unstable_createBlockingRoot(dom); <ide> blockingRoot.render(el); <ide> }; <ide> <ide> describe('ReactTestUtils.act()', () => { <ide> // @gate experimental <ide> it('warns in blocking mode', () => { <ide> expect(() => { <del> const root = ReactDOM.createBlockingRoot(document.createElement('div')); <add> const root = ReactDOM.unstable_createBlockingRoot( <add> document.createElement('div'), <add> ); <ide> root.render(<App />); <ide> Scheduler.unstable_flushAll(); <ide> }).toErrorDev([ <ide> describe('ReactTestUtils.act()', () => { <ide> // @gate experimental <ide> it('warns in concurrent mode', () => { <ide> expect(() => { <del> const root = ReactDOM.createRoot(document.createElement('div')); <add> const root = ReactDOM.unstable_createRoot( <add> document.createElement('div'), <add> ); <ide> root.render(<App />); <ide> Scheduler.unstable_flushAll(); <ide> }).toErrorDev([ <ide><path>packages/react-dom/src/__tests__/ReactUnmockedSchedulerWarning-test.js <ide> it('does not warn when rendering in legacy mode', () => { <ide> // @gate experimental <ide> it('should warn when rendering in concurrent mode', () => { <ide> expect(() => { <del> ReactDOM.createRoot(document.createElement('div')).render(<App />); <add> ReactDOM.unstable_createRoot(document.createElement('div')).render(<App />); <ide> }).toErrorDev( <ide> 'In Concurrent or Sync modes, the "scheduler" module needs to be mocked ' + <ide> 'to guarantee consistent behaviour across tests and browsers.', <ide> {withoutStack: true}, <ide> ); <ide> // does not warn twice <ide> expect(() => { <del> ReactDOM.createRoot(document.createElement('div')).render(<App />); <add> ReactDOM.unstable_createRoot(document.createElement('div')).render(<App />); <ide> }).toErrorDev([]); <ide> }); <ide> <ide> // @gate experimental <ide> it('should warn when rendering in blocking mode', () => { <ide> expect(() => { <del> ReactDOM.createBlockingRoot(document.createElement('div')).render(<App />); <add> ReactDOM.unstable_createBlockingRoot(document.createElement('div')).render( <add> <App />, <add> ); <ide> }).toErrorDev( <ide> 'In Concurrent or Sync modes, the "scheduler" module needs to be mocked ' + <ide> 'to guarantee consistent behaviour across tests and browsers.', <ide> {withoutStack: true}, <ide> ); <ide> // does not warn twice <ide> expect(() => { <del> ReactDOM.createBlockingRoot(document.createElement('div')).render(<App />); <add> ReactDOM.unstable_createBlockingRoot(document.createElement('div')).render( <add> <App />, <add> ); <ide> }).toErrorDev([]); <ide> }); <ide><path>packages/react-dom/src/__tests__/ReactUpdates-test.js <ide> describe('ReactUpdates', () => { <ide> ); <ide> } <ide> <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> let hiddenDiv; <ide> act(() => { <ide> root.render(<Foo />); <ide><path>packages/react-dom/src/events/plugins/__tests__/LegacyChangeEventPlugin-test.js <ide> describe('ChangeEventPlugin', () => { <ide> <ide> // @gate experimental <ide> it('text input', () => { <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> let input; <ide> <ide> class ControlledInput extends React.Component { <ide> describe('ChangeEventPlugin', () => { <ide> <ide> // @gate experimental <ide> it('checkbox input', () => { <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> let input; <ide> <ide> class ControlledInput extends React.Component { <ide> describe('ChangeEventPlugin', () => { <ide> <ide> // @gate experimental <ide> it('textarea', () => { <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> let textarea; <ide> <ide> class ControlledTextarea extends React.Component { <ide> describe('ChangeEventPlugin', () => { <ide> <ide> // @gate experimental <ide> it('parent of input', () => { <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> let input; <ide> <ide> class ControlledInput extends React.Component { <ide> describe('ChangeEventPlugin', () => { <ide> <ide> // @gate experimental <ide> it('is async for non-input events', () => { <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> let input; <ide> <ide> class ControlledInput extends React.Component { <ide> describe('ChangeEventPlugin', () => { <ide> const {act} = TestUtils; <ide> const {useState} = React; <ide> <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> <ide> const target = React.createRef(null); <ide> function Foo() { <ide><path>packages/react-dom/src/events/plugins/__tests__/LegacySimpleEventPlugin-test.js <ide> describe('SimpleEventPlugin', function() { <ide> // @gate experimental <ide> it('flushes pending interactive work before extracting event handler', () => { <ide> container = document.createElement('div'); <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> document.body.appendChild(container); <ide> <ide> let button; <ide> describe('SimpleEventPlugin', function() { <ide> // @gate experimental <ide> it('end result of many interactive updates is deterministic', () => { <ide> container = document.createElement('div'); <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> document.body.appendChild(container); <ide> <ide> let button; <ide> describe('SimpleEventPlugin', function() { <ide> } <ide> <ide> // Initial mount <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<Wrapper />); <ide> expect(Scheduler).toFlushAndYield([ <ide> 'High-pri count: 0, Low-pri count: 0', <ide><path>packages/react-reconciler/src/__tests__/ReactBlocks-test.js <ide> describe('ReactBlocks', () => { <ide> React = require('react'); <ide> ReactNoop = require('react-noop-renderer'); <ide> <del> block = React.block; <add> block = React.unstable_block; <ide> useState = React.useState; <ide> Suspense = React.Suspense; <ide> const cache = new Map(); <ide><path>packages/react-reconciler/src/__tests__/ReactHooksWithNoopRenderer-test.js <ide> describe('ReactHooksWithNoopRenderer', () => { <ide> useImperativeHandle = React.useImperativeHandle; <ide> forwardRef = React.forwardRef; <ide> memo = React.memo; <del> useTransition = React.useTransition; <del> useDeferredValue = React.useDeferredValue; <add> useTransition = React.unstable_useTransition; <add> useDeferredValue = React.unstable_useDeferredValue; <ide> Suspense = React.Suspense; <ide> act = ReactNoop.act; <ide> <ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseList-test.js <ide> describe('ReactSuspenseList', () => { <ide> ReactNoop = require('react-noop-renderer'); <ide> Scheduler = require('scheduler'); <ide> Suspense = React.Suspense; <del> SuspenseList = React.SuspenseList; <add> SuspenseList = React.unstable_SuspenseList; <ide> }); <ide> <ide> function Text(props) { <ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseWithNoopRenderer-test.js <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> <ide> function App() { <ide> const [page, setPage] = React.useState('A'); <del> const [startLoading, isLoading] = React.useTransition(SUSPENSE_CONFIG); <add> const [startLoading, isLoading] = React.unstable_useTransition( <add> SUSPENSE_CONFIG, <add> ); <ide> transitionToPage = nextPage => startLoading(() => setPage(nextPage)); <ide> return ( <ide> <Fragment> <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> <ide> // @gate experimental <ide> it('regression: ping at high priority causes update to be dropped', async () => { <del> const {useState, useTransition} = React; <add> const {useState, unstable_useTransition: useTransition} = React; <ide> <ide> let setTextA; <ide> function A() { <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> let setTextWithLongTransition; <ide> <ide> function App() { <del> const [startShortTransition, isPending1] = React.useTransition({ <add> const [startShortTransition, isPending1] = React.unstable_useTransition({ <ide> timeoutMs: 5000, <ide> }); <del> const [startLongTransition, isPending2] = React.useTransition({ <add> const [startLongTransition, isPending2] = React.unstable_useTransition({ <ide> timeoutMs: 30000, <ide> }); <ide> const isPending = isPending1 || isPending2; <ide><path>packages/react-reconciler/src/__tests__/ReactTransition-test.js <ide> describe('ReactTransition', () => { <ide> ReactNoop = require('react-noop-renderer'); <ide> Scheduler = require('scheduler'); <ide> useState = React.useState; <del> useTransition = React.useTransition; <add> useTransition = React.unstable_useTransition; <ide> Suspense = React.Suspense; <ide> act = ReactNoop.act; <ide> }); <ide><path>packages/react-refresh/src/__tests__/ReactFresh-test.js <ide> describe('ReactFresh', () => { <ide> }; <ide> }); <ide> <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<AppV1 offscreen={true} />); <ide> expect(Scheduler).toFlushAndYieldThrough(['App#layout']); <ide> const el = container.firstChild; <ide><path>packages/react-transport-dom-webpack/src/__tests__/ReactFlightDOM-test.js <ide> describe('ReactFlightDOM', () => { <ide> const response = ReactTransportDOMClient.createFromReadableStream(readable); <ide> <ide> const container = document.createElement('div'); <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> await act(async () => { <ide> root.render(<App response={response} />); <ide> }); <ide> describe('ReactFlightDOM', () => { <ide> const response = ReactTransportDOMClient.createFromReadableStream(readable); <ide> <ide> const container = document.createElement('div'); <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> await act(async () => { <ide> root.render(<App response={response} />); <ide> }); <ide> describe('ReactFlightDOM', () => { <ide> const response = ReactTransportDOMClient.createFromReadableStream(readable); <ide> <ide> const container = document.createElement('div'); <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> await act(async () => { <ide> root.render(<App response={response} />); <ide> }); <ide> describe('ReactFlightDOM', () => { <ide> const response = ReactTransportDOMClient.createFromReadableStream(readable); <ide> <ide> const container = document.createElement('div'); <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> await act(async () => { <ide> root.render(<ProfilePage response={response} />); <ide> }); <ide><path>packages/react/index.classic.fb.js <ide> export { <ide> createFactory, <ide> // exposeConcurrentModeAPIs <ide> useTransition, <add> useTransition as unstable_useTransition, <ide> useDeferredValue, <add> useDeferredValue as unstable_useDeferredValue, <ide> SuspenseList, <add> SuspenseList as unstable_SuspenseList, <ide> unstable_withSuspenseConfig, <ide> // enableBlocksAPI <ide> block, <add> block as unstable_block, <ide> // enableDeprecatedFlareAPI <ide> DEPRECATED_useResponder, <ide> DEPRECATED_createResponder, <ide><path>packages/react/index.experimental.js <ide> export { <ide> __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, <ide> createFactory, <ide> // exposeConcurrentModeAPIs <del> useTransition, <del> useDeferredValue, <del> SuspenseList, <add> useTransition as unstable_useTransition, <add> useDeferredValue as unstable_useDeferredValue, <add> SuspenseList as unstable_SuspenseList, <ide> unstable_withSuspenseConfig, <ide> // enableBlocksAPI <del> block, <add> block as unstable_block, <ide> unstable_useOpaqueIdentifier, <ide> // enableDebugTracing <ide> unstable_DebugTracingMode, <ide><path>packages/react/index.js <ide> export { <ide> __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, <ide> createFactory, <ide> useTransition, <add> useTransition as unstable_useTransition, <ide> useDeferredValue, <add> useDeferredValue as unstable_useDeferredValue, <ide> SuspenseList, <add> SuspenseList as unstable_SuspenseList, <ide> unstable_withSuspenseConfig, <ide> block, <add> block as unstable_block, <ide> DEPRECATED_useResponder, <ide> DEPRECATED_createResponder, <ide> unstable_createFundamental, <ide><path>packages/react/index.modern.fb.js <ide> export { <ide> __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, <ide> // exposeConcurrentModeAPIs <ide> useTransition, <add> useTransition as unstable_useTransition, <ide> useDeferredValue, <add> useDeferredValue as unstable_useDeferredValue, <ide> SuspenseList, <add> SuspenseList as unstable_SuspenseList, <ide> unstable_withSuspenseConfig, <ide> // enableBlocksAPI <ide> block, <add> block as unstable_block, <ide> // enableDeprecatedFlareAPI <ide> DEPRECATED_useResponder, <ide> DEPRECATED_createResponder, <ide><path>packages/react/src/__tests__/ReactStrictMode-test.js <ide> describe('Concurrent Mode', () => { <ide> } <ide> <ide> const container = document.createElement('div'); <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<AsyncRoot />); <ide> expect(() => Scheduler.unstable_flushAll()).toErrorDev( <ide> [ <ide> Please update the following components: AsyncRoot`, <ide> } <ide> <ide> const container = document.createElement('div'); <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<AsyncRoot />); <ide> <ide> expect(() => { <ide> Please update the following components: Parent`, <ide> } <ide> <ide> const container = document.createElement('div'); <del> const root = ReactDOM.createRoot(container); <add> const root = ReactDOM.unstable_createRoot(container); <ide> root.render(<AsyncRoot foo={true} />); <ide> expect(() => <ide> Scheduler.unstable_flushAll(),
31
Javascript
Javascript
fix the vrmlloader `this` scope
770b4296c0f2ceca60632eed7f0b96c726524f1c
<ide><path>examples/js/loaders/VRMLLoader.js <ide> THREE.VRMLLoader.prototype = { <ide> <ide> parse: function ( data ) { <ide> <add> var scope = this; <ide> var texturePath = this.texturePath || ''; <ide> <ide> var textureLoader = new THREE.TextureLoader( this.manager ); <ide> THREE.VRMLLoader.prototype = { <ide> <ide> case 'skyAngle': <ide> case 'groundAngle': <del> this.recordingFieldname = fieldName; <del> this.isRecordingAngles = true; <del> this.angles = []; <add> scope.recordingFieldname = fieldName; <add> scope.isRecordingAngles = true; <add> scope.angles = []; <ide> break; <ide> <ide> case 'skyColor': <ide> case 'groundColor': <del> this.recordingFieldname = fieldName; <del> this.isRecordingColors = true; <del> this.colors = []; <add> scope.recordingFieldname = fieldName; <add> scope.isRecordingColors = true; <add> scope.colors = []; <ide> break; <ide> <ide> case 'point': <del> this.recordingFieldname = fieldName; <del> this.isRecordingPoints = true; <del> this.points = []; <add> scope.recordingFieldname = fieldName; <add> scope.isRecordingPoints = true; <add> scope.points = []; <ide> break; <ide> <ide> case 'coordIndex': <ide> case 'texCoordIndex': <del> this.recordingFieldname = fieldName; <del> this.isRecordingFaces = true; <del> this.indexes = []; <add> scope.recordingFieldname = fieldName; <add> scope.isRecordingFaces = true; <add> scope.indexes = []; <ide> break; <ide> <ide> } <ide> <del> if ( this.isRecordingFaces ) { <add> if ( scope.isRecordingFaces ) { <ide> <ide> // the parts hold the indexes as strings <ide> if ( parts.length > 0 ) { <ide> THREE.VRMLLoader.prototype = { <ide> <ide> if ( index.length > 0 ) { <ide> <del> this.indexes.push( index ); <add> scope.indexes.push( index ); <ide> <ide> } <ide> <ide> THREE.VRMLLoader.prototype = { <ide> <ide> if ( index.length > 0 ) { <ide> <del> this.indexes.push( index ); <add> scope.indexes.push( index ); <ide> <ide> } <ide> <ide> // start new one <ide> index = []; <ide> <del> this.isRecordingFaces = false; <del> node[ this.recordingFieldname ] = this.indexes; <add> scope.isRecordingFaces = false; <add> node[ scope.recordingFieldname ] = scope.indexes; <ide> <ide> } <ide> <del> } else if ( this.isRecordingPoints ) { <add> } else if ( scope.isRecordingPoints ) { <ide> <ide> if ( node.nodeType == 'Coordinate' ) { <ide> <ide> THREE.VRMLLoader.prototype = { <ide> z: parseFloat( parts[ 3 ] ) <ide> }; <ide> <del> this.points.push( point ); <add> scope.points.push( point ); <ide> <ide> } <ide> <ide> THREE.VRMLLoader.prototype = { <ide> y: parseFloat( parts[ 2 ] ) <ide> }; <ide> <del> this.points.push( point ); <add> scope.points.push( point ); <ide> <ide> } <ide> <ide> THREE.VRMLLoader.prototype = { <ide> // end <ide> if ( /]/.exec( line ) ) { <ide> <del> this.isRecordingPoints = false; <del> node.points = this.points; <add> scope.isRecordingPoints = false; <add> node.points = scope.points; <ide> <ide> } <ide> <del> } else if ( this.isRecordingAngles ) { <add> } else if ( scope.isRecordingAngles ) { <ide> <ide> // the parts hold the angles as strings <ide> if ( parts.length > 0 ) { <ide> THREE.VRMLLoader.prototype = { <ide> <ide> } <ide> <del> this.angles.push( parseFloat( parts[ ind ] ) ); <add> scope.angles.push( parseFloat( parts[ ind ] ) ); <ide> <ide> } <ide> <ide> THREE.VRMLLoader.prototype = { <ide> // end <ide> if ( /]/.exec( line ) ) { <ide> <del> this.isRecordingAngles = false; <del> node[ this.recordingFieldname ] = this.angles; <add> scope.isRecordingAngles = false; <add> node[ scope.recordingFieldname ] = scope.angles; <ide> <ide> } <ide> <del> } else if ( this.isRecordingColors ) { <add> } else if ( scope.isRecordingColors ) { <ide> <ide> while ( null !== ( parts = float3_pattern.exec( line ) ) ) { <ide> <ide> THREE.VRMLLoader.prototype = { <ide> b: parseFloat( parts[ 3 ] ) <ide> }; <ide> <del> this.colors.push( color ); <add> scope.colors.push( color ); <ide> <ide> } <ide> <ide> // end <ide> if ( /]/.exec( line ) ) { <ide> <del> this.isRecordingColors = false; <del> node[ this.recordingFieldname ] = this.colors; <add> scope.isRecordingColors = false; <add> node[ scope.recordingFieldname ] = scope.colors; <ide> <ide> } <ide>
1
Text
Text
add a note about downcasing submit tag
5d87bb4da8cce4687d83a81ac5bed07afa4f65b2
<ide><path>guides/source/5_0_release_notes.md <ide> Please refer to the [Changelog][action-view] for detailed changes. <ide> button on submit to prevent double submits. <ide> ([Pull Request](https://github.com/rails/rails/pull/21135)) <ide> <add>* Downcase model name in form submit tags rather than humanize. <add> ([Pull Request](https://github.com/rails/rails/pull/22764)) <add> <ide> <ide> Action Mailer <ide> -------------
1
Text
Text
add contributing.md file
9443dea4e5f50c14674fe92a11d70c8a8a8beae0
<ide><path>CONTRIBUTING.md <add># Contributing to Glances <add> <add>Looking to contribute something to Glances ? **Here's how you can help.** <add> <add>Please take a moment to review this document in order to make the contribution <add>process easy and effective for everyone involved. <add> <add>Following these guidelines helps to communicate that you respect the time of <add>the developers managing and developing this open source project. In return, <add>they should reciprocate that respect in addressing your issue or assessing <add>patches and features. <add> <add> <add>## Using the issue tracker <add> <add>The [issue tracker](https://github.com/nicolargos/glances/issues) is <add>the preferred channel for [bug reports](#bug-reports), [features requests](#feature-requests) <add>and [submitting pull requests](#pull-requests), but please respect the following <add>restrictions: <add> <add>* Please **do not** use the issue tracker for personal support requests. A official Q&A exist. [Use it](https://groups.google.com/forum/?hl=en#!forum/glances-users)! <add> <add>* Please **do not** derail or troll issues. Keep the discussion on topic and <add> respect the opinions of others. <add> <add> <add>## Bug reports <add> <add>A bug is a _demonstrable problem_ that is caused by the code in the repository. <add>Good bug reports are extremely helpful, so thanks! <add> <add>Guidelines for bug reports: <add> <add>0. **Use the GitHub issue search** &mdash; check if the issue has already been <add> reported. <add> <add>1. **Check if the issue has been fixed** &mdash; try to reproduce it using the <add> latest `master` or `develop` branch in the repository. <add> <add>2. **Isolate the problem** &mdash; ideally create a simple test bed. <add> <add>3. **Give us your test environment** &mdash; Operating system name and version <add> Glances version... <add> <add>Example: <add> <add>> Short and descriptive example bug report title <add>> <add>> A summary of the issue and the browser/OS environment in which it occurs. If <add>> suitable, include the steps required to reproduce the bug. <add>> <add>> 1. This is the first step <add>> 2. This is the second step <add>> 3. Further steps, etc. <add>> <add>> Screenshot (if usefull) <add>> <add>> Any other information you want to share that is relevant to the issue being <add>> reported. This might include the lines of code that you have identified as <add>> causing the bug, and potential solutions (and your opinions on their <add>> merits). <add> <add> <add>## Feature requests <add> <add>Feature requests are welcome. But take a moment to find out whether your idea <add>fits with the scope and aims of the project. It's up to *you* to make a strong <add>case to convince the project's developers of the merits of this feature. Please <add>provide as much detail and context as possible. <add> <add> <add>## Pull requests <add> <add>Good pull requests—patches, improvements, new features—are a fantastic <add>help. They should remain focused in scope and avoid containing unrelated <add>commits. <add> <add>**Please ask first** before embarking on any significant pull request (e.g. <add>implementing features, refactoring code, porting to a different language), <add>otherwise you risk spending a lot of time working on something that the <add>project's developers might not want to merge into the project. <add> <add>First of all, all pull request should be done on the `develop` branch. <add> <add>Glances uses PEP8 compatible code, so use a PEP validator before submitting <add>your pull request. Also uses the unitaries tests scripts (unitest.py). <add> <add>Similarly, when contributing to Glances's documentation, you should edit the <add>documentation source files in <add>[the `/doc/` and `/man/` directories of the `develop` branch](https://github.com/nicolargo/glances/tree/develop/docs). <add> <add>Adhering to the following process is the best way to get your work <add>included in the project: <add> <add>1. [Fork](https://help.github.com/fork-a-repo/) the project, clone your fork, <add> and configure the remotes: <add> <add> ```bash <add> # Clone your fork of the repo into the current directory <add> git clone https://github.com/<your-username>/glances.git <add> # Navigate to the newly cloned directory <add> cd glances <add> # Assign the original repo to a remote called "upstream" <add> git remote add upstream https://github.com/nicolargo/glances.git <add> ``` <add> <add>2. Get the latest changes from upstream: <add> <add> ```bash <add> git checkout develop <add> git pull upstream develop <add> ``` <add> <add>3. Create a new topic branch (off the main project development branch) to <add> contain your feature, change, or fix (best way is to call it issue#xxx): <add> <add> ```bash <add> git checkout -b <topic-branch-name> <add> ``` <add> <add>4. Commit your changes in logical chunks. Please adhere to these [git commit <add> message guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) <add> or your code is unlikely be merged into the main project. Use Git's <add> [interactive rebase](https://help.github.com/articles/interactive-rebase) <add> feature to tidy up your commits before making them public. <add> <add>5. Locally merge (or rebase) the upstream development branch into your topic branch: <add> <add> ```bash <add> git pull [--rebase] upstream develop <add> ``` <add> <add>6. Push your topic branch up to your fork: <add> <add> ```bash <add> git push origin <topic-branch-name> <add> ``` <add> <add>7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/) <add> with a clear title and description against the `develop` branch. <add> <add>**IMPORTANT**: By submitting a patch, you agree to allow the project owners to <add>license your work under the terms of the [LGPL](LICENSE) (if it <add>includes code changes).
1
PHP
PHP
remove unused imports
0dbd340ebb1a909c00c26d09a81fce93c2cfbffd
<ide><path>src/Illuminate/Mail/Mailer.php <ide> use Swift_Mailer; <ide> use Swift_Message; <ide> use Illuminate\Support\Arr; <del>use Illuminate\Support\Str; <del>use SuperClosure\Serializer; <ide> use InvalidArgumentException; <ide> use Illuminate\Contracts\View\Factory; <ide> use Illuminate\Contracts\Events\Dispatcher;
1
Ruby
Ruby
say something when running bundle commands
2561a1f546b304032b6d2702c59bdf5492990ba6
<ide><path>railties/lib/rails/generators/app_base.rb <ide> def gem_for_javascript <ide> end <ide> <ide> def bundle_command(command) <add> say_status :run, "bundle #{command}" <add> <ide> # We use backticks and #print here instead of vanilla #system because it <ide> # is easier to silence stdout in the existing test suite this way. The <ide> # end-user gets the bundler commands called anyway.
1
Javascript
Javascript
fix path in doctool/test-doctool-json
0048169f5e6d280ffd4efd9ce3812bb09ff7309e
<ide><path>test/doctool/test-doctool-json.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <del>// The doctool currently uses js-yaml from the tool/eslint/ tree. <add>// The doctool currently uses js-yaml from the tool/node_modules/eslint/ tree. <ide> try { <del> require('../../tools/eslint/node_modules/js-yaml'); <add> require('../../tools/node_modules/eslint/node_modules/js-yaml'); <ide> } catch (e) { <ide> common.skip('missing js-yaml (eslint not present)'); <ide> }
1
Text
Text
translate 10.2 to korean
bf6d9811e72b5a5d96f2c78d9e35da4543e3d24e
<ide><path>docs/docs/10.2-form-input-binding-sugar.ko-KR.md <add>--- <add>id: two-way-binding-helpers-ko-KR <add>title: 양방향 바인딩 핼퍼 <add>permalink: two-way-binding-helpers-ko-KR.html <add>prev: animation-ko-KR.html <add>next: class-name-manipulation-ko-KR.html <add>--- <add> <add>`ReactLink`는 React에서 양방향 바인딩을 표현하는 쉬운 방법입니다. <add> <add>> 주의: <add>> <add>> 프레임워크를 새로 접하신다면, 대부분의 애플리케이션에서 `ReactLink`는 필요없고 신중히 사용하셔야 함을 알려드립니다. <add> <add>React에서 데이터 흐름은 소유주에서 자식으로의 단방향입니다. 이는 [폰 노이만 컴퓨팅 모델](http://ko.wikipedia.org/wiki/%ED%8F%B0_%EB%85%B8%EC%9D%B4%EB%A7%8C_%EA%B5%AC%EC%A1%B0)의 데이터가 단방향으로 흐르기 때문입니다. 이것을 "단방향 데이터 바인딩"으로 생각하셔도 됩니다. <add> <add>하지만 많은 애플리케이션에서 데이터를 요청해서 프로그램으로 돌려줍니다. 예를 들어, 폼을 개발한다면, 사용자 입력을 받았을 때 `state`를 바꾸거나, JavaScript안에서 레이아웃을 바꾸고 그에 따라 어떤 DOM 엘리먼트의 크기를 바꾸게 하고 싶을 수도 있습니다. <add> <add>React에서 이는 "change" 이벤트를 감시하고 데이터 소스(보통 DOM)에서 읽어 컴포넌트에서 `setState()`를 호출하는 식으로 할 수 있습니다. "데이터 흐름 반복을 제한"하면 더 이해하기 편하고, 쉽게 유지보수할 수 있는 프로그램이 만들어지는 것은 명확합니다. 더 자세한 내용은 [폼 문서](/react/docs/forms-ko-KR.html)를 확인하세요. <add> <add>양방향 바인딩(묵시적으로 DOM의 어떤 값은 React `state`와 일치하도록 강제하는 것)은 간결하기도 하고 다양한 애플리케이션을 지원 할 수 있습니다. React는 `ReactLink`를 제공합니다. 이는 위에서 설명한 일반적인 데이터 흐름 반복 패턴을 설정하거나, 어떤 데이터 소스를 React `state`로 "링크하는" 편의 문법입니다. <add> <add>> 주의: <add>> <add>> ReactLink는 얇은 레퍼고 `onChange`/`setState()`패턴 부분의 관례일 뿐입니다. React 애플리케이션에서의 데이터 흐름을 근본적으로 바꾸지는 않습니다. <add> <add>## ReactLink: 적용 전후 <add> <add>`ReactLink`를 사용하지 않는 간단한 폼 예제입니다. <add> <add>```javascript <add>var NoLink = React.createClass({ <add> getInitialState: function() { <add> return {message: 'Hello!'}; <add> }, <add> handleChange: function(event) { <add> this.setState({message: event.target.value}); <add> }, <add> render: function() { <add> var message = this.state.message; <add> return <input type="text" value={message} onChange={this.handleChange} />; <add> } <add>}); <add>``` <add> <add>이것은 정말 잘 동작하고, 데이터가 어떻게 흐르는지 매우 명확하게 보여지지만, 폼필드가 많을 경우 약간 장황해 질 수 있습니다. 타이핑을 줄이기 위해 `ReactLink`를 사용해 보겠습니다. <add> <add>```javascript{2,7} <add>var WithLink = React.createClass({ <add> mixins: [React.addons.LinkedStateMixin], <add> getInitialState: function() { <add> return {message: 'Hello!'}; <add> }, <add> render: function() { <add> return <input type="text" valueLink={this.linkState('message')} />; <add> } <add>}); <add>``` <add> <add>`LinkedStateMixin`는 React 컴포넌트에 `linkState()`라는 메서드를 추가합니다. `linkState()`는 React state의 현재 값과 그것을 변경할 때의 콜백을 가지는 `ReactLink` 객체를 리턴합니다. <add> <add>`ReactLink` 객체는 props로 트리의 위나 아래로 넘길 수 있어서, 쉽고 명확하게 계층구조에서 깊이 있는 컴포넌트와 높이 있는 state 사이의 양방향 바인딩을 설정할 수 있습니다. <add> <add>checkbox의 `value` 어트리뷰트는 다른 것과 다르게 checkbox가 체크되었을 때 폼 submit에 값이 전달되는 것에 주의하세요.(기본값 `on`) 그래서 `value` 어트리뷰트는 checkbox가 체크되거나 해제될 때 업데이트되지 않습니다. checkbox에서는 `valueLink`대신 `checkedLink`를 사용하셔야 합니다. <add>``` <add><input type="checkbox" checkedLink={this.linkState('booleanValue')} /> <add>``` <add> <add> <add>## 내부 구조 <add> <add>`ReactLink`에는 크게 인스턴스를 생성하는 면과 사용하는 면이 있습니다. `ReactLink`가 얼마나 간단한지 확인하기위해, 이 부분들을 보다 명시적으로 고쳐 봅시다. <add> <add>### LinkedStateMixin 없이 ReactLink 쓰기 <add> <add>```javascript{5-7,9-12} <add>var WithoutMixin = React.createClass({ <add> getInitialState: function() { <add> return {message: 'Hello!'}; <add> }, <add> handleChange: function(newValue) { <add> this.setState({message: newValue}); <add> }, <add> render: function() { <add> var valueLink = { <add> value: this.state.message, <add> requestChange: this.handleChange <add> }; <add> return <input type="text" valueLink={valueLink} />; <add> } <add>}); <add>``` <add> <add>보시다시피, `ReactLink` 객체는 `value`와 `requestChange` prop만 가지는 매우 간단한 객체입니다. `LinkedStateMixin`도 간단합니다. 그냥 `this.state`의 값과 `this.setState()`에서 호출되는 콜백을 필드로 가질 뿐입니다. <add> <add>### valueLink 없이 ReactLink 쓰기 <add> <add>```javascript <add>var WithoutLink = React.createClass({ <add> mixins: [React.addons.LinkedStateMixin], <add> getInitialState: function() { <add> return {message: 'Hello!'}; <add> }, <add> render: function() { <add> var valueLink = this.linkState('message'); <add> var handleChange = function(e) { <add> valueLink.requestChange(e.target.value); <add> }; <add> return <input type="text" value={valueLink.value} onChange={handleChange} />; <add> } <add>}); <add>``` <add> <add>`valueLink` prop도 간단합니다. 단순히 `onChange` 이벤트를 처리하고 `this.props.valueLink.requestChange()`를 호출하고 `this.props.value`대신 `this.props.valueLink.value`를 사용합니다. 그게 다에요!
1
PHP
PHP
use di and contract instead of static method
a5ccc1302223042a2b5656da009e8e19aaf4e9df
<ide><path>src/Illuminate/Queue/CallQueuedHandler.php <ide> use Exception; <ide> use ReflectionClass; <ide> use Illuminate\Pipeline\Pipeline; <del>use Illuminate\Container\Container; <ide> use Illuminate\Contracts\Queue\Job; <ide> use Illuminate\Contracts\Bus\Dispatcher; <add>use Illuminate\Contracts\Container\Container; <ide> use Illuminate\Database\Eloquent\ModelNotFoundException; <ide> <ide> class CallQueuedHandler <ide> class CallQueuedHandler <ide> */ <ide> protected $dispatcher; <ide> <add> /** <add> * The container instance. <add> * <add> * @var \Illuminate\Contracts\Container\Container <add> */ <add> protected $container; <add> <ide> /** <ide> * Create a new handler instance. <ide> * <ide> * @param \Illuminate\Contracts\Bus\Dispatcher $dispatcher <add> * @param \Illuminate\Contracts\Container\Container $container <ide> * @return void <ide> */ <del> public function __construct(Dispatcher $dispatcher) <add> public function __construct(Dispatcher $dispatcher, Container $container) <ide> { <add> $this->container = $container; <ide> $this->dispatcher = $dispatcher; <ide> } <ide> <ide> public function call(Job $job, array $data) <ide> */ <ide> protected function dispatchThroughMiddleware(Job $job, $command) <ide> { <del> return (new Pipeline(Container::getInstance()))->send($command) <add> return (new Pipeline($this->container))->send($command) <ide> ->through(array_merge(method_exists($command, 'middleware') ? $command->middleware() : [], $command->middleware ?? [])) <ide> ->then(function ($command) use ($job) { <ide> return $this->dispatcher->dispatchNow( <ide><path>tests/Integration/Queue/CallQueuedHandlerTest.php <ide> public function testJobCanBeDispatched() <ide> { <ide> CallQueuedHandlerTestJob::$handled = false; <ide> <del> $instance = new CallQueuedHandler(new Dispatcher(app())); <add> $instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app); <ide> <ide> $job = m::mock(Job::class); <ide> $job->shouldReceive('hasFailed')->andReturn(false); <ide> public function testJobCanBeDispatchedThroughMiddleware() <ide> CallQueuedHandlerTestJobWithMiddleware::$handled = false; <ide> CallQueuedHandlerTestJobWithMiddleware::$middlewareCommand = null; <ide> <del> $instance = new CallQueuedHandler(new Dispatcher(app())); <add> $instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app); <ide> <ide> $job = m::mock(Job::class); <ide> $job->shouldReceive('hasFailed')->andReturn(false); <ide> public function testJobCanBeDispatchedThroughMiddlewareOnDispatch() <ide> CallQueuedHandlerTestJobWithMiddleware::$handled = false; <ide> CallQueuedHandlerTestJobWithMiddleware::$middlewareCommand = null; <ide> <del> $instance = new CallQueuedHandler(new Dispatcher(app())); <add> $instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app); <ide> <ide> $job = m::mock(Job::class); <ide> $job->shouldReceive('hasFailed')->andReturn(false); <ide> public function testJobCanBeDispatchedThroughMiddlewareOnDispatch() <ide> <ide> public function testJobIsMarkedAsFailedIfModelNotFoundExceptionIsThrown() <ide> { <del> $instance = new CallQueuedHandler(new Dispatcher(app())); <add> $instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app); <ide> <ide> $job = m::mock(Job::class); <ide> $job->shouldReceive('resolveName')->andReturn(__CLASS__); <ide> public function testJobIsDeletedIfHasDeleteProperty() <ide> { <ide> Event::fake(); <ide> <del> $instance = new CallQueuedHandler(new Dispatcher(app())); <add> $instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app); <ide> <ide> $job = m::mock(Job::class); <ide> $job->shouldReceive('getConnectionName')->andReturn('connection');
2
Text
Text
fix optionality of callback arg of checkprime
1ecc6c05405dc23473567e49df689e0e9aa78581
<ide><path>doc/api/crypto.md <ide> is currently in use. Setting to true requires a FIPS build of Node.js. <ide> This property is deprecated. Please use `crypto.setFips()` and <ide> `crypto.getFips()` instead. <ide> <del>### `crypto.checkPrime(candidate[, options[, callback]])` <add>### `crypto.checkPrime(candidate[, options], callback)` <ide> <ide> <!-- YAML <ide> added: v15.8.0
1
Ruby
Ruby
simplify console with helpers
d75a2345015046e08f8191748f0e246e1b9f9703
<ide><path>actionpack/lib/action_view/helpers.rb <ide> module ClassMethods <ide> include FormHelper <ide> include FormOptionsHelper <ide> include FormTagHelper <add> include JavaScriptHelper <ide> include NumberHelper <ide> include PrototypeHelper <ide> include RecordIdentificationHelper <ide><path>railties/lib/console_with_helpers.rb <del>class Module <del> def include_all_modules_from(parent_module) <del> parent_module.constants.each do |const| <del> mod = parent_module.const_get(const) <del> if mod.class == Module <del> send(:include, mod) <del> include_all_modules_from(mod) <del> end <del> end <del> end <del>end <del> <del>def helper(*helper_names) <del> returning @helper_proxy ||= Object.new do |helper| <del> helper_names.each { |h| helper.extend "#{h}_helper".classify.constantize } <del> end <del>end <del> <del>class << helper <del> include_all_modules_from ActionView <add>def helper <add> @helper ||= ApplicationController.helpers <ide> end <ide> <ide> @controller = ApplicationController.new <del>helper :application rescue nil
2
Python
Python
add standardized get_vocab method to tokenizers
c36416e53c29da8b6193f4a36d7b024c5f513495
<ide><path>src/transformers/tokenization_albert.py <ide> def __init__( <ide> def vocab_size(self): <ide> return len(self.sp_model) <ide> <add> def get_vocab(self): <add> vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)} <add> vocab.update(self.added_tokens_encoder) <add> return vocab <add> <ide> def __getstate__(self): <ide> state = self.__dict__.copy() <ide> state["sp_model"] = None <ide><path>src/transformers/tokenization_bert.py <ide> def __init__( <ide> def vocab_size(self): <ide> return len(self.vocab) <ide> <add> def get_vocab(self): <add> return dict(self.vocab, **self.added_tokens_encoder) <add> <ide> def _tokenize(self, text): <ide> split_tokens = [] <ide> if self.do_basic_tokenize: <ide><path>src/transformers/tokenization_ctrl.py <ide> def __init__(self, vocab_file, merges_file, unk_token="<unk>", **kwargs): <ide> def vocab_size(self): <ide> return len(self.encoder) <ide> <add> def get_vocab(self): <add> return dict(self.encoder, **self.added_tokens_encoder) <add> <ide> def bpe(self, token): <ide> if token in self.cache: <ide> return self.cache[token] <ide><path>src/transformers/tokenization_gpt2.py <ide> def __init__( <ide> def vocab_size(self): <ide> return len(self.encoder) <ide> <add> def get_vocab(self): <add> return dict(self.encoder, **self.added_tokens_encoder) <add> <ide> def bpe(self, token): <ide> if token in self.cache: <ide> return self.cache[token] <ide><path>src/transformers/tokenization_openai.py <ide> def __init__(self, vocab_file, merges_file, unk_token="<unk>", **kwargs): <ide> def vocab_size(self): <ide> return len(self.encoder) <ide> <add> def get_vocab(self): <add> return dict(self.encoder, **self.added_tokens_encoder) <add> <ide> def bpe(self, token): <ide> word = tuple(token[:-1]) + (token[-1] + "</w>",) <ide> if token in self.cache: <ide><path>src/transformers/tokenization_t5.py <ide> def __init__( <ide> def vocab_size(self): <ide> return self.sp_model.get_piece_size() + self._extra_ids <ide> <add> def get_vocab(self): <add> vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)} <add> vocab.update(self.added_tokens_encoder) <add> return vocab <add> <ide> def __getstate__(self): <ide> state = self.__dict__.copy() <ide> state["sp_model"] = None <ide><path>src/transformers/tokenization_transfo_xl.py <ide> def convert_to_tensor(self, symbols): <ide> def vocab_size(self): <ide> return len(self.idx2sym) <ide> <add> def get_vocab(self): <add> return dict(self.sym2idx, **self.added_tokens_encoder) <add> <ide> def _tokenize(self, line, add_eos=False, add_double_eos=False): <ide> line = line.strip() <ide> # convert to lower case <ide><path>src/transformers/tokenization_utils.py <ide> def additional_special_tokens_ids(self): <ide> """ Ids of all the additional special tokens in the vocabulary (list of integers). Log an error if used while not having been set. """ <ide> return self.convert_tokens_to_ids(self.additional_special_tokens) <ide> <add> def get_vocab(self): <add> """ Returns the vocabulary as a dict of {token: index} pairs. `tokenizer.get_vocab()[token]` is equivalent to `tokenizer.convert_tokens_to_ids(token)` when `token` is in the vocab. """ <add> raise NotImplementedError() <add> <ide> def __init__(self, max_len=None, **kwargs): <ide> self._bos_token = None <ide> self._eos_token = None <ide><path>src/transformers/tokenization_xlm.py <ide> def ja_tokenize(self, text): <ide> def vocab_size(self): <ide> return len(self.encoder) <ide> <add> def get_vocab(self): <add> return dict(self.encoder, **self.added_tokens_encoder) <add> <ide> def bpe(self, token): <ide> word = tuple(token[:-1]) + (token[-1] + "</w>",) <ide> if token in self.cache: <ide><path>src/transformers/tokenization_xlm_roberta.py <ide> def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None): <ide> def vocab_size(self): <ide> return len(self.sp_model) + len(self.fairseq_tokens_to_ids) <ide> <add> def get_vocab(self): <add> vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)} <add> vocab.update(self.added_tokens_encoder) <add> return vocab <add> <ide> def _tokenize(self, text): <ide> return self.sp_model.EncodeAsPieces(text) <ide> <ide><path>src/transformers/tokenization_xlnet.py <ide> def __init__( <ide> def vocab_size(self): <ide> return len(self.sp_model) <ide> <add> def get_vocab(self): <add> vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)} <add> vocab.update(self.added_tokens_encoder) <add> return vocab <add> <ide> def __getstate__(self): <ide> state = self.__dict__.copy() <ide> state["sp_model"] = None <ide><path>tests/test_tokenization_common.py <ide> def test_separate_tokenizers(self): <ide> print(new_tokenizer.init_kwargs) <ide> assert tokenizer.init_kwargs["random_argument"] is True <ide> assert new_tokenizer.init_kwargs["random_argument"] is False <add> <add> def test_get_vocab(self): <add> tokenizer = self.get_tokenizer() <add> vocab = tokenizer.get_vocab() <add> <add> self.assertIsInstance(vocab, dict) <add> self.assertEqual(len(vocab), len(tokenizer)) <add> <add> for word, ind in vocab.items(): <add> self.assertEqual(tokenizer.convert_tokens_to_ids(word), ind) <add> self.assertEqual(tokenizer.convert_ids_to_tokens(ind), word) <add> <add> tokenizer.add_tokens(["asdfasdfasdfasdf"]) <add> vocab = tokenizer.get_vocab() <add> self.assertIsInstance(vocab, dict) <add> self.assertEqual(len(vocab), len(tokenizer)) <add> <add> for word, ind in vocab.items(): <add> self.assertEqual(tokenizer.convert_tokens_to_ids(word), ind) <add> self.assertEqual(tokenizer.convert_ids_to_tokens(ind), word)
12
Javascript
Javascript
invoke createconnection when no agent
0a01a42e8729cfb1c2bbf59e98daac9d13b06c80
<ide><path>lib/http.js <ide> function ClientRequest(options, cb) { <ide> var self = this; <ide> OutgoingMessage.call(self); <ide> <del> self.agent = options.agent === undefined ? globalAgent : options.agent; <add> self.agent = options.agent; <add> if (!options.agent && options.agent !== false && !options.createConnection) <add> self.agent = globalAgent; <ide> <ide> var defaultPort = options.defaultPort || 80; <ide> <ide><path>test/simple/test-http-createConnection.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>var http = require('http'); <add>var net = require('net'); <add> <add>var create = 0; <add>var response = 0; <add>process.on('exit', function() { <add> assert.equal(1, create, 'createConnection() http option was not called'); <add> assert.equal(1, response, 'http server "request" callback was not called'); <add>}); <add> <add>var server = http.createServer(function(req, res) { <add> res.end(); <add> response++; <add>}).listen(common.PORT, '127.0.0.1', function() { <add> http.get({ createConnection: createConnection }, function (res) { <add> res.resume(); <add> server.close(); <add> }); <add>}); <add> <add>function createConnection() { <add> create++; <add> return net.createConnection(common.PORT, '127.0.0.1'); <add>}
2
Ruby
Ruby
convert `brew options` test to spec
be2645b04f3b001069daf353289a19155afaf00c
<ide><path>Library/Homebrew/test/cmd/options_spec.rb <add>describe "brew options", :integration_test do <add> it "prints a given Formula's options" do <add> setup_test_formula "testball", <<-EOS.undent <add> depends_on "bar" => :recommended <add> EOS <add> <add> expect { brew "options", "testball" } <add> .to output("--with-foo\n\tBuild with foo\n--without-bar\n\tBuild without bar support\n\n").to_stdout <add> .and not_to_output.to_stderr <add> .and be_a_success <add> end <add>end <ide><path>Library/Homebrew/test/options_test.rb <ide> require "testing_env" <ide> require "options" <del>require "testing_env" <del> <del>class IntegrationCommandTestOptions < IntegrationCommandTestCase <del> def test_options <del> setup_test_formula "testball", <<-EOS.undent <del> depends_on "bar" => :recommended <del> EOS <del> <del> assert_equal "--with-foo\n\tBuild with foo\n--without-bar\n\tBuild without bar support", <del> cmd("options", "testball").chomp <del> end <del>end <ide> <ide> class OptionTests < Homebrew::TestCase <ide> def setup
2
PHP
PHP
make fix in other location
063e5ae341c32220d4679d0215ab9b263d0c8a33
<ide><path>src/Illuminate/Database/Eloquent/Relations/MorphToMany.php <ide> public function newPivot(array $attributes = [], $exists = false) <ide> { <ide> $using = $this->using; <ide> <del> $pivot = $using ? new $using($this->parent, $attributes, $this->table, $exists) <add> $pivot = $using ? $using::fromRawAttributes($this->parent, $attributes, $this->table, $exists) <ide> : new MorphPivot($this->parent, $attributes, $this->table, $exists); <ide> <ide> $pivot->setPivotKeys($this->foreignKey, $this->relatedKey)
1
Python
Python
fix mypy errors for ssh provider
da783f88a16e20211d7087bd5c8802dc002c78a8
<ide><path>airflow/providers/ssh/hooks/ssh.py <ide> import warnings <ide> from base64 import decodebytes <ide> from io import StringIO <del>from typing import Dict, Optional, Tuple, Union <add>from typing import Any, Dict, Optional, Sequence, Tuple, Type, Union <ide> <ide> import paramiko <ide> from paramiko.config import SSH_PORT <ide> class SSHHook(BaseHook): <ide> """ <ide> <ide> # List of classes to try loading private keys as, ordered (roughly) by most common to least common <del> _pkey_loaders = ( <add> _pkey_loaders: Sequence[Type[paramiko.PKey]] = ( <ide> paramiko.RSAKey, <ide> paramiko.ECDSAKey, <ide> paramiko.Ed25519Key, <ide> def get_ui_field_behaviour() -> Dict: <ide> def __init__( <ide> self, <ide> ssh_conn_id: Optional[str] = None, <del> remote_host: Optional[str] = None, <add> remote_host: str = '', <ide> username: Optional[str] = None, <ide> password: Optional[str] = None, <ide> key_file: Optional[str] = None, <ide> def __init__( <ide> self.look_for_keys = True <ide> <ide> # Placeholder for deprecated __enter__ <del> self.client = None <add> self.client: Optional[paramiko.SSHClient] = None <ide> <ide> # Use connection to override defaults <ide> if self.ssh_conn_id is not None: <ide> def __init__( <ide> self.username = conn.login <ide> if self.password is None: <ide> self.password = conn.password <del> if self.remote_host is None: <add> if not self.remote_host: <ide> self.remote_host = conn.host <ide> if self.port is None: <ide> self.port = conn.port <ide> def __init__( <ide> ssh_conf.parse(config_fd) <ide> host_info = ssh_conf.lookup(self.remote_host) <ide> if host_info and host_info.get('proxycommand'): <del> self.host_proxy = paramiko.ProxyCommand(host_info.get('proxycommand')) <add> self.host_proxy = paramiko.ProxyCommand(host_info['proxycommand']) <ide> <ide> if not (self.password or self.key_file): <ide> if host_info and host_info.get('identityfile'): <del> self.key_file = host_info.get('identityfile')[0] <add> self.key_file = host_info['identityfile'][0] <ide> <ide> self.port = self.port or SSH_PORT <ide> <ide> def get_conn(self) -> paramiko.SSHClient: <ide> else: <ide> pass # will fallback to system host keys if none explicitly specified in conn extra <ide> <del> connect_kwargs = dict( <add> connect_kwargs: Dict[str, Any] = dict( <ide> hostname=self.remote_host, <ide> username=self.username, <ide> timeout=self.conn_timeout, <ide> def get_conn(self) -> paramiko.SSHClient: <ide> client.connect(**connect_kwargs) <ide> <ide> if self.keepalive_interval: <del> client.get_transport().set_keepalive(self.keepalive_interval) <add> # MyPy check ignored because "paramiko" isn't well-typed. The `client.get_transport()` returns <add> # type "Optional[Transport]" and item "None" has no attribute "set_keepalive". <add> client.get_transport().set_keepalive(self.keepalive_interval) # type: ignore[union-attr] <ide> <ide> self.client = client <ide> return client <ide><path>airflow/providers/ssh/operators/ssh.py <ide> def run_ssh_client_command(self, ssh_client: SSHClient, command: str) -> bytes: <ide> return agg_stdout <ide> <ide> def execute(self, context=None) -> Union[bytes, str]: <del> result = None <add> result: Union[bytes, str] <ide> if self.command is None: <ide> raise AirflowException("SSH operator error: SSH command not specified. Aborting.") <ide>
2
Ruby
Ruby
require https for all *.googlecode.com resources
2e3a0263d4c91525dbb907122c87e90af75c20a2
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_urls <ide> end <ide> <ide> # Check for Google Code download urls, https:// is preferred <add> # Intentionally not extending this to SVN repositories due to certificate <add> # issues. <ide> urls.grep(%r[^http://.*\.googlecode\.com/files.*]) do |u| <ide> problem "Use https:// URLs for downloads from Google Code (url is #{u})." <ide> end
1
PHP
PHP
fix styleci warning
7414de1dbe645e371f9ddff758e11aa287ae92c8
<ide><path>src/Illuminate/Foundation/Testing/TestCase.php <ide> <ide> use Mockery; <ide> use Carbon\Carbon; <del>use Illuminate\Support\Str; <ide> use Carbon\CarbonImmutable; <add>use Illuminate\Support\Str; <ide> use Illuminate\Support\Facades\Facade; <ide> use Illuminate\Database\Eloquent\Model; <ide> use Mockery\Exception\InvalidCountException;
1
Java
Java
use databuffer.write in charsequenceencoder
4955d08f2891810627961ac4df660b9bed64a30b
<ide><path>spring-core/src/main/java/org/springframework/core/codec/CharSequenceEncoder.java <ide> <ide> package org.springframework.core.codec; <ide> <del>import java.nio.ByteBuffer; <del>import java.nio.CharBuffer; <ide> import java.nio.charset.Charset; <add>import java.nio.charset.CoderMalfunctionError; <ide> import java.nio.charset.StandardCharsets; <ide> import java.util.Map; <ide> <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.core.io.buffer.DataBufferFactory; <add>import org.springframework.core.io.buffer.DataBufferUtils; <ide> import org.springframework.core.log.LogFormatUtils; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.MimeType; <ide> public Flux<DataBuffer> encode(Publisher<? extends CharSequence> inputStream, <ide> return Hints.getLogPrefix(hints) + "Writing " + formatted; <ide> }); <ide> } <del> CharBuffer charBuffer = CharBuffer.wrap(charSequence); <del> ByteBuffer byteBuffer = charset.encode(charBuffer); <del> return bufferFactory.wrap(byteBuffer); <add> boolean release = true; <add> DataBuffer dataBuffer = bufferFactory.allocateBuffer(); <add> try { <add> dataBuffer.write(charSequence, charset); <add> release = false; <add> } <add> catch (CoderMalfunctionError ex) { <add> throw new EncodingException("String encoding error: " + ex.getMessage(), ex); <add> } <add> finally { <add> if (release) { <add> DataBufferUtils.release(dataBuffer); <add> } <add> } <add> return dataBuffer; <ide> }); <ide> } <ide> <ide><path>spring-core/src/test/java/org/springframework/core/codec/CharSequenceEncoderTests.java <ide> public void encode() { <ide> .consumeNextWith(expectString(this.foo)) <ide> .consumeNextWith(expectString(this.bar)) <ide> .verifyComplete()); <del> <del> <ide> } <ide> <ide> }
2
Ruby
Ruby
fix typo in named_scope documentation
7a34ab7d60756856b79d2f8ef33ac843a78b70ad
<ide><path>activerecord/lib/active_record/named_scope.rb <ide> def scoped(options = nil) <ide> # on scopes <ide> # <ide> # class Article < ActiveRecord::Base <del> # scope :pubished, where(:published => true) <add> # scope :published, where(:published => true) <ide> # scope :featured, where(:featured => true) <ide> # <ide> # def self.latest_article
1
Text
Text
add a sql example for `not` [ci skip]
a8d1412a3227ac3d14a40f0e62c9cd83b515ff95
<ide><path>guides/source/active_record_querying.md <ide> SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5)) <ide> Post.where.not(author: author) <ide> ``` <ide> <del>In other words, this query can be generated by calling `where` with no argument, then immediately chain with `not` passing `where` conditions. <add>In other words, this query can be generated by calling `where` with no argument, <add>then immediately chain with `not` passing `where` conditions. This will generate <add>SQL code like this: <add> <add>```sql <add>SELECT * FROM posts WHERE (author_id != 1) <add>``` <ide> <ide> Ordering <ide> --------
1
Javascript
Javascript
use mustcall() in test-http-timeout
1111111122342506eefa7fc16f6a2b15bd239510
<ide><path>test/parallel/test-http-timeout.js <ide> // USE OR OTHER DEALINGS IN THE SOFTWARE. <ide> <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> <ide> const http = require('http'); <ide> const Countdown = require('../common/countdown'); <add>const MAX_COUNT = 11; <ide> <del>const server = http.createServer(function(req, res) { <add>const server = http.createServer(common.mustCall(function(req, res) { <ide> res.writeHead(200, { 'Content-Type': 'text/plain' }); <ide> res.end('OK'); <del>}); <add>}, MAX_COUNT)); <ide> <del>const MAX_COUNT = 11; <ide> const agent = new http.Agent({ maxSockets: 1 }); <ide> const countdown = new Countdown(MAX_COUNT, () => server.close()); <ide>
1
Javascript
Javascript
remove second arg from assert.iferror()
dcfd323c6be53c6ea812e5d98eee8f4e8d31dc57
<ide><path>test/parallel/test-fs-readfile.js <ide> for (const e of fileInfo) { <ide> for (const e of fileInfo) { <ide> fs.readFile(e.name, common.mustCall((err, buf) => { <ide> console.log(`Validating readFile on file ${e.name} of length ${e.len}`); <del> assert.ifError(err, 'An error occurred'); <add> assert.ifError(err); <ide> assert.deepStrictEqual(buf, e.contents, 'Incorrect file contents'); <ide> })); <ide> }
1
Ruby
Ruby
add .dry_run? method
f17429f842222428d31095e0f604681764824afa
<ide><path>Library/Homebrew/cmd/cleanup.rb <ide> def cleanup <ide> end <ide> clean_cache <ide> # seems like a good time to do some additional cleanup <del> Homebrew.prune unless ARGV.switch? 'n' <add> Homebrew.prune unless ARGV.dry_run? <ide> else <ide> ARGV.formulae.each do |f| <ide> cleanup_formula f <ide> def cleanup_formula f <ide> f.rack.children.each do |keg| <ide> if f.installed_prefix != keg <ide> puts "Removing #{keg}..." <del> rm_rf keg unless ARGV.switch? 'n' <add> rm_rf keg unless ARGV.dry_run? <ide> end <ide> end <ide> elsif f.rack.children.length > 1 <ide> def clean_cache <ide> old_bottle = bottle_file_outdated? f, pn <ide> if not f or (f.version != version or ARGV.switch? "s" and not f.installed?) or old_bottle <ide> puts "Removing #{pn}..." <del> rm pn unless ARGV.switch? 'n' <add> rm pn unless ARGV.dry_run? <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/cmd/link.rb <ide> def link <ide> abort "Cowardly refusing to `sudo brew link'" <ide> end <ide> <del> if ARGV.force? <del> mode = :force <del> elsif ARGV.include?("--dry-run") || ARGV.include?("-n") <del> mode = :dryrun <del> else <del> mode = nil <add> if ARGV.force? then mode = :force <add> elsif ARGV.dry_run? then mode = :dryrun <add> else mode = nil <ide> end <ide> <ide> ARGV.kegs.each do |keg| <ide><path>Library/Homebrew/extend/ARGV.rb <ide> def interactive? <ide> def one? <ide> flag? '--1' <ide> end <add> def dry_run? <add> include?('--dry-run') || switch?('n') <add> end <ide> <ide> def build_head? <ide> include? '--HEAD'
3
Java
Java
investigate claim on so regarding ctx cache in tcf
c2908399141381de5b9f79f29d5b90c822a7b7e3
<ide><path>spring-test/src/test/java/org/springframework/test/context/support/AbstractContextLoaderUtilsTests.java <ide> import org.springframework.test.context.ContextLoader; <ide> import org.springframework.test.context.MergedContextConfiguration; <ide> import org.springframework.test.context.TestContextBootstrapper; <add>import org.springframework.test.context.web.WebAppConfiguration; <ide> <ide> import static org.junit.Assert.*; <ide> <ide> static class LocationsFoo { <ide> static class ClassesFoo { <ide> } <ide> <add> @WebAppConfiguration <add> static class WebClassesFoo extends ClassesFoo { <add> } <add> <ide> @ContextConfiguration(locations = "/bar.xml", inheritLocations = true, loader = AnnotationConfigContextLoader.class) <ide> @ActiveProfiles("bar") <ide> static class LocationsBar extends LocationsFoo { <ide><path>spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsMergedConfigTests.java <ide> import org.springframework.test.context.ContextConfiguration; <ide> import org.springframework.test.context.ContextLoader; <ide> import org.springframework.test.context.MergedContextConfiguration; <add>import org.springframework.test.context.web.WebDelegatingSmartContextLoader; <add>import org.springframework.test.context.web.WebMergedContextConfiguration; <add> <add>import static org.junit.Assert.*; <ide> <ide> /** <ide> * Unit tests for {@link ContextLoaderUtils} involving {@link MergedContextConfiguration}. <ide> public void buildMergedConfigWithLocalAnnotationAndClasses() { <ide> DelegatingSmartContextLoader.class); <ide> } <ide> <add> /** <add> * Introduced to investigate claims made in a discussion on <add> * <a href="http://stackoverflow.com/questions/24725438/what-could-cause-a-class-implementing-applicationlistenercontextrefreshedevent">Stack Overflow</a>. <add> */ <add> @Test <add> public void buildMergedConfigWithAtWebAppConfigurationWithAnnotationAndClassesOnSuperclass() { <add> Class<?> webTestClass = WebClassesFoo.class; <add> Class<?> standardTestClass = ClassesFoo.class; <add> WebMergedContextConfiguration webMergedConfig = (WebMergedContextConfiguration) buildMergedContextConfiguration(webTestClass); <add> MergedContextConfiguration standardMergedConfig = buildMergedContextConfiguration(standardTestClass); <add> <add> assertEquals(webMergedConfig, webMergedConfig); <add> assertEquals(standardMergedConfig, standardMergedConfig); <add> assertNotEquals(standardMergedConfig, webMergedConfig); <add> assertNotEquals(webMergedConfig, standardMergedConfig); <add> <add> assertMergedConfig(webMergedConfig, webTestClass, EMPTY_STRING_ARRAY, new Class<?>[] { FooConfig.class }, <add> WebDelegatingSmartContextLoader.class); <add> assertMergedConfig(standardMergedConfig, standardTestClass, EMPTY_STRING_ARRAY, <add> new Class<?>[] { FooConfig.class }, DelegatingSmartContextLoader.class); <add> } <add> <ide> @Test <ide> public void buildMergedConfigWithLocalAnnotationAndOverriddenContextLoaderAndLocations() { <ide> Class<?> testClass = PropertiesLocationsFoo.class;
2
Text
Text
update testing.md with pre-processing information
f88fe71ee6c8aed4f906c06b97a269fd1f759115
<ide><path>docs/Testing.md <ide> npm test <ide> <ide> from the react-native root, and we encourage you to add your own tests for any components you want to contribute to. See [`getImageSource-test.js`](https://github.com/facebook/react-native/blob/master/Examples/Movies/__tests__/getImageSource-test.js) for a basic example. <ide> <add>Note: In order to run your own tests, you will have to first follow the Getting Started instructions on the Jest page and then include the `jest` objects below in `package.json` so that the scripts are pre-processed before execution. <add> <add>``` <add>... <add>"scripts": { <add> ... <add> "test": "jest" <add>}, <add>... <add>"jest": { <add> "scriptPreprocessor": "node_modules/react-native/jestSupport/scriptPreprocess.js", <add> "setupEnvScriptFile": "node_modules/react-native/jestSupport/env.js", <add> "testPathIgnorePatterns": [ <add> "/node_modules/", <add> "packager/react-packager/src/Activity/" <add> ], <add> "testFileExtensions": [ <add> "js" <add> ], <add> "unmockedModulePathPatterns": [ <add> "promise", <add> "source-map" <add> ] <add>}, <add>... <add>``` <add> <ide> Note: you may have to install/upgrade/link io.js and other parts of your environment in order for the tests to run correctly. Check out the latest setup in [.travis.yml](https://github.com/facebook/react-native/blob/master/.travis.yml#L11-24) <ide> <ide> ## Integration Tests
1
PHP
PHP
fix coding style
7d4421ebb479d66e7672ac763c221e86d0191b95
<ide><path>src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php <ide> protected function getConfigurationFiles(Application $app) <ide> /** <ide> * Get the configuration file nesting path. <ide> * <del> * @param \Symfony\Component\Finder\SplFileInfo $file <add> * @param \Symfony\Component\Finder\SplFileInfo $file <ide> * @return string <ide> */ <ide> private function getConfigurationNesting(SplFileInfo $file)
1
Ruby
Ruby
use options hash for install_bottle?
a7e1dbae63ee62e7900dc7fbb3f67ea5c435a0a4
<ide><path>Library/Homebrew/bottles.rb <ide> require 'extend/ARGV' <ide> require 'bottle_version' <ide> <del># TODO: use options={} for some arguments. <del> <ide> def bottle_filename f, bottle_revision=nil <ide> name = f.name.downcase <ide> version = f.stable.version <ide> bottle_revision ||= f.bottle.revision.to_i if f.bottle <ide> "#{name}-#{version}#{bottle_native_suffix(bottle_revision)}" <ide> end <ide> <del>def install_bottle? f, warn=false <add>def install_bottle? f, options={:warn=>false} <ide> return true if f.downloader and defined? f.downloader.local_bottle_path \ <ide> and f.downloader.local_bottle_path <ide> <ide> def install_bottle? f, warn=false <ide> return false unless f.build.used_options.empty? <ide> return false unless bottle_current?(f) <ide> if f.bottle.cellar != :any && f.bottle.cellar != HOMEBREW_CELLAR.to_s <del> opoo "Building source; cellar of #{f}'s bottle is #{f.bottle.cellar}" if warn <add> if options[:warn] <add> opoo "Building source; cellar of #{f}'s bottle is #{f.bottle.cellar}" <add> end <ide> return false <ide> end <ide> <ide><path>Library/Homebrew/formula_installer.rb <ide> def initialize ff <ide> check_install_sanity <ide> end <ide> <del> def pour_bottle? warn=false <del> tab.used_options.empty? && options.empty? && install_bottle?(f, warn) <add> def pour_bottle? install_bottle_options={:warn=>false} <add> tab.used_options.empty? && options.empty? && \ <add> install_bottle?(f, install_bottle_options) <ide> end <ide> <ide> def check_install_sanity <ide> def install <ide> @poured_bottle = false <ide> <ide> begin <del> if pour_bottle? true <add> if pour_bottle? :warn => true <ide> pour <ide> @poured_bottle = true <ide> tab = Tab.for_keg f.prefix
2
Java
Java
fix bug in webclientdatabufferallocatingtests
38052e77b710a0fa373483bc6e55d68c26e6ec38
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientDataBufferAllocatingTests.java <ide> import io.netty.channel.ChannelOption; <ide> import okhttp3.mockwebserver.MockResponse; <ide> import okhttp3.mockwebserver.MockWebServer; <add>import org.junit.jupiter.api.AfterAll; <ide> import org.junit.jupiter.api.AfterEach; <del>import org.junit.jupiter.api.BeforeEach; <add>import org.junit.jupiter.api.BeforeAll; <add>import org.junit.jupiter.api.TestInstance; <ide> import reactor.core.publisher.Mono; <ide> import reactor.test.StepVerifier; <ide> <ide> import org.springframework.web.reactive.function.UnsupportedMediaTypeException; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <add>import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; <ide> <ide> /** <ide> * WebClient integration tests focusing on data buffer management. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @author Sam Brannen <ide> */ <del>public class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests { <add>@TestInstance(PER_CLASS) <add>class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTests { <ide> <ide> private static final Duration DELAY = Duration.ofSeconds(5); <ide> <del> <ide> private final ReactorResourceFactory factory = new ReactorResourceFactory(); <del> <del> private final MockWebServer server = new MockWebServer(); <del> <add> private MockWebServer server; <ide> private WebClient webClient; <ide> <ide> <del> @BeforeEach <del> public void setUp() { <del> this.factory.setUseGlobalResources(false); <del> this.factory.afterPropertiesSet(); <add> @BeforeAll <add> void setUpReactorResourceFactory() { <add> factory.afterPropertiesSet(); <add> } <ide> <add> @AfterAll <add> void destroyReactorResourceFactory() { <add> factory.destroy(); <add> } <add> <add> private void setUp(DataBufferFactory bufferFactory) { <add> super.bufferFactory = bufferFactory; <add> this.server = new MockWebServer(); <ide> this.webClient = WebClient <ide> .builder() <ide> .clientConnector(initConnector()) <ide> public void setUp() { <ide> } <ide> <ide> private ReactorClientHttpConnector initConnector() { <del> if (bufferFactory instanceof NettyDataBufferFactory) { <del> ByteBufAllocator allocator = ((NettyDataBufferFactory) bufferFactory).getByteBufAllocator(); <del> return new ReactorClientHttpConnector(this.factory, httpClient -> <add> assertThat(super.bufferFactory).isNotNull(); <add> <add> if (super.bufferFactory instanceof NettyDataBufferFactory) { <add> ByteBufAllocator allocator = ((NettyDataBufferFactory) super.bufferFactory).getByteBufAllocator(); <add> return new ReactorClientHttpConnector(factory, httpClient -> <ide> httpClient.tcpConfiguration(tcpClient -> tcpClient.option(ChannelOption.ALLOCATOR, allocator))); <ide> } <ide> else { <ide> private ReactorClientHttpConnector initConnector() { <ide> } <ide> <ide> @AfterEach <del> public void shutDown() throws InterruptedException { <add> void shutDown() throws InterruptedException { <ide> waitForDataBufferRelease(Duration.ofSeconds(2)); <del> this.factory.destroy(); <ide> } <ide> <ide> <ide> @ParameterizedDataBufferAllocatingTest <del> public void bodyToMonoVoid(String displayName, DataBufferFactory bufferFactory) { <del> super.bufferFactory = bufferFactory; <add> void bodyToMonoVoid(String displayName, DataBufferFactory bufferFactory) { <add> setUp(bufferFactory); <ide> <ide> this.server.enqueue(new MockResponse() <ide> .setResponseCode(201) <ide> public void bodyToMonoVoid(String displayName, DataBufferFactory bufferFactory) <ide> } <ide> <ide> @ParameterizedDataBufferAllocatingTest // SPR-17482 <del> public void bodyToMonoVoidWithoutContentType(String displayName, DataBufferFactory bufferFactory) { <del> super.bufferFactory = bufferFactory; <add> void bodyToMonoVoidWithoutContentType(String displayName, DataBufferFactory bufferFactory) { <add> setUp(bufferFactory); <ide> <ide> this.server.enqueue(new MockResponse() <ide> .setResponseCode(HttpStatus.ACCEPTED.value()) <ide> public void bodyToMonoVoidWithoutContentType(String displayName, DataBufferFacto <ide> } <ide> <ide> @ParameterizedDataBufferAllocatingTest <del> public void onStatusWithBodyNotConsumed(String displayName, DataBufferFactory bufferFactory) { <del> super.bufferFactory = bufferFactory; <add> void onStatusWithBodyNotConsumed(String displayName, DataBufferFactory bufferFactory) { <add> setUp(bufferFactory); <ide> <ide> RuntimeException ex = new RuntimeException("response error"); <ide> testOnStatus(ex, response -> Mono.just(ex)); <ide> } <ide> <ide> @ParameterizedDataBufferAllocatingTest <del> public void onStatusWithBodyConsumed(String displayName, DataBufferFactory bufferFactory) { <del> super.bufferFactory = bufferFactory; <add> void onStatusWithBodyConsumed(String displayName, DataBufferFactory bufferFactory) { <add> setUp(bufferFactory); <ide> <ide> RuntimeException ex = new RuntimeException("response error"); <ide> testOnStatus(ex, response -> response.bodyToMono(Void.class).thenReturn(ex)); <ide> } <ide> <ide> @ParameterizedDataBufferAllocatingTest // SPR-17473 <del> public void onStatusWithMonoErrorAndBodyNotConsumed(String displayName, DataBufferFactory bufferFactory) { <del> super.bufferFactory = bufferFactory; <add> void onStatusWithMonoErrorAndBodyNotConsumed(String displayName, DataBufferFactory bufferFactory) { <add> setUp(bufferFactory); <ide> <ide> RuntimeException ex = new RuntimeException("response error"); <ide> testOnStatus(ex, response -> Mono.error(ex)); <ide> } <ide> <ide> @ParameterizedDataBufferAllocatingTest <del> public void onStatusWithMonoErrorAndBodyConsumed(String displayName, DataBufferFactory bufferFactory) { <del> super.bufferFactory = bufferFactory; <add> void onStatusWithMonoErrorAndBodyConsumed(String displayName, DataBufferFactory bufferFactory) { <add> setUp(bufferFactory); <ide> <ide> RuntimeException ex = new RuntimeException("response error"); <ide> testOnStatus(ex, response -> response.bodyToMono(Void.class).then(Mono.error(ex))); <ide> } <ide> <ide> @ParameterizedDataBufferAllocatingTest // gh-23230 <del> public void onStatusWithImmediateErrorAndBodyNotConsumed(String displayName, DataBufferFactory bufferFactory) { <del> super.bufferFactory = bufferFactory; <add> void onStatusWithImmediateErrorAndBodyNotConsumed(String displayName, DataBufferFactory bufferFactory) { <add> setUp(bufferFactory); <ide> <ide> RuntimeException ex = new RuntimeException("response error"); <ide> testOnStatus(ex, response -> { <ide> public void onStatusWithImmediateErrorAndBodyNotConsumed(String displayName, Dat <ide> } <ide> <ide> @ParameterizedDataBufferAllocatingTest <del> public void releaseBody(String displayName, DataBufferFactory bufferFactory) { <del> super.bufferFactory = bufferFactory; <add> void releaseBody(String displayName, DataBufferFactory bufferFactory) { <add> setUp(bufferFactory); <ide> <ide> this.server.enqueue(new MockResponse() <ide> .setResponseCode(200) <ide> public void releaseBody(String displayName, DataBufferFactory bufferFactory) { <ide> } <ide> <ide> @ParameterizedDataBufferAllocatingTest <del> public void exchangeToBodilessEntity(String displayName, DataBufferFactory bufferFactory) { <del> super.bufferFactory = bufferFactory; <add> void exchangeToBodilessEntity(String displayName, DataBufferFactory bufferFactory) { <add> setUp(bufferFactory); <ide> <ide> this.server.enqueue(new MockResponse() <ide> .setResponseCode(201)
1
PHP
PHP
change indent style
fef793a9ab03a0e7d867fa68939e4055c321af38
<ide><path>src/Illuminate/Routing/Router.php <ide> protected function getGroupResourceName($prefix, $resource, $method) <ide> { <ide> $group = str_replace('/', '.', $this->getLastGroupPrefix()); <ide> <del> if (empty($group)) <del> { <del> return trim("{$prefix}{$resource}.{$method}", '.'); <del> } <add> if (empty($group)) <add> { <add> return trim("{$prefix}{$resource}.{$method}", '.'); <add> } <ide> <ide> return trim("{$prefix}{$group}.{$resource}.{$method}", '.'); <ide> }
1
PHP
PHP
fix translate behavior tests
2a9f7108d965e0360442fabaab480b0ed12bf1b4
<ide><path>tests/TestCase/ORM/Behavior/TranslateBehaviorTest.php <ide> public function testMatchingDoesNotCreateAssociationProperty() <ide> $table = $this->getTableLocator()->get('Articles'); <ide> $table->hasMany('Comments'); <ide> <del> $table->Comments->addBehavior('Translate'); <add> $table->Comments->addBehavior('Translate', ['fields' => ['comment']]); <ide> $table->Comments->setLocale('abc'); <ide> <ide> $this->assertNotEquals($table->Comments->getLocale(), I18n::getLocale()); <ide> public function testDeepMatchingDoesNotCreateAssociationProperty() <ide> $table->hasMany('Comments'); <ide> $table->Comments->belongsTo('Authors')->setForeignKey('user_id'); <ide> <del> $table->Comments->addBehavior('Translate'); <add> $table->Comments->addBehavior('Translate', ['fields' => ['comment']]); <ide> $table->Comments->setLocale('abc'); <ide> <del> $table->Comments->Authors->addBehavior('Translate'); <add> $table->Comments->Authors->addBehavior('Translate', ['fields' => ['name']]); <ide> $table->Comments->Authors->setLocale('xyz'); <ide> <ide> $this->assertNotEquals($table->Comments->getLocale(), I18n::getLocale()); <ide> public function testContainedMatchingDoesNotCreateAssociationProperty() <ide> $table->hasMany('Comments')->setForeignKey('user_id'); <ide> $table->Comments->belongsTo('Articles'); <ide> <del> $table->Comments->Articles->addBehavior('Translate'); <add> $table->Comments->Articles->addBehavior('Translate', ['fields' => ['title', 'body']]); <ide> $table->Comments->Articles->setLocale('xyz'); <ide> <ide> $this->assertNotEquals($table->Comments->Articles->getLocale(), I18n::getLocale()); <ide> public function testContainedMatchingDoesNotCreateAssociationProperty() <ide> ->contain([ <ide> 'Comments' => function ($query) { <ide> return $query->matching('Articles'); <del> } <add> }, <ide> ]) <ide> ->first(); <ide> <ide> public function testLocalePropertyIsSetInMatchingData() <ide> $table = $this->getTableLocator()->get('Articles'); <ide> $table->hasMany('Comments'); <ide> <del> $table->Comments->addBehavior('Translate'); <add> $table->Comments->addBehavior('Translate', ['fields' => ['comment']]); <ide> $table->Comments->setLocale('abc'); <ide> <ide> $this->assertNotEquals($table->Comments->getLocale(), I18n::getLocale()); <ide> public function testLocalePropertyIsSetInMatchingDataWhenUsingDeepMatching() <ide> $table->hasMany('Comments'); <ide> $table->Comments->belongsTo('Authors')->setForeignKey('user_id'); <ide> <del> $table->Comments->addBehavior('Translate'); <add> $table->Comments->addBehavior('Translate', ['fields' => ['comment']]); <ide> $table->Comments->setLocale('abc'); <ide> <del> $table->Comments->Authors->addBehavior('Translate'); <add> $table->Comments->Authors->addBehavior('Translate', ['fields' => ['name']]); <ide> $table->Comments->Authors->setLocale('xyz'); <ide> <ide> $this->assertNotEquals($table->Comments->getLocale(), I18n::getLocale()); <ide> public function testLocalePropertyIsSetInMatchingDataWhenUsingContainedMatching( <ide> $table->hasMany('Articles'); <ide> $table->Articles->belongsToMany('Tags'); <ide> <del> $table->Articles->addBehavior('Translate'); <add> $table->Articles->addBehavior('Translate', ['fields' => ['title', 'body']]); <ide> $table->Articles->setLocale('abc'); <ide> <del> $table->Articles->Tags->addBehavior('Translate'); <add> $table->Articles->Tags->addBehavior('Translate', ['fields' => ['name']]); <ide> $table->Articles->Tags->setLocale('xyz'); <ide> <ide> $this->assertNotEquals($table->Articles->getLocale(), I18n::getLocale()); <ide> public function testLocalePropertyIsSetInMatchingDataWhenUsingContainedMatching( <ide> 'Articles' => function ($query) { <ide> return $query->matching('Tags'); <ide> }, <del> 'Articles.Tags' <add> 'Articles.Tags', <ide> ]) <ide> ->first(); <ide>
1
Text
Text
update compiler requirements in readme
081e94a90d82359ababd12b4cda913467284a40d
<ide><path>README.md <ide> Evented I/O for V8 javascript. <ide> <ide> Prerequisites (Unix only): <ide> <del> * GCC 4.2 or newer <del> * G++ 4.2 or newer <add> * `gcc` and `g++` 4.8 or newer, or <add> * `clang` and `clang++` 3.3 or newer <ide> * Python 2.6 or 2.7 <ide> * GNU Make 3.81 or newer <ide> * libexecinfo (FreeBSD and OpenBSD only) <ide> make install <ide> Prerequisites (Windows only): <ide> <ide> * Python 2.6 or 2.7 <del> * Visual Studio 2010 or 2012 <add> * Visual Studio 2013 for Windows Desktop, or <add> * Visual Studio Express 2013 for Windows Desktop <ide> <ide> Windows: <ide>
1
Javascript
Javascript
remove a pair of outdated comments
4d91d0164d9eff466b4d3b63ecbd50944b5cedfa
<ide><path>lib/_http_common.js <ide> function parserOnHeadersComplete(versionMajor, versionMinor, headers, method, <ide> return parser.onIncoming(incoming, shouldKeepAlive); <ide> } <ide> <del>// XXX This is a mess. <del>// TODO: http.Parser should be a Writable emits request/response events. <ide> function parserOnBody(b, start, len) { <ide> const stream = this.incoming; <ide>
1
Javascript
Javascript
restore original canvas context when destroying
85f3755f9abd6a1b5224f61cb4e209739f850eed
<ide><path>src/Chart.Core.js <ide> destroy : function(){ <ide> this.clear(); <ide> unbindEvents(this, this.events); <add> var canvas = this.chart.canvas; <add> <add> // Reset canvas height/width attributes starts a fresh with the canvas context <add> canvas.width = this.chart.width; <add> canvas.height = this.chart.height; <add> <add> // < IE9 doesn't support removeProperty <add> if (canvas.style.removeProperty) { <add> canvas.style.removeProperty('width'); <add> canvas.style.removeProperty('height'); <add> } else { <add> canvas.style.removeAttribute('width'); <add> canvas.style.removeAttribute('height'); <add> } <add> <ide> delete Chart.instances[this.id]; <ide> }, <ide> showTooltip : function(ChartElements, forceRedraw){
1
Python
Python
clarify subdagoperator exception
fb6a7a8684977af49bab96580a5c07c254ba164f
<ide><path>airflow/operators/subdag_operator.py <ide> def __init__( <ide> super(SubDagOperator, self).__init__(*args, **kwargs) <ide> if dag.dag_id + '.' + kwargs['task_id'] != subdag.dag_id: <ide> raise AirflowException( <del> "The subdag's dag_id should correspond to the parent's " <del> "'dag_id.task_id'") <add> "The subdag's dag_id should have the form " <add> "'{{parent_dag_id}}.{{this_task_id}}'. Expected " <add> "'{d}.{t}'; received '{rcvd}'.".format( <add> d=dag.dag_id, t=kwargs['task_id'], rcvd=subdag.dag_id)) <ide> self.subdag = subdag <ide> self.executor = executor <ide>
1
Go
Go
avoid a data race in container/health.go
53e0c5012637656de1765c330b2549aa7088b853
<ide><path>container/health.go <ide> func (s *Health) String() string { <ide> case types.Starting: <ide> return "health: starting" <ide> default: // Healthy and Unhealthy are clear on their own <del> return s.Health.Status <add> return status <ide> } <ide> } <ide>
1
Javascript
Javascript
add scrolltoend ability to viewability tests
ca8a75536ecb383d459fe922302b499dad66328e
<ide><path>packages/rn-tester/js/examples/FlatList/FlatListExamples.js <ide> export function FlatList_onViewableItemsChanged(props: { <ide> viewabilityConfig: ViewabilityConfig, <ide> offScreen?: ?boolean, <ide> horizontal?: ?boolean, <add> useScrollRefScroll?: ?boolean, <ide> }): React.Node { <del> const {viewabilityConfig, offScreen, horizontal} = props; <add> const {viewabilityConfig, offScreen, horizontal, useScrollRefScroll} = props; <ide> const [output, setOutput] = React.useState(''); <ide> const onViewableItemsChanged = React.useCallback( <ide> info => <ide> export function FlatList_onViewableItemsChanged(props: { <ide> horizontal, <ide> }; <ide> <add> const ref = React.useRef(null); <add> const onTest = <add> useScrollRefScroll === true <add> ? () => { <add> ref?.current?.getScrollResponder()?.scrollToEnd(); <add> } <add> : null; <add> <ide> return ( <ide> <FlatListExampleWithForwardedRef <add> ref={ref} <ide> exampleProps={exampleProps} <add> onTest={onTest} <ide> testOutput={output}> <ide> {offScreen === true ? <View style={styles.offScreen} /> : null} <ide> </FlatListExampleWithForwardedRef> <ide> const FlatListExampleWithForwardedRef = React.forwardRef( <ide> <View style={styles.container}> <ide> {props.testOutput != null ? ( <ide> <View testID="test_container" style={styles.testContainer}> <del> <Text numberOfLines={1} testID="output"> <add> <Text style={styles.output} numberOfLines={1} testID="output"> <ide> {props.testOutput} <ide> </Text> <ide> {props.onTest != null ? ( <ide> const styles = StyleSheet.create({ <ide> justifyContent: 'space-between', <ide> alignItems: 'center', <ide> backgroundColor: '#f2f2f7ff', <del> padding: 4, <ide> height: 40, <ide> }, <ide> output: { <ide> fontSize: 12, <add> width: '80%', <ide> }, <ide> separator: { <ide> height: 12, <ide><path>packages/rn-tester/js/examples/SectionList/SectionListExamples.js <ide> export function SectionList_onViewableItemsChanged(props: { <ide> viewabilityConfig: ViewabilityConfig, <ide> offScreen?: ?boolean, <ide> horizontal?: ?boolean, <add> useScrollRefScroll?: ?boolean, <ide> }): React.Node { <del> const {viewabilityConfig, offScreen, horizontal} = props; <add> const {viewabilityConfig, offScreen, horizontal, useScrollRefScroll} = props; <ide> const [output, setOutput] = React.useState(''); <ide> const exampleProps = { <ide> onViewableItemsChanged: info => <ide> export function SectionList_onViewableItemsChanged(props: { <ide> viewabilityConfig, <ide> horizontal, <ide> }; <add> const ref = React.useRef(null); <add> const onTest = <add> useScrollRefScroll === true <add> ? () => { <add> ref?.current?.getScrollResponder()?.scrollToEnd(); <add> } <add> : null; <ide> <ide> return ( <ide> <SectionListExampleWithForwardedRef <add> ref={ref} <ide> exampleProps={exampleProps} <add> onTest={onTest} <ide> testOutput={output}> <ide> {offScreen === true ? <View style={styles.offScreen} /> : null} <ide> </SectionListExampleWithForwardedRef> <ide> const SectionListExampleWithForwardedRef = React.forwardRef( <ide> <View style={styles.container}> <ide> {props.testOutput != null ? ( <ide> <View testID="test_container" style={styles.testContainer}> <del> <Text numberOfLines={1} testID="output"> <add> <Text style={styles.output} numberOfLines={1} testID="output"> <ide> {props.testOutput} <ide> </Text> <ide> {props.onTest != null ? ( <ide> const styles = StyleSheet.create({ <ide> justifyContent: 'space-between', <ide> alignItems: 'center', <ide> backgroundColor: '#f2f2f7ff', <del> padding: 4, <ide> height: 40, <ide> }, <ide> output: { <add> width: '80%', <ide> fontSize: 12, <ide> }, <ide> separator: {
2
Javascript
Javascript
add test case for ssg full re-export
f1d0e577e6a29a14caba521afa11396fc3bf46f9
<ide><path>test/unit/babel-plugin-next-ssg-transform.test.js <ide> describe('babel plugin (next-ssg-transform)', () => { <ide> `"class El extends React.Component{render(){return __jsx(\\"div\\",null);}}const a=5;export var __N_SSG=true;export{El as default,a};"` <ide> ) <ide> }) <add> <add> it('should support full re-export', () => { <add> const output = babel(trim` <add> export { getStaticProps, default } from 'a' <add> `) <add> <add> expect(output).toMatchInlineSnapshot( <add> `"export var __N_SSG=true;export{default}from'a';"` <add> ) <add> }) <ide> }) <ide> })
1
Go
Go
fix duplicate calls to mountable
ffa7233d1538363fe12ad609e720b8d75e8768de
<ide><path>api/server/router/build/build_routes.go <ide> func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r * <ide> output.Write(notVerboseBuffer.Bytes()) <ide> } <ide> <del> logrus.Debugf("isflushed %v", output.Flushed()) <ide> // Do not write the error in the http output if it's still empty. <ide> // This prevents from writing a 200(OK) when there is an internal error. <ide> if !output.Flushed() { <ide><path>builder/builder-next/adapters/snapshot/snapshot.go <ide> func (s *snapshotter) Mounts(ctx context.Context, key string) (snapshot.Mountabl <ide> } <ide> if l != nil { <ide> id := identity.NewID() <del> rwlayer, err := s.opt.LayerStore.CreateRWLayer(id, l.ChainID(), nil) <del> if err != nil { <del> return nil, err <del> } <del> rootfs, err := rwlayer.Mount("") <del> if err != nil { <del> return nil, err <del> } <del> mnt := []mount.Mount{{ <del> Source: rootfs.Path(), <del> Type: "bind", <del> Options: []string{"rbind"}, <del> }} <del> return &constMountable{ <del> mounts: mnt, <add> var rwlayer layer.RWLayer <add> return &mountable{ <add> acquire: func() ([]mount.Mount, error) { <add> rwlayer, err = s.opt.LayerStore.CreateRWLayer(id, l.ChainID(), nil) <add> if err != nil { <add> return nil, err <add> } <add> rootfs, err := rwlayer.Mount("") <add> if err != nil { <add> return nil, err <add> } <add> return []mount.Mount{{ <add> Source: rootfs.Path(), <add> Type: "bind", <add> Options: []string{"rbind"}, <add> }}, nil <add> }, <ide> release: func() error { <ide> _, err := s.opt.LayerStore.ReleaseRWLayer(rwlayer) <ide> return err <ide> func (s *snapshotter) Mounts(ctx context.Context, key string) (snapshot.Mountabl <ide> <ide> id, _ := s.getGraphDriverID(key) <ide> <del> rootfs, err := s.opt.GraphDriver.Get(id, "") <del> if err != nil { <del> return nil, err <del> } <del> mnt := []mount.Mount{{ <del> Source: rootfs.Path(), <del> Type: "bind", <del> Options: []string{"rbind"}, <del> }} <del> return &constMountable{ <del> mounts: mnt, <add> return &mountable{ <add> acquire: func() ([]mount.Mount, error) { <add> rootfs, err := s.opt.GraphDriver.Get(id, "") <add> if err != nil { <add> return nil, err <add> } <add> return []mount.Mount{{ <add> Source: rootfs.Path(), <add> Type: "bind", <add> Options: []string{"rbind"}, <add> }}, nil <add> }, <ide> release: func() error { <ide> return s.opt.GraphDriver.Put(id) <ide> }, <ide> func (s *snapshotter) Close() error { <ide> return s.db.Close() <ide> } <ide> <del>type constMountable struct { <add>type mountable struct { <add> mu sync.Mutex <ide> mounts []mount.Mount <add> acquire func() ([]mount.Mount, error) <ide> release func() error <ide> } <ide> <del>func (m *constMountable) Mount() ([]mount.Mount, error) { <add>func (m *mountable) Mount() ([]mount.Mount, error) { <add> m.mu.Lock() <add> defer m.mu.Unlock() <add> <add> if m.mounts != nil { <add> return m.mounts, nil <add> } <add> <add> mounts, err := m.acquire() <add> if err != nil { <add> return nil, err <add> } <add> m.mounts = mounts <add> <ide> return m.mounts, nil <ide> } <ide> <del>func (m *constMountable) Release() error { <add>func (m *mountable) Release() error { <add> m.mu.Lock() <add> defer m.mu.Unlock() <ide> if m.release == nil { <ide> return nil <ide> } <add> <add> m.mounts = nil <ide> return m.release() <ide> }
2
Text
Text
add v3.22.1 to changelog.md
f2104f2d2a092cfdb95317f1f6745dcc498f1334
<ide><path>CHANGELOG.md <ide> - [#19136](https://github.com/emberjs/ember.js/pull/19136) [BUGFIX] Update router microlib to improve Transition related debugging <ide> - [#19173](https://github.com/emberjs/ember.js/pull/19173) [BUGFIX] Enforce usage of `capabilities` generation. <ide> <add>### v3.22.1 (November 10, 2020) <add> <add>- [#19193](https://github.com/emberjs/ember.js/pull/19193) [BUGFIX] Ensure `@ember/component` user lifecycle hooks are untracked <add>- [#19197](https://github.com/emberjs/ember.js/pull/19197) [BUGFIX] Restore the shadowed property set behavior <add>- [#19199](https://github.com/emberjs/ember.js/pull/19199) [BUGFIX] Cleans up the DebugRenderTree more thoroughly on errors <add>- [#19249](https://github.com/emberjs/ember.js/pull/19249) [BUGFIX] Fix issues with query params during intermediate transitions <add> <ide> ### v3.22.0 (October 5, 2020) <ide> <ide> - [#19062](https://github.com/emberjs/ember.js/pull/19062) / [#19068](https://github.com/emberjs/ember.js/pull/19068) [FEATURE] Add @ember/destroyable feature from the [Destroyables RFC](https://github.com/emberjs/rfcs/blob/master/text/0580-destroyables.md).
1
Python
Python
fix typo in train.py
c59cf48d7491a5d4fe512fb480d19bb8cf73743e
<ide><path>research/deeplab/train.py <ide> def main(unused_argv): <ide> first_clone_label = graph.get_tensor_by_name( <ide> ('%s/%s:0' % (first_clone_scope, common.LABEL)).strip('/')) <ide> # Scale up summary image pixel values for better visualization. <del> pixel_scaling = max(1, 255 // dataset.num_classes) <add> pixel_scaling = max(1, 255 // dataset.num_of_classes) <ide> summary_label = tf.cast(first_clone_label * pixel_scaling, tf.uint8) <ide> summaries.add( <ide> tf.summary.image('samples/%s' % common.LABEL, summary_label))
1
PHP
PHP
add test for abort case
1c4b2134d361abf6648f5edc44778d15d54d3cee
<ide><path>tests/TestCase/Console/CommandTest.php <ide> use Cake\TestSuite\Stub\ConsoleOutput; <ide> use Cake\TestSuite\TestCase; <ide> use InvalidArgumentException; <add>use TestApp\Command\AbortCommand; <ide> use TestApp\Command\AutoLoadModelCommand; <ide> use TestApp\Command\DemoCommand; <ide> <ide> public function testExecuteCommandInstance() <ide> $this->assertEquals(['Quiet!', 'Demo Command!'], $output->messages()); <ide> } <ide> <add> /** <add> * test executeCommand with an abort <add> * <add> * @return void <add> */ <add> public function testExecuteCommandAbort() <add> { <add> $output = new ConsoleOutput(); <add> $command = new Command(); <add> $result = $command->executeCommand(AbortCommand::class, [], $this->getMockIo($output)); <add> $this->assertSame(127, $result); <add> $this->assertEquals(['<error>Command aborted</error>'], $output->messages()); <add> } <add> <ide> /** <ide> * test executeCommand with an invalid instance <ide> *
1
Python
Python
add assertion for user data
a4a58f9c5b8fa4e1a6cd2d37a0356ba23d05540a
<ide><path>libcloud/test/__init__.py <ide> def assertUrlContainsQueryParams(self, url, expected_params, strict=False): <ide> self.assertDictEqual(params, expected_params) <ide> else: <ide> for key, value in expected_params.items(): <add> self.assertIn(key, params) <ide> self.assertEqual(params[key], value) <ide> <ide> <ide><path>libcloud/test/compute/test_cloudstack.py <ide> def test_create_node_ex_keyname(self): <ide> self.assertEqual(node.extra['key_name'], 'foobar') <ide> <ide> def test_create_node_ex_userdata(self): <add> self.driver.path = '/test/path/userdata' <ide> size = self.driver.list_sizes()[0] <ide> image = self.driver.list_images()[0] <ide> location = self.driver.list_locations()[0] <ide> def _test_path(self, method, url, body, headers): <ide> body, obj = self._load_fixture(fixture) <ide> return (httplib.OK, body, obj, httplib.responses[httplib.OK]) <ide> <add> def _test_path_userdata(self, method, url, body, headers): <add> if 'deployVirtualMachine' in url: <add> self.assertUrlContainsQueryParams(url, {'userdata': 'Zm9vYmFy'}) <add> return self._test_path(method, url, body, headers) <add> <ide> def _cmd_queryAsyncJobResult(self, jobid): <ide> fixture = 'queryAsyncJobResult' + '_' + str(jobid) + '.json' <ide> body, obj = self._load_fixture(fixture)
2
PHP
PHP
add tests for parsedatetime(1970)
62885abbebcc5d7dd442ffc590da6db5f3cfd7a9
<ide><path>tests/TestCase/I18n/TimeTest.php <ide> public function testDebugInfo() <ide> */ <ide> public function testParseDateTime() <ide> { <add> $time = Time::parseDateTime('01/01/1970 00:00am'); <add> $this->assertNotNull($time); <add> $this->assertEquals('1970-01-01 00:00', $time->format('Y-m-d H:i')); <add> <ide> $time = Time::parseDateTime('10/13/2013 12:54am'); <ide> $this->assertNotNull($time); <ide> $this->assertEquals('2013-10-13 00:54', $time->format('Y-m-d H:i'));
1
Text
Text
remove quotation marks from code tag text
fe3f0b2ac48c277f2f1c3c8706c7187082d82c5d
<ide><path>curriculum/challenges/english/01-responsive-web-design/applied-accessibility/standardize-times-with-the-html5-datetime-attribute.english.md <ide> Camper Cat's Mortal Kombat survey results are in! Wrap a <code>time</code> tag a <ide> <ide> ```yml <ide> tests: <del> - text: Your code should have a <code>p</code> element which includes the text "Thank you to everyone for responding to Master Camper Cat's survey." and include a <code>time</code> element. <add> - text: Your code should have a <code>p</code> element which includes the text <code>Thank you to everyone for responding to Master Camper Cat's survey.</code> and include a <code>time</code> element. <ide> testString: assert(timeElement.length); <del> - text: Your added <code>time</code> tags should wrap around the text "Thursday, September 15&lt;sup&gt;th&lt;/sup&gt;". <add> - text: Your added <code>time</code> tags should wrap around the text <code>Thursday, September 15&lt;sup&gt;th&lt;/sup&gt;</code>. <ide> testString: assert(timeElement.length && $(timeElement).html().trim() === "Thursday, September 15<sup>th</sup>"); <ide> - text: Your added <code>time</code> tag should have a <code>datetime</code> attribute that is not empty. <ide> testString: assert(datetimeAttr && datetimeAttr.length); <del> - text: Your added <code>datetime</code> attribute should be set to a value of 2016-09-15. <add> - text: Your added <code>datetime</code> attribute should be set to a value of <code>2016-09-15</code>. <ide> testString: assert(datetimeAttr === "2016-09-15"); <ide> ``` <ide> <ide><path>curriculum/challenges/english/01-responsive-web-design/applied-visual-design/use-the-strong-tag-to-make-text-bold.english.md <ide> tests: <ide> testString: assert($('strong').length == 1); <ide> - text: The <code>strong</code> tag should be inside the <code>p</code> tag. <ide> testString: assert($('p').children('strong').length == 1); <del> - text: The <code>strong</code> tag should wrap around the words "Stanford University". <add> - text: The <code>strong</code> tag should wrap around the words <code>Stanford University</code>. <ide> testString: assert($('strong').text().match(/^Stanford University\.?$/gi)); <ide> ``` <ide> <ide><path>curriculum/challenges/english/01-responsive-web-design/applied-visual-design/use-the-u-tag-to-underline-text.english.md <ide> Wrap the <code>u</code> tag only around the text "Ph.D. students". <ide> tests: <ide> - text: Your code should add a <code>u</code> tag to the markup. <ide> testString: assert($('u').length === 1); <del> - text: The <code>u</code> tag should wrap around the text "Ph.D. students". <add> - text: The <code>u</code> tag should wrap around the text <code>Ph.D. students</code>. <ide> testString: assert($('u').text() === 'Ph.D. students'); <ide> <ide> ``` <ide><path>curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/add-a-submit-button-to-a-form.english.md <ide> tests: <ide> testString: assert($("form").children("button").length > 0); <ide> - text: Your submit button should have the attribute <code>type</code> set to <code>submit</code>. <ide> testString: assert($("button").attr("type") === "submit"); <del> - text: Your submit button should only have the text "Submit". <add> - text: Your submit button should only have the text <code>Submit</code>. <ide> testString: assert($("button").text().match(/^\s*submit\s*$/gi)); <ide> - text: Your <code>button</code> element should have a closing tag. <ide> testString: assert(code.match(/<\/button>/g) && code.match(/<button/g) && code.match(/<\/button>/g).length === code.match(/<button/g).length); <ide><path>curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/add-placeholder-text-to-a-text-field.english.md <ide> Set the <code>placeholder</code> value of your text <code>input</code> to "cat p <ide> tests: <ide> - text: You should add a <code>placeholder</code> attribute to the existing text <code>input</code> element. <ide> testString: assert($("input[placeholder]").length > 0); <del> - text: You should set the value of your placeholder attribute to "cat photo URL". <add> - text: You should set the value of your placeholder attribute to <code>cat photo URL</code>. <ide> testString: assert($("input") && $("input").attr("placeholder") && $("input").attr("placeholder").match(/cat\s+photo\s+URL/gi)); <ide> - text: The finished <code>input</code> element should not have a closing tag. <ide> testString: assert(!code.match(/<input.*\/?>.*<\/input>/gi)); <ide><path>curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/create-an-ordered-list.english.md <ide> Create an ordered list of the top 3 things cats hate the most. <ide> <ide> ```yml <ide> tests: <del> - text: You should have an ordered list for "Top 3 things cats hate:" <add> - text: You should have an ordered list for <code>Top 3 things cats hate:</code> <ide> testString: assert((/Top 3 things cats hate:/i).test($("ol").prev().text())); <del> - text: You should have an unordered list for "Things cats love:" <add> - text: You should have an unordered list for <code>Things cats love:</code> <ide> testString: assert((/Things cats love:/i).test($("ul").prev().text())); <ide> - text: You should have only one <code>ul</code> element. <ide> testString: assert.equal($("ul").length, 1); <ide><path>curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/headline-with-the-h2-element.english.md <ide> tests: <ide> testString: assert(($("h2").length > 0)); <ide> - text: Your <code>h2</code> element should have a closing tag. <ide> testString: assert(code.match(/<\/h2>/g) && code.match(/<\/h2>/g).length === code.match(/<h2>/g).length); <del> - text: Your <code>h2</code> element should have the text "CatPhotoApp". <add> - text: Your <code>h2</code> element should have the text <code>CatPhotoApp</code>. <ide> testString: assert.isTrue((/cat(\s)?photo(\s)?app/gi).test($("h2").text())); <del> - text: Your <code>h1</code> element should have the text "Hello World". <add> - text: Your <code>h1</code> element should have the text <code>Hello World</code>. <ide> testString: assert.isTrue((/hello(\s)+world/gi).test($("h1").text())); <ide> - text: Your <code>h1</code> element should be before your <code>h2</code> element. <ide> testString: assert(code.match(/<h1>\s*?.*?\s*?<\/h1>\s*<h2>\s*?.*?\s*?<\/h2>/gi)); <ide><path>curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/inform-with-the-paragraph-element.english.md <ide> Create a <code>p</code> element below your <code>h2</code> element, and give it <ide> tests: <ide> - text: Your code should have a valid <code>p</code> element. <ide> testString: assert(($("p").length > 0)); <del> - text: Your <code>p</code> element should have the text "Hello Paragraph". <add> - text: Your <code>p</code> element should have the text <code>Hello Paragraph</code>. <ide> testString: assert.isTrue((/hello(\s)+paragraph/gi).test($("p").text())); <ide> - text: Your <code>p</code> element should have a closing tag. <ide> testString: assert(code.match(/<\/p>/g) && code.match(/<\/p>/g).length === code.match(/<p/g).length);
8
PHP
PHP
fix code style 2
4883bb5ae32ba3b79a67598932b648f8f85ecf32
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public function qualifyColumns($columns) <ide> foreach ($columns as $column) { <ide> $qualifiedArray[] = $this->qualifyColumn($column); <ide> } <add> <ide> return $qualifiedArray; <ide> } <ide>
1
Javascript
Javascript
move beforeblur phase to prepareforcommit
bf55ea743496f4fb71df982af0324e322f25046c
<ide><path>packages/react-dom/src/client/ReactDOMHostConfig.js <ide> import { <ide> enableUseEventAPI, <ide> enableScopeAPI, <ide> } from 'shared/ReactFeatureFlags'; <del>import {HostComponent} from 'react-reconciler/src/ReactWorkTags'; <ide> import { <ide> RESPONDER_EVENT_SYSTEM, <ide> IS_PASSIVE, <ide> import { <ide> import {getListenerMapForElement} from '../events/DOMEventListenerMap'; <ide> import {TOP_BEFORE_BLUR, TOP_AFTER_BLUR} from '../events/DOMTopLevelEventTypes'; <ide> <add>// TODO: This is an exposed internal, we should move this around <add>// so this isn't the case. <add>import {isFiberInsideHiddenOrRemovedTree} from 'react-reconciler/src/ReactFiberTreeReflection'; <add> <ide> export type ReactListenerEvent = ReactDOMListenerEvent; <ide> export type ReactListenerMap = ReactDOMListenerMap; <ide> export type ReactListener = ReactDOMListener; <ide> export function getPublicInstance(instance: Instance): * { <ide> export function prepareForCommit(containerInfo: Container): void { <ide> eventsEnabled = ReactBrowserEventEmitterIsEnabled(); <ide> selectionInformation = getSelectionInformation(); <add> if (enableDeprecatedFlareAPI || enableUseEventAPI) { <add> const focusedElem = selectionInformation.focusedElem; <add> if (focusedElem !== null) { <add> const instance = getClosestInstanceFromNode(focusedElem); <add> if (instance !== null && isFiberInsideHiddenOrRemovedTree(instance)) { <add> dispatchBeforeDetachedBlur(focusedElem); <add> } <add> } <add> } <ide> ReactBrowserEventEmitterSetEnabled(false); <ide> } <ide> <ide> function dispatchBeforeDetachedBlur(target: HTMLElement): void { <ide> ); <ide> } <ide> if (enableUseEventAPI) { <del> try { <del> // We need to temporarily enable the event system <del> // to dispatch the "beforeblur" event. <del> ReactBrowserEventEmitterSetEnabled(true); <del> const event = createEvent(TOP_BEFORE_BLUR); <del> // Dispatch "beforeblur" directly on the target, <del> // so it gets picked up by the event system and <del> // can propagate through the React internal tree. <del> target.dispatchEvent(event); <del> } finally { <del> ReactBrowserEventEmitterSetEnabled(false); <del> } <add> const event = createEvent(TOP_BEFORE_BLUR); <add> // Dispatch "beforeblur" directly on the target, <add> // so it gets picked up by the event system and <add> // can propagate through the React internal tree. <add> target.dispatchEvent(event); <ide> } <ide> } <ide> <ide> function dispatchAfterDetachedBlur(target: HTMLElement): void { <ide> } <ide> } <ide> <del>// This is a specific event for the React Flare <del>// event system, so event responders can act <del>// accordingly to a DOM node being unmounted that <del>// previously had active document focus. <ide> export function beforeRemoveInstance( <ide> instance: Instance | TextInstance | SuspenseInstance, <ide> ): void { <del> if ( <del> (enableDeprecatedFlareAPI || enableUseEventAPI) && <del> selectionInformation && <del> instance === selectionInformation.focusedElem <del> ) { <del> dispatchBeforeDetachedBlur(((instance: any): HTMLElement)); <del> } <ide> if (enableUseEventAPI) { <ide> // It's unfortunate that we have to do this cleanup, but <ide> // it's necessary otherwise we will leak the host instances <ide> export function clearSuspenseBoundaryFromContainer( <ide> retryIfBlockedOn(container); <ide> } <ide> <del>function instanceContainsElem(instance: Instance, element: HTMLElement) { <del> let fiber = getClosestInstanceFromNode(element); <del> while (fiber !== null) { <del> if (fiber.tag === HostComponent && fiber.stateNode === instance) { <del> return true; <del> } <del> fiber = fiber.return; <del> } <del> return false; <del>} <del> <ide> export function hideInstance(instance: Instance): void { <del> // Ensure we trigger `onBeforeBlur` if the active focused elment <del> // is ether the instance of a child or the instance. We need <del> // to traverse the Fiber tree here rather than use node.contains() <del> // as the child node might be inside a Portal. <del> if ((enableDeprecatedFlareAPI || enableUseEventAPI) && selectionInformation) { <del> const focusedElem = selectionInformation.focusedElem; <del> if (focusedElem !== null && instanceContainsElem(instance, focusedElem)) { <del> dispatchBeforeDetachedBlur(((focusedElem: any): HTMLElement)); <del> } <del> } <ide> // TODO: Does this work for all element types? What about MathML? Should we <ide> // pass host context to this method? <ide> instance = ((instance: any): HTMLElement); <ide><path>packages/react-interactions/events/src/dom/__tests__/FocusWithin-test.internal.js <ide> const initializeModules = hasPointerEvents => { <ide> jest.resetModules(); <ide> ReactFeatureFlags = require('shared/ReactFeatureFlags'); <ide> ReactFeatureFlags.enableDeprecatedFlareAPI = true; <add> ReactFeatureFlags.enableScopeAPI = true; <ide> React = require('react'); <ide> ReactDOM = require('react-dom'); <ide> Scheduler = require('scheduler'); <ide> describe.each(table)('FocusWithin responder', hasPointerEvents => { <ide> ); <ide> }); <ide> <add> // @gate experimental <add> it('is called after a nested focused element is unmounted (with scope query)', () => { <add> const TestScope = React.unstable_createScope(); <add> const testScopeQuery = (type, props) => true; <add> let targetNodes; <add> let targetNode; <add> <add> const Component = ({show}) => { <add> const scopeRef = React.useRef(null); <add> const listener = useFocusWithin({ <add> onBeforeBlurWithin(event) { <add> const scope = scopeRef.current; <add> targetNode = innerRef.current; <add> targetNodes = scope.DO_NOT_USE_queryAllNodes(testScopeQuery); <add> }, <add> }); <add> <add> return ( <add> <TestScope ref={scopeRef} DEPRECATED_flareListeners={[listener]}> <add> {show && <input ref={innerRef} />} <add> </TestScope> <add> ); <add> }; <add> <add> ReactDOM.render(<Component show={true} />, container); <add> <add> const inner = innerRef.current; <add> const target = createEventTarget(inner); <add> target.keydown({key: 'Tab'}); <add> target.focus(); <add> ReactDOM.render(<Component show={false} />, container); <add> expect(targetNodes).toEqual([targetNode]); <add> }); <add> <ide> // @gate experimental <ide> it('is called after a focused suspended element is hidden', () => { <ide> const Suspense = React.Suspense; <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js <ide> function detachFiber(fiber: Fiber) { <ide> // get GC:ed but we don't know which for sure which parent is the current <ide> // one so we'll settle for GC:ing the subtree of this child. This child <ide> // itself will be GC:ed when the parent updates the next time. <del> fiber.return = null; <add> fiber.alternate = null; <ide> fiber.child = null; <del> fiber.memoizedState = null; <del> fiber.updateQueue = null; <ide> fiber.dependencies = null; <del> fiber.alternate = null; <ide> fiber.firstEffect = null; <ide> fiber.lastEffect = null; <del> fiber.pendingProps = null; <ide> fiber.memoizedProps = null; <add> fiber.memoizedState = null; <add> fiber.pendingProps = null; <add> fiber.return = null; <add> fiber.sibling = null; <ide> fiber.stateNode = null; <add> fiber.updateQueue = null; <add> if (__DEV__) { <add> fiber._debugOwner = null; <add> } <ide> } <ide> <ide> function emptyPortalContainer(current: Fiber) { <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.old.js <ide> function detachFiber(fiber: Fiber) { <ide> // get GC:ed but we don't know which for sure which parent is the current <ide> // one so we'll settle for GC:ing the subtree of this child. This child <ide> // itself will be GC:ed when the parent updates the next time. <del> fiber.return = null; <add> fiber.alternate = null; <ide> fiber.child = null; <del> fiber.memoizedState = null; <del> fiber.updateQueue = null; <ide> fiber.dependencies = null; <del> fiber.alternate = null; <ide> fiber.firstEffect = null; <ide> fiber.lastEffect = null; <del> fiber.pendingProps = null; <ide> fiber.memoizedProps = null; <add> fiber.memoizedState = null; <add> fiber.pendingProps = null; <add> fiber.return = null; <add> fiber.sibling = null; <ide> fiber.stateNode = null; <add> fiber.updateQueue = null; <add> if (__DEV__) { <add> fiber._debugOwner = null; <add> } <ide> } <ide> <ide> function emptyPortalContainer(current: Fiber) { <ide><path>packages/react-reconciler/src/ReactFiberScope.new.js <ide> import type { <ide> } from 'shared/ReactTypes'; <ide> <ide> import {getPublicInstance, getInstanceFromNode} from './ReactFiberHostConfig'; <add>import {isFiberSuspenseAndTimedOut} from './ReactFiberTreeReflection'; <ide> <del>import { <del> HostComponent, <del> SuspenseComponent, <del> ScopeComponent, <del> ContextProvider, <del>} from './ReactWorkTags'; <add>import {HostComponent, ScopeComponent, ContextProvider} from './ReactWorkTags'; <ide> import {enableScopeAPI} from 'shared/ReactFeatureFlags'; <ide> <del>function isFiberSuspenseAndTimedOut(fiber: Fiber): boolean { <del> const memoizedState = fiber.memoizedState; <del> return ( <del> fiber.tag === SuspenseComponent && <del> memoizedState !== null && <del> memoizedState.dehydrated === null <del> ); <del>} <del> <ide> function getSuspenseFallbackChild(fiber: Fiber): Fiber | null { <ide> return ((((fiber.child: any): Fiber).sibling: any): Fiber).child; <ide> } <ide><path>packages/react-reconciler/src/ReactFiberScope.old.js <ide> import type { <ide> } from 'shared/ReactTypes'; <ide> <ide> import {getPublicInstance, getInstanceFromNode} from './ReactFiberHostConfig'; <add>import {isFiberSuspenseAndTimedOut} from './ReactFiberTreeReflection'; <ide> <del>import { <del> HostComponent, <del> SuspenseComponent, <del> ScopeComponent, <del> ContextProvider, <del>} from './ReactWorkTags'; <add>import {HostComponent, ScopeComponent, ContextProvider} from './ReactWorkTags'; <ide> import {enableScopeAPI} from 'shared/ReactFeatureFlags'; <ide> <del>function isFiberSuspenseAndTimedOut(fiber: Fiber): boolean { <del> const memoizedState = fiber.memoizedState; <del> return ( <del> fiber.tag === SuspenseComponent && <del> memoizedState !== null && <del> memoizedState.dehydrated === null <del> ); <del>} <del> <ide> function getSuspenseFallbackChild(fiber: Fiber): Fiber | null { <ide> return ((((fiber.child: any): Fiber).sibling: any): Fiber).child; <ide> } <ide><path>packages/react-reconciler/src/ReactFiberTreeReflection.js <ide> import { <ide> FundamentalComponent, <ide> SuspenseComponent, <ide> } from './ReactWorkTags'; <del>import {NoEffect, Placement, Hydrating} from './ReactSideEffectTags'; <add>import {NoEffect, Placement, Hydrating, Deletion} from './ReactSideEffectTags'; <ide> import {enableFundamentalAPI} from 'shared/ReactFeatureFlags'; <ide> <ide> const ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; <ide> export function findCurrentHostFiberWithNoPortals(parent: Fiber): Fiber | null { <ide> // eslint-disable-next-line no-unreachable <ide> return null; <ide> } <add> <add>export function isFiberSuspenseAndTimedOut(fiber: Fiber): boolean { <add> const memoizedState = fiber.memoizedState; <add> return ( <add> fiber.tag === SuspenseComponent && <add> memoizedState !== null && <add> memoizedState.dehydrated === null <add> ); <add>} <add> <add>// This is only safe to call in the commit phase when the return tree is consistent. <add>// It should not be used anywhere else. See PR #18609 for details. <add>export function isFiberInsideHiddenOrRemovedTree(fiber: Fiber): boolean { <add> let node = fiber; <add> while (node !== null) { <add> if (node.effectTag & Deletion || isFiberSuspenseAndTimedOut(node)) { <add> return true; <add> } <add> node = node.return; <add> } <add> return false; <add>}
7
PHP
PHP
fix alias usage
609104806b8b639710268c75c22f43034c2b72db
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> public function firstOr($columns = ['*'], Closure $callback = null) <ide> public function value($column) <ide> { <ide> if ($result = $this->first([$column])) { <del> return $result->{$column}; <add> return $result->{Str::afterLast($column, '.')}; <ide> } <ide> } <ide>
1
Javascript
Javascript
fix mock for textinput
5a3c6faee9c44a2d99b13d113c91dbf98990f8af
<ide><path>jest/setup.js <ide> jest <ide> mockComponent('../Libraries/Text/Text', MockNativeMethods), <ide> ) <ide> .mock('../Libraries/Components/TextInput/TextInput', () => <del> mockComponent( <del> '../Libraries/Components/TextInput/TextInput', <del> MockNativeMethods, <del> ), <add> mockComponent('../Libraries/Components/TextInput/TextInput', { <add> ...MockNativeMethods, <add> isFocused: jest.fn(), <add> clear: jest.fn(), <add> getNativeRef: jest.fn(), <add> }), <ide> ) <ide> .mock('../Libraries/Modal/Modal', () => <ide> mockComponent('../Libraries/Modal/Modal'),
1
Javascript
Javascript
add touch (zoom) support to d3.behavior.zoom
c29a12168770f34dd8117d698521d7a320c4a659
<ide><path>d3.behavior.js <ide> d3.behavior.zoom = function() { <ide> z = 0, <ide> listeners = [], <ide> pan, <del> zoom; <add> zoom, <add> last = 0; <ide> <ide> function zoom() { <ide> var container = this <ide> .on("mousedown", mousedown) <ide> .on("mousewheel", mousewheel) <ide> .on("DOMMouseScroll", mousewheel) <ide> .on("dblclick", mousewheel) <del> .on("touchstart", mousedown); <add> .on("touchstart", touchstart); <ide> <ide> d3.select(window) <ide> .on("mousemove", mousemove) <ide> .on("mouseup", mouseup) <del> .on("touchmove", mousemove) <del> .on("touchend", mouseup) <del> .on("touchcancel", mouseup); <add> .on("touchmove", touchmove); <add> } <add> <add> function touchstart(d, i) { <add> var n = d3.event.touches.length, <add> t = Date.now(); <add> <add> // doubletap detection <add> if ((n === 1) && (t - last < 300)) { <add> var p = d3.svg.touches(this.nearestViewportElement || this)[0], <add> z0 = z; <add> <add> z = Math.floor(z) + 1; <add> <add> // adjust x and y to center around mouse location <add> var k = Math.pow(2, z - z0) - 1; <add> x += (x - p[0]) * k; <add> y += (y - p[1]) * k; <add> <add> // dispatch redraw <add> dispatch.call(this, d, i); <add> } else if (n > 0) { <add> var p, <add> t0 = d3.event.touches[0]; <add> if (n > 1) { <add> // Use d3.svg.touches to avoid drift. <add> var svgp = d3.svg.touches(this.nearestViewportElement || this), <add> t1 = d3.event.touches[1]; <add> zoom = { <add> x1: x - (svgp[0][0] + svgp[1][0]) / 2, <add> y1: y - (svgp[0][1] + svgp[1][1]) / 2, <add> z0: z <add> }; <add> p = [(t0.clientX + t1.clientX) / 2, (t0.clientY + t1.clientY) / 2]; <add> } else p = [t0.clientX, t0.clientY]; <add> pan = { <add> x0: x - p[0], <add> y0: y - p[1], <add> target: this, <add> data: d, <add> index: i <add> }; <add> } <add> last = t; <add> d3.event.preventDefault(); <add> window.focus(); // TODO focusableParent <add> } <add> <add> function touchmove(d, i) { <add> var e = d3.event; <add> switch (e.touches.length) { <add> case 1: { // single-touch pan <add> var t0 = e.touches[0]; <add> if (pan) { <add> x = t0.clientX + pan.x0; <add> y = t0.clientY + pan.y0; <add> dispatch.call(pan.target, pan.data, pan.index); <add> } <add> e.preventDefault(); <add> break; <add> } <add> case 2: { // double-touch pan + zoom + rotate <add> var t0 = e.touches[0], <add> t1 = e.touches[1], <add> k = e.scale - 1; <add> <add> x = pan.x0 + zoom.x1 * k + (t0.clientX + t1.clientX) / 2; <add> y = pan.y0 + zoom.y1 * k + (t0.clientY + t1.clientY) / 2; <add> z = zoom.z0 + Math.log(e.scale) / Math.LN2; <add> <add> // dispatch redraw <add> dispatch.call(this, d, i); <add> e.preventDefault(); <add> break; <add> } <add> } <ide> } <ide> <ide> function mousedown(d, i) { <del> var touches = d3.event.touches, <del> e = touches ? touches[0] : d3.event; <ide> pan = { <del> x0: x - e.clientX, <del> y0: y - e.clientY, <add> x0: x - d3.event.clientX, <add> y0: y - d3.event.clientY, <ide> target: this, <ide> data: d, <ide> index: i <ide> d3.behavior.zoom = function() { <ide> } <ide> <ide> function mousemove() { <del> var touches = d3.event.touches, <del> e = touches ? touches[0] : d3.event; <ide> zoom = null; <ide> if (pan) { <del> x = e.clientX + pan.x0; <del> y = e.clientY + pan.y0; <add> x = d3.event.clientX + pan.x0; <add> y = d3.event.clientY + pan.y0; <ide> dispatch.call(pan.target, pan.data, pan.index); <ide> } <ide> } <ide><path>d3.behavior.min.js <del>(function(){d3.behavior={},d3.behavior.zoom=function(){function m(a,b){function i(a,b){var c=a.__domain||(a.__domain=a.domain()),d=a.range().map(function(a){return(a-b)/h});a.domain(c).domain(d.map(a.invert))}var g=d3.event,h=Math.pow(2,e);d3.event={scale:h,translate:[c,d],transform:function(a,b){a&&i(a,c),b&&i(b,d)}};try{for(var j=0,k=f.length;j<k;j++)f[j].call(this,a,b)}finally{d3.event=g}}function l(f,g){var i=d3.event;if(!h){var j=d3.svg.mouse(this.nearestViewportElement||this);h={x0:c,y0:d,z0:e,x1:c-j[0],y1:d-j[1]}}if(i.type==="dblclick")e=i.shiftKey?Math.ceil(e-1):Math.floor(e+1);else{var k=(i.wheelDelta/120||-i.detail)*.1;if(a<0){var l=Date.now(),n=l-b;n>9&&Math.abs(i.wheelDelta)/n>=50&&(a=1),b=l}a===1&&(k*=.03),e+=k}var o=Math.pow(2,e-h.z0)-1;c=h.x0+h.x1*o,d=h.y0+h.y1*o,m.call(this,f,g)}function k(){g&&(j(),g=null)}function j(){var a=d3.event.touches,b=a?a[0]:d3.event;h=null,g&&(c=b.clientX+g.x0,d=b.clientY+g.y0,m.call(g.target,g.data,g.index))}function i(a,b){var e=d3.event.touches,f=e?e[0]:d3.event;g={x0:c-f.clientX,y0:d-f.clientY,target:this,data:a,index:b},d3.event.preventDefault(),window.focus()}function h(){var a=this.on("mousedown",i).on("mousewheel",l).on("DOMMouseScroll",l).on("dblclick",l).on("touchstart",i);d3.select(window).on("mousemove",j).on("mouseup",k).on("touchmove",j).on("touchend",k).on("touchcancel",k)}var a=/WebKit\/533/.test(navigator.userAgent)?-1:0,b=0,c=0,d=0,e=0,f=[],g,h;h.on=function(a,b){a=="zoom"&&f.push(b);return h};return h}})() <ide>\ No newline at end of file <add>(function(){d3.behavior={},d3.behavior.zoom=function(){function p(a,b){function i(a,b){var c=a.__domain||(a.__domain=a.domain()),d=a.range().map(function(a){return(a-b)/h});a.domain(c).domain(d.map(a.invert))}var g=d3.event,h=Math.pow(2,e);d3.event={scale:h,translate:[c,d],transform:function(a,b){a&&i(a,c),b&&i(b,d)}};try{for(var j=0,k=f.length;j<k;j++)f[j].call(this,a,b)}finally{d3.event=g}}function o(f,g){var i=d3.event;if(!h){var j=d3.svg.mouse(this.nearestViewportElement||this);h={x0:c,y0:d,z0:e,x1:c-j[0],y1:d-j[1]}}if(i.type==="dblclick")e=i.shiftKey?Math.ceil(e-1):Math.floor(e+1);else{var k=(i.wheelDelta/120||-i.detail)*.1;if(a<0){var l=Date.now(),m=l-b;m>9&&Math.abs(i.wheelDelta)/m>=50&&(a=1),b=l}a===1&&(k*=.03),e+=k}var n=Math.pow(2,e-h.z0)-1;c=h.x0+h.x1*n,d=h.y0+h.y1*n,p.call(this,f,g)}function n(){g&&(m(),g=null)}function m(){h=null,g&&(c=d3.event.clientX+g.x0,d=d3.event.clientY+g.y0,p.call(g.target,g.data,g.index))}function l(a,b){g={x0:c-d3.event.clientX,y0:d-d3.event.clientY,target:this,data:a,index:b},d3.event.preventDefault(),window.focus()}function k(a,b){var f=d3.event;switch(f.touches.length){case 1:var i=f.touches[0];g&&(c=i.clientX+g.x0,d=i.clientY+g.y0,p.call(g.target,g.data,g.index)),f.preventDefault();break;case 2:var i=f.touches[0],j=f.touches[1],k=f.scale-1;c=g.x0+h.x1*k+(i.clientX+j.clientX)/2,d=g.y0+h.y1*k+(i.clientY+j.clientY)/2,e=h.z0+Math.log(f.scale)/Math.LN2,p.call(this,a,b),f.preventDefault()}}function j(a,b){var f=d3.event.touches.length,j=Date.now();if(f===1&&j-i<300){var k=d3.svg.touches(this.nearestViewportElement||this)[0],l=e;e=Math.floor(e)+1;var m=Math.pow(2,e-l)-1;c+=(c-k[0])*m,d+=(d-k[1])*m,p.call(this,a,b)}else if(f>0){var k,n=d3.event.touches[0];if(f>1){var o=d3.svg.touches(this.nearestViewportElement||this),q=d3.event.touches[1];h={x1:c-(o[0][0]+o[1][0])/2,y1:d-(o[0][1]+o[1][1])/2,z0:e},k=[(n.clientX+q.clientX)/2,(n.clientY+q.clientY)/2]}else k=[n.clientX,n.clientY];g={x0:c-k[0],y0:d-k[1],target:this,data:a,index:b}}i=j,d3.event.preventDefault(),window.focus()}function h(){var a=this.on("mousedown",l).on("mousewheel",o).on("DOMMouseScroll",o).on("dblclick",o).on("touchstart",j);d3.select(window).on("mousemove",m).on("mouseup",n).on("touchmove",k)}var a=/WebKit\/533/.test(navigator.userAgent)?-1:0,b=0,c=0,d=0,e=0,f=[],g,h,i=0;h.on=function(a,b){a=="zoom"&&f.push(b);return h};return h}})() <ide>\ No newline at end of file <ide><path>src/behavior/zoom.js <ide> d3.behavior.zoom = function() { <ide> z = 0, <ide> listeners = [], <ide> pan, <del> zoom; <add> zoom, <add> last = 0; <ide> <ide> function zoom() { <ide> var container = this <ide> .on("mousedown", mousedown) <ide> .on("mousewheel", mousewheel) <ide> .on("DOMMouseScroll", mousewheel) <ide> .on("dblclick", mousewheel) <del> .on("touchstart", mousedown); <add> .on("touchstart", touchstart); <ide> <ide> d3.select(window) <ide> .on("mousemove", mousemove) <ide> .on("mouseup", mouseup) <del> .on("touchmove", mousemove) <del> .on("touchend", mouseup) <del> .on("touchcancel", mouseup); <add> .on("touchmove", touchmove); <add> } <add> <add> function touchstart(d, i) { <add> var n = d3.event.touches.length, <add> t = Date.now(); <add> <add> // doubletap detection <add> if ((n === 1) && (t - last < 300)) { <add> var p = d3.svg.touches(this.nearestViewportElement || this)[0], <add> z0 = z; <add> <add> z = Math.floor(z) + 1; <add> <add> // adjust x and y to center around mouse location <add> var k = Math.pow(2, z - z0) - 1; <add> x += (x - p[0]) * k; <add> y += (y - p[1]) * k; <add> <add> // dispatch redraw <add> dispatch.call(this, d, i); <add> } else if (n > 0) { <add> var p, <add> t0 = d3.event.touches[0]; <add> if (n > 1) { <add> // Use d3.svg.touches to avoid drift. <add> var svgp = d3.svg.touches(this.nearestViewportElement || this), <add> t1 = d3.event.touches[1]; <add> zoom = { <add> x1: x - (svgp[0][0] + svgp[1][0]) / 2, <add> y1: y - (svgp[0][1] + svgp[1][1]) / 2, <add> z0: z <add> }; <add> p = [(t0.clientX + t1.clientX) / 2, (t0.clientY + t1.clientY) / 2]; <add> } else p = [t0.clientX, t0.clientY]; <add> pan = { <add> x0: x - p[0], <add> y0: y - p[1], <add> target: this, <add> data: d, <add> index: i <add> }; <add> } <add> last = t; <add> d3.event.preventDefault(); <add> window.focus(); // TODO focusableParent <add> } <add> <add> function touchmove(d, i) { <add> var e = d3.event; <add> switch (e.touches.length) { <add> case 1: { // single-touch pan <add> var t0 = e.touches[0]; <add> if (pan) { <add> x = t0.clientX + pan.x0; <add> y = t0.clientY + pan.y0; <add> dispatch.call(pan.target, pan.data, pan.index); <add> } <add> e.preventDefault(); <add> break; <add> } <add> case 2: { // double-touch pan + zoom + rotate <add> var t0 = e.touches[0], <add> t1 = e.touches[1], <add> k = e.scale - 1; <add> <add> x = pan.x0 + zoom.x1 * k + (t0.clientX + t1.clientX) / 2; <add> y = pan.y0 + zoom.y1 * k + (t0.clientY + t1.clientY) / 2; <add> z = zoom.z0 + Math.log(e.scale) / Math.LN2; <add> <add> // dispatch redraw <add> dispatch.call(this, d, i); <add> e.preventDefault(); <add> break; <add> } <add> } <ide> } <ide> <ide> function mousedown(d, i) { <del> var touches = d3.event.touches, <del> e = touches ? touches[0] : d3.event; <ide> pan = { <del> x0: x - e.clientX, <del> y0: y - e.clientY, <add> x0: x - d3.event.clientX, <add> y0: y - d3.event.clientY, <ide> target: this, <ide> data: d, <ide> index: i <ide> d3.behavior.zoom = function() { <ide> } <ide> <ide> function mousemove() { <del> var touches = d3.event.touches, <del> e = touches ? touches[0] : d3.event; <ide> zoom = null; <ide> if (pan) { <del> x = e.clientX + pan.x0; <del> y = e.clientY + pan.y0; <add> x = d3.event.clientX + pan.x0; <add> y = d3.event.clientY + pan.y0; <ide> dispatch.call(pan.target, pan.data, pan.index); <ide> } <ide> }
3
Text
Text
add 4.0 to security policy
4bb89e7c5c3d57ea21daeb0fc4ac7e66ccaf0382
<ide><path>SECURITY.md <ide> We support fixing security issues on the following releases: <ide> <ide> | Version | Supported | <ide> | ------- | ------------------ | <add>| 4.0.x | :white_check_mark: | <add>| 3.8.x | :white_check_mark: | <ide> | 3.7.x | :white_check_mark: | <del>| 3.6.x | :white_check_mark: | <del>| <= 3.5 | :x: | <add>| <= 3.6 | :x: | <ide> | 2.10.x | :white_check_mark: | <ide> | <= 2.9 | :x: | <ide>
1
Go
Go
remove httputils dependency from api client lib
83b5729f6452de6b40719b9485947eea0bd0eedd
<ide><path>api/client/lib/image_build.go <ide> import ( <ide> "encoding/json" <ide> "net/http" <ide> "net/url" <add> "regexp" <ide> "strconv" <ide> <ide> "github.com/docker/docker/api/types" <del> "github.com/docker/docker/pkg/httputils" <ide> "github.com/docker/docker/pkg/units" <ide> "github.com/docker/docker/runconfig" <ide> ) <ide> <add>var headerRegexp = regexp.MustCompile(`\ADocker/.+\s\((.+)\)\z`) <add> <ide> // ImageBuild sends request to the daemon to build images. <ide> // The Body in the response implement an io.ReadCloser and it's up to the caller to <ide> // close it. <ide> func (cli *Client) ImageBuild(options types.ImageBuildOptions) (types.ImageBuild <ide> return types.ImageBuildResponse{}, err <ide> } <ide> <del> var osType string <del> if h, err := httputils.ParseServerHeader(serverResp.header.Get("Server")); err == nil { <del> osType = h.OS <del> } <add> osType := getDockerOS(serverResp.header.Get("Server")) <ide> <ide> return types.ImageBuildResponse{ <ide> Body: serverResp.body, <ide> func imageBuildOptionsToQuery(options types.ImageBuildOptions) (url.Values, erro <ide> <ide> return query, nil <ide> } <add> <add>func getDockerOS(serverHeader string) string { <add> var osType string <add> matches := headerRegexp.FindStringSubmatch(serverHeader) <add> if len(matches) > 0 { <add> osType = matches[1] <add> } <add> return osType <add>} <ide><path>api/client/lib/image_build_test.go <add>package lib <add> <add>import "testing" <add> <add>func TestGetDockerOS(t *testing.T) { <add> cases := map[string]string{ <add> "Docker/v1.22 (linux)": "linux", <add> "Docker/v1.22 (windows)": "windows", <add> "Foo/v1.22 (bar)": "", <add> } <add> for header, os := range cases { <add> g := getDockerOS(header) <add> if g != os { <add> t.Fatalf("Expected %s, got %s", os, g) <add> } <add> } <add>}
2
Javascript
Javascript
add minwithcomments and minlang into release tasks
4352f3561e88f8ba9d60347f5e1b668a9baf8508
<ide><path>Gruntfile.js <ide> module.exports = function (grunt) { <ide> grunt.registerTask('default', ['jshint', 'nodeunit']); <ide> <ide> // Task to be run when releasing a new version <del> grunt.registerTask('release', ['jshint', 'nodeunit', 'concatlang', 'uglify']); <add> grunt.registerTask('release', ['jshint', 'nodeunit', 'minwithcomments', 'concatlang', 'minlang']); <ide> };
1
Ruby
Ruby
move strict cop
ea77fce409879406b9caa6a745f6eef63cc32b3e
<ide><path>Library/Homebrew/rubocops/lines.rb <ide> def autocorrect(node) <ide> end <ide> <ide> class Miscellaneous < FormulaCop <del> MAKE_CHECK_WHITELIST = %w[ <del> beecrypt <del> ccrypt <del> git <del> gmp <del> gnupg <del> [email protected] <del> google-sparsehash <del> jemalloc <del> jpeg-turbo <del> mpfr <del> nettle <del> open-mpi <del> [email protected] <del> pcre <del> protobuf <del> wolfssl <del> xz <del> ].freeze <del> <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> # FileUtils is included in Formula <ide> # encfs modifies a file with this name, so check for some leading characters <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> # Avoid hard-coding compilers <ide> find_every_method_call_by_name(body_node, :system).each do |method| <ide> param = parameters(method).first <del> if match = regex_match_group(param, %r{^(/usr/bin/)?(gcc|llvm-gcc|clang)\s?}) <add> if match = regex_match_group(param, %r{^(/usr/bin/)?(gcc|llvm-gcc|clang)[\s"]?}) <ide> problem "Use \"\#{ENV.cc}\" instead of hard-coding \"#{match[2]}\"" <del> elsif match = regex_match_group(param, %r{^(/usr/bin/)?((g|llvm-g|clang)\+\+)\s?}) <add> elsif match = regex_match_group(param, %r{^(/usr/bin/)?((g|llvm-g|clang)\+\+)[\s"]?}) <ide> problem "Use \"\#{ENV.cxx}\" instead of hard-coding \"#{match[2]}\"" <ide> end <ide> end <ide> <ide> find_instance_method_call(body_node, "ENV", :[]=) do |method| <ide> param = parameters(method)[1] <del> if match = regex_match_group(param, %r{^(/usr/bin/)?(gcc|llvm-gcc|clang)\s?}) <add> if match = regex_match_group(param, %r{^(/usr/bin/)?(gcc|llvm-gcc|clang)[\s"]?}) <ide> problem "Use \"\#{ENV.cc}\" instead of hard-coding \"#{match[2]}\"" <del> elsif match = regex_match_group(param, %r{^(/usr/bin/)?((g|llvm-g|clang)\+\+)\s?}) <add> elsif match = regex_match_group(param, %r{^(/usr/bin/)?((g|llvm-g|clang)\+\+)[\s"]?}) <ide> problem "Use \"\#{ENV.cxx}\" instead of hard-coding \"#{match[2]}\"" <ide> end <ide> end <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> <ide> problem "Use the `#{match}` Ruby method instead of `#{method.source}`" <ide> end <del> <del> return if formula_tap != "homebrew-core" <del> <del> # Avoid build-time checks in homebrew/core <del> find_every_method_call_by_name(body_node, :system).each do |method| <del> next if @formula_name.start_with?("lib") <del> next if MAKE_CHECK_WHITELIST.include?(@formula_name) <del> <del> params = parameters(method) <del> next unless node_equals?(params[0], "make") <del> <del> params[1..].each do |arg| <del> next unless regex_match_group(arg, /^(checks?|tests?)$/) <del> <del> offending_node(method) <del> problem "Formulae in homebrew/core (except e.g. cryptography, libraries) " \ <del> "should not run build-time checks" <del> end <del> end <ide> end <ide> <ide> def modifier?(node) <ide> def modifier?(node) <ide> EOS <ide> end <ide> end <add> <add> module FormulaAuditStrict <add> class MakeCheck < FormulaCop <add> MAKE_CHECK_WHITELIST = %w[ <add> beecrypt <add> ccrypt <add> git <add> gmp <add> gnupg <add> [email protected] <add> google-sparsehash <add> jemalloc <add> jpeg-turbo <add> mpfr <add> nettle <add> open-mpi <add> [email protected] <add> pcre <add> protobuf <add> wolfssl <add> xz <add> ].freeze <add> <add> def audit_formula(_node, _class_node, _parent_class_node, body_node) <add> return if formula_tap != "homebrew-core" <add> <add> # Avoid build-time checks in homebrew/core <add> find_every_method_call_by_name(body_node, :system).each do |method| <add> next if @formula_name.start_with?("lib") <add> next if MAKE_CHECK_WHITELIST.include?(@formula_name) <add> <add> params = parameters(method) <add> next unless node_equals?(params[0], "make") <add> <add> params[1..].each do |arg| <add> next unless regex_match_group(arg, /^(checks?|tests?)$/) <add> <add> offending_node(method) <add> problem "Formulae in homebrew/core (except e.g. cryptography, libraries) " \ <add> "should not run build-time checks" <add> end <add> end <add> end <add> end <add> end <ide> end <ide> end <ide><path>Library/Homebrew/test/rubocops/lines_spec.rb <ide> class Foo < Formula <ide> subject(:cop) { described_class.new } <ide> <ide> context "When auditing formula" do <del> it "build-time checks in homebrew/core" do <del> expect_offense(<<~RUBY, "/homebrew-core/") <del> class Foo < Formula <del> desc "foo" <del> url 'https://brew.sh/foo-1.0.tgz' <del> system "make", "-j1", "test" <del> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Formulae in homebrew/core (except e.g. cryptography, libraries) should not run build-time checks <del> end <del> RUBY <del> end <del> <ide> it "FileUtils usage" do <ide> expect_offense(<<~RUBY) <ide> class Foo < Formula <ide> class Foo < Formula <ide> RUBY <ide> end <ide> end <add>end <add> <add>describe RuboCop::Cop::FormulaAuditStrict::MakeCheck do <add> subject(:cop) { described_class.new } <add> <add> it "build-time checks in homebrew/core" do <add> expect_offense(<<~RUBY, "/homebrew-core/") <add> class Foo < Formula <add> desc "foo" <add> url 'https://brew.sh/foo-1.0.tgz' <add> system "make", "-j1", "test" <add> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Formulae in homebrew/core (except e.g. cryptography, libraries) should not run build-time checks <add> end <add> RUBY <add> end <ide> <ide> include_examples "formulae exist", described_class::MAKE_CHECK_WHITELIST <ide> end
2
Javascript
Javascript
remove calculations inside 'const' declarations
a44f6e6cd9fa60f3b50113615ab1fdcbf2887eb4
<ide><path>examples/js/SkyShader.js <ide> THREE.ShaderLib[ 'sky' ] = { <ide> <ide> // wavelength of used primaries, according to preetham <ide> "const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 );", <del> // this pre-calcuation replaces older TotalRayleigh(vec3 lambda) function <add> // this pre-calcuation replaces older TotalRayleigh(vec3 lambda) function: <add> // (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn)) <ide> "const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 );", <ide> <ide> // mie stuff <ide> // K coefficient for the primaries <ide> "const float v = 4.0;", <del> "const vec3 K = vec3( 0.686, 0.678, 0.666 );", <del> "const vec3 MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K;", <add> "const vec3 K = vec3( 0.686, 0.678, 0.666 );", <add> // MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K <add> "const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 );", <ide> <ide> // earth shadow hack <del> "const float cutoffAngle = pi / 1.95;", <add> // cutoffAngle = pi / 1.95; <add> "const float cutoffAngle = 1.6110731556870734;", <ide> "const float steepness = 1.5;", <ide> "const float EE = 1000.0;", <ide> <ide> THREE.ShaderLib[ 'sky' ] = { <ide> // 66 arc seconds -> degrees, and the cosine of that <ide> "const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324;", <ide> <del> "const float THREE_OVER_SIXTEENPI = 3.0 / ( 16.0 * pi );", <del> "const float ONE_OVER_FOURPI = ( 1.0 / ( 4.0 * pi ) );", <add> // 3.0 / ( 16.0 * pi ) <add> "const float THREE_OVER_SIXTEENPI = 0.05968310365946075;", <add> // 1.0 / ( 4.0 * pi ) <add> "const float ONE_OVER_FOURPI = 0.07957747154594767;", <ide> <ide> "float rayleighPhase( float cosTheta )", <ide> "{",
1
Javascript
Javascript
remove needless assignment of null
1081f0f33df3a6e8825489600967a6f9e469ebb6
<ide><path>lib/fs.js <ide> ReadStream.prototype._read = function(n) { <ide> <ide> if (!pool || pool.length - pool.used < kMinPoolSpace) { <ide> // discard the old pool. <del> pool = null; <ide> allocNewPool(this._readableState.highWaterMark); <ide> } <ide>
1
Ruby
Ruby
verify downloads by default
3cfb028e7f15bc3c51783380d8358b1c7f141ec9
<ide><path>Library/Homebrew/cmd/fetch.rb <ide> def fetch_fetchable(f) <ide> already_fetched = f.cached_download.exist? <ide> <ide> begin <del> download = f.fetch <add> download = f.fetch(verify_download_integrity: false) <ide> rescue DownloadError <ide> retry if retry_fetch? f <ide> raise <ide><path>Library/Homebrew/dev-cmd/mirror.rb <ide> def mirror <ide> downloader = f.downloader <ide> <ide> downloader.fetch <del> f.verify_download_integrity(downloader.cached_location) <ide> <ide> filename = downloader.basename <ide> <ide><path>Library/Homebrew/formula.rb <ide> def to_hash <ide> end <ide> <ide> # @private <del> def fetch <del> active_spec.fetch <add> def fetch(verify_download_integrity: true) <add> active_spec.fetch(verify_download_integrity: verify_download_integrity) <ide> end <ide> <ide> # @private <ide> def prepare_patches <ide> active_spec.add_legacy_patches(patches) if respond_to?(:patches) <ide> <ide> patchlist.grep(DATAPatch) { |p| p.path = path } <del> <del> patchlist.each do |patch| <del> patch.verify_download_integrity(patch.fetch) if patch.external? <del> end <add> patchlist.select(&:external?).each(&:fetch) <ide> end <ide> <ide> # The methods below define the formula DSL. <ide><path>Library/Homebrew/formula_installer.rb <ide> def pour <ide> downloader = LocalBottleDownloadStrategy.new(bottle_path) <ide> else <ide> downloader = formula.bottle <del> downloader.verify_download_integrity(downloader.fetch) <add> downloader.fetch <ide> end <add> <ide> HOMEBREW_CELLAR.cd do <ide> downloader.stage <ide> end <ide><path>Library/Homebrew/resource.rb <ide> def clear_cache <ide> def stage(target = nil, &block) <ide> raise ArgumentError, "target directory or block is required" unless target || block <ide> <del> verify_download_integrity(fetch) <add> fetch <ide> prepare_patches <ide> unpack(target, &block) <ide> end <ide> <ide> def prepare_patches <ide> patches.grep(DATAPatch) { |p| p.path = owner.owner.path } <del> <del> patches.each do |patch| <del> patch.verify_download_integrity(patch.fetch) if patch.external? <del> end <add> patches.select(&:external?).each(&:fetch) <ide> end <ide> <ide> def apply_patches <ide> def files(*files) <ide> Partial.new(self, files) <ide> end <ide> <del> def fetch <add> def fetch(verify_download_integrity: true) <ide> HOMEBREW_CACHE.mkpath <ide> <ide> begin <ide> def fetch <ide> raise DownloadError.new(self, e) <ide> end <ide> <del> cached_download <add> download = cached_download <add> verify_download_integrity(download) if verify_download_integrity <add> download <ide> end <ide> <ide> def verify_download_integrity(fn)
5
Javascript
Javascript
execute jquery#load callback with correct context
5d20a3c3f10bda935c8370392a25e45719afa6b9
<ide><path>src/ajax/load.js <ide> jQuery.fn.load = function( url, params, callback ) { <ide> // If it fails, this function gets "jqXHR", "status", "error" <ide> } ).always( callback && function( jqXHR, status ) { <ide> self.each( function() { <del> callback.apply( self, response || [ jqXHR.responseText, status, jqXHR ] ); <add> callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] ); <ide> } ); <ide> } ); <ide> } <ide><path>test/unit/ajax.js <ide> if ( typeof window.ArrayBuffer === "undefined" || typeof new XMLHttpRequest().re <ide> } <ide> ); <ide> <add> QUnit.test( <add> "jQuery#load() - should resolve with correct context", 2, <add> function( assert ) { <add> var done = assert.async(); <add> var ps = jQuery( "<p></p><p></p>" ); <add> var i = 0; <add> <add> ps.appendTo( "#qunit-fixture" ); <add> <add> ps.load( "data/ajax/method.php", function() { <add> assert.strictEqual( this, ps[ i++ ] ); <add> <add> if ( i === 2 ) { <add> done(); <add> } <add> } ); <add> } <add> ); <add> <ide> QUnit.test( <ide> "#11402 - jQuery.domManip() - script in comments are properly evaluated", 2, <ide> function( assert ) {
2
Python
Python
add support for custom scope name
41aafda97ff4b7bc6125c07bbfe3658707414a81
<ide><path>research/object_detection/utils/ops.py <ide> def map_box_encodings(i): <ide> <ide> <ide> def nearest_neighbor_upsampling(input_tensor, scale=None, height_scale=None, <del> width_scale=None): <add> width_scale=None, <add> name='nearest_neighbor_upsampling'): <ide> """Nearest neighbor upsampling implementation. <ide> <ide> Nearest neighbor upsampling function that maps input tensor with shape <ide> def nearest_neighbor_upsampling(input_tensor, scale=None, height_scale=None, <ide> option when provided overrides `scale` option. <ide> width_scale: An integer multiple to scale the width of input image. This <ide> option when provided overrides `scale` option. <add> name: A name for the operation (optional). <ide> Returns: <ide> data_up: A float32 tensor of size <ide> [batch, height_in*scale, width_in*scale, channels]. <ide> def nearest_neighbor_upsampling(input_tensor, scale=None, height_scale=None, <ide> if not scale and (height_scale is None or width_scale is None): <ide> raise ValueError('Provide either `scale` or `height_scale` and' <ide> ' `width_scale`.') <del> with tf.name_scope('nearest_neighbor_upsampling'): <add> with tf.name_scope(name): <ide> h_scale = scale if height_scale is None else height_scale <ide> w_scale = scale if width_scale is None else width_scale <ide> (batch_size, height, width, <ide> channels) = shape_utils.combined_static_and_dynamic_shape(input_tensor) <del> output_tensor = tf.stack([input_tensor] * w_scale, axis=3) <del> output_tensor = tf.stack([output_tensor] * h_scale, axis=2) <add> output_tensor = tf.stack([input_tensor] * w_scale, axis=3, name='w_stack') <add> output_tensor = tf.stack([output_tensor] * h_scale, axis=2, name='h_stack') <ide> return tf.reshape(output_tensor, <ide> [batch_size, height * h_scale, width * w_scale, channels]) <ide>
1
Text
Text
add changelog for eslint-plugin-react-hooks
4e93b9364c978fd0c1224f8008dd19f88a82a048
<ide><path>packages/eslint-plugin-react-hooks/CHANGELOG.md <add>## 4.0.0 <add> <add>* **New Violations:** Consider `PascalCase.useFoo()` calls as Hooks. ([@cyan33](https://github.com/cyan33) in [#18722](https://github.com/facebook/react/pull/18722)) <add>* **New Violations:** Check callback body when it's not written inline. ([@gaearon](https://github.com/gaearon) in [#18435](https://github.com/facebook/react/pull/18435)) <add>* Add a way to enable the dangerous autofix. ([@gaearon](https://github.com/gaearon) in [#18437](https://github.com/facebook/react/pull/18437)) <add>* Offer a more sensible suggestion when encountering an assignment. ([@Zzzen](https://github.com/Zzzen) in [#16784](https://github.com/facebook/react/pull/16784)) <add>* Consider TypeScript casts of `useRef` as constant. ([@sophiebits](https://github.com/sophiebits) in [#18496](https://github.com/facebook/react/pull/18496)) <add>* Add documentation. ([@ghmcadams](https://github.com/ghmcadams) in [#16607](https://github.com/facebook/react/pull/16607)) <add> <add>## 3.0.0 <add> <add>* **New Violations:** Forbid calling Hooks from classes. ([@ianobermiller](https://github.com/ianobermiller) in [#18341](https://github.com/facebook/react/pull/18341)) <add>* Add a recommended config. ([@SimenB](https://github.com/SimenB) in [#14762](https://github.com/facebook/react/pull/14762)) <add> <add>## 2.5.0 <add> <add>* Fix a misleading error message in loops. ([@M-Izadmehr](https://github.com/M-Izadmehr) in [#16853](https://github.com/facebook/react/pull/16853)) <add> <add>## 2.4.0 <add> <add>* **New Violations:** Run checks for functions passed to `forwardRef`. ([@dprgarner](https://github.com/dprgarner) in [#17255](https://github.com/facebook/react/pull/17255)) <add>* **New Violations:** Check for ref usage in any Hook containing the word `Effect`. ([@gaearon](https://github.com/gaearon) in [#17663](https://github.com/facebook/react/pull/17663)) <add>* Disable dangerous autofix and use ESLint Suggestions API instead. ([@wdoug](https://github.com/wdoug) in [#17385](https://github.com/facebook/react/pull/17385)) <add> <add>## 2.0.0 <add> <add>* **New Violations:** Forbid calling Hooks at the top level. ([@gaearon](https://github.com/gaearon) in [#16455](https://github.com/facebook/react/pull/16455)) <add>* Fix a crash when referencing arguments in arrow functions. ([@hristo-kanchev](https://github.com/hristo-kanchev) in [#16356](https://github.com/facebook/react/pull/16356)) <add> <add> <add>## 1.x <add> <add>The 1.x releases aren’t noted in this changelog, but you can find them in the [commit history](https://github.com/facebook/react/commits/master/packages/eslint-plugin-react-hooks).
1
PHP
PHP
add missing tab
024e5fbaf7a67008eec1bc99eaeefd8755a88cee
<ide><path>src/Illuminate/Queue/IronQueue.php <ide> public function push($job, $data = '', $queue = null) <ide> * @param string $queue <ide> * @return mixed <ide> */ <del>public function later($delay, $job, $data = '', $queue = null) <add> public function later($delay, $job, $data = '', $queue = null) <ide> { <ide> $delay = $this->getSeconds($delay); <ide> <ide> public function getIron() <ide> return $this->iron; <ide> } <ide> <del>} <ide>\ No newline at end of file <add>}
1
Javascript
Javascript
update current challenge for all challenges
f6fa7549065a6ae161dc7c251d44fc21efa12955
<ide><path>client/src/templates/Challenges/backend/Show.js <ide> import { graphql } from 'gatsby'; <ide> <ide> import { <ide> executeChallenge, <add> challengeMounted, <ide> challengeTestsSelector, <ide> consoleOutputSelector, <ide> initTests, <ide> const reduxFormPropTypes = { <ide> }; <ide> <ide> const propTypes = { <add> challengeMounted: PropTypes.func.isRequired, <ide> description: PropTypes.string, <ide> executeChallenge: PropTypes.func.isRequired, <ide> id: PropTypes.string, <add> initTests: PropTypes.func.isRequired, <ide> output: PropTypes.string, <ide> tests: PropTypes.array, <ide> title: PropTypes.string, <add> updateChallengeMeta: PropTypes.func.isRequired, <ide> ...reduxFormPropTypes <ide> }; <ide> <ide> const mapStateToProps = createSelector( <ide> ); <ide> <ide> const mapDispatchToActions = { <add> challengeMounted, <ide> executeChallenge, <ide> initTests, <ide> updateChallengeMeta <ide> export class BackEnd extends Component { <ide> <ide> componentDidMount() { <ide> const { <add> challengeMounted, <ide> initTests, <ide> updateChallengeMeta, <ide> data: { <ide> export class BackEnd extends Component { <ide> } = this.props; <ide> initTests(tests); <ide> updateChallengeMeta({ ...challengeMeta, challengeType }); <add> challengeMounted(challengeMeta.id); <ide> window.addEventListener('resize', this.updateDimensions); <ide> } <ide> <ide> export class BackEnd extends Component { <ide> } <ide> } = prevProps; <ide> const { <add> challengeMounted, <ide> initTests, <ide> updateChallengeMeta, <ide> data: { <ide> export class BackEnd extends Component { <ide> if (prevTitle !== currentTitle) { <ide> initTests(tests); <ide> updateChallengeMeta({ ...challengeMeta, challengeType }); <add> challengeMounted(challengeMeta.id); <ide> } <ide> } <ide> <ide><path>client/src/templates/Challenges/classic/Show.js <ide> class ShowClassic extends Component { <ide> } <ide> } <ide> <add> componentWillUnmount() { <add> const { createFiles } = this.props; <add> createFiles({}); <add> } <add> <ide> getChallenge = () => this.props.data.challengeNode; <ide> <ide> getBlockNameTitle() { <ide><path>client/src/templates/Challenges/project/Show.js <ide> import Helmet from 'react-helmet'; <ide> import { randomCompliment } from '../utils/get-words'; <ide> import { ChallengeNode } from '../../../redux/propTypes'; <ide> import { <add> challengeMounted, <ide> updateChallengeMeta, <del> createFiles, <ide> updateSuccessMessage, <ide> openModal, <ide> updateProjectFormValues <ide> const mapDispatchToProps = dispatch => <ide> bindActionCreators( <ide> { <ide> updateChallengeMeta, <del> createFiles, <add> challengeMounted, <ide> updateProjectFormValues, <ide> updateSuccessMessage, <ide> openCompletionModal: () => openModal('completion') <ide> const mapDispatchToProps = dispatch => <ide> ); <ide> <ide> const propTypes = { <del> createFiles: PropTypes.func.isRequired, <add> challengeMounted: PropTypes.func.isRequired, <ide> data: PropTypes.shape({ <ide> challengeNode: ChallengeNode <ide> }), <ide> const propTypes = { <ide> export class Project extends Component { <ide> componentDidMount() { <ide> const { <del> createFiles, <del> data: { challengeNode: { title, challengeType } }, <add> challengeMounted, <add> data: { <add> challengeNode: { title, challengeType } <add> }, <ide> pageContext: { challengeMeta }, <ide> updateChallengeMeta, <ide> updateSuccessMessage <ide> } = this.props; <del> createFiles({}); <ide> updateSuccessMessage(randomCompliment()); <del> return updateChallengeMeta({ ...challengeMeta, title, challengeType }); <add> updateChallengeMeta({ ...challengeMeta, title, challengeType }); <add> challengeMounted(challengeMeta.id); <ide> } <ide> <ide> componentDidUpdate(prevProps) { <del> const { data: { challengeNode: { title: prevTitle } } } = prevProps; <ide> const { <del> createFiles, <del> data: { challengeNode: { title: currentTitle, challengeType } }, <add> data: { <add> challengeNode: { title: prevTitle } <add> } <add> } = prevProps; <add> const { <add> challengeMounted, <add> data: { <add> challengeNode: { title: currentTitle, challengeType } <add> }, <ide> pageContext: { challengeMeta }, <ide> updateChallengeMeta, <ide> updateSuccessMessage <ide> } = this.props; <ide> updateSuccessMessage(randomCompliment()); <ide> if (prevTitle !== currentTitle) { <del> createFiles({}); <ide> updateChallengeMeta({ <ide> ...challengeMeta, <ide> title: currentTitle, <ide> challengeType <ide> }); <add> challengeMounted(challengeMeta.id); <ide> } <ide> } <ide> <ide> export class Project extends Component { <ide> Project.displayName = 'Project'; <ide> Project.propTypes = propTypes; <ide> <del>export default connect(mapStateToProps, mapDispatchToProps)(Project); <add>export default connect( <add> mapStateToProps, <add> mapDispatchToProps <add>)(Project); <ide> <ide> export const query = graphql` <ide> query ProjectChallenge($slug: String!) { <ide><path>client/src/templates/Challenges/redux/code-storage-epic.js <ide> function saveCodeEpic(action$, state$) { <ide> function loadCodeEpic(action$, state$) { <ide> return action$.pipe( <ide> ofType(types.challengeMounted), <add> filter(() => { <add> const files = challengeFilesSelector(state$.value); <add> return Object.keys(files).length > 0; <add> }), <ide> switchMap(({ payload: id }) => { <ide> let finalFiles; <ide> const state = state$.value; <ide><path>client/src/templates/Challenges/redux/current-challenge-epic.js <del>import { of } from 'rxjs'; <del>import { ofType } from 'redux-observable'; <del> <del>import { types } from './'; <del>import { filter, switchMap, catchError, mapTo } from 'rxjs/operators'; <del>import { <del> isSignedInSelector, <del> currentChallengeIdSelector, <del> updateComplete, <del> updateFailed <del>} from '../../../redux'; <del>import postUpdate$ from '../utils/postUpdate$'; <del> <del>function currentChallengeEpic(action$, state$) { <del> return action$.pipe( <del> ofType(types.challengeMounted), <del> filter(() => isSignedInSelector(state$.value)), <del> filter( <del> ({ payload }) => payload !== currentChallengeIdSelector(state$.value) <del> ), <del> switchMap(({ payload }) => { <del> const update = { <del> endpoint: '/update-my-current-challenge', <del> payload: { <del> currentChallengeId: payload <del> } <del> }; <del> return postUpdate$(update).pipe( <del> mapTo(updateComplete()), <del> catchError(() => of(updateFailed(update))) <del> ); <del> }) <del> ); <del>} <del> <del>export default currentChallengeEpic; <ide><path>client/src/templates/Challenges/redux/current-challenge-saga.js <add>import { put, select, call, takeEvery } from 'redux-saga/effects'; <add> <add>import { <add> isSignedInSelector, <add> currentChallengeIdSelector, <add> updateComplete, <add> updateFailed <add>} from '../../../redux'; <add> <add>import { post } from '../../../utils/ajax'; <add> <add>function* currentChallengeSaga({ payload }) { <add> const isSignedIn = yield select(isSignedInSelector); <add> const currentChallengeId = yield select(currentChallengeIdSelector); <add> if (isSignedIn && payload !== currentChallengeId) { <add> const update = { <add> endpoint: '/update-my-current-challenge', <add> payload: { <add> currentChallengeId: payload <add> } <add> }; <add> try { <add> yield call(post, update.endpoint, update.payload); <add> yield put(updateComplete()); <add> } catch { <add> yield put(updateFailed(update)); <add> } <add> } <add>} <add> <add>export function createCurrentChallengeSaga(types) { <add> return [ <add> takeEvery(types.challengeMounted, currentChallengeSaga) <add> ]; <add>} <ide><path>client/src/templates/Challenges/redux/index.js <ide> import completionEpic from './completion-epic'; <ide> import codeLockEpic from './code-lock-epic'; <ide> import createQuestionEpic from './create-question-epic'; <ide> import codeStorageEpic from './code-storage-epic'; <del>import currentChallengeEpic from './current-challenge-epic'; <ide> <ide> import { createIdToNameMapSaga } from './id-to-name-map-saga'; <ide> import { createExecuteChallengeSaga } from './execute-challenge-saga'; <add>import { createCurrentChallengeSaga } from './current-challenge-saga'; <ide> <ide> export const ns = 'challenge'; <ide> export const backendNS = 'backendChallenge'; <ide> export const epics = [ <ide> codeLockEpic, <ide> completionEpic, <ide> createQuestionEpic, <del> codeStorageEpic, <del> currentChallengeEpic <add> codeStorageEpic <ide> ]; <ide> <ide> export const sagas = [ <ide> ...createIdToNameMapSaga(types), <del> ...createExecuteChallengeSaga(types) <add> ...createExecuteChallengeSaga(types), <add> ...createCurrentChallengeSaga(types) <ide> ]; <ide> <ide> export const createFiles = createAction(types.createFiles, challengeFiles => <ide> export const reducer = handleActions( <ide> ...state, <ide> currentTab: payload <ide> }), <del> [types.executeChallenge]: (state, { payload }) => ({ <add> [types.executeChallenge]: state => ({ <ide> ...state, <ide> currentTab: 3 <ide> })
7
Mixed
Text
kill react.initializetouchevents for good
9c4c2f58ea103f84c055d2241c0f178c79d90fd9
<ide><path>docs/docs/03-interactivity-and-dynamic-uis.md <ide> React.render( <ide> <ide> With React you simply pass your event handler as a camelCased prop similar to how you'd do it in normal HTML. React ensures that all events behave identically in IE8 and above by implementing a synthetic event system. That is, React knows how to bubble and capture events according to the spec, and the events passed to your event handler are guaranteed to be consistent with [the W3C spec](http://www.w3.org/TR/DOM-Level-3-Events/), regardless of which browser you're using. <ide> <del>If you'd like to use React on a touch device such as a phone or tablet, simply call `React.initializeTouchEvents(true);` to enable touch event handling. <del> <ide> <ide> ## Under the Hood: Autobinding and Event Delegation <ide> <ide><path>docs/docs/03-interactivity-and-dynamic-uis.zh-CN.md <ide> React.render( <ide> <ide> React 里只需把事件处理器(event handler)以骆峰命名(camelCased)形式当作组件的 props 传入即可,就像使用普通 HTML 那样。React 内部创建一套合成事件系统来使所有事件在 IE8 和以上浏览器表现一致。也就是说,React 知道如何冒泡和捕获事件,而且你的事件处理器接收到的 events 参数与 [W3C 规范](http://www.w3.org/TR/DOM-Level-3-Events/) 一致,无论你使用哪种浏览器。 <ide> <del>如果需要在手机或平板等触摸设备上使用 React,需要调用 `React.initializeTouchEvents(true);` 启用触摸事件处理。 <del> <ide> ## 幕后原理:自动绑定(Autobinding)和事件代理(Event Delegation) <ide> <ide> 在幕后,React 做了一些操作来让代码高效运行且易于理解。 <ide><path>docs/docs/ref-01-top-level-api.md <ide> If this component has been mounted into the DOM, this returns the corresponding <ide> `React.PropTypes` includes types that can be used with a component's `propTypes` object to validate props being passed to your components. For more information about `propTypes`, see [Reusable Components](/react/docs/reusable-components.html). <ide> <ide> <del>### React.initializeTouchEvents <del> <del>```javascript <del>initializeTouchEvents(boolean shouldUseTouch) <del>``` <del> <del>Configure React's event system to handle touch events on mobile devices. <del> <del> <ide> ### React.Children <ide> <ide> `React.Children` provides utilities for dealing with the `this.props.children` opaque data structure. <ide><path>docs/docs/ref-05-events.md <ide> boolean shiftKey <ide> <ide> ### Touch events <ide> <del>To enable touch events, call `React.initializeTouchEvents(true)` before <del>rendering any component. <del> <ide> Event names: <ide> <ide> ``` <ide><path>docs/docs/ref-05-events.zh-CN.md <ide> boolean shiftKey <ide> <ide> ### 触控事件 <ide> <del>在渲染任意组件之前调用 `React.initializeTouchEvents(true)`,以启用触控事件。 <del> <ide> 事件名称: <ide> <ide> ``` <ide><path>src/browser/eventPlugins/TapEventPlugin.js <ide> function getDistance(coords, nativeEvent) { <ide> ); <ide> } <ide> <del>var dependencies = [ <del> topLevelTypes.topMouseDown, <del> topLevelTypes.topMouseMove, <del> topLevelTypes.topMouseUp <del>]; <del> <del>var touchDependencies = [ <add>var touchEvents = [ <ide> topLevelTypes.topTouchStart, <ide> topLevelTypes.topTouchCancel, <ide> topLevelTypes.topTouchEnd, <ide> topLevelTypes.topTouchMove <ide> ]; <ide> <del>if (EventPluginUtils.useTouchEvents) { <del> dependencies = dependencies.concat(touchDependencies); <del>} <add>var dependencies = [ <add> topLevelTypes.topMouseDown, <add> topLevelTypes.topMouseMove, <add> topLevelTypes.topMouseUp <add>].concat(touchEvents); <ide> <ide> var eventTypes = { <ide> touchTap: { <ide> var TapEventPlugin = { <ide> // on ios, there is a delay after touch event and synthetic <ide> // mouse events, so that user can perform double tap <ide> // solution: ignore mouse events following touchevent within small timeframe <del> if (touchDependencies.indexOf(topLevelType) !== -1) { <add> if (touchEvents.indexOf(topLevelType) !== -1) { <ide> usedTouch = true; <ide> usedTouchTime = Date.now(); <ide> } else { <ide><path>src/browser/ui/React.js <ide> <ide> 'use strict'; <ide> <del>var EventPluginUtils = require('EventPluginUtils'); <ide> var ReactChildren = require('ReactChildren'); <ide> var ReactComponent = require('ReactComponent'); <ide> var ReactClass = require('ReactClass'); <ide> var React = { <ide> Component: ReactComponent, <ide> DOM: ReactDOM, <ide> PropTypes: ReactPropTypes, <del> initializeTouchEvents: function(shouldUseTouch) { <del> EventPluginUtils.useTouchEvents = shouldUseTouch; <del> }, <ide> createClass: ReactClass.createClass, <ide> createElement: createElement, <ide> cloneElement: cloneElement, <ide><path>src/event/EventPluginUtils.js <ide> var EventPluginUtils = { <ide> executeDispatchesInOrder: executeDispatchesInOrder, <ide> executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, <ide> hasDispatches: hasDispatches, <del> injection: injection, <del> useTouchEvents: false <add> injection: injection <ide> }; <ide> <ide> module.exports = EventPluginUtils;
8
Javascript
Javascript
reduce code logic. defer promises
b6f621fee381f4f71f86e5ba095034c69dd0bffe
<ide><path>common/models/user.js <ide> import { <ide> const debug = debugFactory('fcc:user:remote'); <ide> const BROWNIEPOINTS_TIMEOUT = [1, 'hour']; <ide> <del>const createEmailError = () => new Error( <del> 'Please check to make sure the email is a valid email address.' <add>const createEmailError = redirectTo => wrapHandledError( <add> new Error('email format is invalid'), <add> { <add> type: 'info', <add> message: 'Please check to make sure the email is a valid email address.', <add> redirectTo <add> } <ide> ); <ide> <ide> function destroyAll(id, Model) { <ide> module.exports = function(User) { <ide> `); <ide> }; <ide> <del> User.prototype.requestUpdateEmail = function requestUpdateEmail( <del> newEmail <del> ) { <del> const ownEmail = newEmail === this.email; <del> if (!isEmail('' + newEmail)) { <del> debug('invalid email:', newEmail ); <del> return Observable.throw(createEmailError()); <del> } <del> // email is already associated and verified with this account <del> if (ownEmail && this.emailVerified) { <del> return Observable.throw(new Error( <del> `${newEmail} is already associated with this account.` <del> )); <del> } <add> User.prototype.requestUpdateEmail = function requestUpdateEmail(newEmail) { <add> return Observable.defer(() => { <add> const ownEmail = newEmail === this.email; <add> if (!isEmail('' + newEmail)) { <add> debug('invalid email:', newEmail ); <add> throw createEmailError(); <add> } <add> // email is already associated and verified with this account <add> if (ownEmail && this.emailVerified) { <add> throw wrapHandledError( <add> new Error('email is already associated with account'), <add> { <add> type: 'info', <add> message: `${newEmail} is already associated with this account.` <add> } <add> ); <add> } <ide> <del> const minutesLeft = getWaitPeriod(this.emailVerifyTTL); <del> if (ownEmail && minutesLeft > 0) { <del> const timeToWait = minutesLeft ? <del> `${minutesLeft} minute${minutesLeft > 1 ? 's' : ''}` : <del> 'a few seconds'; <del> debug('request before wait time : ' + timeToWait); <del> return Observable.of(dedent` <del> Please wait ${timeToWait} to resend an authentication link. <del> `); <del> } <add> const minutesLeft = getWaitPeriod(this.emailVerifyTTL); <add> if (ownEmail && minutesLeft > 0) { <add> const timeToWait = minutesLeft ? <add> `${minutesLeft} minute${minutesLeft > 1 ? 's' : ''}` : <add> 'a few seconds'; <add> <add> debug('request before wait time : ' + timeToWait); <ide> <del> return Observable.fromPromise(User.doesExist(null, newEmail)) <add> return Observable.of(dedent` <add> Please wait ${timeToWait} to resend an authentication link. <add> `); <add> } <add> // defer prevents the promise from firing prematurely <add> return Observable.defer(() => User.doesExist(null, newEmail)); <add> }) <ide> .flatMap(exists => { <ide> // not associated with this account, but is associated with another <del> if (!ownEmail && exists) { <del> return Promise.reject( <del> new Error( <del> `${newEmail} is already associated with another account.` <del> ) <add> if (!exists) { <add> throw wrapHandledError( <add> new Error('email already in use'), <add> { <add> type: 'info', <add> message: `${newEmail} is already associated with another account.` <add> } <ide> ); <ide> } <ide> <ide> const emailVerified = false; <del> return this.update$({ <add> const data = { <ide> newEmail, <ide> emailVerified, <ide> emailVerifyTTL: new Date() <del> }) <del> .do(() => { <del> this.newEmail = newEmail; <del> this.emailVerified = emailVerified; <del> this.emailVerifyTTL = new Date(); <del> }); <add> }; <add> return this.update$(data).do(() => Object.assign(this, data)); <ide> }) <ide> .flatMap(() => { <ide> const mailOptions = {
1
PHP
PHP
correct doc blocks as per cs
759c24e6608960d799141311905d3adeafa0f703
<ide><path>lib/Cake/Console/ConsoleErrorHandler.php <ide> public function handleError($code, $description, $file = null, $line = null, $co <ide> /** <ide> * Wrapper for exit(), used for testing. <ide> * <del> * @param int $code The exit code. <add> * @param integer $code The exit code. <ide> * @return void <ide> */ <ide> protected function _stop($code = 0) { <ide><path>lib/Cake/Error/exceptions.php <ide> class CakeBaseException extends RuntimeException { <ide> * @param string|array $header. An array of header strings or a single header string <ide> * - an associative array of "header name" => "header value" <ide> * - an array of string headers is also accepted <del> * @param string $value. The header value. <add> * @param string $value The header value. <ide> * @return array <ide> * @see CakeResponse::header() <ide> */ <ide> class BadRequestException extends HttpException { <ide> * Constructor <ide> * <ide> * @param string $message If no message is given 'Bad Request' will be the message <del> * @param int $code Status code, defaults to 400 <add> * @param integer $code Status code, defaults to 400 <ide> */ <ide> public function __construct($message = null, $code = 400) { <ide> if (empty($message)) { <ide> class UnauthorizedException extends HttpException { <ide> * Constructor <ide> * <ide> * @param string $message If no message is given 'Unauthorized' will be the message <del> * @param int $code Status code, defaults to 401 <add> * @param integer $code Status code, defaults to 401 <ide> */ <ide> public function __construct($message = null, $code = 401) { <ide> if (empty($message)) { <ide> class ForbiddenException extends HttpException { <ide> * Constructor <ide> * <ide> * @param string $message If no message is given 'Forbidden' will be the message <del> * @param int $code Status code, defaults to 403 <add> * @param integer $code Status code, defaults to 403 <ide> */ <ide> public function __construct($message = null, $code = 403) { <ide> if (empty($message)) { <ide> class NotFoundException extends HttpException { <ide> * Constructor <ide> * <ide> * @param string $message If no message is given 'Not Found' will be the message <del> * @param int $code Status code, defaults to 404 <add> * @param integer $code Status code, defaults to 404 <ide> */ <ide> public function __construct($message = null, $code = 404) { <ide> if (empty($message)) { <ide> class MethodNotAllowedException extends HttpException { <ide> * Constructor <ide> * <ide> * @param string $message If no message is given 'Method Not Allowed' will be the message <del> * @param int $code Status code, defaults to 405 <add> * @param integer $code Status code, defaults to 405 <ide> */ <ide> public function __construct($message = null, $code = 405) { <ide> if (empty($message)) { <ide> class InternalErrorException extends HttpException { <ide> * Constructor <ide> * <ide> * @param string $message If no message is given 'Internal Server Error' will be the message <del> * @param int $code Status code, defaults to 500 <add> * @param integer $code Status code, defaults to 500 <ide> */ <ide> public function __construct($message = null, $code = 500) { <ide> if (empty($message)) { <ide> class CakeException extends CakeBaseException { <ide> * <ide> * @param string|array $message Either the string of the error message, or an array of attributes <ide> * that are made available in the view, and sprintf()'d into CakeException::$_messageTemplate <del> * @param int $code The code of the error, is also the HTTP status code for the error. <add> * @param integer $code The code of the error, is also the HTTP status code for the error. <ide> */ <ide> public function __construct($message, $code = 500) { <ide> if (is_array($message)) { <ide><path>lib/Cake/Log/Engine/SyslogLog.php <ide> public function write($type, $message) { <ide> * will initialize the connection to the system logger <ide> * <ide> * @param string $ident the prefix to add to all messages logged <del> * @param int $options the options flags to be used for logged messages <del> * @param int $facility the stream or facility to log to <add> * @param integer $options the options flags to be used for logged messages <add> * @param integer $facility the stream or facility to log to <ide> * @return void <ide> */ <ide> protected function _open($ident, $options, $facility) { <ide> protected function _open($ident, $options, $facility) { <ide> * Extracts the call to syslog() in order to run unit tests on it. This function <ide> * will perform the actual write in the system logger <ide> * <del> * @param int $priority <add> * @param integer $priority <ide> * @param string $message <ide> * @return bool <ide> */ <ide><path>lib/Cake/Network/CakeSocket.php <ide> public function connect() { <ide> * <ide> * Instead we need to handle those errors manually. <ide> * <del> * @param int $code <add> * @param integer $code <ide> * @param string $message <ide> * @return void <ide> */
4
Mixed
Javascript
add offsetgridlines option to line charts
2677360f4bcda5109664c6f2fc93378f46f82760
<ide><path>docs/01-Line-Chart.md <ide> These are the customisation options specific to Line charts. These options are m <ide> //String - A legend template <ide> legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>" <ide> {% endraw %} <add> <add> //Boolean - Whether to horizontally center the label and point dot inside the grid <add> offsetGridLines : false <ide> }; <ide> ``` <ide> <ide><path>src/Chart.Line.js <ide> datasetFill : true, <ide> <ide> //String - A legend template <del> legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>" <add> legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>", <add> <add> //Boolean - Whether to horizontally center the label and point dot inside the grid <add> offsetGridLines : false <ide> <ide> }; <ide> <ide> initialize: function(data){ <ide> //Declare the extension of the default point, to cater for the options passed in to the constructor <ide> this.PointClass = Chart.Point.extend({ <add> offsetGridLines : this.options.offsetGridLines, <ide> strokeWidth : this.options.pointDotStrokeWidth, <ide> radius : this.options.pointDotRadius, <ide> display: this.options.pointDot, <ide> width : this.chart.width, <ide> ctx : this.chart.ctx, <ide> textColor : this.options.scaleFontColor, <add> offsetGridLines : this.options.offsetGridLines, <ide> fontSize : this.options.scaleFontSize, <ide> fontStyle : this.options.scaleFontStyle, <ide> fontFamily : this.options.scaleFontFamily,
2
Ruby
Ruby
use the build accessor rather than metaprogramming
92eb96aca08a22d69d0c7a4455444e9af95acf63
<ide><path>Library/Homebrew/formula.rb <ide> def verify_download_integrity fn <ide> end <ide> <ide> def test <del> tab = Tab.for_formula(self) <del> extend Module.new { define_method(:build) { tab } } <add> self.build = Tab.for_formula(self) <ide> ret = nil <ide> mktemp do <ide> @testpath = Pathname.pwd
1
Ruby
Ruby
allow env overriding
5d8a6e368f2c8fd5d2075cfb9dd8bb3928c2ac42
<ide><path>Library/Homebrew/test/test_integration_cmds.rb <ide> <ide> class IntegrationCommandTests < Homebrew::TestCase <ide> def cmd_output(*args) <add> # 1.8-compatible way of writing def cmd_output(*args, **env) <add> env = args.last.is_a?(Hash) ? args.pop : {} <ide> cmd_args = %W[ <ide> -W0 <ide> -I#{HOMEBREW_LIBRARY_PATH}/test/lib <ide> def cmd_output(*args) <ide> ENV["HOMEBREW_BREW_FILE"] = HOMEBREW_PREFIX/"bin/brew" <ide> ENV["HOMEBREW_INTEGRATION_TEST"] = args.join " " <ide> ENV["HOMEBREW_TEST_TMPDIR"] = TEST_TMPDIR <add> env.each_pair { |k,v| ENV[k] = v } <add> <ide> read, write = IO.pipe <ide> begin <ide> pid = fork do
1
Javascript
Javascript
use sortableset in modules
4e5ef0d72d4a473074462a17114e327f59890925
<ide><path>lib/Module.js <ide> "use strict"; <ide> <ide> const util = require("util"); <add> <ide> const DependenciesBlock = require("./DependenciesBlock"); <ide> const ModuleReason = require("./ModuleReason"); <add>const SortableSet = require("./util/SortableSet"); <ide> const Template = require("./Template"); <ide> <del>function byId(a, b) { <del> return a.id - b.id; <del>} <del> <del>function byDebugId(a, b) { <del> return a.debugId - b.debugId; <del>} <del> <ide> let debugId = 1000; <ide> <ide> class Module extends DependenciesBlock { <add> <add> static sortById(a, b) { <add> return a.id - b.id; <add> } <add> <add> static sortByDebugId(a, b) { <add> return a.debugId - b.debugId; <add> } <add> <ide> constructor() { <ide> super(); <ide> this.context = null; <ide> class Module extends DependenciesBlock { <ide> this.used = null; <ide> this.usedExports = null; <ide> this.providedExports = null; <del> this._chunks = new Set(); <del> this._chunksIsSorted = true; <del> this._chunksIsSortedByDebugId = true; <add> this._chunks = new SortableSet(undefined, Module.sortById); <ide> this._chunksDebugIdent = undefined; <ide> this.warnings = []; <ide> this.dependenciesWarnings = []; <ide> class Module extends DependenciesBlock { <ide> this.providedExports = null; <ide> this._chunks.clear(); <ide> this._chunksDebugIdent = undefined; <del> this._chunksIsSorted = this._chunksIsSortedByDebugId = false; <ide> super.disconnect(); <ide> } <ide> <ide> class Module extends DependenciesBlock { <ide> this.depth = null; <ide> this._chunks.clear(); <ide> this._chunksDebugIdent = undefined; <del> this._chunksIsSorted = this._chunksIsSortedByDebugId = false; <ide> super.unseal(); <ide> } <ide> <ide> addChunk(chunk) { <ide> this._chunks.add(chunk); <ide> this._chunksDebugIdent = undefined; <del> this._chunksIsSorted = this._chunksIsSortedByDebugId = false; <ide> } <ide> <ide> removeChunk(chunk) { <ide> class Module extends DependenciesBlock { <ide> <ide> getChunkIdsIdent() { <ide> if(this._chunksDebugIdent !== undefined) return this._chunksDebugIdent; <del> this._ensureChunksSortedByDebugId(); <add> this._chunks.sortWith(Module.sortByDebugId); <ide> const chunks = this._chunks; <ide> const list = []; <ide> for(const chunk of chunks) { <ide> class Module extends DependenciesBlock { <ide> <ide> hasEqualsChunks(otherModule) { <ide> if(this._chunks.size !== otherModule._chunks.size) return false; <del> this._ensureChunksSortedByDebugId(); <del> otherModule._ensureChunksSortedByDebugId(); <add> this._chunks.sortWith(Module.sortByDebugId); <add> otherModule._chunks.sortWith(Module.sortByDebugId); <ide> const a = this._chunks[Symbol.iterator](); <ide> const b = otherModule._chunks[Symbol.iterator](); <ide> while(true) { // eslint-disable-line <ide> class Module extends DependenciesBlock { <ide> } <ide> } <ide> <del> _ensureChunksSorted() { <del> if(this._chunksIsSorted) return; <del> this._chunks = new Set(Array.from(this._chunks).sort(byId)); <del> this._chunksIsSortedByDebugId = false; <del> this._chunksIsSorted = true; <del> } <del> <del> _ensureChunksSortedByDebugId() { <del> if(this._chunksIsSortedByDebugId) return; <del> this._chunks = new Set(Array.from(this._chunks).sort(byDebugId)); <del> this._chunksIsSorted = false; <del> this._chunksIsSortedByDebugId = true; <del> } <del> <ide> addReason(module, dependency) { <ide> this.reasons.push(new ModuleReason(module, dependency)); <ide> } <ide> class Module extends DependenciesBlock { <ide> sortItems(sortChunks) { <ide> super.sortItems(); <ide> if(sortChunks) <del> this._ensureChunksSorted(); <del> this.reasons.sort((a, b) => byId(a.module, b.module)); <add> this._chunks.sort(); <add> this.reasons.sort((a, b) => Module.sortById(a.module, b.module)); <ide> if(Array.isArray(this.usedExports)) { <ide> this.usedExports.sort(); <ide> }
1