content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Python | Python | fix gfile reading | 8b18491b26e4b8271db757a3245008882ea112b3 | <ide><path>official/transformer/compute_bleu.py
<ide> def bleu_tokenize(string):
<ide> def bleu_wrapper(ref_filename, hyp_filename, case_sensitive=False):
<ide> """Compute BLEU for two files (reference and hypothesis translation)."""
<ide> ref_lines = tokenizer.native_to_unicode(
<del> tf.gfile.Open(ref_filename, "r").read()).split("\n")
<add> tf.io.gfile.GFile(ref_filename).read()).strip().splitlines()
<ide> hyp_lines = tokenizer.native_to_unicode(
<del> tf.gfile.Open(hyp_filename, "r").read()).split("\n")
<add> tf.io.gfile.GFile(hyp_filename).read()).strip().splitlines()
<ide>
<ide> if len(ref_lines) != len(hyp_lines):
<ide> raise ValueError("Reference and translation files have different number of " | 1 |
PHP | PHP | avoid side effects in router.php | d5e758433909b954fc011ec4ca521025f79f32b6 | <ide><path>src/Routing/Router.php
<ide> protected static function _loadRoutes()
<ide> include CONFIG . 'routes.php';
<ide> }
<ide> }
<del>
<del>//Save the initial state
<del>Router::reload();
<ide><path>tests/bootstrap.php
<ide> use Cake\Datasource\ConnectionManager;
<ide> use Cake\I18n\I18n;
<ide> use Cake\Log\Log;
<add>use Cake\Routing\Router;
<ide>
<ide> require_once 'vendor/autoload.php';
<ide>
<ide> Carbon\Carbon::setTestNow(Carbon\Carbon::now());
<ide>
<ide> ini_set('intl.default_locale', 'en_US');
<add>
<add>Router::reload(); | 2 |
PHP | PHP | reduce scope of changes in previous commit | 7e0cfa9c4611bd6f25697d2c327bb2ac1c01198a | <ide><path>src/ORM/ResultSet.php
<ide> public function valid()
<ide> $this->_current = $this->_results[$this->_index];
<ide> return true;
<ide> }
<add> if (!$valid) {
<add> return $valid;
<add> }
<ide> }
<ide>
<ide> $this->_current = $this->_fetchResult();
<ide> public function valid()
<ide> public function first()
<ide> {
<ide> foreach ($this as $result) {
<del> if ($this->_statement) {
<add> if ($this->_statement && !$this->_useBuffering) {
<ide> $this->_statement->closeCursor();
<ide> }
<ide> return $result;
<ide><path>tests/TestCase/ORM/QueryRegressionTest.php
<ide> public function testFirstOnResultSet()
<ide> $results = TableRegistry::get('Articles')->find()->all();
<ide> $this->assertEquals(3, $results->count());
<ide> $this->assertNotNull($results->first());
<del> $this->assertCount(1, $results->toArray());
<add> $this->assertCount(3, $results->toArray());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/ORM/QueryTest.php
<ide> public function testResultsAreWrappedInMapReduce()
<ide> '\Database\StatementInterface',
<ide> ['fetch', 'closeCursor', 'rowCount']
<ide> );
<del> $statement->expects($this->exactly(3))
<add> $statement->expects($this->exactly(2))
<ide> ->method('fetch')
<del> ->will($this->onConsecutiveCalls(['a' => 1], ['a' => 2], false));
<add> ->will($this->onConsecutiveCalls(['a' => 1], ['a' => 2]));
<ide>
<ide> $statement->expects($this->once())
<ide> ->method('rowCount') | 3 |
Javascript | Javascript | remove babel include from react-loader | 6de9ff2debfd17de5e897cc252165085ea7646f8 | <ide><path>fixtures/public/react-loader.js
<ide>
<ide> var REACT_PATH = 'react.js';
<ide> var DOM_PATH = 'react-dom.js';
<del>var BABEL_PATH = 'https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.19.0/babel.js';
<ide>
<ide> function parseQuery(qstr) {
<ide> var query = {};
<ide> function parseQuery(qstr) {
<ide> var query = parseQuery(window.location.search);
<ide> var version = query.version || 'local';
<ide>
<del>console.log(query)
<del>
<ide> if (version !== 'local') {
<ide> REACT_PATH = 'https://unpkg.com/react@' + version + '/dist/react.min.js';
<ide> DOM_PATH = 'https://unpkg.com/react-dom@' + version + '/dist/react-dom.min.js';
<ide> }
<ide>
<ide> console.log('Loading ' + version);
<ide>
<del>document.write('<script src="' + BABEL_PATH + '"></script>');
<ide> document.write('<script src="' + REACT_PATH + '"></script>');
<ide>
<ide> // Versions earlier than 14 do not use ReactDOM | 1 |
Go | Go | remove dead code after decoupling from jsonlog | d3b3ebc3a4e185da08ec049bbeba46e942f30c80 | <ide><path>daemon/container.go
<ide> func (streamConfig *StreamConfig) StdinPipe() io.WriteCloser {
<ide>
<ide> func (streamConfig *StreamConfig) StdoutPipe() io.ReadCloser {
<ide> reader, writer := io.Pipe()
<del> streamConfig.stdout.AddWriter(writer, "")
<add> streamConfig.stdout.AddWriter(writer)
<ide> return ioutils.NewBufReader(reader)
<ide> }
<ide>
<ide> func (streamConfig *StreamConfig) StderrPipe() io.ReadCloser {
<ide> reader, writer := io.Pipe()
<del> streamConfig.stderr.AddWriter(writer, "")
<del> return ioutils.NewBufReader(reader)
<del>}
<del>
<del>func (streamConfig *StreamConfig) StdoutLogPipe() io.ReadCloser {
<del> reader, writer := io.Pipe()
<del> streamConfig.stdout.AddWriter(writer, "stdout")
<del> return ioutils.NewBufReader(reader)
<del>}
<del>
<del>func (streamConfig *StreamConfig) StderrLogPipe() io.ReadCloser {
<del> reader, writer := io.Pipe()
<del> streamConfig.stderr.AddWriter(writer, "stderr")
<add> streamConfig.stderr.AddWriter(writer)
<ide> return ioutils.NewBufReader(reader)
<ide> }
<ide>
<ide><path>pkg/broadcastwriter/broadcastwriter.go
<ide> package broadcastwriter
<ide>
<ide> import (
<del> "bytes"
<ide> "io"
<ide> "sync"
<del> "time"
<del>
<del> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/pkg/jsonlog"
<del> "github.com/docker/docker/pkg/timeutils"
<ide> )
<ide>
<ide> // BroadcastWriter accumulate multiple io.WriteCloser by stream.
<ide> type BroadcastWriter struct {
<ide> sync.Mutex
<del> buf *bytes.Buffer
<del> jsLogBuf *bytes.Buffer
<del> streams map[string](map[io.WriteCloser]struct{})
<add> writers map[io.WriteCloser]struct{}
<ide> }
<ide>
<del>// AddWriter adds new io.WriteCloser for stream.
<del>// If stream is "", then all writes proceed as is. Otherwise every line from
<del>// input will be packed to serialized jsonlog.JSONLog.
<del>func (w *BroadcastWriter) AddWriter(writer io.WriteCloser, stream string) {
<add>// AddWriter adds new io.WriteCloser.
<add>func (w *BroadcastWriter) AddWriter(writer io.WriteCloser) {
<ide> w.Lock()
<del> if _, ok := w.streams[stream]; !ok {
<del> w.streams[stream] = make(map[io.WriteCloser]struct{})
<del> }
<del> w.streams[stream][writer] = struct{}{}
<add> w.writers[writer] = struct{}{}
<ide> w.Unlock()
<ide> }
<ide>
<ide> // Write writes bytes to all writers. Failed writers will be evicted during
<ide> // this call.
<ide> func (w *BroadcastWriter) Write(p []byte) (n int, err error) {
<ide> w.Lock()
<del> if writers, ok := w.streams[""]; ok {
<del> for sw := range writers {
<del> if n, err := sw.Write(p); err != nil || n != len(p) {
<del> // On error, evict the writer
<del> delete(writers, sw)
<del> }
<del> }
<del> if len(w.streams) == 1 {
<del> if w.buf.Len() >= 4096 {
<del> w.buf.Reset()
<del> } else {
<del> w.buf.Write(p)
<del> }
<del> w.Unlock()
<del> return len(p), nil
<add> for sw := range w.writers {
<add> if n, err := sw.Write(p); err != nil || n != len(p) {
<add> // On error, evict the writer
<add> delete(w.writers, sw)
<ide> }
<ide> }
<del> if w.jsLogBuf == nil {
<del> w.jsLogBuf = new(bytes.Buffer)
<del> w.jsLogBuf.Grow(1024)
<del> }
<del> var timestamp string
<del> created := time.Now().UTC()
<del> w.buf.Write(p)
<del> for {
<del> if n := w.buf.Len(); n == 0 {
<del> break
<del> }
<del> i := bytes.IndexByte(w.buf.Bytes(), '\n')
<del> if i < 0 {
<del> break
<del> }
<del> lineBytes := w.buf.Next(i + 1)
<del> if timestamp == "" {
<del> timestamp, err = timeutils.FastMarshalJSON(created)
<del> if err != nil {
<del> continue
<del> }
<del> }
<del>
<del> for stream, writers := range w.streams {
<del> if stream == "" {
<del> continue
<del> }
<del> jsonLog := jsonlog.JSONLogBytes{Log: lineBytes, Stream: stream, Created: timestamp}
<del> err = jsonLog.MarshalJSONBuf(w.jsLogBuf)
<del> if err != nil {
<del> logrus.Errorf("Error making JSON log line: %s", err)
<del> continue
<del> }
<del> w.jsLogBuf.WriteByte('\n')
<del> b := w.jsLogBuf.Bytes()
<del> for sw := range writers {
<del> if _, err := sw.Write(b); err != nil {
<del> delete(writers, sw)
<del> }
<del> }
<del> }
<del> w.jsLogBuf.Reset()
<del> }
<del> w.jsLogBuf.Reset()
<ide> w.Unlock()
<ide> return len(p), nil
<ide> }
<ide> func (w *BroadcastWriter) Write(p []byte) (n int, err error) {
<ide> // will be saved.
<ide> func (w *BroadcastWriter) Clean() error {
<ide> w.Lock()
<del> for _, writers := range w.streams {
<del> for w := range writers {
<del> w.Close()
<del> }
<add> for w := range w.writers {
<add> w.Close()
<ide> }
<del> w.streams = make(map[string](map[io.WriteCloser]struct{}))
<add> w.writers = make(map[io.WriteCloser]struct{})
<ide> w.Unlock()
<ide> return nil
<ide> }
<ide>
<ide> func New() *BroadcastWriter {
<ide> return &BroadcastWriter{
<del> streams: make(map[string](map[io.WriteCloser]struct{})),
<del> buf: bytes.NewBuffer(nil),
<add> writers: make(map[io.WriteCloser]struct{}),
<ide> }
<ide> }
<ide><path>pkg/broadcastwriter/broadcastwriter_test.go
<ide> func TestBroadcastWriter(t *testing.T) {
<ide>
<ide> // Test 1: Both bufferA and bufferB should contain "foo"
<ide> bufferA := &dummyWriter{}
<del> writer.AddWriter(bufferA, "")
<add> writer.AddWriter(bufferA)
<ide> bufferB := &dummyWriter{}
<del> writer.AddWriter(bufferB, "")
<add> writer.AddWriter(bufferB)
<ide> writer.Write([]byte("foo"))
<ide>
<ide> if bufferA.String() != "foo" {
<ide> func TestBroadcastWriter(t *testing.T) {
<ide> // Test2: bufferA and bufferB should contain "foobar",
<ide> // while bufferC should only contain "bar"
<ide> bufferC := &dummyWriter{}
<del> writer.AddWriter(bufferC, "")
<add> writer.AddWriter(bufferC)
<ide> writer.Write([]byte("bar"))
<ide>
<ide> if bufferA.String() != "foobar" {
<ide> func TestRaceBroadcastWriter(t *testing.T) {
<ide> writer := New()
<ide> c := make(chan bool)
<ide> go func() {
<del> writer.AddWriter(devNullCloser(0), "")
<add> writer.AddWriter(devNullCloser(0))
<ide> c <- true
<ide> }()
<ide> writer.Write([]byte("hello"))
<ide> func BenchmarkBroadcastWriter(b *testing.B) {
<ide> writer := New()
<ide> setUpWriter := func() {
<ide> for i := 0; i < 100; i++ {
<del> writer.AddWriter(devNullCloser(0), "stdout")
<del> writer.AddWriter(devNullCloser(0), "stderr")
<del> writer.AddWriter(devNullCloser(0), "")
<add> writer.AddWriter(devNullCloser(0))
<add> writer.AddWriter(devNullCloser(0))
<add> writer.AddWriter(devNullCloser(0))
<ide> }
<ide> }
<ide> testLine := "Line that thinks that it is log line from docker"
<ide> func BenchmarkBroadcastWriter(b *testing.B) {
<ide> b.StartTimer()
<ide> }
<ide> }
<del>
<del>func BenchmarkBroadcastWriterWithoutStdoutStderr(b *testing.B) {
<del> writer := New()
<del> setUpWriter := func() {
<del> for i := 0; i < 100; i++ {
<del> writer.AddWriter(devNullCloser(0), "")
<del> }
<del> }
<del> testLine := "Line that thinks that it is log line from docker"
<del> var buf bytes.Buffer
<del> for i := 0; i < 100; i++ {
<del> buf.Write([]byte(testLine + "\n"))
<del> }
<del> // line without eol
<del> buf.Write([]byte(testLine))
<del> testText := buf.Bytes()
<del> b.SetBytes(int64(5 * len(testText)))
<del> b.ResetTimer()
<del> for i := 0; i < b.N; i++ {
<del> setUpWriter()
<del>
<del> for j := 0; j < 5; j++ {
<del> if _, err := writer.Write(testText); err != nil {
<del> b.Fatal(err)
<del> }
<del> }
<del>
<del> writer.Clean()
<del> }
<del>}
<ide><path>pkg/jsonlog/jsonlog.go
<ide> package jsonlog
<ide> import (
<ide> "encoding/json"
<ide> "fmt"
<del> "io"
<ide> "time"
<ide> )
<ide>
<ide> func (jl *JSONLog) Reset() {
<ide> jl.Stream = ""
<ide> jl.Created = time.Time{}
<ide> }
<del>
<del>func WriteLog(src io.Reader, dst io.Writer, format string, since time.Time) error {
<del> dec := json.NewDecoder(src)
<del> l := &JSONLog{}
<del> for {
<del> l.Reset()
<del> if err := dec.Decode(l); err != nil {
<del> if err == io.EOF {
<del> return nil
<del> }
<del> return err
<del> }
<del> if !since.IsZero() && l.Created.Before(since) {
<del> continue
<del> }
<del>
<del> line, err := l.Format(format)
<del> if err != nil {
<del> return err
<del> }
<del> if _, err := io.WriteString(dst, line); err != nil {
<del> return err
<del> }
<del> }
<del>}
<ide><path>pkg/jsonlog/jsonlog_test.go
<del>package jsonlog
<del>
<del>import (
<del> "bytes"
<del> "encoding/json"
<del> "io/ioutil"
<del> "regexp"
<del> "strconv"
<del> "strings"
<del> "testing"
<del> "time"
<del>
<del> "github.com/docker/docker/pkg/timeutils"
<del>)
<del>
<del>// Invalid json should return an error
<del>func TestWriteLogWithInvalidJSON(t *testing.T) {
<del> json := strings.NewReader("Invalid json")
<del> w := bytes.NewBuffer(nil)
<del> if err := WriteLog(json, w, "json", time.Time{}); err == nil {
<del> t.Fatalf("Expected an error, got [%v]", w.String())
<del> }
<del>}
<del>
<del>// Any format is valid, it will just print it
<del>func TestWriteLogWithInvalidFormat(t *testing.T) {
<del> testLine := "Line that thinks that it is log line from docker\n"
<del> var buf bytes.Buffer
<del> e := json.NewEncoder(&buf)
<del> for i := 0; i < 35; i++ {
<del> e.Encode(JSONLog{Log: testLine, Stream: "stdout", Created: time.Now()})
<del> }
<del> w := bytes.NewBuffer(nil)
<del> if err := WriteLog(&buf, w, "invalid format", time.Time{}); err != nil {
<del> t.Fatal(err)
<del> }
<del> res := w.String()
<del> t.Logf("Result of WriteLog: %q", res)
<del> lines := strings.Split(strings.TrimSpace(res), "\n")
<del> expression := "^invalid format Line that thinks that it is log line from docker$"
<del> logRe := regexp.MustCompile(expression)
<del> expectedLines := 35
<del> if len(lines) != expectedLines {
<del> t.Fatalf("Must be %v lines but got %d", expectedLines, len(lines))
<del> }
<del> for _, l := range lines {
<del> if !logRe.MatchString(l) {
<del> t.Fatalf("Log line not in expected format [%v]: %q", expression, l)
<del> }
<del> }
<del>}
<del>
<del>// Having multiple Log/Stream element
<del>func TestWriteLogWithMultipleStreamLog(t *testing.T) {
<del> testLine := "Line that thinks that it is log line from docker\n"
<del> var buf bytes.Buffer
<del> e := json.NewEncoder(&buf)
<del> for i := 0; i < 35; i++ {
<del> e.Encode(JSONLog{Log: testLine, Stream: "stdout", Created: time.Now()})
<del> }
<del> w := bytes.NewBuffer(nil)
<del> if err := WriteLog(&buf, w, "invalid format", time.Time{}); err != nil {
<del> t.Fatal(err)
<del> }
<del> res := w.String()
<del> t.Logf("Result of WriteLog: %q", res)
<del> lines := strings.Split(strings.TrimSpace(res), "\n")
<del> expression := "^invalid format Line that thinks that it is log line from docker$"
<del> logRe := regexp.MustCompile(expression)
<del> expectedLines := 35
<del> if len(lines) != expectedLines {
<del> t.Fatalf("Must be %v lines but got %d", expectedLines, len(lines))
<del> }
<del> for _, l := range lines {
<del> if !logRe.MatchString(l) {
<del> t.Fatalf("Log line not in expected format [%v]: %q", expression, l)
<del> }
<del> }
<del>}
<del>
<del>// Write log with since after created, it won't print anything
<del>func TestWriteLogWithDate(t *testing.T) {
<del> created, _ := time.Parse("YYYY-MM-dd", "2015-01-01")
<del> var buf bytes.Buffer
<del> testLine := "Line that thinks that it is log line from docker\n"
<del> jsonLog := JSONLog{Log: testLine, Stream: "stdout", Created: created}
<del> if err := json.NewEncoder(&buf).Encode(jsonLog); err != nil {
<del> t.Fatal(err)
<del> }
<del> w := bytes.NewBuffer(nil)
<del> if err := WriteLog(&buf, w, "json", time.Now()); err != nil {
<del> t.Fatal(err)
<del> }
<del> res := w.String()
<del> if res != "" {
<del> t.Fatalf("Expected empty log, got [%v]", res)
<del> }
<del>}
<del>
<del>// Happy path :)
<del>func TestWriteLog(t *testing.T) {
<del> testLine := "Line that thinks that it is log line from docker\n"
<del> format := timeutils.RFC3339NanoFixed
<del> logs := map[string][]string{
<del> "": {"35", "^Line that thinks that it is log line from docker$"},
<del> "json": {"1", `^{\"log\":\"Line that thinks that it is log line from docker\\n\",\"stream\":\"stdout\",\"time\":.{30,}\"}$`},
<del> // 30+ symbols, five more can come from system timezone
<del> format: {"35", `.{30,} Line that thinks that it is log line from docker`},
<del> }
<del> for givenFormat, expressionAndLines := range logs {
<del> expectedLines, _ := strconv.Atoi(expressionAndLines[0])
<del> expression := expressionAndLines[1]
<del> var buf bytes.Buffer
<del> e := json.NewEncoder(&buf)
<del> for i := 0; i < 35; i++ {
<del> e.Encode(JSONLog{Log: testLine, Stream: "stdout", Created: time.Now()})
<del> }
<del> w := bytes.NewBuffer(nil)
<del> if err := WriteLog(&buf, w, givenFormat, time.Time{}); err != nil {
<del> t.Fatal(err)
<del> }
<del> res := w.String()
<del> t.Logf("Result of WriteLog: %q", res)
<del> lines := strings.Split(strings.TrimSpace(res), "\n")
<del> if len(lines) != expectedLines {
<del> t.Fatalf("Must be %v lines but got %d", expectedLines, len(lines))
<del> }
<del> logRe := regexp.MustCompile(expression)
<del> for _, l := range lines {
<del> if !logRe.MatchString(l) {
<del> t.Fatalf("Log line not in expected format [%v]: %q", expression, l)
<del> }
<del> }
<del> }
<del>}
<del>
<del>func BenchmarkWriteLog(b *testing.B) {
<del> var buf bytes.Buffer
<del> e := json.NewEncoder(&buf)
<del> testLine := "Line that thinks that it is log line from docker\n"
<del> for i := 0; i < 30; i++ {
<del> e.Encode(JSONLog{Log: testLine, Stream: "stdout", Created: time.Now()})
<del> }
<del> r := bytes.NewReader(buf.Bytes())
<del> w := ioutil.Discard
<del> format := timeutils.RFC3339NanoFixed
<del> b.SetBytes(int64(r.Len()))
<del> b.ResetTimer()
<del> for i := 0; i < b.N; i++ {
<del> if err := WriteLog(r, w, format, time.Time{}); err != nil {
<del> b.Fatal(err)
<del> }
<del> b.StopTimer()
<del> r.Seek(0, 0)
<del> b.StartTimer()
<del> }
<del>} | 5 |
Javascript | Javascript | add $httpbackend mock | cd28a2e952efbc2f76ff86b6b7d21fd5e41cec65 | <ide><path>angularFiles.js
<ide> angularFiles = {
<ide> 'src/service/sniffer.js',
<ide> 'src/service/window.js',
<ide> 'src/service/http.js',
<add> 'src/service/httpBackend.js',
<ide> 'src/service/locale.js',
<ide> 'src/directives.js',
<ide> 'src/markups.js',
<ide><path>src/AngularPublic.js
<ide> function ngModule($provide, $injector) {
<ide> $provide.service('$filter', $FilterProvider);
<ide> $provide.service('$formFactory', $FormFactoryProvider);
<ide> $provide.service('$http', $HttpProvider);
<add> $provide.service('$httpBackend', $HttpBackendProvider);
<ide> $provide.service('$location', $LocationProvider);
<ide> $provide.service('$log', $LogProvider);
<ide> $provide.service('$parse', $ParseProvider);
<ide><path>src/angular-mocks.js
<ide> angular.module.ngMock = function($provide){
<ide> $provide.service('$browser', angular.module.ngMock.$BrowserProvider);
<ide> $provide.service('$exceptionHandler', angular.module.ngMock.$ExceptionHandlerProvider);
<ide> $provide.service('$log', angular.module.ngMock.$LogProvider);
<add> $provide.service('$httpBackend', angular.module.ngMock.$HttpBackendProvider);
<ide> };
<ide> angular.module.ngMock.$inject = ['$provide'];
<ide>
<ide> angular.module.ngMock.$inject = ['$provide'];
<ide> *
<ide> * The following apis can be used in tests:
<ide> *
<del> * - {@link #xhr} β enables testing of code that uses
<del> * the {@link angular.module.ng.$xhr $xhr service} to make XmlHttpRequests.
<ide> * - $browser.defer β enables testing of code that uses
<ide> * {@link angular.module.ng.$defer $defer} for executing functions via the `setTimeout` api.
<ide> */
<ide> angular.module.ngMock.dump = function(object){
<ide> }
<ide> };
<ide>
<add>/**
<add> * @ngdoc object
<add> * @name angular.module.ngMock.$httpBackend
<add> */
<add>angular.module.ngMock.$HttpBackendProvider = function() {
<add> this.$get = function() {
<add> var definitions = [],
<add> expectations = [],
<add> responses = [];
<add>
<add> function createResponse(status, data, headers) {
<add> return angular.isNumber(status) ? [status, data, headers] : [200, status, data];
<add> }
<add>
<add> // TODO(vojta): change params to: method, url, data, headers, callback
<add> function $httpBackend(method, url, data, callback, headers) {
<add> var xhr = new MockXhr(),
<add> expectation = expectations[0],
<add> wasExpected = false;
<add>
<add> if (expectation && expectation.match(method, url)) {
<add> if (!expectation.matchData(data))
<add> throw Error('Expected ' + method + ' ' + url + ' with different data');
<add>
<add> if (!expectation.matchHeaders(headers))
<add> throw Error('Expected ' + method + ' ' + url + ' with different headers');
<add>
<add> expectations.shift();
<add>
<add> if (expectation.response) {
<add> responses.push(function() {
<add> xhr.$$headers = expectation.response[2];
<add> callback(expectation.response[0], expectation.response[1]);
<add> });
<add> return method == 'JSONP' ? undefined : xhr;
<add> }
<add> wasExpected = true;
<add> }
<add>
<add> var i = -1, definition;
<add> while ((definition = definitions[++i])) {
<add> if (definition.match(method, url, data, headers || {})) {
<add> if (!definition.response) throw Error('No response defined !');
<add> responses.push(function() {
<add> var response = angular.isFunction(definition.response) ?
<add> definition.response(method, url, data, headers) : definition.response;
<add> xhr.$$headers = response[2];
<add> callback(response[0], response[1]);
<add> });
<add> return method == 'JSONP' ? undefined : xhr;
<add> }
<add> }
<add> throw wasExpected ? Error('No response defined !') :
<add> Error('Unexpected request: ' + method + ' ' + url);
<add> }
<add>
<add> $httpBackend.when = function(method, url, data, headers) {
<add> var definition = new MockHttpExpectation(method, url, data, headers);
<add> definitions.push(definition);
<add> return {
<add> then: function(status, data, headers) {
<add> definition.response = angular.isFunction(status) ? status : createResponse(status, data, headers);
<add> }
<add> };
<add> };
<add>
<add> $httpBackend.expect = function(method, url, data, headers) {
<add> var expectation = new MockHttpExpectation(method, url, data, headers);
<add> expectations.push(expectation);
<add> return {
<add> respond: function(status, data, headers) {
<add> expectation.response = createResponse(status, data, headers);
<add> }
<add> };
<add> };
<add>
<add> $httpBackend.flush = function(count) {
<add> count = count || responses.length;
<add> while (count--) {
<add> if (!responses.length) throw Error('No more pending requests');
<add> responses.shift()();
<add> }
<add> };
<add>
<add>
<add>
<add> $httpBackend.verifyExpectations = function() {
<add> if (expectations.length) {
<add> throw Error('Unsatisfied requests: ' + expectations.join(', '));
<add> }
<add> };
<add>
<add> $httpBackend.resetExpectations = function() {
<add> expectations = [];
<add> responses = [];
<add> };
<add>
<add> return $httpBackend;
<add> };
<add>};
<add>
<add>function MockHttpExpectation(method, url, data, headers) {
<add>
<add> this.match = function(m, u, d, h) {
<add> if (method != m) return false;
<add> if (!this.matchUrl(u)) return false;
<add> if (angular.isDefined(d) && !this.matchData(d)) return false;
<add> if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
<add> return true;
<add> };
<add>
<add> this.matchUrl = function(u) {
<add> if (!url) return true;
<add> if (angular.isFunction(url.test)) {
<add> if (!url.test(u)) return false;
<add> } else if (url != u) return false;
<add>
<add> return true;
<add> };
<add>
<add> this.matchHeaders = function(h) {
<add> if (angular.isUndefined(headers)) return true;
<add> if (angular.isFunction(headers)) {
<add> if (!headers(h)) return false;
<add> } else if (!angular.equals(headers, h)) return false;
<add>
<add> return true;
<add> };
<add>
<add> this.matchData = function(d) {
<add> if (angular.isUndefined(data)) return true;
<add> if (data && angular.isFunction(data.test)) {
<add> if (!data.test(d)) return false;
<add> } else if (data != d) return false;
<add>
<add> return true;
<add> };
<add>
<add> this.toString = function() {
<add> return method + ' ' + url;
<add> };
<add>}
<add>
<add>function MockXhr() {
<add>
<add> // hack for testing $http
<add> MockXhr.$$lastInstance = this;
<add>
<add> this.getResponseHeader = function(name) {
<add> return this.$$headers[name];
<add> };
<add>
<add> this.getAllResponseHeaders = function() {
<add> var lines = [];
<add>
<add> angular.forEach(this.$$headers, function(value, key) {
<add> lines.push(key + ': ' + value);
<add> });
<add> return lines.join('\n');
<add> };
<add>
<add> this.abort = noop;
<add>}
<add>
<ide> window.jstestdriver && (function(window){
<ide> /**
<ide> * Global method to output any number of objects into JSTD console. Useful for debugging.
<ide><path>src/service/http.js
<ide> function transform(data, fns, param) {
<ide> /**
<ide> * @ngdoc object
<ide> * @name angular.module.ng.$http
<add> * @requires $httpBacked
<ide> * @requires $browser
<ide> * @requires $exceptionHandler
<ide> * @requires $cacheFactory
<ide> function $HttpProvider() {
<ide> }
<ide> };
<ide>
<del> this.$get = ['$browser', '$exceptionHandler', '$cacheFactory', '$rootScope',
<del> function($browser, $exceptionHandler, $cacheFactory, $rootScope) {
<add> this.$get = ['$httpBackend', '$browser', '$exceptionHandler', '$cacheFactory', '$rootScope',
<add> function($httpBackend, $browser, $exceptionHandler, $cacheFactory, $rootScope) {
<ide>
<ide> var cache = $cacheFactory('$http'),
<ide> pendingRequestsCount = 0;
<ide> function $HttpProvider() {
<ide> /**
<ide> * Represents Request object, returned by $http()
<ide> *
<del> * !!! ACCESS CLOSURE VARS: $browser, $config, $log, $rootScope, cache, pendingRequestsCount
<add> * !!! ACCESS CLOSURE VARS: $httpBackend, $browser, $config, $log, $rootScope, cache, pendingRequestsCount
<ide> */
<ide> function XhrFuture() {
<ide> var rawRequest, cfg = {}, callbacks = [],
<ide> defHeaders = $config.headers,
<ide> parsedHeaders;
<ide>
<ide> /**
<del> * Callback registered to $browser.xhr:
<add> * Callback registered to $httpBackend():
<ide> * - caches the response if desired
<ide> * - calls fireCallbacks()
<ide> * - clears the reference to raw request object
<ide> function $HttpProvider() {
<ide> * Fire all registered callbacks for given status code
<ide> *
<ide> * This method when:
<del> * - serving response from real request ($browser.xhr callback)
<add> * - serving response from real request
<ide> * - serving response from cache
<ide> *
<ide> * It does:
<ide> function $HttpProvider() {
<ide> fireCallbacks(fromCache[1], fromCache[0]);
<ide> });
<ide> } else {
<del> rawRequest = $browser.xhr(cfg.method, cfg.url, data, done, headers, cfg.timeout);
<add> rawRequest = $httpBackend(cfg.method, cfg.url, data, done, headers, cfg.timeout);
<ide> }
<ide>
<ide> pendingRequestsCount++;
<ide><path>src/service/httpBackend.js
<add>function $HttpBackendProvider() {
<add> this.$get = ['$browser', function($browser) {
<add> return $browser.xhr;
<add> }];
<add>}
<add>
<ide><path>test/angular-mocksSpec.js
<ide> describe('mocks', function() {
<ide> expect(count).toBe(2);
<ide> });
<ide> });
<add>
<add>
<add> describe('$httpBackend', function() {
<add> var hb, callback;
<add>
<add> beforeEach(inject(function($httpBackend) {
<add> callback = jasmine.createSpy('callback');
<add> hb = $httpBackend;
<add> }));
<add>
<add>
<add> it('should respond with first matched definition', function() {
<add> hb.when('GET', '/url1').then(200, 'content', {});
<add> hb.when('GET', '/url1').then(201, 'another', {});
<add>
<add> callback.andCallFake(function(status, response) {
<add> expect(status).toBe(200);
<add> expect(response).toBe('content');
<add> });
<add>
<add> hb('GET', '/url1', null, callback);
<add> expect(callback).not.toHaveBeenCalled();
<add> hb.flush();
<add> expect(callback).toHaveBeenCalledOnce();
<add> });
<add>
<add>
<add> it('should throw error when unexpected request', function() {
<add> hb.when('GET', '/url1').then(200, 'content');
<add> expect(function() {
<add> hb('GET', '/xxx');
<add> }).toThrow('Unexpected request: GET /xxx');
<add> });
<add>
<add>
<add> it('should match headers if specified', function() {
<add> hb.when('GET', '/url', null, {'X': 'val1'}).then(201, 'content1');
<add> hb.when('GET', '/url', null, {'X': 'val2'}).then(202, 'content2');
<add> hb.when('GET', '/url').then(203, 'content3');
<add>
<add> hb('GET', '/url', null, function(status, response) {
<add> expect(status).toBe(203);
<add> expect(response).toBe('content3');
<add> });
<add>
<add> hb('GET', '/url', null, function(status, response) {
<add> expect(status).toBe(201);
<add> expect(response).toBe('content1');
<add> }, {'X': 'val1'});
<add>
<add> hb('GET', '/url', null, function(status, response) {
<add> expect(status).toBe(202);
<add> expect(response).toBe('content2');
<add> }, {'X': 'val2'});
<add>
<add> hb.flush();
<add> });
<add>
<add>
<add> it('should match data if specified', function() {
<add> hb.when('GET', '/a/b', '{a: true}').then(201, 'content1');
<add> hb.when('GET', '/a/b').then(202, 'content2');
<add>
<add> hb('GET', '/a/b', '{a: true}', function(status, response) {
<add> expect(status).toBe(201);
<add> expect(response).toBe('content1');
<add> });
<add>
<add> hb('GET', '/a/b', null, function(status, response) {
<add> expect(status).toBe(202);
<add> expect(response).toBe('content2');
<add> });
<add>
<add> hb.flush();
<add> });
<add>
<add>
<add> it('should match only method', function() {
<add> hb.when('GET').then(202, 'c');
<add> callback.andCallFake(function(status, response) {
<add> expect(status).toBe(202);
<add> expect(response).toBe('c');
<add> });
<add>
<add> hb('GET', '/some', null, callback, {});
<add> hb('GET', '/another', null, callback, {'X-Fake': 'Header'});
<add> hb('GET', '/third', 'some-data', callback, {});
<add> hb.flush();
<add>
<add> expect(callback).toHaveBeenCalled();
<add> });
<add>
<add>
<add> it('should expose given headers', function() {
<add> hb.when('GET', '/u1').then(200, null, {'X-Fake': 'Header', 'Content-Type': 'application/json'});
<add> var xhr = hb('GET', '/u1', null, noop, {});
<add> hb.flush();
<add> expect(xhr.getResponseHeader('X-Fake')).toBe('Header');
<add> expect(xhr.getAllResponseHeaders()).toBe('X-Fake: Header\nContent-Type: application/json');
<add> });
<add>
<add>
<add> it('should preserve the order of requests', function() {
<add> hb.when('GET', '/url1').then(200, 'first');
<add> hb.when('GET', '/url2').then(201, 'second');
<add>
<add> hb('GET', '/url2', null, callback);
<add> hb('GET', '/url1', null, callback);
<add>
<add> hb.flush();
<add>
<add> expect(callback.callCount).toBe(2);
<add> expect(callback.argsForCall[0]).toEqual([201, 'second']);
<add> expect(callback.argsForCall[1]).toEqual([200, 'first']);
<add> });
<add>
<add>
<add> it('then() should take function', function() {
<add> hb.when('GET', '/some').then(function(m, u, d, h) {
<add> return [301, m + u + ';' + d + ';a=' + h.a, {'Connection': 'keep-alive'}];
<add> });
<add>
<add> var xhr = hb('GET', '/some', 'data', callback, {a: 'b'});
<add> hb.flush();
<add>
<add> expect(callback).toHaveBeenCalledOnce();
<add> expect(callback.mostRecentCall.args[0]).toBe(301);
<add> expect(callback.mostRecentCall.args[1]).toBe('GET/some;data;a=b');
<add> expect(xhr.getResponseHeader('Connection')).toBe('keep-alive');
<add> });
<add>
<add>
<add> it('expect() should require specified order', function() {
<add> hb.expect('GET', '/url1').respond(200, '');
<add> hb.expect('GET', '/url2').respond(200, '');
<add>
<add> expect(function() {
<add> hb('GET', '/url2', null, noop, {});
<add> }).toThrow('Unexpected request: GET /url2');
<add> });
<add>
<add>
<add> it('expect() should have precendence over when()', function() {
<add> callback.andCallFake(function(status, response) {
<add> expect(status).toBe(300);
<add> expect(response).toBe('expect');
<add> });
<add>
<add> hb.when('GET', '/url').then(200, 'when');
<add> hb.expect('GET', '/url').respond(300, 'expect');
<add>
<add> hb('GET', '/url', null, callback, {});
<add> hb.flush();
<add> expect(callback).toHaveBeenCalledOnce();
<add> });
<add>
<add>
<add> it ('should throw exception when only headers differes from expectation', function() {
<add> hb.when('GET').then(200, '', {});
<add> hb.expect('GET', '/match', undefined, {'Content-Type': 'application/json'});
<add>
<add> expect(function() {
<add> hb('GET', '/match', null, noop, {});
<add> }).toThrow('Expected GET /match with different headers');
<add> });
<add>
<add>
<add> it ('should throw exception when only data differes from expectation', function() {
<add> hb.when('GET').then(200, '', {});
<add> hb.expect('GET', '/match', 'some-data');
<add>
<add> expect(function() {
<add> hb('GET', '/match', 'different', noop, {});
<add> }).toThrow('Expected GET /match with different data');
<add> });
<add>
<add>
<add> it('expect() should without respond() and use then()', function() {
<add> callback.andCallFake(function(status, response) {
<add> expect(status).toBe(201);
<add> expect(response).toBe('data');
<add> });
<add>
<add> hb.when('GET', '/some').then(201, 'data');
<add> hb.expect('GET', '/some');
<add> hb('GET', '/some', null, callback);
<add> hb.flush();
<add>
<add> expect(callback).toHaveBeenCalled();
<add> expect(function() { hb.verifyExpectations(); }).not.toThrow();
<add> });
<add>
<add>
<add> it('flush() should not flush requests fired during callbacks', function() {
<add> // regression
<add> hb.when('GET').then(200, '');
<add> hb('GET', '/some', null, function() {
<add> hb('GET', '/other', null, callback);
<add> });
<add>
<add> hb.flush();
<add> expect(callback).not.toHaveBeenCalled();
<add> });
<add>
<add>
<add> it('flush() should flush given number of pending requests', function() {
<add> hb.when('GET').then(200, '');
<add> hb('GET', '/some', null, callback);
<add> hb('GET', '/some', null, callback);
<add> hb('GET', '/some', null, callback);
<add>
<add> hb.flush(2);
<add> expect(callback).toHaveBeenCalled();
<add> expect(callback.callCount).toBe(2);
<add> });
<add>
<add>
<add> it('flush() should throw exception when flushing more requests than pending', function() {
<add> hb.when('GET').then(200, '');
<add> hb('GET', '/url', null, callback);
<add>
<add> expect(function() {hb.flush(2);}).toThrow('No more pending requests');
<add> expect(callback).toHaveBeenCalledOnce();
<add> });
<add>
<add>
<add> it('respond() should set default status 200 if not defined', function() {
<add> callback.andCallFake(function(status, response) {
<add> expect(status).toBe(200);
<add> expect(response).toBe('some-data');
<add> });
<add>
<add> hb.expect('GET', '/url1').respond('some-data');
<add> hb.expect('GET', '/url2').respond('some-data', {'X-Header': 'true'});
<add> hb('GET', '/url1', null, callback);
<add> hb('GET', '/url2', null, callback);
<add> hb.flush();
<add> expect(callback).toHaveBeenCalled();
<add> expect(callback.callCount).toBe(2);
<add> });
<add>
<add>
<add> it('then() should set default status 200 if not defined', function() {
<add> callback.andCallFake(function(status, response) {
<add> expect(status).toBe(200);
<add> expect(response).toBe('some-data');
<add> });
<add>
<add> hb.when('GET', '/url1').then('some-data');
<add> hb.when('GET', '/url2').then('some-data', {'X-Header': 'true'});
<add> hb('GET', '/url1', null, callback);
<add> hb('GET', '/url2', null, callback);
<add> hb.flush();
<add> expect(callback).toHaveBeenCalled();
<add> expect(callback.callCount).toBe(2);
<add> });
<add>
<add>
<add> it('should respond with definition if no response for expectation', function() {
<add> callback.andCallFake(function(status, response) {
<add> expect(status).toBe(201);
<add> expect(response).toBe('def-response');
<add> });
<add>
<add> hb.when('GET').then(201, 'def-response');
<add> hb.expect('GET', '/some-url');
<add>
<add> hb('GET', '/some-url', null, callback);
<add> hb.flush();
<add> expect(callback).toHaveBeenCalledOnce();
<add> hb.verifyExpectations();
<add> });
<add>
<add>
<add> it('should throw an exception if no response defined', function() {
<add> hb.when('GET', '/test');
<add> expect(function() {
<add> hb('GET', '/test', null, callback);
<add> }).toThrow('No response defined !');
<add> });
<add>
<add>
<add> it('should throw an exception if no response for expection and no definition', function() {
<add> hb.expect('GET', '/url');
<add> expect(function() {
<add> hb('GET', '/url', null, callback);
<add> }).toThrow('No response defined !');
<add> });
<add>
<add>
<add> it('should respond undefined when JSONP method', function() {
<add> hb.when('JSONP', '/url1').then(200);
<add> hb.expect('JSONP', '/url2').respond(200);
<add>
<add> expect(hb('JSONP', '/url1')).toBeUndefined();
<add> expect(hb('JSONP', '/url2')).toBeUndefined();
<add> });
<add>
<add>
<add> describe('verify', function() {
<add>
<add> it('should throw exception if not all expectations were satisfied', function() {
<add> hb.expect('POST', '/u1', 'ddd').respond(201, '', {});
<add> hb.expect('GET', '/u2').respond(200, '', {});
<add> hb.expect('POST', '/u3').respond(201, '', {});
<add>
<add> hb('POST', '/u1', 'ddd', noop, {});
<add>
<add> expect(function() {hb.verifyExpectations();})
<add> .toThrow('Unsatisfied requests: GET /u2, POST /u3');
<add> });
<add>
<add>
<add> it('should do nothing when no expectation', function() {
<add> hb.when('DELETE', '/some').then(200, '');
<add>
<add> expect(function() {hb.verifyExpectations();}).not.toThrow();
<add> });
<add>
<add>
<add> it('should do nothing when all expectations satisfied', function() {
<add> hb.expect('GET', '/u2').respond(200, '', {});
<add> hb.expect('POST', '/u3').respond(201, '', {});
<add> hb.when('DELETE', '/some').then(200, '');
<add>
<add> hb('GET', '/u2', noop);
<add> hb('POST', '/u3', noop);
<add>
<add> expect(function() {hb.verifyExpectations();}).not.toThrow();
<add> });
<add> });
<add>
<add>
<add> describe('reset', function() {
<add>
<add> it('should remove all expectations', function() {
<add> hb.expect('GET', '/u2').respond(200, '', {});
<add> hb.expect('POST', '/u3').respond(201, '', {});
<add> hb.resetExpectations();
<add>
<add> expect(function() {hb.verifyExpectations();}).not.toThrow();
<add> });
<add>
<add>
<add> it('should remove all responses', function() {
<add> hb.expect('GET', '/url').respond(200, '', {});
<add> hb('GET', '/url', null, callback, {});
<add> hb.resetExpectations();
<add> hb.flush();
<add>
<add> expect(callback).not.toHaveBeenCalled();
<add> });
<add> });
<add>
<add>
<add> describe('MockHttpExpectation', function() {
<add>
<add> it('should accept url as regexp', function() {
<add> var exp = new MockHttpExpectation('GET', /^\/x/);
<add>
<add> expect(exp.match('GET', '/x')).toBe(true);
<add> expect(exp.match('GET', '/xxx/x')).toBe(true);
<add> expect(exp.match('GET', 'x')).toBe(false);
<add> expect(exp.match('GET', 'a/x')).toBe(false);
<add> });
<add>
<add>
<add> it('should accept data as regexp', function() {
<add> var exp = new MockHttpExpectation('POST', '/url', /\{.*?\}/);
<add>
<add> expect(exp.match('POST', '/url', '{"a": "aa"}')).toBe(true);
<add> expect(exp.match('POST', '/url', '{"one": "two"}')).toBe(true);
<add> expect(exp.match('POST', '/url', '{"one"')).toBe(false);
<add> });
<add>
<add>
<add> it('should ignore data only if undefined (not null or false)', function() {
<add> var exp = new MockHttpExpectation('POST', '/url', null);
<add> expect(exp.matchData(null)).toBe(true);
<add> expect(exp.matchData('some-data')).toBe(false);
<add>
<add> exp = new MockHttpExpectation('POST', '/url', undefined);
<add> expect(exp.matchData(null)).toBe(true);
<add> expect(exp.matchData('some-data')).toBe(true);
<add> });
<add>
<add>
<add> it('should accept headers as function', function() {
<add> var exp = new MockHttpExpectation('GET', '/url', undefined, function(h) {
<add> return h['Content-Type'] == 'application/json';
<add> });
<add>
<add> expect(exp.matchHeaders({})).toBe(false);
<add> expect(exp.matchHeaders({'Content-Type': 'application/json', 'X-Another': 'true'})).toBe(true);
<add> });
<add> });
<add> });
<ide> });
<ide><path>test/service/httpSpec.js
<ide> // TODO(vojta): refactor these tests to use new inject() syntax
<ide> describe('$http', function() {
<ide>
<del> var $http, $browser, $exceptionHandler, // services
<del> method, url, data, headers, timeout, // passed arguments
<del> onSuccess, onError, // callback spies
<del> scope, errorLogs, respond, rawXhrObject, future;
<add> var $http, $browser, $exceptionHandler, $httpBackend,
<add> scope, callback, future, callback;
<ide>
<ide> beforeEach(inject(function($injector) {
<ide> $injector.get('$exceptionHandlerProvider').mode('log');
<ide> scope = $injector.get('$rootScope');
<ide> $http = $injector.get('$http');
<ide> $browser = $injector.get('$browser');
<add> $httpBackend = $injector.get('$httpBackend');
<ide> $exceptionHandler = $injector.get('$exceptionHandler');
<del>
<del> // TODO(vojta): move this into mock browser ?
<del> respond = method = url = data = headers = null;
<del> rawXhrObject = {
<del> abort: jasmine.createSpy('request.abort'),
<del> getResponseHeader: function(h) {return h + '-val';},
<del> getAllResponseHeaders: function() {
<del> return 'content-encoding: gzip\nserver: Apache\n';
<del> }
<del> };
<del>
<ide> spyOn(scope, '$apply');
<del> spyOn($browser, 'xhr').andCallFake(function(m, u, d, c, h, t) {
<del> method = m;
<del> url = u;
<del> data = d;
<del> respond = c;
<del> headers = h;
<del> timeout = t;
<del> return rawXhrObject;
<del> });
<add> callback = jasmine.createSpy('callback');
<ide> }));
<ide>
<ide> afterEach(function() {
<del> // expect($exceptionHandler.errors.length).toBe(0);
<add> if ($exceptionHandler.errors.length) throw $exceptionHandler.errors;
<add> $httpBackend.verifyExpectations();
<ide> });
<ide>
<del> function doCommonXhr(method, url) {
<del> future = $http({method: method || 'GET', url: url || '/url'});
<del>
<del> onSuccess = jasmine.createSpy('on200');
<del> onError = jasmine.createSpy('on400');
<del> future.on('200', onSuccess);
<del> future.on('400', onError);
<del>
<del> return future;
<del> }
<del>
<ide>
<ide> it('should do basic request', function() {
<add> $httpBackend.expect('GET', '/url').respond('');
<ide> $http({url: '/url', method: 'GET'});
<del> expect($browser.xhr).toHaveBeenCalledOnce();
<del> expect(url).toBe('/url');
<del> expect(method).toBe('GET');
<ide> });
<ide>
<ide>
<ide> it('should pass data if specified', function() {
<add> $httpBackend.expect('POST', '/url', 'some-data').respond('');
<ide> $http({url: '/url', method: 'POST', data: 'some-data'});
<del> expect($browser.xhr).toHaveBeenCalledOnce();
<del> expect(data).toBe('some-data');
<ide> });
<ide>
<ide>
<del> it('should pass timeout if specified', function() {
<del> $http({url: '/url', method: 'POST', timeout: 5000});
<del> expect($browser.xhr).toHaveBeenCalledOnce();
<del> expect(timeout).toBe(5000);
<del> });
<add> // TODO(vojta): test passing timeout
<ide>
<ide>
<ide> describe('callbacks', function() {
<ide>
<del> beforeEach(doCommonXhr);
<add> function throwing(name) {
<add> return function() {
<add> throw name;
<add> };
<add> }
<ide>
<ide> it('should log exceptions', function() {
<del> onSuccess.andThrow('exception in success callback');
<del> onError.andThrow('exception in error callback');
<add> $httpBackend.expect('GET', '/url1').respond(200, 'content');
<add> $httpBackend.expect('GET', '/url2').respond(400, '');
<ide>
<del> respond(200, 'content');
<del> expect($exceptionHandler.errors.pop()).toContain('exception in success callback');
<add> $http({url: '/url1', method: 'GET'}).on('200', throwing('exception in success callback'));
<add> $http({url: '/url2', method: 'GET'}).on('400', throwing('exception in error callback'));
<add> $httpBackend.flush();
<ide>
<del> respond(400, '');
<del> expect($exceptionHandler.errors.pop()).toContain('exception in error callback');
<add> expect($exceptionHandler.errors.shift()).toContain('exception in success callback');
<add> expect($exceptionHandler.errors.shift()).toContain('exception in error callback');
<ide> });
<ide>
<ide>
<ide> it('should log more exceptions', function() {
<del> onError.andThrow('exception in error callback');
<del> future.on('500', onError).on('50x', onError);
<del> respond(500, '');
<add> $httpBackend.expect('GET', '/url').respond(500, '');
<add> $http({url: '/url', method: 'GET'})
<add> .on('500', throwing('exception in error callback'))
<add> .on('5xx', throwing('exception in error callback'));
<add> $httpBackend.flush();
<ide>
<ide> expect($exceptionHandler.errors.length).toBe(2);
<ide> $exceptionHandler.errors = [];
<ide> });
<ide>
<ide>
<ide> it('should get response as first param', function() {
<del> respond(200, 'response');
<del> expect(onSuccess).toHaveBeenCalledOnce();
<del> expect(onSuccess.mostRecentCall.args[0]).toBe('response');
<add> $httpBackend.expect('GET', '/url').respond('some-content');
<add> $http({url: '/url', method: 'GET'}).on('200', callback);
<add> $httpBackend.flush();
<ide>
<del> respond(400, 'empty');
<del> expect(onError).toHaveBeenCalledOnce();
<del> expect(onError.mostRecentCall.args[0]).toBe('empty');
<add> expect(callback).toHaveBeenCalledOnce();
<add> expect(callback.mostRecentCall.args[0]).toBe('some-content');
<ide> });
<ide>
<ide>
<ide> it('should get status code as second param', function() {
<del> respond(200, 'response');
<del> expect(onSuccess).toHaveBeenCalledOnce();
<del> expect(onSuccess.mostRecentCall.args[1]).toBe(200);
<add> $httpBackend.expect('GET', '/url').respond(250, 'some-content');
<add> $http({url: '/url', method: 'GET'}).on('2xx', callback);
<add> $httpBackend.flush();
<ide>
<del> respond(400, 'empty');
<del> expect(onError).toHaveBeenCalledOnce();
<del> expect(onError.mostRecentCall.args[1]).toBe(400);
<add> expect(callback).toHaveBeenCalledOnce();
<add> expect(callback.mostRecentCall.args[1]).toBe(250);
<ide> });
<ide> });
<ide>
<ide>
<ide> describe('response headers', function() {
<ide>
<del> var callback;
<del>
<del> beforeEach(function() {
<del> callback = jasmine.createSpy('callback');
<del> });
<del>
<ide> it('should return single header', function() {
<add> $httpBackend.expect('GET', '/url').respond('', {'date': 'date-val'});
<ide> callback.andCallFake(function(r, s, header) {
<ide> expect(header('date')).toBe('date-val');
<ide> });
<ide>
<ide> $http({url: '/url', method: 'GET'}).on('200', callback);
<del> respond(200, '');
<add> $httpBackend.flush();
<ide>
<ide> expect(callback).toHaveBeenCalledOnce();
<ide> });
<ide>
<ide>
<ide> it('should return null when single header does not exist', function() {
<add> $httpBackend.expect('GET', '/url').respond('', {'Some-Header': 'Fake'});
<ide> callback.andCallFake(function(r, s, header) {
<ide> header(); // we need that to get headers parsed first
<ide> expect(header('nothing')).toBe(null);
<ide> });
<ide>
<ide> $http({url: '/url', method: 'GET'}).on('200', callback);
<del> respond(200, '');
<add> $httpBackend.flush();
<ide>
<ide> expect(callback).toHaveBeenCalledOnce();
<ide> });
<ide>
<ide>
<ide> it('should return all headers as object', function() {
<add> $httpBackend.expect('GET', '/url').respond('', {'content-encoding': 'gzip', 'server': 'Apache'});
<ide> callback.andCallFake(function(r, s, header) {
<ide> expect(header()).toEqual({'content-encoding': 'gzip', 'server': 'Apache'});
<ide> });
<ide>
<ide> $http({url: '/url', method: 'GET'}).on('200', callback);
<del> respond(200, '');
<add> $httpBackend.flush();
<ide>
<ide> expect(callback).toHaveBeenCalledOnce();
<ide> });
<ide>
<ide>
<ide> it('should return empty object for jsonp request', function() {
<del> // jsonp doesn't return raw object
<del> rawXhrObject = undefined;
<ide> callback.andCallFake(function(r, s, headers) {
<ide> expect(headers()).toEqual({});
<ide> });
<ide>
<add> $httpBackend.expect('JSONP', '/some').respond(200);
<ide> $http({url: '/some', method: 'JSONP'}).on('200', callback);
<del> respond(200, '');
<add> $httpBackend.flush();
<ide> expect(callback).toHaveBeenCalledOnce();
<ide> });
<ide> });
<ide> describe('$http', function() {
<ide> describe('request headers', function() {
<ide>
<ide> it('should send custom headers', function() {
<add> $httpBackend.expect('GET', '/url', undefined, function(headers) {
<add> return headers['Custom'] == 'header' && headers['Content-Type'] == 'application/json';
<add> }).respond('');
<add>
<ide> $http({url: '/url', method: 'GET', headers: {
<ide> 'Custom': 'header',
<ide> 'Content-Type': 'application/json'
<ide> }});
<ide>
<del> expect(headers['Custom']).toEqual('header');
<del> expect(headers['Content-Type']).toEqual('application/json');
<add> $httpBackend.flush();
<ide> });
<ide>
<ide>
<ide> it('should set default headers for GET request', function() {
<del> $http({url: '/url', method: 'GET', headers: {}});
<add> $httpBackend.expect('GET', '/url', undefined, function(headers) {
<add> return headers['Accept'] == 'application/json, text/plain, */*' &&
<add> headers['X-Requested-With'] == 'XMLHttpRequest';
<add> }).respond('');
<ide>
<del> expect(headers['Accept']).toBe('application/json, text/plain, */*');
<del> expect(headers['X-Requested-With']).toBe('XMLHttpRequest');
<add> $http({url: '/url', method: 'GET', headers: {}});
<add> $httpBackend.flush();
<ide> });
<ide>
<ide>
<ide> it('should set default headers for POST request', function() {
<del> $http({url: '/url', method: 'POST', headers: {}});
<add> $httpBackend.expect('POST', '/url', undefined, function(headers) {
<add> return headers['Accept'] == 'application/json, text/plain, */*' &&
<add> headers['X-Requested-With'] == 'XMLHttpRequest' &&
<add> headers['Content-Type'] == 'application/json';
<add> }).respond('');
<ide>
<del> expect(headers['Accept']).toBe('application/json, text/plain, */*');
<del> expect(headers['X-Requested-With']).toBe('XMLHttpRequest');
<del> expect(headers['Content-Type']).toBe('application/json');
<add> $http({url: '/url', method: 'POST', headers: {}});
<add> $httpBackend.flush();
<ide> });
<ide>
<ide>
<ide> it('should set default headers for PUT request', function() {
<del> $http({url: '/url', method: 'PUT', headers: {}});
<add> $httpBackend.expect('PUT', '/url', undefined, function(headers) {
<add> return headers['Accept'] == 'application/json, text/plain, */*' &&
<add> headers['X-Requested-With'] == 'XMLHttpRequest' &&
<add> headers['Content-Type'] == 'application/json';
<add> }).respond('');
<ide>
<del> expect(headers['Accept']).toBe('application/json, text/plain, */*');
<del> expect(headers['X-Requested-With']).toBe('XMLHttpRequest');
<del> expect(headers['Content-Type']).toBe('application/json');
<add> $http({url: '/url', method: 'PUT', headers: {}});
<add> $httpBackend.flush();
<ide> });
<ide>
<ide>
<ide> it('should set default headers for custom HTTP method', function() {
<del> $http({url: '/url', method: 'FOO', headers: {}});
<add> $httpBackend.expect('FOO', '/url', undefined, function(headers) {
<add> return headers['Accept'] == 'application/json, text/plain, */*' &&
<add> headers['X-Requested-With'] == 'XMLHttpRequest';
<add> }).respond('');
<ide>
<del> expect(headers['Accept']).toBe('application/json, text/plain, */*');
<del> expect(headers['X-Requested-With']).toBe('XMLHttpRequest');
<add> $http({url: '/url', method: 'FOO', headers: {}});
<add> $httpBackend.flush();
<ide> });
<ide>
<ide>
<ide> it('should override default headers with custom', function() {
<add> $httpBackend.expect('POST', '/url', undefined, function(headers) {
<add> return headers['Accept'] == 'Rewritten' &&
<add> headers['X-Requested-With'] == 'XMLHttpRequest' &&
<add> headers['Content-Type'] == 'Rewritten';
<add> }).respond('');
<add>
<ide> $http({url: '/url', method: 'POST', headers: {
<ide> 'Accept': 'Rewritten',
<ide> 'Content-Type': 'Rewritten'
<ide> }});
<del>
<del> expect(headers['Accept']).toBe('Rewritten');
<del> expect(headers['X-Requested-With']).toBe('XMLHttpRequest');
<del> expect(headers['Content-Type']).toBe('Rewritten');
<add> $httpBackend.flush();
<ide> });
<ide>
<ide>
<ide> it('should set the XSRF cookie into a XSRF header', function() {
<add> function checkXSRF(secret) {
<add> return function(headers) {
<add> return headers['X-XSRF-TOKEN'] == secret;
<add> };
<add> }
<add>
<ide> $browser.cookies('XSRF-TOKEN', 'secret');
<add> $httpBackend.expect('GET', '/url', undefined, checkXSRF('secret')).respond('');
<add> $httpBackend.expect('POST', '/url', undefined, checkXSRF('secret')).respond('');
<add> $httpBackend.expect('PUT', '/url', undefined, checkXSRF('secret')).respond('');
<add> $httpBackend.expect('DELETE', '/url', undefined, checkXSRF('secret')).respond('');
<ide>
<ide> $http({url: '/url', method: 'GET'});
<del> expect(headers['X-XSRF-TOKEN']).toBe('secret');
<del>
<ide> $http({url: '/url', method: 'POST', headers: {'S-ome': 'Header'}});
<del> expect(headers['X-XSRF-TOKEN']).toBe('secret');
<del>
<ide> $http({url: '/url', method: 'PUT', headers: {'Another': 'Header'}});
<del> expect(headers['X-XSRF-TOKEN']).toBe('secret');
<del>
<ide> $http({url: '/url', method: 'DELETE', headers: {}});
<del> expect(headers['X-XSRF-TOKEN']).toBe('secret');
<add>
<add> $httpBackend.flush();
<ide> });
<ide> });
<ide>
<ide>
<ide> describe('short methods', function() {
<ide>
<del> it('should have .get()', function() {
<del> $http.get('/url');
<add> function checkHeader(name, value) {
<add> return function(headers) {
<add> return headers[name] == value;
<add> };
<add> }
<ide>
<del> expect(method).toBe('GET');
<del> expect(url).toBe('/url');
<add> it('should have get()', function() {
<add> $httpBackend.expect('GET', '/url').respond('');
<add> $http.get('/url');
<ide> });
<ide>
<ide>
<del> it('.get() should allow config param', function() {
<add> it('get() should allow config param', function() {
<add> $httpBackend.expect('GET', '/url', undefined, checkHeader('Custom', 'Header')).respond('');
<ide> $http.get('/url', {headers: {'Custom': 'Header'}});
<del>
<del> expect(method).toBe('GET');
<del> expect(url).toBe('/url');
<del> expect(headers['Custom']).toBe('Header');
<ide> });
<ide>
<ide>
<del> it('should have .delete()', function() {
<add> it('should have delete()', function() {
<add> $httpBackend.expect('DELETE', '/url').respond('');
<ide> $http['delete']('/url');
<del>
<del> expect(method).toBe('DELETE');
<del> expect(url).toBe('/url');
<ide> });
<ide>
<ide>
<del> it('.delete() should allow config param', function() {
<add> it('delete() should allow config param', function() {
<add> $httpBackend.expect('DELETE', '/url', undefined, checkHeader('Custom', 'Header')).respond('');
<ide> $http['delete']('/url', {headers: {'Custom': 'Header'}});
<del>
<del> expect(method).toBe('DELETE');
<del> expect(url).toBe('/url');
<del> expect(headers['Custom']).toBe('Header');
<ide> });
<ide>
<ide>
<del> it('should have .head()', function() {
<add> it('should have head()', function() {
<add> $httpBackend.expect('HEAD', '/url').respond('');
<ide> $http.head('/url');
<del>
<del> expect(method).toBe('HEAD');
<del> expect(url).toBe('/url');
<ide> });
<ide>
<ide>
<del> it('.head() should allow config param', function() {
<add> it('head() should allow config param', function() {
<add> $httpBackend.expect('HEAD', '/url', undefined, checkHeader('Custom', 'Header')).respond('');
<ide> $http.head('/url', {headers: {'Custom': 'Header'}});
<del>
<del> expect(method).toBe('HEAD');
<del> expect(url).toBe('/url');
<del> expect(headers['Custom']).toBe('Header');
<ide> });
<ide>
<ide>
<del> it('should have .patch()', function() {
<add> it('should have patch()', function() {
<add> $httpBackend.expect('PATCH', '/url').respond('');
<ide> $http.patch('/url');
<del>
<del> expect(method).toBe('PATCH');
<del> expect(url).toBe('/url');
<ide> });
<ide>
<ide>
<del> it('.patch() should allow config param', function() {
<add> it('patch() should allow config param', function() {
<add> $httpBackend.expect('PATCH', '/url', undefined, checkHeader('Custom', 'Header')).respond('');
<ide> $http.patch('/url', {headers: {'Custom': 'Header'}});
<del>
<del> expect(method).toBe('PATCH');
<del> expect(url).toBe('/url');
<del> expect(headers['Custom']).toBe('Header');
<ide> });
<ide>
<ide>
<del> it('should have .post()', function() {
<add> it('should have post()', function() {
<add> $httpBackend.expect('POST', '/url', 'some-data').respond('');
<ide> $http.post('/url', 'some-data');
<del>
<del> expect(method).toBe('POST');
<del> expect(url).toBe('/url');
<del> expect(data).toBe('some-data');
<ide> });
<ide>
<ide>
<del> it('.post() should allow config param', function() {
<add> it('post() should allow config param', function() {
<add> $httpBackend.expect('POST', '/url', 'some-data', checkHeader('Custom', 'Header')).respond('');
<ide> $http.post('/url', 'some-data', {headers: {'Custom': 'Header'}});
<del>
<del> expect(method).toBe('POST');
<del> expect(url).toBe('/url');
<del> expect(data).toBe('some-data');
<del> expect(headers['Custom']).toBe('Header');
<ide> });
<ide>
<ide>
<del> it('should have .put()', function() {
<add> it('should have put()', function() {
<add> $httpBackend.expect('PUT', '/url', 'some-data').respond('');
<ide> $http.put('/url', 'some-data');
<del>
<del> expect(method).toBe('PUT');
<del> expect(url).toBe('/url');
<del> expect(data).toBe('some-data');
<ide> });
<ide>
<ide>
<del> it('.put() should allow config param', function() {
<add> it('put() should allow config param', function() {
<add> $httpBackend.expect('PUT', '/url', 'some-data', checkHeader('Custom', 'Header')).respond('');
<ide> $http.put('/url', 'some-data', {headers: {'Custom': 'Header'}});
<del>
<del> expect(method).toBe('PUT');
<del> expect(url).toBe('/url');
<del> expect(data).toBe('some-data');
<del> expect(headers['Custom']).toBe('Header');
<ide> });
<ide>
<ide>
<del> it('should have .jsonp()', function() {
<add> it('should have jsonp()', function() {
<add> $httpBackend.expect('JSONP', '/url').respond('');
<ide> $http.jsonp('/url');
<del>
<del> expect(method).toBe('JSONP');
<del> expect(url).toBe('/url');
<ide> });
<ide>
<ide>
<del> it('.jsonp() should allow config param', function() {
<add> it('jsonp() should allow config param', function() {
<add> $httpBackend.expect('JSONP', '/url', undefined, checkHeader('Custom', 'Header')).respond('');
<ide> $http.jsonp('/url', {headers: {'Custom': 'Header'}});
<del>
<del> expect(method).toBe('JSONP');
<del> expect(url).toBe('/url');
<del> expect(headers['Custom']).toBe('Header');
<ide> });
<ide> });
<ide>
<ide> describe('$http', function() {
<ide>
<ide> describe('abort', function() {
<ide>
<del> beforeEach(doCommonXhr);
<add> var future, rawXhrObject;
<add>
<add> beforeEach(function() {
<add> $httpBackend.when('GET', '/url').then('');
<add> future = $http({method: 'GET', url: '/url'});
<add> rawXhrObject = MockXhr.$$lastInstance;
<add> spyOn(rawXhrObject, 'abort');
<add> });
<ide>
<ide> it('should return itself to allow chaining', function() {
<ide> expect(future.abort()).toBe(future);
<ide> describe('$http', function() {
<ide>
<ide>
<ide> it('should not abort already finished request', function() {
<del> respond(200, 'content');
<add> $httpBackend.flush();
<ide>
<ide> future.abort();
<ide> expect(rawXhrObject.abort).not.toHaveBeenCalled();
<ide> describe('$http', function() {
<ide>
<ide> describe('retry', function() {
<ide>
<add> var future;
<add>
<add> beforeEach(function() {
<add> $httpBackend.expect('HEAD', '/url-x').respond('');
<add> future = $http({method: 'HEAD', url: '/url-x'}).on('2xx', callback);
<add> });
<add>
<ide> it('should retry last request with same callbacks', function() {
<del> doCommonXhr('HEAD', '/url-x');
<del> respond(200, '');
<del> $browser.xhr.reset();
<del> onSuccess.reset();
<add> $httpBackend.flush();
<add> callback.reset();
<ide>
<add> $httpBackend.expect('HEAD', '/url-x').respond('');
<ide> future.retry();
<del> expect($browser.xhr).toHaveBeenCalledOnce();
<del> expect(method).toBe('HEAD');
<del> expect(url).toBe('/url-x');
<del>
<del> respond(200, 'body');
<del> expect(onSuccess).toHaveBeenCalledOnce();
<add> $httpBackend.flush();
<add> expect(callback).toHaveBeenCalledOnce();
<ide> });
<ide>
<ide>
<ide> it('should return itself to allow chaining', function() {
<del> doCommonXhr();
<del> respond(200, '');
<add> $httpBackend.flush();
<add>
<add> $httpBackend.expect('HEAD', '/url-x').respond('');
<ide> expect(future.retry()).toBe(future);
<ide> });
<ide>
<ide>
<ide> it('should throw error when pending request', function() {
<del> doCommonXhr();
<ide> expect(future.retry).toThrow('Can not retry request. Abort pending request first.');
<ide> });
<ide> });
<ide>
<ide>
<ide> describe('on', function() {
<ide>
<del> var callback;
<add> var future;
<add>
<add> function expectToMatch(status, pattern) {
<add> expectToNotMatch(status, pattern, true);
<add> }
<add>
<add> function expectToNotMatch(status, pattern, match) {
<add> callback.reset();
<add> future = $http({method: 'GET', url: '/' + status});
<add> future.on(pattern, callback);
<add> $httpBackend.flush();
<add>
<add> if (match) expect(callback).toHaveBeenCalledOnce();
<add> else expect(callback).not.toHaveBeenCalledOnce();
<add> }
<ide>
<ide> beforeEach(function() {
<del> future = $http({method: 'GET', url: '/url'});
<del> callback = jasmine.createSpy('callback');
<add> $httpBackend.when('GET').then(function(m, url) {
<add> return [parseInt(url.substr(1)), '', {}];
<add> });
<ide> });
<ide>
<ide> it('should return itself to allow chaining', function() {
<add> future = $http({method: 'GET', url: '/url'});
<ide> expect(future.on('200', noop)).toBe(future);
<ide> });
<ide>
<ide>
<ide> it('should call exact status code callback', function() {
<del> future.on('205', callback);
<del> respond(205, '');
<del>
<del> expect(callback).toHaveBeenCalledOnce();
<add> expectToMatch(205, '205');
<ide> });
<ide>
<ide>
<ide> it('should match 2xx', function() {
<del> future.on('2xx', callback);
<del>
<del> respond(200, '');
<del> respond(201, '');
<del> respond(266, '');
<add> expectToMatch(200, '2xx');
<add> expectToMatch(201, '2xx');
<add> expectToMatch(266, '2xx');
<ide>
<del> respond(400, '');
<del> respond(300, '');
<del>
<del> expect(callback).toHaveBeenCalled();
<del> expect(callback.callCount).toBe(3);
<add> expectToNotMatch(400, '2xx');
<add> expectToNotMatch(300, '2xx');
<ide> });
<ide>
<ide>
<ide> it('should match 20x', function() {
<del> future.on('20x', callback);
<del>
<del> respond(200, '');
<del> respond(201, '');
<del> respond(205, '');
<del>
<del> respond(400, '');
<del> respond(300, '');
<del> respond(210, '');
<del> respond(255, '');
<add> expectToMatch(200, '20x');
<add> expectToMatch(201, '20x');
<add> expectToMatch(205, '20x');
<ide>
<del> expect(callback).toHaveBeenCalled();
<del> expect(callback.callCount).toBe(3);
<add> expectToNotMatch(210, '20x');
<add> expectToNotMatch(301, '20x');
<add> expectToNotMatch(404, '20x');
<add> expectToNotMatch(501, '20x');
<ide> });
<ide>
<ide>
<ide> it('should match 2x1', function() {
<del> future.on('2x1', callback);
<del>
<del> respond(201, '');
<del> respond(211, '');
<del> respond(251, '');
<del>
<del> respond(400, '');
<del> respond(300, '');
<del> respond(210, '');
<del> respond(255, '');
<add> expectToMatch(201, '2x1');
<add> expectToMatch(211, '2x1');
<add> expectToMatch(251, '2x1');
<ide>
<del> expect(callback).toHaveBeenCalled();
<del> expect(callback.callCount).toBe(3);
<add> expectToNotMatch(210, '2x1');
<add> expectToNotMatch(301, '2x1');
<add> expectToNotMatch(400, '2x1');
<ide> });
<ide>
<ide>
<ide> it('should match xxx', function() {
<del> future.on('xxx', callback);
<del>
<del> respond(201, '');
<del> respond(211, '');
<del> respond(251, '');
<del> respond(404, '');
<del> respond(501, '');
<del>
<del> expect(callback).toHaveBeenCalled();
<del> expect(callback.callCount).toBe(5);
<add> expectToMatch(200, 'xxx');
<add> expectToMatch(210, 'xxx');
<add> expectToMatch(301, 'xxx');
<add> expectToMatch(406, 'xxx');
<add> expectToMatch(510, 'xxx');
<ide> });
<ide>
<ide>
<ide> it('should call all matched callbacks', function() {
<ide> var no = jasmine.createSpy('wrong');
<del> future.on('xxx', callback);
<del> future.on('2xx', callback);
<del> future.on('205', callback);
<del> future.on('3xx', no);
<del> future.on('2x1', no);
<del> future.on('4xx', no);
<del> respond(205, '');
<add> $http({method: 'GET', url: '/205'})
<add> .on('xxx', callback)
<add> .on('2xx', callback)
<add> .on('205', callback)
<add> .on('3xx', no)
<add> .on('2x1', no)
<add> .on('4xx', no);
<add>
<add> $httpBackend.flush();
<ide>
<ide> expect(callback).toHaveBeenCalled();
<ide> expect(callback.callCount).toBe(3);
<ide> describe('$http', function() {
<ide>
<ide>
<ide> it('should allow list of status patterns', function() {
<del> future.on('2xx,3xx', callback);
<del>
<del> respond(405, '');
<del> expect(callback).not.toHaveBeenCalled();
<del>
<del> respond(201);
<del> expect(callback).toHaveBeenCalledOnce();
<del>
<del> respond(301);
<del> expect(callback.callCount).toBe(2);
<add> expectToMatch(201, '2xx,3xx');
<add> expectToMatch(301, '2xx,3xx');
<add> expectToNotMatch(405, '2xx,3xx');
<ide> });
<ide>
<ide>
<ide> it('should preserve the order of listeners', function() {
<ide> var log = '';
<del> future.on('2xx', function() {log += '1';});
<del> future.on('201', function() {log += '2';});
<del> future.on('2xx', function() {log += '3';});
<ide>
<del> respond(201);
<add> $http({method: 'GET', url: '/201'})
<add> .on('2xx', function() {log += '1';})
<add> .on('201', function() {log += '2';})
<add> .on('2xx', function() {log += '3';});
<add>
<add> $httpBackend.flush();
<ide> expect(log).toBe('123');
<ide> });
<ide>
<ide>
<ide> it('should know "success" alias', function() {
<del> future.on('success', callback);
<del> respond(200, '');
<del> expect(callback).toHaveBeenCalledOnce();
<del>
<del> callback.reset();
<del> respond(201, '');
<del> expect(callback).toHaveBeenCalledOnce();
<del>
<del> callback.reset();
<del> respond(250, '');
<del> expect(callback).toHaveBeenCalledOnce();
<add> expectToMatch(200, 'success');
<add> expectToMatch(201, 'success');
<add> expectToMatch(250, 'success');
<ide>
<del> callback.reset();
<del> respond(404, '');
<del> respond(501, '');
<del> expect(callback).not.toHaveBeenCalled();
<add> expectToNotMatch(403, 'success');
<add> expectToNotMatch(501, 'success');
<ide> });
<ide>
<ide>
<ide> it('should know "error" alias', function() {
<del> future.on('error', callback);
<del> respond(401, '');
<del> expect(callback).toHaveBeenCalledOnce();
<del>
<del> callback.reset();
<del> respond(500, '');
<del> expect(callback).toHaveBeenCalledOnce();
<add> expectToMatch(401, 'error');
<add> expectToMatch(500, 'error');
<add> expectToMatch(0, 'error');
<ide>
<del> callback.reset();
<del> respond(0, '');
<del> expect(callback).toHaveBeenCalledOnce();
<del>
<del> callback.reset();
<del> respond(201, '');
<del> respond(200, '');
<del> respond(300, '');
<del> expect(callback).not.toHaveBeenCalled();
<add> expectToNotMatch(201, 'error');
<add> expectToNotMatch(200, 'error');
<ide> });
<ide>
<ide>
<ide> it('should know "always" alias', function() {
<del> future.on('always', callback);
<del> respond(201, '');
<del> respond(200, '');
<del> respond(300, '');
<del> respond(401, '');
<del> respond(502, '');
<del> respond(0, '');
<del> respond(-1, '');
<del> respond(-2, '');
<del>
<del> expect(callback).toHaveBeenCalled();
<del> expect(callback.callCount).toBe(8);
<add> expectToMatch(200, 'always');
<add> expectToMatch(201, 'always');
<add> expectToMatch(250, 'always');
<add> expectToMatch(300, 'always');
<add> expectToMatch(302, 'always');
<add> expectToMatch(404, 'always');
<add> expectToMatch(501, 'always');
<add> expectToMatch(0, 'always');
<add> expectToMatch(-1, 'always');
<add> expectToMatch(-2, 'always');
<ide> });
<ide>
<ide>
<ide> it('should call "xxx" when 0 status code', function() {
<del> future.on('xxx', callback);
<del> respond(0, '');
<del> expect(callback).toHaveBeenCalledOnce();
<add> expectToMatch(0, 'xxx');
<ide> });
<ide>
<ide>
<ide> it('should not call "2xx" when 0 status code', function() {
<del> future.on('2xx', callback);
<del> respond(0, '');
<del> expect(callback).not.toHaveBeenCalled();
<add> expectToNotMatch(0, '2xx');
<ide> });
<ide>
<ide> it('should normalize internal statuses -1, -2 to 0', function() {
<ide> callback.andCallFake(function(response, status) {
<ide> expect(status).toBe(0);
<ide> });
<ide>
<del> future.on('xxx', callback);
<del> respond(-1, '');
<del> respond(-2, '');
<add> $http({method: 'GET', url: '/0'}).on('xxx', callback);
<add> $http({method: 'GET', url: '/-1'}).on('xxx', callback);
<add> $http({method: 'GET', url: '/-2'}).on('xxx', callback);
<ide>
<add> $httpBackend.flush();
<ide> expect(callback).toHaveBeenCalled();
<del> expect(callback.callCount).toBe(2);
<add> expect(callback.callCount).toBe(3);
<ide> });
<ide>
<ide> it('should match "timeout" when -1 internal status', function() {
<del> future.on('timeout', callback);
<del> respond(-1, '');
<del>
<del> expect(callback).toHaveBeenCalledOnce();
<add> expectToMatch(-1, 'timeout');
<ide> });
<ide>
<ide> it('should match "abort" when 0 status', function() {
<del> future.on('abort', callback);
<del> respond(0, '');
<del>
<del> expect(callback).toHaveBeenCalledOnce();
<add> expectToMatch(0, 'abort');
<ide> });
<ide>
<ide> it('should match "error" when 0, -1, or -2', function() {
<del> future.on('error', callback);
<del> respond(0, '');
<del> respond(-1, '');
<del> respond(-2, '');
<del>
<del> expect(callback).toHaveBeenCalled();
<del> expect(callback.callCount).toBe(3);
<add> expectToMatch(0, 'error');
<add> expectToMatch(-1, 'error');
<add> expectToMatch(-2, 'error');
<ide> });
<ide> });
<ide> });
<ide>
<ide>
<ide> describe('scope.$apply', function() {
<ide>
<del> beforeEach(doCommonXhr);
<del>
<ide> it('should $apply after success callback', function() {
<del> respond(200, '');
<add> $httpBackend.when('GET').then(200);
<add> $http({method: 'GET', url: '/some'});
<add> $httpBackend.flush();
<ide> expect(scope.$apply).toHaveBeenCalledOnce();
<ide> });
<ide>
<ide>
<ide> it('should $apply after error callback', function() {
<del> respond(404, '');
<add> $httpBackend.when('GET').then(404);
<add> $http({method: 'GET', url: '/some'});
<add> $httpBackend.flush();
<ide> expect(scope.$apply).toHaveBeenCalledOnce();
<ide> });
<ide>
<ide>
<ide> it('should $apply even if exception thrown during callback', function() {
<del> onSuccess.andThrow('error in callback');
<del> onError.andThrow('error in callback');
<del>
<del> respond(200, '');
<del> expect(scope.$apply).toHaveBeenCalledOnce();
<add> $httpBackend.when('GET').then(200);
<add> callback.andThrow('error in callback');
<ide>
<del> scope.$apply.reset();
<del> respond(400, '');
<add> $http({method: 'GET', url: '/some'}).on('200', callback);
<add> $httpBackend.flush();
<ide> expect(scope.$apply).toHaveBeenCalledOnce();
<ide>
<ide> $exceptionHandler.errors = [];
<ide> describe('$http', function() {
<ide> describe('default', function() {
<ide>
<ide> it('should transform object into json', function() {
<add> $httpBackend.expect('POST', '/url', '{"one":"two"}').respond('');
<ide> $http({method: 'POST', url: '/url', data: {one: 'two'}});
<del> expect(data).toBe('{"one":"two"}');
<ide> });
<ide>
<ide>
<ide> it('should ignore strings', function() {
<add> $httpBackend.expect('POST', '/url', 'string-data').respond('');
<ide> $http({method: 'POST', url: '/url', data: 'string-data'});
<del> expect(data).toBe('string-data');
<ide> });
<ide> });
<ide> });
<ide> describe('$http', function() {
<ide> describe('default', function() {
<ide>
<ide> it('should deserialize json objects', function() {
<del> doCommonXhr();
<del> respond(200, '{"foo":"bar","baz":23}');
<add> $httpBackend.expect('GET', '/url').respond('{"foo":"bar","baz":23}');
<add> $http({method: 'GET', url: '/url'}).on('200', callback);
<add> $httpBackend.flush();
<ide>
<del> expect(onSuccess.mostRecentCall.args[0]).toEqual({foo: 'bar', baz: 23});
<add> expect(callback).toHaveBeenCalledOnce();
<add> expect(callback.mostRecentCall.args[0]).toEqual({foo: 'bar', baz: 23});
<ide> });
<ide>
<ide>
<ide> it('should deserialize json arrays', function() {
<del> doCommonXhr();
<del> respond(200, '[1, "abc", {"foo":"bar"}]');
<add> $httpBackend.expect('GET', '/url').respond('[1, "abc", {"foo":"bar"}]');
<add> $http({method: 'GET', url: '/url'}).on('200', callback);
<add> $httpBackend.flush();
<ide>
<del> expect(onSuccess.mostRecentCall.args[0]).toEqual([1, 'abc', {foo: 'bar'}]);
<add> expect(callback).toHaveBeenCalledOnce();
<add> expect(callback.mostRecentCall.args[0]).toEqual([1, 'abc', {foo: 'bar'}]);
<ide> });
<ide>
<ide>
<ide> it('should deserialize json with security prefix', function() {
<del> doCommonXhr();
<del> respond(200, ')]}\',\n[1, "abc", {"foo":"bar"}]');
<add> $httpBackend.expect('GET', '/url').respond(')]}\',\n[1, "abc", {"foo":"bar"}]');
<add> $http({method: 'GET', url: '/url'}).on('200', callback);
<add> $httpBackend.flush();
<ide>
<del> expect(onSuccess.mostRecentCall.args[0]).toEqual([1, 'abc', {foo:'bar'}]);
<add> expect(callback).toHaveBeenCalledOnce();
<add> expect(callback.mostRecentCall.args[0]).toEqual([1, 'abc', {foo:'bar'}]);
<ide> });
<ide> });
<ide>
<add>
<ide> it('should pipeline more functions', function() {
<ide> function first(d) {return d + '1';}
<ide> function second(d) {return d + '2';}
<del> onSuccess = jasmine.createSpy('onSuccess');
<ide>
<del> $http({method: 'POST', url: '/url', data: '0', transformResponse: [first, second]})
<del> .on('200', onSuccess);
<add> $httpBackend.expect('POST', '/url').respond('0');
<add> $http({method: 'POST', url: '/url', transformResponse: [first, second]})
<add> .on('200', callback);
<add> $httpBackend.flush();
<ide>
<del> respond(200, '0');
<del> expect(onSuccess).toHaveBeenCalledOnce();
<del> expect(onSuccess.mostRecentCall.args[0]).toBe('012');
<add> expect(callback).toHaveBeenCalledOnce();
<add> expect(callback.mostRecentCall.args[0]).toBe('012');
<ide> });
<ide> });
<ide> });
<ide>
<ide>
<ide> describe('cache', function() {
<ide>
<del> function doFirstCacheRequest(method, responseStatus) {
<del> onSuccess = jasmine.createSpy('on200');
<del> $http({method: method || 'get', url: '/url', cache: true});
<del> respond(responseStatus || 200, 'content');
<del> $browser.xhr.reset();
<add> function doFirstCacheRequest(method, respStatus, headers) {
<add> $httpBackend.expect(method || 'GET', '/url').respond(respStatus || 200, 'content', headers);
<add> $http({method: method || 'GET', url: '/url', cache: true});
<add> $httpBackend.flush();
<ide> }
<ide>
<ide> it('should cache GET request', function() {
<ide> doFirstCacheRequest();
<ide>
<del> $http({method: 'get', url: '/url', cache: true}).on('200', onSuccess);
<add> $http({method: 'get', url: '/url', cache: true}).on('200', callback);
<ide> $browser.defer.flush();
<ide>
<del> expect(onSuccess).toHaveBeenCalledOnce();
<del> expect(onSuccess.mostRecentCall.args[0]).toBe('content');
<del> expect($browser.xhr).not.toHaveBeenCalled();
<add> expect(callback).toHaveBeenCalledOnce();
<add> expect(callback.mostRecentCall.args[0]).toBe('content');
<ide> });
<ide>
<ide>
<ide> it('should always call callback asynchronously', function() {
<ide> doFirstCacheRequest();
<add> $http({method: 'get', url: '/url', cache: true}).on('200', callback);
<ide>
<del> $http({method: 'get', url: '/url', cache: true}).on('200', onSuccess);
<del> expect(onSuccess).not.toHaveBeenCalled();
<add> expect(callback).not.toHaveBeenCalledOnce();
<ide> });
<ide>
<ide>
<ide> it('should not cache POST request', function() {
<del> doFirstCacheRequest('post');
<add> doFirstCacheRequest('POST');
<ide>
<del> $http({method: 'post', url: '/url', cache: true}).on('200', onSuccess);
<del> $browser.defer.flush();
<del> expect(onSuccess).not.toHaveBeenCalled();
<del> expect($browser.xhr).toHaveBeenCalledOnce();
<add> $httpBackend.expect('POST', '/url').respond('content2');
<add> $http({method: 'POST', url: '/url', cache: true}).on('200', callback);
<add> $httpBackend.flush();
<add>
<add> expect(callback).toHaveBeenCalledOnce();
<add> expect(callback.mostRecentCall.args[0]).toBe('content2');
<ide> });
<ide>
<ide>
<ide> it('should not cache PUT request', function() {
<del> doFirstCacheRequest('put');
<add> doFirstCacheRequest('PUT');
<ide>
<del> $http({method: 'put', url: '/url', cache: true}).on('200', onSuccess);
<del> $browser.defer.flush();
<del> expect(onSuccess).not.toHaveBeenCalled();
<del> expect($browser.xhr).toHaveBeenCalledOnce();
<add> $httpBackend.expect('PUT', '/url').respond('content2');
<add> $http({method: 'PUT', url: '/url', cache: true}).on('200', callback);
<add> $httpBackend.flush();
<add>
<add> expect(callback).toHaveBeenCalledOnce();
<add> expect(callback.mostRecentCall.args[0]).toBe('content2');
<ide> });
<ide>
<ide>
<ide> it('should not cache DELETE request', function() {
<del> doFirstCacheRequest('delete');
<add> doFirstCacheRequest('DELETE');
<ide>
<del> $http({method: 'delete', url: '/url', cache: true}).on('200', onSuccess);
<del> $browser.defer.flush();
<del> expect(onSuccess).not.toHaveBeenCalled();
<del> expect($browser.xhr).toHaveBeenCalledOnce();
<add> $httpBackend.expect('DELETE', '/url').respond(206);
<add> $http({method: 'DELETE', url: '/url', cache: true}).on('206', callback);
<add> $httpBackend.flush();
<add>
<add> expect(callback).toHaveBeenCalledOnce();
<ide> });
<ide>
<ide>
<ide> it('should not cache non 2xx responses', function() {
<del> doFirstCacheRequest('get', 404);
<add> doFirstCacheRequest('GET', 404);
<ide>
<del> $http({method: 'get', url: '/url', cache: true}).on('200', onSuccess);
<del> $browser.defer.flush();
<del> expect(onSuccess).not.toHaveBeenCalled();
<del> expect($browser.xhr).toHaveBeenCalledOnce();
<add> $httpBackend.expect('GET', '/url').respond('content2');
<add> $http({method: 'GET', url: '/url', cache: true}).on('200', callback);
<add> $httpBackend.flush();
<add>
<add> expect(callback).toHaveBeenCalledOnce();
<add> expect(callback.mostRecentCall.args[0]).toBe('content2');
<ide> });
<ide>
<ide>
<ide> it('should cache the headers as well', function() {
<del> doFirstCacheRequest();
<del> onSuccess.andCallFake(function(r, s, headers) {
<add> doFirstCacheRequest('GET', 200, {'content-encoding': 'gzip', 'server': 'Apache'});
<add> callback.andCallFake(function(r, s, headers) {
<ide> expect(headers()).toEqual({'content-encoding': 'gzip', 'server': 'Apache'});
<ide> expect(headers('server')).toBe('Apache');
<ide> });
<ide>
<del> $http({method: 'get', url: '/url', cache: true}).on('200', onSuccess);
<add> $http({method: 'GET', url: '/url', cache: true}).on('200', callback);
<ide> $browser.defer.flush();
<del> expect(onSuccess).toHaveBeenCalledOnce();
<add> expect(callback).toHaveBeenCalledOnce();
<ide> });
<ide>
<ide>
<ide> it('should cache status code as well', function() {
<del> doFirstCacheRequest('get', 201);
<del> onSuccess.andCallFake(function(r, status, h) {
<add> doFirstCacheRequest('GET', 201);
<add> callback.andCallFake(function(r, status, h) {
<ide> expect(status).toBe(201);
<ide> });
<ide>
<del> $http({method: 'get', url: '/url', cache: true}).on('2xx', onSuccess);
<add> $http({method: 'get', url: '/url', cache: true}).on('2xx', callback);
<ide> $browser.defer.flush();
<del> expect(onSuccess).toHaveBeenCalledOnce();
<add> expect(callback).toHaveBeenCalledOnce();
<ide> });
<ide> });
<ide>
<ide>
<ide> describe('pendingCount', function() {
<ide>
<ide> it('should return number of pending requests', function() {
<add> $httpBackend.when('GET').then(200);
<ide> expect($http.pendingCount()).toBe(0);
<ide>
<ide> $http({method: 'get', url: '/some'});
<ide> expect($http.pendingCount()).toBe(1);
<ide>
<del> respond(200, '');
<add> $httpBackend.flush();
<ide> expect($http.pendingCount()).toBe(0);
<ide> });
<ide>
<ide>
<ide> it('should decrement the counter when request aborted', function() {
<add> $httpBackend.when('GET').then(0);
<ide> future = $http({method: 'get', url: '/x'});
<ide> expect($http.pendingCount()).toBe(1);
<add>
<ide> future.abort();
<del> respond(0, '');
<add> $httpBackend.flush();
<ide>
<ide> expect($http.pendingCount()).toBe(0);
<ide> });
<ide>
<ide>
<ide> it('should decrement the counter when served from cache', function() {
<add> $httpBackend.when('GET').then(200);
<add>
<ide> $http({method: 'get', url: '/cached', cache: true});
<del> respond(200, 'content');
<add> $httpBackend.flush();
<ide> expect($http.pendingCount()).toBe(0);
<ide>
<ide> $http({method: 'get', url: '/cached', cache: true});
<ide> describe('$http', function() {
<ide>
<ide>
<ide> it('should decrement the counter before firing callbacks', function() {
<del> $http({method: 'get', url: '/cached'}).on('xxx', function() {
<add> $httpBackend.when('GET').then(200);
<add> $http({method: 'get', url: '/url'}).on('xxx', function() {
<ide> expect($http.pendingCount()).toBe(0);
<ide> });
<ide>
<ide> expect($http.pendingCount()).toBe(1);
<del> respond(200, 'content');
<add> $httpBackend.flush();
<ide> });
<ide> });
<ide> });
<ide><path>test/widgetsSpec.js
<ide> describe("widget", function() {
<ide> expect($rootScope.$$childHead).toBeFalsy();
<ide> }));
<ide>
<del> it('should do xhr request and cache it', inject(function($rootScope, $browser, $compile) {
<add> it('should do xhr request and cache it', inject(function($rootScope, $httpBackend, $compile) {
<ide> var element = $compile('<ng:include src="url"></ng:include>')($rootScope);
<del> var $browserXhr = $browser.xhr;
<del> $browserXhr.expectGET('myUrl').respond('my partial');
<add> $httpBackend.expect('GET', 'myUrl').respond('my partial');
<ide>
<ide> $rootScope.url = 'myUrl';
<ide> $rootScope.$digest();
<del> $browserXhr.flush();
<add> $httpBackend.flush();
<ide> expect(element.text()).toEqual('my partial');
<ide>
<ide> $rootScope.url = null;
<ide> describe("widget", function() {
<ide> }));
<ide>
<ide> it('should clear content when error during xhr request',
<del> inject(function($browser, $compile, $rootScope) {
<add> inject(function($httpBackend, $compile, $rootScope) {
<ide> var element = $compile('<ng:include src="url">content</ng:include>')($rootScope);
<del> var $browserXhr = $browser.xhr;
<del> $browserXhr.expectGET('myUrl').respond(404, '');
<add> $httpBackend.expect('GET', 'myUrl').respond(404, '');
<ide>
<ide> $rootScope.url = 'myUrl';
<ide> $rootScope.$digest();
<del> $browserXhr.flush();
<add> $httpBackend.flush();
<ide>
<ide> expect(element.text()).toBe('');
<ide> }));
<ide> describe("widget", function() {
<ide>
<ide>
<ide> it('should load content via xhr when route changes',
<del> inject(function($rootScope, $compile, $browser, $location, $route) {
<add> inject(function($rootScope, $compile, $httpBackend, $location, $route) {
<ide> $route.when('/foo', {template: 'myUrl1'});
<ide> $route.when('/bar', {template: 'myUrl2'});
<ide>
<ide> expect(element.text()).toEqual('');
<ide>
<ide> $location.path('/foo');
<del> $browser.xhr.expectGET('myUrl1').respond('<div>{{1+3}}</div>');
<add> $httpBackend.expect('GET', 'myUrl1').respond('<div>{{1+3}}</div>');
<ide> $rootScope.$digest();
<del> $browser.xhr.flush();
<add> $httpBackend.flush();
<ide> expect(element.text()).toEqual('4');
<ide>
<ide> $location.path('/bar');
<del> $browser.xhr.expectGET('myUrl2').respond('angular is da best');
<add> $httpBackend.expect('GET', 'myUrl2').respond('angular is da best');
<ide> $rootScope.$digest();
<del> $browser.xhr.flush();
<add> $httpBackend.flush();
<ide> expect(element.text()).toEqual('angular is da best');
<ide> }));
<ide>
<ide> it('should remove all content when location changes to an unknown route',
<del> inject(function($rootScope, $compile, $location, $browser, $route) {
<add> inject(function($rootScope, $compile, $location, $httpBackend, $route) {
<ide> $route.when('/foo', {template: 'myUrl1'});
<ide>
<ide> $location.path('/foo');
<del> $browser.xhr.expectGET('myUrl1').respond('<div>{{1+3}}</div>');
<add> $httpBackend.expect('GET', 'myUrl1').respond('<div>{{1+3}}</div>');
<ide> $rootScope.$digest();
<del> $browser.xhr.flush();
<add> $httpBackend.flush();
<ide> expect(element.text()).toEqual('4');
<ide>
<ide> $location.path('/unknown');
<ide> describe("widget", function() {
<ide> }));
<ide>
<ide> it('should chain scopes and propagate evals to the child scope',
<del> inject(function($rootScope, $compile, $location, $browser, $route) {
<add> inject(function($rootScope, $compile, $location, $httpBackend, $route) {
<ide> $route.when('/foo', {template: 'myUrl1'});
<ide> $rootScope.parentVar = 'parent';
<ide>
<ide> $location.path('/foo');
<del> $browser.xhr.expectGET('myUrl1').respond('<div>{{parentVar}}</div>');
<add> $httpBackend.expect('GET', 'myUrl1').respond('<div>{{parentVar}}</div>');
<ide> $rootScope.$digest();
<del> $browser.xhr.flush();
<add> $httpBackend.flush();
<ide> expect(element.text()).toEqual('parent');
<ide>
<ide> $rootScope.parentVar = 'new parent';
<ide> describe("widget", function() {
<ide> }));
<ide>
<ide> it('should be possible to nest ng:view in ng:include', inject(function() {
<add> // TODO(vojta): refactor this test
<ide> var injector = angular.injector('ng', 'ngMock');
<ide> var myApp = injector.get('$rootScope');
<del> var $browser = injector.get('$browser');
<del> $browser.xhr.expectGET('includePartial.html').respond('view: <ng:view></ng:view>');
<add> var $httpBackend = injector.get('$httpBackend');
<add> $httpBackend.expect('GET', 'includePartial.html').respond('view: <ng:view></ng:view>');
<ide> injector.get('$location').path('/foo');
<ide>
<ide> var $route = injector.get('$route');
<ide> describe("widget", function() {
<ide> '</div>')(myApp);
<ide> myApp.$apply();
<ide>
<del> $browser.xhr.expectGET('viewPartial.html').respond('content');
<add> $httpBackend.expect('GET', 'viewPartial.html').respond('content');
<add> $httpBackend.flush();
<ide> myApp.$digest();
<del> $browser.xhr.flush();
<add> $httpBackend.flush();
<ide>
<ide> expect(myApp.$element.text()).toEqual('include: view: content');
<ide> expect($route.current.template).toEqual('viewPartial.html');
<ide> dealoc(myApp);
<ide> }));
<ide>
<ide> it('should initialize view template after the view controller was initialized even when ' +
<del> 'templates were cached', inject(function($rootScope, $compile, $location, $browser, $route) {
<add> 'templates were cached', inject(function($rootScope, $compile, $location, $httpBackend, $route) {
<ide> //this is a test for a regression that was introduced by making the ng:view cache sync
<ide>
<ide> $route.when('/foo', {controller: ParentCtrl, template: 'viewPartial.html'});
<del>
<ide> $rootScope.log = [];
<ide>
<ide> function ParentCtrl() {
<ide> describe("widget", function() {
<ide> };
<ide>
<ide> $location.path('/foo');
<del> $browser.xhr.expectGET('viewPartial.html').
<add> $httpBackend.expect('GET', 'viewPartial.html').
<ide> respond('<div ng:init="log.push(\'init\')">' +
<ide> '<div ng:controller="ChildCtrl"></div>' +
<ide> '</div>');
<ide> $rootScope.$apply();
<del> $browser.xhr.flush();
<add> $httpBackend.flush();
<ide>
<ide> expect($rootScope.log).toEqual(['parent', 'init', 'child']);
<ide>
<ide> describe("widget", function() {
<ide> $rootScope.log = [];
<ide> $location.path('/foo');
<ide> $rootScope.$apply();
<del> $browser.defer.flush();
<ide>
<ide> expect($rootScope.log).toEqual(['parent', 'init', 'child']);
<ide> }));
<ide>
<ide> it('should discard pending xhr callbacks if a new route is requested before the current ' +
<del> 'finished loading', inject(function($route, $rootScope, $location, $browser) {
<add> 'finished loading', inject(function($route, $rootScope, $location, $httpBackend) {
<ide> // this is a test for a bad race condition that affected feedback
<ide>
<ide> $route.when('/foo', {template: 'myUrl1'});
<ide> describe("widget", function() {
<ide> expect($rootScope.$element.text()).toEqual('');
<ide>
<ide> $location.path('/foo');
<del> $browser.xhr.expectGET('myUrl1').respond('<div>{{1+3}}</div>');
<add> $httpBackend.expect('GET', 'myUrl1').respond('<div>{{1+3}}</div>');
<ide> $rootScope.$digest();
<ide> $location.path('/bar');
<del> $browser.xhr.expectGET('myUrl2').respond('<div>{{1+1}}</div>');
<add> $httpBackend.expect('GET', 'myUrl2').respond('<div>{{1+1}}</div>');
<ide> $rootScope.$digest();
<del> $browser.xhr.flush(); // now that we have to requests pending, flush!
<add> $httpBackend.flush(); // now that we have to requests pending, flush!
<ide>
<ide> expect($rootScope.$element.text()).toEqual('2');
<ide> }));
<ide>
<ide> it('should clear the content when error during xhr request',
<del> inject(function($route, $location, $rootScope, $browser) {
<add> inject(function($route, $location, $rootScope, $httpBackend) {
<ide> $route.when('/foo', {controller: noop, template: 'myUrl1'});
<ide>
<ide> $location.path('/foo');
<del> $browser.xhr.expectGET('myUrl1').respond(404, '');
<add> $httpBackend.expect('GET', 'myUrl1').respond(404, '');
<ide> $rootScope.$element.text('content');
<ide>
<ide> $rootScope.$digest();
<del> $browser.xhr.flush();
<add> $httpBackend.flush();
<ide>
<ide> expect($rootScope.$element.text()).toBe('');
<ide> })); | 8 |
Text | Text | add docs link to to_internal_value() | ffde1691025761c97927f9f4bbd5a9f3ec9ea96e | <ide><path>docs/api-guide/relations.md
<ide> output representation should be generated from the model instance.
<ide>
<ide> To implement a custom relational field, you should override `RelatedField`, and implement the `.to_representation(self, value)` method. This method takes the target of the field as the `value` argument, and should return the representation that should be used to serialize the target. The `value` argument will typically be a model instance.
<ide>
<del>If you want to implement a read-write relational field, you must also implement the `.to_internal_value(self, data)` method.
<add>If you want to implement a read-write relational field, you must also implement the [`.to_internal_value(self, data)` method][to_internal_value].
<ide>
<ide> To provide a dynamic queryset based on the `context`, you can also override `.get_queryset(self)` instead of specifying `.queryset` on the class or when initializing the field.
<ide>
<ide> The [rest-framework-generic-relations][drf-nested-relations] library provides re
<ide> [drf-nested-relations]: https://github.com/Ian-Foote/rest-framework-generic-relations
<ide> [django-intermediary-manytomany]: https://docs.djangoproject.com/en/2.2/topics/db/models/#intermediary-manytomany
<ide> [dealing-with-nested-objects]: https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects
<add>[to_internal_value]: https://www.django-rest-framework.org/api-guide/serializers/#to_internal_valueself-data | 1 |
Python | Python | add some docstrings in optimizers | 59e67fd049252fe1d9194071ed38e81f9fbc2dcf | <ide><path>keras/optimizers.py
<ide> def serialize(optimizer):
<ide>
<ide>
<ide> def deserialize(config, custom_objects=None):
<add> """Inverse of the `serialize` function.
<add>
<add> # Arguments
<add> config: Optimizer configuration dictionary.
<add> custom_objects: Optional dictionary mapping
<add> names (strings) to custom objects
<add> (classes and functions)
<add> to be considered during deserialization.
<add>
<add> # Returns
<add> A Keras Optimizer instance.
<add> """
<ide> all_classes = {
<ide> 'sgd': SGD,
<ide> 'rmsprop': RMSprop,
<ide> def deserialize(config, custom_objects=None):
<ide>
<ide>
<ide> def get(identifier):
<add> """Retrieves a Keras Optimizer instance.
<add>
<add> # Arguments
<add> identifier: Optimizer identifier, one of
<add> - String: name of an optimizer
<add> - Dictionary: configuration dictionary.
<add> - Keras Optimizer instance (it will be returned unchanged).
<add> - TensorFlow Optimizer instance
<add> (it will be wrapped as a Keras Optimizer).
<add>
<add> # Returns
<add> A Keras Optimizer instance.
<add> """
<ide> if K.backend() == 'tensorflow':
<ide> # Wrap TF optimizer instances
<ide> if isinstance(identifier, tf.train.Optimizer): | 1 |
Text | Text | fix example of parsing request.url | fff75645e9e9793397d89327c1bed87795ccb9b0 | <ide><path>doc/api/http.md
<ide> When `request.url` is `'/status?name=ryan'` and
<ide>
<ide> ```console
<ide> $ node
<del>> new URL(request.url, request.headers.host)
<add>> new URL(request.url, `http://${request.headers.host}`)
<ide> URL {
<ide> href: 'http://localhost:3000/status?name=ryan',
<ide> origin: 'http://localhost:3000', | 1 |
Text | Text | update links to api documentation & add a todo | 90d780c027e4f5d55d21d068f5b3c6310eaf3931 | <ide><path>guides/source/action_view_overview.md
<ide> TODO...
<ide> Overview of all the helpers provided by Action View
<ide> ---------------------------------------------------
<ide>
<del>The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the API Documentation, which covers all of the helpers in more detail, but this should serve as a good starting point.
<add>The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the [API Documentation](http://api.rubyonrails.org/classes/ActionView/Helpers.html), which covers all of the helpers in more detail, but this should serve as a good starting point.
<ide>
<ide> ### ActiveRecordHelper
<add>TODO: Is it me or there's no ActiveRecordHelper? *Agis-*
<ide>
<del>The Active Record Helper makes it easier to create forms for records kept in instance variables. You may also want to review the [Rails Form helpers guide](form_helpers.html).
<add>The Active Record Helper makes it easier to create forms for records kept in instance variables. You may also want to review the [Rails Form helpers guide](http://guides.rubyonrails.org/form_helpers.html).
<ide>
<ide> #### error_message_on
<ide> | 1 |
Python | Python | make numpy._array_api.array.device return "cpu" | 3cab20ee117d39c74abd2a28f142529e379844b1 | <ide><path>numpy/_array_api/_array_object.py
<ide> def dtype(self) -> Dtype:
<ide>
<ide> @property
<ide> def device(self) -> Device:
<del> """
<del> Array API compatible wrapper for :py:meth:`np.ndaray.device <numpy.ndarray.device>`.
<del>
<del> See its docstring for more information.
<del> """
<del> # Note: device support is required for this
<del> raise NotImplementedError("The device attribute is not yet implemented")
<add> return 'cpu'
<ide>
<ide> @property
<ide> def ndim(self) -> int: | 1 |
Javascript | Javascript | make debugging of inspector-port-zero easier | 5c7b1ecbceeb32d947bea31c1256b1a9a42b8cba | <ide><path>test/sequential/test-inspector-port-zero.js
<ide> function test(arg, port = '') {
<ide> };
<ide> proc.stdout.on('close', mustCall(() => onclose()));
<ide> proc.stderr.on('close', mustCall(() => onclose()));
<del> proc.on('exit', mustCall((exitCode) => assert.strictEqual(exitCode, 0)));
<add> proc.on('exit', mustCall((exitCode, signal) => assert.strictEqual(
<add> exitCode,
<add> 0,
<add> `exitCode: ${exitCode}, signal: ${signal}`)));
<ide> }
<ide> }
<ide> | 1 |
Mixed | Python | add missing pronoums/determiners | 28db7dd5d9aaf53a3c4e9b13048415502d998aae | <ide><path>.github/contributors/jonesmartins.md
<add># spaCy contributor agreement
<add>
<add>This spaCy Contributor Agreement (**"SCA"**) is based on the
<add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf).
<add>The SCA applies to any contribution that you make to any product or project
<add>managed by us (the **"project"**), and sets out the intellectual property rights
<add>you grant to us in the contributed materials. The term **"us"** shall mean
<add>[ExplosionAI GmbH](https://explosion.ai/legal). The term
<add>**"you"** shall mean the person or entity identified below.
<add>
<add>If you agree to be bound by these terms, fill in the information requested
<add>below and include the filled-in version with your first pull request, under the
<add>folder [`.github/contributors/`](/.github/contributors/). The name of the file
<add>should be your GitHub username, with the extension `.md`. For example, the user
<add>example_user would create the file `.github/contributors/example_user.md`.
<add>
<add>Read this agreement carefully before signing. These terms and conditions
<add>constitute a binding legal agreement.
<add>
<add>## Contributor Agreement
<add>
<add>1. The term "contribution" or "contributed materials" means any source code,
<add>object code, patch, tool, sample, graphic, specification, manual,
<add>documentation, or any other material posted or submitted by you to the project.
<add>
<add>2. With respect to any worldwide copyrights, or copyright applications and
<add>registrations, in your contribution:
<add>
<add> * you hereby assign to us joint ownership, and to the extent that such
<add> assignment is or becomes invalid, ineffective or unenforceable, you hereby
<add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge,
<add> royalty-free, unrestricted license to exercise all rights under those
<add> copyrights. This includes, at our option, the right to sublicense these same
<add> rights to third parties through multiple levels of sublicensees or other
<add> licensing arrangements;
<add>
<add> * you agree that each of us can do all things in relation to your
<add> contribution as if each of us were the sole owners, and if one of us makes
<add> a derivative work of your contribution, the one who makes the derivative
<add> work (or has it made will be the sole owner of that derivative work;
<add>
<add> * you agree that you will not assert any moral rights in your contribution
<add> against us, our licensees or transferees;
<add>
<add> * you agree that we may register a copyright in your contribution and
<add> exercise all ownership rights associated with it; and
<add>
<add> * you agree that neither of us has any duty to consult with, obtain the
<add> consent of, pay or render an accounting to the other for any use or
<add> distribution of your contribution.
<add>
<add>3. With respect to any patents you own, or that you can license without payment
<add>to any third party, you hereby grant to us a perpetual, irrevocable,
<add>non-exclusive, worldwide, no-charge, royalty-free license to:
<add>
<add> * make, have made, use, sell, offer to sell, import, and otherwise transfer
<add> your contribution in whole or in part, alone or in combination with or
<add> included in any product, work or materials arising out of the project to
<add> which your contribution was submitted, and
<add>
<add> * at our option, to sublicense these same rights to third parties through
<add> multiple levels of sublicensees or other licensing arrangements.
<add>
<add>4. Except as set out above, you keep all right, title, and interest in your
<add>contribution. The rights that you grant to us under these terms are effective
<add>on the date you first submitted a contribution to us, even if your submission
<add>took place before the date you sign these terms.
<add>
<add>5. You covenant, represent, warrant and agree that:
<add>
<add> * Each contribution that you submit is and shall be an original work of
<add> authorship and you can legally grant the rights set out in this SCA;
<add>
<add> * to the best of your knowledge, each contribution will not violate any
<add> third party's copyrights, trademarks, patents, or other intellectual
<add> property rights; and
<add>
<add> * each contribution shall be in compliance with U.S. export control laws and
<add> other applicable export and import laws. You agree to notify us if you
<add> become aware of any circumstance which would make any of the foregoing
<add> representations inaccurate in any respect. We may publicly disclose your
<add> participation in the project, including the fact that you have signed the SCA.
<add>
<add>6. This SCA is governed by the laws of the State of California and applicable
<add>U.S. Federal law. Any choice of law rules will not apply.
<add>
<add>7. Please place an βxβ on one of the applicable statement below. Please do NOT
<add>mark both statements:
<add>
<add> * [x] I am signing on behalf of myself as an individual and no other person
<add> or entity, including my employer, has or will have rights with respect to my
<add> contributions.
<add>
<add> * [ ] I am signing on behalf of my employer or a legal entity and I have the
<add> actual authority to contractually bind that entity.
<add>
<add>## Contributor Details
<add>
<add>| Field | Entry |
<add>|------------------------------- | -------------------- |
<add>| Name | Jones Martins |
<add>| Company name (if applicable) | |
<add>| Title or role (if applicable) | |
<add>| Date | 2020-06-10 |
<add>| GitHub username | jonesmartins |
<add>| Website (optional) | |
<ide><path>spacy/lang/en/tokenizer_exceptions.py
<ide>
<ide> # W-words, relative pronouns, prepositions etc.
<ide>
<del>for word in ["who", "what", "when", "where", "why", "how", "there", "that"]:
<add>for word in ["who", "what", "when", "where", "why", "how", "there", "that", "this", "these", "those"]:
<ide> for orth in [word, word.title()]:
<ide> _exc[orth + "'s"] = [
<ide> {ORTH: orth, LEMMA: word, NORM: word},
<ide><path>spacy/tests/lang/en/test_exceptions.py
<ide> def test_en_tokenizer_doesnt_split_apos_exc(en_tokenizer, text):
<ide> assert tokens[0].text == text
<ide>
<ide>
<del>@pytest.mark.parametrize("text", ["we'll", "You'll", "there'll"])
<add>@pytest.mark.parametrize("text", ["we'll", "You'll", "there'll", "this'll", "those'll"])
<ide> def test_en_tokenizer_handles_ll_contraction(en_tokenizer, text):
<ide> tokens = en_tokenizer(text)
<ide> assert len(tokens) == 2 | 3 |
Python | Python | append host info in network.extra for kvm | 40faf235d48c6d9fef7d1d50be87229dece648a5 | <ide><path>libcloud/compute/drivers/libvirt_driver.py
<ide> def ex_list_networks(self):
<ide> networks = []
<ide> try:
<ide> for net in self.connection.listAllNetworks():
<del> extra = {'bridge': net.bridgeName(), 'xml': net.XMLDesc()}
<add> extra = {'bridge': net.bridgeName(), 'xml': net.XMLDesc(), 'host': self.host}
<ide> networks.append(Network(net.UUIDString(), net.name(), extra))
<ide> except:
<ide> pass # Not supported by all hypervisors. | 1 |
Python | Python | add test for vector resizing, re issue #544 | e7af75e0a91a8d0f2eb2e3c5a3e680750d4324c0 | <ide><path>spacy/tests/vocab/test_add_vectors.py
<add>import numpy
<add>
<add>import spacy.en
<add>
<add>
<add>def test_add_vector():
<add> vocab = spacy.en.English.Defaults.create_vocab()
<add> vocab.resize_vectors(10)
<add> lex = vocab[u'Hello']
<add> lex.vector = numpy.ndarray((10,), dtype='float32')
<add> lex = vocab[u'Hello']
<add> assert lex.vector.shape == (10,) | 1 |
Ruby | Ruby | use array.wrap instead of using ternary | e12810178cebc0c40a90b4aba3976537852b71b4 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def initialize_schema_migrations_table
<ide> end
<ide>
<ide> def assume_migrated_upto_version(version, migrations_paths = ActiveRecord::Migrator.migrations_paths)
<del> migrations_paths = [migrations_paths] unless migrations_paths.kind_of?(Array)
<add> migrations_paths = Array.wrap(migrations_paths)
<ide> version = version.to_i
<ide> sm_table = quote_table_name(ActiveRecord::Migrator.schema_migrations_table_name)
<ide>
<ide><path>activerecord/lib/active_record/migration.rb
<ide> def proper_table_name(name)
<ide> def migrations_paths
<ide> @migrations_paths ||= ['db/migrate']
<ide> # just to not break things if someone uses: migration_path = some_string
<del> @migrations_paths.kind_of?(Array) ? @migrations_paths : [@migrations_paths]
<add> Array.wrap(@migrations_paths)
<ide> end
<ide>
<ide> def migrations_path
<ide> migrations_paths.first
<ide> end
<ide>
<ide> def migrations(paths)
<del> paths = [paths] unless paths.kind_of?(Array)
<add> paths = Array.wrap(paths)
<ide>
<ide> files = Dir[*paths.map { |p| "#{p}/[0-9]*_*.rb" }]
<ide> | 2 |
Ruby | Ruby | fix a typo | fb7ce8c4847bc6bacd8b6f3fb684332228847df7 | <ide><path>Library/Contributions/example-formula.rb
<ide> def install
<ide> # patch you have to resort to `inreplace`, because in the patch
<ide> # you don't have access to any var defined by the formula. Only
<ide> # HOMEBREW_PREFIX is available in the embedded patch.
<del> # inreplace supports reg. exes.
<add> # inreplace supports regular expressions.
<ide> inreplace "somefile.cfg", /look[for]what?/, "replace by #{bin}/tool"
<ide>
<ide> # To call out to the system, we use the `system` method and we prefer | 1 |
Python | Python | make files in numpy/lib pep8 compliant | 01b0d7e82211b581aaff925e3ccc36cff9ac1895 | <ide><path>numpy/lib/_datasource.py
<ide> """A file interface for handling local and remote data files.
<del>The goal of datasource is to abstract some of the file system operations when
<del>dealing with data files so the researcher doesn't have to know all the
<add>
<add>The goal of datasource is to abstract some of the file system operations
<add>when dealing with data files so the researcher doesn't have to know all the
<ide> low-level details. Through datasource, a researcher can obtain and use a
<ide> file with one function call, regardless of location of the file.
<ide>
<ide> DataSource is meant to augment standard python libraries, not replace them.
<del>It should work seemlessly with standard file IO operations and the os module.
<add>It should work seemlessly with standard file IO operations and the os
<add>module.
<ide>
<ide> DataSource files can originate locally or remotely:
<ide>
<ide> - local files : '/home/guido/src/local/data.txt'
<ide> - URLs (http, ftp, ...) : 'http://www.scipy.org/not/real/data.txt'
<ide>
<del>DataSource files can also be compressed or uncompressed. Currently only gzip
<del>and bz2 are supported.
<add>DataSource files can also be compressed or uncompressed. Currently only
<add>gzip and bz2 are supported.
<ide>
<ide> Example::
<ide>
<ide> class _FileOpeners(object):
<ide> Container for different methods to open (un-)compressed files.
<ide>
<ide> `_FileOpeners` contains a dictionary that holds one method for each
<del> supported file format. Attribute lookup is implemented in such a way that
<del> an instance of `_FileOpeners` itself can be indexed with the keys of that
<del> dictionary. Currently uncompressed files as well as files
<add> supported file format. Attribute lookup is implemented in such a way
<add> that an instance of `_FileOpeners` itself can be indexed with the keys
<add> of that dictionary. Currently uncompressed files as well as files
<ide> compressed with ``gzip`` or ``bz2`` compression are supported.
<ide>
<ide> Notes
<ide> class _FileOpeners(object):
<ide> True
<ide>
<ide> """
<add>
<ide> def __init__(self):
<ide> self._loaded = False
<ide> self._file_openers = {None: open}
<add>
<ide> def _load(self):
<ide> if self._loaded:
<ide> return
<ide> def keys(self):
<ide> """
<ide> self._load()
<ide> return list(self._file_openers.keys())
<add>
<ide> def __getitem__(self, key):
<ide> self._load()
<ide> return self._file_openers[key]
<ide> def open(path, mode='r', destpath=os.curdir):
<ide> """
<ide> Open `path` with `mode` and return the file object.
<ide>
<del> If ``path`` is an URL, it will be downloaded, stored in the `DataSource`
<del> `destpath` directory and opened from there.
<add> If ``path`` is an URL, it will be downloaded, stored in the
<add> `DataSource` `destpath` directory and opened from there.
<ide>
<ide> Parameters
<ide> ----------
<ide> path : str
<ide> Local file path or URL to open.
<ide> mode : str, optional
<ide> Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to
<del> append. Available modes depend on the type of object specified by path.
<del> Default is 'r'.
<add> append. Available modes depend on the type of object specified by
<add> path. Default is 'r'.
<ide> destpath : str, optional
<del> Path to the directory where the source file gets downloaded to for use.
<del> If `destpath` is None, a temporary directory will be created. The
<del> default path is the current directory.
<add> Path to the directory where the source file gets downloaded to for
<add> use. If `destpath` is None, a temporary directory will be created.
<add> The default path is the current directory.
<ide>
<ide> Returns
<ide> -------
<ide> class DataSource (object):
<ide> A generic data source file (file, http, ftp, ...).
<ide>
<ide> DataSources can be local files or remote files/URLs. The files may
<del> also be compressed or uncompressed. DataSource hides some of the low-level
<del> details of downloading the file, allowing you to simply pass in a valid
<del> file path (or URL) and obtain a file object.
<add> also be compressed or uncompressed. DataSource hides some of the
<add> low-level details of downloading the file, allowing you to simply pass
<add> in a valid file path (or URL) and obtain a file object.
<ide>
<ide> Parameters
<ide> ----------
<ide> destpath : str or None, optional
<del> Path to the directory where the source file gets downloaded to for use.
<del> If `destpath` is None, a temporary directory will be created.
<add> Path to the directory where the source file gets downloaded to for
<add> use. If `destpath` is None, a temporary directory will be created.
<ide> The default path is the current directory.
<ide>
<ide> Notes
<ide> def __init__(self, destpath=os.curdir):
<ide> self._destpath = os.path.abspath(destpath)
<ide> self._istmpdest = False
<ide> else:
<del> import tempfile # deferring import to improve startup time
<add> import tempfile # deferring import to improve startup time
<ide> self._destpath = tempfile.mkdtemp()
<ide> self._istmpdest = True
<ide>
<ide> def __del__(self):
<ide>
<ide> def _iszip(self, filename):
<ide> """Test if the filename is a zip file by looking at the file extension.
<add>
<ide> """
<ide> fname, ext = os.path.splitext(filename)
<ide> return ext in _file_openers.keys()
<ide> def _cache(self, path):
<ide> def _findfile(self, path):
<ide> """Searches for ``path`` and returns full path if found.
<ide>
<del> If path is an URL, _findfile will cache a local copy and return
<del> the path to the cached file.
<del> If path is a local file, _findfile will return a path to that local
<del> file.
<add> If path is an URL, _findfile will cache a local copy and return the
<add> path to the cached file. If path is a local file, _findfile will
<add> return a path to that local file.
<ide>
<del> The search will include possible compressed versions of the file and
<del> return the first occurence found.
<add> The search will include possible compressed versions of the file
<add> and return the first occurence found.
<ide>
<ide> """
<ide>
<ide> def _sanitize_relative_path(self, path):
<ide> # Note: os.path.join treats '/' as os.sep on Windows
<ide> path = path.lstrip(os.sep).lstrip('/')
<ide> path = path.lstrip(os.pardir).lstrip('..')
<del> drive, path = os.path.splitdrive(path) # for Windows
<add> drive, path = os.path.splitdrive(path) # for Windows
<ide> return path
<ide>
<ide> def exists(self, path):
<ide> def exists(self, path):
<ide> - a local file.
<ide> - a remote URL that has been downloaded and stored locally in the
<ide> `DataSource` directory.
<del> - a remote URL that has not been downloaded, but is valid and accessible.
<add> - a remote URL that has not been downloaded, but is valid and
<add> accessible.
<ide>
<ide> Parameters
<ide> ----------
<ide> def exists(self, path):
<ide>
<ide> Notes
<ide> -----
<del> When `path` is an URL, `exists` will return True if it's either stored
<del> locally in the `DataSource` directory, or is a valid remote URL.
<del> `DataSource` does not discriminate between the two, the file is accessible
<del> if it exists in either location.
<add> When `path` is an URL, `exists` will return True if it's either
<add> stored locally in the `DataSource` directory, or is a valid remote
<add> URL. `DataSource` does not discriminate between the two, the file
<add> is accessible if it exists in either location.
<ide>
<ide> """
<ide> # We import this here because importing urllib2 is slow and
<ide> def open(self, path, mode='r'):
<ide> """
<ide> Open and return file-like object.
<ide>
<del> If `path` is an URL, it will be downloaded, stored in the `DataSource`
<del> directory and opened from there.
<add> If `path` is an URL, it will be downloaded, stored in the
<add> `DataSource` directory and opened from there.
<ide>
<ide> Parameters
<ide> ----------
<ide> path : str
<ide> Local file path or URL to open.
<ide> mode : {'r', 'w', 'a'}, optional
<del> Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to
<del> append. Available modes depend on the type of object specified by
<del> `path`. Default is 'r'.
<add> Mode to open `path`. Mode 'r' for reading, 'w' for writing,
<add> 'a' to append. Available modes depend on the type of object
<add> specified by `path`. Default is 'r'.
<ide>
<ide> Returns
<ide> -------
<ide> class Repository (DataSource):
<ide> """
<ide> Repository(baseurl, destpath='.')
<ide>
<del> A data repository where multiple DataSource's share a base URL/directory.
<add> A data repository where multiple DataSource's share a base
<add> URL/directory.
<ide>
<del> `Repository` extends `DataSource` by prepending a base URL (or directory)
<del> to all the files it handles. Use `Repository` when you will be working
<del> with multiple files from one base URL. Initialize `Repository` with the
<del> base URL, then refer to each file by its filename only.
<add> `Repository` extends `DataSource` by prepending a base URL (or
<add> directory) to all the files it handles. Use `Repository` when you will
<add> be working with multiple files from one base URL. Initialize
<add> `Repository` with the base URL, then refer to each file by its filename
<add> only.
<ide>
<ide> Parameters
<ide> ----------
<ide> baseurl : str
<ide> Path to the local directory or remote location that contains the
<ide> data files.
<ide> destpath : str or None, optional
<del> Path to the directory where the source file gets downloaded to for use.
<del> If `destpath` is None, a temporary directory will be created.
<add> Path to the directory where the source file gets downloaded to for
<add> use. If `destpath` is None, a temporary directory will be created.
<ide> The default path is the current directory.
<ide>
<ide> Examples
<ide> def abspath(self, path):
<ide> Parameters
<ide> ----------
<ide> path : str
<del> Can be a local file or a remote URL. This may, but does not have
<del> to, include the `baseurl` with which the `Repository` was initialized.
<add> Can be a local file or a remote URL. This may, but does not
<add> have to, include the `baseurl` with which the `Repository` was
<add> initialized.
<ide>
<ide> Returns
<ide> -------
<ide> def exists(self, path):
<ide> Parameters
<ide> ----------
<ide> path : str
<del> Can be a local file or a remote URL. This may, but does not have
<del> to, include the `baseurl` with which the `Repository` was initialized.
<add> Can be a local file or a remote URL. This may, but does not
<add> have to, include the `baseurl` with which the `Repository` was
<add> initialized.
<ide>
<ide> Returns
<ide> -------
<ide> def exists(self, path):
<ide>
<ide> Notes
<ide> -----
<del> When `path` is an URL, `exists` will return True if it's either stored
<del> locally in the `DataSource` directory, or is a valid remote URL.
<del> `DataSource` does not discriminate between the two, the file is accessible
<del> if it exists in either location.
<add> When `path` is an URL, `exists` will return True if it's either
<add> stored locally in the `DataSource` directory, or is a valid remote
<add> URL. `DataSource` does not discriminate between the two, the file
<add> is accessible if it exists in either location.
<ide>
<ide> """
<ide> return DataSource.exists(self, self._fullpath(path))
<ide> def open(self, path, mode='r'):
<ide> """
<ide> Open and return file-like object prepending Repository base URL.
<ide>
<del> If `path` is an URL, it will be downloaded, stored in the DataSource
<del> directory and opened from there.
<add> If `path` is an URL, it will be downloaded, stored in the
<add> DataSource directory and opened from there.
<ide>
<ide> Parameters
<ide> ----------
<ide> path : str
<ide> Local file path or URL to open. This may, but does not have to,
<del> include the `baseurl` with which the `Repository` was initialized.
<add> include the `baseurl` with which the `Repository` was
<add> initialized.
<ide> mode : {'r', 'w', 'a'}, optional
<del> Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to
<del> append. Available modes depend on the type of object specified by
<del> `path`. Default is 'r'.
<add> Mode to open `path`. Mode 'r' for reading, 'w' for writing,
<add> 'a' to append. Available modes depend on the type of object
<add> specified by `path`. Default is 'r'.
<ide>
<ide> Returns
<ide> -------
<ide><path>numpy/lib/_iotools.py
<ide> from numpy.compat import asbytes, bytes, asbytes_nested, basestring
<ide>
<ide> if sys.version_info[0] >= 3:
<del> from builtins import bool, int, float, complex, object, str
<add> from builtins import bool, int, float, complex, object, str
<ide> unicode = str
<ide> else:
<ide> from __builtin__ import bool, int, float, complex, object, unicode, str
<ide> if sys.version_info[0] >= 3:
<ide> def _bytes_to_complex(s):
<ide> return complex(s.decode('ascii'))
<add>
<ide> def _bytes_to_name(s):
<ide> return s.decode('ascii')
<ide> else:
<ide> def flatten_dtype(ndtype, flatten_base=False):
<ide> return types
<ide>
<ide>
<del>
<del>
<del>
<del>
<ide> class LineSplitter(object):
<ide> """
<ide> Object to split a string at a given delimiter or at given places.
<ide> def autostrip(self, method):
<ide> """
<ide> return lambda input: [_.strip() for _ in method(input)]
<ide> #
<add>
<ide> def __init__(self, delimiter=None, comments=asbytes('#'), autostrip=True):
<ide> self.comments = comments
<ide> # Delimiter is a character
<ide> def __init__(self, delimiter=None, comments=asbytes('#'), autostrip=True):
<ide> delimiter = [slice(i, j) for (i, j) in zip(idx[:-1], idx[1:])]
<ide> # Delimiter is a single integer
<ide> elif int(delimiter):
<del> (_handyman, delimiter) = (self._fixedwidth_splitter, int(delimiter))
<add> (_handyman, delimiter) = (
<add> self._fixedwidth_splitter, int(delimiter))
<ide> else:
<ide> (_handyman, delimiter) = (self._delimited_splitter, None)
<ide> self.delimiter = delimiter
<ide> def __init__(self, delimiter=None, comments=asbytes('#'), autostrip=True):
<ide> else:
<ide> self._handyman = _handyman
<ide> #
<add>
<ide> def _delimited_splitter(self, line):
<ide> if self.comments is not None:
<ide> line = line.split(self.comments)[0]
<ide> def _delimited_splitter(self, line):
<ide> return []
<ide> return line.split(self.delimiter)
<ide> #
<add>
<ide> def _fixedwidth_splitter(self, line):
<ide> if self.comments is not None:
<ide> line = line.split(self.comments)[0]
<ide> def _fixedwidth_splitter(self, line):
<ide> slices = [slice(i, i + fixed) for i in range(0, len(line), fixed)]
<ide> return [line[s] for s in slices]
<ide> #
<add>
<ide> def _variablewidth_splitter(self, line):
<ide> if self.comments is not None:
<ide> line = line.split(self.comments)[0]
<ide> def _variablewidth_splitter(self, line):
<ide> slices = self.delimiter
<ide> return [line[s] for s in slices]
<ide> #
<add>
<ide> def __call__(self, line):
<ide> return self._handyman(line)
<ide>
<ide>
<del>
<ide> class NameValidator(object):
<ide> """
<ide> Object to validate a list of strings to use as field names.
<ide>
<ide> The strings are stripped of any non alphanumeric character, and spaces
<del> are replaced by '_'. During instantiation, the user can define a list of
<del> names to exclude, as well as a list of invalid characters. Names in the
<del> exclusion list are appended a '_' character.
<add> are replaced by '_'. During instantiation, the user can define a list
<add> of names to exclude, as well as a list of invalid characters. Names in
<add> the exclusion list are appended a '_' character.
<ide>
<del> Once an instance has been created, it can be called with a list of names,
<del> and a list of valid names will be created.
<del> The `__call__` method accepts an optional keyword "default" that sets
<del> the default name in case of ambiguity. By default this is 'f', so
<del> that names will default to `f0`, `f1`, etc.
<add> Once an instance has been created, it can be called with a list of
<add> names, and a list of valid names will be created. The `__call__`
<add> method accepts an optional keyword "default" that sets the default name
<add> in case of ambiguity. By default this is 'f', so that names will
<add> default to `f0`, `f1`, etc.
<ide>
<ide> Parameters
<ide> ----------
<ide> excludelist : sequence, optional
<del> A list of names to exclude. This list is appended to the default list
<del> ['return', 'file', 'print']. Excluded names are appended an underscore:
<del> for example, `file` becomes `file_` if supplied.
<add> A list of names to exclude. This list is appended to the default
<add> list ['return', 'file', 'print']. Excluded names are appended an
<add> underscore: for example, `file` becomes `file_` if supplied.
<ide> deletechars : str, optional
<ide> A string combining invalid characters that must be deleted from the
<ide> names.
<ide> class NameValidator(object):
<ide>
<ide> Notes
<ide> -----
<del> Calling an instance of `NameValidator` is the same as calling its method
<del> `validate`.
<add> Calling an instance of `NameValidator` is the same as calling its
<add> method `validate`.
<ide>
<ide> Examples
<ide> --------
<ide> class NameValidator(object):
<ide> defaultexcludelist = ['return', 'file', 'print']
<ide> defaultdeletechars = set("""~!@#$%^&*()-=+~\|]}[{';: /?.>,<""")
<ide> #
<add>
<ide> def __init__(self, excludelist=None, deletechars=None,
<ide> case_sensitive=None, replace_space='_'):
<ide> # Process the exclusion list ..
<ide> def __init__(self, excludelist=None, deletechars=None,
<ide>
<ide> def validate(self, names, defaultfmt="f%i", nbfields=None):
<ide> """
<del> Validate a list of strings to use as field names for a structured array.
<add> Validate a list of strings as field names for a structured array.
<ide>
<ide> Parameters
<ide> ----------
<ide> names : sequence of str
<ide> Strings to be validated.
<ide> defaultfmt : str, optional
<del> Default format string, used if validating a given string reduces its
<del> length to zero.
<add> Default format string, used if validating a given string
<add> reduces its length to zero.
<ide> nboutput : integer, optional
<del> Final number of validated names, used to expand or shrink the initial
<del> list of names.
<add> Final number of validated names, used to expand or shrink the
<add> initial list of names.
<ide>
<ide> Returns
<ide> -------
<ide> def validate(self, names, defaultfmt="f%i", nbfields=None):
<ide>
<ide> Notes
<ide> -----
<del> A `NameValidator` instance can be called directly, which is the same as
<del> calling `validate`. For examples, see `NameValidator`.
<add> A `NameValidator` instance can be called directly, which is the
<add> same as calling `validate`. For examples, see `NameValidator`.
<ide>
<ide> """
<ide> # Initial checks ..............
<ide> def validate(self, names, defaultfmt="f%i", nbfields=None):
<ide> seen[item] = cnt + 1
<ide> return tuple(validatednames)
<ide> #
<add>
<ide> def __call__(self, names, defaultfmt="f%i", nbfields=None):
<ide> return self.validate(names, defaultfmt=defaultfmt, nbfields=nbfields)
<ide>
<ide>
<del>
<ide> def str2bool(value):
<ide> """
<ide> Tries to transform a string supposed to represent a boolean to a boolean.
<ide> class ConversionWarning(UserWarning):
<ide> pass
<ide>
<ide>
<del>
<ide> class StringConverter(object):
<ide> """
<del> Factory class for function transforming a string into another object (int,
<del> float).
<add> Factory class for function transforming a string into another object
<add> (int, float).
<ide>
<ide> After initialization, an instance can be called to transform a string
<del> into another object. If the string is recognized as representing a missing
<del> value, a default value is returned.
<add> into another object. If the string is recognized as representing a
<add> missing value, a default value is returned.
<ide>
<ide> Attributes
<ide> ----------
<ide> func : function
<ide> Function used for the conversion.
<ide> default : any
<del> Default value to return when the input corresponds to a missing value.
<add> Default value to return when the input corresponds to a missing
<add> value.
<ide> type : type
<ide> Type of the output.
<ide> _status : int
<ide> class StringConverter(object):
<ide> If a `dtype`, specifies the input data type, used to define a basic
<ide> function and a default value for missing data. For example, when
<ide> `dtype` is float, the `func` attribute is set to `float` and the
<del> default value to `np.nan`.
<del> If a function, this function is used to convert a string to another
<del> object. In this case, it is recommended to give an associated default
<del> value as input.
<add> default value to `np.nan`. If a function, this function is used to
<add> convert a string to another object. In this case, it is recommended
<add> to give an associated default value as input.
<ide> default : any, optional
<del> Value to return by default, that is, when the string to be converted
<del> is flagged as missing. If not given, `StringConverter` tries to supply
<del> a reasonable default value.
<add> Value to return by default, that is, when the string to be
<add> converted is flagged as missing. If not given, `StringConverter`
<add> tries to supply a reasonable default value.
<ide> missing_values : sequence of str, optional
<ide> Sequence of strings indicating a missing value.
<ide> locked : bool, optional
<ide> class StringConverter(object):
<ide> (nx.string_, bytes, asbytes('???'))]
<ide> (_defaulttype, _defaultfunc, _defaultfill) = zip(*_mapper)
<ide> #
<add>
<ide> @classmethod
<ide> def _getdtype(cls, val):
<ide> """Returns the dtype of the input variable."""
<ide> return np.array(val).dtype
<ide> #
<add>
<ide> @classmethod
<ide> def _getsubdtype(cls, val):
<ide> """Returns the type of the dtype of the input variable."""
<ide> return np.array(val).dtype.type
<ide> #
<del> # This is a bit annoying. We want to return the "general" type in most cases
<del> # (ie. "string" rather than "S10"), but we want to return the specific type
<del> # for datetime64 (ie. "datetime64[us]" rather than "datetime64").
<add> # This is a bit annoying. We want to return the "general" type in most
<add> # cases (ie. "string" rather than "S10"), but we want to return the
<add> # specific type for datetime64 (ie. "datetime64[us]" rather than
<add> # "datetime64").
<add>
<ide> @classmethod
<ide> def _dtypeortype(cls, dtype):
<ide> """Returns dtype for datetime64 and type of dtype otherwise."""
<ide> if dtype.type == np.datetime64:
<ide> return dtype
<ide> return dtype.type
<ide> #
<add>
<ide> @classmethod
<ide> def upgrade_mapper(cls, func, default=None):
<ide> """
<del> Upgrade the mapper of a StringConverter by adding a new function and its
<del> corresponding default.
<add> Upgrade the mapper of a StringConverter by adding a new function and
<add> its corresponding default.
<ide>
<del> The input function (or sequence of functions) and its associated default
<del> value (if any) is inserted in penultimate position of the mapper.
<del> The corresponding type is estimated from the dtype of the default value.
<add> The input function (or sequence of functions) and its associated
<add> default value (if any) is inserted in penultimate position of the
<add> mapper. The corresponding type is estimated from the dtype of the
<add> default value.
<ide>
<ide> Parameters
<ide> ----------
<ide> def upgrade_mapper(cls, func, default=None):
<ide> for (fct, dft) in zip(func, default):
<ide> cls._mapper.insert(-1, (cls._getsubdtype(dft), fct, dft))
<ide> #
<add>
<ide> def __init__(self, dtype_or_func=None, default=None, missing_values=None,
<ide> locked=False):
<ide> # Convert unicode (for Py3)
<ide> def __init__(self, dtype_or_func=None, default=None, missing_values=None,
<ide> except TypeError:
<ide> # dtype_or_func must be a function, then
<ide> if not hasattr(dtype_or_func, '__call__'):
<del> errmsg = "The input argument `dtype` is neither a function"\
<del> " or a dtype (got '%s' instead)"
<add> errmsg = ("The input argument `dtype` is neither a"
<add> " function nor a dtype (got '%s' instead)")
<ide> raise TypeError(errmsg % type(dtype_or_func))
<ide> # Set the function
<ide> self.func = dtype_or_func
<del> # If we don't have a default, try to guess it or set it to None
<add> # If we don't have a default, try to guess it or set it to
<add> # None
<ide> if default is None:
<ide> try:
<ide> default = self.func(asbytes('0'))
<ide> def __init__(self, dtype_or_func=None, default=None, missing_values=None,
<ide> elif issubclass(dtype.type, np.int64):
<ide> self.func = np.int64
<ide> else:
<del> self.func = lambda x : int(float(x))
<add> self.func = lambda x: int(float(x))
<ide> # Store the list of strings corresponding to missing values.
<ide> if missing_values is None:
<ide> self.missing_values = set([asbytes('')])
<ide> def __init__(self, dtype_or_func=None, default=None, missing_values=None,
<ide> self._checked = False
<ide> self._initial_default = default
<ide> #
<add>
<ide> def _loose_call(self, value):
<ide> try:
<ide> return self.func(value)
<ide> except ValueError:
<ide> return self.default
<ide> #
<add>
<ide> def _strict_call(self, value):
<ide> try:
<ide> return self.func(value)
<ide> def _strict_call(self, value):
<ide> return self.default
<ide> raise ValueError("Cannot convert string '%s'" % value)
<ide> #
<add>
<ide> def __call__(self, value):
<ide> return self._callingfunction(value)
<ide> #
<add>
<ide> def upgrade(self, value):
<ide> """
<del> Try to find the best converter for a given string, and return the result.
<add> Rind the best converter for a given string, and return the result.
<ide>
<ide> The supplied string `value` is converted by testing different
<del> converters in order. First the `func` method of the `StringConverter`
<del> instance is tried, if this fails other available converters are tried.
<del> The order in which these other converters are tried is determined by the
<del> `_status` attribute of the instance.
<add> converters in order. First the `func` method of the
<add> `StringConverter` instance is tried, if this fails other available
<add> converters are tried. The order in which these other converters
<add> are tried is determined by the `_status` attribute of the instance.
<ide>
<ide> Parameters
<ide> ----------
<ide> def iterupgrade(self, value):
<ide> # Complains if we try to upgrade by the maximum
<ide> _status = self._status
<ide> if _status == _statusmax:
<del> raise ConverterError("Could not find a valid conversion function")
<add> raise ConverterError(
<add> "Could not find a valid conversion function"
<add> )
<ide> elif _status < _statusmax - 1:
<ide> _status += 1
<ide> (self.type, self.func, default) = self._mapper[_status]
<ide> def update(self, func, default=None, testing_value=None,
<ide> func : function
<ide> Conversion function.
<ide> default : any, optional
<del> Value to return by default, that is, when the string to be converted
<del> is flagged as missing. If not given, `StringConverter` tries to supply
<del> a reasonable default value.
<add> Value to return by default, that is, when the string to be
<add> converted is flagged as missing. If not given,
<add> `StringConverter` tries to supply a reasonable default value.
<ide> testing_value : str, optional
<ide> A string representing a standard input value of the converter.
<del> This string is used to help defining a reasonable default value.
<add> This string is used to help defining a reasonable default
<add> value.
<ide> missing_values : sequence of str, optional
<ide> Sequence of strings indicating a missing value.
<ide> locked : bool, optional
<del> Whether the StringConverter should be locked to prevent automatic
<del> upgrade or not. Default is False.
<add> Whether the StringConverter should be locked to prevent
<add> automatic upgrade or not. Default is False.
<ide>
<ide> Notes
<ide> -----
<del> `update` takes the same parameters as the constructor of `StringConverter`,
<del> except that `func` does not accept a `dtype` whereas `dtype_or_func` in
<del> the constructor does.
<add> `update` takes the same parameters as the constructor of
<add> `StringConverter`, except that `func` does not accept a `dtype`
<add> whereas `dtype_or_func` in the constructor does.
<ide>
<ide> """
<ide> self.func = func
<ide> def update(self, func, default=None, testing_value=None,
<ide> self.missing_values = []
<ide>
<ide>
<del>
<ide> def easy_dtype(ndtype, names=None, defaultfmt="f%i", **validationargs):
<ide> """
<ide> Convenience function to create a `np.dtype` object.
<ide> def easy_dtype(ndtype, names=None, defaultfmt="f%i", **validationargs):
<ide> Parameters
<ide> ----------
<ide> ndtype : var
<del> Definition of the dtype. Can be any string or dictionary
<del> recognized by the `np.dtype` function, or a sequence of types.
<add> Definition of the dtype. Can be any string or dictionary recognized
<add> by the `np.dtype` function, or a sequence of types.
<ide> names : str or sequence, optional
<ide> Sequence of strings to use as field names for a structured dtype.
<del> For convenience, `names` can be a string of a comma-separated list of
<del> names.
<add> For convenience, `names` can be a string of a comma-separated list
<add> of names.
<ide> defaultfmt : str, optional
<ide> Format string used to define missing names, such as ``"f%i"``
<ide> (default) or ``"fields_%02i"``.
<ide> validationargs : optional
<del> A series of optional arguments used to initialize a `NameValidator`.
<add> A series of optional arguments used to initialize a
<add> `NameValidator`.
<ide>
<ide> Examples
<ide> --------
<ide> def easy_dtype(ndtype, names=None, defaultfmt="f%i", **validationargs):
<ide> elif (nbtypes > 0):
<ide> validate = NameValidator(**validationargs)
<ide> # Default initial names : should we change the format ?
<del> if (ndtype.names == tuple("f%i" % i for i in range(nbtypes))) and \
<del> (defaultfmt != "f%i"):
<add> if ((ndtype.names == tuple("f%i" % i for i in range(nbtypes))) and
<add> (defaultfmt != "f%i")):
<ide> ndtype.names = validate([''] * nbtypes, defaultfmt=defaultfmt)
<ide> # Explicit initial names : just validate
<ide> else:
<ide><path>numpy/lib/_version.py
<ide> class NumpyVersion():
<ide> >>> NumpyVersion('1.7') # raises ValueError, add ".0"
<ide>
<ide> """
<add>
<ide> def __init__(self, vstring):
<ide> self.vstring = vstring
<ide> ver_main = re.match(r'\d[.]\d+[.]\d+', vstring)
<ide><path>numpy/lib/arraypad.py
<ide> def _prepend_ramp(arr, pad_amt, end, axis=-1):
<ide> ramp_arr = _arange_ndarray(arr, padshape, axis,
<ide> reverse=True).astype(np.float64)
<ide>
<del>
<ide> # Appropriate slicing to extract n-dimensional edge along `axis`
<ide> edge_slice = tuple(slice(None) if i != axis else 0
<ide> for (i, x) in enumerate(arr.shape))
<ide><path>numpy/lib/arraysetops.py
<ide> def intersect1d(ar1, ar2, assume_unique=False):
<ide> # Might be faster than unique( intersect1d( ar1, ar2 ) )?
<ide> ar1 = unique(ar1)
<ide> ar2 = unique(ar2)
<del> aux = np.concatenate( (ar1, ar2) )
<add> aux = np.concatenate((ar1, ar2))
<ide> aux.sort()
<ide> return aux[:-1][aux[1:] == aux[:-1]]
<ide>
<ide> def setxor1d(ar1, ar2, assume_unique=False):
<ide> ar1 = unique(ar1)
<ide> ar2 = unique(ar2)
<ide>
<del> aux = np.concatenate( (ar1, ar2) )
<add> aux = np.concatenate((ar1, ar2))
<ide> if aux.size == 0:
<ide> return aux
<ide>
<ide> aux.sort()
<ide> # flag = ediff1d( aux, to_end = 1, to_begin = 1 ) == 0
<del> flag = np.concatenate( ([True], aux[1:] != aux[:-1], [True] ) )
<add> flag = np.concatenate(([True], aux[1:] != aux[:-1], [True]))
<ide> # flag2 = ediff1d( flag ) == 0
<ide> flag2 = flag[1:] == flag[:-1]
<ide> return aux[flag2]
<ide> def in1d(ar1, ar2, assume_unique=False, invert=False):
<ide> ar1, rev_idx = np.unique(ar1, return_inverse=True)
<ide> ar2 = np.unique(ar2)
<ide>
<del> ar = np.concatenate( (ar1, ar2) )
<add> ar = np.concatenate((ar1, ar2))
<ide> # We need this to be a stable sort, so always use 'mergesort'
<ide> # here. The values from the first array should always come before
<ide> # the values from the second array.
<ide> def in1d(ar1, ar2, assume_unique=False, invert=False):
<ide> bool_ar = (sar[1:] != sar[:-1])
<ide> else:
<ide> bool_ar = (sar[1:] == sar[:-1])
<del> flag = np.concatenate( (bool_ar, [invert]) )
<del> indx = order.argsort(kind='mergesort')[:len( ar1 )]
<add> flag = np.concatenate((bool_ar, [invert]))
<add> indx = order.argsort(kind='mergesort')[:len(ar1)]
<ide>
<ide> if assume_unique:
<ide> return flag[indx]
<ide> def union1d(ar1, ar2):
<ide> array([-2, -1, 0, 1, 2])
<ide>
<ide> """
<del> return unique( np.concatenate( (ar1, ar2) ) )
<add> return unique(np.concatenate((ar1, ar2)))
<ide>
<ide> def setdiff1d(ar1, ar2, assume_unique=False):
<ide> """
<ide><path>numpy/lib/arrayterator.py
<ide> def __getitem__(self, index):
<ide>
<ide> """
<ide> # Fix index, handling ellipsis and incomplete slices.
<del> if not isinstance(index, tuple): index = (index,)
<add> if not isinstance(index, tuple):
<add> index = (index,)
<ide> fixed = []
<ide> length, dims = len(index), len(self.shape)
<ide> for slice_ in index:
<ide> def shape(self):
<ide>
<ide> def __iter__(self):
<ide> # Skip arrays with degenerate dimensions
<del> if [dim for dim in self.shape if dim <= 0]: raise StopIteration
<add> if [dim for dim in self.shape if dim <= 0]:
<add> raise StopIteration
<ide>
<ide> start = self.start[:]
<ide> stop = self.stop[:]
<ide> def __iter__(self):
<ide> # along higher dimensions, so we read only a single position
<ide> if count == 0:
<ide> stop[i] = start[i]+1
<del> elif count <= self.shape[i]: # limit along this dimension
<add> elif count <= self.shape[i]:
<add> # limit along this dimension
<ide> stop[i] = start[i] + count*step[i]
<ide> rundim = i
<ide> else:
<del> stop[i] = self.stop[i] # read everything along this
<del> # dimension
<add> # read everything along this dimension
<add> stop[i] = self.stop[i]
<ide> stop[i] = min(self.stop[i], stop[i])
<ide> count = count//self.shape[i]
<ide>
<ide><path>numpy/lib/financial.py
<ide> def fv(rate, nper, pmt, pv, when='end'):
<ide> temp = (1+rate)**nper
<ide> miter = np.broadcast(rate, nper, pmt, pv, when)
<ide> zer = np.zeros(miter.shape)
<del> fact = np.where(rate==zer, nper+zer, (1+rate*when)*(temp-1)/rate+zer)
<add> fact = np.where(rate == zer, nper + zer,
<add> (1 + rate*when)*(temp - 1)/rate + zer)
<ide> return -(pv*temp + pmt*fact)
<ide>
<ide> def pmt(rate, nper, pv, fv=0, when='end'):
<ide> def pmt(rate, nper, pv, fv=0, when='end'):
<ide> temp = (1+rate)**nper
<ide> miter = np.broadcast(rate, nper, pv, fv, when)
<ide> zer = np.zeros(miter.shape)
<del> fact = np.where(rate==zer, nper+zer, (1+rate*when)*(temp-1)/rate+zer)
<add> fact = np.where(rate == zer, nper + zer,
<add> (1 + rate*when)*(temp - 1)/rate + zer)
<ide> return -(fv + pv*temp) / fact
<ide>
<ide> def nper(rate, pmt, pv, fv=0, when='end'):
<ide> def nper(rate, pmt, pv, fv=0, when='end'):
<ide> B = np.log((-fv+z) / (pv+z))/np.log(1.0+rate)
<ide> miter = np.broadcast(rate, pmt, pv, fv, when)
<ide> zer = np.zeros(miter.shape)
<del> return np.where(rate==zer, A+zer, B+zer) + 0.0
<add> return np.where(rate == zer, A + zer, B + zer) + 0.0
<ide>
<ide> def ipmt(rate, per, nper, pv, fv=0.0, when='end'):
<ide> """
<ide> def ipmt(rate, per, nper, pv, fv=0.0, when='end'):
<ide>
<ide> """
<ide> when = _convert_when(when)
<del> rate, per, nper, pv, fv, when = np.broadcast_arrays(rate, per, nper, pv, fv, when)
<add> rate, per, nper, pv, fv, when = np.broadcast_arrays(rate, per, nper,
<add> pv, fv, when)
<ide> total_pmt = pmt(rate, nper, pv, fv, when)
<ide> ipmt = _rbl(rate, per, total_pmt, pv, when)*rate
<ide> try:
<ide> def pv(rate, nper, pmt, fv=0.0, when='end'):
<ide> return -(fv + pmt*fact)/temp
<ide>
<ide> # Computed with Sage
<del># (y + (r + 1)^n*x + p*((r + 1)^n - 1)*(r*w + 1)/r)/(n*(r + 1)^(n - 1)*x - p*((r + 1)^n - 1)*(r*w + 1)/r^2 + n*p*(r + 1)^(n - 1)*(r*w + 1)/r + p*((r + 1)^n - 1)*w/r)
<add># (y + (r + 1)^n*x + p*((r + 1)^n - 1)*(r*w + 1)/r)/(n*(r + 1)^(n - 1)*x -
<add># p*((r + 1)^n - 1)*(r*w + 1)/r^2 + n*p*(r + 1)^(n - 1)*(r*w + 1)/r +
<add># p*((r + 1)^n - 1)*w/r)
<ide>
<ide> def _g_div_gp(r, n, p, x, y, w):
<ide> t1 = (r+1)**n
<ide> t2 = (r+1)**(n-1)
<del> return (y + t1*x + p*(t1 - 1)*(r*w + 1)/r)/(n*t2*x - p*(t1 - 1)*(r*w + 1)/(r**2) + n*p*t2*(r*w + 1)/r + p*(t1 - 1)*w/r)
<add> return ((y + t1*x + p*(t1 - 1)*(r*w + 1)/r) /
<add> (n*t2*x - p*(t1 - 1)*(r*w + 1)/(r**2) + n*p*t2*(r*w + 1)/r +
<add> p*(t1 - 1)*w/r))
<ide>
<ide> # Use Newton's iteration until the change is less than 1e-6
<ide> # for all values or a maximum of 100 iterations is reached.
<ide> def rate(nper, pmt, pv, fv, when='end', guess=0.10, tol=1e-6, maxiter=100):
<ide> while (iter < maxiter) and not close:
<ide> rnp1 = rn - _g_div_gp(rn, nper, pmt, pv, fv, when)
<ide> diff = abs(rnp1-rn)
<del> close = np.all(diff<tol)
<add> close = np.all(diff < tol)
<ide> iter += 1
<ide> rn = rnp1
<ide> if not close:
<ide> def irr(values):
<ide> ----------
<ide> values : array_like, shape(N,)
<ide> Input cash flows per time period. By convention, net "deposits"
<del> are negative and net "withdrawals" are positive. Thus, for example,
<del> at least the first element of `values`, which represents the initial
<del> investment, will typically be negative.
<add> are negative and net "withdrawals" are positive. Thus, for
<add> example, at least the first element of `values`, which represents
<add> the initial investment, will typically be negative.
<ide>
<ide> Returns
<ide> -------
<ide> def irr(values):
<ide> Notes
<ide> -----
<ide> The IRR is perhaps best understood through an example (illustrated
<del> using np.irr in the Examples section below). Suppose one invests
<del> 100 units and then makes the following withdrawals at regular
<del> (fixed) intervals: 39, 59, 55, 20. Assuming the ending value is 0,
<del> one's 100 unit investment yields 173 units; however, due to the
<del> combination of compounding and the periodic withdrawals, the
<del> "average" rate of return is neither simply 0.73/4 nor (1.73)^0.25-1.
<del> Rather, it is the solution (for :math:`r`) of the equation:
<add> using np.irr in the Examples section below). Suppose one invests 100
<add> units and then makes the following withdrawals at regular (fixed)
<add> intervals: 39, 59, 55, 20. Assuming the ending value is 0, one's 100
<add> unit investment yields 173 units; however, due to the combination of
<add> compounding and the periodic withdrawals, the "average" rate of return
<add> is neither simply 0.73/4 nor (1.73)^0.25-1. Rather, it is the solution
<add> (for :math:`r`) of the equation:
<ide>
<ide> .. math:: -100 + \\frac{39}{1+r} + \\frac{59}{(1+r)^2}
<ide> + \\frac{55}{(1+r)^3} + \\frac{20}{(1+r)^4} = 0
<ide> def npv(rate, values):
<ide> The discount rate.
<ide> values : array_like, shape(M, )
<ide> The values of the time series of cash flows. The (fixed) time
<del> interval between cash flow "events" must be the same as that
<del> for which `rate` is given (i.e., if `rate` is per year, then
<del> precisely a year is understood to elapse between each cash flow
<del> event). By convention, investments or "deposits" are negative,
<del> income or "withdrawals" are positive; `values` must begin with
<del> the initial investment, thus `values[0]` will typically be
<del> negative.
<add> interval between cash flow "events" must be the same as that for
<add> which `rate` is given (i.e., if `rate` is per year, then precisely
<add> a year is understood to elapse between each cash flow event). By
<add> convention, investments or "deposits" are negative, income or
<add> "withdrawals" are positive; `values` must begin with the initial
<add> investment, thus `values[0]` will typically be negative.
<ide>
<ide> Returns
<ide> -------
<ide> out : float
<del> The NPV of the input cash flow series `values` at the discount `rate`.
<add> The NPV of the input cash flow series `values` at the discount
<add> `rate`.
<ide>
<ide> Notes
<ide> -----
<ide> def mirr(values, finance_rate, reinvest_rate):
<ide> Parameters
<ide> ----------
<ide> values : array_like
<del> Cash flows (must contain at least one positive and one negative value)
<del> or nan is returned. The first value is considered a sunk cost at time zero.
<add> Cash flows (must contain at least one positive and one negative
<add> value) or nan is returned. The first value is considered a sunk
<add> cost at time zero.
<ide> finance_rate : scalar
<ide> Interest rate paid on the cash flows
<ide> reinvest_rate : scalar
<ide><path>numpy/lib/format.py
<ide>
<ide> MAGIC_PREFIX = asbytes('\x93NUMPY')
<ide> MAGIC_LEN = len(MAGIC_PREFIX) + 2
<del>BUFFER_SIZE = 2 ** 18 #size of buffer for reading npz files in bytes
<add>BUFFER_SIZE = 2**18 # size of buffer for reading npz files in bytes
<ide>
<ide> # difference between version 1.0 and 2.0 is a 4 byte (I) header length
<ide> # instead of 2 bytes (H) allowing storage of large structured arrays
<ide> def dtype_to_descr(dtype):
<ide>
<ide> """
<ide> if dtype.names is not None:
<del> # This is a record array. The .descr is fine.
<del> # XXX: parts of the record array with an empty name, like padding bytes,
<del> # still get fiddled with. This needs to be fixed in the C implementation
<del> # of dtype().
<add> # This is a record array. The .descr is fine. XXX: parts of the
<add> # record array with an empty name, like padding bytes, still get
<add> # fiddled with. This needs to be fixed in the C implementation of
<add> # dtype().
<ide> return dtype.descr
<ide> else:
<ide> return dtype.str
<ide> def _write_array_header(fp, d, version=None):
<ide> header.append("}")
<ide> header = "".join(header)
<ide> # Pad the header with spaces and a final newline such that the magic
<del> # string, the header-length short and the header are aligned on a 16-byte
<del> # boundary. Hopefully, some system, possibly memory-mapping, can take
<del> # advantage of our premature optimization.
<add> # string, the header-length short and the header are aligned on a
<add> # 16-byte boundary. Hopefully, some system, possibly memory-mapping,
<add> # can take advantage of our premature optimization.
<ide> current_header_len = MAGIC_LEN + 2 + len(header) + 1 # 1 for the newline
<ide> topad = 16 - (current_header_len % 16)
<ide> header = asbytes(header + ' '*topad + '\n')
<ide> def write_array_header_1_0(fp, d):
<ide> ----------
<ide> fp : filelike object
<ide> d : dict
<del> This has the appropriate entries for writing its string representation
<del> to the header of the file.
<add> This has the appropriate entries for writing its string
<add> representation to the header of the file.
<ide> """
<ide> _write_array_header(fp, d, (1, 0))
<ide>
<ide> def write_array_header_2_0(fp, d):
<ide> ----------
<ide> fp : filelike object
<ide> d : dict
<del> This has the appropriate entries for writing its string representation
<del> to the header of the file.
<add> This has the appropriate entries for writing its string
<add> representation to the header of the file.
<ide> """
<ide> _write_array_header(fp, d, (2, 0))
<ide>
<ide> def read_array_header_1_0(fp):
<ide> shape : tuple of int
<ide> The shape of the array.
<ide> fortran_order : bool
<del> The array data will be written out directly if it is either C-contiguous
<del> or Fortran-contiguous. Otherwise, it will be made contiguous before
<del> writing it out.
<add> The array data will be written out directly if it is either
<add> C-contiguous or Fortran-contiguous. Otherwise, it will be made
<add> contiguous before writing it out.
<ide> dtype : dtype
<ide> The dtype of the file's data.
<ide>
<ide> def read_array_header_2_0(fp):
<ide> shape : tuple of int
<ide> The shape of the array.
<ide> fortran_order : bool
<del> The array data will be written out directly if it is either C-contiguous
<del> or Fortran-contiguous. Otherwise, it will be made contiguous before
<del> writing it out.
<add> The array data will be written out directly if it is either
<add> C-contiguous or Fortran-contiguous. Otherwise, it will be made
<add> contiguous before writing it out.
<ide> dtype : dtype
<ide> The dtype of the file's data.
<ide>
<ide> def _read_array_header(fp, version):
<ide> else:
<ide> raise ValueError("Invalid version %r" % version)
<ide>
<del> # The header is a pretty-printed string representation of a literal Python
<del> # dictionary with trailing newlines padded to a 16-byte boundary. The keys
<del> # are strings.
<add> # The header is a pretty-printed string representation of a literal
<add> # Python dictionary with trailing newlines padded to a 16-byte
<add> # boundary. The keys are strings.
<ide> # "shape" : tuple of int
<ide> # "fortran_order" : bool
<ide> # "descr" : dtype.descr
<ide> def _read_array_header(fp, version):
<ide>
<ide> # Sanity-check the values.
<ide> if (not isinstance(d['shape'], tuple) or
<del> not numpy.all([isinstance(x, (int, long)) for x in d['shape']])):
<add> not numpy.all([isinstance(x, (int, long)) for x in d['shape']])):
<ide> msg = "shape is not valid: %r"
<ide> raise ValueError(msg % (d['shape'],))
<ide> if not isinstance(d['fortran_order'], bool):
<ide> def write_array(fp, array, version=None):
<ide> Parameters
<ide> ----------
<ide> fp : file_like object
<del> An open, writable file object, or similar object with a ``.write()``
<del> method.
<add> An open, writable file object, or similar object with a
<add> ``.write()`` method.
<ide> array : ndarray
<ide> The array to write to disk.
<ide> version : (int, int) or None, optional
<del> The version number of the format. None means use the oldest supported
<del> version that is able to store the data. Default: None
<add> The version number of the format. None means use the oldest
<add> supported version that is able to store the data. Default: None
<ide>
<ide> Raises
<ide> ------
<ide> def write_array(fp, array, version=None):
<ide> buffersize = max(16 * 1024 ** 2 // array.itemsize, 1)
<ide>
<ide> if array.dtype.hasobject:
<del> # We contain Python objects so we cannot write out the data directly.
<del> # Instead, we will pickle it out with version 2 of the pickle protocol.
<add> # We contain Python objects so we cannot write out the data
<add> # directly. Instead, we will pickle it out with version 2 of the
<add> # pickle protocol.
<ide> pickle.dump(array, fp, protocol=2)
<ide> elif array.flags.f_contiguous and not array.flags.c_contiguous:
<ide> if isfileobj(fp):
<ide> def read_array(fp):
<ide> # We can use the fast fromfile() function.
<ide> array = numpy.fromfile(fp, dtype=dtype, count=count)
<ide> else:
<del> # This is not a real file. We have to read it the memory-intensive
<del> # way.
<del> # crc32 module fails on reads greater than 2 ** 32 bytes, breaking
<del> # large reads from gzip streams. Chunk reads to BUFFER_SIZE bytes to
<del> # avoid issue and reduce memory overhead of the read. In
<del> # non-chunked case count < max_read_count, so only one read is
<del> # performed.
<add> # This is not a real file. We have to read it the
<add> # memory-intensive way.
<add> # crc32 module fails on reads greater than 2 ** 32 bytes,
<add> # breaking large reads from gzip streams. Chunk reads to
<add> # BUFFER_SIZE bytes to avoid issue and reduce memory overhead
<add> # of the read. In non-chunked case count < max_read_count, so
<add> # only one read is performed.
<ide>
<ide> max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize)
<ide>
<ide> def open_memmap(filename, mode='r+', dtype=None, shape=None,
<ide> object.
<ide> mode : str, optional
<ide> The mode in which to open the file; the default is 'r+'. In
<del> addition to the standard file modes, 'c' is also accepted to
<del> mean "copy on write." See `memmap` for the available mode strings.
<add> addition to the standard file modes, 'c' is also accepted to mean
<add> "copy on write." See `memmap` for the available mode strings.
<ide> dtype : data-type, optional
<ide> The data type of the array if we are creating a new file in "write"
<del> mode, if not, `dtype` is ignored. The default value is None,
<del> which results in a data-type of `float64`.
<add> mode, if not, `dtype` is ignored. The default value is None, which
<add> results in a data-type of `float64`.
<ide> shape : tuple of int
<ide> The shape of the array if we are creating a new file in "write"
<ide> mode, in which case this parameter is required. Otherwise, this
<ide> parameter is ignored and is thus optional.
<ide> fortran_order : bool, optional
<ide> Whether the array should be Fortran-contiguous (True) or
<del> C-contiguous (False, the default) if we are creating a new file
<del> in "write" mode.
<add> C-contiguous (False, the default) if we are creating a new file in
<add> "write" mode.
<ide> version : tuple of int (major, minor) or None
<ide> If the mode is a "write" mode, then this is the version of the file
<del> format used to create the file.
<del> None means use the oldest supported version that is able to store the
<del> data. Default: None
<add> format used to create the file. None means use the oldest
<add> supported version that is able to store the data. Default: None
<ide>
<ide> Returns
<ide> -------
<ide> def open_memmap(filename, mode='r+', dtype=None, shape=None,
<ide>
<ide> """
<ide> if not isinstance(filename, basestring):
<del> raise ValueError("Filename must be a string. Memmap cannot use" \
<add> raise ValueError("Filename must be a string. Memmap cannot use"
<ide> " existing file handles.")
<ide>
<ide> if 'w' in mode:
<ide> # We are creating the file, not reading it.
<ide> # Check if we ought to create the file.
<ide> _check_version(version)
<del> # Ensure that the given dtype is an authentic dtype object rather than
<del> # just something that can be interpreted as a dtype object.
<add> # Ensure that the given dtype is an authentic dtype object rather
<add> # than just something that can be interpreted as a dtype object.
<ide> dtype = numpy.dtype(dtype)
<ide> if dtype.hasobject:
<ide> msg = "Array can't be memory-mapped: Python objects in dtype."
<ide> def _read_bytes(fp, size, error_template="ran out of data"):
<ide> """
<ide> data = bytes()
<ide> while True:
<del> # io files (default in python3) return None or raise on would-block,
<del> # python2 file will truncate, probably nothing can be done about that.
<del> # note that regular files can't be non-blocking
<add> # io files (default in python3) return None or raise on
<add> # would-block, python2 file will truncate, probably nothing can be
<add> # done about that. note that regular files can't be non-blocking
<ide> try:
<ide> r = fp.read(size - len(data))
<ide> data += r
<ide> def _read_bytes(fp, size, error_template="ran out of data"):
<ide> pass
<ide> if len(data) != size:
<ide> msg = "EOF: reading %s, expected %d bytes got %d"
<del> raise ValueError(msg %(error_template, size, len(data)))
<add> raise ValueError(msg % (error_template, size, len(data)))
<ide> else:
<ide> return data
<ide><path>numpy/lib/function_base.py
<ide> def histogramdd(sample, bins=10, range=None, normed=False, weights=None):
<ide> Ncount[i] = digitize(sample[:, i], edges[i])
<ide>
<ide> # Using digitize, values that fall on an edge are put in the right bin.
<del> # For the rightmost bin, we want values equal to the right
<del> # edge to be counted in the last bin, and not as an outlier.
<add> # For the rightmost bin, we want values equal to the right edge to be
<add> # counted in the last bin, and not as an outlier.
<ide> for i in arange(D):
<ide> # Rounding precision
<ide> mindiff = dedges[i].min()
<ide> if not np.isinf(mindiff):
<ide> decimal = int(-log10(mindiff)) + 6
<ide> # Find which points are on the rightmost edge.
<ide> not_smaller_than_edge = (sample[:, i] >= edges[i][-1])
<del> on_edge = (around(sample[:, i], decimal) == around(edges[i][-1], decimal))
<add> on_edge = (around(sample[:, i], decimal) ==
<add> around(edges[i][-1], decimal))
<ide> # Shift these points one bin to the left.
<ide> Ncount[i][where(on_edge & not_smaller_than_edge)[0]] -= 1
<ide>
<ide> class vectorize(object):
<ide> further degrades performance.
<ide>
<ide> """
<add>
<ide> def __init__(self, pyfunc, otypes='', doc=None, excluded=None,
<ide> cache=False):
<ide> self.pyfunc = pyfunc
<ide> def meshgrid(*xi, **kwargs):
<ide> raise TypeError("meshgrid() got an unexpected keyword argument '%s'"
<ide> % (list(kwargs)[0],))
<ide>
<del> if not indexing in ['xy', 'ij']:
<add> if indexing not in ['xy', 'ij']:
<ide> raise ValueError(
<ide> "Valid values for `indexing` are 'xy' and 'ij'.")
<ide>
<ide> def delete(arr, obj, axis=None):
<ide> Notes
<ide> -----
<ide> Often it is preferable to use a boolean mask. For example:
<del>
<add>
<ide> >>> mask = np.ones(len(arr), dtype=bool)
<ide> >>> mask[[0,2,4]] = False
<ide> >>> result = arr[mask,...]
<ide><path>numpy/lib/index_tricks.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<del>__all__ = ['ravel_multi_index',
<del> 'unravel_index',
<del> 'mgrid',
<del> 'ogrid',
<del> 'r_', 'c_', 's_',
<del> 'index_exp', 'ix_',
<del> 'ndenumerate', 'ndindex',
<del> 'fill_diagonal', 'diag_indices', 'diag_indices_from']
<del>
<ide> import sys
<add>import math
<add>
<ide> import numpy.core.numeric as _nx
<del>from numpy.core.numeric import ( asarray, ScalarType, array, alltrue, cumprod,
<del> arange )
<add>from numpy.core.numeric import (
<add> asarray, ScalarType, array, alltrue, cumprod, arange
<add> )
<ide> from numpy.core.numerictypes import find_common_type
<del>import math
<ide>
<ide> from . import function_base
<ide> import numpy.matrixlib as matrix
<ide> from .function_base import diff
<ide> from numpy.lib._compiled_base import ravel_multi_index, unravel_index
<ide> from numpy.lib.stride_tricks import as_strided
<add>
<ide> makemat = matrix.matrix
<ide>
<add>
<add>__all__ = [
<add> 'ravel_multi_index', 'unravel_index', 'mgrid', 'ogrid', 'r_', 'c_',
<add> 's_', 'index_exp', 'ix_', 'ndenumerate', 'ndindex', 'fill_diagonal',
<add> 'diag_indices', 'diag_indices_from'
<add> ]
<add>
<add>
<ide> def ix_(*args):
<ide> """
<ide> Construct an open mesh from multiple sequences.
<ide> class nd_grid(object):
<ide> [4]]), array([[0, 1, 2, 3, 4]])]
<ide>
<ide> """
<add>
<ide> def __init__(self, sparse=False):
<ide> self.sparse = sparse
<add>
<ide> def __getitem__(self, key):
<ide> try:
<ide> size = []
<ide> typ = int
<ide> for k in range(len(key)):
<ide> step = key[k].step
<ide> start = key[k].start
<del> if start is None: start=0
<del> if step is None: step=1
<add> if start is None:
<add> start = 0
<add> if step is None:
<add> step = 1
<ide> if isinstance(step, complex):
<ide> size.append(int(abs(step)))
<ide> typ = float
<ide> else:
<del> size.append(int(math.ceil((key[k].stop - start)/(step*1.0))))
<del> if isinstance(step, float) or \
<del> isinstance(start, float) or \
<del> isinstance(key[k].stop, float):
<add> size.append(
<add> int(math.ceil((key[k].stop - start)/(step*1.0))))
<add> if (isinstance(step, float) or
<add> isinstance(start, float) or
<add> isinstance(key[k].stop, float)):
<ide> typ = float
<ide> if self.sparse:
<ide> nn = [_nx.arange(_x, dtype=_t)
<ide> def __getitem__(self, key):
<ide> for k in range(len(size)):
<ide> step = key[k].step
<ide> start = key[k].start
<del> if start is None: start=0
<del> if step is None: step=1
<add> if start is None:
<add> start = 0
<add> if step is None:
<add> step = 1
<ide> if isinstance(step, complex):
<ide> step = int(abs(step))
<ide> if step != 1:
<ide> def __getitem__(self, key):
<ide> step = key.step
<ide> stop = key.stop
<ide> start = key.start
<del> if start is None: start = 0
<add> if start is None:
<add> start = 0
<ide> if isinstance(step, complex):
<ide> step = abs(step)
<ide> length = int(step)
<ide> if step != 1:
<ide> step = (key.stop-start)/float(step-1)
<del> stop = key.stop+step
<add> stop = key.stop + step
<ide> return _nx.arange(0, length, 1, float)*step + start
<ide> else:
<ide> return _nx.arange(start, stop, step)
<ide> def __len__(self):
<ide>
<ide> mgrid = nd_grid(sparse=False)
<ide> ogrid = nd_grid(sparse=True)
<del>mgrid.__doc__ = None # set in numpy.add_newdocs
<del>ogrid.__doc__ = None # set in numpy.add_newdocs
<add>mgrid.__doc__ = None # set in numpy.add_newdocs
<add>ogrid.__doc__ = None # set in numpy.add_newdocs
<ide>
<ide> class AxisConcatenator(object):
<ide> """
<ide> class AxisConcatenator(object):
<ide> For detailed documentation on usage, see `r_`.
<ide>
<ide> """
<add>
<ide> def _retval(self, res):
<ide> if self.matrix:
<ide> oldndim = res.ndim
<ide> def __getitem__(self, key):
<ide> step = key[k].step
<ide> start = key[k].start
<ide> stop = key[k].stop
<del> if start is None: start = 0
<add> if start is None:
<add> start = 0
<ide> if step is None:
<ide> step = 1
<ide> if isinstance(step, complex):
<ide> class RClass(AxisConcatenator):
<ide> matrix([[1, 2, 3, 4, 5, 6]])
<ide>
<ide> """
<add>
<ide> def __init__(self):
<ide> AxisConcatenator.__init__(self, 0)
<ide>
<ide> class CClass(AxisConcatenator):
<ide> array([[1, 2, 3, 0, 0, 4, 5, 6]])
<ide>
<ide> """
<add>
<ide> def __init__(self):
<ide> AxisConcatenator.__init__(self, -1, ndmin=2, trans1d=0)
<ide>
<ide> class ndenumerate(object):
<ide> (1, 1) 4
<ide>
<ide> """
<add>
<ide> def __init__(self, arr):
<ide> self.iter = asarray(arr).flat
<ide>
<ide> class ndindex(object):
<ide> (2, 1, 0)
<ide>
<ide> """
<add>
<ide> def __init__(self, *shape):
<ide> if len(shape) == 1 and isinstance(shape[0], tuple):
<ide> shape = shape[0]
<del> x = as_strided(_nx.zeros(1), shape=shape, strides=_nx.zeros_like(shape))
<add> x = as_strided(_nx.zeros(1), shape=shape,
<add> strides=_nx.zeros_like(shape))
<ide> self._it = _nx.nditer(x, flags=['multi_index', 'zerosize_ok'],
<ide> order='C')
<ide>
<ide> def ndincr(self):
<ide>
<ide> def __next__(self):
<ide> """
<del> Standard iterator method, updates the index and returns the index tuple.
<add> Standard iterator method, updates the index and returns the index
<add> tuple.
<ide>
<ide> Returns
<ide> -------
<ide> val : tuple of ints
<del> Returns a tuple containing the indices of the current iteration.
<add> Returns a tuple containing the indices of the current
<add> iteration.
<ide>
<ide> """
<ide> next(self._it)
<ide> return self._it.multi_index
<ide>
<del> next = __next__
<add> next = __next__
<ide>
<ide>
<ide> # You can do all this with slice() plus a few special objects,
<ide> class IndexExpression(object):
<ide> array([2, 4])
<ide>
<ide> """
<add>
<ide> def __init__(self, maketuple):
<ide> self.maketuple = maketuple
<ide>
<ide> def fill_diagonal(a, val, wrap=False):
<ide> else:
<ide> # For more than d=2, the strided formula is only valid for arrays with
<ide> # all dimensions equal, so we check first.
<del> if not alltrue(diff(a.shape)==0):
<add> if not alltrue(diff(a.shape) == 0):
<ide> raise ValueError("All dimensions of input must be of equal length")
<ide> step = 1 + (cumprod(a.shape[:-1])).sum()
<ide>
<ide><path>numpy/lib/npyio.py
<ide> class BagObj(object):
<ide> "Doesn't matter what you want, you're gonna get this"
<ide>
<ide> """
<add>
<ide> def __init__(self, obj):
<ide> # Use weakref to make NpzFile objects collectable by refcount
<ide> self._obj = weakref.proxy(obj)
<ide> class NpzFile(object):
<ide> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
<ide>
<ide> """
<add>
<ide> def __init__(self, fid, own_fid=False):
<ide> # Import is postponed to here since zipfile depends on gzip, an
<ide> # optional component of the so-called standard library.
<ide> def split_line(line):
<ide>
<ide> # Verify that the array has at least dimensions `ndmin`.
<ide> # Check correctness of the values of `ndmin`
<del> if not ndmin in [0, 1, 2]:
<add> if ndmin not in [0, 1, 2]:
<ide> raise ValueError('Illegal value of ndmin keyword: %s' % ndmin)
<ide> # Tweak the size and shape of the arrays - remove extraneous dimensions
<ide> if X.ndim > ndmin:
<ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
<ide> first_line = next(fhd)
<ide> if names is True:
<ide> if comments in first_line:
<del> first_line = asbytes('').join(first_line.split(comments)[1:])
<add> first_line = (
<add> asbytes('').join(first_line.split(comments)[1:]))
<ide> first_values = split_line(first_line)
<ide> except StopIteration:
<ide> # return an empty array if the datafile is empty
<ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
<ide> if usemask:
<ide> masks = masks[:-skip_footer]
<ide>
<del>
<ide> # Convert each value according to the converter:
<ide> # We want to modify the list in place to avoid creating a new one...
<del> #
<del> # if loose:
<del> # conversionfuncs = [conv._loose_call for conv in converters]
<del> # else:
<del> # conversionfuncs = [conv._strict_call for conv in converters]
<del> # for (i, vals) in enumerate(rows):
<del> # rows[i] = tuple([convert(val)
<del> # for (convert, val) in zip(conversionfuncs, vals)])
<ide> if loose:
<del> rows = list(zip(*[[converter._loose_call(_r) for _r in map(itemgetter(i), rows)]
<del> for (i, converter) in enumerate(converters)]))
<add> rows = list(
<add> zip(*[[conv._loose_call(_r) for _r in map(itemgetter(i), rows)]
<add> for (i, conv) in enumerate(converters)]))
<ide> else:
<del> rows = list(zip(*[[converter._strict_call(_r) for _r in map(itemgetter(i), rows)]
<del> for (i, converter) in enumerate(converters)]))
<add> rows = list(
<add> zip(*[[conv._strict_call(_r) for _r in map(itemgetter(i), rows)]
<add> for (i, conv) in enumerate(converters)]))
<add>
<ide> # Reset the dtype
<ide> data = rows
<ide> if dtype is None:
<ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
<ide> if user_converters:
<ide> ishomogeneous = True
<ide> descr = []
<del> for (i, ttype) in enumerate([conv.type for conv in converters]):
<add> for i, ttype in enumerate([conv.type for conv in converters]):
<ide> # Keep the dtype of the current converter
<ide> if i in user_converters:
<ide> ishomogeneous &= (ttype == dtype.type)
<ide><path>numpy/lib/polynomial.py
<ide> def poly(seq_of_zeros):
<ide> neg_roots = NX.conjugate(sort_complex(
<ide> NX.compress(roots.imag < 0, roots)))
<ide> if (len(pos_roots) == len(neg_roots) and
<del> NX.alltrue(neg_roots == pos_roots)):
<add> NX.alltrue(neg_roots == pos_roots)):
<ide> a = a.real.copy()
<ide>
<ide> return a
<ide> def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
<ide> deg : int
<ide> Degree of the fitting polynomial
<ide> rcond : float, optional
<del> Relative condition number of the fit. Singular values smaller than this
<del> relative to the largest singular value will be ignored. The default
<del> value is len(x)*eps, where eps is the relative precision of the float
<del> type, about 2e-16 in most cases.
<add> Relative condition number of the fit. Singular values smaller than
<add> this relative to the largest singular value will be ignored. The
<add> default value is len(x)*eps, where eps is the relative precision of
<add> the float type, about 2e-16 in most cases.
<ide> full : bool, optional
<del> Switch determining nature of return value. When it is
<del> False (the default) just the coefficients are returned, when True
<del> diagnostic information from the singular value decomposition is also
<del> returned.
<add> Switch determining nature of return value. When it is False (the
<add> default) just the coefficients are returned, when True diagnostic
<add> information from the singular value decomposition is also returned.
<ide> w : array_like, shape (M,), optional
<ide> weights to apply to the y-coordinates of the sample points.
<ide> cov : bool, optional
<ide> def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
<ide> Returns
<ide> -------
<ide> p : ndarray, shape (M,) or (M, K)
<del> Polynomial coefficients, highest power first.
<del> If `y` was 2-D, the coefficients for `k`-th data set are in ``p[:,k]``.
<add> Polynomial coefficients, highest power first. If `y` was 2-D, the
<add> coefficients for `k`-th data set are in ``p[:,k]``.
<ide>
<del> residuals, rank, singular_values, rcond : present only if `full` = True
<del> Residuals of the least-squares fit, the effective rank of the scaled
<del> Vandermonde coefficient matrix, its singular values, and the specified
<del> value of `rcond`. For more details, see `linalg.lstsq`.
<add> residuals, rank, singular_values, rcond :
<add> Present only if `full` = True. Residuals of the least-squares fit,
<add> the effective rank of the scaled Vandermonde coefficient matrix,
<add> its singular values, and the specified value of `rcond`. For more
<add> details, see `linalg.lstsq`.
<ide>
<del> V : ndaray, shape (M,M) or (M,M,K) : present only if `full` = False and `cov`=True
<del> The covariance matrix of the polynomial coefficient estimates. The diagonal
<del> of this matrix are the variance estimates for each coefficient. If y is a 2-d
<del> array, then the covariance matrix for the `k`-th data set are in ``V[:,:,k]``
<add> V : ndarray, shape (M,M) or (M,M,K)
<add> Present only if `full` = False and `cov`=True. The covariance
<add> matrix of the polynomial coefficient estimates. The diagonal of
<add> this matrix are the variance estimates for each coefficient. If y
<add> is a 2-D array, then the covariance matrix for the `k`-th data set
<add> are in ``V[:,:,k]``
<ide>
<ide>
<ide> Warns
<ide> def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
<ide>
<ide> >>> import matplotlib.pyplot as plt
<ide> >>> xp = np.linspace(-2, 6, 100)
<del> >>> plt.plot(x, y, '.', xp, p(xp), '-', xp, p30(xp), '--')
<del> [<matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>]
<add> >>> _ = plt.plot(x, y, '.', xp, p(xp), '-', xp, p30(xp), '--')
<ide> >>> plt.ylim(-2,2)
<ide> (-2, 2)
<ide> >>> plt.show()
<ide> def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
<ide> y = NX.asarray(y) + 0.0
<ide>
<ide> # check arguments.
<del> if deg < 0 :
<add> if deg < 0:
<ide> raise ValueError("expected deg >= 0")
<ide> if x.ndim != 1:
<ide> raise TypeError("expected 1D vector for x")
<ide> if x.size == 0:
<ide> raise TypeError("expected non-empty vector for x")
<del> if y.ndim < 1 or y.ndim > 2 :
<add> if y.ndim < 1 or y.ndim > 2:
<ide> raise TypeError("expected 1D or 2D array for y")
<del> if x.shape[0] != y.shape[0] :
<add> if x.shape[0] != y.shape[0]:
<ide> raise TypeError("expected x and y to have same length")
<ide>
<ide> # set rcond
<del> if rcond is None :
<add> if rcond is None:
<ide> rcond = len(x)*finfo(x.dtype).eps
<ide>
<ide> # set up least squares equation for powers of x
<ide> def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
<ide> w = NX.asarray(w) + 0.0
<ide> if w.ndim != 1:
<ide> raise TypeError("expected a 1-d array for weights")
<del> if w.shape[0] != y.shape[0] :
<add> if w.shape[0] != y.shape[0]:
<ide> raise TypeError("expected w and y to have the same length")
<ide> lhs *= w[:, NX.newaxis]
<ide> if rhs.ndim == 2:
<ide> def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
<ide> msg = "Polyfit may be poorly conditioned"
<ide> warnings.warn(msg, RankWarning)
<ide>
<del> if full :
<add> if full:
<ide> return c, resids, rank, s, rcond
<del> elif cov :
<add> elif cov:
<ide> Vbase = inv(dot(lhs.T, lhs))
<ide> Vbase /= NX.outer(scale, scale)
<ide> # Some literature ignores the extra -2.0 factor in the denominator, but
<ide> def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
<ide> return c, Vbase * fac
<ide> else:
<ide> return c, Vbase[:,:, NX.newaxis] * fac
<del> else :
<add> else:
<ide> return c
<ide>
<ide>
<ide> def _raise_power(astr, wrap=70):
<ide> n = span[1]
<ide> toadd2 = partstr + ' '*(len(power)-1)
<ide> toadd1 = ' '*(len(partstr)-1) + power
<del> if ((len(line2)+len(toadd2) > wrap) or \
<del> (len(line1)+len(toadd1) > wrap)):
<add> if ((len(line2) + len(toadd2) > wrap) or
<add> (len(line1) + len(toadd1) > wrap)):
<ide> output += line1 + "\n" + line2 + "\n "
<ide> line1 = toadd1
<ide> line2 = toadd2
<ide> def fmt_float(q):
<ide> thestr = newstr
<ide> return _raise_power(thestr)
<ide>
<del>
<ide> def __call__(self, val):
<ide> return polyval(self.coeffs, val)
<ide>
<ide> def __getattr__(self, key):
<ide> try:
<ide> return self.__dict__[key]
<ide> except KeyError:
<del> raise AttributeError("'%s' has no attribute '%s'" % (self.__class__, key))
<add> raise AttributeError(
<add> "'%s' has no attribute '%s'" % (self.__class__, key))
<ide>
<ide> def __getitem__(self, val):
<ide> ind = self.order - val
<ide><path>numpy/lib/recfunctions.py
<ide> """
<ide> Collection of utilities to manipulate structured arrays.
<ide>
<del>Most of these functions were initially implemented by John Hunter for matplotlib.
<del>They have been rewritten and extended for convenience.
<add>Most of these functions were initially implemented by John Hunter for
<add>matplotlib. They have been rewritten and extended for convenience.
<ide>
<ide> """
<ide> from __future__ import division, absolute_import, print_function
<ide> def recursive_fill_fields(input, output):
<ide> return output
<ide>
<ide>
<del>
<ide> def get_names(adtype):
<ide> """
<ide> Returns the field names of the input datatype as a tuple.
<ide> def zip_descr(seqarrays, flatten=False):
<ide>
<ide> def get_fieldstructure(adtype, lastname=None, parents=None,):
<ide> """
<del> Returns a dictionary with fields as keys and a list of parent fields as values.
<add> Returns a dictionary with fields indexing lists of their parent fields.
<ide>
<ide> This function is used to simplify access to fields nested in other fields.
<ide>
<ide> def get_fieldstructure(adtype, lastname=None, parents=None,):
<ide> else:
<ide> lastparent = [_ for _ in (parents.get(lastname, []) or [])]
<ide> if lastparent:
<del># if (lastparent[-1] != lastname):
<del> lastparent.append(lastname)
<add> lastparent.append(lastname)
<ide> elif lastname:
<ide> lastparent = [lastname, ]
<ide> parents[name] = lastparent or []
<ide> def _izip_fields_flat(iterable):
<ide> """
<ide> Returns an iterator of concatenated fields from a sequence of arrays,
<ide> collapsing any nested structure.
<add>
<ide> """
<ide> for element in iterable:
<ide> if isinstance(element, np.void):
<ide> def _izip_fields_flat(iterable):
<ide> def _izip_fields(iterable):
<ide> """
<ide> Returns an iterator of concatenated fields from a sequence of arrays.
<add>
<ide> """
<ide> for element in iterable:
<del> if hasattr(element, '__iter__') and not isinstance(element, basestring):
<add> if (hasattr(element, '__iter__') and
<add> not isinstance(element, basestring)):
<ide> for f in _izip_fields(element):
<ide> yield f
<ide> elif isinstance(element, np.void) and len(tuple(element)) == 1:
<ide> def _fix_defaults(output, defaults=None):
<ide> return output
<ide>
<ide>
<del>
<del>def merge_arrays(seqarrays,
<del> fill_value= -1, flatten=False, usemask=False, asrecarray=False):
<add>def merge_arrays(seqarrays, fill_value=-1, flatten=False,
<add> usemask=False, asrecarray=False):
<ide> """
<ide> Merge arrays field by field.
<ide>
<ide> def merge_arrays(seqarrays,
<ide> return output
<ide>
<ide>
<del>
<ide> def drop_fields(base, drop_names, usemask=True, asrecarray=False):
<ide> """
<ide> Return a new array with fields in `drop_names` dropped.
<ide> def drop_fields(base, drop_names, usemask=True, asrecarray=False):
<ide> base : array
<ide> Input array
<ide> drop_names : string or sequence
<del> String or sequence of strings corresponding to the names of the fields
<del> to drop.
<add> String or sequence of strings corresponding to the names of the
<add> fields to drop.
<ide> usemask : {False, True}, optional
<ide> Whether to return a masked array or not.
<del> asrecarray : string or sequence
<add> asrecarray : string or sequence, optional
<ide> Whether to return a recarray or a mrecarray (`asrecarray=True`) or
<del> a plain ndarray or masked array with flexible dtype (`asrecarray=False`)
<add> a plain ndarray or masked array with flexible dtype. The default
<add> is False.
<ide>
<ide> Examples
<ide> --------
<ide> def drop_fields(base, drop_names, usemask=True, asrecarray=False):
<ide> drop_names = [drop_names, ]
<ide> else:
<ide> drop_names = set(drop_names)
<del> #
<add>
<ide> def _drop_descr(ndtype, drop_names):
<ide> names = ndtype.names
<ide> newdtype = []
<ide> def _drop_descr(ndtype, drop_names):
<ide> else:
<ide> newdtype.append((name, current))
<ide> return newdtype
<del> #
<add>
<ide> newdtype = _drop_descr(base.dtype, drop_names)
<ide> if not newdtype:
<ide> return None
<del> #
<add>
<ide> output = np.empty(base.shape, dtype=newdtype)
<ide> output = recursive_fill_fields(base, output)
<ide> return _fix_output(output, usemask=usemask, asrecarray=asrecarray)
<ide> def rec_drop_fields(base, drop_names):
<ide> return drop_fields(base, drop_names, usemask=False, asrecarray=True)
<ide>
<ide>
<del>
<ide> def rename_fields(base, namemapper):
<ide> """
<ide> Rename the fields from a flexible-datatype ndarray or recarray.
<ide> def _recursive_rename_fields(ndtype, namemapper):
<ide> newname = namemapper.get(name, name)
<ide> current = ndtype[name]
<ide> if current.names:
<del> newdtype.append((newname,
<del> _recursive_rename_fields(current, namemapper)))
<add> newdtype.append(
<add> (newname, _recursive_rename_fields(current, namemapper))
<add> )
<ide> else:
<ide> newdtype.append((newname, current))
<ide> return newdtype
<ide> def _recursive_rename_fields(ndtype, namemapper):
<ide>
<ide>
<ide> def append_fields(base, names, data, dtypes=None,
<del> fill_value= -1, usemask=True, asrecarray=False):
<add> fill_value=-1, usemask=True, asrecarray=False):
<ide> """
<ide> Add new fields to an existing array.
<ide>
<ide> def append_fields(base, names, data, dtypes=None,
<ide> if dtypes is None:
<ide> data = [np.array(a, copy=False, subok=True) for a in data]
<ide> data = [a.view([(name, a.dtype)]) for (name, a) in zip(names, data)]
<del> else :
<add> else:
<ide> if not isinstance(dtypes, (tuple, list)):
<ide> dtypes = [dtypes, ]
<ide> if len(data) != len(dtypes):
<ide> def append_fields(base, names, data, dtypes=None,
<ide> return _fix_output(output, usemask=usemask, asrecarray=asrecarray)
<ide>
<ide>
<del>
<ide> def rec_append_fields(base, names, data, dtypes=None):
<ide> """
<ide> Add new fields to an existing array.
<ide> def rec_append_fields(base, names, data, dtypes=None):
<ide> asrecarray=True, usemask=False)
<ide>
<ide>
<del>
<ide> def stack_arrays(arrays, defaults=None, usemask=True, asrecarray=False,
<ide> autoconvert=False):
<ide> """
<ide> def stack_arrays(arrays, defaults=None, usemask=True, asrecarray=False,
<ide> defaults : dictionary, optional
<ide> Dictionary mapping field names to the corresponding default values.
<ide> usemask : {True, False}, optional
<del> Whether to return a MaskedArray (or MaskedRecords is `asrecarray==True`)
<del> or a ndarray.
<add> Whether to return a MaskedArray (or MaskedRecords is
<add> `asrecarray==True`) or a ndarray.
<ide> asrecarray : {False, True}, optional
<del> Whether to return a recarray (or MaskedRecords if `usemask==True`) or
<del> just a flexible-type ndarray.
<add> Whether to return a recarray (or MaskedRecords if `usemask==True`)
<add> or just a flexible-type ndarray.
<ide> autoconvert : {False, True}, optional
<ide> Whether automatically cast the type of the field to the maximum.
<ide>
<ide> def stack_arrays(arrays, defaults=None, usemask=True, asrecarray=False,
<ide> current_descr[-1] = descr[1]
<ide> newdescr[nameidx] = tuple(current_descr)
<ide> elif descr[1] != current_descr[-1]:
<del> raise TypeError("Incompatible type '%s' <> '%s'" % \
<add> raise TypeError("Incompatible type '%s' <> '%s'" %
<ide> (dict(newdescr)[name], descr[1]))
<ide> # Only one field: use concatenate
<ide> if len(newdescr) == 1:
<ide> def stack_arrays(arrays, defaults=None, usemask=True, asrecarray=False,
<ide> usemask=usemask, asrecarray=asrecarray)
<ide>
<ide>
<del>
<ide> def find_duplicates(a, key=None, ignoremask=True, return_index=False):
<ide> """
<ide> Find the duplicates in a structured array along a given key
<ide> def find_duplicates(a, key=None, ignoremask=True, return_index=False):
<ide> return duplicates
<ide>
<ide>
<del>
<ide> def join_by(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2',
<ide> defaults=None, usemask=True, asrecarray=False):
<ide> """
<ide> Join arrays `r1` and `r2` on key `key`.
<ide>
<ide> The key should be either a string or a sequence of string corresponding
<del> to the fields used to join the array.
<del> An exception is raised if the `key` field cannot be found in the two input
<del> arrays.
<del> Neither `r1` nor `r2` should have any duplicates along `key`: the presence
<del> of duplicates will make the output quite unreliable. Note that duplicates
<del> are not looked for by the algorithm.
<add> to the fields used to join the array. An exception is raised if the
<add> `key` field cannot be found in the two input arrays. Neither `r1` nor
<add> `r2` should have any duplicates along `key`: the presence of duplicates
<add> will make the output quite unreliable. Note that duplicates are not
<add> looked for by the algorithm.
<ide>
<ide> Parameters
<ide> ----------
<ide> def join_by(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2',
<ide> Structured arrays.
<ide> jointype : {'inner', 'outer', 'leftouter'}, optional
<ide> If 'inner', returns the elements common to both r1 and r2.
<del> If 'outer', returns the common elements as well as the elements of r1
<del> not in r2 and the elements of not in r2.
<del> If 'leftouter', returns the common elements and the elements of r1 not
<del> in r2.
<add> If 'outer', returns the common elements as well as the elements of
<add> r1 not in r2 and the elements of not in r2.
<add> If 'leftouter', returns the common elements and the elements of r1
<add> not in r2.
<ide> r1postfix : string, optional
<del> String appended to the names of the fields of r1 that are present in r2
<del> but absent of the key.
<add> String appended to the names of the fields of r1 that are present
<add> in r2 but absent of the key.
<ide> r2postfix : string, optional
<del> String appended to the names of the fields of r2 that are present in r1
<del> but absent of the key.
<add> String appended to the names of the fields of r2 that are present
<add> in r1 but absent of the key.
<ide> defaults : {dictionary}, optional
<ide> Dictionary mapping field names to the corresponding default values.
<ide> usemask : {True, False}, optional
<del> Whether to return a MaskedArray (or MaskedRecords is `asrecarray==True`)
<del> or a ndarray.
<add> Whether to return a MaskedArray (or MaskedRecords is
<add> `asrecarray==True`) or a ndarray.
<ide> asrecarray : {False, True}, optional
<del> Whether to return a recarray (or MaskedRecords if `usemask==True`) or
<del> just a flexible-type ndarray.
<add> Whether to return a recarray (or MaskedRecords if `usemask==True`)
<add> or just a flexible-type ndarray.
<ide>
<ide> Notes
<ide> -----
<ide> * The output is sorted along the key.
<del> * A temporary array is formed by dropping the fields not in the key for the
<del> two arrays and concatenating the result. This array is then sorted, and
<del> the common entries selected. The output is constructed by filling the fields
<del> with the selected entries. Matching is not preserved if there are some
<del> duplicates...
<add> * A temporary array is formed by dropping the fields not in the key for
<add> the two arrays and concatenating the result. This array is then
<add> sorted, and the common entries selected. The output is constructed by
<add> filling the fields with the selected entries. Matching is not
<add> preserved if there are some duplicates...
<ide>
<ide> """
<ide> # Check jointype
<ide> if jointype not in ('inner', 'outer', 'leftouter'):
<del> raise ValueError("The 'jointype' argument should be in 'inner', "\
<del> "'outer' or 'leftouter' (got '%s' instead)" % jointype)
<add> raise ValueError(
<add> "The 'jointype' argument should be in 'inner', "
<add> "'outer' or 'leftouter' (got '%s' instead)" % jointype
<add> )
<ide> # If we have a single key, put it in a tuple
<ide> if isinstance(key, basestring):
<ide> key = (key,)
<ide> def join_by(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2',
<ide> ndtype.append(desc)
<ide> # Revert the elements to tuples
<ide> ndtype = [tuple(_) for _ in ndtype]
<del> # Find the largest nb of common fields : r1cmn and r2cmn should be equal, but...
<add> # Find the largest nb of common fields :
<add> # r1cmn and r2cmn should be equal, but...
<ide> cmn = max(r1cmn, r2cmn)
<ide> # Construct an empty array
<ide> output = ma.masked_all((cmn + r1spc + r2spc,), dtype=ndtype)
<ide> names = output.dtype.names
<ide> for f in r1names:
<ide> selected = s1[f]
<del> if f not in names or (f in r2names and not r2postfix and not f in key):
<add> if f not in names or (f in r2names and not r2postfix and f not in key):
<ide> f += r1postfix
<ide> current = output[f]
<ide> current[:r1cmn] = selected[:r1cmn]
<ide><path>numpy/lib/scimath.py
<ide> """
<ide> from __future__ import division, absolute_import, print_function
<ide>
<del>__all__ = ['sqrt', 'log', 'log2', 'logn', 'log10', 'power', 'arccos',
<del> 'arcsin', 'arctanh']
<del>
<ide> import numpy.core.numeric as nx
<ide> import numpy.core.numerictypes as nt
<ide> from numpy.core.numeric import asarray, any
<ide> from numpy.lib.type_check import isreal
<ide>
<add>
<add>__all__ = [
<add> 'sqrt', 'log', 'log2', 'logn', 'log10', 'power', 'arccos', 'arcsin',
<add> 'arctanh'
<add> ]
<add>
<add>
<ide> _ln2 = nx.log(2.0)
<ide>
<add>
<ide> def _tocomplex(arr):
<ide> """Convert its input `arr` to a complex array.
<ide>
<ide> def _fix_real_lt_zero(x):
<ide>
<ide> >>> np.lib.scimath._fix_real_lt_zero([-1,2])
<ide> array([-1.+0.j, 2.+0.j])
<add>
<ide> """
<ide> x = asarray(x)
<del> if any(isreal(x) & (x<0)):
<add> if any(isreal(x) & (x < 0)):
<ide> x = _tocomplex(x)
<ide> return x
<ide>
<ide> def _fix_real_abs_gt_1(x):
<ide> array([ 0.+0.j, 2.+0.j])
<ide> """
<ide> x = asarray(x)
<del> if any(isreal(x) & (abs(x)>1)):
<add> if any(isreal(x) & (abs(x) > 1)):
<ide> x = _tocomplex(x)
<ide> return x
<ide>
<ide><path>numpy/lib/setup.py
<ide> def configuration(parent_package='',top_path=None):
<ide>
<ide> config.add_include_dirs(join('..', 'core', 'include'))
<ide>
<del>
<ide> config.add_extension('_compiled_base',
<ide> sources=[join('src', '_compiled_base.c')]
<ide> )
<ide> def configuration(parent_package='',top_path=None):
<ide>
<ide> return config
<ide>
<del>if __name__=='__main__':
<add>if __name__ == '__main__':
<ide> from numpy.distutils.core import setup
<ide> setup(configuration=configuration)
<ide><path>numpy/lib/shape_base.py
<ide> def apply_over_axes(func, a, axes):
<ide> if array(axes).ndim == 0:
<ide> axes = (axes,)
<ide> for axis in axes:
<del> if axis < 0: axis = N + axis
<add> if axis < 0:
<add> axis = N + axis
<ide> args = (val, axis)
<ide> res = func(*args)
<ide> if res.ndim == val.ndim:
<ide> def _replace_zero_by_x_arrays(sub_arys):
<ide> sub_arys[i] = _nx.empty(0, dtype=sub_arys[i].dtype)
<ide> return sub_arys
<ide>
<del>def array_split(ary,indices_or_sections,axis = 0):
<add>def array_split(ary, indices_or_sections, axis=0):
<ide> """
<ide> Split an array into multiple sub-arrays.
<ide>
<ide> def array_split(ary,indices_or_sections,axis = 0):
<ide> Ntotal = ary.shape[axis]
<ide> except AttributeError:
<ide> Ntotal = len(ary)
<del> try: # handle scalar case.
<add> try:
<add> # handle scalar case.
<ide> Nsections = len(indices_or_sections) + 1
<ide> div_points = [0] + list(indices_or_sections) + [Ntotal]
<del> except TypeError: #indices_or_sections is a scalar, not an array.
<add> except TypeError:
<add> # indices_or_sections is a scalar, not an array.
<ide> Nsections = int(indices_or_sections)
<ide> if Nsections <= 0:
<ide> raise ValueError('number sections must be larger than 0.')
<ide> Neach_section, extras = divmod(Ntotal, Nsections)
<del> section_sizes = [0] + \
<del> extras * [Neach_section+1] + \
<del> (Nsections-extras) * [Neach_section]
<add> section_sizes = ([0] +
<add> extras * [Neach_section+1] +
<add> (Nsections-extras) * [Neach_section])
<ide> div_points = _nx.array(section_sizes).cumsum()
<ide>
<ide> sub_arys = []
<ide> sary = _nx.swapaxes(ary, axis, 0)
<ide> for i in range(Nsections):
<del> st = div_points[i]; end = div_points[i+1]
<add> st = div_points[i]
<add> end = div_points[i + 1]
<ide> sub_arys.append(_nx.swapaxes(sary[st:end], axis, 0))
<ide>
<ide> # This "kludge" was introduced here to replace arrays shaped (0, 10)
<ide> def split(ary,indices_or_sections,axis=0):
<ide> array([], dtype=float64)]
<ide>
<ide> """
<del> try: len(indices_or_sections)
<add> try:
<add> len(indices_or_sections)
<ide> except TypeError:
<ide> sections = indices_or_sections
<ide> N = ary.shape[axis]
<ide> if N % sections:
<del> raise ValueError('array split does not result in an equal division')
<add> raise ValueError(
<add> 'array split does not result in an equal division')
<ide> res = array_split(ary, indices_or_sections, axis)
<ide> return res
<ide>
<ide> def tile(A, reps):
<ide> if (d < c.ndim):
<ide> tup = (1,)*(c.ndim-d) + tup
<ide> for i, nrep in enumerate(tup):
<del> if nrep!=1:
<add> if nrep != 1:
<ide> c = c.reshape(-1, n).repeat(nrep, 0)
<ide> dim_in = shape[i]
<ide> dim_out = dim_in*nrep
<ide><path>numpy/lib/stride_tricks.py
<ide> __all__ = ['broadcast_arrays']
<ide>
<ide> class DummyArray(object):
<del> """ Dummy object that just exists to hang __array_interface__ dictionaries
<add> """Dummy object that just exists to hang __array_interface__ dictionaries
<ide> and possibly keep alive a reference to a base array.
<ide> """
<add>
<ide> def __init__(self, interface, base=None):
<ide> self.__array_interface__ = interface
<ide> self.base = base
<ide> def broadcast_arrays(*args):
<ide> strides = [list(x.strides) for x in args]
<ide> nds = [len(s) for s in shapes]
<ide> biggest = max(nds)
<del> # Go through each array and prepend dimensions of length 1 to each of the
<del> # shapes in order to make the number of dimensions equal.
<add> # Go through each array and prepend dimensions of length 1 to each of
<add> # the shapes in order to make the number of dimensions equal.
<ide> for i in range(len(args)):
<ide> diff = biggest - nds[i]
<ide> if diff > 0:
<ide> def broadcast_arrays(*args):
<ide> raise ValueError("shape mismatch: two or more arrays have "
<ide> "incompatible dimensions on axis %r." % (axis,))
<ide> elif len(unique) == 2:
<del> # There is exactly one non-1 length. The common shape will take this
<del> # value.
<add> # There is exactly one non-1 length. The common shape will take
<add> # this value.
<ide> unique.remove(1)
<ide> new_length = unique.pop()
<ide> common_shape.append(new_length)
<del> # For each array, if this axis is being broadcasted from a length of
<del> # 1, then set its stride to 0 so that it repeats its data.
<add> # For each array, if this axis is being broadcasted from a
<add> # length of 1, then set its stride to 0 so that it repeats its
<add> # data.
<ide> for i in range(len(args)):
<ide> if shapes[i][axis] == 1:
<ide> shapes[i][axis] = new_length
<ide> strides[i][axis] = 0
<ide> else:
<del> # Every array has a length of 1 on this axis. Strides can be left
<del> # alone as nothing is broadcasted.
<add> # Every array has a length of 1 on this axis. Strides can be
<add> # left alone as nothing is broadcasted.
<ide> common_shape.append(1)
<ide>
<ide> # Construct the new arrays.
<ide> broadcasted = [as_strided(x, shape=sh, strides=st) for (x, sh, st) in
<del> zip(args, shapes, strides)]
<add> zip(args, shapes, strides)]
<ide> return broadcasted
<ide><path>numpy/lib/type_check.py
<ide> def mintypecode(typechars,typeset='GDFgdf',default='d'):
<ide> 'G'
<ide>
<ide> """
<del> typecodes = [(isinstance(t, str) and t) or asarray(t).dtype.char\
<add> typecodes = [(isinstance(t, str) and t) or asarray(t).dtype.char
<ide> for t in typechars]
<ide> intersection = [t for t in typecodes if t in typeset]
<ide> if not intersection:
<ide> def iscomplexobj(x):
<ide> True
<ide>
<ide> """
<del> return issubclass( asarray(x).dtype.type, _nx.complexfloating)
<add> return issubclass(asarray(x).dtype.type, _nx.complexfloating)
<ide>
<ide> def isrealobj(x):
<ide> """
<ide> def isrealobj(x):
<ide> False
<ide>
<ide> """
<del> return not issubclass( asarray(x).dtype.type, _nx.complexfloating)
<add> return not issubclass(asarray(x).dtype.type, _nx.complexfloating)
<ide>
<ide> #-----------------------------------------------------------------------------
<ide>
<ide> def asscalar(a):
<ide>
<ide> #-----------------------------------------------------------------------------
<ide>
<del>_namefromtype = {'S1' : 'character',
<del> '?' : 'bool',
<del> 'b' : 'signed char',
<del> 'B' : 'unsigned char',
<del> 'h' : 'short',
<del> 'H' : 'unsigned short',
<del> 'i' : 'integer',
<del> 'I' : 'unsigned integer',
<del> 'l' : 'long integer',
<del> 'L' : 'unsigned long integer',
<del> 'q' : 'long long integer',
<del> 'Q' : 'unsigned long long integer',
<del> 'f' : 'single precision',
<del> 'd' : 'double precision',
<del> 'g' : 'long precision',
<del> 'F' : 'complex single precision',
<del> 'D' : 'complex double precision',
<del> 'G' : 'complex long double precision',
<del> 'S' : 'string',
<del> 'U' : 'unicode',
<del> 'V' : 'void',
<del> 'O' : 'object'
<add>_namefromtype = {'S1': 'character',
<add> '?': 'bool',
<add> 'b': 'signed char',
<add> 'B': 'unsigned char',
<add> 'h': 'short',
<add> 'H': 'unsigned short',
<add> 'i': 'integer',
<add> 'I': 'unsigned integer',
<add> 'l': 'long integer',
<add> 'L': 'unsigned long integer',
<add> 'q': 'long long integer',
<add> 'Q': 'unsigned long long integer',
<add> 'f': 'single precision',
<add> 'd': 'double precision',
<add> 'g': 'long precision',
<add> 'F': 'complex single precision',
<add> 'D': 'complex double precision',
<add> 'G': 'complex long double precision',
<add> 'S': 'string',
<add> 'U': 'unicode',
<add> 'V': 'void',
<add> 'O': 'object'
<ide> }
<ide>
<ide> def typename(char):
<ide> def typename(char):
<ide> #determine the "minimum common type" for a group of arrays.
<ide> array_type = [[_nx.single, _nx.double, _nx.longdouble],
<ide> [_nx.csingle, _nx.cdouble, _nx.clongdouble]]
<del>array_precision = {_nx.single : 0,
<del> _nx.double : 1,
<del> _nx.longdouble : 2,
<del> _nx.csingle : 0,
<del> _nx.cdouble : 1,
<del> _nx.clongdouble : 2}
<add>array_precision = {_nx.single: 0,
<add> _nx.double: 1,
<add> _nx.longdouble: 2,
<add> _nx.csingle: 0,
<add> _nx.cdouble: 1,
<add> _nx.clongdouble: 2}
<ide> def common_type(*arrays):
<ide> """
<ide> Return a scalar type which is common to the input arrays.
<ide><path>numpy/lib/user_array.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> from numpy.core import (
<del> array, asarray, absolute, add, subtract, multiply, divide,
<del> remainder, power, left_shift, right_shift, bitwise_and, bitwise_or,
<del> bitwise_xor, invert, less, less_equal, not_equal, equal, greater,
<del> greater_equal, shape, reshape, arange, sin, sqrt, transpose
<del> )
<add> array, asarray, absolute, add, subtract, multiply, divide,
<add> remainder, power, left_shift, right_shift, bitwise_and, bitwise_or,
<add> bitwise_xor, invert, less, less_equal, not_equal, equal, greater,
<add> greater_equal, shape, reshape, arange, sin, sqrt, transpose
<add>)
<ide> from numpy.compat import long
<ide>
<add>
<ide> class container(object):
<add>
<ide> def __init__(self, data, dtype=None, copy=True):
<ide> self.array = array(data, dtype, copy=copy)
<ide>
<ide> def __repr__(self):
<ide> if len(self.shape) > 0:
<del> return self.__class__.__name__+repr(self.array)[len("array"):]
<add> return self.__class__.__name__ + repr(self.array)[len("array"):]
<ide> else:
<del> return self.__class__.__name__+"("+repr(self.array)+")"
<add> return self.__class__.__name__ + "(" + repr(self.array) + ")"
<ide>
<del> def __array__(self,t=None):
<del> if t: return self.array.astype(t)
<add> def __array__(self, t=None):
<add> if t:
<add> return self.array.astype(t)
<ide> return self.array
<ide>
<ide> # Array as sequence
<del> def __len__(self): return len(self.array)
<add> def __len__(self):
<add> return len(self.array)
<ide>
<ide> def __getitem__(self, index):
<ide> return self._rc(self.array[index])
<ide>
<ide> def __getslice__(self, i, j):
<ide> return self._rc(self.array[i:j])
<ide>
<del>
<ide> def __setitem__(self, index, value):
<ide> self.array[index] = asarray(value, self.dtype)
<add>
<ide> def __setslice__(self, i, j, value):
<ide> self.array[i:j] = asarray(value, self.dtype)
<ide>
<ide> def __abs__(self):
<ide> return self._rc(absolute(self.array))
<add>
<ide> def __neg__(self):
<ide> return self._rc(-self.array)
<ide>
<ide> def __add__(self, other):
<del> return self._rc(self.array+asarray(other))
<add> return self._rc(self.array + asarray(other))
<add>
<ide> __radd__ = __add__
<ide>
<ide> def __iadd__(self, other):
<ide> add(self.array, other, self.array)
<ide> return self
<ide>
<ide> def __sub__(self, other):
<del> return self._rc(self.array-asarray(other))
<add> return self._rc(self.array - asarray(other))
<add>
<ide> def __rsub__(self, other):
<del> return self._rc(asarray(other)-self.array)
<add> return self._rc(asarray(other) - self.array)
<add>
<ide> def __isub__(self, other):
<ide> subtract(self.array, other, self.array)
<ide> return self
<ide>
<ide> def __mul__(self, other):
<ide> return self._rc(multiply(self.array, asarray(other)))
<add>
<ide> __rmul__ = __mul__
<add>
<ide> def __imul__(self, other):
<ide> multiply(self.array, other, self.array)
<ide> return self
<ide>
<ide> def __div__(self, other):
<ide> return self._rc(divide(self.array, asarray(other)))
<add>
<ide> def __rdiv__(self, other):
<ide> return self._rc(divide(asarray(other), self.array))
<add>
<ide> def __idiv__(self, other):
<ide> divide(self.array, other, self.array)
<ide> return self
<ide>
<ide> def __mod__(self, other):
<ide> return self._rc(remainder(self.array, other))
<add>
<ide> def __rmod__(self, other):
<ide> return self._rc(remainder(other, self.array))
<add>
<ide> def __imod__(self, other):
<ide> remainder(self.array, other, self.array)
<ide> return self
<ide>
<ide> def __divmod__(self, other):
<ide> return (self._rc(divide(self.array, other)),
<ide> self._rc(remainder(self.array, other)))
<add>
<ide> def __rdivmod__(self, other):
<ide> return (self._rc(divide(other, self.array)),
<ide> self._rc(remainder(other, self.array)))
<ide>
<ide> def __pow__(self, other):
<ide> return self._rc(power(self.array, asarray(other)))
<add>
<ide> def __rpow__(self, other):
<ide> return self._rc(power(asarray(other), self.array))
<add>
<ide> def __ipow__(self, other):
<ide> power(self.array, other, self.array)
<ide> return self
<ide>
<ide> def __lshift__(self, other):
<ide> return self._rc(left_shift(self.array, other))
<add>
<ide> def __rshift__(self, other):
<ide> return self._rc(right_shift(self.array, other))
<add>
<ide> def __rlshift__(self, other):
<ide> return self._rc(left_shift(other, self.array))
<add>
<ide> def __rrshift__(self, other):
<ide> return self._rc(right_shift(other, self.array))
<add>
<ide> def __ilshift__(self, other):
<ide> left_shift(self.array, other, self.array)
<ide> return self
<add>
<ide> def __irshift__(self, other):
<ide> right_shift(self.array, other, self.array)
<ide> return self
<ide>
<ide> def __and__(self, other):
<ide> return self._rc(bitwise_and(self.array, other))
<add>
<ide> def __rand__(self, other):
<ide> return self._rc(bitwise_and(other, self.array))
<add>
<ide> def __iand__(self, other):
<ide> bitwise_and(self.array, other, self.array)
<ide> return self
<ide>
<ide> def __xor__(self, other):
<ide> return self._rc(bitwise_xor(self.array, other))
<add>
<ide> def __rxor__(self, other):
<ide> return self._rc(bitwise_xor(other, self.array))
<add>
<ide> def __ixor__(self, other):
<ide> bitwise_xor(self.array, other, self.array)
<ide> return self
<ide>
<ide> def __or__(self, other):
<ide> return self._rc(bitwise_or(self.array, other))
<add>
<ide> def __ror__(self, other):
<ide> return self._rc(bitwise_or(other, self.array))
<add>
<ide> def __ior__(self, other):
<ide> bitwise_or(self.array, other, self.array)
<ide> return self
<ide>
<ide> def __pos__(self):
<ide> return self._rc(self.array)
<add>
<ide> def __invert__(self):
<ide> return self._rc(invert(self.array))
<ide>
<ide> def _scalarfunc(self, func):
<ide> if len(self.shape) == 0:
<ide> return func(self[0])
<ide> else:
<del> raise TypeError("only rank-0 arrays can be converted to Python scalars.")
<add> raise TypeError(
<add> "only rank-0 arrays can be converted to Python scalars.")
<add>
<add> def __complex__(self):
<add> return self._scalarfunc(complex)
<ide>
<del> def __complex__(self): return self._scalarfunc(complex)
<del> def __float__(self): return self._scalarfunc(float)
<del> def __int__(self): return self._scalarfunc(int)
<del> def __long__(self): return self._scalarfunc(long)
<del> def __hex__(self): return self._scalarfunc(hex)
<del> def __oct__(self): return self._scalarfunc(oct)
<add> def __float__(self):
<add> return self._scalarfunc(float)
<ide>
<del> def __lt__(self, other): return self._rc(less(self.array, other))
<del> def __le__(self, other): return self._rc(less_equal(self.array, other))
<del> def __eq__(self, other): return self._rc(equal(self.array, other))
<del> def __ne__(self, other): return self._rc(not_equal(self.array, other))
<del> def __gt__(self, other): return self._rc(greater(self.array, other))
<del> def __ge__(self, other): return self._rc(greater_equal(self.array, other))
<add> def __int__(self):
<add> return self._scalarfunc(int)
<ide>
<del> def copy(self): return self._rc(self.array.copy())
<add> def __long__(self):
<add> return self._scalarfunc(long)
<ide>
<del> def tostring(self): return self.array.tostring()
<add> def __hex__(self):
<add> return self._scalarfunc(hex)
<ide>
<del> def byteswap(self): return self._rc(self.array.byteswap())
<add> def __oct__(self):
<add> return self._scalarfunc(oct)
<ide>
<del> def astype(self, typecode): return self._rc(self.array.astype(typecode))
<add> def __lt__(self, other):
<add> return self._rc(less(self.array, other))
<add>
<add> def __le__(self, other):
<add> return self._rc(less_equal(self.array, other))
<add>
<add> def __eq__(self, other):
<add> return self._rc(equal(self.array, other))
<add>
<add> def __ne__(self, other):
<add> return self._rc(not_equal(self.array, other))
<add>
<add> def __gt__(self, other):
<add> return self._rc(greater(self.array, other))
<add>
<add> def __ge__(self, other):
<add> return self._rc(greater_equal(self.array, other))
<add>
<add> def copy(self):
<add> return self._rc(self.array.copy())
<add>
<add> def tostring(self):
<add> return self.array.tostring()
<add>
<add> def byteswap(self):
<add> return self._rc(self.array.byteswap())
<add>
<add> def astype(self, typecode):
<add> return self._rc(self.array.astype(typecode))
<ide>
<ide> def _rc(self, a):
<del> if len(shape(a)) == 0: return a
<del> else: return self.__class__(a)
<add> if len(shape(a)) == 0:
<add> return a
<add> else:
<add> return self.__class__(a)
<ide>
<ide> def __array_wrap__(self, *args):
<ide> return self.__class__(args[0])
<ide> def __getattr__(self, attr):
<ide> # Test of class container
<ide> #############################################################
<ide> if __name__ == '__main__':
<del> temp=reshape(arange(10000), (100, 100))
<add> temp = reshape(arange(10000), (100, 100))
<ide>
<del> ua=container(temp)
<add> ua = container(temp)
<ide> # new object created begin test
<ide> print(dir(ua))
<del> print(shape(ua), ua.shape) # I have changed Numeric.py
<add> print(shape(ua), ua.shape) # I have changed Numeric.py
<ide>
<del> ua_small=ua[:3, :5]
<add> ua_small = ua[:3, :5]
<ide> print(ua_small)
<del> ua_small[0, 0]=10 # this did not change ua[0,0], which is not normal behavior
<add> # this did not change ua[0,0], which is not normal behavior
<add> ua_small[0, 0] = 10
<ide> print(ua_small[0, 0], ua[0, 0])
<del> print(sin(ua_small)/3.*6.+sqrt(ua_small**2))
<add> print(sin(ua_small) / 3. * 6. + sqrt(ua_small ** 2))
<ide> print(less(ua_small, 103), type(less(ua_small, 103)))
<del> print(type(ua_small*reshape(arange(15), shape(ua_small))))
<add> print(type(ua_small * reshape(arange(15), shape(ua_small))))
<ide> print(reshape(ua_small, (5, 3)))
<ide> print(transpose(ua_small))
<ide><path>numpy/lib/utils.py
<ide> class _Deprecate(object):
<ide> deprecate
<ide>
<ide> """
<add>
<ide> def __init__(self, old_name=None, new_name=None, message=None):
<ide> self.old_name = old_name
<ide> self.new_name = new_name
<ide> def deprecate(*args, **kwargs):
<ide> func : function
<ide> The function to be deprecated.
<ide> old_name : str, optional
<del> The name of the function to be deprecated. Default is None, in which
<del> case the name of `func` is used.
<add> The name of the function to be deprecated. Default is None, in
<add> which case the name of `func` is used.
<ide> new_name : str, optional
<del> The new name for the function. Default is None, in which case
<del> the deprecation message is that `old_name` is deprecated. If given,
<del> the deprecation message is that `old_name` is deprecated and `new_name`
<add> The new name for the function. Default is None, in which case the
<add> deprecation message is that `old_name` is deprecated. If given, the
<add> deprecation message is that `old_name` is deprecated and `new_name`
<ide> should be used instead.
<ide> message : str, optional
<del> Additional explanation of the deprecation. Displayed in the docstring
<del> after the warning.
<add> Additional explanation of the deprecation. Displayed in the
<add> docstring after the warning.
<ide>
<ide> Returns
<ide> -------
<ide> def deprecate(*args, **kwargs):
<ide>
<ide> Examples
<ide> --------
<del> Note that ``olduint`` returns a value after printing Deprecation Warning:
<add> Note that ``olduint`` returns a value after printing Deprecation
<add> Warning:
<ide>
<ide> >>> olduint = np.deprecate(np.uint)
<ide> >>> olduint(6)
<ide> def byte_bounds(a):
<ide> Parameters
<ide> ----------
<ide> a : ndarray
<del> Input array. It must conform to the Python-side of the array interface.
<add> Input array. It must conform to the Python-side of the array
<add> interface.
<ide>
<ide> Returns
<ide> -------
<ide> (low, high) : tuple of 2 integers
<del> The first integer is the first byte of the array, the second integer is
<del> just past the last byte of the array. If `a` is not contiguous it
<del> will not use every byte between the (`low`, `high`) values.
<add> The first integer is the first byte of the array, the second
<add> integer is just past the last byte of the array. If `a` is not
<add> contiguous it will not use every byte between the (`low`, `high`)
<add> values.
<ide>
<ide> Examples
<ide> --------
<ide> def byte_bounds(a):
<ide> a_data = ai['data'][0]
<ide> astrides = ai['strides']
<ide> ashape = ai['shape']
<del>
<ide> bytes_a = asarray(a).dtype.itemsize
<del>
<add>
<ide> a_low = a_high = a_data
<del> if astrides is None: # contiguous case
<add> if astrides is None:
<add> # contiguous case
<ide> a_high += a.size * bytes_a
<ide> else:
<ide> for shape, stride in zip(ashape, astrides):
<ide> def who(vardict=None):
<ide>
<ide> Notes
<ide> -----
<del> Prints out the name, shape, bytes and type of all of the ndarrays present
<del> in `vardict`.
<add> Prints out the name, shape, bytes and type of all of the ndarrays
<add> present in `vardict`.
<ide>
<ide> Examples
<ide> --------
<ide> def who(vardict=None):
<ide> idv = id(var)
<ide> if idv in cache.keys():
<ide> namestr = name + " (%s)" % cache[idv]
<del> original=0
<add> original = 0
<ide> else:
<ide> cache[idv] = name
<ide> namestr = name
<del> original=1
<add> original = 1
<ide> shapestr = " x ".join(map(str, var.shape))
<ide> bytestr = str(var.nbytes)
<ide> sta.append([namestr, shapestr, bytestr, var.dtype.name,
<ide> def who(vardict=None):
<ide> # NOTE: pydoc defines a help function which works simliarly to this
<ide> # except it uses a pager to take over the screen.
<ide>
<del># combine name and arguments and split to multiple lines of
<del># width characters. End lines on a comma and begin argument list
<del># indented with the rest of the arguments.
<add># combine name and arguments and split to multiple lines of width
<add># characters. End lines on a comma and begin argument list indented with
<add># the rest of the arguments.
<ide> def _split_line(name, arguments, width):
<ide> firstwidth = len(name)
<ide> k = firstwidth
<ide> def _info(obj, output=sys.stdout):
<ide> print("aligned: ", bp(obj.flags.aligned), file=output)
<ide> print("contiguous: ", bp(obj.flags.contiguous), file=output)
<ide> print("fortran: ", obj.flags.fortran, file=output)
<del> print("data pointer: %s%s" % (hex(obj.ctypes._as_parameter_.value), extra), file=output)
<add> print(
<add> "data pointer: %s%s" % (hex(obj.ctypes._as_parameter_.value), extra),
<add> file=output
<add> )
<ide> print("byteorder: ", end=' ', file=output)
<ide> if endian in ['|', '=']:
<ide> print("%s%s%s" % (tic, sys.byteorder, tic), file=output)
<ide> def _info(obj, output=sys.stdout):
<ide> print("type: %s" % obj.dtype, file=output)
<ide>
<ide>
<del>def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'):
<add>def info(object=None, maxwidth=76, output=sys.stdout, toplevel='numpy'):
<ide> """
<ide> Get help information for a function, class, or module.
<ide>
<ide> def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'):
<ide> object : object or str, optional
<ide> Input object or name to get information about. If `object` is a
<ide> numpy object, its docstring is given. If it is a string, available
<del> modules are searched for matching objects.
<del> If None, information about `info` itself is returned.
<add> modules are searched for matching objects. If None, information
<add> about `info` itself is returned.
<ide> maxwidth : int, optional
<ide> Printing width.
<ide> output : file like object, optional
<del> File like object that the output is written to, default is ``stdout``.
<del> The object has to be opened in 'w' or 'a' mode.
<add> File like object that the output is written to, default is
<add> ``stdout``. The object has to be opened in 'w' or 'a' mode.
<ide> toplevel : str, optional
<ide> Start search at this level.
<ide>
<ide> def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'):
<ide>
<ide> Notes
<ide> -----
<del> When used interactively with an object, ``np.info(obj)`` is equivalent to
<del> ``help(obj)`` on the Python prompt or ``obj?`` on the IPython prompt.
<add> When used interactively with an object, ``np.info(obj)`` is equivalent
<add> to ``help(obj)`` on the Python prompt or ``obj?`` on the IPython
<add> prompt.
<ide>
<ide> Examples
<ide> --------
<ide> def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'):
<ide> """
<ide> global _namedict, _dictlist
<ide> # Local import to speed up numpy's import time.
<del> import pydoc, inspect
<add> import pydoc
<add> import inspect
<ide>
<del> if hasattr(object, '_ppimport_importer') or \
<del> hasattr(object, '_ppimport_module'):
<add> if (hasattr(object, '_ppimport_importer') or
<add> hasattr(object, '_ppimport_module')):
<ide> object = object._ppimport_module
<ide> elif hasattr(object, '_ppimport_attr'):
<ide> object = object._ppimport_attr
<ide> def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'):
<ide> try:
<ide> obj = _namedict[namestr][object]
<ide> if id(obj) in objlist:
<del> print("\n *** Repeat reference found in %s *** " % namestr, file=output)
<add> print("\n "
<add> "*** Repeat reference found in %s *** " % namestr,
<add> file=output
<add> )
<ide> else:
<ide> objlist.append(id(obj))
<ide> print(" *** Found in %s ***" % namestr, file=output)
<ide> def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'):
<ide> if numfound == 0:
<ide> print("Help for %s not found." % object, file=output)
<ide> else:
<del> print("\n *** Total of %d references found. ***" % numfound, file=output)
<add> print("\n "
<add> "*** Total of %d references found. ***" % numfound,
<add> file=output
<add> )
<ide>
<ide> elif inspect.isfunction(object):
<ide> name = object.__name__
<ide> def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'):
<ide> arguments = "()"
<ide> try:
<ide> if hasattr(object, '__init__'):
<del> arguments = inspect.formatargspec(*inspect.getargspec(object.__init__.__func__))
<add> arguments = inspect.formatargspec(
<add> *inspect.getargspec(object.__init__.__func__)
<add> )
<ide> arglist = arguments.split(', ')
<ide> if len(arglist) > 1:
<ide> arglist[1] = "("+arglist[1]
<ide> def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'):
<ide> continue
<ide> thisobj = getattr(object, meth, None)
<ide> if thisobj is not None:
<del> methstr, other = pydoc.splitdoc(inspect.getdoc(thisobj) or "None")
<add> methstr, other = pydoc.splitdoc(
<add> inspect.getdoc(thisobj) or "None"
<add> )
<ide> print(" %s -- %s" % (meth, methstr), file=output)
<ide>
<ide> elif (sys.version_info[0] < 3
<ide> def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'):
<ide> print("Instance of class: ", object.__class__.__name__, file=output)
<ide> print(file=output)
<ide> if hasattr(object, '__call__'):
<del> arguments = inspect.formatargspec(*inspect.getargspec(object.__call__.__func__))
<add> arguments = inspect.formatargspec(
<add> *inspect.getargspec(object.__call__.__func__)
<add> )
<ide> arglist = arguments.split(', ')
<ide> if len(arglist) > 1:
<ide> arglist[1] = "("+arglist[1]
<ide> def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'):
<ide>
<ide> elif inspect.ismethod(object):
<ide> name = object.__name__
<del> arguments = inspect.formatargspec(*inspect.getargspec(object.__func__))
<add> arguments = inspect.formatargspec(
<add> *inspect.getargspec(object.__func__)
<add> )
<ide> arglist = arguments.split(', ')
<ide> if len(arglist) > 1:
<ide> arglist[1] = "("+arglist[1]
<ide> def source(object, output=sys.stdout):
<ide> Parameters
<ide> ----------
<ide> object : numpy object
<del> Input object. This can be any object (function, class, module, ...).
<add> Input object. This can be any object (function, class, module,
<add> ...).
<ide> output : file object, optional
<ide> If `output` not supplied then source code is printed to screen
<ide> (sys.stdout). File object must be created with either write 'w' or
<ide> def interp(x, xp, fp, left=None, right=None):
<ide> # and index: index in breadth-first namespace traversal
<ide> _lookfor_caches = {}
<ide>
<del># regexp whose match indicates that the string may contain a function signature
<add># regexp whose match indicates that the string may contain a function
<add># signature
<ide> _function_signature_re = re.compile(r"[a-z0-9_]+\(.*[,=].*\)", re.I)
<ide>
<ide> def lookfor(what, module=None, import_modules=True, regenerate=False,
<ide> def lookfor(what, module=None, import_modules=True, regenerate=False,
<ide> # XXX: maybe using a real stemming search engine would be better?
<ide> found = []
<ide> whats = str(what).lower().split()
<del> if not whats: return
<add> if not whats:
<add> return
<ide>
<ide> for name, (docstring, kind, index) in cache.items():
<ide> if kind in ('module', 'object'):
<ide> def _lookfor_generate_cache(module, import_modules, regenerate):
<ide> stack = [(module.__name__, module)]
<ide> while stack:
<ide> name, item = stack.pop(0)
<del> if id(item) in seen: continue
<add> if id(item) in seen:
<add> continue
<ide> seen[id(item)] = True
<ide>
<ide> index += 1
<ide> def _lookfor_generate_cache(module, import_modules, regenerate):
<ide> for mod_path in os.listdir(pth):
<ide> this_py = os.path.join(pth, mod_path)
<ide> init_py = os.path.join(pth, mod_path, '__init__.py')
<del> if os.path.isfile(this_py) and mod_path.endswith('.py'):
<add> if (os.path.isfile(this_py) and
<add> mod_path.endswith('.py')):
<ide> to_import = mod_path[:-3]
<ide> elif os.path.isfile(init_py):
<ide> to_import = mod_path
<ide> def _lookfor_generate_cache(module, import_modules, regenerate):
<ide>
<ide> try:
<ide> doc = inspect.getdoc(item)
<del> except NameError: # ref SWIG's NameError: Unknown C global variable
<add> except NameError:
<add> # ref SWIG's NameError: Unknown C global variable
<ide> doc = None
<ide> if doc is not None:
<ide> cache[name] = (doc, kind, index)
<ide> def visitConst(self, node, **kw):
<ide> return node.value
<ide>
<ide> def visitDict(self, node,**kw):
<del> return dict([(self.visit(k), self.visit(v)) for k, v in node.items])
<add> return dict(
<add> [(self.visit(k), self.visit(v)) for k, v in node.items]
<add> )
<ide>
<ide> def visitTuple(self, node, **kw):
<ide> return tuple([self.visit(i) for i in node.nodes])
<ide> def safe_eval(source):
<ide> Raises
<ide> ------
<ide> SyntaxError
<del> If the code has invalid Python syntax, or if it contains non-literal
<del> code.
<add> If the code has invalid Python syntax, or if it contains
<add> non-literal code.
<ide>
<ide> Examples
<ide> --------
<ide> def safe_eval(source):
<ide> import warnings
<ide>
<ide> with warnings.catch_warnings():
<del> # compiler package is deprecated for 3.x, which is already solved here
<add> # compiler package is deprecated for 3.x, which is already solved
<add> # here
<ide> warnings.simplefilter('ignore', DeprecationWarning)
<ide> try:
<ide> import compiler | 20 |
PHP | PHP | update deprecation description | e9694863787e55678e8f1a2d769c9c785403a2ca | <ide><path>src/Controller/Controller.php
<ide> public function redirect($url, int $status = 302): ?Response
<ide> * Any other parameters passed to this method will be passed as parameters to the new action.
<ide> * @param mixed ...$args Arguments passed to the action
<ide> * @return mixed Returns the return value of the called action
<del> * @deprecated 4.2.0 Refactor your code to not require changing the action for the same HTTP request.
<del> * Use actual redirection instead.
<add> * @deprecated 4.2.0 Refactor your code use `redirect()` instead of forwarding actions.
<ide> */
<ide> public function setAction(string $action, ...$args)
<ide> { | 1 |
Python | Python | remove broken test. closes | 7b42c5ed17a2430d66da88932ad4e81492d9b914 | <ide><path>tests/test_routers.py
<ide> def test_list_and_detail_route_decorators(self):
<ide> else:
<ide> method_map = 'get'
<ide> self.assertEqual(route.mapping[method_map], method_name)
<del>
<del>
<del>class TestRootWithAListlessViewset(TestCase):
<del> def setUp(self):
<del> class NoteViewSet(mixins.RetrieveModelMixin,
<del> viewsets.GenericViewSet):
<del> model = RouterTestModel
<del>
<del> self.router = DefaultRouter()
<del> self.router.register(r'notes', NoteViewSet)
<del> self.view = self.router.urls[0].callback
<del>
<del> def test_api_root(self):
<del> request = factory.get('/')
<del> response = self.view(request)
<del> self.assertEqual(response.data, {}) | 1 |
Javascript | Javascript | remove target argument from node.module#newchild | d703813c27fbef30a3f9c7a63189365cc514db01 | <ide><path>src/node.js
<ide> node.Module.prototype.loadScript = function (loadPromise) {
<ide> content = content.replace(/^\#\!.*/, '');
<ide>
<ide> function requireAsync (url) {
<del> return self.newChild(url, {});
<add> return self.newChild(url);
<ide> }
<ide>
<ide> function require (url) {
<ide> node.Module.prototype.loadScript = function (loadPromise) {
<ide> });
<ide> };
<ide>
<del>node.Module.prototype.newChild = function (path, target) {
<del> return node.loadModule(path, target, this);
<add>node.Module.prototype.newChild = function (path) {
<add> return node.loadModule(path, {}, this);
<ide> };
<ide>
<ide> node.Module.prototype.waitChildrenLoad = function (callback) { | 1 |
Javascript | Javascript | fix typo in code comment | ce2e5b3469560d0b1eccab9ce28ef6c6c57ada12 | <ide><path>packages/ember-views/lib/views/view.js
<ide> class:
<ide> eventManager: Ember.Object.create({
<ide> mouseEnter: function(event, view){
<ide> // view might be instance of either
<del> // OutsideView or InnerView depending on
<add> // OuterView or InnerView depending on
<ide> // where on the page the user interaction occured
<ide> }
<ide> }) | 1 |
PHP | PHP | update core cake.php to match other versions | 72b9eb540eaf16565d08461bb581ff2dda5ca238 | <ide><path>lib/Cake/Console/cake.php
<ide> * @since CakePHP(tm) v 1.2.0.5012
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<del>require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ShellDispatcher.php');
<add>$ds = DIRECTORY_SEPARATOR;
<add>$dispatcher = 'Cake' . $ds . 'Console' . $ds . 'ShellDispatcher.php';
<add>$found = false;
<add>$paths = explode(PATH_SEPARATOR, ini_get('include_path'));
<add>
<add>foreach ($paths as $path) {
<add> if (file_exists($path . $ds . $dispatcher)) {
<add> $found = $path;
<add> }
<add>}
<add>
<add>if (!$found && function_exists('ini_set')) {
<add> $root = dirname(dirname(dirname(__FILE__)));
<add> ini_set('include_path', __CAKE_PATH__ . PATH_SEPARATOR . ini_get('include_path'));
<add>}
<add>
<add>if (!include($dispatcher)) {
<add> trigger_error('Could not locate CakePHP core files.', E_USER_ERROR);
<add>}
<add>unset($paths, $path, $found, $dispatcher, $root, $ds);
<ide>
<ide> return ShellDispatcher::run($argv); | 1 |
Javascript | Javascript | remove unneeded code | 77ce7471397a6d37304af54c6d4bd10c4ded9e45 | <ide><path>lib/DelegatedModule.js
<ide> class DelegatedModule extends Module {
<ide> return obj;
<ide> }
<ide>
<del> deserialize(context) {
<del> super.deserialize(context);
<del> }
<del>
<ide> /**
<ide> * Assuming this module is in the cache. Update the (cached) module with
<ide> * the fresh module from the factory. Usually updates internal references
<ide> class DelegatedModule extends Module {
<ide> updateCacheModule(module) {
<ide> super.updateCacheModule(module);
<ide> const m = /** @type {DelegatedModule} */ (module);
<del> this.sourceRequest = m.sourceRequest;
<del> this.request = m.request;
<ide> this.delegationType = m.delegationType;
<ide> this.userRequest = m.userRequest;
<ide> this.originalRequest = m.originalRequest;
<ide><path>lib/DllModule.js
<ide> class DllModule extends Module {
<ide> }
<ide>
<ide> serialize(context) {
<add> context.write(this.name);
<ide> super.serialize(context);
<ide> }
<ide>
<ide> deserialize(context) {
<add> this.name = context.read();
<ide> super.deserialize(context);
<ide> }
<add>
<add> /**
<add> * Assuming this module is in the cache. Update the (cached) module with
<add> * the fresh module from the factory. Usually updates internal references
<add> * and properties.
<add> * @param {Module} module fresh module
<add> * @returns {void}
<add> */
<add> updateCacheModule(module) {
<add> super.updateCacheModule(module);
<add> this.dependencies = module.dependencies;
<add> }
<ide> }
<ide>
<ide> makeSerializable(DllModule, "webpack/lib/DllModule");
<ide><path>lib/dependencies/DelegatedSourceDependency.js
<ide> class DelegatedSourceDependency extends ModuleDependency {
<ide> get type() {
<ide> return "delegated source";
<ide> }
<del>
<del> serialize(context) {
<del> super.serialize(context);
<del> }
<del>
<del> deserialize(context) {
<del> super.deserialize(context);
<del> }
<ide> }
<ide>
<ide> makeSerializable(
<ide><path>lib/dependencies/EntryDependency.js
<ide> class EntryDependency extends ModuleDependency {
<ide> get type() {
<ide> return "entry";
<ide> }
<del>
<del> serialize(context) {
<del> super.serialize(context);
<del> }
<del>
<del> deserialize(context) {
<del> super.deserialize(context);
<del> }
<ide> }
<ide>
<ide> makeSerializable(EntryDependency, "webpack/lib/dependencies/EntryDependency"); | 4 |
Ruby | Ruby | fix tap name for linuxbrew | 45c61cdcdbe182d2ed2d8deb8dab2b3ab2507095 | <ide><path>Library/Homebrew/dev-cmd/pull.rb
<ide> def pull
<ide> elsif (api_match = arg.match HOMEBREW_PULL_API_REGEX)
<ide> _, user, repo, issue = *api_match
<ide> url = "https://github.com/#{user}/#{repo}/pull/#{issue}"
<del> tap = Tap.fetch(user, repo) if repo.start_with?("homebrew-")
<add> tap = Tap.fetch(user, repo) if repo.match?(HOMEBREW_OFFICIAL_REPO_PREFIXES_REGEX)
<ide> elsif (url_match = arg.match HOMEBREW_PULL_OR_COMMIT_URL_REGEX)
<ide> url, user, repo, issue = *url_match
<del> tap = Tap.fetch(user, repo) if repo.start_with?("homebrew-")
<add> tap = Tap.fetch(user, repo) if repo.match?(HOMEBREW_OFFICIAL_REPO_PREFIXES_REGEX)
<ide> else
<ide> odie "Not a GitHub pull request or commit: #{arg}"
<ide> end
<ide><path>Library/Homebrew/tap.rb
<ide> def self.fetch(*args)
<ide>
<ide> # We special case homebrew and linuxbrew so that users don't have to shift in a terminal.
<ide> user = user.capitalize if ["homebrew", "linuxbrew"].include? user
<del> repo = repo.delete_prefix "homebrew-"
<add> repo = repo.sub(HOMEBREW_OFFICIAL_REPO_PREFIXES_REGEX, "")
<ide>
<ide> return CoreTap.instance if ["Homebrew", "Linuxbrew"].include?(user) && ["core", "homebrew"].include?(repo)
<ide>
<ide><path>Library/Homebrew/tap_constants.rb
<ide> HOMEBREW_TAP_PATH_REGEX = Regexp.new(HOMEBREW_TAP_DIR_REGEX.source + %r{(?:/.*)?$}.source)
<ide> # match official taps' casks, e.g. homebrew/cask/somecask or homebrew/cask-versions/somecask
<ide> HOMEBREW_CASK_TAP_CASK_REGEX = %r{^(?:([Cc]askroom)/(cask|versions)|(homebrew)/(cask|cask-[\w-]+))/([\w+-.]+)$}.freeze
<add>HOMEBREW_OFFICIAL_REPO_PREFIXES_REGEX = /^(home|linux)brew-/.freeze | 3 |
Javascript | Javascript | update webdriverio config to match the new schema | ece51f97ac46086843b1a54f3802838a9d7de14c | <ide><path>spec/integration/helpers/start-atom.js
<ide> const ChromedriverPath = path.resolve(
<ide> 'bin',
<ide> 'chromedriver'
<ide> );
<del>const ChromedriverPort = 9515;
<add>const ChromedriverPort = 8082;
<ide> const ChromedriverURLBase = '/wd/hub';
<ide> const ChromedriverStatusURL = `http://localhost:${ChromedriverPort}${ChromedriverURLBase}/status`;
<ide>
<ide> const buildAtomClient = async (args, env) => {
<ide> host: 'localhost',
<ide> port: ChromedriverPort,
<ide> capabilities: {
<del> browserName: 'atom',
<del> chromeOptions: {
<add> browserName: 'chrome', //Webdriverio will figure it out on it's own, but I will leave it in case it's helpful in the future https://webdriver.io/docs/configurationfile.html
<add> 'goog:chromeOptions': {
<ide> binary: AtomLauncherPath,
<ide> args: [
<ide> `atom-path=${AtomPath}`,
<ide> Logs:\n${chromedriverLogs.join('\n')}`);
<ide> try {
<ide> client = await buildAtomClient(args, env);
<ide> } catch (error) {
<add> console.log(error)
<ide> jasmine
<ide> .getEnv()
<ide> .currentSpec.fail(`Unable to build Atom client.\n${error}`); | 1 |
Java | Java | fix ise in [http|rsocket]serviceproxyfactory | 5aeafc07616b9adcf0f37f6dd81f18ecf5faba6c | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/service/RSocketServiceProxyFactory.java
<ide> public void setCustomArgumentResolvers(List<RSocketServiceArgumentResolver> reso
<ide> @Deprecated(since = "6.0.0-RC2", forRemoval = true)
<ide> @Override
<ide> public void setEmbeddedValueResolver(StringValueResolver resolver) {
<del> Assert.state(this.beanStyleFactory != null, "RSocketServiceProxyFactory was created through the builder");
<del> this.beanStyleFactory.setEmbeddedValueResolver(resolver);
<add> if (this.beanStyleFactory != null) {
<add> this.beanStyleFactory.setEmbeddedValueResolver(resolver);
<add> }
<ide> }
<ide>
<ide> /**
<ide><path>spring-web/src/main/java/org/springframework/web/service/invoker/HttpServiceProxyFactory.java
<ide> public void setConversionService(ConversionService conversionService) {
<ide> @Deprecated(since = "6.0.0-RC2", forRemoval = true)
<ide> @Override
<ide> public void setEmbeddedValueResolver(StringValueResolver resolver) {
<del> Assert.state(this.beanStyleFactory != null, "HttpServiceProxyFactory was created through the builder");
<del> this.beanStyleFactory.setEmbeddedValueResolver(resolver);
<add> if (this.beanStyleFactory != null) {
<add> this.beanStyleFactory.setEmbeddedValueResolver(resolver);
<add> }
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | resolve merge conflict | 9cdb2588b4295d06627c3032699da536d324323f | <ide><path>controllers/story.js
<ide> function hotRank(timeValue, rank) {
<ide> */
<ide> var hotness;
<ide> var z = Math.log(rank) / Math.log(10);
<del> hotness = z + (timeValue / 45000000);
<add> hotness = z + (timeValue / 172800000);
<ide> return hotness;
<ide>
<ide> }
<ide><path>controllers/user.js
<ide> exports.getEmailSignup = function(req, res) {
<ide> */
<ide>
<ide> exports.postEmailSignup = function(req, res, next) {
<del> var errors = req.validationErrors();
<ide>
<del> if (errors) {
<del> req.flash('errors', errors);
<del> return res.redirect('/email-signup');
<del> }
<add>
<add> req.assert('email', 'valid email required').isEmail();
<add> var errors = req.validationErrors();
<add>
<add> if (errors) {
<add> req.flash('errors', errors);
<add> return res.redirect('/email-signup');
<add> }
<ide>
<ide> var possibleUserData = req.body;
<ide> | 2 |
Ruby | Ruby | require reporting before attempting to "shush" | 3b325d624ccb5b390356d61a3ba72f09709066a4 | <ide><path>activesupport/lib/active_support/core_ext/rexml.rb
<add>require 'active_support/core_ext/kernel/reporting'
<add>
<ide> # Fixes the rexml vulnerability disclosed at:
<ide> # http://www.ruby-lang.org/en/news/2008/08/23/dos-vulnerability-in-rexml/
<ide> # This fix is identical to rexml-expansion-fix version 1.0.1
<ide><path>activesupport/lib/active_support/xml_mini/rexml.rb
<add>require 'active_support/core_ext/kernel/reporting'
<ide> require 'active_support/core_ext/object/blank'
<ide>
<ide> # = XmlMini ReXML implementation | 2 |
Javascript | Javascript | move container border removal to the display layer | 30d63b0c502e0b55590bc4bd4fb12c7fa5a7a5d9 | <ide><path>src/core/annotation.js
<ide> var HighlightAnnotation = (function HighlightAnnotationClosure() {
<ide>
<ide> this.data.annotationType = AnnotationType.HIGHLIGHT;
<ide> this._preparePopup(parameters.dict);
<del>
<del> // PDF viewers completely ignore any border styles.
<del> this.data.borderStyle.setWidth(0);
<ide> }
<ide>
<ide> Util.inherit(HighlightAnnotation, Annotation, {});
<ide> var UnderlineAnnotation = (function UnderlineAnnotationClosure() {
<ide>
<ide> this.data.annotationType = AnnotationType.UNDERLINE;
<ide> this._preparePopup(parameters.dict);
<del>
<del> // PDF viewers completely ignore any border styles.
<del> this.data.borderStyle.setWidth(0);
<ide> }
<ide>
<ide> Util.inherit(UnderlineAnnotation, Annotation, {});
<ide> var SquigglyAnnotation = (function SquigglyAnnotationClosure() {
<ide>
<ide> this.data.annotationType = AnnotationType.SQUIGGLY;
<ide> this._preparePopup(parameters.dict);
<del>
<del> // PDF viewers completely ignore any border styles.
<del> this.data.borderStyle.setWidth(0);
<ide> }
<ide>
<ide> Util.inherit(SquigglyAnnotation, Annotation, {});
<ide> var StrikeOutAnnotation = (function StrikeOutAnnotationClosure() {
<ide>
<ide> this.data.annotationType = AnnotationType.STRIKEOUT;
<ide> this._preparePopup(parameters.dict);
<del>
<del> // PDF viewers completely ignore any border styles.
<del> this.data.borderStyle.setWidth(0);
<ide> }
<ide>
<ide> Util.inherit(StrikeOutAnnotation, Annotation, {});
<ide><path>src/display/annotation_layer.js
<ide> AnnotationElementFactory.prototype =
<ide> * @alias AnnotationElement
<ide> */
<ide> var AnnotationElement = (function AnnotationElementClosure() {
<del> function AnnotationElement(parameters, isRenderable) {
<add> function AnnotationElement(parameters, isRenderable, ignoreBorder) {
<ide> this.isRenderable = isRenderable || false;
<ide> this.data = parameters.data;
<ide> this.layer = parameters.layer;
<ide> var AnnotationElement = (function AnnotationElementClosure() {
<ide> this.renderInteractiveForms = parameters.renderInteractiveForms;
<ide>
<ide> if (isRenderable) {
<del> this.container = this._createContainer();
<add> this.container = this._createContainer(ignoreBorder);
<ide> }
<ide> }
<ide>
<ide> var AnnotationElement = (function AnnotationElementClosure() {
<ide> * Create an empty container for the annotation's HTML element.
<ide> *
<ide> * @private
<add> * @param {boolean} ignoreBorder
<ide> * @memberof AnnotationElement
<ide> * @returns {HTMLSectionElement}
<ide> */
<del> _createContainer: function AnnotationElement_createContainer() {
<add> _createContainer:
<add> function AnnotationElement_createContainer(ignoreBorder) {
<ide> var data = this.data, page = this.page, viewport = this.viewport;
<ide> var container = document.createElement('section');
<ide> var width = data.rect[2] - data.rect[0];
<ide> var AnnotationElement = (function AnnotationElementClosure() {
<ide> CustomStyle.setProp('transformOrigin', container,
<ide> -rect[0] + 'px ' + -rect[1] + 'px');
<ide>
<del> if (data.borderStyle.width > 0) {
<add> if (!ignoreBorder && data.borderStyle.width > 0) {
<ide> container.style.borderWidth = data.borderStyle.width + 'px';
<ide> if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
<ide> // Underline styles only have a bottom border, so we do not need
<ide> var HighlightAnnotationElement = (
<ide> function HighlightAnnotationElement(parameters) {
<ide> var isRenderable = !!(parameters.data.hasPopup ||
<ide> parameters.data.title || parameters.data.contents);
<del> AnnotationElement.call(this, parameters, isRenderable);
<add> AnnotationElement.call(this, parameters, isRenderable,
<add> /* ignoreBorder = */ true);
<ide> }
<ide>
<ide> Util.inherit(HighlightAnnotationElement, AnnotationElement, {
<ide> var HighlightAnnotationElement = (
<ide> if (!this.data.hasPopup) {
<ide> this._createPopup(this.container, null, this.data);
<ide> }
<del>
<ide> return this.container;
<ide> }
<ide> });
<ide> var UnderlineAnnotationElement = (
<ide> function UnderlineAnnotationElement(parameters) {
<ide> var isRenderable = !!(parameters.data.hasPopup ||
<ide> parameters.data.title || parameters.data.contents);
<del> AnnotationElement.call(this, parameters, isRenderable);
<add> AnnotationElement.call(this, parameters, isRenderable,
<add> /* ignoreBorder = */ true);
<ide> }
<ide>
<ide> Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
<ide> var UnderlineAnnotationElement = (
<ide> if (!this.data.hasPopup) {
<ide> this._createPopup(this.container, null, this.data);
<ide> }
<del>
<ide> return this.container;
<ide> }
<ide> });
<ide> var SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() {
<ide> function SquigglyAnnotationElement(parameters) {
<ide> var isRenderable = !!(parameters.data.hasPopup ||
<ide> parameters.data.title || parameters.data.contents);
<del> AnnotationElement.call(this, parameters, isRenderable);
<add> AnnotationElement.call(this, parameters, isRenderable,
<add> /* ignoreBorder = */ true);
<ide> }
<ide>
<ide> Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
<ide> var SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() {
<ide> if (!this.data.hasPopup) {
<ide> this._createPopup(this.container, null, this.data);
<ide> }
<del>
<ide> return this.container;
<ide> }
<ide> });
<ide> var StrikeOutAnnotationElement = (
<ide> function StrikeOutAnnotationElement(parameters) {
<ide> var isRenderable = !!(parameters.data.hasPopup ||
<ide> parameters.data.title || parameters.data.contents);
<del> AnnotationElement.call(this, parameters, isRenderable);
<add> AnnotationElement.call(this, parameters, isRenderable,
<add> /* ignoreBorder = */ true);
<ide> }
<ide>
<ide> Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
<ide> var StrikeOutAnnotationElement = (
<ide> if (!this.data.hasPopup) {
<ide> this._createPopup(this.container, null, this.data);
<ide> }
<del>
<ide> return this.container;
<ide> }
<ide> }); | 2 |
PHP | PHP | fix cs error | aeea5d8cba5dbff97557e4984867b9761be4c9d6 | <ide><path>src/Validation/Validator.php
<ide> protected function sortMessageAndWhen($first, $second, $method)
<ide> */
<ide> public function allowEmptyString($field, ?string $message = null, $when = true)
<ide> {
<del> list($message, $when) = $this->sortMessageAndWhen($message, $when, __METHOD__);
<add> [$message, $when] = $this->sortMessageAndWhen($message, $when, __METHOD__);
<ide>
<ide> return $this->allowEmptyFor($field, self::EMPTY_STRING, $when, $message);
<ide> }
<ide> public function notEmptyString($field, $message = null, $when = false)
<ide> */
<ide> public function allowEmptyArray(string $field, ?string $message = null, $when = true)
<ide> {
<del> list($message, $when) = $this->sortMessageAndWhen($message, $when, __METHOD__);
<add> [$message, $when] = $this->sortMessageAndWhen($message, $when, __METHOD__);
<ide>
<ide> return $this->allowEmptyFor($field, self::EMPTY_STRING | self::EMPTY_ARRAY, $when, $message);
<ide> }
<ide> public function notEmptyArray($field, $message = null, $when = false)
<ide> */
<ide> public function allowEmptyFile(string $field, ?string $message = null, $when = true)
<ide> {
<del> list($message, $when) = $this->sortMessageAndWhen($message, $when, __METHOD__);
<add> [$message, $when] = $this->sortMessageAndWhen($message, $when, __METHOD__);
<ide>
<ide> return $this->allowEmptyFor($field, self::EMPTY_FILE, $when, $message);
<ide> }
<ide> public function notEmptyFile($field, $message = null, $when = false)
<ide> */
<ide> public function allowEmptyDate(string $field, ?string $message = null, $when = true)
<ide> {
<del> list($message, $when) = $this->sortMessageAndWhen($message, $when, __METHOD__);
<add> [$message, $when] = $this->sortMessageAndWhen($message, $when, __METHOD__);
<ide>
<ide> return $this->allowEmptyFor($field, self::EMPTY_STRING | self::EMPTY_DATE, $when, $message);
<ide> }
<ide> public function notEmptyDate(string $field, ?string $message = null, $when = fal
<ide> */
<ide> public function allowEmptyTime(string $field, ?string $message = null, $when = true)
<ide> {
<del> list($message, $when) = $this->sortMessageAndWhen($message, $when, __METHOD__);
<add> [$message, $when] = $this->sortMessageAndWhen($message, $when, __METHOD__);
<ide>
<ide> return $this->allowEmptyFor($field, self::EMPTY_STRING | self::EMPTY_TIME, $when, $message);
<ide> }
<ide> public function notEmptyTime(string $field, ?string $message = null, $when = fal
<ide> */
<ide> public function allowEmptyDateTime(string $field, ?string $message = null, $when = true)
<ide> {
<del> list($message, $when) = $this->sortMessageAndWhen($message, $when, __METHOD__);
<add> [$message, $when] = $this->sortMessageAndWhen($message, $when, __METHOD__);
<ide>
<ide> return $this->allowEmptyFor($field, self::EMPTY_STRING | self::EMPTY_DATE | self::EMPTY_TIME, $when, $message);
<ide> }
<ide><path>tests/TestCase/Validation/ValidatorTest.php
<ide> public function testNotEmptyArray()
<ide> $this->assertFalse($validator->field('items')->isEmptyAllowed());
<ide>
<ide> $error = [
<del> 'items' => ['_empty' => 'not empty']
<add> 'items' => ['_empty' => 'not empty'],
<ide> ];
<ide> $data = ['items' => ''];
<ide> $result = $validator->errors($data);
<ide> public function testNotEmptyFile()
<ide> 'type' => '',
<ide> 'tmp_name' => '',
<ide> 'error' => UPLOAD_ERR_NO_FILE,
<del> ]
<add> ],
<ide> ];
<ide> $error = ['photo' => ['_empty' => 'required field']];
<ide> $this->assertSame($error, $validator->errors($data));
<ide> public function testNotEmptyFile()
<ide> 'type' => '',
<ide> 'tmp_name' => '',
<ide> 'error' => UPLOAD_ERR_FORM_SIZE,
<del> ]
<add> ],
<ide> ];
<ide> $this->assertEmpty($validator->errors($data));
<ide> }
<ide> public function testNotEmptyDate()
<ide> 'date' => [
<ide> 'year' => '',
<ide> 'month' => '',
<del> 'day' => ''
<add> 'day' => '',
<ide> ],
<ide> ];
<ide> $result = $validator->errors($data);
<ide> public function testNotEmptyDate()
<ide> 'date' => [
<ide> 'year' => 2019,
<ide> 'month' => 2,
<del> 'day' => 17
<del> ]
<add> 'day' => 17,
<add> ],
<ide> ];
<ide> $result = $validator->errors($data);
<ide> $this->assertEmpty($result);
<ide><path>tests/TestCase/View/Widget/RadioWidgetTest.php
<ide> public function testRenderComplexLabelAttributes()
<ide> 'options' => [
<ide> ['value' => 'r', 'text' => 'Red', 'label' => ['style' => 'color:red']],
<ide> ['value' => 'b', 'text' => 'Black', 'label' => ['data-test' => 'yes']],
<del> ]
<add> ],
<ide> ];
<ide> $result = $radio->render($data, $this->context);
<ide> $expected = [ | 3 |
Javascript | Javascript | add an example with custom loading component | f2bfcd01b0ea12a3dd267f7d714b6cdbccf4b1e9 | <ide><path>examples/with-dynamic-import/components/hello.js
<del>export default () => (
<del> <p>Hello World (imported dynamiclly) </p>
<del>)
<ide><path>examples/with-dynamic-import/components/hello1.js
<add>export default () => (
<add> <p>Hello World 1 (imported dynamiclly) </p>
<add>)
<ide><path>examples/with-dynamic-import/components/hello2.js
<add>export default () => (
<add> <p>Hello World 2 (imported dynamiclly) </p>
<add>)
<ide><path>examples/with-dynamic-import/pages/index.js
<ide> import Header from '../components/Header'
<ide> import Counter from '../components/Counter'
<ide> import dynamic from 'next/dynamic'
<ide>
<del>const DynamicComponent = dynamic(import('../components/hello'))
<add>const DynamicComponent = dynamic(import('../components/hello1'))
<add>const DynamicComponentWithCustomLoading = dynamic(
<add> import('../components/hello2'),
<add> {
<add> loading: () => (<p>...</p>)
<add> }
<add>)
<ide>
<ide> export default () => (
<ide> <div>
<ide> <Header />
<ide> <DynamicComponent />
<add> <DynamicComponentWithCustomLoading />
<ide> <p>HOME PAGE is here!</p>
<ide> <Counter />
<ide> </div>
<ide><path>lib/dynamic.js
<ide> import React from 'react'
<ide>
<ide> let currentChunks = []
<ide>
<del>export default function dynamicComponent (promise, Loading = () => (<p>Loading...</p>)) {
<add>export default function dynamicComponent (promise, options = {}) {
<ide> return class Comp extends React.Component {
<ide> constructor (...args) {
<ide> super(...args)
<add> this.LoadingComponent = options.loading ? options.loading : () => (<p>loading...</p>)
<ide> this.state = { AsyncComponent: null }
<ide> this.isServer = typeof window === 'undefined'
<ide> this.loadComponent()
<ide> export default function dynamicComponent (promise, Loading = () => (<p>Loading..
<ide>
<ide> render () {
<ide> const { AsyncComponent } = this.state
<del> if (!AsyncComponent) return (<Loading {...this.props} />)
<add> const { LoadingComponent } = this
<add> if (!AsyncComponent) return (<LoadingComponent {...this.props} />)
<ide>
<ide> return <AsyncComponent {...this.props} />
<ide> } | 5 |
Javascript | Javascript | add second argument to assert.throws() | 1377d5ac2e3d47940121a873806a03f13128691a | <ide><path>test/parallel/test-util-inspect-proxy.js
<ide> assert.strictEqual(processUtil.getProxyDetails({}), undefined);
<ide> // and the get function on the handler object defined above
<ide> // is actually invoked.
<ide> assert.throws(
<del> () => util.inspect(proxyObj)
<add> () => util.inspect(proxyObj),
<add> /^Error: Getter should not be called$/
<ide> );
<ide>
<ide> // Yo dawg, I heard you liked Proxy so I put a Proxy | 1 |
Java | Java | fix textinput contentsize | 7c268b31c25441ad56f08ab9f769a3efe90bfea9 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactContentSizeChangedEvent.java
<ide> public class ReactContentSizeChangedEvent extends Event<ReactTextChangedEvent> {
<ide>
<ide> public static final String EVENT_NAME = "topContentSizeChange";
<ide>
<del> private int mContentWidth;
<del> private int mContentHeight;
<add> private float mContentWidth;
<add> private float mContentHeight;
<ide>
<ide> public ReactContentSizeChangedEvent(
<ide> int viewId,
<del> int contentSizeWidth,
<del> int contentSizeHeight) {
<add> float contentSizeWidth,
<add> float contentSizeHeight) {
<ide> super(viewId);
<ide> mContentWidth = contentSizeWidth;
<ide> mContentHeight = contentSizeHeight;
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextChangedEvent.java
<ide> public class ReactTextChangedEvent extends Event<ReactTextChangedEvent> {
<ide> public static final String EVENT_NAME = "topChange";
<ide>
<ide> private String mText;
<del> private int mContentWidth;
<del> private int mContentHeight;
<add> private float mContentWidth;
<add> private float mContentHeight;
<ide> private int mEventCount;
<ide>
<ide> public ReactTextChangedEvent(
<ide> int viewId,
<ide> String text,
<del> int contentSizeWidth,
<del> int contentSizeHeight,
<add> float contentSizeWidth,
<add> float contentSizeHeight,
<ide> int eventCount) {
<ide> super(viewId);
<ide> mText = text;
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java
<ide> public void onTextChanged(CharSequence s, int start, int before, int count) {
<ide> new ReactTextChangedEvent(
<ide> mEditText.getId(),
<ide> s.toString(),
<del> (int) PixelUtil.toDIPFromPixel(contentWidth),
<del> (int) PixelUtil.toDIPFromPixel(contentHeight),
<add> PixelUtil.toDIPFromPixel(contentWidth),
<add> PixelUtil.toDIPFromPixel(contentHeight),
<ide> mEditText.incrementAndGetEventCounter()));
<ide>
<ide> mEventDispatcher.dispatchEvent(
<ide> public void onLayout() {
<ide> contentWidth = mEditText.getCompoundPaddingLeft() + mEditText.getLayout().getWidth() +
<ide> mEditText.getCompoundPaddingRight();
<ide> contentHeight = mEditText.getCompoundPaddingTop() + mEditText.getLayout().getHeight() +
<del> mEditText.getCompoundPaddingTop();
<add> mEditText.getCompoundPaddingBottom();
<ide> }
<ide>
<ide> if (contentWidth != mPreviousContentWidth || contentHeight != mPreviousContentHeight) {
<ide> public void onLayout() {
<ide> mEventDispatcher.dispatchEvent(
<ide> new ReactContentSizeChangedEvent(
<ide> mEditText.getId(),
<del> (int) PixelUtil.toDIPFromPixel(contentWidth),
<del> (int) PixelUtil.toDIPFromPixel(contentHeight)));
<add> PixelUtil.toDIPFromPixel(contentWidth),
<add> PixelUtil.toDIPFromPixel(contentHeight)));
<ide> }
<ide> }
<ide> } | 3 |
PHP | PHP | fix two testing cases in paginationpaginatortest | 9ef5b650f7dd7643f0f9a13063ec9dc0e4e7d7a6 | <ide><path>tests/Pagination/PaginationPaginatorTest.php
<ide> public function testPresenterCanGetAUrlRangeForAWindowOfLinks()
<ide>
<ide> public function testBootstrapPresenterCanGeneratorLinksForSlider()
<ide> {
<del> return;
<ide> $array = [];
<ide> for ($i = 1; $i <= 13; $i++)
<ide> $array[$i] = 'item'.$i;
<del> $p = new LengthAwarePaginator($array, count($array), 7, 1);
<add> $p = new LengthAwarePaginator($array, count($array), 1, 7);
<ide> $presenter = new BootstrapPresenter($p);
<ide>
<ide> $this->assertEquals(trim(file_get_contents(__DIR__.'/fixtures/slider.html')), $presenter->render());
<ide> public function testBootstrapPresenterCanGeneratorLinksForSlider()
<ide>
<ide> public function testBootstrapPresenterCanGeneratorLinksForTooCloseToBeginning()
<ide> {
<del> return;
<ide> $array = [];
<ide> for ($i = 1; $i <= 13; $i++)
<ide> $array[$i] = 'item'.$i;
<del> $p = new LengthAwarePaginator($array, count($array), 2, 1);
<add> $p = new LengthAwarePaginator($array, count($array), 1, 2);
<ide> $presenter = new BootstrapPresenter($p);
<ide>
<ide> $this->assertEquals(trim(file_get_contents(__DIR__.'/fixtures/beginning.html')), $presenter->render()); | 1 |
Python | Python | fix psutilversion plugin (#815) | 84e8759a8deae2060fc8731d7f11f03a32485985 | <ide><path>glances/plugins/glances_psutilversion.py
<ide> # You should have received a copy of the GNU Lesser General Public License
<ide> # along with this program. If not, see <http://www.gnu.org/licenses/>.
<ide>
<add>from glances.globals import psutil_version
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<ide>
<del>from psutil import __version__ as __psutil_version
<del>
<ide>
<ide> class Plugin(GlancesPlugin):
<del>
<ide> """Get the psutil version for client/server purposes.
<ide>
<ide> stats is a tuple
<ide> def update(self):
<ide> if self.input_method == 'local':
<ide> # PsUtil version only available in local
<ide> try:
<del> self.stats = tuple([int(num) for num in __psutil_version.split('.')])
<add> self.stats = tuple([int(num) for num in psutil_version.split('.')])
<ide> except NameError:
<ide> pass
<ide> else: | 1 |
Javascript | Javascript | pass config options to package transpilers | 4f7b22c84edd00de5718dbca0158cdb6b99077f2 | <ide><path>src/package-transpilation-registry.js
<ide> PackageTranspilationRegistry.prototype.transpileWithPackageTranspiler = function
<ide> if (transpilerPath) {
<ide> this.transpilerPaths[transpilerPath] = true
<ide> var transpiler = require(transpilerPath)
<del> var result = transpiler.compile(sourceCode, filePath)
<add> var result = transpiler.compile(sourceCode, filePath, config.options || {})
<ide> if (result === undefined) {
<ide> return sourceCode
<ide> } else { | 1 |
Ruby | Ruby | condense artifact entries | 5c7e7eebe4d779dca0d5aaaec440105fb3e85c83 | <ide><path>Library/Homebrew/cask/cask.rb
<ide> def to_hash_with_variations
<ide>
<ide> def artifacts_list
<ide> artifacts.map do |artifact|
<del> if artifact.is_a? Artifact::AbstractFlightBlock
<del> { type: artifact.summarize }
<add> key, value = if artifact.is_a? Artifact::AbstractFlightBlock
<add> artifact.summarize
<ide> else
<del> {
<del> type: artifact.class.dsl_key,
<del> args: to_h_gsubs(artifact.to_args),
<del> }
<add> [artifact.class.dsl_key, to_h_gsubs(artifact.to_args)]
<ide> end
<add>
<add> { key => value }
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/test/cask/cmd/list_spec.rb
<ide> "sha256": "67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94",
<ide> "artifacts": [
<ide> {
<del> "type": "app",
<del> "args": [
<add> "app": [
<ide> "Caffeine.app"
<ide> ]
<ide> },
<ide> {
<del> "type": "zap",
<del> "args": [
<add> "zap": [
<ide> {
<ide> "trash": "$HOME/support/fixtures/cask/caffeine/org.example.caffeine.plist"
<ide> }
<ide> "sha256": "e44ffa103fbf83f55c8d0b1bea309a43b2880798dae8620b1ee8da5e1095ec68",
<ide> "artifacts": [
<ide> {
<del> "type": "app",
<del> "args": [
<add> "app": [
<ide> "Transmission.app"
<ide> ]
<ide> }
<ide> "sha256": "67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94",
<ide> "artifacts": [
<ide> {
<del> "type": "app",
<del> "args": [
<add> "app": [
<ide> "Caffeine.app"
<ide> ]
<ide> }
<ide> "sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b",
<ide> "artifacts": [
<ide> {
<del> "type": "app",
<del> "args": [
<add> "app": [
<ide> "ThirdParty.app"
<ide> ]
<ide> } | 2 |
Java | Java | add spel support for increment/decrement operators | f64325882da41bb128dec1b6d687b6eb6525623f | <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ExpressionState.java
<ide> /*
<del> * Copyright 2002-2011 the original author or authors.
<add> * Copyright 2002-2012 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.expression.OperatorOverloader;
<ide> import org.springframework.expression.PropertyAccessor;
<ide> import org.springframework.expression.TypeComparator;
<add>import org.springframework.expression.TypeConverter;
<ide> import org.springframework.expression.TypedValue;
<ide>
<ide> /**
<ide> public Object convertValue(Object value, TypeDescriptor targetTypeDescriptor) th
<ide> return this.relatedContext.getTypeConverter().convertValue(value, TypeDescriptor.forObject(value), targetTypeDescriptor);
<ide> }
<ide>
<add> public TypeConverter getTypeConverter() {
<add> return this.relatedContext.getTypeConverter();
<add> }
<add>
<ide> public Object convertValue(TypedValue value, TypeDescriptor targetTypeDescriptor) throws EvaluationException {
<ide> Object val = value.getValue();
<ide> return this.relatedContext.getTypeConverter().convertValue(val, TypeDescriptor.forObject(val), targetTypeDescriptor);
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java
<ide> public enum SpelMessage {
<ide> MISSING_ARRAY_DIMENSION(Kind.ERROR, 1063, "A required array dimension has not been specified"), //
<ide> INITIALIZER_LENGTH_INCORRECT(
<ide> Kind.ERROR, 1064, "array initializer size does not match array dimensions"), //
<del> UNEXPECTED_ESCAPE_CHAR(Kind.ERROR,1065,"unexpected escape character.");
<add> UNEXPECTED_ESCAPE_CHAR(Kind.ERROR,1065,"unexpected escape character."), //
<add> OPERAND_NOT_INCREMENTABLE(Kind.ERROR,1066,"the expression component ''{0}'' does not support increment"), //
<add> OPERAND_NOT_DECREMENTABLE(Kind.ERROR,1067,"the expression component ''{0}'' does not support decrement"), //
<add> NOT_ASSIGNABLE(Kind.ERROR,1068,"the expression component ''{0}'' is not assignable"), //
<ide> ;
<ide>
<ide> private Kind kind;
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/AstUtils.java
<ide> /*
<del> * Copyright 2010 the original author or authors.
<add> * Copyright 2010-2012 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public class AstUtils {
<ide> * @param targetType the type upon which property access is being attempted
<ide> * @return a list of resolvers that should be tried in order to access the property
<ide> */
<del> public static List<PropertyAccessor> getPropertyAccessorsToTry(Class<?> targetType, ExpressionState state) {
<add> public static List<PropertyAccessor> getPropertyAccessorsToTry(Class<?> targetType, List<PropertyAccessor> propertyAccessors) {
<ide> List<PropertyAccessor> specificAccessors = new ArrayList<PropertyAccessor>();
<ide> List<PropertyAccessor> generalAccessors = new ArrayList<PropertyAccessor>();
<del> for (PropertyAccessor resolver : state.getPropertyAccessors()) {
<add> for (PropertyAccessor resolver : propertyAccessors) {
<ide> Class<?>[] targets = resolver.getSpecificTargetClasses();
<ide> if (targets == null) { // generic resolver that says it can be used for any type
<ide> generalAccessors.add(resolver);
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/CompoundExpression.java
<ide> /*
<del> * Copyright 2002-2009 the original author or authors.
<add> * Copyright 2002-2012 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public CompoundExpression(int pos,SpelNodeImpl... expressionComponents) {
<ide> throw new IllegalStateException("Dont build compound expression less than one entry: "+expressionComponents.length);
<ide> }
<ide> }
<del>
<ide>
<del> /**
<del> * Evalutes a compound expression. This involves evaluating each piece in turn and the return value from each piece
<del> * is the active context object for the subsequent piece.
<del> * @param state the state in which the expression is being evaluated
<del> * @return the final value from the last piece of the compound expression
<del> */
<ide> @Override
<del> public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
<add> protected ValueRef getValueRef(ExpressionState state) throws EvaluationException {
<add> if (getChildCount()==1) {
<add> return children[0].getValueRef(state);
<add> }
<ide> TypedValue result = null;
<ide> SpelNodeImpl nextNode = null;
<ide> try {
<ide> nextNode = children[0];
<ide> result = nextNode.getValueInternal(state);
<del> for (int i = 1; i < getChildCount(); i++) {
<add> int cc = getChildCount();
<add> for (int i = 1; i < cc-1; i++) {
<ide> try {
<ide> state.pushActiveContextObject(result);
<ide> nextNode = children[i];
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> state.popActiveContextObject();
<ide> }
<ide> }
<add> try {
<add> state.pushActiveContextObject(result);
<add> nextNode = children[cc-1];
<add> return nextNode.getValueRef(state);
<add> } finally {
<add> state.popActiveContextObject();
<add> }
<ide> } catch (SpelEvaluationException ee) {
<del> // Correct the position for the error before rethrowing
<add> // Correct the position for the error before re-throwing
<ide> ee.setPosition(nextNode.getStartPosition());
<ide> throw ee;
<ide> }
<del> return result;
<add> }
<add>
<add> /**
<add> * Evaluates a compound expression. This involves evaluating each piece in turn and the return value from each piece
<add> * is the active context object for the subsequent piece.
<add> * @param state the state in which the expression is being evaluated
<add> * @return the final value from the last piece of the compound expression
<add> */
<add> @Override
<add> public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
<add> return getValueRef(state).getValue();
<ide> }
<ide>
<ide> @Override
<ide> public void setValue(ExpressionState state, Object value) throws EvaluationException {
<del> if (getChildCount() == 1) {
<del> getChild(0).setValue(state, value);
<del> return;
<del> }
<del> TypedValue ctx = children[0].getValueInternal(state);
<del> for (int i = 1; i < getChildCount() - 1; i++) {
<del> try {
<del> state.pushActiveContextObject(ctx);
<del> ctx = children[i].getValueInternal(state);
<del> } finally {
<del> state.popActiveContextObject();
<del> }
<del> }
<del> try {
<del> state.pushActiveContextObject(ctx);
<del> getChild(getChildCount() - 1).setValue(state, value);
<del> } finally {
<del> state.popActiveContextObject();
<del> }
<add> getValueRef(state).setValue(value);
<ide> }
<ide>
<ide> @Override
<ide> public boolean isWritable(ExpressionState state) throws EvaluationException {
<del> if (getChildCount() == 1) {
<del> return getChild(0).isWritable(state);
<del> }
<del> TypedValue ctx = children[0].getValueInternal(state);
<del> for (int i = 1; i < getChildCount() - 1; i++) {
<del> try {
<del> state.pushActiveContextObject(ctx);
<del> ctx = children[i].getValueInternal(state);
<del> } finally {
<del> state.popActiveContextObject();
<del> }
<del> }
<del> try {
<del> state.pushActiveContextObject(ctx);
<del> return getChild(getChildCount() - 1).isWritable(state);
<del> } finally {
<del> state.popActiveContextObject();
<del> }
<add> return getValueRef(state).isWritable();
<ide> }
<ide>
<ide> @Override
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java
<ide> /*
<del> * Copyright 2002-2010 the original author or authors.
<add> * Copyright 2002-2012 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.expression.EvaluationContext;
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.PropertyAccessor;
<add>import org.springframework.expression.TypeConverter;
<ide> import org.springframework.expression.TypedValue;
<ide> import org.springframework.expression.spel.ExpressionState;
<ide> import org.springframework.expression.spel.SpelEvaluationException;
<ide> import org.springframework.expression.spel.SpelMessage;
<ide> import org.springframework.expression.spel.support.ReflectivePropertyAccessor;
<ide>
<ide> /**
<del> * An Indexer can index into some proceeding structure to access a particular piece of it.
<del> * Supported structures are: strings/collections (lists/sets)/arrays
<add> * An Indexer can index into some proceeding structure to access a particular
<add> * piece of it. Supported structures are: strings/collections
<add> * (lists/sets)/arrays
<ide> *
<ide> * @author Andy Clement
<ide> * @since 3.0
<ide> // TODO support correct syntax for multidimensional [][][] and not [,,,]
<ide> public class Indexer extends SpelNodeImpl {
<ide>
<del> // These fields are used when the indexer is being used as a property read accessor. If the name and
<del> // target type match these cached values then the cachedReadAccessor is used to read the property.
<del> // If they do not match, the correct accessor is discovered and then cached for later use.
<add> // These fields are used when the indexer is being used as a property read accessor.
<add> // If the name and target type match these cached values then the cachedReadAccessor
<add> // is used to read the property. If they do not match, the correct accessor is
<add> // discovered and then cached for later use.
<ide> private String cachedReadName;
<ide> private Class<?> cachedReadTargetType;
<ide> private PropertyAccessor cachedReadAccessor;
<ide>
<del> // These fields are used when the indexer is being used as a property write accessor. If the name and
<del> // target type match these cached values then the cachedWriteAccessor is used to write the property.
<del> // If they do not match, the correct accessor is discovered and then cached for later use.
<add> // These fields are used when the indexer is being used as a property write accessor.
<add> // If the name and target type match these cached values then the cachedWriteAccessor
<add> // is used to write the property. If they do not match, the correct accessor is
<add> // discovered and then cached for later use.
<ide> private String cachedWriteName;
<ide> private Class<?> cachedWriteTargetType;
<ide> private PropertyAccessor cachedWriteAccessor;
<del>
<ide>
<ide> public Indexer(int pos, SpelNodeImpl expr) {
<ide> super(pos, expr);
<ide> }
<ide>
<ide> @Override
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
<del> TypedValue context = state.getActiveContextObject();
<del> Object targetObject = context.getValue();
<del> TypeDescriptor targetObjectTypeDescriptor = context.getTypeDescriptor();
<del> TypedValue indexValue = null;
<del> Object index = null;
<del>
<del> // This first part of the if clause prevents a 'double dereference' of the property (SPR-5847)
<del> if (targetObject instanceof Map && (children[0] instanceof PropertyOrFieldReference)) {
<del> PropertyOrFieldReference reference = (PropertyOrFieldReference)children[0];
<del> index = reference.getName();
<del> indexValue = new TypedValue(index);
<add> return getValueRef(state).getValue();
<add> }
<add>
<add> @Override
<add> public void setValue(ExpressionState state, Object newValue) throws EvaluationException {
<add> getValueRef(state).setValue(newValue);
<add> }
<add>
<add> @Override
<add> public boolean isWritable(ExpressionState expressionState)
<add> throws SpelEvaluationException {
<add> return true;
<add> }
<add>
<add> class ArrayIndexingValueRef implements ValueRef {
<add>
<add> private TypeConverter typeConverter;
<add> private Object array;
<add> private int idx;
<add> private TypeDescriptor typeDescriptor;
<add>
<add> ArrayIndexingValueRef(TypeConverter typeConverter, Object array,
<add> int idx, TypeDescriptor typeDescriptor) {
<add> this.typeConverter = typeConverter;
<add> this.array = array;
<add> this.idx = idx;
<add> this.typeDescriptor = typeDescriptor;
<ide> }
<del> else {
<del> // In case the map key is unqualified, we want it evaluated against the root object so
<del> // temporarily push that on whilst evaluating the key
<del> try {
<del> state.pushActiveContextObject(state.getRootContextObject());
<del> indexValue = children[0].getValueInternal(state);
<del> index = indexValue.getValue();
<del> }
<del> finally {
<del> state.popActiveContextObject();
<del> }
<add>
<add> public TypedValue getValue() {
<add> Object arrayElement = accessArrayElement(array, idx);
<add> return new TypedValue(arrayElement,
<add> typeDescriptor.elementTypeDescriptor(arrayElement));
<ide> }
<ide>
<del> // Indexing into a Map
<del> if (targetObject instanceof Map) {
<del> Object key = index;
<del> if (targetObjectTypeDescriptor.getMapKeyTypeDescriptor() != null) {
<del> key = state.convertValue(key, targetObjectTypeDescriptor.getMapKeyTypeDescriptor());
<add> public void setValue(Object newValue) {
<add> setArrayElement(typeConverter, array, idx, newValue, typeDescriptor
<add> .getElementTypeDescriptor().getType());
<add> }
<add>
<add> public boolean isWritable() {
<add> return true;
<add> }
<add> }
<add>
<add> @SuppressWarnings({ "rawtypes", "unchecked" })
<add> class MapIndexingValueRef implements ValueRef {
<add>
<add> private TypeConverter typeConverter;
<add> private Map map;
<add> private Object key;
<add> private TypeDescriptor mapEntryTypeDescriptor;
<add>
<add> MapIndexingValueRef(TypeConverter typeConverter, Map map, Object key,
<add> TypeDescriptor mapEntryTypeDescriptor) {
<add> this.typeConverter = typeConverter;
<add> this.map = map;
<add> this.key = key;
<add> this.mapEntryTypeDescriptor = mapEntryTypeDescriptor;
<add> }
<add>
<add> public TypedValue getValue() {
<add> Object value = map.get(key);
<add> return new TypedValue(value,
<add> mapEntryTypeDescriptor.getMapValueTypeDescriptor(value));
<add> }
<add>
<add> public void setValue(Object newValue) {
<add> if (mapEntryTypeDescriptor.getMapValueTypeDescriptor() != null) {
<add> newValue = typeConverter.convertValue(newValue,
<add> TypeDescriptor.forObject(newValue),
<add> mapEntryTypeDescriptor.getMapValueTypeDescriptor());
<ide> }
<del> Object value = ((Map<?, ?>) targetObject).get(key);
<del> return new TypedValue(value, targetObjectTypeDescriptor.getMapValueTypeDescriptor(value));
<add> map.put(key, newValue);
<ide> }
<del>
<del> if (targetObject == null) {
<del> throw new SpelEvaluationException(getStartPosition(),SpelMessage.CANNOT_INDEX_INTO_NULL_VALUE);
<add>
<add> public boolean isWritable() {
<add> return true;
<ide> }
<del>
<del> // if the object is something that looks indexable by an integer, attempt to treat the index value as a number
<del> if (targetObject instanceof Collection || targetObject.getClass().isArray() || targetObject instanceof String) {
<del> int idx = (Integer) state.convertValue(index, TypeDescriptor.valueOf(Integer.class));
<del> if (targetObject.getClass().isArray()) {
<del> Object arrayElement = accessArrayElement(targetObject, idx);
<del> return new TypedValue(arrayElement, targetObjectTypeDescriptor.elementTypeDescriptor(arrayElement));
<del> } else if (targetObject instanceof Collection) {
<del> Collection c = (Collection) targetObject;
<del> if (idx >= c.size()) {
<del> if (!growCollection(state, targetObjectTypeDescriptor, idx, c)) {
<del> throw new SpelEvaluationException(getStartPosition(),SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS, c.size(), idx);
<del> }
<add>
<add> }
<add>
<add> class PropertyIndexingValueRef implements ValueRef {
<add>
<add> private Object targetObject;
<add> private String name;
<add> private EvaluationContext eContext;
<add> private TypeDescriptor td;
<add>
<add> public PropertyIndexingValueRef(Object targetObject, String value,
<add> EvaluationContext evaluationContext,
<add> TypeDescriptor targetObjectTypeDescriptor) {
<add> this.targetObject = targetObject;
<add> this.name = value;
<add> this.eContext = evaluationContext;
<add> this.td = targetObjectTypeDescriptor;
<add> }
<add>
<add> public TypedValue getValue() {
<add> Class<?> targetObjectRuntimeClass = getObjectClass(targetObject);
<add>
<add> try {
<add> if (cachedReadName != null
<add> && cachedReadName.equals(name)
<add> && cachedReadTargetType != null
<add> && cachedReadTargetType
<add> .equals(targetObjectRuntimeClass)) {
<add> // it is OK to use the cached accessor
<add> return cachedReadAccessor
<add> .read(eContext, targetObject, name);
<ide> }
<del> int pos = 0;
<del> for (Object o : c) {
<del> if (pos == idx) {
<del> return new TypedValue(o, targetObjectTypeDescriptor.elementTypeDescriptor(o));
<add>
<add> List<PropertyAccessor> accessorsToTry = AstUtils
<add> .getPropertyAccessorsToTry(targetObjectRuntimeClass,
<add> eContext.getPropertyAccessors());
<add>
<add> if (accessorsToTry != null) {
<add> for (PropertyAccessor accessor : accessorsToTry) {
<add> if (accessor.canRead(eContext, targetObject, name)) {
<add> if (accessor instanceof ReflectivePropertyAccessor) {
<add> accessor = ((ReflectivePropertyAccessor) accessor)
<add> .createOptimalAccessor(eContext,
<add> targetObject, name);
<add> }
<add> cachedReadAccessor = accessor;
<add> cachedReadName = name;
<add> cachedReadTargetType = targetObjectRuntimeClass;
<add> return accessor.read(eContext, targetObject, name);
<add> }
<ide> }
<del> pos++;
<del> }
<del> } else if (targetObject instanceof String) {
<del> String ctxString = (String) targetObject;
<del> if (idx >= ctxString.length()) {
<del> throw new SpelEvaluationException(getStartPosition(),SpelMessage.STRING_INDEX_OUT_OF_BOUNDS, ctxString.length(), idx);
<ide> }
<del> return new TypedValue(String.valueOf(ctxString.charAt(idx)));
<add> } catch (AccessException e) {
<add> throw new SpelEvaluationException(getStartPosition(), e,
<add> SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE,
<add> td.toString());
<ide> }
<add> throw new SpelEvaluationException(getStartPosition(),
<add> SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, td.toString());
<ide> }
<del>
<del> // Try and treat the index value as a property of the context object
<del> // TODO could call the conversion service to convert the value to a String
<del> if (indexValue.getTypeDescriptor().getType()==String.class) {
<del> Class<?> targetObjectRuntimeClass = getObjectClass(targetObject);
<del> String name = (String)indexValue.getValue();
<del> EvaluationContext eContext = state.getEvaluationContext();
<add>
<add> public void setValue(Object newValue) {
<add> Class<?> contextObjectClass = getObjectClass(targetObject);
<ide>
<ide> try {
<del> if (cachedReadName!=null && cachedReadName.equals(name) && cachedReadTargetType!=null && cachedReadTargetType.equals(targetObjectRuntimeClass)) {
<add> if (cachedWriteName != null && cachedWriteName.equals(name)
<add> && cachedWriteTargetType != null
<add> && cachedWriteTargetType.equals(contextObjectClass)) {
<ide> // it is OK to use the cached accessor
<del> return cachedReadAccessor.read(eContext, targetObject, name);
<add> cachedWriteAccessor.write(eContext, targetObject, name,
<add> newValue);
<add> return;
<ide> }
<del>
<del> List<PropertyAccessor> accessorsToTry = AstUtils.getPropertyAccessorsToTry(targetObjectRuntimeClass, state);
<del>
<del> if (accessorsToTry != null) {
<add>
<add> List<PropertyAccessor> accessorsToTry = AstUtils
<add> .getPropertyAccessorsToTry(contextObjectClass,
<add> eContext.getPropertyAccessors());
<add> if (accessorsToTry != null) {
<ide> for (PropertyAccessor accessor : accessorsToTry) {
<del> if (accessor.canRead(eContext, targetObject, name)) {
<del> if (accessor instanceof ReflectivePropertyAccessor) {
<del> accessor = ((ReflectivePropertyAccessor)accessor).createOptimalAccessor(eContext, targetObject, name);
<del> }
<del> this.cachedReadAccessor = accessor;
<del> this.cachedReadName = name;
<del> this.cachedReadTargetType = targetObjectRuntimeClass;
<del> return accessor.read(eContext, targetObject, name);
<del> }
<add> if (accessor.canWrite(eContext, targetObject, name)) {
<add> cachedWriteName = name;
<add> cachedWriteTargetType = contextObjectClass;
<add> cachedWriteAccessor = accessor;
<add> accessor.write(eContext, targetObject, name,
<add> newValue);
<add> return;
<add> }
<ide> }
<ide> }
<del> } catch (AccessException e) {
<del> throw new SpelEvaluationException(getStartPosition(), e, SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, targetObjectTypeDescriptor.toString());
<add> } catch (AccessException ae) {
<add> throw new SpelEvaluationException(getStartPosition(), ae,
<add> SpelMessage.EXCEPTION_DURING_PROPERTY_WRITE, name,
<add> ae.getMessage());
<ide> }
<ide> }
<del>
<del> throw new SpelEvaluationException(getStartPosition(),SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, targetObjectTypeDescriptor.toString());
<del> }
<del>
<del> @Override
<del> public boolean isWritable(ExpressionState expressionState) throws SpelEvaluationException {
<del> return true;
<add>
<add> public boolean isWritable() {
<add> return true;
<add> }
<ide> }
<del>
<del> @SuppressWarnings("unchecked")
<del> @Override
<del> public void setValue(ExpressionState state, Object newValue) throws EvaluationException {
<del> TypedValue contextObject = state.getActiveContextObject();
<del> Object targetObject = contextObject.getValue();
<del> TypeDescriptor targetObjectTypeDescriptor = contextObject.getTypeDescriptor();
<del> TypedValue index = children[0].getValueInternal(state);
<ide>
<del> if (targetObject == null) {
<del> throw new SpelEvaluationException(SpelMessage.CANNOT_INDEX_INTO_NULL_VALUE);
<add> @SuppressWarnings({ "rawtypes", "unchecked" })
<add> class CollectionIndexingValueRef implements ValueRef {
<add>
<add> private TypeConverter typeConverter;
<add> private Collection collection;
<add> private int index;
<add> private TypeDescriptor collectionEntryTypeDescriptor;
<add> private boolean growCollection;
<add>
<add> CollectionIndexingValueRef(Collection collection, int index,
<add> TypeDescriptor collectionEntryTypeDescriptor, TypeConverter typeConverter, boolean growCollection) {
<add> this.typeConverter = typeConverter;
<add> this.growCollection = growCollection;
<add> this.collection = collection;
<add> this.index = index;
<add> this.collectionEntryTypeDescriptor = collectionEntryTypeDescriptor;
<ide> }
<del> // Indexing into a Map
<del> if (targetObject instanceof Map) {
<del> Map map = (Map) targetObject;
<del> Object key = index.getValue();
<del> if (targetObjectTypeDescriptor.getMapKeyTypeDescriptor() != null) {
<del> key = state.convertValue(index, targetObjectTypeDescriptor.getMapKeyTypeDescriptor());
<add>
<add> public TypedValue getValue() {
<add> if (index >= collection.size()) {
<add> if (growCollection) {
<add> growCollection(collectionEntryTypeDescriptor,index,collection);
<add> } else {
<add> throw new SpelEvaluationException(getStartPosition(),
<add> SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS,
<add> collection.size(), index);
<add> }
<ide> }
<del> if (targetObjectTypeDescriptor.getMapValueTypeDescriptor() != null) {
<del> newValue = state.convertValue(newValue, targetObjectTypeDescriptor.getMapValueTypeDescriptor());
<add> int pos = 0;
<add> for (Object o : collection) {
<add> if (pos == index) {
<add> return new TypedValue(o,
<add> collectionEntryTypeDescriptor
<add> .elementTypeDescriptor(o));
<add> }
<add> pos++;
<ide> }
<del> map.put(key, newValue);
<del> return;
<add> throw new IllegalStateException();
<ide> }
<ide>
<del> if (targetObjectTypeDescriptor.isArray()) {
<del> int idx = (Integer)state.convertValue(index, TypeDescriptor.valueOf(Integer.class));
<del> setArrayElement(state, contextObject.getValue(), idx, newValue, targetObjectTypeDescriptor.getElementTypeDescriptor().getType());
<del> return;
<del> }
<del> else if (targetObject instanceof Collection) {
<del> int idx = (Integer) state.convertValue(index, TypeDescriptor.valueOf(Integer.class));
<del> Collection c = (Collection) targetObject;
<del> if (idx >= c.size()) {
<del> if (!growCollection(state, targetObjectTypeDescriptor, idx, c)) {
<del> throw new SpelEvaluationException(getStartPosition(),SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS, c.size(), idx);
<add> public void setValue(Object newValue) {
<add> if (index >= collection.size()) {
<add> if (growCollection) {
<add> growCollection(collectionEntryTypeDescriptor, index, collection);
<add> } else {
<add> throw new SpelEvaluationException(getStartPosition(),
<add> SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS,
<add> collection.size(), index);
<ide> }
<ide> }
<del> if (targetObject instanceof List) {
<del> List list = (List) targetObject;
<del> if (targetObjectTypeDescriptor.getElementTypeDescriptor() != null) {
<del> newValue = state.convertValue(newValue, targetObjectTypeDescriptor.getElementTypeDescriptor());
<add> if (collection instanceof List) {
<add> List list = (List) collection;
<add> if (collectionEntryTypeDescriptor.getElementTypeDescriptor() != null) {
<add> newValue = typeConverter.convertValue(newValue,
<add> TypeDescriptor.forObject(newValue),
<add> collectionEntryTypeDescriptor
<add> .getElementTypeDescriptor());
<ide> }
<del> list.set(idx, newValue);
<add> list.set(index, newValue);
<ide> return;
<add> } else {
<add> throw new SpelEvaluationException(getStartPosition(),
<add> SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE,
<add> collectionEntryTypeDescriptor.toString());
<ide> }
<del> else {
<del> throw new SpelEvaluationException(getStartPosition(),SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, targetObjectTypeDescriptor.toString());
<add> }
<add>
<add> public boolean isWritable() {
<add> return true;
<add> }
<add> }
<add>
<add> class StringIndexingLValue implements ValueRef {
<add>
<add> private String target;
<add> private int index;
<add> private TypeDescriptor td;
<add>
<add> public StringIndexingLValue(String target, int index, TypeDescriptor td) {
<add> this.target = target;
<add> this.index = index;
<add> this.td = td;
<add> }
<add>
<add> public TypedValue getValue() {
<add> if (index >= target.length()) {
<add> throw new SpelEvaluationException(getStartPosition(),
<add> SpelMessage.STRING_INDEX_OUT_OF_BOUNDS,
<add> target.length(), index);
<ide> }
<add> return new TypedValue(String.valueOf(target.charAt(index)));
<ide> }
<del>
<del> // Try and treat the index value as a property of the context object
<del> // TODO could call the conversion service to convert the value to a String
<del> if (index.getTypeDescriptor().getType() == String.class) {
<del> Class<?> contextObjectClass = getObjectClass(contextObject.getValue());
<del> String name = (String)index.getValue();
<del> EvaluationContext eContext = state.getEvaluationContext();
<add>
<add> public void setValue(Object newValue) {
<add> throw new SpelEvaluationException(getStartPosition(),
<add> SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, td.toString());
<add> }
<add>
<add> public boolean isWritable() {
<add> return true;
<add> }
<add>
<add> }
<add>
<add> @Override
<add> protected ValueRef getValueRef(ExpressionState state)
<add> throws EvaluationException {
<add> TypedValue context = state.getActiveContextObject();
<add> Object targetObject = context.getValue();
<add> TypeDescriptor targetObjectTypeDescriptor = context.getTypeDescriptor();
<add> TypedValue indexValue = null;
<add> Object index = null;
<add>
<add> // This first part of the if clause prevents a 'double dereference' of
<add> // the property (SPR-5847)
<add> if (targetObject instanceof Map && (children[0] instanceof PropertyOrFieldReference)) {
<add> PropertyOrFieldReference reference = (PropertyOrFieldReference) children[0];
<add> index = reference.getName();
<add> indexValue = new TypedValue(index);
<add> } else {
<add> // In case the map key is unqualified, we want it evaluated against
<add> // the root object so temporarily push that on whilst evaluating the key
<ide> try {
<del> if (cachedWriteName!=null && cachedWriteName.equals(name) && cachedWriteTargetType!=null && cachedWriteTargetType.equals(contextObjectClass)) {
<del> // it is OK to use the cached accessor
<del> cachedWriteAccessor.write(eContext, targetObject, name,newValue);
<del> return;
<del> }
<del>
<del> List<PropertyAccessor> accessorsToTry = AstUtils.getPropertyAccessorsToTry(contextObjectClass, state);
<del> if (accessorsToTry != null) {
<del> for (PropertyAccessor accessor : accessorsToTry) {
<del> if (accessor.canWrite(eContext, contextObject.getValue(), name)) {
<del> this.cachedWriteName = name;
<del> this.cachedWriteTargetType = contextObjectClass;
<del> this.cachedWriteAccessor = accessor;
<del> accessor.write(eContext, contextObject.getValue(), name, newValue);
<del> return;
<del> }
<del> }
<del> }
<del> } catch (AccessException ae) {
<del> throw new SpelEvaluationException(getStartPosition(), ae, SpelMessage.EXCEPTION_DURING_PROPERTY_WRITE,
<del> name, ae.getMessage());
<add> state.pushActiveContextObject(state.getRootContextObject());
<add> indexValue = children[0].getValueInternal(state);
<add> index = indexValue.getValue();
<add> } finally {
<add> state.popActiveContextObject();
<add> }
<add> }
<add>
<add> // Indexing into a Map
<add> if (targetObject instanceof Map) {
<add> Object key = index;
<add> if (targetObjectTypeDescriptor.getMapKeyTypeDescriptor() != null) {
<add> key = state.convertValue(key,
<add> targetObjectTypeDescriptor.getMapKeyTypeDescriptor());
<add> }
<add> return new MapIndexingValueRef(state.getTypeConverter(),
<add> (Map<?, ?>) targetObject, key, targetObjectTypeDescriptor);
<add> }
<add>
<add> if (targetObject == null) {
<add> throw new SpelEvaluationException(getStartPosition(),
<add> SpelMessage.CANNOT_INDEX_INTO_NULL_VALUE);
<add> }
<add>
<add> // if the object is something that looks indexable by an integer,
<add> // attempt to treat the index value as a number
<add> if (targetObject instanceof Collection
<add> || targetObject.getClass().isArray()
<add> || targetObject instanceof String) {
<add> int idx = (Integer) state.convertValue(index,
<add> TypeDescriptor.valueOf(Integer.class));
<add> if (targetObject.getClass().isArray()) {
<add> return new ArrayIndexingValueRef(state.getTypeConverter(),
<add> targetObject, idx, targetObjectTypeDescriptor);
<add> } else if (targetObject instanceof Collection) {
<add> return new CollectionIndexingValueRef(
<add> (Collection<?>) targetObject, idx,
<add> targetObjectTypeDescriptor,state.getTypeConverter(),
<add> state.getConfiguration().isAutoGrowCollections());
<add> } else if (targetObject instanceof String) {
<add> return new StringIndexingLValue((String) targetObject, idx,
<add> targetObjectTypeDescriptor);
<ide> }
<add> }
<ide>
<add> // Try and treat the index value as a property of the context object
<add> // TODO could call the conversion service to convert the value to a
<add> // String
<add> if (indexValue.getTypeDescriptor().getType() == String.class) {
<add> return new PropertyIndexingValueRef(targetObject,
<add> (String) indexValue.getValue(),
<add> state.getEvaluationContext(), targetObjectTypeDescriptor);
<ide> }
<del>
<del> throw new SpelEvaluationException(getStartPosition(),SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, targetObjectTypeDescriptor.toString());
<add>
<add> throw new SpelEvaluationException(getStartPosition(),
<add> SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE,
<add> targetObjectTypeDescriptor.toString());
<ide> }
<del>
<add>
<ide> /**
<del> * Attempt to grow the specified collection so that the specified index is valid.
<del> *
<del> * @param state the expression state
<add> * Attempt to grow the specified collection so that the specified index is
<add> * valid.
<add> *
<ide> * @param elementType the type of the elements in the collection
<ide> * @param index the index into the collection that needs to be valid
<ide> * @param collection the collection to grow with elements
<del> * @return true if collection growing succeeded, otherwise false
<ide> */
<del> @SuppressWarnings("unchecked")
<del> private boolean growCollection(ExpressionState state, TypeDescriptor targetType, int index,
<del> Collection collection) {
<del> if (state.getConfiguration().isAutoGrowCollections()) {
<del> if (targetType.getElementTypeDescriptor() == null) {
<del> throw new SpelEvaluationException(getStartPosition(), SpelMessage.UNABLE_TO_GROW_COLLECTION_UNKNOWN_ELEMENT_TYPE);
<del> }
<del> TypeDescriptor elementType = targetType.getElementTypeDescriptor();
<del> Object newCollectionElement = null;
<del> try {
<del> int newElements = index - collection.size();
<del> while (newElements>0) {
<del> collection.add(elementType.getType().newInstance());
<del> newElements--;
<del> }
<del> newCollectionElement = elementType.getType().newInstance();
<del> }
<del> catch (Exception ex) {
<del> throw new SpelEvaluationException(getStartPosition(), ex, SpelMessage.UNABLE_TO_GROW_COLLECTION);
<add> private void growCollection(TypeDescriptor targetType, int index, Collection<Object> collection) {
<add> if (targetType.getElementTypeDescriptor() == null) {
<add> throw new SpelEvaluationException(
<add> getStartPosition(),
<add> SpelMessage.UNABLE_TO_GROW_COLLECTION_UNKNOWN_ELEMENT_TYPE);
<add> }
<add> TypeDescriptor elementType = targetType.getElementTypeDescriptor();
<add> Object newCollectionElement = null;
<add> try {
<add> int newElements = index - collection.size();
<add> while (newElements > 0) {
<add> collection.add(elementType.getType().newInstance());
<add> newElements--;
<ide> }
<del> collection.add(newCollectionElement);
<del> return true;
<add> newCollectionElement = elementType.getType().newInstance();
<add> } catch (Exception ex) {
<add> throw new SpelEvaluationException(getStartPosition(), ex,
<add> SpelMessage.UNABLE_TO_GROW_COLLECTION);
<ide> }
<del> return false;
<add> collection.add(newCollectionElement);
<ide> }
<del>
<add>
<ide> @Override
<ide> public String toStringAST() {
<ide> StringBuilder sb = new StringBuilder();
<ide> public String toStringAST() {
<ide> return sb.toString();
<ide> }
<ide>
<del> private void setArrayElement(ExpressionState state, Object ctx, int idx, Object newValue, Class clazz) throws EvaluationException {
<add> private void setArrayElement(TypeConverter converter, Object ctx, int idx,
<add> Object newValue, Class<?> clazz) throws EvaluationException {
<ide> Class<?> arrayComponentType = clazz;
<ide> if (arrayComponentType == Integer.TYPE) {
<ide> int[] array = (int[]) ctx;
<ide> checkAccess(array.length, idx);
<del> array[idx] = (Integer)state.convertValue(newValue, TypeDescriptor.valueOf(Integer.class));
<add> array[idx] = (Integer) converter.convertValue(newValue,
<add> TypeDescriptor.forObject(newValue),
<add> TypeDescriptor.valueOf(Integer.class));
<ide> } else if (arrayComponentType == Boolean.TYPE) {
<ide> boolean[] array = (boolean[]) ctx;
<ide> checkAccess(array.length, idx);
<del> array[idx] = (Boolean)state.convertValue(newValue, TypeDescriptor.valueOf(Boolean.class));
<add> array[idx] = (Boolean) converter.convertValue(newValue,
<add> TypeDescriptor.forObject(newValue),
<add> TypeDescriptor.valueOf(Boolean.class));
<ide> } else if (arrayComponentType == Character.TYPE) {
<ide> char[] array = (char[]) ctx;
<ide> checkAccess(array.length, idx);
<del> array[idx] = (Character)state.convertValue(newValue, TypeDescriptor.valueOf(Character.class));
<add> array[idx] = (Character) converter.convertValue(newValue,
<add> TypeDescriptor.forObject(newValue),
<add> TypeDescriptor.valueOf(Character.class));
<ide> } else if (arrayComponentType == Long.TYPE) {
<ide> long[] array = (long[]) ctx;
<ide> checkAccess(array.length, idx);
<del> array[idx] = (Long)state.convertValue(newValue, TypeDescriptor.valueOf(Long.class));
<add> array[idx] = (Long) converter.convertValue(newValue,
<add> TypeDescriptor.forObject(newValue),
<add> TypeDescriptor.valueOf(Long.class));
<ide> } else if (arrayComponentType == Short.TYPE) {
<ide> short[] array = (short[]) ctx;
<ide> checkAccess(array.length, idx);
<del> array[idx] = (Short)state.convertValue(newValue, TypeDescriptor.valueOf(Short.class));
<add> array[idx] = (Short) converter.convertValue(newValue,
<add> TypeDescriptor.forObject(newValue),
<add> TypeDescriptor.valueOf(Short.class));
<ide> } else if (arrayComponentType == Double.TYPE) {
<ide> double[] array = (double[]) ctx;
<ide> checkAccess(array.length, idx);
<del> array[idx] = (Double)state.convertValue(newValue, TypeDescriptor.valueOf(Double.class));
<add> array[idx] = (Double) converter.convertValue(newValue,
<add> TypeDescriptor.forObject(newValue),
<add> TypeDescriptor.valueOf(Double.class));
<ide> } else if (arrayComponentType == Float.TYPE) {
<ide> float[] array = (float[]) ctx;
<ide> checkAccess(array.length, idx);
<del> array[idx] = (Float)state.convertValue(newValue, TypeDescriptor.valueOf(Float.class));
<add> array[idx] = (Float) converter.convertValue(newValue,
<add> TypeDescriptor.forObject(newValue),
<add> TypeDescriptor.valueOf(Float.class));
<ide> } else if (arrayComponentType == Byte.TYPE) {
<ide> byte[] array = (byte[]) ctx;
<ide> checkAccess(array.length, idx);
<del> array[idx] = (Byte)state.convertValue(newValue, TypeDescriptor.valueOf(Byte.class));
<add> array[idx] = (Byte) converter.convertValue(newValue,
<add> TypeDescriptor.forObject(newValue),
<add> TypeDescriptor.valueOf(Byte.class));
<ide> } else {
<ide> Object[] array = (Object[]) ctx;
<ide> checkAccess(array.length, idx);
<del> array[idx] = state.convertValue(newValue, TypeDescriptor.valueOf(clazz));
<del> }
<add> array[idx] = converter.convertValue(newValue,
<add> TypeDescriptor.forObject(newValue),
<add> TypeDescriptor.valueOf(clazz));
<add> }
<ide> }
<del>
<add>
<ide> private Object accessArrayElement(Object ctx, int idx) throws SpelEvaluationException {
<ide> Class<?> arrayComponentType = ctx.getClass().getComponentType();
<ide> if (arrayComponentType == Integer.TYPE) {
<ide> private Object accessArrayElement(Object ctx, int idx) throws SpelEvaluationExce
<ide>
<ide> private void checkAccess(int arrayLength, int index) throws SpelEvaluationException {
<ide> if (index > arrayLength) {
<del> throw new SpelEvaluationException(getStartPosition(), SpelMessage.ARRAY_INDEX_OUT_OF_BOUNDS, arrayLength, index);
<add> throw new SpelEvaluationException(getStartPosition(),
<add> SpelMessage.ARRAY_INDEX_OUT_OF_BOUNDS, arrayLength, index);
<ide> }
<ide> }
<ide>
<del>}
<add>}
<ide>\ No newline at end of file
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/MethodReference.java
<ide> /*
<del> * Copyright 2002-2009 the original author or authors.
<add> * Copyright 2002-2012 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public MethodReference(boolean nullSafe, String methodName, int pos, SpelNodeImp
<ide> this.nullSafe = nullSafe;
<ide> }
<ide>
<add> class MethodValueRef implements ValueRef {
<add>
<add> private ExpressionState state;
<add> private EvaluationContext evaluationContext;
<add> private Object target;
<add> private Object[] arguments;
<add>
<add> MethodValueRef(ExpressionState state, EvaluationContext evaluationContext, Object object, Object[] arguments) {
<add> this.state = state;
<add> this.evaluationContext = evaluationContext;
<add> this.target = object;
<add> this.arguments = arguments;
<add> }
<add>
<add> public TypedValue getValue() {
<add> MethodExecutor executorToUse = cachedExecutor;
<add> if (executorToUse != null) {
<add> try {
<add> return executorToUse.execute(evaluationContext, target, arguments);
<add> }
<add> catch (AccessException ae) {
<add> // Two reasons this can occur:
<add> // 1. the method invoked actually threw a real exception
<add> // 2. the method invoked was not passed the arguments it expected and has become 'stale'
<add>
<add> // In the first case we should not retry, in the second case we should see if there is a
<add> // better suited method.
<add>
<add> // To determine which situation it is, the AccessException will contain a cause.
<add> // If the cause is an InvocationTargetException, a user exception was thrown inside the method.
<add> // Otherwise the method could not be invoked.
<add> throwSimpleExceptionIfPossible(state, ae);
<add>
<add> // at this point we know it wasn't a user problem so worth a retry if a better candidate can be found
<add> cachedExecutor = null;
<add> }
<add> }
<add>
<add> // either there was no accessor or it no longer existed
<add> executorToUse = findAccessorForMethod(name, getTypes(arguments), target, evaluationContext);
<add> cachedExecutor = executorToUse;
<add> try {
<add> return executorToUse.execute(evaluationContext, target, arguments);
<add> } catch (AccessException ae) {
<add> // Same unwrapping exception handling as above in above catch block
<add> throwSimpleExceptionIfPossible(state, ae);
<add> throw new SpelEvaluationException( getStartPosition(), ae, SpelMessage.EXCEPTION_DURING_METHOD_INVOCATION,
<add> name, state.getActiveContextObject().getValue().getClass().getName(), ae.getMessage());
<add> }
<add> }
<add>
<add> public void setValue(Object newValue) {
<add> throw new IllegalAccessError();
<add> }
<add>
<add> public boolean isWritable() {
<add> return false;
<add> }
<add>
<add> }
<add>
<add> @Override
<add> protected ValueRef getValueRef(ExpressionState state) throws EvaluationException {
<add> TypedValue currentContext = state.getActiveContextObject();
<add> Object[] arguments = new Object[getChildCount()];
<add> for (int i = 0; i < arguments.length; i++) {
<add> // Make the root object the active context again for evaluating the parameter
<add> // expressions
<add> try {
<add> state.pushActiveContextObject(state.getRootContextObject());
<add> arguments[i] = children[i].getValueInternal(state).getValue();
<add> }
<add> finally {
<add> state.popActiveContextObject();
<add> }
<add> }
<add> if (currentContext.getValue() == null) {
<add> if (nullSafe) {
<add> return ValueRef.NullValueRef.instance;
<add> }
<add> else {
<add> throw new SpelEvaluationException(getStartPosition(), SpelMessage.METHOD_CALL_ON_NULL_OBJECT_NOT_ALLOWED,
<add> FormatHelper.formatMethodForMessage(name, getTypes(arguments)));
<add> }
<add> }
<add>
<add> return new MethodValueRef(state,state.getEvaluationContext(),state.getActiveContextObject().getValue(),arguments);
<add> }
<ide>
<ide> @Override
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> arguments[i] = children[i].getValueInternal(state).getValue();
<ide> }
<ide> finally {
<del> state.popActiveContextObject();
<add> state.popActiveContextObject();
<ide> }
<ide> }
<ide> if (currentContext.getValue() == null) {
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> // Two reasons this can occur:
<ide> // 1. the method invoked actually threw a real exception
<ide> // 2. the method invoked was not passed the arguments it expected and has become 'stale'
<del>
<del> // In the first case we should not retry, in the second case we should see if there is a
<add>
<add> // In the first case we should not retry, in the second case we should see if there is a
<ide> // better suited method.
<del>
<add>
<ide> // To determine which situation it is, the AccessException will contain a cause.
<ide> // If the cause is an InvocationTargetException, a user exception was thrown inside the method.
<ide> // Otherwise the method could not be invoked.
<ide> throwSimpleExceptionIfPossible(state, ae);
<del>
<add>
<ide> // at this point we know it wasn't a user problem so worth a retry if a better candidate can be found
<ide> this.cachedExecutor = null;
<ide> }
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide>
<ide>
<ide> /**
<del> * Decode the AccessException, throwing a lightweight evaluation exception or, if the cause was a RuntimeException,
<add> * Decode the AccessException, throwing a lightweight evaluation exception or, if the cause was a RuntimeException,
<ide> * throw the RuntimeException directly.
<ide> */
<ide> private void throwSimpleExceptionIfPossible(ExpressionState state, AccessException ae) {
<ide> private void throwSimpleExceptionIfPossible(ExpressionState state, AccessExcepti
<ide> "A problem occurred when trying to execute method '" + this.name +
<ide> "' on object of type '" + state.getActiveContextObject().getValue().getClass().getName() + "'",
<ide> rootCause);
<del> }
<add> }
<ide> }
<ide> }
<ide>
<ide> public String toStringAST() {
<ide> return sb.toString();
<ide> }
<ide>
<del> private MethodExecutor findAccessorForMethod(String name, List<TypeDescriptor> argumentTypes, ExpressionState state)
<add> private MethodExecutor findAccessorForMethod(String name,
<add> List<TypeDescriptor> argumentTypes, ExpressionState state)
<ide> throws SpelEvaluationException {
<add> return findAccessorForMethod(name,argumentTypes,state.getActiveContextObject().getValue(),state.getEvaluationContext());
<add> }
<ide>
<del> TypedValue context = state.getActiveContextObject();
<del> Object contextObject = context.getValue();
<del> EvaluationContext eContext = state.getEvaluationContext();
<add> private MethodExecutor findAccessorForMethod(String name,
<add> List<TypeDescriptor> argumentTypes, Object contextObject, EvaluationContext eContext)
<add> throws SpelEvaluationException {
<ide>
<ide> List<MethodResolver> mResolvers = eContext.getMethodResolvers();
<ide> if (mResolvers != null) {
<ide> for (MethodResolver methodResolver : mResolvers) {
<ide> try {
<ide> MethodExecutor cEx = methodResolver.resolve(
<del> state.getEvaluationContext(), contextObject, name, argumentTypes);
<add> eContext, contextObject, name, argumentTypes);
<ide> if (cEx != null) {
<ide> return cEx;
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpDec.java
<add>/*
<add> * Copyright 2002-2012 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.expression.spel.ast;
<add>
<add>import org.springframework.expression.EvaluationException;
<add>import org.springframework.expression.Operation;
<add>import org.springframework.expression.TypedValue;
<add>import org.springframework.expression.spel.ExpressionState;
<add>import org.springframework.expression.spel.SpelEvaluationException;
<add>import org.springframework.expression.spel.SpelMessage;
<add>import org.springframework.util.Assert;
<add>
<add>/**
<add> * Decrement operator. Can be used in a prefix or postfix form. This will throw
<add> * appropriate exceptions if the operand in question does not support decrement.
<add> *
<add> * @author Andy Clement
<add> * @since 3.2
<add> */
<add>public class OpDec extends Operator {
<add>
<add> private boolean postfix; // false means prefix
<add>
<add> public OpDec(int pos, boolean postfix, SpelNodeImpl... operands) {
<add> super("--", pos, operands);
<add> Assert.notEmpty(operands);
<add> this.postfix = postfix;
<add> }
<add>
<add> @Override
<add> public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
<add> SpelNodeImpl operand = getLeftOperand();
<add>
<add> // The operand is going to be read and then assigned to, we don't want to evaluate it twice.
<add>
<add> ValueRef lvalue = operand.getValueRef(state);
<add>
<add> final TypedValue operandTypedValue = lvalue.getValue();//operand.getValueInternal(state);
<add> final Object operandValue = operandTypedValue.getValue();
<add> TypedValue returnValue = operandTypedValue;
<add> TypedValue newValue = null;
<add>
<add> if (operandValue instanceof Number) {
<add> Number op1 = (Number) operandValue;
<add> if (op1 instanceof Double) {
<add> newValue = new TypedValue(op1.doubleValue() - 1.0d, operandTypedValue.getTypeDescriptor());
<add> } else if (op1 instanceof Float) {
<add> newValue = new TypedValue(op1.floatValue() - 1.0f, operandTypedValue.getTypeDescriptor());
<add> } else if (op1 instanceof Long) {
<add> newValue = new TypedValue(op1.longValue() - 1L, operandTypedValue.getTypeDescriptor());
<add> } else if (op1 instanceof Short) {
<add> newValue = new TypedValue(op1.shortValue() - (short)1, operandTypedValue.getTypeDescriptor());
<add> } else {
<add> newValue = new TypedValue(op1.intValue() - 1, operandTypedValue.getTypeDescriptor());
<add> }
<add> }
<add> if (newValue==null) {
<add> try {
<add> newValue = state.operate(Operation.SUBTRACT, returnValue.getValue(), 1);
<add> } catch (SpelEvaluationException see) {
<add> if (see.getMessageCode()==SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES) {
<add> // This means the operand is not decrementable
<add> throw new SpelEvaluationException(operand.getStartPosition(),SpelMessage.OPERAND_NOT_DECREMENTABLE,operand.toStringAST());
<add> } else {
<add> throw see;
<add> }
<add> }
<add> }
<add>
<add> // set the new value
<add> try {
<add> lvalue.setValue(newValue.getValue());
<add> } catch (SpelEvaluationException see) {
<add> // if unable to set the value the operand is not writable (e.g. 1-- )
<add> if (see.getMessageCode()==SpelMessage.SETVALUE_NOT_SUPPORTED) {
<add> throw new SpelEvaluationException(operand.getStartPosition(),SpelMessage.OPERAND_NOT_DECREMENTABLE);
<add> } else {
<add> throw see;
<add> }
<add> }
<add>
<add> if (!postfix) {
<add> // the return value is the new value, not the original value
<add> returnValue = newValue;
<add> }
<add>
<add> return returnValue;
<add> }
<add>
<add> @Override
<add> public String toStringAST() {
<add> return new StringBuilder().append(getLeftOperand().toStringAST()).append("--").toString();
<add> }
<add>
<add> @Override
<add> public SpelNodeImpl getRightOperand() {
<add> return null;
<add> }
<add>
<add>}
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpInc.java
<add>/*
<add> * Copyright 2002-2012 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.expression.spel.ast;
<add>
<add>import org.springframework.expression.EvaluationException;
<add>import org.springframework.expression.Operation;
<add>import org.springframework.expression.TypedValue;
<add>import org.springframework.expression.spel.ExpressionState;
<add>import org.springframework.expression.spel.SpelEvaluationException;
<add>import org.springframework.expression.spel.SpelMessage;
<add>import org.springframework.util.Assert;
<add>
<add>/**
<add> * Increment operator. Can be used in a prefix or postfix form. This will throw
<add> * appropriate exceptions if the operand in question does not support increment.
<add> *
<add> * @author Andy Clement
<add> * @since 3.2
<add> */
<add>public class OpInc extends Operator {
<add>
<add> private boolean postfix; // false means prefix
<add>
<add> public OpInc(int pos, boolean postfix, SpelNodeImpl... operands) {
<add> super("++", pos, operands);
<add> Assert.notEmpty(operands);
<add> this.postfix = postfix;
<add> }
<add>
<add> @Override
<add> public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
<add> SpelNodeImpl operand = getLeftOperand();
<add>
<add> ValueRef lvalue = operand.getValueRef(state);
<add>
<add> final TypedValue operandTypedValue = lvalue.getValue();
<add> final Object operandValue = operandTypedValue.getValue();
<add> TypedValue returnValue = operandTypedValue;
<add> TypedValue newValue = null;
<add>
<add> if (operandValue instanceof Number) {
<add> Number op1 = (Number) operandValue;
<add> if (op1 instanceof Double) {
<add> newValue = new TypedValue(op1.doubleValue() + 1.0d, operandTypedValue.getTypeDescriptor());
<add> } else if (op1 instanceof Float) {
<add> newValue = new TypedValue(op1.floatValue() + 1.0f, operandTypedValue.getTypeDescriptor());
<add> } else if (op1 instanceof Long) {
<add> newValue = new TypedValue(op1.longValue() + 1L, operandTypedValue.getTypeDescriptor());
<add> } else if (op1 instanceof Short) {
<add> newValue = new TypedValue(op1.shortValue() + (short)1, operandTypedValue.getTypeDescriptor());
<add> } else {
<add> newValue = new TypedValue(op1.intValue() + 1, operandTypedValue.getTypeDescriptor());
<add> }
<add> }
<add> if (newValue==null) {
<add> try {
<add> newValue = state.operate(Operation.ADD, returnValue.getValue(), 1);
<add> } catch (SpelEvaluationException see) {
<add> if (see.getMessageCode()==SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES) {
<add> // This means the operand is not incrementable
<add> throw new SpelEvaluationException(operand.getStartPosition(),SpelMessage.OPERAND_NOT_INCREMENTABLE,operand.toStringAST());
<add> } else {
<add> throw see;
<add> }
<add> }
<add> }
<add>
<add> // set the name value
<add> try {
<add> lvalue.setValue(newValue.getValue());
<add> } catch (SpelEvaluationException see) {
<add> // if unable to set the value the operand is not writable (e.g. 1++ )
<add> if (see.getMessageCode()==SpelMessage.SETVALUE_NOT_SUPPORTED) {
<add> throw new SpelEvaluationException(operand.getStartPosition(),SpelMessage.OPERAND_NOT_INCREMENTABLE);
<add> } else {
<add> throw see;
<add> }
<add> }
<add>
<add> if (!postfix) {
<add> // the return value is the new value, not the original value
<add> returnValue = newValue;
<add> }
<add>
<add> return returnValue;
<add> }
<add>
<add> @Override
<add> public String toStringAST() {
<add> return new StringBuilder().append(getLeftOperand().toStringAST()).append("++").toString();
<add> }
<add>
<add> @Override
<add> public SpelNodeImpl getRightOperand() {
<add> return null;
<add> }
<add>
<add>}
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/Projection.java
<ide> /*
<del> * Copyright 2002-2010 the original author or authors.
<add> * Copyright 2002-2012 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public Projection(boolean nullSafe, int pos, SpelNodeImpl expression) {
<ide>
<ide> @Override
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
<add> return getValueRef(state).getValue();
<add> }
<add>
<add> @Override
<add> protected ValueRef getValueRef(ExpressionState state) throws EvaluationException {
<ide> TypedValue op = state.getActiveContextObject();
<ide>
<ide> Object operand = op.getValue();
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> if (operand instanceof Map) {
<ide> Map<?, ?> mapData = (Map<?, ?>) operand;
<ide> List<Object> result = new ArrayList<Object>();
<del> for (Map.Entry entry : mapData.entrySet()) {
<add> for (Map.Entry<?,?> entry : mapData.entrySet()) {
<ide> try {
<ide> state.pushActiveContextObject(new TypedValue(entry));
<ide> result.add(this.children[0].getValueInternal(state).getValue());
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> state.popActiveContextObject();
<ide> }
<ide> }
<del> return new TypedValue(result); // TODO unable to build correct type descriptor
<add> return new ValueRef.TypedValueHolderValueRef(new TypedValue(result),this); // TODO unable to build correct type descriptor
<ide> }
<ide> else if (operand instanceof Collection || operandIsArray) {
<ide> Collection<?> data = (operand instanceof Collection ? (Collection<?>) operand :
<ide> else if (operand instanceof Collection || operandIsArray) {
<ide> }
<ide> Object resultArray = Array.newInstance(arrayElementType, result.size());
<ide> System.arraycopy(result.toArray(), 0, resultArray, 0, result.size());
<del> return new TypedValue(resultArray);
<add> return new ValueRef.TypedValueHolderValueRef(new TypedValue(resultArray),this);
<ide> }
<del> return new TypedValue(result);
<add> return new ValueRef.TypedValueHolderValueRef(new TypedValue(result),this);
<ide> }
<ide> else {
<ide> if (operand==null) {
<ide> if (this.nullSafe) {
<del> return TypedValue.NULL;
<add> return ValueRef.NullValueRef.instance;
<ide> }
<ide> else {
<ide> throw new SpelEvaluationException(getStartPosition(),
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/PropertyOrFieldReference.java
<ide> /*
<del> * Copyright 2002-2010 the original author or authors.
<add> * Copyright 2002-2012 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public class PropertyOrFieldReference extends SpelNodeImpl {
<ide> private volatile PropertyAccessor cachedReadAccessor;
<ide>
<ide> private volatile PropertyAccessor cachedWriteAccessor;
<del>
<add>
<ide>
<ide> public PropertyOrFieldReference(boolean nullSafe, String propertyOrFieldName, int pos) {
<ide> super(pos);
<ide> public String getName() {
<ide> }
<ide>
<ide>
<add> static class AccessorLValue implements ValueRef {
<add> private PropertyOrFieldReference ref;
<add> private TypedValue contextObject;
<add> private EvaluationContext eContext;
<add> private boolean isAutoGrowNullReferences;
<add>
<add> public AccessorLValue(
<add> PropertyOrFieldReference propertyOrFieldReference,
<add> TypedValue activeContextObject,
<add> EvaluationContext evaluationContext, boolean isAutoGrowNullReferences) {
<add> this.ref = propertyOrFieldReference;
<add> this.contextObject = activeContextObject;
<add> this.eContext =evaluationContext;
<add> this.isAutoGrowNullReferences = isAutoGrowNullReferences;
<add> }
<add>
<add> public TypedValue getValue() {
<add> return ref.getValueInternal(contextObject,eContext,isAutoGrowNullReferences);
<add> }
<add>
<add> public void setValue(Object newValue) {
<add> ref.writeProperty(contextObject,eContext, ref.name, newValue);
<add> }
<add>
<add> public boolean isWritable() {
<add> return true;
<add> }
<add>
<add> }
<add>
<add> @Override
<add> public ValueRef getValueRef(ExpressionState state) throws EvaluationException {
<add> return new AccessorLValue(this,state.getActiveContextObject(),state.getEvaluationContext(),state.getConfiguration().isAutoGrowNullReferences());
<add> }
<add>
<ide> @Override
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
<del> TypedValue result = readProperty(state, this.name);
<del>
<del> // Dynamically create the objects if the user has requested that optional behaviour
<del> if (result.getValue() == null && state.getConfiguration().isAutoGrowNullReferences() &&
<add> return getValueInternal(state.getActiveContextObject(), state.getEvaluationContext(), state.getConfiguration().isAutoGrowNullReferences());
<add> }
<add>
<add> private TypedValue getValueInternal(TypedValue contextObject, EvaluationContext eContext, boolean isAutoGrowNullReferences) throws EvaluationException {
<add>
<add> TypedValue result = readProperty(contextObject, eContext, this.name);
<add>
<add> // Dynamically create the objects if the user has requested that optional behavior
<add> if (result.getValue() == null && isAutoGrowNullReferences &&
<ide> nextChildIs(Indexer.class, PropertyOrFieldReference.class)) {
<ide> TypeDescriptor resultDescriptor = result.getTypeDescriptor();
<ide> // Creating lists and maps
<ide> if ((resultDescriptor.getType().equals(List.class) || resultDescriptor.getType().equals(Map.class))) {
<ide> // Create a new collection or map ready for the indexer
<ide> if (resultDescriptor.getType().equals(List.class)) {
<ide> try {
<del> if (isWritable(state)) {
<del> List newList = ArrayList.class.newInstance();
<del> writeProperty(state, this.name, newList);
<del> result = readProperty(state, this.name);
<add> if (isWritableProperty(this.name,contextObject,eContext)) {
<add> List<?> newList = ArrayList.class.newInstance();
<add> writeProperty(contextObject, eContext, this.name, newList);
<add> result = readProperty(contextObject, eContext, this.name);
<ide> }
<ide> }
<ide> catch (InstantiationException ex) {
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> }
<ide> else {
<ide> try {
<del> if (isWritable(state)) {
<del> Map newMap = HashMap.class.newInstance();
<del> writeProperty(state, name, newMap);
<del> result = readProperty(state, this.name);
<add> if (isWritableProperty(this.name,contextObject,eContext)) {
<add> Map<?,?> newMap = HashMap.class.newInstance();
<add> writeProperty(contextObject, eContext, name, newMap);
<add> result = readProperty(contextObject, eContext, this.name);
<ide> }
<ide> }
<ide> catch (InstantiationException ex) {
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> else {
<ide> // 'simple' object
<ide> try {
<del> if (isWritable(state)) {
<add> if (isWritableProperty(this.name,contextObject,eContext)) {
<ide> Object newObject = result.getTypeDescriptor().getType().newInstance();
<del> writeProperty(state, name, newObject);
<del> result = readProperty(state, this.name);
<add> writeProperty(contextObject, eContext, name, newObject);
<add> result = readProperty(contextObject, eContext, this.name);
<ide> }
<ide> }
<ide> catch (InstantiationException ex) {
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide>
<ide> @Override
<ide> public void setValue(ExpressionState state, Object newValue) throws SpelEvaluationException {
<del> writeProperty(state, this.name, newValue);
<add> writeProperty(state.getActiveContextObject(), state.getEvaluationContext(), this.name, newValue);
<ide> }
<ide>
<ide> @Override
<ide> public boolean isWritable(ExpressionState state) throws SpelEvaluationException {
<del> return isWritableProperty(this.name, state);
<add> return isWritableProperty(this.name, state.getActiveContextObject(), state.getEvaluationContext());
<ide> }
<ide>
<ide> @Override
<ide> public String toStringAST() {
<ide> * @return the value of the property
<ide> * @throws SpelEvaluationException if any problem accessing the property or it cannot be found
<ide> */
<del> private TypedValue readProperty(ExpressionState state, String name) throws EvaluationException {
<del> TypedValue contextObject = state.getActiveContextObject();
<add> private TypedValue readProperty(TypedValue contextObject, EvaluationContext eContext, String name) throws EvaluationException {
<ide> Object targetObject = contextObject.getValue();
<ide>
<ide> if (targetObject == null && this.nullSafe) {
<ide> private TypedValue readProperty(ExpressionState state, String name) throws Evalu
<ide> PropertyAccessor accessorToUse = this.cachedReadAccessor;
<ide> if (accessorToUse != null) {
<ide> try {
<del> return accessorToUse.read(state.getEvaluationContext(), contextObject.getValue(), name);
<add> return accessorToUse.read(eContext, contextObject.getValue(), name);
<ide> }
<ide> catch (AccessException ae) {
<ide> // this is OK - it may have gone stale due to a class change,
<ide> private TypedValue readProperty(ExpressionState state, String name) throws Evalu
<ide> }
<ide>
<ide> Class<?> contextObjectClass = getObjectClass(contextObject.getValue());
<del> List<PropertyAccessor> accessorsToTry = getPropertyAccessorsToTry(contextObjectClass, state);
<del> EvaluationContext eContext = state.getEvaluationContext();
<add> List<PropertyAccessor> accessorsToTry = getPropertyAccessorsToTry(contextObjectClass, eContext.getPropertyAccessors());
<ide>
<ide> // Go through the accessors that may be able to resolve it. If they are a cacheable accessor then
<ide> // get the accessor and use it. If they are not cacheable but report they can read the property
<ide> private TypedValue readProperty(ExpressionState state, String name) throws Evalu
<ide> }
<ide> }
<ide>
<del> private void writeProperty(ExpressionState state, String name, Object newValue) throws SpelEvaluationException {
<del> TypedValue contextObject = state.getActiveContextObject();
<del> EvaluationContext eContext = state.getEvaluationContext();
<add> private void writeProperty(TypedValue contextObject, EvaluationContext eContext, String name, Object newValue) throws SpelEvaluationException {
<ide>
<ide> if (contextObject.getValue() == null && nullSafe) {
<ide> return;
<ide> }
<ide>
<ide> PropertyAccessor accessorToUse = this.cachedWriteAccessor;
<ide> if (accessorToUse != null) {
<del> try {
<del> accessorToUse.write(state.getEvaluationContext(), contextObject.getValue(), name, newValue);
<add> try {
<add> accessorToUse.write(eContext, contextObject.getValue(), name, newValue);
<ide> return;
<ide> }
<ide> catch (AccessException ae) {
<ide> private void writeProperty(ExpressionState state, String name, Object newValue)
<ide>
<ide> Class<?> contextObjectClass = getObjectClass(contextObject.getValue());
<ide>
<del> List<PropertyAccessor> accessorsToTry = getPropertyAccessorsToTry(contextObjectClass, state);
<add> List<PropertyAccessor> accessorsToTry = getPropertyAccessorsToTry(contextObjectClass, eContext.getPropertyAccessors());
<ide> if (accessorsToTry != null) {
<ide> try {
<ide> for (PropertyAccessor accessor : accessorsToTry) {
<ide> private void writeProperty(ExpressionState state, String name, Object newValue)
<ide> }
<ide> }
<ide>
<del> public boolean isWritableProperty(String name, ExpressionState state) throws SpelEvaluationException {
<del> Object contextObject = state.getActiveContextObject().getValue();
<add> public boolean isWritableProperty(String name, TypedValue contextObject, EvaluationContext eContext) throws SpelEvaluationException {
<add> Object contextObjectValue = contextObject.getValue();
<ide> // TypeDescriptor td = state.getActiveContextObject().getTypeDescriptor();
<del> EvaluationContext eContext = state.getEvaluationContext();
<del> List<PropertyAccessor> resolversToTry = getPropertyAccessorsToTry(getObjectClass(contextObject), state);
<add> List<PropertyAccessor> resolversToTry = getPropertyAccessorsToTry(getObjectClass(contextObjectValue), eContext.getPropertyAccessors());
<ide> if (resolversToTry != null) {
<ide> for (PropertyAccessor pfResolver : resolversToTry) {
<ide> try {
<del> if (pfResolver.canWrite(eContext, contextObject, name)) {
<add> if (pfResolver.canWrite(eContext, contextObjectValue, name)) {
<ide> return true;
<ide> }
<ide> }
<ide> public boolean isWritableProperty(String name, ExpressionState state) throws Spe
<ide> * @param targetType the type upon which property access is being attempted
<ide> * @return a list of resolvers that should be tried in order to access the property
<ide> */
<del> private List<PropertyAccessor> getPropertyAccessorsToTry(Class<?> targetType, ExpressionState state) {
<add> private List<PropertyAccessor> getPropertyAccessorsToTry(Class<?> targetType, List<PropertyAccessor> propertyAccessors) {
<ide> List<PropertyAccessor> specificAccessors = new ArrayList<PropertyAccessor>();
<ide> List<PropertyAccessor> generalAccessors = new ArrayList<PropertyAccessor>();
<del> for (PropertyAccessor resolver : state.getPropertyAccessors()) {
<add> for (PropertyAccessor resolver : propertyAccessors) {
<ide> Class<?>[] targets = resolver.getSpecificTargetClasses();
<ide> if (targets == null) { // generic resolver that says it can be used for any type
<ide> generalAccessors.add(resolver);
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/Selection.java
<ide> /*
<del> * Copyright 2002-2010 the original author or authors.
<add> * Copyright 2002-2012 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public Selection(boolean nullSafe, int variant,int pos,SpelNodeImpl expression)
<ide> this.variant = variant;
<ide> }
<ide>
<del> @SuppressWarnings("unchecked")
<ide> @Override
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
<add> return getValueRef(state).getValue();
<add> }
<add>
<add> @Override
<add> protected ValueRef getValueRef(ExpressionState state) throws EvaluationException {
<ide> TypedValue op = state.getActiveContextObject();
<ide> Object operand = op.getValue();
<del>
<add>
<ide> SpelNodeImpl selectionCriteria = children[0];
<ide> if (operand instanceof Map) {
<ide> Map<?, ?> mapdata = (Map<?, ?>) operand;
<ide> // TODO don't lose generic info for the new map
<ide> Map<Object,Object> result = new HashMap<Object,Object>();
<ide> Object lastKey = null;
<del> for (Map.Entry entry : mapdata.entrySet()) {
<add> for (Map.Entry<?,?> entry : mapdata.entrySet()) {
<ide> try {
<ide> TypedValue kvpair = new TypedValue(entry);
<ide> state.pushActiveContextObject(kvpair);
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> if (((Boolean) o).booleanValue() == true) {
<ide> if (variant == FIRST) {
<ide> result.put(entry.getKey(),entry.getValue());
<del> return new TypedValue(result);
<add> return new ValueRef.TypedValueHolderValueRef(new TypedValue(result),this);
<ide> }
<ide> result.put(entry.getKey(),entry.getValue());
<ide> lastKey = entry.getKey();
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> }
<ide> }
<ide> if ((variant == FIRST || variant == LAST) && result.size() == 0) {
<del> return new TypedValue(null);
<add> return new ValueRef.TypedValueHolderValueRef(new TypedValue(null),this);
<ide> }
<ide> if (variant == LAST) {
<del> Map resultMap = new HashMap();
<add> Map<Object,Object> resultMap = new HashMap<Object,Object>();
<ide> Object lastValue = result.get(lastKey);
<ide> resultMap.put(lastKey,lastValue);
<del> return new TypedValue(resultMap);
<add> return new ValueRef.TypedValueHolderValueRef(new TypedValue(resultMap),this);
<ide> }
<del> return new TypedValue(result);
<add> return new ValueRef.TypedValueHolderValueRef(new TypedValue(result),this);
<ide> } else if ((operand instanceof Collection) || ObjectUtils.isArray(operand)) {
<ide> List<Object> data = new ArrayList<Object>();
<ide> Collection<?> c = (operand instanceof Collection) ?
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> if (o instanceof Boolean) {
<ide> if (((Boolean) o).booleanValue() == true) {
<ide> if (variant == FIRST) {
<del> return new TypedValue(element);
<add> return new ValueRef.TypedValueHolderValueRef(new TypedValue(element),this);
<ide> }
<ide> result.add(element);
<ide> }
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> }
<ide> }
<ide> if ((variant == FIRST || variant == LAST) && result.size() == 0) {
<del> return TypedValue.NULL;
<add> return ValueRef.NullValueRef.instance;
<ide> }
<ide> if (variant == LAST) {
<del> return new TypedValue(result.get(result.size() - 1));
<add> return new ValueRef.TypedValueHolderValueRef(new TypedValue(result.get(result.size() - 1)),this);
<ide> }
<ide> if (operand instanceof Collection) {
<del> return new TypedValue(result);
<add> return new ValueRef.TypedValueHolderValueRef(new TypedValue(result),this);
<ide> }
<ide> else {
<ide> Class<?> elementType = ClassUtils.resolvePrimitiveIfNecessary(op.getTypeDescriptor().getElementTypeDescriptor().getType());
<ide> Object resultArray = Array.newInstance(elementType, result.size());
<ide> System.arraycopy(result.toArray(), 0, resultArray, 0, result.size());
<del> return new TypedValue(resultArray);
<add> return new ValueRef.TypedValueHolderValueRef(new TypedValue(resultArray),this);
<ide> }
<ide> } else {
<ide> if (operand==null) {
<ide> if (nullSafe) {
<del> return TypedValue.NULL;
<add> return ValueRef.NullValueRef.instance;
<ide> } else {
<ide> throw new SpelEvaluationException(getStartPosition(), SpelMessage.INVALID_TYPE_FOR_SELECTION,
<ide> "null");
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/SpelNodeImpl.java
<ide> /*
<del> * Copyright 2002-2009 the original author or authors.
<add> * Copyright 2002-2012 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public int getStartPosition() {
<ide>
<ide> public int getEndPosition() {
<ide> return (pos&0xffff);
<del> }
<add> }
<add>
<add> protected ValueRef getValueRef(ExpressionState state) throws EvaluationException {
<add> throw new SpelEvaluationException(pos,SpelMessage.NOT_ASSIGNABLE,toStringAST());
<add> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/ValueRef.java
<add>/*
<add> * Copyright 2002-2012 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.expression.spel.ast;
<add>
<add>import org.springframework.expression.TypedValue;
<add>import org.springframework.expression.spel.SpelEvaluationException;
<add>import org.springframework.expression.spel.SpelMessage;
<add>
<add>/**
<add> * Represents a reference to a value. With a reference it is possible to get or set the
<add> * value. Passing around value references rather than the values themselves can avoid
<add> * incorrect duplication of operand evaluation. For example in 'list[index++]++' without a
<add> * value reference for 'list[index++]' it would be necessary to evaluate list[index++]
<add> * twice (once to get the value, once to determine where the value goes) and that would
<add> * double increment index.
<add> *
<add> * @author Andy Clement
<add> * @since 3.2
<add> */
<add>public interface ValueRef {
<add>
<add> /**
<add> * A ValueRef for the null value.
<add> */
<add> static class NullValueRef implements ValueRef {
<add>
<add> static NullValueRef instance = new NullValueRef();
<add>
<add> public TypedValue getValue() {
<add> return TypedValue.NULL;
<add> }
<add>
<add> public void setValue(Object newValue) {
<add> // The exception position '0' isn't right but the overhead of creating
<add> // instances of this per node (where the node is solely for error reporting)
<add> // would be unfortunate.
<add> throw new SpelEvaluationException(0,SpelMessage.NOT_ASSIGNABLE,"null");
<add> }
<add>
<add> public boolean isWritable() {
<add> return false;
<add> }
<add>
<add> }
<add>
<add> /**
<add> * A ValueRef holder for a single value, which cannot be set.
<add> */
<add> static class TypedValueHolderValueRef implements ValueRef {
<add>
<add> private TypedValue typedValue;
<add> private SpelNodeImpl node; // used only for error reporting
<add>
<add> public TypedValueHolderValueRef(TypedValue typedValue,SpelNodeImpl node) {
<add> this.typedValue = typedValue;
<add> this.node = node;
<add> }
<add>
<add> public TypedValue getValue() {
<add> return typedValue;
<add> }
<add>
<add> public void setValue(Object newValue) {
<add> throw new SpelEvaluationException(
<add> node.pos, SpelMessage.NOT_ASSIGNABLE, node.toStringAST());
<add> }
<add>
<add> public boolean isWritable() {
<add> return false;
<add> }
<add>
<add> }
<add>
<add> /**
<add> * Returns the value this ValueRef points to, it should not require expression
<add> * component re-evaluation.
<add> * @return the value
<add> */
<add> TypedValue getValue();
<add>
<add> /**
<add> * Sets the value this ValueRef points to, it should not require expression component
<add> * re-evaluation.
<add> * @param newValue the new value
<add> */
<add> void setValue(Object newValue);
<add>
<add> /**
<add> * Indicates whether calling setValue(Object) is supported.
<add> * @return true if setValue() is supported for this value reference.
<add> */
<add> boolean isWritable();
<add>}
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/VariableReference.java
<ide> /*
<del> * Copyright 2002-2009 the original author or authors.
<add> * Copyright 2002-2012 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.expression.EvaluationContext;
<ide> import org.springframework.expression.TypedValue;
<ide> import org.springframework.expression.spel.ExpressionState;
<ide> import org.springframework.expression.spel.SpelEvaluationException;
<ide> public VariableReference(String variableName, int pos) {
<ide> }
<ide>
<ide>
<add> class VariableRef implements ValueRef {
<add>
<add> private String name;
<add> private TypedValue value;
<add> private EvaluationContext eContext;
<add>
<add> public VariableRef(String name, TypedValue value,
<add> EvaluationContext evaluationContext) {
<add> this.name = name;
<add> this.value = value;
<add> this.eContext = evaluationContext;
<add> }
<add>
<add> public TypedValue getValue() {
<add> return value;
<add> }
<add>
<add> public void setValue(Object newValue) {
<add> eContext.setVariable(name, newValue);
<add> }
<add>
<add> public boolean isWritable() {
<add> return true;
<add> }
<add>
<add> }
<add>
<add>
<add> @Override
<add> public ValueRef getValueRef(ExpressionState state) throws SpelEvaluationException {
<add> if (this.name.equals(THIS)) {
<add> return new ValueRef.TypedValueHolderValueRef(state.getActiveContextObject(),this);
<add> }
<add> if (this.name.equals(ROOT)) {
<add> return new ValueRef.TypedValueHolderValueRef(state.getRootContextObject(),this);
<add> }
<add> TypedValue result = state.lookupVariable(this.name);
<add> // a null value will mean either the value was null or the variable was not found
<add> return new VariableRef(this.name,result,state.getEvaluationContext());
<add> }
<add>
<ide> @Override
<ide> public TypedValue getValueInternal(ExpressionState state) throws SpelEvaluationException {
<ide> if (this.name.equals(THIS)) {
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java
<ide> import org.springframework.expression.spel.SpelMessage;
<ide> import org.springframework.expression.spel.SpelParseException;
<ide> import org.springframework.expression.spel.SpelParserConfiguration;
<del>import org.springframework.expression.spel.ast.Assign;
<del>import org.springframework.expression.spel.ast.BeanReference;
<del>import org.springframework.expression.spel.ast.BooleanLiteral;
<del>import org.springframework.expression.spel.ast.CompoundExpression;
<del>import org.springframework.expression.spel.ast.ConstructorReference;
<del>import org.springframework.expression.spel.ast.Elvis;
<del>import org.springframework.expression.spel.ast.FunctionReference;
<del>import org.springframework.expression.spel.ast.Identifier;
<del>import org.springframework.expression.spel.ast.Indexer;
<del>import org.springframework.expression.spel.ast.InlineList;
<del>import org.springframework.expression.spel.ast.Literal;
<del>import org.springframework.expression.spel.ast.MethodReference;
<del>import org.springframework.expression.spel.ast.NullLiteral;
<del>import org.springframework.expression.spel.ast.OpAnd;
<del>import org.springframework.expression.spel.ast.OpDivide;
<del>import org.springframework.expression.spel.ast.OpEQ;
<del>import org.springframework.expression.spel.ast.OpGE;
<del>import org.springframework.expression.spel.ast.OpGT;
<del>import org.springframework.expression.spel.ast.OpLE;
<del>import org.springframework.expression.spel.ast.OpLT;
<del>import org.springframework.expression.spel.ast.OpMinus;
<del>import org.springframework.expression.spel.ast.OpModulus;
<del>import org.springframework.expression.spel.ast.OpMultiply;
<del>import org.springframework.expression.spel.ast.OpNE;
<del>import org.springframework.expression.spel.ast.OpOr;
<del>import org.springframework.expression.spel.ast.OpPlus;
<del>import org.springframework.expression.spel.ast.OperatorInstanceof;
<del>import org.springframework.expression.spel.ast.OperatorMatches;
<del>import org.springframework.expression.spel.ast.OperatorNot;
<del>import org.springframework.expression.spel.ast.OperatorPower;
<del>import org.springframework.expression.spel.ast.Projection;
<del>import org.springframework.expression.spel.ast.PropertyOrFieldReference;
<del>import org.springframework.expression.spel.ast.QualifiedIdentifier;
<del>import org.springframework.expression.spel.ast.Selection;
<del>import org.springframework.expression.spel.ast.SpelNodeImpl;
<del>import org.springframework.expression.spel.ast.StringLiteral;
<del>import org.springframework.expression.spel.ast.Ternary;
<del>import org.springframework.expression.spel.ast.TypeReference;
<del>import org.springframework.expression.spel.ast.VariableReference;
<add>import org.springframework.expression.spel.ast.*;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> private SpelNodeImpl eatRelationalExpression() {
<ide> //sumExpression: productExpression ( (PLUS^ | MINUS^) productExpression)*;
<ide> private SpelNodeImpl eatSumExpression() {
<ide> SpelNodeImpl expr = eatProductExpression();
<del> while (peekToken(TokenKind.PLUS,TokenKind.MINUS)) {
<del> Token t = nextToken();//consume PLUS or MINUS
<add> while (peekToken(TokenKind.PLUS,TokenKind.MINUS,TokenKind.INC)) {
<add> Token t = nextToken();//consume PLUS or MINUS or INC
<ide> SpelNodeImpl rhExpr = eatProductExpression();
<ide> checkRightOperand(t,rhExpr);
<ide> if (t.kind==TokenKind.PLUS) {
<ide> expr = new OpPlus(toPos(t),expr,rhExpr);
<del> } else {
<del> Assert.isTrue(t.kind==TokenKind.MINUS);
<add> } else if (t.kind==TokenKind.MINUS) {
<ide> expr = new OpMinus(toPos(t),expr,rhExpr);
<ide> }
<ide> }
<ide> private SpelNodeImpl eatSumExpression() {
<ide>
<ide> // productExpression: powerExpr ((STAR^ | DIV^| MOD^) powerExpr)* ;
<ide> private SpelNodeImpl eatProductExpression() {
<del> SpelNodeImpl expr = eatPowerExpression();
<add> SpelNodeImpl expr = eatPowerIncDecExpression();
<ide> while (peekToken(TokenKind.STAR,TokenKind.DIV,TokenKind.MOD)) {
<ide> Token t = nextToken(); // consume STAR/DIV/MOD
<del> SpelNodeImpl rhExpr = eatPowerExpression();
<add> SpelNodeImpl rhExpr = eatPowerIncDecExpression();
<ide> checkRightOperand(t,rhExpr);
<ide> if (t.kind==TokenKind.STAR) {
<ide> expr = new OpMultiply(toPos(t),expr,rhExpr);
<ide> private SpelNodeImpl eatProductExpression() {
<ide> return expr;
<ide> }
<ide>
<del> // powerExpr : unaryExpression (POWER^ unaryExpression)? ;
<del> private SpelNodeImpl eatPowerExpression() {
<add> // powerExpr : unaryExpression (POWER^ unaryExpression)? (INC || DEC) ;
<add> private SpelNodeImpl eatPowerIncDecExpression() {
<ide> SpelNodeImpl expr = eatUnaryExpression();
<ide> if (peekToken(TokenKind.POWER)) {
<ide> Token t = nextToken();//consume POWER
<ide> SpelNodeImpl rhExpr = eatUnaryExpression();
<ide> checkRightOperand(t,rhExpr);
<ide> return new OperatorPower(toPos(t),expr, rhExpr);
<add> } else if (expr!=null && peekToken(TokenKind.INC,TokenKind.DEC)) {
<add> Token t = nextToken();//consume INC/DEC
<add> if (t.getKind()==TokenKind.INC) {
<add> return new OpInc(toPos(t),true,expr);
<add> } else {
<add> return new OpDec(toPos(t),true,expr);
<add> }
<ide> }
<ide> return expr;
<ide> }
<ide>
<del> // unaryExpression: (PLUS^ | MINUS^ | BANG^) unaryExpression | primaryExpression ;
<add> // unaryExpression: (PLUS^ | MINUS^ | BANG^ | INC^ | DEC^) unaryExpression | primaryExpression ;
<ide> private SpelNodeImpl eatUnaryExpression() {
<ide> if (peekToken(TokenKind.PLUS,TokenKind.MINUS,TokenKind.NOT)) {
<ide> Token t = nextToken();
<ide> private SpelNodeImpl eatUnaryExpression() {
<ide> Assert.isTrue(t.kind==TokenKind.MINUS);
<ide> return new OpMinus(toPos(t),expr);
<ide> }
<add> } else if (peekToken(TokenKind.INC,TokenKind.DEC)) {
<add> Token t = nextToken();
<add> SpelNodeImpl expr = eatUnaryExpression();
<add> if (t.getKind()==TokenKind.INC) {
<add> return new OpInc(toPos(t),false,expr);
<add> } else {
<add> return new OpDec(toPos(t),false,expr);
<add> }
<ide> } else {
<ide> return eatPrimaryExpression();
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/standard/TokenKind.java
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<add>
<ide> package org.springframework.expression.spel.standard;
<ide>
<ide> /**
<ide> enum TokenKind {
<ide> DIV("/"), GE(">="), GT(">"), LE("<="), LT("<"), EQ("=="), NE("!="),
<ide> MOD("%"), NOT("!"), ASSIGN("="), INSTANCEOF("instanceof"), MATCHES("matches"), BETWEEN("between"),
<ide> SELECT("?["), POWER("^"),
<del> ELVIS("?:"), SAFE_NAVI("?."), BEAN_REF("@"), SYMBOLIC_OR("||"), SYMBOLIC_AND("&&")
<add> ELVIS("?:"), SAFE_NAVI("?."), BEAN_REF("@"), SYMBOLIC_OR("||"), SYMBOLIC_AND("&&"), INC("++"), DEC("--")
<ide> ;
<del>
<add>
<ide> char[] tokenChars;
<ide> private boolean hasPayload; // is there more to this token than simply the kind
<del>
<add>
<ide> private TokenKind(String tokenString) {
<ide> tokenChars = tokenString.toCharArray();
<ide> hasPayload = tokenChars.length==0;
<ide> private TokenKind(String tokenString) {
<ide> private TokenKind() {
<ide> this("");
<ide> }
<del>
<add>
<ide> public String toString() {
<ide> return this.name()+(tokenChars.length!=0?"("+new String(tokenChars)+")":"");
<ide> }
<del>
<add>
<ide> public boolean hasPayload() {
<ide> return hasPayload;
<ide> }
<del>
<add>
<ide> public int getLength() {
<ide> return tokenChars.length;
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/standard/Tokenizer.java
<ide> public void process() {
<ide> } else {
<ide> switch (ch) {
<ide> case '+':
<del> pushCharToken(TokenKind.PLUS);
<add> if (isTwoCharToken(TokenKind.INC)) {
<add> pushPairToken(TokenKind.INC);
<add> } else {
<add> pushCharToken(TokenKind.PLUS);
<add> }
<ide> break;
<ide> case '_': // the other way to start an identifier
<ide> lexIdentifier();
<ide> break;
<ide> case '-':
<del> pushCharToken(TokenKind.MINUS);
<add> if (isTwoCharToken(TokenKind.DEC)) {
<add> pushPairToken(TokenKind.DEC);
<add> } else {
<add> pushCharToken(TokenKind.MINUS);
<add> }
<ide> break;
<ide> case ':':
<ide> pushCharToken(TokenKind.COLON);
<ide><path>spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java
<ide>
<ide> import org.springframework.core.convert.TypeDescriptor;
<ide> import org.springframework.expression.AccessException;
<add>import org.springframework.expression.BeanResolver;
<ide> import org.springframework.expression.EvaluationContext;
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.Expression;
<ide>
<ide> /**
<ide> * Tests the evaluation of real expressions in a real context.
<del> *
<add> *
<ide> * @author Andy Clement
<ide> * @author Mark Fisher
<ide> * @author Sam Brannen
<ide> public List<Method> filter(List<Method> methods) {
<ide>
<ide> }
<ide>
<add> // increment/decrement operators - SPR-9751
<add>
<add> static class Spr9751 {
<add> public String type = "hello";
<add> public double ddd = 2.0d;
<add> public float fff = 3.0f;
<add> public long lll = 66666L;
<add> public int iii = 42;
<add> public short sss = (short)15;
<add> public Spr9751_2 foo = new Spr9751_2();
<add>
<add> public void m() {}
<add>
<add> public int[] intArray = new int[]{1,2,3,4,5};
<add> public int index1 = 2;
<add>
<add> public Integer[] integerArray;
<add> public int index2 = 2;
<add>
<add> public List<String> listOfStrings;
<add> public int index3 = 0;
<add>
<add> public Spr9751() {
<add> integerArray = new Integer[5];
<add> integerArray[0] = 1;
<add> integerArray[1] = 2;
<add> integerArray[2] = 3;
<add> integerArray[3] = 4;
<add> integerArray[4] = 5;
<add> listOfStrings = new ArrayList<String>();
<add> listOfStrings.add("abc");
<add> }
<add>
<add> public static boolean isEven(int i) {
<add> return (i%2)==0;
<add> }
<add> }
<add>
<add> static class Spr9751_2 {
<add> public int iii = 99;
<add> }
<add>
<add> /**
<add> * This test is checking that with the changes for 9751 that the refactoring in Indexer is
<add> * coping correctly for references beyond collection boundaries.
<add> */
<add> @Test
<add> public void collectionGrowingViaIndexer() {
<add> Spr9751 instance = new Spr9751();
<add>
<add> // Add a new element to the list
<add> StandardEvaluationContext ctx = new StandardEvaluationContext(instance);
<add> ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
<add> Expression e = parser.parseExpression("listOfStrings[++index3]='def'");
<add> e.getValue(ctx);
<add> assertEquals(2,instance.listOfStrings.size());
<add> assertEquals("def",instance.listOfStrings.get(1));
<add>
<add> // Check reference beyond end of collection
<add> ctx = new StandardEvaluationContext(instance);
<add> parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
<add> e = parser.parseExpression("listOfStrings[0]");
<add> String value = e.getValue(ctx,String.class);
<add> assertEquals("abc",value);
<add> e = parser.parseExpression("listOfStrings[1]");
<add> value = e.getValue(ctx,String.class);
<add> assertEquals("def",value);
<add> e = parser.parseExpression("listOfStrings[2]");
<add> value = e.getValue(ctx,String.class);
<add> assertEquals("",value);
<add>
<add> // Now turn off growing and reference off the end
<add> ctx = new StandardEvaluationContext(instance);
<add> parser = new SpelExpressionParser(new SpelParserConfiguration(false, false));
<add> e = parser.parseExpression("listOfStrings[3]");
<add> try {
<add> e.getValue(ctx,String.class);
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> assertEquals(SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS,see.getMessageCode());
<add> }
<add> }
<add>
<add> // For now I am making #this not assignable
<add> @Test
<add> public void increment01root() {
<add> Integer i = 42;
<add> StandardEvaluationContext ctx = new StandardEvaluationContext(i);
<add> ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
<add> Expression e = parser.parseExpression("#this++");
<add> assertEquals(42,i.intValue());
<add> try {
<add> e.getValue(ctx,Integer.class);
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode());
<add> }
<add> }
<add>
<add> @Test
<add> public void increment02postfix() {
<add> Spr9751 helper = new Spr9751();
<add> StandardEvaluationContext ctx = new StandardEvaluationContext(helper);
<add> ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
<add> Expression e = null;
<add>
<add> // double
<add> e = parser.parseExpression("ddd++");
<add> assertEquals(2.0d,helper.ddd,0d);
<add> double return_ddd = e.getValue(ctx,Double.TYPE);
<add> assertEquals(2.0d,return_ddd,0d);
<add> assertEquals(3.0d,helper.ddd,0d);
<add>
<add> // float
<add> e = parser.parseExpression("fff++");
<add> assertEquals(3.0f,helper.fff,0d);
<add> float return_fff = e.getValue(ctx,Float.TYPE);
<add> assertEquals(3.0f,return_fff,0d);
<add> assertEquals(4.0f,helper.fff,0d);
<add>
<add> // long
<add> e = parser.parseExpression("lll++");
<add> assertEquals(66666L,helper.lll);
<add> long return_lll = e.getValue(ctx,Long.TYPE);
<add> assertEquals(66666L,return_lll);
<add> assertEquals(66667L,helper.lll);
<add>
<add> // int
<add> e = parser.parseExpression("iii++");
<add> assertEquals(42,helper.iii);
<add> int return_iii = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(42,return_iii);
<add> assertEquals(43,helper.iii);
<add> return_iii = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(43,return_iii);
<add> assertEquals(44,helper.iii);
<add>
<add> // short
<add> e = parser.parseExpression("sss++");
<add> assertEquals(15,helper.sss);
<add> short return_sss = e.getValue(ctx,Short.TYPE);
<add> assertEquals(15,return_sss);
<add> assertEquals(16,helper.sss);
<add> }
<add>
<add> @Test
<add> public void increment02prefix() {
<add> Spr9751 helper = new Spr9751();
<add> StandardEvaluationContext ctx = new StandardEvaluationContext(helper);
<add> ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
<add> Expression e = null;
<add>
<add> // double
<add> e = parser.parseExpression("++ddd");
<add> assertEquals(2.0d,helper.ddd,0d);
<add> double return_ddd = e.getValue(ctx,Double.TYPE);
<add> assertEquals(3.0d,return_ddd,0d);
<add> assertEquals(3.0d,helper.ddd,0d);
<add>
<add> // float
<add> e = parser.parseExpression("++fff");
<add> assertEquals(3.0f,helper.fff,0d);
<add> float return_fff = e.getValue(ctx,Float.TYPE);
<add> assertEquals(4.0f,return_fff,0d);
<add> assertEquals(4.0f,helper.fff,0d);
<add>
<add> // long
<add> e = parser.parseExpression("++lll");
<add> assertEquals(66666L,helper.lll);
<add> long return_lll = e.getValue(ctx,Long.TYPE);
<add> assertEquals(66667L,return_lll);
<add> assertEquals(66667L,helper.lll);
<add>
<add> // int
<add> e = parser.parseExpression("++iii");
<add> assertEquals(42,helper.iii);
<add> int return_iii = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(43,return_iii);
<add> assertEquals(43,helper.iii);
<add> return_iii = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(44,return_iii);
<add> assertEquals(44,helper.iii);
<add>
<add> // short
<add> e = parser.parseExpression("++sss");
<add> assertEquals(15,helper.sss);
<add> int return_sss = (Integer)e.getValue(ctx);
<add> assertEquals(16,return_sss);
<add> assertEquals(16,helper.sss);
<add> }
<add>
<add> @Test
<add> public void increment03() {
<add> Spr9751 helper = new Spr9751();
<add> StandardEvaluationContext ctx = new StandardEvaluationContext(helper);
<add> ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
<add> Expression e = null;
<add>
<add> e = parser.parseExpression("m()++");
<add> try {
<add> e.getValue(ctx,Double.TYPE);
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> assertEquals(SpelMessage.OPERAND_NOT_INCREMENTABLE,see.getMessageCode());
<add> }
<add>
<add> e = parser.parseExpression("++m()");
<add> try {
<add> e.getValue(ctx,Double.TYPE);
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> assertEquals(SpelMessage.OPERAND_NOT_INCREMENTABLE,see.getMessageCode());
<add> }
<add> }
<add>
<add>
<add> @Test
<add> public void increment04() {
<add> Integer i = 42;
<add> StandardEvaluationContext ctx = new StandardEvaluationContext(i);
<add> ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
<add> try {
<add> Expression e = parser.parseExpression("++1");
<add> e.getValue(ctx,Integer.class);
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode());
<add> }
<add> try {
<add> Expression e = parser.parseExpression("1++");
<add> e.getValue(ctx,Integer.class);
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode());
<add> }
<add> }
<add> @Test
<add> public void decrement01root() {
<add> Integer i = 42;
<add> StandardEvaluationContext ctx = new StandardEvaluationContext(i);
<add> ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
<add> Expression e = parser.parseExpression("#this--");
<add> assertEquals(42,i.intValue());
<add> try {
<add> e.getValue(ctx,Integer.class);
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode());
<add> }
<add> }
<add>
<add> @Test
<add> public void decrement02postfix() {
<add> Spr9751 helper = new Spr9751();
<add> StandardEvaluationContext ctx = new StandardEvaluationContext(helper);
<add> ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
<add> Expression e = null;
<add>
<add> // double
<add> e = parser.parseExpression("ddd--");
<add> assertEquals(2.0d,helper.ddd,0d);
<add> double return_ddd = e.getValue(ctx,Double.TYPE);
<add> assertEquals(2.0d,return_ddd,0d);
<add> assertEquals(1.0d,helper.ddd,0d);
<add>
<add> // float
<add> e = parser.parseExpression("fff--");
<add> assertEquals(3.0f,helper.fff,0d);
<add> float return_fff = e.getValue(ctx,Float.TYPE);
<add> assertEquals(3.0f,return_fff,0d);
<add> assertEquals(2.0f,helper.fff,0d);
<add>
<add> // long
<add> e = parser.parseExpression("lll--");
<add> assertEquals(66666L,helper.lll);
<add> long return_lll = e.getValue(ctx,Long.TYPE);
<add> assertEquals(66666L,return_lll);
<add> assertEquals(66665L,helper.lll);
<add>
<add> // int
<add> e = parser.parseExpression("iii--");
<add> assertEquals(42,helper.iii);
<add> int return_iii = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(42,return_iii);
<add> assertEquals(41,helper.iii);
<add> return_iii = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(41,return_iii);
<add> assertEquals(40,helper.iii);
<add>
<add> // short
<add> e = parser.parseExpression("sss--");
<add> assertEquals(15,helper.sss);
<add> short return_sss = e.getValue(ctx,Short.TYPE);
<add> assertEquals(15,return_sss);
<add> assertEquals(14,helper.sss);
<add> }
<add>
<add> @Test
<add> public void decrement02prefix() {
<add> Spr9751 helper = new Spr9751();
<add> StandardEvaluationContext ctx = new StandardEvaluationContext(helper);
<add> ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
<add> Expression e = null;
<add>
<add> // double
<add> e = parser.parseExpression("--ddd");
<add> assertEquals(2.0d,helper.ddd,0d);
<add> double return_ddd = e.getValue(ctx,Double.TYPE);
<add> assertEquals(1.0d,return_ddd,0d);
<add> assertEquals(1.0d,helper.ddd,0d);
<add>
<add> // float
<add> e = parser.parseExpression("--fff");
<add> assertEquals(3.0f,helper.fff,0d);
<add> float return_fff = e.getValue(ctx,Float.TYPE);
<add> assertEquals(2.0f,return_fff,0d);
<add> assertEquals(2.0f,helper.fff,0d);
<add>
<add> // long
<add> e = parser.parseExpression("--lll");
<add> assertEquals(66666L,helper.lll);
<add> long return_lll = e.getValue(ctx,Long.TYPE);
<add> assertEquals(66665L,return_lll);
<add> assertEquals(66665L,helper.lll);
<add>
<add> // int
<add> e = parser.parseExpression("--iii");
<add> assertEquals(42,helper.iii);
<add> int return_iii = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(41,return_iii);
<add> assertEquals(41,helper.iii);
<add> return_iii = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(40,return_iii);
<add> assertEquals(40,helper.iii);
<add>
<add> // short
<add> e = parser.parseExpression("--sss");
<add> assertEquals(15,helper.sss);
<add> int return_sss = (Integer)e.getValue(ctx);
<add> assertEquals(14,return_sss);
<add> assertEquals(14,helper.sss);
<add> }
<add>
<add> @Test
<add> public void decrement03() {
<add> Spr9751 helper = new Spr9751();
<add> StandardEvaluationContext ctx = new StandardEvaluationContext(helper);
<add> ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
<add> Expression e = null;
<add>
<add> e = parser.parseExpression("m()--");
<add> try {
<add> e.getValue(ctx,Double.TYPE);
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> assertEquals(SpelMessage.OPERAND_NOT_DECREMENTABLE,see.getMessageCode());
<add> }
<add>
<add> e = parser.parseExpression("--m()");
<add> try {
<add> e.getValue(ctx,Double.TYPE);
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> assertEquals(SpelMessage.OPERAND_NOT_DECREMENTABLE,see.getMessageCode());
<add> }
<add> }
<add>
<add>
<add> @Test
<add> public void decrement04() {
<add> Integer i = 42;
<add> StandardEvaluationContext ctx = new StandardEvaluationContext(i);
<add> ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
<add> try {
<add> Expression e = parser.parseExpression("--1");
<add> e.getValue(ctx,Integer.class);
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode());
<add> }
<add> try {
<add> Expression e = parser.parseExpression("1--");
<add> e.getValue(ctx,Integer.class);
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> assertEquals(SpelMessage.NOT_ASSIGNABLE,see.getMessageCode());
<add> }
<add> }
<add>
<add> @Test
<add> public void incdecTogether() {
<add> Spr9751 helper = new Spr9751();
<add> StandardEvaluationContext ctx = new StandardEvaluationContext(helper);
<add> ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
<add> Expression e = null;
<add>
<add> // index1 is 2 at the start - the 'intArray[#root.index1++]' should not be evaluated twice!
<add> // intArray[2] is 3
<add> e = parser.parseExpression("intArray[#root.index1++]++");
<add> e.getValue(ctx,Integer.class);
<add> assertEquals(3,helper.index1);
<add> assertEquals(4,helper.intArray[2]);
<add>
<add> // index1 is 3 intArray[3] is 4
<add> e = parser.parseExpression("intArray[#root.index1++]--");
<add> assertEquals(4,e.getValue(ctx,Integer.class).intValue());
<add> assertEquals(4,helper.index1);
<add> assertEquals(3,helper.intArray[3]);
<add>
<add> // index1 is 4, intArray[3] is 3
<add> e = parser.parseExpression("intArray[--#root.index1]++");
<add> assertEquals(3,e.getValue(ctx,Integer.class).intValue());
<add> assertEquals(3,helper.index1);
<add> assertEquals(4,helper.intArray[3]);
<add> }
<add>
<add>
<add>
<add>
<add> private void expectFail(ExpressionParser parser, EvaluationContext eContext, String expressionString, SpelMessage messageCode) {
<add> try {
<add> Expression e = parser.parseExpression(expressionString);
<add> SpelUtilities.printAbstractSyntaxTree(System.out, e);
<add> e.getValue(eContext);
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> see.printStackTrace();
<add> assertEquals(messageCode,see.getMessageCode());
<add> }
<add> }
<add>
<add> private void expectFailNotAssignable(ExpressionParser parser, EvaluationContext eContext, String expressionString) {
<add> expectFail(parser,eContext,expressionString,SpelMessage.NOT_ASSIGNABLE);
<add> }
<add>
<add> private void expectFailSetValueNotSupported(ExpressionParser parser, EvaluationContext eContext, String expressionString) {
<add> expectFail(parser,eContext,expressionString,SpelMessage.SETVALUE_NOT_SUPPORTED);
<add> }
<add>
<add> private void expectFailNotIncrementable(ExpressionParser parser, EvaluationContext eContext, String expressionString) {
<add> expectFail(parser,eContext,expressionString,SpelMessage.OPERAND_NOT_INCREMENTABLE);
<add> }
<add>
<add> private void expectFailNotDecrementable(ExpressionParser parser, EvaluationContext eContext, String expressionString) {
<add> expectFail(parser,eContext,expressionString,SpelMessage.OPERAND_NOT_DECREMENTABLE);
<add> }
<add>
<add> // Verify how all the nodes behave with assignment (++, --, =)
<add> @Test
<add> public void incrementAllNodeTypes() throws SecurityException, NoSuchMethodException {
<add> Spr9751 helper = new Spr9751();
<add> StandardEvaluationContext ctx = new StandardEvaluationContext(helper);
<add> ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
<add> Expression e = null;
<add>
<add> // BooleanLiteral
<add> expectFailNotAssignable(parser, ctx, "true++");
<add> expectFailNotAssignable(parser, ctx, "--false");
<add> expectFailSetValueNotSupported(parser, ctx, "true=false");
<add>
<add> // IntLiteral
<add> expectFailNotAssignable(parser, ctx, "12++");
<add> expectFailNotAssignable(parser, ctx, "--1222");
<add> expectFailSetValueNotSupported(parser, ctx, "12=16");
<add>
<add> // LongLiteral
<add> expectFailNotAssignable(parser, ctx, "1.0d++");
<add> expectFailNotAssignable(parser, ctx, "--3.4d");
<add> expectFailSetValueNotSupported(parser, ctx, "1.0d=3.2d");
<add>
<add> // NullLiteral
<add> expectFailNotAssignable(parser, ctx, "null++");
<add> expectFailNotAssignable(parser, ctx, "--null");
<add> expectFailSetValueNotSupported(parser, ctx, "null=null");
<add> expectFailSetValueNotSupported(parser, ctx, "null=123");
<add>
<add> // OpAnd
<add> expectFailNotAssignable(parser, ctx, "(true && false)++");
<add> expectFailNotAssignable(parser, ctx, "--(false AND true)");
<add> expectFailSetValueNotSupported(parser, ctx, "(true && false)=(false && true)");
<add>
<add> // OpDivide
<add> expectFailNotAssignable(parser, ctx, "(3/4)++");
<add> expectFailNotAssignable(parser, ctx, "--(2/5)");
<add> expectFailSetValueNotSupported(parser, ctx, "(1/2)=(3/4)");
<add>
<add> // OpEq
<add> expectFailNotAssignable(parser, ctx, "(3==4)++");
<add> expectFailNotAssignable(parser, ctx, "--(2==5)");
<add> expectFailSetValueNotSupported(parser, ctx, "(1==2)=(3==4)");
<add>
<add> // OpGE
<add> expectFailNotAssignable(parser, ctx, "(3>=4)++");
<add> expectFailNotAssignable(parser, ctx, "--(2>=5)");
<add> expectFailSetValueNotSupported(parser, ctx, "(1>=2)=(3>=4)");
<add>
<add> // OpGT
<add> expectFailNotAssignable(parser, ctx, "(3>4)++");
<add> expectFailNotAssignable(parser, ctx, "--(2>5)");
<add> expectFailSetValueNotSupported(parser, ctx, "(1>2)=(3>4)");
<add>
<add> // OpLE
<add> expectFailNotAssignable(parser, ctx, "(3<=4)++");
<add> expectFailNotAssignable(parser, ctx, "--(2<=5)");
<add> expectFailSetValueNotSupported(parser, ctx, "(1<=2)=(3<=4)");
<add>
<add> // OpLT
<add> expectFailNotAssignable(parser, ctx, "(3<4)++");
<add> expectFailNotAssignable(parser, ctx, "--(2<5)");
<add> expectFailSetValueNotSupported(parser, ctx, "(1<2)=(3<4)");
<add>
<add> // OpMinus
<add> expectFailNotAssignable(parser, ctx, "(3-4)++");
<add> expectFailNotAssignable(parser, ctx, "--(2-5)");
<add> expectFailSetValueNotSupported(parser, ctx, "(1-2)=(3-4)");
<add>
<add> // OpModulus
<add> expectFailNotAssignable(parser, ctx, "(3%4)++");
<add> expectFailNotAssignable(parser, ctx, "--(2%5)");
<add> expectFailSetValueNotSupported(parser, ctx, "(1%2)=(3%4)");
<add>
<add> // OpMultiply
<add> expectFailNotAssignable(parser, ctx, "(3*4)++");
<add> expectFailNotAssignable(parser, ctx, "--(2*5)");
<add> expectFailSetValueNotSupported(parser, ctx, "(1*2)=(3*4)");
<add>
<add> // OpNE
<add> expectFailNotAssignable(parser, ctx, "(3!=4)++");
<add> expectFailNotAssignable(parser, ctx, "--(2!=5)");
<add> expectFailSetValueNotSupported(parser, ctx, "(1!=2)=(3!=4)");
<add>
<add> // OpOr
<add> expectFailNotAssignable(parser, ctx, "(true || false)++");
<add> expectFailNotAssignable(parser, ctx, "--(false OR true)");
<add> expectFailSetValueNotSupported(parser, ctx, "(true || false)=(false OR true)");
<add>
<add> // OpPlus
<add> expectFailNotAssignable(parser, ctx, "(3+4)++");
<add> expectFailNotAssignable(parser, ctx, "--(2+5)");
<add> expectFailSetValueNotSupported(parser, ctx, "(1+2)=(3+4)");
<add>
<add> // RealLiteral
<add> expectFailNotAssignable(parser, ctx, "1.0d++");
<add> expectFailNotAssignable(parser, ctx, "--2.0d");
<add> expectFailSetValueNotSupported(parser, ctx, "(1.0d)=(3.0d)");
<add> expectFailNotAssignable(parser, ctx, "1.0f++");
<add> expectFailNotAssignable(parser, ctx, "--2.0f");
<add> expectFailSetValueNotSupported(parser, ctx, "(1.0f)=(3.0f)");
<add>
<add> // StringLiteral
<add> expectFailNotAssignable(parser, ctx, "'abc'++");
<add> expectFailNotAssignable(parser, ctx, "--'def'");
<add> expectFailSetValueNotSupported(parser, ctx, "'abc'='def'");
<add>
<add> // Ternary
<add> expectFailNotAssignable(parser, ctx, "(true?true:false)++");
<add> expectFailNotAssignable(parser, ctx, "--(true?true:false)");
<add> expectFailSetValueNotSupported(parser, ctx, "(true?true:false)=(true?true:false)");
<add>
<add> // TypeReference
<add> expectFailNotAssignable(parser, ctx, "T(String)++");
<add> expectFailNotAssignable(parser, ctx, "--T(Integer)");
<add> expectFailSetValueNotSupported(parser, ctx, "T(String)=T(Integer)");
<add>
<add> // OperatorBetween
<add> expectFailNotAssignable(parser, ctx, "(3 between {1,5})++");
<add> expectFailNotAssignable(parser, ctx, "--(3 between {1,5})");
<add> expectFailSetValueNotSupported(parser, ctx, "(3 between {1,5})=(3 between {1,5})");
<add>
<add> // OperatorInstanceOf
<add> expectFailNotAssignable(parser, ctx, "(type instanceof T(String))++");
<add> expectFailNotAssignable(parser, ctx, "--(type instanceof T(String))");
<add> expectFailSetValueNotSupported(parser, ctx, "(type instanceof T(String))=(type instanceof T(String))");
<add>
<add> // Elvis
<add> expectFailNotAssignable(parser, ctx, "(true?:false)++");
<add> expectFailNotAssignable(parser, ctx, "--(true?:false)");
<add> expectFailSetValueNotSupported(parser, ctx, "(true?:false)=(true?:false)");
<add>
<add> // OpInc
<add> expectFailNotAssignable(parser, ctx, "(iii++)++");
<add> expectFailNotAssignable(parser, ctx, "--(++iii)");
<add> expectFailSetValueNotSupported(parser, ctx, "(iii++)=(++iii)");
<add>
<add> // OpDec
<add> expectFailNotAssignable(parser, ctx, "(iii--)++");
<add> expectFailNotAssignable(parser, ctx, "--(--iii)");
<add> expectFailSetValueNotSupported(parser, ctx, "(iii--)=(--iii)");
<add>
<add> // OperatorNot
<add> expectFailNotAssignable(parser, ctx, "(!true)++");
<add> expectFailNotAssignable(parser, ctx, "--(!false)");
<add> expectFailSetValueNotSupported(parser, ctx, "(!true)=(!false)");
<add>
<add> // OperatorPower
<add> expectFailNotAssignable(parser, ctx, "(iii^2)++");
<add> expectFailNotAssignable(parser, ctx, "--(iii^2)");
<add> expectFailSetValueNotSupported(parser, ctx, "(iii^2)=(iii^3)");
<add>
<add> // Assign
<add> // iii=42
<add> e = parser.parseExpression("iii=iii++");
<add> assertEquals(42,helper.iii);
<add> int return_iii = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(42,helper.iii);
<add> assertEquals(42,return_iii);
<add>
<add> // Identifier
<add> e = parser.parseExpression("iii++");
<add> assertEquals(42,helper.iii);
<add> return_iii = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(42,return_iii);
<add> assertEquals(43,helper.iii);
<add>
<add> e = parser.parseExpression("--iii");
<add> assertEquals(43,helper.iii);
<add> return_iii = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(42,return_iii);
<add> assertEquals(42,helper.iii);
<add>
<add> e = parser.parseExpression("iii=99");
<add> assertEquals(42,helper.iii);
<add> return_iii = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(99,return_iii);
<add> assertEquals(99,helper.iii);
<add>
<add> // CompoundExpression
<add> // foo.iii == 99
<add> e = parser.parseExpression("foo.iii++");
<add> assertEquals(99,helper.foo.iii);
<add> int return_foo_iii = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(99,return_foo_iii);
<add> assertEquals(100,helper.foo.iii);
<add>
<add> e = parser.parseExpression("--foo.iii");
<add> assertEquals(100,helper.foo.iii);
<add> return_foo_iii = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(99,return_foo_iii);
<add> assertEquals(99,helper.foo.iii);
<add>
<add> e = parser.parseExpression("foo.iii=999");
<add> assertEquals(99,helper.foo.iii);
<add> return_foo_iii = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(999,return_foo_iii);
<add> assertEquals(999,helper.foo.iii);
<add>
<add> // ConstructorReference
<add> expectFailNotAssignable(parser, ctx, "(new String('abc'))++");
<add> expectFailNotAssignable(parser, ctx, "--(new String('abc'))");
<add> expectFailSetValueNotSupported(parser, ctx, "(new String('abc'))=(new String('abc'))");
<add>
<add> // MethodReference
<add> expectFailNotIncrementable(parser, ctx, "m()++");
<add> expectFailNotDecrementable(parser, ctx, "--m()");
<add> expectFailSetValueNotSupported(parser, ctx, "m()=m()");
<add>
<add> // OperatorMatches
<add> expectFailNotAssignable(parser, ctx, "('abc' matches '^a..')++");
<add> expectFailNotAssignable(parser, ctx, "--('abc' matches '^a..')");
<add> expectFailSetValueNotSupported(parser, ctx, "('abc' matches '^a..')=('abc' matches '^a..')");
<add>
<add> // Selection
<add> ctx.registerFunction("isEven", Spr9751.class.getDeclaredMethod("isEven", Integer.TYPE));
<add>
<add> expectFailNotIncrementable(parser, ctx, "({1,2,3}.?[#isEven(#this)])++");
<add> expectFailNotDecrementable(parser, ctx, "--({1,2,3}.?[#isEven(#this)])");
<add> expectFailNotAssignable(parser, ctx, "({1,2,3}.?[#isEven(#this)])=({1,2,3}.?[#isEven(#this)])");
<add>
<add> // slightly diff here because return value isn't a list, it is a single entity
<add> expectFailNotAssignable(parser, ctx, "({1,2,3}.^[#isEven(#this)])++");
<add> expectFailNotAssignable(parser, ctx, "--({1,2,3}.^[#isEven(#this)])");
<add> expectFailNotAssignable(parser, ctx, "({1,2,3}.^[#isEven(#this)])=({1,2,3}.^[#isEven(#this)])");
<add>
<add> expectFailNotAssignable(parser, ctx, "({1,2,3}.$[#isEven(#this)])++");
<add> expectFailNotAssignable(parser, ctx, "--({1,2,3}.$[#isEven(#this)])");
<add> expectFailNotAssignable(parser, ctx, "({1,2,3}.$[#isEven(#this)])=({1,2,3}.$[#isEven(#this)])");
<add>
<add> // FunctionReference
<add> expectFailNotAssignable(parser, ctx, "#isEven(3)++");
<add> expectFailNotAssignable(parser, ctx, "--#isEven(4)");
<add> expectFailSetValueNotSupported(parser, ctx, "#isEven(3)=#isEven(5)");
<add>
<add> // VariableReference
<add> ctx.setVariable("wibble", "hello world");
<add> expectFailNotIncrementable(parser, ctx, "#wibble++");
<add> expectFailNotDecrementable(parser, ctx, "--#wibble");
<add> e = parser.parseExpression("#wibble=#wibble+#wibble");
<add> String s = e.getValue(ctx,String.class);
<add> assertEquals("hello worldhello world",s);
<add> assertEquals("hello worldhello world",(String)ctx.lookupVariable("wibble"));
<add>
<add> ctx.setVariable("wobble", 3);
<add> e = parser.parseExpression("#wobble++");
<add> assertEquals(3,((Integer)ctx.lookupVariable("wobble")).intValue());
<add> int r = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(3,r);
<add> assertEquals(4,((Integer)ctx.lookupVariable("wobble")).intValue());
<add>
<add> e = parser.parseExpression("--#wobble");
<add> assertEquals(4,((Integer)ctx.lookupVariable("wobble")).intValue());
<add> r = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(3,r);
<add> assertEquals(3,((Integer)ctx.lookupVariable("wobble")).intValue());
<add>
<add> e = parser.parseExpression("#wobble=34");
<add> assertEquals(3,((Integer)ctx.lookupVariable("wobble")).intValue());
<add> r = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(34,r);
<add> assertEquals(34,((Integer)ctx.lookupVariable("wobble")).intValue());
<add>
<add> // Projection
<add> expectFailNotIncrementable(parser, ctx, "({1,2,3}.![#isEven(#this)])++"); // projection would be {false,true,false}
<add> expectFailNotDecrementable(parser, ctx, "--({1,2,3}.![#isEven(#this)])"); // projection would be {false,true,false}
<add> expectFailNotAssignable(parser, ctx, "({1,2,3}.![#isEven(#this)])=({1,2,3}.![#isEven(#this)])");
<add>
<add> // InlineList
<add> expectFailNotAssignable(parser, ctx, "({1,2,3})++");
<add> expectFailNotAssignable(parser, ctx, "--({1,2,3})");
<add> expectFailSetValueNotSupported(parser, ctx, "({1,2,3})=({1,2,3})");
<add>
<add> // BeanReference
<add> ctx.setBeanResolver(new MyBeanResolver());
<add> expectFailNotAssignable(parser, ctx, "@foo++");
<add> expectFailNotAssignable(parser, ctx, "--@foo");
<add> expectFailSetValueNotSupported(parser, ctx, "@foo=@bar");
<add>
<add> // PropertyOrFieldReference
<add> helper.iii = 42;
<add> e = parser.parseExpression("iii++");
<add> assertEquals(42,helper.iii);
<add> r = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(42,r);
<add> assertEquals(43,helper.iii);
<add>
<add> e = parser.parseExpression("--iii");
<add> assertEquals(43,helper.iii);
<add> r = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(42,r);
<add> assertEquals(42,helper.iii);
<add>
<add> e = parser.parseExpression("iii=100");
<add> assertEquals(42,helper.iii);
<add> r = e.getValue(ctx,Integer.TYPE);
<add> assertEquals(100,r);
<add> assertEquals(100,helper.iii);
<add>
<add> }
<add>
<add> static class MyBeanResolver implements BeanResolver {
<add>
<add> public Object resolve(EvaluationContext context, String beanName)
<add> throws AccessException {
<add> if (beanName.equals("foo") || beanName.equals("bar")) {
<add> return new Spr9751_2();
<add> }
<add> throw new AccessException("not heard of "+beanName);
<add> }
<add>
<add> }
<add>
<add>
<ide> }
<ide><path>spring-expression/src/test/java/org/springframework/expression/spel/InProgressTests.java
<ide> /*
<del> * Copyright 2002-2009 the original author or authors.
<add> * Copyright 2002-2012 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<add>
<ide> package org.springframework.expression.spel;
<ide>
<ide> import java.util.ArrayList;
<ide>
<ide> import org.junit.Test;
<ide> import org.springframework.expression.spel.standard.SpelExpression;
<del>import org.springframework.expression.spel.support.StandardEvaluationContext;
<ide>
<ide> /**
<ide> * These are tests for language features that are not yet considered 'live'. Either missing implementation or
<ide> * documentation.
<del> *
<add> *
<ide> * Where implementation is missing the tests are commented out.
<del> *
<add> *
<ide> * @author Andy Clement
<ide> */
<ide> public class InProgressTests extends ExpressionTestCase {
<ide>
<ide> @Test
<ide> public void testRelOperatorsBetween01() {
<ide> evaluate("1 between listOneFive", "true", Boolean.class);
<del> // evaluate("1 between {1, 5}", "true", Boolean.class); // no inline list building at the moment
<add> // no inline list building at the moment
<add> // evaluate("1 between {1, 5}", "true", Boolean.class);
<ide> }
<ide>
<ide> @Test
<ide> public void testProjection05() {
<ide> public void testProjection06() throws Exception {
<ide> SpelExpression expr = (SpelExpression) parser.parseExpression("'abc'.![true]");
<ide> Assert.assertEquals("'abc'.![true]", expr.toStringAST());
<del> Assert.assertFalse(expr.isWritable(new StandardEvaluationContext()));
<ide> }
<ide>
<ide> // SELECTION
<ide> public void testSelectionError_NonBooleanSelectionCriteria() {
<ide> @Test
<ide> public void testSelection03() {
<ide> evaluate("mapOfNumbersUpToTen.?[key>5].size()", "5", Integer.class);
<del> // evaluate("listOfNumbersUpToTen.?{#this>5}", "5", ArrayList.class);
<ide> }
<ide>
<ide> @Test
<ide> public void testSelectionLast02() {
<ide> public void testSelectionAST() throws Exception {
<ide> SpelExpression expr = (SpelExpression) parser.parseExpression("'abc'.^[true]");
<ide> Assert.assertEquals("'abc'.^[true]", expr.toStringAST());
<del> Assert.assertFalse(expr.isWritable(new StandardEvaluationContext()));
<ide> expr = (SpelExpression) parser.parseExpression("'abc'.?[true]");
<ide> Assert.assertEquals("'abc'.?[true]", expr.toStringAST());
<del> Assert.assertFalse(expr.isWritable(new StandardEvaluationContext()));
<ide> expr = (SpelExpression) parser.parseExpression("'abc'.$[true]");
<ide> Assert.assertEquals("'abc'.$[true]", expr.toStringAST());
<del> Assert.assertFalse(expr.isWritable(new StandardEvaluationContext()));
<ide> }
<ide>
<ide> // Constructor invocation
<del>
<del> // public void testPrimitiveTypeArrayConstructors() {
<del> // evaluate("new int[]{1,2,3,4}.count()", 4, Integer.class);
<del> // evaluate("new boolean[]{true,false,true}.count()", 3, Integer.class);
<del> // evaluate("new char[]{'a','b','c'}.count()", 3, Integer.class);
<del> // evaluate("new long[]{1,2,3,4,5}.count()", 5, Integer.class);
<del> // evaluate("new short[]{2,3,4,5,6}.count()", 5, Integer.class);
<del> // evaluate("new double[]{1d,2d,3d,4d}.count()", 4, Integer.class);
<del> // evaluate("new float[]{1f,2f,3f,4f}.count()", 4, Integer.class);
<del> // evaluate("new byte[]{1,2,3,4}.count()", 4, Integer.class);
<del> // }
<del> //
<del> // public void testPrimitiveTypeArrayConstructorsElements() {
<del> // evaluate("new int[]{1,2,3,4}[0]", 1, Integer.class);
<del> // evaluate("new boolean[]{true,false,true}[0]", true, Boolean.class);
<del> // evaluate("new char[]{'a','b','c'}[0]", 'a', Character.class);
<del> // evaluate("new long[]{1,2,3,4,5}[0]", 1L, Long.class);
<del> // evaluate("new short[]{2,3,4,5,6}[0]", (short) 2, Short.class);
<del> // evaluate("new double[]{1d,2d,3d,4d}[0]", (double) 1, Double.class);
<del> // evaluate("new float[]{1f,2f,3f,4f}[0]", (float) 1, Float.class);
<del> // evaluate("new byte[]{1,2,3,4}[0]", (byte) 1, Byte.class);
<del> // }
<del> //
<del> // public void testErrorCases() {
<del> // evaluateAndCheckError("new char[7]{'a','c','d','e'}", SpelMessages.INITIALIZER_LENGTH_INCORRECT);
<del> // evaluateAndCheckError("new char[3]{'a','c','d','e'}", SpelMessages.INITIALIZER_LENGTH_INCORRECT);
<del> // evaluateAndCheckError("new char[2]{'hello','world'}", SpelMessages.TYPE_CONVERSION_ERROR);
<del> // evaluateAndCheckError("new String('a','c','d')", SpelMessages.CONSTRUCTOR_NOT_FOUND);
<del> // }
<del> //
<del> // public void testTypeArrayConstructors() {
<del> // evaluate("new String[]{'a','b','c','d'}[1]", "b", String.class);
<del> // evaluateAndCheckError("new String[]{'a','b','c','d'}.size()", SpelMessages.METHOD_NOT_FOUND, 30, "size()",
<del> // "java.lang.String[]");
<del> // evaluateAndCheckError("new String[]{'a','b','c','d'}.juggernaut", SpelMessages.PROPERTY_OR_FIELD_NOT_FOUND, 30,
<del> // "juggernaut", "java.lang.String[]");
<del> // evaluate("new String[]{'a','b','c','d'}.length", 4, Integer.class);
<del> // }
<del>
<del> // public void testMultiDimensionalArrays() {
<del> // evaluate(
<del> // "new String[3,4]",
<del> // "[Ljava.lang.String;[3]{java.lang.String[4]{null,null,null,null},java.lang.String[4]{null,null,null,null},java.lang.String[4]{null,null,null,null}}"
<del> // ,
<del> // new String[3][4].getClass());
<del> // }
<del> //
<del> //
<del> // evaluate("new String(new char[]{'h','e','l','l','o'})", "hello", String.class);
<del> //
<del> //
<del> //
<del> // public void testRelOperatorsIn01() {
<del> // evaluate("3 in {1,2,3,4,5}", "true", Boolean.class);
<del> // }
<del> //
<del> // public void testRelOperatorsIn02() {
<del> // evaluate("name in {null, \"Nikola Tesla\"}", "true", Boolean.class);
<del> // evaluate("name in {null, \"Anonymous\"}", "false", Boolean.class);
<del> // }
<del> //
<del> //
<del> // public void testRelOperatorsBetween02() {
<del> // evaluate("'efg' between {'abc', 'xyz'}", "true", Boolean.class);
<del> // }
<del> //
<del> //
<del> // public void testRelOperatorsBetweenErrors02() {
<del> // evaluateAndCheckError("'abc' between {5,7}", SpelMessages.NOT_COMPARABLE, 6);
<del> // }
<del> // Lambda calculations
<del> //
<del> //
<del> // public void testLambda02() {
<del> // evaluate("(#max={|x,y| $x > $y ? $x : $y };true)", "true", Boolean.class);
<del> // }
<del> //
<del> // public void testLambdaMax() {
<del> // evaluate("(#max = {|x,y| $x > $y ? $x : $y }; #max(5,25))", "25", Integer.class);
<del> // }
<del> //
<del> // public void testLambdaFactorial01() {
<del> // evaluate("(#fact = {|n| $n <= 1 ? 1 : $n * #fact($n-1) }; #fact(5))", "120", Integer.class);
<del> // }
<del> //
<del> // public void testLambdaFactorial02() {
<del> // evaluate("(#fact = {|n| $n <= 1 ? 1 : #fact($n-1) * $n }; #fact(5))", "120", Integer.class);
<del> // }
<del> //
<del> // public void testLambdaAlphabet01() {
<del> // evaluate("(#alpha = {|l,s| $l>'z'?$s:#alpha($l+1,$s+$l)};#alphabet={||#alpha('a','')}; #alphabet())",
<del> // "abcdefghijklmnopqrstuvwxyz", String.class);
<del> // }
<del> //
<del> // public void testLambdaAlphabet02() {
<del> // evaluate("(#alphabet = {|l,s| $l>'z'?$s:#alphabet($l+1,$s+$l)};#alphabet('a',''))",
<del> // "abcdefghijklmnopqrstuvwxyz", String.class);
<del> // }
<del> //
<del> // public void testLambdaDelegation01() {
<del> // evaluate("(#sqrt={|n| T(Math).sqrt($n)};#delegate={|f,n| $f($n)};#delegate(#sqrt,4))", "2.0", Double.class);
<del> // }
<del> //
<del> // public void testVariableReferences() {
<del> // evaluate("(#answer=42;#answer)", "42", Integer.class, true);
<del> // evaluate("($answer=42;$answer)", "42", Integer.class, true);
<del> // }
<del>
<del>// // inline map creation
<del> // @Test
<del> // public void testInlineMapCreation01() {
<del> // evaluate("#{'key1':'Value 1', 'today':'Monday'}", "{key1=Value 1, today=Monday}", HashMap.class);
<del> // }
<del> //
<del> // @Test
<del> // public void testInlineMapCreation02() {
<del> // // "{2=February, 1=January, 3=March}", HashMap.class);
<del> // evaluate("#{1:'January', 2:'February', 3:'March'}.size()", 3, Integer.class);
<del> // }
<del> //
<del> // @Test
<del> // public void testInlineMapCreation03() {
<del> // evaluate("#{'key1':'Value 1', 'today':'Monday'}['key1']", "Value 1", String.class);
<del>// }
<del>//
<del>// @Test
<del>// public void testInlineMapCreation04() {
<del>// evaluate("#{1:'January', 2:'February', 3:'March'}[3]", "March", String.class);
<del>// }
<del>//
<del>// @Test
<del>// public void testInlineMapCreation05() {
<del>// evaluate("#{1:'January', 2:'February', 3:'March'}.get(2)", "February", String.class);
<del>// }
<del>
<del> // set construction
<ide> @Test
<ide> public void testSetConstruction01() {
<ide> evaluate("new java.util.HashSet().addAll({'a','b','c'})", "true", Boolean.class);
<ide> }
<ide>
<del> //
<del> // public void testConstructorInvocation02() {
<del> // evaluate("new String[3]", "java.lang.String[3]{null,null,null}", String[].class);
<del> // }
<del> //
<del> // public void testConstructorInvocation03() {
<del> // evaluateAndCheckError("new String[]", SpelMessages.NO_SIZE_OR_INITIALIZER_FOR_ARRAY_CONSTRUCTION, 4);
<del> // }
<del> //
<del> // public void testConstructorInvocation04() {
<del> // evaluateAndCheckError("new String[3]{'abc',3,'def'}", SpelMessages.INCORRECT_ELEMENT_TYPE_FOR_ARRAY, 4);
<del> // }
<del> // array construction
<del> // @Test
<del> // public void testArrayConstruction01() {
<del> // evaluate("new int[] {1, 2, 3, 4, 5}", "int[5]{1,2,3,4,5}", int[].class);
<del> // }
<del> // public void testArrayConstruction02() {
<del> // evaluate("new String[] {'abc', 'xyz'}", "java.lang.String[2]{abc,xyz}", String[].class);
<del> // }
<del> //
<del> // collection processors
<del> // from spring.net: count,sum,max,min,average,sort,orderBy,distinct,nonNull
<del> // public void testProcessorsCount01() {
<del> // evaluate("new String[] {'abc','def','xyz'}.count()", "3", Integer.class);
<del> // }
<del> //
<del> // public void testProcessorsCount02() {
<del> // evaluate("new int[] {1,2,3}.count()", "3", Integer.class);
<del> // }
<del> //
<del> // public void testProcessorsMax01() {
<del> // evaluate("new int[] {1,2,3}.max()", "3", Integer.class);
<del> // }
<del> //
<del> // public void testProcessorsMin01() {
<del> // evaluate("new int[] {1,2,3}.min()", "1", Integer.class);
<del> // }
<del> //
<del> // public void testProcessorsKeys01() {
<del> // evaluate("#{1:'January', 2:'February', 3:'March'}.keySet().sort()", "[1, 2, 3]", ArrayList.class);
<del> // }
<del> //
<del> // public void testProcessorsValues01() {
<del> // evaluate("#{1:'January', 2:'February', 3:'March'}.values().sort()", "[February, January, March]",
<del> // ArrayList.class);
<del> // }
<del> //
<del> // public void testProcessorsAverage01() {
<del> // evaluate("new int[] {1,2,3}.average()", "2", Integer.class);
<del> // }
<del> //
<del> // public void testProcessorsSort01() {
<del> // evaluate("new int[] {3,2,1}.sort()", "int[3]{1,2,3}", int[].class);
<del> // }
<del> //
<del> // public void testCollectionProcessorsNonNull01() {
<del> // evaluate("{'a','b',null,'d',null}.nonnull()", "[a, b, d]", ArrayList.class);
<del> // }
<del> //
<del> // public void testCollectionProcessorsDistinct01() {
<del> // evaluate("{'a','b','a','d','e'}.distinct()", "[a, b, d, e]", ArrayList.class);
<del> // }
<del> //
<del> // public void testProjection03() {
<del> // evaluate("{1,2,3,4,5,6,7,8,9,10}.!{#this>5}",
<del> // "[false, false, false, false, false, true, true, true, true, true]", ArrayList.class);
<del> // }
<del> //
<del> // public void testProjection04() {
<del> // evaluate("{1,2,3,4,5,6,7,8,9,10}.!{$index>5?'y':'n'}", "[n, n, n, n, n, n, y, y, y, y]", ArrayList.class);
<del> // }
<del> // Bean references
<del> // public void testReferences01() {
<del> // evaluate("@(apple).name", "Apple", String.class, true);
<del> // }
<del> //
<del> // public void testReferences02() {
<del> // evaluate("@(fruits:banana).name", "Banana", String.class, true);
<del> // }
<del> //
<del> // public void testReferences03() {
<del> // evaluate("@(a.b.c)", null, null);
<del> // } // null - no context, a.b.c treated as name
<del> //
<del> // public void testReferences05() {
<del> // evaluate("@(a/b/c:orange).name", "Orange", String.class, true);
<del> // }
<del> //
<del> // public void testReferences06() {
<del> // evaluate("@(apple).color.getRGB() == T(java.awt.Color).green.getRGB()", "true", Boolean.class);
<del> // }
<del> //
<del> // public void testReferences07() {
<del> // evaluate("@(apple).color.getRGB().equals(T(java.awt.Color).green.getRGB())", "true", Boolean.class);
<del> // }
<del> //
<del> // value is not public, it is accessed through getRGB()
<del> // public void testStaticRef01() {
<del> // evaluate("T(Color).green.value!=0", "true", Boolean.class);
<del> // }
<del> // Indexer
<del> // public void testCutProcessor01() {
<del> // evaluate("{1,2,3,4,5}.cut(1,3)", "[2, 3, 4]", ArrayList.class);
<del> // }
<del> //
<del> // public void testCutProcessor02() {
<del> // evaluate("{1,2,3,4,5}.cut(3,1)", "[4, 3, 2]", ArrayList.class);
<del> // }
<del> // Ternary operator
<del> // public void testTernaryOperator01() {
<del> // evaluate("{1}.#isEven(#this[0]) == 'y'?'it is even':'it is odd'", "it is odd", String.class);
<del> // }
<del> //
<del> // public void testTernaryOperator02() {
<del> // evaluate("{2}.#isEven(#this[0]) == 'y'?'it is even':'it is odd'", "it is even", String.class);
<del> // }
<del> // public void testSelectionUsingIndex() {
<del> // evaluate("{1,2,3,4,5,6,7,8,9,10}.?{$index > 5 }", "[7, 8, 9, 10]", ArrayList.class);
<del> // }
<del> // public void testSelection01() {
<del> // inline list creation not supported:
<del> // evaluate("{1,2,3,4,5,6,7,8,9,10}.?{#isEven(#this) == 'y'}", "[2, 4, 6, 8, 10]", ArrayList.class);
<del> // }
<del> //
<del> // public void testSelectionUsingIndex() {
<del> // evaluate("listOfNumbersUpToTen.?[#index > 5 ]", "[7, 8, 9, 10]", ArrayList.class);
<del> // }
<del>
<ide> } | 19 |
Ruby | Ruby | add the storage.yml file by default | 3e723543296a1553452887e27801e563aadcdcb1 | <ide><path>railties/lib/rails/generators/rails/app/app_generator.rb
<ide> def config
<ide> template "cable.yml" unless options[:skip_action_cable]
<ide> template "puma.rb" unless options[:skip_puma]
<ide> template "spring.rb" if spring_install?
<add> template "storage.yml"
<ide>
<ide> directory "environments"
<ide> directory "initializers" | 1 |
PHP | PHP | pass scope to log engines | d819fa48c1782d49506438806182f83d94e70ddf | <ide><path>Cake/Log/Engine/ConsoleLog.php
<ide> public function __construct($config = array()) {
<ide> *
<ide> * @param string $type The type of log you are making.
<ide> * @param string $message The message you want to log.
<add> * @param string|array $scope The scope(s) a log message is being created in.
<add> * See Cake\Log\Log::config() for more information on logging scopes.
<ide> * @return boolean success of write.
<ide> */
<del> public function write($type, $message) {
<add> public function write($type, $message, $scope = []) {
<ide> $output = date('Y-m-d H:i:s') . ' ' . ucfirst($type) . ': ' . $message . "\n";
<ide> return $this->_output->write(sprintf('<%s>%s</%s>', $type, $output, $type), false);
<ide> }
<ide><path>Cake/Log/Engine/FileLog.php
<ide> public function config($config = array()) {
<ide> *
<ide> * @param string $type The type of log you are making.
<ide> * @param string $message The message you want to log.
<add> * @param string|array $scope The scope(s) a log message is being created in.
<add> * See Cake\Log\Log::config() for more information on logging scopes.
<ide> * @return boolean success of write.
<ide> */
<del> public function write($type, $message) {
<add> public function write($type, $message, $scope = []) {
<ide> $output = date('Y-m-d H:i:s') . ' ' . ucfirst($type) . ': ' . $message . "\n";
<ide> $filename = $this->_getFilename($type);
<ide> if (!empty($this->_size)) {
<ide><path>Cake/Log/Engine/SyslogLog.php
<ide> public function __construct($config = array()) {
<ide> *
<ide> * @param string $type The type of log you are making.
<ide> * @param string $message The message you want to log.
<add> * @param string|array $scope The scope(s) a log message is being created in.
<add> * See Cake\Log\Log::config() for more information on logging scopes.
<ide> * @return boolean success of write.
<ide> */
<del> public function write($type, $message) {
<add> public function write($type, $message, $scope = []) {
<ide> if (!$this->_open) {
<ide> $config = $this->_config;
<ide> $this->_open($config['prefix'], $config['flag'], $config['facility']);
<ide><path>Cake/Log/Log.php
<ide> public static function write($level, $message, $scope = array()) {
<ide> count(array_intersect((array)$scope, $scopes)) > 0
<ide> );
<ide> if ($correctLevel && $inScope) {
<del> $logger->write($level, $message);
<add> $logger->write($level, $message, $scope);
<ide> $logged = true;
<ide> }
<ide> }
<ide><path>Cake/Log/LogInterface.php
<ide> interface LogInterface {
<ide> *
<ide> * @param string $type
<ide> * @param string $message
<add> * @param string|array $scope
<ide> * @return void
<ide> */
<del> public function write($type, $message);
<add> public function write($type, $message, $scope = []);
<ide> }
<ide><path>Cake/Test/TestApp/Log/Engine/TestAppLog.php
<ide> */
<ide> class TestAppLog extends BaseLog {
<ide>
<del> public function write($type, $message) {
<add> public $passedScope = null;
<add>
<add> public function write($type, $message, $scope = []) {
<add> $this->passedScope = $scope;
<ide> }
<ide>
<ide> }
<ide><path>Cake/Test/TestApp/Plugin/TestPlugin/Log/Engine/TestPluginLog.php
<ide> */
<ide> class TestPluginLog implements LogInterface {
<ide>
<del> public function write($type, $message) {
<add> public function write($type, $message, $scope = []) {
<ide> }
<ide>
<ide> }
<ide><path>Cake/Test/TestCase/Log/LogTest.php
<ide> public function testScopedLoggingExclusive() {
<ide> $this->assertFalse(file_exists(LOGS . 'shops.log'));
<ide> }
<ide>
<add>/**
<add> * testPassingScopeToEngine method
<add> */
<add> public function testPassingScopeToEngine() {
<add> Configure::write('App.namespace', 'TestApp');
<add>
<add> Log::reset();
<add>
<add> Log::config('scope_test', [
<add> 'engine' => 'TestApp',
<add> 'types' => array('notice', 'info', 'debug'),
<add> 'scopes' => array('foo', 'bar'),
<add> ]);
<add>
<add> $engine = Log::engine('scope_test');
<add> $this->assertNull($engine->passedScope);
<add>
<add> Log::write('debug', 'test message', 'foo');
<add> $this->assertEquals('foo', $engine->passedScope);
<add>
<add> Log::write('debug', 'test message', ['foo', 'bar']);
<add> $this->assertEquals(['foo', 'bar'], $engine->passedScope);
<add>
<add> $result = Log::write('debug', 'test message');
<add> $this->assertFalse($result);
<add> }
<add>
<ide> /**
<ide> * test convenience methods
<ide> */ | 8 |
Mixed | Ruby | add `if_exists` option to `remove_index` | 36ea1084fb77496a249fd0b90d647bc5394f2f32 | <ide><path>activerecord/CHANGELOG.md
<add>* Add support for `if_exists` option for removing an index.
<add>
<add> The `remove_index` method can take an `if_exists` option. If this is set to true an error won't be raised if the index doesn't exist.
<add>
<add> *Eileen M. Uchitelle*
<add>
<ide> * Remove ibm_db, informix, mssql, oracle, and oracle12 Arel visitors which are not used in the code base.
<ide>
<ide> *Ryuta Kamizono*
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def add_index(table_name, column_name, options = {})
<ide> #
<ide> # remove_index :accounts, :branch_id, name: :by_branch_party
<ide> #
<add> # Checks if the index exists before trying to remove it. Will silently ignore indexes that
<add> # don't exist.
<add> #
<add> # remove_index :accounts, if_exists: true
<add> #
<ide> # Removes the index named +by_branch_party+ in the +accounts+ table +concurrently+.
<ide> #
<ide> # remove_index :accounts, name: :by_branch_party, algorithm: :concurrently
<ide> def add_index(table_name, column_name, options = {})
<ide> #
<ide> # For more information see the {"Transactional Migrations" section}[rdoc-ref:Migration].
<ide> def remove_index(table_name, column_name = nil, options = {})
<add> return if options[:if_exists] && !index_exists?(table_name, column_name, options)
<add>
<ide> index_name = index_name_for_remove(table_name, column_name, options)
<add>
<ide> execute "DROP INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)}"
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
<ide> def add_index(table_name, column_name, options = {}) #:nodoc:
<ide> end
<ide> end
<ide>
<del> def remove_index(table_name, column_name = nil, options = {}) #:nodoc:
<add> def remove_index(table_name, column_name = nil, options = {}) # :nodoc:
<ide> table = Utils.extract_schema_qualified_name(table_name.to_s)
<ide>
<ide> if column_name.is_a?(Hash)
<ide> def remove_index(table_name, column_name = nil, options = {}) #:nodoc:
<ide> end
<ide> end
<ide>
<add> return if options[:if_exists] && !index_exists?(table_name, column_name, options)
<add>
<ide> index_to_remove = PostgreSQL::Name.new(table.schema, index_name_for_remove(table.to_s, column_name, options))
<add>
<ide> algorithm =
<ide> if options.key?(:algorithm)
<ide> index_algorithms.fetch(options[:algorithm]) do
<ide> raise ArgumentError.new("Algorithm must be one of the following: #{index_algorithms.keys.map(&:inspect).join(', ')}")
<ide> end
<ide> end
<add>
<ide> execute "DROP INDEX #{algorithm} #{quote_table_name(index_to_remove)}"
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
<ide> def primary_keys(table_name) # :nodoc:
<ide> pks.sort_by { |f| f["pk"] }.map { |f| f["name"] }
<ide> end
<ide>
<del> def remove_index(table_name, column_name, options = {}) #:nodoc:
<add> def remove_index(table_name, column_name, options = {}) # :nodoc:
<add> return if options[:if_exists] && !index_exists?(table_name, column_name, options)
<add>
<ide> index_name = index_name_for_remove(table_name, column_name, options)
<add>
<ide> exec_query "DROP INDEX #{quote_column_name(index_name)}"
<ide> end
<ide>
<ide><path>activerecord/test/cases/migration/index_test.rb
<ide> def test_add_index_does_not_accept_too_long_index_names
<ide> connection.add_index(table_name, "foo", name: good_index_name)
<ide> end
<ide>
<del> def test_add_index_which_already_exists_does_not_raise_error
<add> def test_add_index_which_already_exists_does_not_raise_error_with_option
<ide> connection.add_index(table_name, "foo", if_not_exists: true)
<ide>
<ide> assert_nothing_raised do
<ide> connection.add_index(table_name, "foo", if_not_exists: true)
<ide> end
<add>
<add> assert connection.index_name_exists?(table_name, "index_testings_on_foo")
<add> end
<add>
<add> def test_remove_index_which_does_not_exist_doesnt_raise_with_option
<add> connection.add_index(table_name, "foo")
<add>
<add> connection.remove_index(table_name, "foo")
<add>
<add> assert_raises ArgumentError do
<add> connection.remove_index(table_name, "foo")
<add> end
<add>
<add> assert_nothing_raised do
<add> connection.remove_index(table_name, "foo", if_exists: true)
<add> end
<ide> end
<ide>
<ide> def test_internal_index_with_name_matching_database_limit | 5 |
Javascript | Javascript | fix race in parallel/test-vm-debug-context | 8d1c87ea0a0534d42938f1f8804c48cf6599f617 | <ide><path>test/parallel/test-vm-debug-context.js
<ide> var proc = spawn(process.execPath, [script]);
<ide> var data = [];
<ide> proc.stdout.on('data', assert.fail);
<ide> proc.stderr.on('data', data.push.bind(data));
<add>proc.stderr.once('end', common.mustCall(function() {
<add> var haystack = Buffer.concat(data).toString('utf8');
<add> assert(/SyntaxError: Unexpected token \*/.test(haystack));
<add>}));
<ide> proc.once('exit', common.mustCall(function(exitCode, signalCode) {
<ide> assert.equal(exitCode, 1);
<ide> assert.equal(signalCode, null);
<del> var haystack = Buffer.concat(data).toString('utf8');
<del> assert(/SyntaxError: Unexpected token \*/.test(haystack));
<ide> }));
<ide>
<ide> var proc = spawn(process.execPath, [script, 'handle-fatal-exception']); | 1 |
Mixed | Javascript | fix skewx on android and in the js decomposition | 797367c0890a38ec51cfaf7bd90b9cc7db0e97c7 | <ide><path>Libraries/Utilities/MatrixMath.js
<ide> const MatrixMath = {
<ide> skew[0] = MatrixMath.v3Dot(row[0], row[1]);
<ide> row[1] = MatrixMath.v3Combine(row[1], row[0], 1.0, -skew[0]);
<ide>
<del> // Compute XY shear factor and make 2nd row orthogonal to 1st.
<del> skew[0] = MatrixMath.v3Dot(row[0], row[1]);
<del> row[1] = MatrixMath.v3Combine(row[1], row[0], 1.0, -skew[0]);
<del>
<ide> // Now, compute Y scale and normalize 2nd row.
<ide> scale[1] = MatrixMath.v3Length(row[1]);
<ide> row[1] = MatrixMath.v3Normalize(row[1], scale[1]);
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/MatrixMathHelper.java
<ide> public static void decomposeMatrix(double[] transformMatrix, MatrixDecomposition
<ide> skew[0] = v3Dot(row[0], row[1]);
<ide> row[1] = v3Combine(row[1], row[0], 1.0, -skew[0]);
<ide>
<del> // Compute XY shear factor and make 2nd row orthogonal to 1st.
<del> skew[0] = v3Dot(row[0], row[1]);
<del> row[1] = v3Combine(row[1], row[0], 1.0, -skew[0]);
<del>
<ide> // Now, compute Y scale and normalize 2nd row.
<ide> scale[1] = v3Length(row[1]);
<ide> row[1] = v3Normalize(row[1], scale[1]); | 2 |
Python | Python | fix morph rules | 782056d11722a5b3eb352cfdf29a4b5deabd49a8 | <ide><path>spacy/lang/en/morph_rules.py
<ide> "will",
<ide> ]
<ide>
<del>_relative_pronouns = ["this", "that", "those", "these"]
<add># This seems kind of wrong too?
<add>#_relative_pronouns = ["this", "that", "those", "these"]
<ide>
<ide> MORPH_RULES = {
<del> "DT": {word: {"POS": "PRON"} for word in _relative_pronouns},
<add> #"DT": {word: {"POS": "PRON"} for word in _relative_pronouns},
<ide> "IN": {word: {"POS": "SCONJ"} for word in _subordinating_conjunctions},
<ide> "NN": {
<ide> "something": {"POS": "PRON"}, | 1 |
PHP | PHP | add 'proccessing' message to queue worker output | 4ee7aa8c1ff3cbea1441ef0b4c2968eaf4a3c0d5 | <ide><path>src/Illuminate/Queue/Console/WorkCommand.php
<ide> use Illuminate\Queue\WorkerOptions;
<ide> use Illuminate\Queue\Events\JobFailed;
<ide> use Illuminate\Queue\Events\JobProcessed;
<add>use Illuminate\Queue\Events\JobProcessing;
<ide>
<ide> class WorkCommand extends Command
<ide> {
<ide> protected function gatherWorkerOptions()
<ide> */
<ide> protected function listenForEvents()
<ide> {
<add> $this->laravel['events']->listen(JobProcessing::class, function ($event) {
<add> $this->writeOutput($event->job, 'starting');
<add> });
<add>
<ide> $this->laravel['events']->listen(JobProcessed::class, function ($event) {
<del> $this->writeOutput($event->job, false);
<add> $this->writeOutput($event->job, 'success');
<ide> });
<ide>
<ide> $this->laravel['events']->listen(JobFailed::class, function ($event) {
<del> $this->writeOutput($event->job, true);
<add> $this->writeOutput($event->job, 'failed');
<ide>
<ide> $this->logFailedJob($event);
<ide> });
<ide> protected function listenForEvents()
<ide> * Write the status output for the queue worker.
<ide> *
<ide> * @param \Illuminate\Contracts\Queue\Job $job
<del> * @param bool $failed
<add> * @param string $status
<ide> * @return void
<ide> */
<del> protected function writeOutput(Job $job, $failed)
<add> protected function writeOutput(Job $job, $status)
<ide> {
<del> if ($failed) {
<del> $this->output->writeln('<error>['.Carbon::now()->format('Y-m-d H:i:s').'] Failed:</error> '.$job->resolveName());
<del> } else {
<del> $this->output->writeln('<info>['.Carbon::now()->format('Y-m-d H:i:s').'] Processed:</info> '.$job->resolveName());
<add> switch ($status) {
<add> case 'starting':
<add> $this->output->writeln('<comment>['.Carbon::now()->format('Y-m-d H:i:s').'] Processing:</comment> '.$job->resolveName());
<add> break;
<add> case 'success':
<add> $this->output->writeln('<info>['.Carbon::now()->format('Y-m-d H:i:s').'] Processed:</info> '.$job->resolveName());
<add> break;
<add> case 'failed':
<add> $this->output->writeln('<error>['.Carbon::now()->format('Y-m-d H:i:s').'] Failed:</error> '.$job->resolveName());
<add> break;
<ide> }
<ide> }
<ide> | 1 |
Mixed | Ruby | return a 405 response for unknown http methods | ec462b4de7904e0e55a312940e88b9e825bf955c | <ide><path>actionpack/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Return a 405 Method Not Allowed response when a request contains an unknown
<add> HTTP method.
<add>
<add> *Lewis Marshall*
<add>
<ide> * Add support for extracting the port from the `:host` option passed to `url_for`.
<ide>
<ide> *Andrew White*
<ide><path>actionpack/lib/action_dispatch/middleware/exception_wrapper.rb
<ide> class ExceptionWrapper
<ide> 'ActionController::RoutingError' => :not_found,
<ide> 'AbstractController::ActionNotFound' => :not_found,
<ide> 'ActionController::MethodNotAllowed' => :method_not_allowed,
<add> 'ActionController::UnknownHttpMethod' => :method_not_allowed,
<ide> 'ActionController::NotImplemented' => :not_implemented,
<ide> 'ActionController::UnknownFormat' => :not_acceptable,
<ide> 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity,
<ide><path>actionpack/test/dispatch/debug_exceptions_test.rb
<ide> def call(env)
<ide> raise RuntimeError
<ide> when "/method_not_allowed"
<ide> raise ActionController::MethodNotAllowed
<add> when "/unknown_http_method"
<add> raise ActionController::UnknownHttpMethod
<ide> when "/not_implemented"
<ide> raise ActionController::NotImplemented
<ide> when "/unprocessable_entity"
<ide> def setup
<ide> assert_response 405
<ide> assert_match(/ActionController::MethodNotAllowed/, body)
<ide>
<add> get "/unknown_http_method", {}, {'action_dispatch.show_exceptions' => true}
<add> assert_response 405
<add> assert_match(/ActionController::UnknownHttpMethod/, body)
<add>
<ide> get "/bad_request", {}, {'action_dispatch.show_exceptions' => true}
<ide> assert_response 400
<ide> assert_match(/ActionController::BadRequest/, body)
<ide><path>actionpack/test/dispatch/show_exceptions_test.rb
<ide> def call(env)
<ide> raise AbstractController::ActionNotFound
<ide> when "/method_not_allowed"
<ide> raise ActionController::MethodNotAllowed
<add> when "/unknown_http_method"
<add> raise ActionController::UnknownHttpMethod
<ide> when "/not_found_original_exception"
<ide> raise ActionView::Template::Error.new('template', AbstractController::ActionNotFound.new)
<ide> else
<ide> def call(env)
<ide> get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
<ide> assert_response 405
<ide> assert_equal "", body
<add>
<add> get "/unknown_http_method", {}, {'action_dispatch.show_exceptions' => true}
<add> assert_response 405
<add> assert_equal "", body
<ide> end
<ide>
<ide> test "localize rescue error page" do | 4 |
Text | Text | add variable expansion note | c86466f4ee13817c190f6bbe34ee70bb96508261 | <ide><path>docs/basic-features/environment-variables.md
<ide> export async function getStaticProps() {
<ide> }
<ide> ```
<ide>
<add>> **Note**: Next.js will automatically expand variables (`$VAR`) inside of your `.env*` files.
<add>> This allows you to reference other secrets, like so:
<add>>
<add>> ```bash
<add>> # .env
<add>> HOSTNAME=localhost
<add>> PORT=8080
<add>> HOST=http://$HOSTNAME:$PORT
<add>> ```
<add>>
<add>> If you are trying to use a variable with a `$` in the actual value, it needs to be escaped like so: `\$`.
<add>>
<add>> For example:
<add>>
<add>> ```bash
<add>> # .env
<add>> A=abc
<add>> WRONG=pre$A # becomes "preabc"
<add>> CORRECT=pre\$A # becomes "pre$A"
<add>> ```
<add>
<ide> ## Exposing Environment Variables to the Browser
<ide>
<ide> By default all environment variables loaded through `.env.local` are only available in the Node.js environment, meaning they won't be exposed to the browser. | 1 |
PHP | PHP | expose randombytes in the string class | a389ec1c98ed4e5f0961921e2e2ea9298e953363 | <ide><path>src/Illuminate/Support/Str.php
<ide> public static function plural($value, $count = 2)
<ide> * @throws \RuntimeException
<ide> */
<ide> public static function random($length = 16)
<add> {
<add> $bytes = static::randomBytes($length * 2);
<add>
<add> $string = substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $length);
<add>
<add> while (($len = strlen($string)) < $length) {
<add> $string .= static::random($length - $len);
<add> }
<add>
<add> return $string;
<add> }
<add>
<add> /**
<add> * Generate a more truly "random" bytes.
<add> *
<add> * @param int $length
<add> * @return string
<add> *
<add> * @throws \RuntimeException
<add> */
<add> public static function randomBytes($length = 16)
<ide> {
<ide> if (function_exists('random_bytes')) {
<del> $bytes = random_bytes($length * 2);
<add> $bytes = random_bytes($length);
<ide> } elseif (function_exists('openssl_random_pseudo_bytes')) {
<del> $bytes = openssl_random_pseudo_bytes($length * 2, $strong);
<add> $bytes = openssl_random_pseudo_bytes($length, $strong);
<ide> if ($bytes === false || $strong === false) {
<ide> throw new RuntimeException('Unable to generate random string.');
<ide> }
<ide> } else {
<ide> throw new RuntimeException('OpenSSL extension is required for PHP 5 users.');
<ide> }
<ide>
<del> $string = substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $length);
<del>
<del> while (($len = strlen($string)) < $length) {
<del> $string .= static::random($length - $len);
<del> }
<del>
<del> return $string;
<add> return $bytes;
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | trim model class name | 54d33832ec1e9c3c0a894c941334e2a6ba6d2be6 | <ide><path>src/Illuminate/Auth/Middleware/Authorize.php
<ide> protected function getGateArguments($request, $models)
<ide> */
<ide> protected function getModel($request, $model)
<ide> {
<del> return $this->isClassName($model) ? $model : $request->route($model, $model);
<add> return $this->isClassName($model) ? trim($model) : $request->route($model, $model);
<ide> }
<ide>
<ide> /** | 1 |
Go | Go | remove use of table from 'docker diff' | 49c72506ace177e33d867123ca15f193c38bcf45 | <ide><path>api/client/diff.go
<ide> package client
<ide>
<ide> import (
<add> "encoding/json"
<ide> "fmt"
<ide>
<del> "github.com/docker/docker/engine"
<add> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/pkg/archive"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> )
<ide>
<ide> // CmdDiff shows changes on a container's filesystem.
<ide> //
<del>// Each changed file is printed on a separate line, prefixed with a single character that indicates the status of the file: C (modified), A (added), or D (deleted).
<add>// Each changed file is printed on a separate line, prefixed with a single
<add>// character that indicates the status of the file: C (modified), A (added),
<add>// or D (deleted).
<ide> //
<ide> // Usage: docker diff CONTAINER
<ide> func (cli *DockerCli) CmdDiff(args ...string) error {
<ide> cmd := cli.Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem", true)
<ide> cmd.Require(flag.Exact, 1)
<del>
<ide> cmd.ParseFlags(args, true)
<ide>
<del> body, _, err := readBody(cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil, nil))
<del>
<add> rdr, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil, nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> outs := engine.NewTable("", 0)
<del> if _, err := outs.ReadListFrom(body); err != nil {
<add> changes := []types.ContainerChange{}
<add> err = json.NewDecoder(rdr).Decode(&changes)
<add> if err != nil {
<ide> return err
<ide> }
<del> for _, change := range outs.Data {
<add>
<add> for _, change := range changes {
<ide> var kind string
<del> switch change.GetInt("Kind") {
<add> switch change.Kind {
<ide> case archive.ChangeModify:
<ide> kind = "C"
<ide> case archive.ChangeAdd:
<ide> kind = "A"
<ide> case archive.ChangeDelete:
<ide> kind = "D"
<ide> }
<del> fmt.Fprintf(cli.out, "%s %s\n", kind, change.Get("Path"))
<add> fmt.Fprintf(cli.out, "%s %s\n", kind, change.Path)
<ide> }
<add>
<ide> return nil
<ide> }
<ide><path>api/types/types.go
<ide> type ContainerWaitResponse struct {
<ide> type ContainerCommitResponse struct {
<ide> ID string `json:"Id"`
<ide> }
<add>
<add>// GET "/containers/{name:.*}/changes"
<add>type ContainerChange struct {
<add> Kind int
<add> Path string
<add>}
<ide><path>daemon/changes.go
<ide> package daemon
<ide>
<ide> import (
<add> "encoding/json"
<ide> "fmt"
<ide>
<ide> "github.com/docker/docker/engine"
<ide> func (daemon *Daemon) ContainerChanges(job *engine.Job) error {
<ide> return err
<ide> }
<ide>
<del> outs := engine.NewTable("", 0)
<ide> changes, err := container.Changes()
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> for _, change := range changes {
<del> out := &engine.Env{}
<del> if err := out.Import(change); err != nil {
<del> return err
<del> }
<del> outs.Add(out)
<del> }
<del>
<del> if _, err := outs.WriteListTo(job.Stdout); err != nil {
<add> if err = json.NewEncoder(job.Stdout).Encode(changes); err != nil {
<ide> return err
<ide> }
<ide> | 3 |
Javascript | Javascript | leave div commands on stack and change evaluation | 8fccd199484c7bd1935da23c08c7df39293d8ecd | <ide><path>src/fonts.js
<ide> var Type1Parser = function type1Parser() {
<ide>
<ide> var kEscapeCommand = 12;
<ide>
<del> // The initial stack can have numbers expressed with the div command which
<del> // need to be calculated before conversion. Looking at the spec it doesn't
<del> // appear div should even be allowed as a first command but there have been
<del> // a number of fonts that have this.
<del> function evaluateStack(stack) {
<del> var newStack = [];
<del> for (var i = 0, ii = stack.length; i < ii; i++) {
<del> var token = stack[i];
<del> if (token === 'div') {
<del> var b = newStack.pop();
<del> var a = newStack.pop();
<del> newStack.push(a / b);
<del> } else if (isInt(token)) {
<del> newStack.push(token);
<add> // Breaks up the stack by arguments and also calculates the value.
<add> function breakUpArgs(stack, numArgs) {
<add> var args = [];
<add> var index = stack.length - 1;
<add> for (var i = 0; i < numArgs; i++) {
<add> if (index < 0) {
<add> args.unshift({ arg: [0],
<add> value: 0 });
<add> warn('Malformed charstring stack: not enough values on stack.');
<add> continue;
<add> }
<add> if (stack[index] === 'div') {
<add> var a = stack[index - 2];
<add> var b = stack[index - 1];
<add> if (!isInt(a) || !isInt(b)) {
<add> warn('Malformed charsting stack: expected ints on stack for div.');
<add> a = 0;
<add> b = 1;
<add> }
<add> args.unshift({ arg: [a, b, 'div'],
<add> value: a / b });
<add> index -= 3;
<ide> } else {
<del> warn('Unsupported initial stack ' + stack);
<add> args.unshift({ arg: stack.slice(index, index + 1),
<add> value: stack[index] });
<add> index--;
<ide> }
<ide> }
<del> return newStack;
<add> return args;
<ide> }
<ide>
<ide> function decodeCharString(array) {
<ide> var Type1Parser = function type1Parser() {
<ide> command = charStringDictionary['12'][escape];
<ide> } else {
<ide> if (value == 13) { // hsbw
<del> charstring = evaluateStack(charstring);
<del> if (charstring.length !== 2)
<del> warn('Unsupported hsbw format.');
<del> lsb = charstring[0];
<del> width = charstring[1];
<del> charstring.splice(0, 1);
<del> charstring.push(lsb, 'hmoveto');
<add> var args = breakUpArgs(charstring, 2);
<add> lsb = args[0]['value'];
<add> width = args[1]['value'];
<add> // To convert to type2 we have to move the width value to the first
<add> // part of the charstring and then use hmoveto with lsb.
<add> charstring = args[1]['arg'];
<add> charstring = charstring.concat(args[0]['arg']);
<add> charstring.push('hmoveto');
<ide> continue;
<ide> } else if (value == 10) { // callsubr
<ide> if (charstring[charstring.length - 1] < 3) { // subr #0..2 | 1 |
Java | Java | fix javadoc typo | 06d3e1b94ef482c9055805abcff19be613ae31c4 | <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/WebSocketMessageBrokerConfigurer.java
<ide> public interface WebSocketMessageBrokerConfigurer {
<ide>
<ide> /**
<ide> * Configure the {@link org.springframework.messaging.MessageChannel} used for
<del> * incoming messages from WebSocket clients. By default the channel is backed
<add> * outbound messages to WebSocket clients. By default the channel is backed
<ide> * by a thread pool of size 1. It is recommended to customize thread pool
<ide> * settings for production use.
<ide> */ | 1 |
PHP | PHP | fix code style | 07419646263ab7fdf872a1087019c9f4917b5f02 | <ide><path>tests/TestCase/BasicsTest.php
<ide> public function testEventManagerReset2($prevEventManager)
<ide> $this->assertInstanceOf(EventManager::class, $prevEventManager);
<ide> $this->assertNotSame($prevEventManager, EventManager::instance());
<ide> }
<del>
<ide> } | 1 |
Javascript | Javascript | improve fs coverage | 2465062c45bb73025ecf06f475339bcf6e783de2 | <ide><path>test/parallel/test-fs-read.js
<ide> assert.throws(
<ide> }
<ide> );
<ide>
<del>['buffer', 'offset', 'length'].forEach((option) =>
<del> assert.throws(
<del> () => fs.read(fd, {
<del> [option]: null
<del> }),
<del> `not throws when options.${option} is null`
<del> ));
<add>assert.throws(
<add> () => fs.read(fd, { buffer: null }, common.mustNotCall()),
<add> /TypeError: Cannot read property 'byteLength' of null/,
<add> 'throws when options.buffer is null'
<add>);
<add>
<add>assert.throws(
<add> () => fs.readSync(fd, { buffer: null }),
<add> {
<add> name: 'TypeError',
<add> message: 'The "buffer" argument must be an instance of Buffer, ' +
<add> 'TypedArray, or DataView. Received an instance of Object',
<add> },
<add> 'throws when options.buffer is null'
<add>);
<ide>
<ide> assert.throws(
<ide> () => fs.read(null, Buffer.alloc(1), 0, 1, 0),
<ide><path>test/parallel/test-fs-readfile.js
<ide> for (const e of fileInfo) {
<ide> assert.deepStrictEqual(buf, e.contents);
<ide> }));
<ide> }
<add>// Test readFile size too large
<add>{
<add> const kIoMaxLength = 2 ** 31 - 1;
<add>
<add> const file = path.join(tmpdir.path, `${prefix}-too-large.txt`);
<add> fs.writeFileSync(file, Buffer.from('0'));
<add> fs.truncateSync(file, kIoMaxLength + 1);
<add>
<add> fs.readFile(file, common.expectsError({
<add> code: 'ERR_FS_FILE_TOO_LARGE',
<add> name: 'RangeError',
<add> }));
<add> assert.throws(() => {
<add> fs.readFileSync(file);
<add> }, { code: 'ERR_FS_FILE_TOO_LARGE', name: 'RangeError' });
<add>}
<add>
<ide> {
<ide> // Test cancellation, before
<ide> const signal = AbortSignal.abort(); | 2 |
Ruby | Ruby | raise helpful error when role doesn't exist | 22a1265828d9f743b8348fe53424fffb60d6d824 | <ide><path>activerecord/lib/active_record/connection_handling.rb
<ide> def lookup_connection_handler(handler_key) # :nodoc:
<ide> end
<ide>
<ide> def with_handler(handler_key, &blk) # :nodoc:
<add> unless ActiveRecord::Base.connection_handlers.keys.include?(handler_key)
<add> raise ArgumentError, "The #{handler_key} role does not exist. Add it by establishing a connection with `connects_to` or use an existing role (#{ActiveRecord::Base.connection_handlers.keys.join(", ")})."
<add> end
<add>
<ide> handler = lookup_connection_handler(handler_key)
<ide> swap_connection_handler(handler, &blk)
<ide> end
<ide><path>activerecord/test/cases/connection_adapters/connection_handlers_multi_db_test.rb
<ide> def test_connection_handlers_swapping_connections_in_fiber
<ide> ensure
<ide> ActiveRecord::Base.connection_handlers = original_handlers
<ide> end
<add>
<add> def test_calling_connected_to_on_a_non_existent_handler_raises
<add> error = assert_raises ArgumentError do
<add> ActiveRecord::Base.connected_to(role: :reading) do
<add> yield
<add> end
<add> end
<add>
<add> assert_equal "The reading role does not exist. Add it by establishing a connection with `connects_to` or use an existing role (writing).", error.message
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/query_cache_test.rb
<ide> def test_exceptional_middleware_clears_and_disables_cache_on_error
<ide> end
<ide>
<ide> def test_query_cache_is_applied_to_connections_in_all_handlers
<add> ActiveRecord::Base.connection_handlers = {
<add> writing: ActiveRecord::Base.default_connection_handler,
<add> reading: ActiveRecord::ConnectionAdapters::ConnectionHandler.new
<add> }
<add>
<ide> ActiveRecord::Base.connected_to(role: :reading) do
<ide> ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations["arunit"])
<ide> end | 3 |
PHP | PHP | fix variable name to prevent type warning in ide | 03580bd554fe2379b53def0f95166b02de3f7dcf | <ide><path>src/Validation/Validator.php
<ide> public function count()
<ide> */
<ide> public function add($field, $name, $rule = [])
<ide> {
<del> $field = $this->field($field);
<add> $validationSet = $this->field($field);
<ide>
<ide> if (!is_array($name)) {
<ide> $rules = [$name => $rule];
<ide> public function add($field, $name, $rule = [])
<ide> if (is_array($rule)) {
<ide> $rule += ['rule' => $name];
<ide> }
<del> $field->add($name, $rule);
<add> $validationSet->add($name, $rule);
<ide> }
<ide>
<ide> return $this;
<ide> public function addNested($field, Validator $validator, $message = null, $when =
<ide> {
<ide> $extra = array_filter(['message' => $message, 'on' => $when]);
<ide>
<del> $field = $this->field($field);
<del> $field->add(static::NESTED, $extra + ['rule' => function ($value, $context) use ($validator, $message) {
<add> $validationSet = $this->field($field);
<add> $validationSet->add(static::NESTED, $extra + ['rule' => function ($value, $context) use ($validator, $message) {
<ide> if (!is_array($value)) {
<ide> return false;
<ide> }
<ide> public function addNestedMany($field, Validator $validator, $message = null, $wh
<ide> {
<ide> $extra = array_filter(['message' => $message, 'on' => $when]);
<ide>
<del> $field = $this->field($field);
<del> $field->add(static::NESTED, $extra + ['rule' => function ($value, $context) use ($validator, $message) {
<add> $validationSet = $this->field($field);
<add> $validationSet->add(static::NESTED, $extra + ['rule' => function ($value, $context) use ($validator, $message) {
<ide> if (!is_array($value)) {
<ide> return false;
<ide> } | 1 |
Ruby | Ruby | require string extensions | d99cfd139424b12f662eecba28acb05994865aa0 | <ide><path>Library/Homebrew/tap.rb
<add>require "extend/string"
<add>
<ide> # a {Tap} is used to extend the formulae provided by Homebrew core.
<ide> # Usually, it's synced with a remote git repository. And it's likely
<ide> # a Github repository with the name of `user/homebrew-repo`. In such | 1 |
Javascript | Javascript | remove some dead code | 20bcabb1ea4cf492ade240bd6915b4bd44f04895 | <ide><path>src/renderers/shared/stack/reconciler/ReactHostComponent.js
<ide>
<ide> var invariant = require('invariant');
<ide>
<del>var autoGenerateWrapperClass = null;
<ide> var genericComponentClass = null;
<ide> // This registry keeps track of wrapper classes around host tags.
<ide> var tagToComponentClass = {};
<ide> var ReactHostComponentInjection = {
<ide> },
<ide> };
<ide>
<del>/**
<del> * Get a composite component wrapper class for a specific tag.
<del> *
<del> * @param {ReactElement} element The tag for which to get the class.
<del> * @return {function} The React class constructor function.
<del> */
<del>function getComponentClassForElement(element) {
<del> if (typeof element.type === 'function') {
<del> return element.type;
<del> }
<del> var tag = element.type;
<del> var componentClass = tagToComponentClass[tag];
<del> if (componentClass == null) {
<del> tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag);
<del> }
<del> return componentClass;
<del>}
<del>
<ide> /**
<ide> * Get a host internal component class for a specific tag.
<ide> *
<ide> function isTextComponent(component) {
<ide> }
<ide>
<ide> var ReactHostComponent = {
<del> getComponentClassForElement: getComponentClassForElement,
<ide> createInternalComponent: createInternalComponent,
<ide> createInstanceForText: createInstanceForText,
<ide> isTextComponent: isTextComponent, | 1 |
PHP | PHP | return response from named limiter | efcb7e9ef40cbcc087331fec997853926219d72e | <ide><path>src/Illuminate/Routing/Middleware/ThrottleRequests.php
<ide> protected function handleRequestUsingNamedLimiter($request, Closure $next, $limi
<ide> $limiterResponse = call_user_func($limiter, $request);
<ide>
<ide> if ($limiterResponse instanceof Response) {
<del> return $limit;
<add> return $limiterResponse;
<ide> } elseif ($limiterResponse instanceof Unlimited) {
<ide> return $next($request);
<ide> } | 1 |
Text | Text | clarify installation instructions | 7b859625b727aa7f8e7fffd4481693d81b82a532 | <ide><path>README.md
<ide> To install the stable version:
<ide> npm install --save redux
<ide> ```
<ide>
<add>This assumes you are using [npm](https://www.npmjs.com/) as your package manager.
<add>If you donβt, you can [access these files on npmcdn](https://npmcdn.com/redux/), download them, or point your package manager to them.
<add>
<add>Most commonly people consume Redux as a collection of [CommonJS](http://webpack.github.io/docs/commonjs.html) modules. These modules are what you get when you import `redux` in a [Webpack](http://webpack.github.io), [Browserify](http://browserify.org/), or a Node environment. If you like to live on the edge and use [Rollup](http://rollupjs.org), we support that as well.
<add>
<add>If you donβt use a module bundler, itβs also fine. The `redux` npm package includes precompiled production and development [UMD](https://github.com/umdjs/umd) builds in the [`dist` folder](https://npmcdn.com/redux/dist/). They can be used directly without a bundler and are thus compatible with many popular JavaScript module loaders and environments. For example, you can drop a UMD build as a [`<script>` tag](https://npmcdn.com/redux/dist/redux.js) on the page, or [tell Bower to install it](https://github.com/reactjs/redux/pull/1181#issuecomment-167361975). The UMD builds make Redux available as a `window.Redux` global variable.
<add>
<add>The Redux source code is written in ES2015 but we precompile both CommonJS and UMD builds to ES5 so they work in [any modern browser](http://caniuse.com/#feat=es5). You donβt need to use Babel or a module bundler to [get started with Redux](https://github.com/reactjs/redux/blob/master/examples/counter-vanilla/index.html).
<add>
<add>#### Complementary Packages
<add>
<ide> Most likely, youβll also need [the React bindings](https://github.com/reactjs/react-redux) and [the developer tools](https://github.com/gaearon/redux-devtools).
<ide>
<ide> ```
<ide> npm install --save react-redux
<ide> npm install --save-dev redux-devtools
<ide> ```
<ide>
<del>This assumes that youβre using [npm](https://www.npmjs.com/) package manager with a module bundler like [Webpack](http://webpack.github.io) or [Browserify](http://browserify.org/) to consume [CommonJS modules](http://webpack.github.io/docs/commonjs.html).
<del>
<del>If you donβt yet use [npm](https://www.npmjs.com/) or a modern module bundler, and would rather prefer a single-file [UMD](https://github.com/umdjs/umd) build that makes `Redux` available as a global object, you can grab a pre-built version from [cdnjs](https://cdnjs.com/libraries/redux). We *donβt* recommend this approach for any serious application, as most of the libraries complementary to Redux are only available on [npm](https://www.npmjs.com/).
<add>Note that unlike Redux itself, many packages in the Redux ecosystem donβt provide UMD builds, so we recommend using CommonJS module bundlers like [Webpack](http://webpack.github.io) and [Browserify](http://browserify.org/) for the most comfortable development experience.
<ide>
<ide> ### The Gist
<ide> | 1 |
Ruby | Ruby | pass args properly | c494789d700fbb76035c2cd5d8c92cbe3ef2c0b0 | <ide><path>Library/Homebrew/cmd/list.rb
<ide> def list_args
<ide> def list
<ide> args = list_args.parse
<ide>
<del> return list_casks if args.cask?
<add> return list_casks(args: args) if args.cask?
<ide>
<ide> return list_unbrewed if args.unbrewed?
<ide>
<ide> def list
<ide> end
<ide>
<ide> if args.pinned? || args.versions?
<del> filtered_list
<add> filtered_list args: args
<ide> elsif args.no_named?
<ide> if args.full_name?
<ide> full_names = Formula.installed.map(&:full_name).sort(&tap_and_name_comparison)
<ide> def list_unbrewed
<ide> safe_system "find", *arguments
<ide> end
<ide>
<del> def filtered_list
<add> def filtered_list(args:)
<ide> names = if args.no_named?
<ide> Formula.racks
<ide> else
<ide> def filtered_list
<ide> end
<ide> end
<ide>
<del> def list_casks
<add> def list_casks(args:)
<ide> cask_list = Cask::Cmd::List.new args.named
<ide> cask_list.one = ARGV.include? "-1"
<ide> cask_list.versions = args.versions? | 1 |
PHP | PHP | fix cs error | 176d21a71592ad0778bd913fcb25df2029c472d2 | <ide><path>src/Validation/Validation.php
<ide> public static function comparison($check1, $operator = null, $check2 = null)
<ide> * @param array $context The validation context.
<ide> * @return bool
<ide> */
<del> public static function compareWith($check, $field, $context) {
<add> public static function compareWith($check, $field, $context)
<add> {
<ide> if (!isset($context['data'][$field])) {
<ide> return false;
<ide> } | 1 |
Text | Text | fix typo in image-classification/readme.md | 7d5ce6802ec5bab29d60e3501337d3477f31b866 | <ide><path>examples/pytorch/image-classification/README.md
<ide> This directory contains 2 scripts that showcase how to fine-tune any model suppo
<ide> Try out the inference widget here: https://huggingface.co/google/vit-base-patch16-224
<ide>
<ide> Content:
<del>- [PyTorch version, Trainer](#pytorch-version-no-trainer)
<del>- [PyTorch version, no Trainer](#pytorch-version-trainer)
<add>- [PyTorch version, Trainer](#pytorch-version-trainer)
<add>- [PyTorch version, no Trainer](#pytorch-version-no-trainer)
<ide>
<ide> ## PyTorch version, Trainer
<ide>
<ide> This command is the same and will work for:
<ide>
<ide> Note that this library is in alpha release so your feedback is more than welcome if you encounter any problem using it.
<ide>
<del>Regarding using custom data with this script, we refer to [using your own data](#using-your-own-data).
<ide>\ No newline at end of file
<add>Regarding using custom data with this script, we refer to [using your own data](#using-your-own-data). | 1 |
Python | Python | implement cors for the restful api | 6a1d74276341caccd7dc653f6f7787b70597d4f9 | <ide><path>glances/outputs/glances_bottle.py
<ide>
<ide> # Import mandatory Bottle lib
<ide> try:
<del> from bottle import Bottle, template, static_file, TEMPLATE_PATH, abort, response
<add> from bottle import Bottle, template, static_file, TEMPLATE_PATH, abort, response, request
<ide> except ImportError:
<ide> logger.critical('Bottle module not found. Glances cannot start in web server mode.')
<ide> sys.exit(2)
<ide> def __init__(self, args=None):
<ide>
<ide> # Init Bottle
<ide> self._app = Bottle()
<add> # Enable CORS (issue #479)
<add> self._app.install(EnableCors())
<add> # Define routes
<ide> self._route()
<ide>
<ide> # Update the template path (glances/outputs/bottle)
<ide> def _favicon(self):
<ide> # Return the static file
<ide> return static_file('favicon.ico', root=self.STATIC_PATH)
<ide>
<add> def enable_cors(self):
<add> """Enable CORS"""
<add> response.headers['Access-Control-Allow-Origin'] = '*'
<add> response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
<add> response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
<add>
<ide> def _api_plugins(self):
<ide> """
<ide> Glances API RESTFul implementation
<ide> def display(self, stats, refresh_time=None):
<ide> }
<ide>
<ide> return template('base', refresh_time=refresh_time, stats=stats)
<add>
<add>
<add>class EnableCors(object):
<add> name = 'enable_cors'
<add> api = 2
<add>
<add> def apply(self, fn, context):
<add> def _enable_cors(*args, **kwargs):
<add> # set CORS headers
<add> response.headers['Access-Control-Allow-Origin'] = '*'
<add> response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
<add> response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
<add>
<add> if request.method != 'OPTIONS':
<add> # actual request; reply with the actual response
<add> return fn(*args, **kwargs)
<add>
<add> return _enable_cors | 1 |
PHP | PHP | add setcollection method to the paginator | 2fdb5d13d05f771877dcdd9a44cb8e6d403cd8ac | <ide><path>src/Illuminate/Pagination/AbstractPaginator.php
<ide> public function getCollection()
<ide> return $this->items;
<ide> }
<ide>
<add> /**
<add> * Set the paginator's underlying collection.
<add> *
<add> * @param \Illuminate\Support\Collection $collection
<add> * @return $this
<add> */
<add> public function setCollection(\Illuminate\Support\Collection $collection)
<add> {
<add> $this->items = $collection;
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Determine if the given item exists.
<ide> * | 1 |
PHP | PHP | remove redundant setloggers() call | 621ac4fd477286387ee934deb65fdf31885631c0 | <ide><path>src/Console/Shell.php
<ide> public function __construct(ConsoleIo $io = null)
<ide> ['tasks'],
<ide> ['associative' => ['tasks']]
<ide> );
<del> $this->_io->setLoggers(true);
<ide>
<ide> if (isset($this->modelClass)) {
<ide> $this->loadModel();
<ide><path>tests/TestCase/Console/ShellTest.php
<ide> public function testQuietLog()
<ide> $io->expects($this->at(0))
<ide> ->method('setLoggers')
<ide> ->with(true);
<del> $io->expects($this->at(3))
<add> $io->expects($this->at(2))
<ide> ->method('setLoggers')
<ide> ->with(ConsoleIo::QUIET);
<ide> | 2 |
Ruby | Ruby | fix bad install names in executables | 186a76c741a92c25d58b85d597bbb9fb5774c668 | <ide><path>Library/Homebrew/keg_fix_install_names.rb
<ide> def fix_install_names
<ide> system MacOS.locate("install_name_tool"), "-id", id, file if file.dylib?
<ide>
<ide> bad_names.each do |bad_name|
<del> new_name = bad_name
<del> new_name = Pathname.new(bad_name).basename unless (file.parent + new_name).exist?
<del>
<del> # First check to see if the dylib is present in the current
<del> # directory, so we can skip the more expensive search.
<del> if (file.parent + new_name).exist?
<del> system MacOS.locate("install_name_tool"), "-change", bad_name, "@loader_path/#{new_name}", file
<add> # If file is a dylib or bundle itself, look for the dylib named by
<add> # bad_name relative to the lib directory, so that we can skip the more
<add> # expensive recursive search if possible.
<add> if file.dylib? or file.mach_o_bundle? and (file.parent + bad_name).exist?
<add> system MacOS.locate("install_name_tool"), "-change", bad_name, "@loader_path/#{bad_name}", file
<add> elsif file.mach_o_executable? and (lib/bad_name).exist?
<add> system MacOS.locate("install_name_tool"), "-change", bad_name, "#{lib}/#{bad_name}", file
<ide> else
<del> # Otherwise, try and locate the appropriate dylib by walking
<del> # the entire 'lib' tree recursively.
<del> abs_name = (self+'lib').find do |pn|
<del> break pn if pn.basename == Pathname.new(new_name)
<del> end
<add> # Otherwise, try and locate the dylib by walking the entire
<add> # lib tree recursively.
<add> abs_name = find_dylib(Pathname.new(bad_name).basename)
<ide>
<ide> if abs_name and abs_name.exist?
<ide> system MacOS.locate("install_name_tool"), "-change", bad_name, abs_name, file
<ide> def fix_install_names
<ide>
<ide> OTOOL_RX = /\t(.*) \(compatibility version (\d+\.)*\d+, current version (\d+\.)*\d+\)/
<ide>
<add> def lib; join 'lib' end
<add>
<ide> def bad_install_names_for file
<ide> ENV['HOMEBREW_MACH_O_FILE'] = file.to_s # solves all shell escaping problems
<ide> install_names = `#{MacOS.locate("otool")} -L "$HOMEBREW_MACH_O_FILE"`.split "\n"
<ide>
<ide> install_names.shift # first line is fluff
<ide> install_names.map!{ |s| OTOOL_RX =~ s && $1 }
<ide>
<del> # Bundles don't have an ID
<del> id = install_names.shift unless file.mach_o_bundle?
<add> # Bundles and executables do not have an ID
<add> id = install_names.shift if file.dylib?
<ide>
<ide> install_names.compact!
<ide> install_names.reject!{ |fn| fn =~ /^@(loader|executable)_path/ }
<ide> def bad_install_names_for file
<ide> yield id, install_names
<ide> end
<ide>
<add> def find_dylib name
<add> (join 'lib').find do |pn|
<add> break pn if pn.basename == Pathname.new(name)
<add> end
<add> end
<add>
<ide> def mach_o_files
<ide> mach_o_files = []
<ide> if (lib = join 'lib').directory?
<ide> def mach_o_files
<ide> mach_o_files << pn if pn.dylib? or pn.mach_o_bundle?
<ide> end
<ide> end
<add>
<add> if (bin = join 'bin').directory?
<add> bin.find do |pn|
<add> next if pn.symlink? or pn.directory?
<add> mach_o_files << pn if pn.mach_o_executable?
<add> end
<add> end
<ide> mach_o_files
<ide> end
<ide> end | 1 |
Text | Text | update information on test/known_issues | 1807080d3d94f930cdf6f145fc33b916bec8c4be | <ide><path>test/README.md
<ide> On how to run tests in this direcotry, see
<ide> </tr>
<ide> <tr>
<ide> <td>known_issues</td>
<del> <td>No</td>
<del> <td>Tests reproducing known issues within the system.</td>
<add> <td>Yes</td>
<add> <td>
<add> Tests reproducing known issues within the system. All tests inside of
<add> this directory are expected to fail consistently. If a test doesn't fail
<add> on certain platforms, those should be skipped via `known_issues.status`.
<add> </td>
<ide> </tr>
<ide> <tr>
<ide> <td>message</td> | 1 |
Javascript | Javascript | use async/await in before-quit handler | 9d30003e58ca837a1593b4cac03da0df706e6ea4 | <ide><path>src/main-process/atom-application.js
<ide> class AtomApplication extends EventEmitter {
<ide> this.openPathOnEvent('application:open-your-stylesheet', 'atom://.atom/stylesheet')
<ide> this.openPathOnEvent('application:open-license', path.join(process.resourcesPath, 'LICENSE.md'))
<ide>
<del> this.disposable.add(ipcHelpers.on(app, 'before-quit', event => {
<add> this.disposable.add(ipcHelpers.on(app, 'before-quit', async event => {
<ide> let resolveBeforeQuitPromise
<del> this.lastBeforeQuitPromise = new Promise(resolve => {
<del> resolveBeforeQuitPromise = resolve
<del> })
<del>
<del> if (this.quitting) return resolveBeforeQuitPromise()
<add> this.lastBeforeQuitPromise = new Promise(resolve => { resolveBeforeQuitPromise = resolve })
<add>
<add> if (!this.quitting) {
<add> this.quitting = true
<add> event.preventDefault()
<add> const windowUnloadPromises = this.getAllWindows().map(window => window.prepareToUnload())
<add> const windowUnloadedResults = await Promise.all(windowUnloadPromises)
<add> if (windowUnloadedResults.every(Boolean)) app.quit()
<add> }
<ide>
<del> this.quitting = true
<del> event.preventDefault()
<del> const windowUnloadPromises = this.getAllWindows().map(window => window.prepareToUnload())
<del> return Promise.all(windowUnloadPromises).then(windowUnloadedResults => {
<del> const didUnloadAllWindows = windowUnloadedResults.every(Boolean)
<del> if (didUnloadAllWindows) app.quit()
<del> resolveBeforeQuitPromise()
<del> })
<add> resolveBeforeQuitPromise()
<ide> }))
<ide>
<ide> this.disposable.add(ipcHelpers.on(app, 'will-quit', () => { | 1 |
Text | Text | update v5.5 changelog (fix) | 6b692b327d667610ed22265c8de8291551e2d749 | <ide><path>CHANGELOG-5.5.md
<ide> - β οΈ Call `setConnection()` in `Model::save()` ([#20466](https://github.com/laravel/framework/pull/20466))
<ide> - β οΈ Touch parent timestamp only if the model is dirty ([#20489](https://github.com/laravel/framework/pull/20489))
<ide> - Added `Model::loadMissing()` method ([#20630](https://github.com/laravel/framework/pull/20630), [4166c12](https://github.com/laravel/framework/commit/4166c12492ce7b1112911299caf4cdb17efc9364))
<del>- Return the model instance from `Model::refresh()` ([#20657](https://github.com/laravel/framework/pull/20657))
<ide>
<ide> ### Encryption
<ide> - Use `openssl_cipher_iv_length()` in `Encrypter` ([#18684](https://github.com/laravel/framework/pull/18684)) | 1 |
Javascript | Javascript | remove unused function argument from http test | f52fb0ac8fc0369aff7635bcb37aadc57d98a645 | <ide><path>test/sequential/test-http-server-consumed-timeout.js
<ide> server.listen(0, common.mustCall(() => {
<ide> const req = http.request({
<ide> port: server.address().port,
<ide> method: 'POST'
<del> }, (res) => {
<add> }, () => {
<ide> const interval = setInterval(() => {
<ide> intervalWasInvoked = true;
<ide> // If machine is busy enough that the interval takes more than TIMEOUT ms | 1 |
Ruby | Ruby | remove outdated comment [ci skip] | d33bdef821e6fafac0eed39fd0329761d6f180ae | <ide><path>actionmailer/lib/action_mailer/base.rb
<ide> def respond_to_missing?(method, include_all = false)
<ide>
<ide> attr_internal :message
<ide>
<del> # Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
<del> # will be initialized according to the named method. If not, the mailer will
<del> # remain uninitialized (useful when you only need to invoke the "receive"
<del> # method, for instance).
<ide> def initialize
<ide> super()
<ide> @_mail_was_called = false | 1 |
Mixed | Go | build tag to enable showing version info | 25154682a5cd57aa4fc3ef88baeee3ce1f204060 | <ide><path>daemon/graphdriver/btrfs/btrfs.go
<ide> func (d *Driver) String() string {
<ide> }
<ide>
<ide> func (d *Driver) Status() [][2]string {
<del> return [][2]string{
<del> {"Build Version", BtrfsBuildVersion()},
<del> {"Library Version", fmt.Sprintf("%d", BtrfsLibVersion())},
<add> status := [][2]string{}
<add> if bv := BtrfsBuildVersion(); bv != "-" {
<add> status = append(status, [2]string{"Build Version", bv})
<ide> }
<add> if lv := BtrfsLibVersion(); lv != -1 {
<add> status = append(status, [2]string{"Library Version", fmt.Sprintf("%d", lv)})
<add> }
<add> return status
<ide> }
<ide>
<ide> func (d *Driver) Cleanup() error {
<ide><path>daemon/graphdriver/btrfs/version.go
<del>// +build linux
<add>// +build linux,!btrfs_noversion
<ide>
<ide> package btrfs
<ide>
<ide> /*
<ide> #include <btrfs/version.h>
<add>
<add>// because around version 3.16, they did not define lib version yet
<add>int my_btrfs_lib_version() {
<add>#ifdef BTRFS_LIB_VERSION
<add> return BTRFS_LIB_VERSION;
<add>#else
<add> return -1;
<add>#endif
<add>}
<ide> */
<ide> import "C"
<ide>
<ide><path>daemon/graphdriver/btrfs/version_none.go
<add>// +build linux,btrfs_noversion
<add>
<add>package btrfs
<add>
<add>// TODO(vbatts) remove this work-around once supported linux distros are on
<add>// btrfs utililties of >= 3.16.1
<add>
<add>func BtrfsBuildVersion() string {
<add> return "-"
<add>}
<add>func BtrfsLibVersion() int {
<add> return -1
<add>}
<ide><path>hack/PACKAGERS.md
<ide> SELinux, you will need to use the `selinux` build tag:
<ide> export DOCKER_BUILDTAGS='selinux'
<ide> ```
<ide>
<add>If your version of btrfs-progs is < 3.16.1 (also called btrfs-tools), then you
<add>will need the following tag to not check for btrfs version headers:
<add>```bash
<add>export DOCKER_BUILDTAGS='btrfs_noversion'
<add>```
<add>
<ide> There are build tags for disabling graphdrivers as well. By default, support
<ide> for all graphdrivers are built in.
<ide> | 4 |
PHP | PHP | update doc block | e94859827747678b8d96575adb64d98ad4e3f288 | <ide><path>lib/Cake/Core/CakePlugin.php
<ide> public static function load($plugin, $config = array()) {
<ide> * {{{
<ide> * CakePlugin::loadAll(array(
<ide> * array('bootstrap' => true),
<del> * 'DebugKit' => array('routes' => true),
<add> * 'DebugKit' => array('routes' => true, 'bootstrap' => false),
<ide> * ))
<ide> * }}}
<ide> *
<del> * The above example will load the bootstrap file for all plugins, but for DebugKit it will only load the routes file
<del> * and will not look for any bootstrap script.
<add> * The above example will load the bootstrap file for all plugins, but for DebugKit it will only load
<add> * the routes file and will not look for any bootstrap script.
<ide> *
<ide> * @param array $options
<ide> * @return void | 1 |
Javascript | Javascript | make prereleases less verbose [ci skip] | ca0b20ae8b25aa3d4b7b6b21e72b610cb8e2adce | <ide><path>website/src/widgets/changelog.js
<ide> function formatReleases(json) {
<ide> }))
<ide> }
<ide>
<del>const ChangelogTable = ({ data = [] }) => {
<del> return (
<del> <Table>
<del> <thead>
<del> <Tr>
<del> <Th>Date</Th>
<del> <Th>Version</Th>
<del> <Th>Title</Th>
<del> </Tr>
<del> </thead>
<del> <tbody>
<del> {data.map(({ title, url, date, tag }) => (
<del> <Tr key={tag}>
<del> <Td nowrap>
<del> <Label>{date}</Label>
<del> </Td>
<del> <Td>
<del> <Link to={url} hideIcon>
<del> <InlineCode>{tag}</InlineCode>
<del> </Link>
<del> </Td>
<del> <Td>{title}</Td>
<del> </Tr>
<del> ))}
<del> </tbody>
<del> </Table>
<del> )
<del>}
<del>
<ide> const Changelog = () => {
<ide> const [initialized, setInitialized] = useState(false)
<ide> const [isLoading, setIsLoading] = useState(false)
<ide> const Changelog = () => {
<ide> ) : isLoading ? null : (
<ide> <>
<ide> <H3 id="changelog-stable">Stable Releases</H3>
<del> <ChangelogTable data={releases} />
<add> <Table>
<add> <thead>
<add> <Tr>
<add> <Th>Date</Th>
<add> <Th>Version</Th>
<add> <Th>Title</Th>
<add> </Tr>
<add> </thead>
<add> <tbody>
<add> {releases.map(({ title, url, date, tag }) => (
<add> <Tr key={tag}>
<add> <Td nowrap>
<add> <Label>{date}</Label>
<add> </Td>
<add> <Td>
<add> <Link to={url} hideIcon>
<add> <InlineCode>{tag}</InlineCode>
<add> </Link>
<add> </Td>
<add> <Td>{title}</Td>
<add> </Tr>
<add> ))}
<add> </tbody>
<add> </Table>
<ide>
<ide> <H3 id="changelog-pre">Pre-Releases</H3>
<ide>
<ide> const Changelog = () => {
<ide> <InlineCode>spacy-nightly</InlineCode> package on pip.
<ide> </p>
<ide>
<del> <ChangelogTable data={prereleases} />
<add> <p>
<add> {prereleases.map(({ title, date, url, tag }) => (
<add> <>
<add> <Link to={url} hideIcon data-tooltip={`${date}: ${title}`}>
<add> <InlineCode>{tag}</InlineCode>
<add> </Link>{' '}
<add> </>
<add> ))}
<add> </p>
<ide> </>
<ide> )
<ide> } | 1 |
Ruby | Ruby | add missing public method doc to timewithzone.name | 9b854ccd77498e5c0f30912596737f0b8efa4654 | <ide><path>activesupport/lib/active_support/time_with_zone.rb
<ide> module ActiveSupport
<ide> # t.is_a?(ActiveSupport::TimeWithZone) # => true
<ide> #
<ide> class TimeWithZone
<add>
<add> # Report class name as 'Time' to thwart type checking
<ide> def self.name
<del> 'Time' # Report class name as 'Time' to thwart type checking
<add> 'Time'
<ide> end
<ide>
<ide> include Comparable | 1 |
Javascript | Javascript | use task.pagelimit properly | ecf831b44bb712dca16dfb1616140cc1faf99202 | <ide><path>test/driver.js
<ide> function nextTask() {
<ide> }
<ide>
<ide> function isLastPage(task) {
<del> return task.pageNum > (task.pageLimit || task.pdfDoc.numPages);
<add> var limit = task.pageLimit || 0;
<add> if (!limit || limit > task.pdfDoc.numPages)
<add> limit = task.pdfDoc.numPages;
<add>
<add> return task.pageNum > limit;
<ide> }
<ide>
<ide> function canvasToDataURL() { | 1 |
Go | Go | pass root to chroot to for chroot untar | d089b639372a8f9301747ea56eaf0a42df24016a | <ide><path>daemon/archive.go
<ide> type archiver interface {
<ide> }
<ide>
<ide> // helper functions to extract or archive
<del>func extractArchive(i interface{}, src io.Reader, dst string, opts *archive.TarOptions) error {
<add>func extractArchive(i interface{}, src io.Reader, dst string, opts *archive.TarOptions, root string) error {
<ide> if ea, ok := i.(extractor); ok {
<ide> return ea.ExtractArchive(src, dst, opts)
<ide> }
<del> return chrootarchive.Untar(src, dst, opts)
<add>
<add> return chrootarchive.UntarWithRoot(src, dst, opts, root)
<ide> }
<ide>
<ide> func archivePath(i interface{}, src string, opts *archive.TarOptions) (io.ReadCloser, error) {
<ide> func (daemon *Daemon) containerExtractToDir(container *container.Container, path
<ide> }
<ide> }
<ide>
<del> if err := extractArchive(driver, content, resolvedPath, options); err != nil {
<add> if err := extractArchive(driver, content, resolvedPath, options, container.BaseFS.Path()); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>pkg/chrootarchive/archive.go
<ide> func NewArchiver(idMapping *idtools.IdentityMapping) *archive.Archiver {
<ide> // The archive may be compressed with one of the following algorithms:
<ide> // identity (uncompressed), gzip, bzip2, xz.
<ide> func Untar(tarArchive io.Reader, dest string, options *archive.TarOptions) error {
<del> return untarHandler(tarArchive, dest, options, true)
<add> return untarHandler(tarArchive, dest, options, true, dest)
<add>}
<add>
<add>// UntarWithRoot is the same as `Untar`, but allows you to pass in a root directory
<add>// The root directory is the directory that will be chrooted to.
<add>// `dest` must be a path within `root`, if it is not an error will be returned.
<add>//
<add>// `root` should set to a directory which is not controlled by any potentially
<add>// malicious process.
<add>//
<add>// This should be used to prevent a potential attacker from manipulating `dest`
<add>// such that it would provide access to files outside of `dest` through things
<add>// like symlinks. Normally `ResolveSymlinksInScope` would handle this, however
<add>// sanitizing symlinks in this manner is inherrently racey:
<add>// ref: CVE-2018-15664
<add>func UntarWithRoot(tarArchive io.Reader, dest string, options *archive.TarOptions, root string) error {
<add> return untarHandler(tarArchive, dest, options, true, root)
<ide> }
<ide>
<ide> // UntarUncompressed reads a stream of bytes from `archive`, parses it as a tar archive,
<ide> // and unpacks it into the directory at `dest`.
<ide> // The archive must be an uncompressed stream.
<ide> func UntarUncompressed(tarArchive io.Reader, dest string, options *archive.TarOptions) error {
<del> return untarHandler(tarArchive, dest, options, false)
<add> return untarHandler(tarArchive, dest, options, false, dest)
<ide> }
<ide>
<ide> // Handler for teasing out the automatic decompression
<del>func untarHandler(tarArchive io.Reader, dest string, options *archive.TarOptions, decompress bool) error {
<add>func untarHandler(tarArchive io.Reader, dest string, options *archive.TarOptions, decompress bool, root string) error {
<ide> if tarArchive == nil {
<ide> return fmt.Errorf("Empty archive")
<ide> }
<ide> func untarHandler(tarArchive io.Reader, dest string, options *archive.TarOptions
<ide> r = decompressedArchive
<ide> }
<ide>
<del> return invokeUnpack(r, dest, options)
<add> return invokeUnpack(r, dest, options, root)
<ide> }
<ide><path>pkg/chrootarchive/archive_unix.go
<ide> import (
<ide> "io"
<ide> "io/ioutil"
<ide> "os"
<add> "path/filepath"
<ide> "runtime"
<ide>
<ide> "github.com/docker/docker/pkg/archive"
<ide> func untar() {
<ide> fatal(err)
<ide> }
<ide>
<del> if err := chroot(flag.Arg(0)); err != nil {
<add> dst := flag.Arg(0)
<add> var root string
<add> if len(flag.Args()) > 1 {
<add> root = flag.Arg(1)
<add> }
<add>
<add> if root == "" {
<add> root = dst
<add> }
<add>
<add> if err := chroot(root); err != nil {
<ide> fatal(err)
<ide> }
<ide>
<del> if err := archive.Unpack(os.Stdin, "/", options); err != nil {
<add> if err := archive.Unpack(os.Stdin, dst, options); err != nil {
<ide> fatal(err)
<ide> }
<ide> // fully consume stdin in case it is zero padded
<ide> func untar() {
<ide> os.Exit(0)
<ide> }
<ide>
<del>func invokeUnpack(decompressedArchive io.Reader, dest string, options *archive.TarOptions) error {
<add>func invokeUnpack(decompressedArchive io.Reader, dest string, options *archive.TarOptions, root string) error {
<ide>
<ide> // We can't pass a potentially large exclude list directly via cmd line
<ide> // because we easily overrun the kernel's max argument/environment size
<ide> func invokeUnpack(decompressedArchive io.Reader, dest string, options *archive.T
<ide> return fmt.Errorf("Untar pipe failure: %v", err)
<ide> }
<ide>
<del> cmd := reexec.Command("docker-untar", dest)
<add> if root != "" {
<add> relDest, err := filepath.Rel(root, dest)
<add> if err != nil {
<add> return err
<add> }
<add> if relDest == "." {
<add> relDest = "/"
<add> }
<add> if relDest[0] != '/' {
<add> relDest = "/" + relDest
<add> }
<add> dest = relDest
<add> }
<add>
<add> cmd := reexec.Command("docker-untar", dest, root)
<ide> cmd.Stdin = decompressedArchive
<ide>
<ide> cmd.ExtraFiles = append(cmd.ExtraFiles, r)
<ide> func invokeUnpack(decompressedArchive io.Reader, dest string, options *archive.T
<ide> w.Close()
<ide> return fmt.Errorf("Untar error on re-exec cmd: %v", err)
<ide> }
<add>
<ide> //write the options to the pipe for the untar exec to read
<ide> if err := json.NewEncoder(w).Encode(options); err != nil {
<ide> w.Close()
<ide><path>pkg/chrootarchive/archive_unix_test.go
<add>// +build !windows
<add>
<add>package chrootarchive
<add>
<add>import (
<add> "bytes"
<add> "io"
<add> "io/ioutil"
<add> "os"
<add> "path/filepath"
<add> "testing"
<add>
<add> "github.com/docker/docker/pkg/archive"
<add> "golang.org/x/sys/unix"
<add> "gotest.tools/assert"
<add>)
<add>
<add>// Test for CVE-2018-15664
<add>// Assures that in the case where an "attacker" controlled path is a symlink to
<add>// some path outside of a container's rootfs that we do not copy data to a
<add>// container path that will actually overwrite data on the host
<add>func TestUntarWithMaliciousSymlinks(t *testing.T) {
<add> dir, err := ioutil.TempDir("", t.Name())
<add> assert.NilError(t, err)
<add> defer os.RemoveAll(dir)
<add>
<add> root := filepath.Join(dir, "root")
<add>
<add> err = os.MkdirAll(root, 0755)
<add> assert.NilError(t, err)
<add>
<add> // Add a file into a directory above root
<add> // Ensure that we can't access this file while tarring.
<add> err = ioutil.WriteFile(filepath.Join(dir, "host-file"), []byte("I am a host file"), 0644)
<add> assert.NilError(t, err)
<add>
<add> // Create some data which which will be copied into the "container" root into
<add> // the symlinked path.
<add> // Before this change, the copy would overwrite the "host" content.
<add> // With this change it should not.
<add> data := filepath.Join(dir, "data")
<add> err = os.MkdirAll(data, 0755)
<add> assert.NilError(t, err)
<add> err = ioutil.WriteFile(filepath.Join(data, "local-file"), []byte("pwn3d"), 0644)
<add> assert.NilError(t, err)
<add>
<add> safe := filepath.Join(root, "safe")
<add> err = unix.Symlink(dir, safe)
<add> assert.NilError(t, err)
<add>
<add> rdr, err := archive.TarWithOptions(data, &archive.TarOptions{IncludeFiles: []string{"local-file"}, RebaseNames: map[string]string{"local-file": "host-file"}})
<add> assert.NilError(t, err)
<add>
<add> // Use tee to test both the good case and the bad case w/o recreating the archive
<add> bufRdr := bytes.NewBuffer(nil)
<add> tee := io.TeeReader(rdr, bufRdr)
<add>
<add> err = UntarWithRoot(tee, safe, nil, root)
<add> assert.Assert(t, err != nil)
<add> assert.ErrorContains(t, err, "open /safe/host-file: no such file or directory")
<add>
<add> // Make sure the "host" file is still in tact
<add> // Before the fix the host file would be overwritten
<add> hostData, err := ioutil.ReadFile(filepath.Join(dir, "host-file"))
<add> assert.NilError(t, err)
<add> assert.Equal(t, string(hostData), "I am a host file")
<add>
<add> // Now test by chrooting to an attacker controlled path
<add> // This should succeed as is and overwrite a "host" file
<add> // Note that this would be a mis-use of this function.
<add> err = UntarWithRoot(bufRdr, safe, nil, safe)
<add> assert.NilError(t, err)
<add>
<add> hostData, err = ioutil.ReadFile(filepath.Join(dir, "host-file"))
<add> assert.NilError(t, err)
<add> assert.Equal(t, string(hostData), "pwn3d")
<add>}
<ide><path>pkg/chrootarchive/archive_windows.go
<ide> func chroot(path string) error {
<ide>
<ide> func invokeUnpack(decompressedArchive io.ReadCloser,
<ide> dest string,
<del> options *archive.TarOptions) error {
<add> options *archive.TarOptions, root string) error {
<ide> // Windows is different to Linux here because Windows does not support
<ide> // chroot. Hence there is no point sandboxing a chrooted process to
<ide> // do the unpack. We call inline instead within the daemon process. | 5 |
Python | Python | drop python 3.6 compatibility objects/modules | 1dccaad46b901189c1928cef8419f1ea1160d550 | <ide><path>airflow/compat/asyncio.py
<del># Licensed to the Apache Software Foundation (ASF) under one
<del># or more contributor license agreements. See the NOTICE file
<del># distributed with this work for additional information
<del># regarding copyright ownership. The ASF licenses this file
<del># to you under the Apache License, Version 2.0 (the
<del># "License"); you may not use this file except in compliance
<del># with the License. You may obtain a copy of the License at
<del>#
<del># http://www.apache.org/licenses/LICENSE-2.0
<del>#
<del># Unless required by applicable law or agreed to in writing,
<del># software distributed under the License is distributed on an
<del># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<del># KIND, either express or implied. See the License for the
<del># specific language governing permissions and limitations
<del># under the License.
<del>
<del>try:
<del> from asyncio import create_task
<del>except ImportError:
<del> # create_task is not present in Python 3.6. Once Airflow is at 3.7+, we can
<del> # remove this helper.
<del> def create_task(*args, **kwargs): # type: ignore
<del> """A version of create_task that always errors."""
<del> raise RuntimeError("Airflow's async functionality is only available on Python 3.7+")
<del>
<del>
<del>__all__ = ["create_task"]
<ide><path>airflow/jobs/triggerer_job.py
<ide>
<ide> from sqlalchemy import func
<ide>
<del>from airflow.compat.asyncio import create_task
<ide> from airflow.configuration import conf
<ide> from airflow.jobs.base_job import BaseJob
<ide> from airflow.models.trigger import Trigger
<ide> async def arun(self):
<ide> The loop in here runs trigger addition/deletion/cleanup. Actual
<ide> triggers run in their own separate coroutines.
<ide> """
<del> watchdog = create_task(self.block_watchdog())
<add> watchdog = asyncio.create_task(self.block_watchdog())
<ide> last_status = time.time()
<ide> while not self.stop:
<ide> # Run core logic
<ide> async def create_triggers(self):
<ide> trigger_id, trigger_instance = self.to_create.popleft()
<ide> if trigger_id not in self.triggers:
<ide> self.triggers[trigger_id] = {
<del> "task": create_task(self.run_trigger(trigger_id, trigger_instance)),
<add> "task": asyncio.create_task(self.run_trigger(trigger_id, trigger_instance)),
<ide> "name": f"{trigger_instance!r} (ID {trigger_id})",
<ide> "events": 0,
<ide> }
<ide><path>airflow/models/dag.py
<ide> from airflow.timetables.base import DagRunInfo, DataInterval, TimeRestriction, Timetable
<ide> from airflow.timetables.interval import CronDataIntervalTimetable, DeltaDataIntervalTimetable
<ide> from airflow.timetables.simple import NullTimetable, OnceTimetable
<del>from airflow.typing_compat import Literal, RePatternType
<add>from airflow.typing_compat import Literal
<ide> from airflow.utils import timezone
<ide> from airflow.utils.dag_cycle_tester import check_cycle
<ide> from airflow.utils.dates import cron_presets, date_range as utils_date_range
<ide> def sub_dag(self, *args, **kwargs):
<ide>
<ide> def partial_subset(
<ide> self,
<del> task_ids_or_regex: Union[str, RePatternType, Iterable[str]],
<add> task_ids_or_regex: Union[str, re.Pattern, Iterable[str]],
<ide> include_downstream=False,
<ide> include_upstream=True,
<ide> include_direct_upstream=False,
<ide> def partial_subset(
<ide> memo = {id(self.task_dict): None, id(self._task_group): None}
<ide> dag = copy.deepcopy(self, memo) # type: ignore
<ide>
<del> if isinstance(task_ids_or_regex, (str, RePatternType)):
<add> if isinstance(task_ids_or_regex, (str, re.Pattern)):
<ide> matched_tasks = [t for t in self.tasks if re.findall(task_ids_or_regex, t.task_id)]
<ide> else:
<ide> matched_tasks = [t for t in self.tasks if t.task_id in task_ids_or_regex]
<ide><path>airflow/typing_compat.py
<ide> from typing import Literal, Protocol, TypedDict, runtime_checkable # type: ignore
<ide> except ImportError:
<ide> from typing_extensions import Literal, Protocol, TypedDict, runtime_checkable # type: ignore # noqa
<del>
<del>
<del># Before Py 3.7, there is no re.Pattern class
<del>try:
<del> from re import Pattern as RePatternType # type: ignore
<del>except ImportError:
<del> import re
<del>
<del> RePatternType = type(re.compile('', 0)) # type: ignore
<ide><path>airflow/utils/log/secrets_masker.py
<ide> from airflow.compat.functools import cache, cached_property
<ide>
<ide> if TYPE_CHECKING:
<del> from airflow.typing_compat import RePatternType
<del>
<ide> RedactableItem = Union[str, Dict[Any, Any], Tuple[Any, ...], List[Any]]
<ide>
<ide>
<ide> def _secrets_masker() -> "SecretsMasker":
<ide> class SecretsMasker(logging.Filter):
<ide> """Redact secrets from logs"""
<ide>
<del> replacer: Optional["RePatternType"] = None
<add> replacer: Optional[re.Pattern] = None
<ide> patterns: Set[str]
<ide>
<ide> ALREADY_FILTERED_FLAG = "__SecretsMasker_filtered"
<ide><path>tests/triggers/test_temporal.py
<ide> import pendulum
<ide> import pytest
<ide>
<del>from airflow.compat.asyncio import create_task
<ide> from airflow.triggers.base import TriggerEvent
<ide> from airflow.triggers.temporal import DateTimeTrigger, TimeDeltaTrigger
<ide> from airflow.utils import timezone
<ide> async def test_datetime_trigger_timing():
<ide>
<ide> # Create a task that runs the trigger for a short time then cancels it
<ide> trigger = DateTimeTrigger(future_moment)
<del> trigger_task = create_task(trigger.run().__anext__())
<add> trigger_task = asyncio.create_task(trigger.run().__anext__())
<ide> await asyncio.sleep(0.5)
<ide>
<ide> # It should not have produced a result
<ide> async def test_datetime_trigger_timing():
<ide>
<ide> # Now, make one waiting for en event in the past and do it again
<ide> trigger = DateTimeTrigger(past_moment)
<del> trigger_task = create_task(trigger.run().__anext__())
<add> trigger_task = asyncio.create_task(trigger.run().__anext__())
<ide> await asyncio.sleep(0.5)
<ide>
<ide> assert trigger_task.done() is True | 6 |
Java | Java | fix javadoc for flowable and observable reduce. | cf6f5b887bdd0f2e568c600a94bb931d8969c581 | <ide><path>src/main/java/io/reactivex/Flowable.java
<ide> public final Maybe<T> reduce(BiFunction<T, T, T> reducer) {
<ide> }
<ide>
<ide> /**
<del> * Returns a Flowable that applies a specified accumulator function to the first item emitted by a source
<add> * Returns a Single that applies a specified accumulator function to the first item emitted by a source
<ide> * Publisher and a specified seed value, then feeds the result of that function along with the second item
<ide> * emitted by a Publisher into the same function, and so on until all items have been emitted by the
<ide> * source Publisher, emitting the final result from the final call to your function as its sole item.
<ide><path>src/main/java/io/reactivex/Observable.java
<ide> public final Maybe<T> reduce(BiFunction<T, T, T> reducer) {
<ide> }
<ide>
<ide> /**
<del> * Returns an Observable that applies a specified accumulator function to the first item emitted by a source
<add> * Returns a Single that applies a specified accumulator function to the first item emitted by a source
<ide> * ObservableSource and a specified seed value, then feeds the result of that function along with the second item
<ide> * emitted by an ObservableSource into the same function, and so on until all items have been emitted by the
<ide> * source ObservableSource, emitting the final result from the final call to your function as its sole item. | 2 |
Javascript | Javascript | use common.mustcall in test-https-strict | f11d4a1556a5536d69c1ae524822a709689c46ac | <ide><path>test/parallel/test-https-strict.js
<ide> server2.listen(0, listening());
<ide> server3.listen(0, listening());
<ide>
<ide> const responseErrors = {};
<del>let expectResponseCount = 0;
<del>let responseCount = 0;
<ide> let pending = 0;
<ide>
<ide>
<ide> function makeReq(path, port, error, host, ca) {
<ide> options.headers = { host: host };
<ide> }
<ide> const req = https.get(options);
<del> expectResponseCount++;
<ide> const server = port === server1.address().port ? server1 :
<ide> port === server2.address().port ? server2 :
<ide> port === server3.address().port ? server3 :
<ide> null;
<del>
<ide> if (!server) throw new Error('invalid port: ' + port);
<ide> server.expectCount++;
<ide>
<del> req.on('response', (res) => {
<del> responseCount++;
<add> req.on('response', common.mustCall((res) => {
<ide> assert.strictEqual(res.connection.authorizationError, error);
<ide> responseErrors[path] = res.connection.authorizationError;
<ide> pending--;
<ide> function makeReq(path, port, error, host, ca) {
<ide> server3.close();
<ide> }
<ide> res.resume();
<del> });
<add> }));
<ide> }
<ide>
<ide> function allListening() {
<ide> process.on('exit', () => {
<ide> assert.strictEqual(server1.requests.length, server1.expectCount);
<ide> assert.strictEqual(server2.requests.length, server2.expectCount);
<ide> assert.strictEqual(server3.requests.length, server3.expectCount);
<del> assert.strictEqual(responseCount, expectResponseCount);
<ide> }); | 1 |
PHP | PHP | improve setup warnings for security.salt | d839d01d25a7f49ec0b74bbf3384f0a1052e851b | <ide><path>src/Error/Debugger.php
<ide> public static function formatHtmlMessage(string $message): string
<ide> */
<ide> public static function checkSecurityKeys(): void
<ide> {
<del> if (Security::getSalt() === '__SALT__') {
<del> trigger_error(sprintf(
<del> 'Please change the value of %s in %s to a salt value specific to your application.',
<del> '\'Security.salt\'',
<del> 'ROOT/config/app.php'
<del> ), E_USER_NOTICE);
<add> $salt = Security::getSalt();
<add> if ($salt === '__SALT__' || strlen($salt) < 32) {
<add> trigger_error(
<add> "Please change the value of `Security.salt` in `ROOT/config/app.php` to a random value of at least 32 characters.",
<add> E_USER_NOTICE
<add> );
<ide> }
<ide> }
<ide> } | 1 |
PHP | PHP | remove uneeded type casting | 1823d99dec990e484a13aec28395468a2a6952d4 | <ide><path>src/Mailer/Renderer.php
<ide> public function render(string $content, array $types = []): array
<ide> $view->setTemplatePath(static::TEMPLATE_FOLDER . DIRECTORY_SEPARATOR . $type);
<ide> $view->setLayoutPath(static::TEMPLATE_FOLDER . DIRECTORY_SEPARATOR . $type);
<ide>
<del> $rendered[$type] = (string)$view->render();
<add> $rendered[$type] = $view->render();
<ide> }
<ide>
<ide> return $rendered; | 1 |
Javascript | Javascript | move checkbox js files to fb internal | dff17effe54dc58dda19fcc81ebacbd8f46e9005 | <ide><path>Libraries/Components/CheckBox/AndroidCheckBoxNativeComponent.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> *
<del> * @flow strict-local
<del> * @format
<del> */
<del>
<del>'use strict';
<del>
<del>import * as React from 'react';
<del>
<del>import codegenNativeCommands from 'react-native/Libraries/Utilities/codegenNativeCommands';
<del>
<del>const requireNativeComponent = require('../../ReactNative/requireNativeComponent');
<del>
<del>import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes';
<del>import type {ViewProps} from '../View/ViewPropTypes';
<del>import type {SyntheticEvent} from '../../Types/CoreEventTypes';
<del>import type {ProcessedColorValue} from '../../StyleSheet/processColor';
<del>
<del>type CheckBoxEvent = SyntheticEvent<
<del> $ReadOnly<{|
<del> target: number,
<del> value: boolean,
<del> |}>,
<del>>;
<del>
<del>type NativeProps = $ReadOnly<{|
<del> ...ViewProps,
<del>
<del> /**
<del> * Used in case the props change removes the component.
<del> */
<del> onChange?: ?(event: CheckBoxEvent) => mixed,
<del>
<del> /**
<del> * Invoked with the new value when the value changes.
<del> */
<del> onValueChange?: ?(value: boolean) => mixed,
<del>
<del> /**
<del> * Used to locate this view in end-to-end tests.
<del> */
<del> testID?: ?string,
<del>
<del> on?: ?boolean,
<del> enabled?: boolean,
<del> tintColors:
<del> | {|
<del> true: ?ProcessedColorValue,
<del> false: ?ProcessedColorValue,
<del> |}
<del> | typeof undefined,
<del>|}>;
<del>
<del>type NativeType = HostComponent<NativeProps>;
<del>
<del>interface NativeCommands {
<del> +setNativeValue: (
<del> viewRef: React.ElementRef<NativeType>,
<del> value: boolean,
<del> ) => void;
<del>}
<del>
<del>export const Commands: NativeCommands = codegenNativeCommands<NativeCommands>({
<del> supportedCommands: ['setNativeValue'],
<del>});
<del>
<del>export default (requireNativeComponent<NativeProps>(
<del> 'AndroidCheckBox',
<del>): NativeType);
<ide><path>Libraries/Components/CheckBox/CheckBox.android.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> *
<del> * @flow strict-local
<del> * @format
<del> */
<del>
<del>'use strict';
<del>
<del>const React = require('react');
<del>const StyleSheet = require('../../StyleSheet/StyleSheet');
<del>const invariant = require('invariant');
<del>const processColor = require('../../StyleSheet/processColor');
<del>
<del>const nullthrows = require('nullthrows');
<del>const setAndForwardRef = require('../../Utilities/setAndForwardRef');
<del>
<del>import AndroidCheckBoxNativeComponent, {
<del> Commands as AndroidCheckBoxCommands,
<del>} from './AndroidCheckBoxNativeComponent';
<del>
<del>import type {ViewProps} from '../View/ViewPropTypes';
<del>import type {SyntheticEvent} from '../../Types/CoreEventTypes';
<del>import type {ColorValue} from '../../StyleSheet/StyleSheetTypes';
<del>
<del>type CheckBoxEvent = SyntheticEvent<
<del> $ReadOnly<{|
<del> target: number,
<del> value: boolean,
<del> |}>,
<del>>;
<del>
<del>type CommonProps = $ReadOnly<{|
<del> ...ViewProps,
<del>
<del> /**
<del> * Used in case the props change removes the component.
<del> */
<del> onChange?: ?(event: CheckBoxEvent) => mixed,
<del>
<del> /**
<del> * Invoked with the new value when the value changes.
<del> */
<del> onValueChange?: ?(value: boolean) => mixed,
<del>
<del> /**
<del> * Used to locate this view in end-to-end tests.
<del> */
<del> testID?: ?string,
<del>|}>;
<del>
<del>type Props = $ReadOnly<{|
<del> ...CommonProps,
<del>
<del> /**
<del> * The value of the checkbox. If true the checkbox will be turned on.
<del> * Default value is false.
<del> */
<del> value?: ?boolean,
<del>
<del> /**
<del> * If true the user won't be able to toggle the checkbox.
<del> * Default value is false.
<del> */
<del> disabled?: ?boolean,
<del>
<del> /**
<del> * Used to get the ref for the native checkbox
<del> */
<del> forwardedRef?: ?React.Ref<typeof AndroidCheckBoxNativeComponent>,
<del>
<del> /**
<del> * Controls the colors the checkbox has in checked and unchecked states.
<del> */
<del> tintColors?: {|true?: ?ColorValue, false?: ?ColorValue|},
<del>|}>;
<del>
<del>/**
<del> * Renders a boolean input (Android only).
<del> *
<del> * This is a controlled component that requires an `onValueChange` callback that
<del> * updates the `value` prop in order for the component to reflect user actions.
<del> * If the `value` prop is not updated, the component will continue to render
<del> * the supplied `value` prop instead of the expected result of any user actions.
<del> *
<del> * ```
<del> * import React from 'react';
<del> * import { AppRegistry, StyleSheet, Text, View, CheckBox } from 'react-native';
<del> *
<del> * export default class App extends React.Component {
<del> * constructor(props) {
<del> * super(props);
<del> * this.state = {
<del> * checked: false
<del> * }
<del> * }
<del> *
<del> * toggle() {
<del> * this.setState(({checked}) => {
<del> * return {
<del> * checked: !checked
<del> * };
<del> * });
<del> * }
<del> *
<del> * render() {
<del> * const {checked} = this.state;
<del> * return (
<del> * <View style={styles.container}>
<del> * <Text>Checked</Text>
<del> * <CheckBox value={checked} onChange={this.toggle.bind(this)} />
<del> * </View>
<del> * );
<del> * }
<del> * }
<del> *
<del> * const styles = StyleSheet.create({
<del> * container: {
<del> * flex: 1,
<del> * flexDirection: 'row',
<del> * alignItems: 'center',
<del> * justifyContent: 'center',
<del> * },
<del> * });
<del> *
<del> * // skip this line if using Create React Native App
<del> * AppRegistry.registerComponent('App', () => App);
<del> * ```
<del> *
<del> * @keyword checkbox
<del> * @keyword toggle
<del> */
<del>class CheckBox extends React.Component<Props> {
<del> _nativeRef: ?React.ElementRef<typeof AndroidCheckBoxNativeComponent> = null;
<del> _setNativeRef = setAndForwardRef({
<del> getForwardedRef: () => this.props.forwardedRef,
<del> setLocalRef: ref => {
<del> this._nativeRef = ref;
<del> },
<del> });
<del>
<del> _onChange = (event: CheckBoxEvent) => {
<del> const value = this.props.value ?? false;
<del> AndroidCheckBoxCommands.setNativeValue(nullthrows(this._nativeRef), value);
<del> // Change the props after the native props are set in case the props
<del> // change removes the component
<del> this.props.onChange && this.props.onChange(event);
<del> this.props.onValueChange &&
<del> this.props.onValueChange(event.nativeEvent.value);
<del> };
<del>
<del> _getTintColors(tintColors) {
<del> if (tintColors) {
<del> const processedTextColorTrue = processColor(tintColors.true);
<del> invariant(
<del> processedTextColorTrue == null ||
<del> typeof processedTextColorTrue === 'number',
<del> 'Unexpected color given for tintColors.true',
<del> );
<del> const processedTextColorFalse = processColor(tintColors.true);
<del> invariant(
<del> processedTextColorFalse == null ||
<del> typeof processedTextColorFalse === 'number',
<del> 'Unexpected color given for tintColors.false',
<del> );
<del> return {
<del> true: processedTextColorTrue,
<del> false: processedTextColorFalse,
<del> };
<del> } else {
<del> return undefined;
<del> }
<del> }
<del>
<del> render() {
<del> const {
<del> disabled: _,
<del> value: __,
<del> tintColors,
<del> style,
<del> forwardedRef,
<del> ...props
<del> } = this.props;
<del> const disabled = this.props.disabled ?? false;
<del> const value = this.props.value ?? false;
<del>
<del> const nativeProps = {
<del> ...props,
<del> onStartShouldSetResponder: () => true,
<del> onResponderTerminationRequest: () => false,
<del> enabled: !disabled,
<del> on: value,
<del> tintColors: this._getTintColors(tintColors),
<del> style: [styles.rctCheckBox, style],
<del> };
<del> return (
<del> <AndroidCheckBoxNativeComponent
<del> {...nativeProps}
<del> ref={this._setNativeRef}
<del> onChange={this._onChange}
<del> />
<del> );
<del> }
<del>}
<del>
<del>const styles = StyleSheet.create({
<del> rctCheckBox: {
<del> height: 32,
<del> width: 32,
<del> },
<del>});
<del>
<del>type CheckBoxType = React.AbstractComponent<
<del> Props,
<del> React.ElementRef<typeof AndroidCheckBoxNativeComponent>,
<del>>;
<del>
<del>const CheckBoxWithRef = React.forwardRef<
<del> Props,
<del> React.ElementRef<typeof AndroidCheckBoxNativeComponent>,
<del>>(function CheckBoxWithRef(props, ref) {
<del> return <CheckBox {...props} forwardedRef={ref} />;
<del>});
<del>
<del>module.exports = (CheckBoxWithRef: CheckBoxType);
<ide><path>Libraries/Components/CheckBox/CheckBox.ios.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> *
<del> * @flow strict-local
<del> * @format
<del> */
<del>
<del>'use strict';
<del>
<del>module.exports = require('../UnimplementedViews/UnimplementedView');
<ide><path>RNTester/js/examples/CheckBox/CheckBoxExample.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> *
<del> * @flow
<del> * @format
<del> */
<del>
<del>'use strict';
<del>
<del>const React = require('react');
<del>const {CheckBox, Text, View, StyleSheet} = require('react-native');
<del>
<del>type BasicState = {|
<del> trueCheckBoxIsOn: boolean,
<del> falseCheckBoxIsOn: boolean,
<del>|};
<del>
<del>type BasicProps = $ReadOnly<{||}>;
<del>class BasicCheckBoxExample extends React.Component<BasicProps, BasicState> {
<del> state = {
<del> trueCheckBoxIsOn: true,
<del> falseCheckBoxIsOn: false,
<del> };
<del>
<del> render() {
<del> return (
<del> <View>
<del> <CheckBox
<del> onValueChange={value => this.setState({falseCheckBoxIsOn: value})}
<del> style={styles.checkbox}
<del> value={this.state.falseCheckBoxIsOn}
<del> tintColors={{false: 'red'}}
<del> />
<del> <CheckBox
<del> onValueChange={value => this.setState({trueCheckBoxIsOn: value})}
<del> value={this.state.trueCheckBoxIsOn}
<del> tintColors={{true: 'green'}}
<del> />
<del> </View>
<del> );
<del> }
<del>}
<del>
<del>type DisabledProps = $ReadOnly<{||}>;
<del>class DisabledCheckBoxExample extends React.Component<DisabledProps> {
<del> render() {
<del> return (
<del> <View>
<del> <CheckBox disabled={true} style={styles.checkbox} value={true} />
<del> <CheckBox disabled={true} value={false} />
<del> </View>
<del> );
<del> }
<del>}
<del>
<del>type EventProps = $ReadOnly<{||}>;
<del>type EventState = {|
<del> eventCheckBoxIsOn: boolean,
<del> eventCheckBoxRegressionIsOn: boolean,
<del>|};
<del>
<del>class EventCheckBoxExample extends React.Component<EventProps, EventState> {
<del> state = {
<del> eventCheckBoxIsOn: false,
<del> eventCheckBoxRegressionIsOn: true,
<del> };
<del>
<del> render() {
<del> return (
<del> <View style={styles.container}>
<del> <View>
<del> <CheckBox
<del> onValueChange={value => this.setState({eventCheckBoxIsOn: value})}
<del> style={styles.checkbox}
<del> value={this.state.eventCheckBoxIsOn}
<del> />
<del> <CheckBox
<del> onValueChange={value => this.setState({eventCheckBoxIsOn: value})}
<del> style={styles.checkbox}
<del> value={this.state.eventCheckBoxIsOn}
<del> />
<del> <Text>{this.state.eventCheckBoxIsOn ? 'On' : 'Off'}</Text>
<del> </View>
<del> <View>
<del> <CheckBox
<del> onValueChange={value =>
<del> this.setState({eventCheckBoxRegressionIsOn: value})
<del> }
<del> style={styles.checkbox}
<del> value={this.state.eventCheckBoxRegressionIsOn}
<del> />
<del> <CheckBox
<del> onValueChange={value =>
<del> this.setState({eventCheckBoxRegressionIsOn: value})
<del> }
<del> style={styles.checkbox}
<del> value={this.state.eventCheckBoxRegressionIsOn}
<del> />
<del> <Text>{this.state.eventCheckBoxRegressionIsOn ? 'On' : 'Off'}</Text>
<del> </View>
<del> </View>
<del> );
<del> }
<del>}
<del>
<del>const styles = StyleSheet.create({
<del> container: {
<del> flexDirection: 'row',
<del> justifyContent: 'space-around',
<del> },
<del> checkbox: {
<del> marginBottom: 10,
<del> },
<del>});
<del>
<del>exports.title = '<CheckBox>';
<del>exports.displayName = 'CheckBoxExample';
<del>exports.description = 'Native boolean input';
<del>exports.examples = [
<del> {
<del> title:
<del> 'CheckBoxes can be set to true or false, and the color of both states can be specified.',
<del> render(): React.Element<any> {
<del> return <BasicCheckBoxExample />;
<del> },
<del> },
<del> {
<del> title: 'CheckBoxes can be disabled',
<del> render(): React.Element<any> {
<del> return <DisabledCheckBoxExample />;
<del> },
<del> },
<del> {
<del> title: 'Change events can be detected',
<del> render(): React.Element<any> {
<del> return <EventCheckBoxExample />;
<del> },
<del> },
<del> {
<del> title: 'CheckBoxes are controlled components',
<del> render(): React.Element<any> {
<del> return <CheckBox />;
<del> },
<del> },
<del>];
<ide><path>RNTester/js/utils/RNTesterList.android.js
<ide> const ComponentExamples: Array<RNTesterExample> = [
<ide> key: 'ButtonExample',
<ide> module: require('../examples/Button/ButtonExample'),
<ide> },
<del> {
<del> key: 'CheckBoxExample',
<del> module: require('../examples/CheckBox/CheckBoxExample'),
<del> },
<ide> {
<ide> key: 'FlatListExample',
<ide> module: require('../examples/FlatList/FlatListExample'),
<ide><path>index.js
<ide> import typeof AccessibilityInfo from './Libraries/Components/AccessibilityInfo/AccessibilityInfo';
<ide> import typeof ActivityIndicator from './Libraries/Components/ActivityIndicator/ActivityIndicator';
<ide> import typeof Button from './Libraries/Components/Button';
<del>import typeof CheckBox from './Libraries/Components/CheckBox/CheckBox';
<ide> import typeof DatePickerIOS from './Libraries/Components/DatePicker/DatePickerIOS';
<ide> import typeof DrawerLayoutAndroid from './Libraries/Components/DrawerAndroid/DrawerLayoutAndroid';
<ide> import typeof FlatList from './Libraries/Lists/FlatList';
<ide> module.exports = {
<ide> get Button(): Button {
<ide> return require('./Libraries/Components/Button');
<ide> },
<del> get CheckBox(): CheckBox {
<del> warnOnce(
<del> 'checkBox-moved',
<del> 'CheckBox has been extracted from react-native core and will be removed in a future release. ' +
<del> "It can now be installed and imported from '@react-native-community/checkbox' instead of 'react-native'. " +
<del> 'See https://github.com/react-native-community/react-native-checkbox',
<del> );
<del> return require('./Libraries/Components/CheckBox/CheckBox');
<del> },
<ide> get DatePickerIOS(): DatePickerIOS {
<ide> warnOnce(
<ide> 'DatePickerIOS-merged',
<ide> if (__DEV__) {
<ide> );
<ide> },
<ide> });
<add>
<add> // $FlowFixMe This is intentional: Flow will error when attempting to access CheckBox.
<add> Object.defineProperty(module.exports, 'CheckBox', {
<add> configurable: true,
<add> get() {
<add> invariant(
<add> false,
<add> 'CheckBox has been removed from React Native. ' +
<add> "It can now be installed and imported from '@react-native-community/checkbox' instead of 'react-native'. " +
<add> 'See https://github.com/react-native-community/react-native-checkbox',
<add> );
<add> },
<add> });
<ide> } | 6 |
Ruby | Ruby | fix code example for word_wrap helper | 334c43370b3a0f179a282080e1d47f072706e1bc | <ide><path>actionpack/lib/action_view/helpers/text_helper.rb
<ide> def pluralize(count, singular, plural = nil)
<ide> # # => Once upon a time
<ide> #
<ide> # word_wrap('Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding a successor to the throne turned out to be more trouble than anyone could have imagined...')
<del> # # => Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\n a successor to the throne turned out to be more trouble than anyone could have\n imagined...
<add> # # => Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\na successor to the throne turned out to be more trouble than anyone could have\nimagined...
<ide> #
<ide> # word_wrap('Once upon a time', :line_width => 8)
<del> # # => Once upon\na time
<add> # # => Once\nupon a\ntime
<ide> #
<ide> # word_wrap('Once upon a time', :line_width => 1)
<ide> # # => Once\nupon\na\ntime | 1 |
PHP | PHP | return empty string on non-existent session read() | 1b0b4fc0625a6b0bda8cb92f6bdf8db6672a8b9a | <ide><path>src/Network/Session/CacheSession.php
<ide> public function close()
<ide> * Method used to read from a cache session.
<ide> *
<ide> * @param string $id The key of the value to read
<del> * @return mixed The value of the key or false if it does not exist
<add> * @return string The value of the key or empty if it does not exist
<ide> */
<ide> public function read($id)
<ide> {
<del> return Cache::read($id, $this->_options['config']);
<add> $value = Cache::read($id, $this->_options['config']);
<add>
<add> if (empty($value)) {
<add> return '';
<add> }
<add>
<add> return $value;
<ide> }
<ide>
<ide> /**
<ide><path>src/Network/Session/DatabaseSession.php
<ide> public function close()
<ide> * Method used to read from a database session.
<ide> *
<ide> * @param int|string $id The key of the value to read
<del> * @return mixed The value of the key or false if it does not exist
<add> * @return string The value of the key or empty if it does not exist
<ide> */
<ide> public function read($id)
<ide> {
<ide> public function read($id)
<ide> ->first();
<ide>
<ide> if (empty($result)) {
<del> return false;
<add> return '';
<ide> }
<ide>
<ide> if (is_string($result['data'])) { | 2 |
Text | Text | use code markup/markdown in headers | 933fd9b14983f960101f4f1a8200ff318fa39175 | <ide><path>doc/api/net.md
<ide> net.createServer().listen(
<ide> path.join('\\\\?\\pipe', process.cwd(), 'myctl'));
<ide> ```
<ide>
<del>## Class: net.Server
<add>## Class: `net.Server`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> added: v0.1.90
<ide>
<ide> This class is used to create a TCP or [IPC][] server.
<ide>
<del>### new net.Server(\[options\]\[, connectionListener\])
<add>### `new net.Server([options][, connectionListener])`
<ide>
<ide> * `options` {Object} See
<ide> [`net.createServer([options][, connectionListener])`][`net.createServer()`].
<ide> This class is used to create a TCP or [IPC][] server.
<ide>
<ide> `net.Server` is an [`EventEmitter`][] with the following events:
<ide>
<del>### Event: 'close'
<add>### Event: `'close'`
<ide> <!-- YAML
<ide> added: v0.5.0
<ide> -->
<ide>
<ide> Emitted when the server closes. If connections exist, this
<ide> event is not emitted until all connections are ended.
<ide>
<del>### Event: 'connection'
<add>### Event: `'connection'`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> added: v0.1.90
<ide> Emitted when a new connection is made. `socket` is an instance of
<ide> `net.Socket`.
<ide>
<del>### Event: 'error'
<add>### Event: `'error'`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> event will **not** be emitted directly following this event unless
<ide> [`server.close()`][] is manually called. See the example in discussion of
<ide> [`server.listen()`][].
<ide>
<del>### Event: 'listening'
<add>### Event: `'listening'`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide>
<ide> Emitted when the server has been bound after calling [`server.listen()`][].
<ide>
<del>### server.address()
<add>### `server.address()`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> server.listen(() => {
<ide>
<ide> Don't call `server.address()` until the `'listening'` event has been emitted.
<ide>
<del>### server.close(\[callback\])
<add>### `server.close([callback])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> The optional `callback` will be called once the `'close'` event occurs. Unlike
<ide> that event, it will be called with an `Error` as its only argument if the server
<ide> was not open when it was closed.
<ide>
<del>### server.connections
<add>### `server.connections`
<ide> <!-- YAML
<ide> added: v0.2.0
<ide> deprecated: v0.9.7
<ide> This becomes `null` when sending a socket to a child with
<ide> [`child_process.fork()`][]. To poll forks and get current number of active
<ide> connections, use asynchronous [`server.getConnections()`][] instead.
<ide>
<del>### server.getConnections(callback)
<add>### `server.getConnections(callback)`
<ide> <!-- YAML
<ide> added: v0.9.7
<ide> -->
<ide> when sockets were sent to forks.
<ide>
<ide> Callback should take two arguments `err` and `count`.
<ide>
<del>### server.listen()
<add>### `server.listen()`
<ide>
<ide> Start a server listening for connections. A `net.Server` can be a TCP or
<ide> an [IPC][] server depending on what it listens to.
<ide> server.on('error', (e) => {
<ide> });
<ide> ```
<ide>
<del>#### server.listen(handle\[, backlog\]\[, callback\])
<add>#### `server.listen(handle[, backlog][, callback])`
<ide> <!-- YAML
<ide> added: v0.5.10
<ide> -->
<ide> valid file descriptor.
<ide>
<ide> Listening on a file descriptor is not supported on Windows.
<ide>
<del>#### server.listen(options\[, callback\])
<add>#### `server.listen(options[, callback])`
<ide> <!-- YAML
<ide> added: v0.11.14
<ide> changes:
<ide> Starting an IPC server as root may cause the server path to be inaccessible for
<ide> unprivileged users. Using `readableAll` and `writableAll` will make the server
<ide> accessible for all users.
<ide>
<del>#### server.listen(path\[, backlog\]\[, callback\])
<add>#### `server.listen(path[, backlog][, callback])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> added: v0.1.90
<ide>
<ide> Start an [IPC][] server listening for connections on the given `path`.
<ide>
<del>#### server.listen(\[port\[, host\[, backlog\]\]\]\[, callback\])
<add>#### `server.listen([port[, host[, backlog]]][, callback])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> In most operating systems, listening to the [unspecified IPv6 address][] (`::`)
<ide> may cause the `net.Server` to also listen on the [unspecified IPv4 address][]
<ide> (`0.0.0.0`).
<ide>
<del>### server.listening
<add>### `server.listening`
<ide> <!-- YAML
<ide> added: v5.7.0
<ide> -->
<ide>
<ide> * {boolean} Indicates whether or not the server is listening for connections.
<ide>
<del>### server.maxConnections
<add>### `server.maxConnections`
<ide> <!-- YAML
<ide> added: v0.2.0
<ide> -->
<ide> high.
<ide> It is not recommended to use this option once a socket has been sent to a child
<ide> with [`child_process.fork()`][].
<ide>
<del>### server.ref()
<add>### `server.ref()`
<ide> <!-- YAML
<ide> added: v0.9.1
<ide> -->
<ide> Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will
<ide> *not* let the program exit if it's the only server left (the default behavior).
<ide> If the server is `ref`ed calling `ref()` again will have no effect.
<ide>
<del>### server.unref()
<add>### `server.unref()`
<ide> <!-- YAML
<ide> added: v0.9.1
<ide> -->
<ide> Calling `unref()` on a server will allow the program to exit if this is the only
<ide> active server in the event system. If the server is already `unref`ed calling
<ide> `unref()` again will have no effect.
<ide>
<del>## Class: net.Socket
<add>## Class: `net.Socket`
<ide> <!-- YAML
<ide> added: v0.3.4
<ide> -->
<ide> is received. For example, it is passed to the listeners of a
<ide> [`'connection'`][] event emitted on a [`net.Server`][], so the user can use
<ide> it to interact with the client.
<ide>
<del>### new net.Socket(\[options\])
<add>### `new net.Socket([options])`
<ide> <!-- YAML
<ide> added: v0.3.4
<ide> -->
<ide> Creates a new socket object.
<ide> The newly created socket can be either a TCP socket or a streaming [IPC][]
<ide> endpoint, depending on what it [`connect()`][`socket.connect()`] to.
<ide>
<del>### Event: 'close'
<add>### Event: `'close'`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> added: v0.1.90
<ide> Emitted once the socket is fully closed. The argument `hadError` is a boolean
<ide> which says if the socket was closed due to a transmission error.
<ide>
<del>### Event: 'connect'
<add>### Event: `'connect'`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide>
<ide> Emitted when a socket connection is successfully established.
<ide> See [`net.createConnection()`][].
<ide>
<del>### Event: 'data'
<add>### Event: `'data'`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> Emitted when data is received. The argument `data` will be a `Buffer` or
<ide> The data will be lost if there is no listener when a `Socket`
<ide> emits a `'data'` event.
<ide>
<del>### Event: 'drain'
<add>### Event: `'drain'`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> Emitted when the write buffer becomes empty. Can be used to throttle uploads.
<ide>
<ide> See also: the return values of `socket.write()`.
<ide>
<del>### Event: 'end'
<add>### Event: `'end'`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> user to write arbitrary amounts of data. The user must call
<ide> [`end()`][`socket.end()`] explicitly to close the connection (i.e. sending a
<ide> FIN packet back).
<ide>
<del>### Event: 'error'
<add>### Event: `'error'`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> added: v0.1.90
<ide> Emitted when an error occurs. The `'close'` event will be called directly
<ide> following this event.
<ide>
<del>### Event: 'lookup'
<add>### Event: `'lookup'`
<ide> <!-- YAML
<ide> added: v0.11.3
<ide> changes:
<ide> Not applicable to Unix sockets.
<ide> * `family` {string|null} The address type. See [`dns.lookup()`][].
<ide> * `host` {string} The hostname.
<ide>
<del>### Event: 'ready'
<add>### Event: `'ready'`
<ide> <!-- YAML
<ide> added: v9.11.0
<ide> -->
<ide> Emitted when a socket is ready to be used.
<ide>
<ide> Triggered immediately after `'connect'`.
<ide>
<del>### Event: 'timeout'
<add>### Event: `'timeout'`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> the socket has been idle. The user must manually close the connection.
<ide>
<ide> See also: [`socket.setTimeout()`][].
<ide>
<del>### socket.address()
<add>### `socket.address()`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> Returns the bound `address`, the address `family` name and `port` of the
<ide> socket as reported by the operating system:
<ide> `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
<ide>
<del>### socket.bufferSize
<add>### `socket.bufferSize`
<ide> <!-- YAML
<ide> added: v0.3.8
<ide> -->
<ide> Users who experience large or growing `bufferSize` should attempt to
<ide> "throttle" the data flows in their program with
<ide> [`socket.pause()`][] and [`socket.resume()`][].
<ide>
<del>### socket.bytesRead
<add>### `socket.bytesRead`
<ide> <!-- YAML
<ide> added: v0.5.3
<ide> -->
<ide> added: v0.5.3
<ide>
<ide> The amount of received bytes.
<ide>
<del>### socket.bytesWritten
<add>### `socket.bytesWritten`
<ide> <!-- YAML
<ide> added: v0.5.3
<ide> -->
<ide> added: v0.5.3
<ide>
<ide> The amount of bytes sent.
<ide>
<del>### socket.connect()
<add>### `socket.connect()`
<ide>
<ide> Initiate a connection on a given socket.
<ide>
<ide> the error passed to the [`'error'`][] listener.
<ide> The last parameter `connectListener`, if supplied, will be added as a listener
<ide> for the [`'connect'`][] event **once**.
<ide>
<del>#### socket.connect(options\[, connectListener\])
<add>#### `socket.connect(options[, connectListener])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> changes:
<ide> net.connect({
<ide> });
<ide> ```
<ide>
<del>#### socket.connect(path\[, connectListener\])
<add>#### `socket.connect(path[, connectListener])`
<ide>
<ide> * `path` {string} Path the client should connect to. See
<ide> [Identifying paths for IPC connections][].
<ide> Alias to
<ide> [`socket.connect(options[, connectListener])`][`socket.connect(options)`]
<ide> called with `{ path: path }` as `options`.
<ide>
<del>#### socket.connect(port\[, host\]\[, connectListener\])
<add>#### `socket.connect(port[, host][, connectListener])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> Alias to
<ide> [`socket.connect(options[, connectListener])`][`socket.connect(options)`]
<ide> called with `{port: port, host: host}` as `options`.
<ide>
<del>### socket.connecting
<add>### `socket.connecting`
<ide> <!-- YAML
<ide> added: v6.1.0
<ide> -->
<ide> that the
<ide> [`socket.connect(options[, connectListener])`][`socket.connect(options)`]
<ide> callback is a listener for the `'connect'` event.
<ide>
<del>### socket.destroy(\[exception\])
<add>### `socket.destroy([exception])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> case of errors (parse error or so).
<ide> If `exception` is specified, an [`'error'`][] event will be emitted and any
<ide> listeners for that event will receive `exception` as an argument.
<ide>
<del>### socket.destroyed
<add>### `socket.destroyed`
<ide>
<ide> * {boolean} Indicates if the connection is destroyed or not. Once a
<ide> connection is destroyed no further data can be transferred using it.
<ide>
<del>### socket.end(\[data\[, encoding\]\]\[, callback\])
<add>### `socket.end([data[, encoding]][, callback])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> server will still send some data.
<ide> If `data` is specified, it is equivalent to calling
<ide> `socket.write(data, encoding)` followed by [`socket.end()`][].
<ide>
<del>### socket.localAddress
<add>### `socket.localAddress`
<ide> <!-- YAML
<ide> added: v0.9.6
<ide> -->
<ide> connecting on. For example, in a server listening on `'0.0.0.0'`, if a client
<ide> connects on `'192.168.1.1'`, the value of `socket.localAddress` would be
<ide> `'192.168.1.1'`.
<ide>
<del>### socket.localPort
<add>### `socket.localPort`
<ide> <!-- YAML
<ide> added: v0.9.6
<ide> -->
<ide> added: v0.9.6
<ide>
<ide> The numeric representation of the local port. For example, `80` or `21`.
<ide>
<del>### socket.pause()
<add>### `socket.pause()`
<ide>
<ide> * Returns: {net.Socket} The socket itself.
<ide>
<ide> Pauses the reading of data. That is, [`'data'`][] events will not be emitted.
<ide> Useful to throttle back an upload.
<ide>
<del>### socket.pending
<add>### `socket.pending`
<ide> <!-- YAML
<ide> added: v11.2.0
<ide> -->
<ide> This is `true` if the socket is not connected yet, either because `.connect()`
<ide> has not yet been called or because it is still in the process of connecting
<ide> (see [`socket.connecting`][]).
<ide>
<del>### socket.ref()
<add>### `socket.ref()`
<ide> <!-- YAML
<ide> added: v0.9.1
<ide> -->
<ide> Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will
<ide> *not* let the program exit if it's the only socket left (the default behavior).
<ide> If the socket is `ref`ed calling `ref` again will have no effect.
<ide>
<del>### socket.remoteAddress
<add>### `socket.remoteAddress`
<ide> <!-- YAML
<ide> added: v0.5.10
<ide> -->
<ide> The string representation of the remote IP address. For example,
<ide> `'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if
<ide> the socket is destroyed (for example, if the client disconnected).
<ide>
<del>### socket.remoteFamily
<add>### `socket.remoteFamily`
<ide> <!-- YAML
<ide> added: v0.11.14
<ide> -->
<ide> added: v0.11.14
<ide>
<ide> The string representation of the remote IP family. `'IPv4'` or `'IPv6'`.
<ide>
<del>### socket.remotePort
<add>### `socket.remotePort`
<ide> <!-- YAML
<ide> added: v0.5.10
<ide> -->
<ide> added: v0.5.10
<ide>
<ide> The numeric representation of the remote port. For example, `80` or `21`.
<ide>
<del>### socket.resume()
<add>### `socket.resume()`
<ide>
<ide> * Returns: {net.Socket} The socket itself.
<ide>
<ide> Resumes reading after a call to [`socket.pause()`][].
<ide>
<del>### socket.setEncoding(\[encoding\])
<add>### `socket.setEncoding([encoding])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> added: v0.1.90
<ide> Set the encoding for the socket as a [Readable Stream][]. See
<ide> [`readable.setEncoding()`][] for more information.
<ide>
<del>### socket.setKeepAlive(\[enable\]\[, initialDelay\])
<add>### `socket.setKeepAlive([enable][, initialDelay])`
<ide> <!-- YAML
<ide> added: v0.1.92
<ide> -->
<ide> data packet received and the first keepalive probe. Setting `0` for
<ide> `initialDelay` will leave the value unchanged from the default
<ide> (or previous) setting.
<ide>
<del>### socket.setNoDelay(\[noDelay\])
<add>### `socket.setNoDelay([noDelay])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> Disables the Nagle algorithm. By default TCP connections use the Nagle
<ide> algorithm, they buffer data before sending it off. Setting `true` for
<ide> `noDelay` will immediately fire off data each time `socket.write()` is called.
<ide>
<del>### socket.setTimeout(timeout\[, callback\])
<add>### `socket.setTimeout(timeout[, callback])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> If `timeout` is 0, then the existing idle timeout is disabled.
<ide> The optional `callback` parameter will be added as a one-time listener for the
<ide> [`'timeout'`][] event.
<ide>
<del>### socket.unref()
<add>### `socket.unref()`
<ide> <!-- YAML
<ide> added: v0.9.1
<ide> -->
<ide> Calling `unref()` on a socket will allow the program to exit if this is the only
<ide> active socket in the event system. If the socket is already `unref`ed calling
<ide> `unref()` again will have no effect.
<ide>
<del>### socket.write(data\[, encoding\]\[, callback\])
<add>### `socket.write(data[, encoding][, callback])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> written out, which may not be immediately.
<ide> See `Writable` stream [`write()`][stream_writable_write] method for more
<ide> information.
<ide>
<del>## net.connect()
<add>## `net.connect()`
<ide>
<ide> Aliases to
<ide> [`net.createConnection()`][`net.createConnection()`].
<ide> Possible signatures:
<ide> * [`net.connect(port[, host][, connectListener])`][`net.connect(port, host)`]
<ide> for TCP connections.
<ide>
<del>### net.connect(options\[, connectListener\])
<add>### `net.connect(options[, connectListener])`
<ide> <!-- YAML
<ide> added: v0.7.0
<ide> -->
<ide> added: v0.7.0
<ide> Alias to
<ide> [`net.createConnection(options[, connectListener])`][`net.createConnection(options)`].
<ide>
<del>### net.connect(path\[, connectListener\])
<add>### `net.connect(path[, connectListener])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> added: v0.1.90
<ide> Alias to
<ide> [`net.createConnection(path[, connectListener])`][`net.createConnection(path)`].
<ide>
<del>### net.connect(port\[, host\]\[, connectListener\])
<add>### `net.connect(port[, host][, connectListener])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> added: v0.1.90
<ide> Alias to
<ide> [`net.createConnection(port[, host][, connectListener])`][`net.createConnection(port, host)`].
<ide>
<del>## net.createConnection()
<add>## `net.createConnection()`
<ide>
<ide> A factory function, which creates a new [`net.Socket`][],
<ide> immediately initiates connection with [`socket.connect()`][],
<ide> Possible signatures:
<ide>
<ide> The [`net.connect()`][] function is an alias to this function.
<ide>
<del>### net.createConnection(options\[, connectListener\])
<add>### `net.createConnection(options[, connectListener])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> changed to:
<ide> const client = net.createConnection({ path: '/tmp/echo.sock' });
<ide> ```
<ide>
<del>### net.createConnection(path\[, connectListener\])
<add>### `net.createConnection(path[, connectListener])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> immediately initiates connection with
<ide> [`socket.connect(path[, connectListener])`][`socket.connect(path)`],
<ide> then returns the `net.Socket` that starts the connection.
<ide>
<del>### net.createConnection(port\[, host\]\[, connectListener\])
<add>### `net.createConnection(port[, host][, connectListener])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> immediately initiates connection with
<ide> [`socket.connect(port[, host][, connectListener])`][`socket.connect(port, host)`],
<ide> then returns the `net.Socket` that starts the connection.
<ide>
<del>## net.createServer(\[options\]\[, connectionListener\])
<add>## `net.createServer([options][, connectionListener])`
<ide> <!-- YAML
<ide> added: v0.5.0
<ide> -->
<ide> Use `nc` to connect to a Unix domain socket server:
<ide> $ nc -U /tmp/echo.sock
<ide> ```
<ide>
<del>## net.isIP(input)
<add>## `net.isIP(input)`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> -->
<ide> Tests if input is an IP address. Returns `0` for invalid strings,
<ide> returns `4` for IP version 4 addresses, and returns `6` for IP version 6
<ide> addresses.
<ide>
<del>## net.isIPv4(input)
<add>## `net.isIPv4(input)`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> -->
<ide> added: v0.3.0
<ide>
<ide> Returns `true` if input is a version 4 IP address, otherwise returns `false`.
<ide>
<del>## net.isIPv6(input)
<add>## `net.isIPv6(input)`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> --> | 1 |
Javascript | Javascript | improve throughput of actionsfor by 30%-40% | 9b3e1eca1f9b0e9e649adcfea15e50b8d895e29f | <ide><path>packages/ember-metal/lib/events.js
<ide> function indexOf(array, target, method) {
<ide> function actionsFor(obj, eventName) {
<ide> var meta = metaFor(obj, true);
<ide> var actions;
<add> var listeners = meta.listeners;
<ide>
<del> if (!meta.listeners) { meta.listeners = {}; }
<del>
<del> if (!meta.hasOwnProperty('listeners')) {
<add> if (!listeners) {
<add> listeners = meta.listeners = create(null);
<add> listeners.__source__ = obj;
<add> } else if (listeners.__source__ !== obj) {
<ide> // setup inherited copy of the listeners object
<del> meta.listeners = create(meta.listeners);
<add> listeners = meta.listeners = create(listeners);
<add> listeners.__source__ = obj;
<ide> }
<ide>
<del> actions = meta.listeners[eventName];
<add> actions = listeners[eventName];
<ide>
<ide> // if there are actions, but the eventName doesn't exist in our listeners, then copy them from the prototype
<del> if (actions && !meta.listeners.hasOwnProperty(eventName)) {
<del> actions = meta.listeners[eventName] = meta.listeners[eventName].slice();
<add> if (actions && actions.__source__ !== obj) {
<add> actions = listeners[eventName] = listeners[eventName].slice();
<add> actions.__source__ = obj;
<ide> } else if (!actions) {
<del> actions = meta.listeners[eventName] = [];
<add> actions = listeners[eventName] = [];
<add> actions.__source__ = obj;
<ide> }
<ide>
<ide> return actions;
<ide> export function watchedEvents(obj) {
<ide> var listeners = obj['__ember_meta__'].listeners, ret = [];
<ide>
<ide> if (listeners) {
<del> for(var eventName in listeners) {
<del> if (listeners[eventName]) { ret.push(eventName); }
<add> for (var eventName in listeners) {
<add> if (eventName !== '__source__' &&
<add> listeners[eventName]) {
<add> ret.push(eventName);
<add> }
<ide> }
<ide> }
<ide> return ret; | 1 |
PHP | PHP | make getdictionary public | e747c4a1098d5c33073588ce91d4025f8e9d629e | <ide><path>src/Illuminate/Database/Eloquent/Collection.php
<ide> public function unique()
<ide> * @param \Illuminate\Support\Collection $collection
<ide> * @return array
<ide> */
<del> protected function getDictionary($collection)
<add> public function getDictionary($collection)
<ide> {
<ide> $dictionary = array();
<ide> | 1 |
PHP | PHP | fix whitespace and comment errors | 6f7557898d2e5bb22b2d030b860d111f76279fb3 | <ide><path>lib/Cake/Network/CakeSocket.php
<ide> class CakeSocket {
<ide> * @var array
<ide> */
<ide> protected $_baseConfig = array(
<del> 'persistent' => false,
<del> 'host' => 'localhost',
<del> 'protocol' => 'tcp',
<del> 'port' => 80,
<del> 'timeout' => 30
<add> 'persistent' => false,
<add> 'host' => 'localhost',
<add> 'protocol' => 'tcp',
<add> 'port' => 80,
<add> 'timeout' => 30
<ide> );
<ide>
<ide> /**
<ide> class CakeSocket {
<ide>
<ide> /**
<ide> * True if the socket stream is encrypted after a CakeSocket::enableCrypto() call
<del> * @var type
<del> */
<add> *
<add> * @var boolean
<add> */
<ide> public $encrypted = false;
<del>
<add>
<ide> /**
<ide> * Contains all the encryption methods available
<del> * @var array
<add> *
<add> * @var array
<ide> */
<ide> protected $_encryptMethods = array(
<ide> 'sslv2_client' => STREAM_CRYPTO_METHOD_SSLv2_CLIENT,
<ide> public function reset($state = null) {
<ide>
<ide> /**
<ide> * Encrypts current stream socket, using one of the defined encryption methods
<del> *
<add> *
<ide> * @param string $type can be one of 'ssl2', 'ssl3', 'ssl23' or 'tls'
<ide> * @param string $clientOrServer can be one of 'client', 'server'. Default is 'client'
<ide> * @param boolean $enable enable or disable encryption. Default is true (enable)
<ide> * @return boolean True on success
<del> * @throws SocketException
<del> * @see stream_socket_enable_crypto
<add> * @throws InvalidArgumentException When an invalid encryption scheme is chosen.
<add> * @throws SocketException When attempting to enable SSL/TLS fails
<add> * @see stream_socket_enable_crypto
<ide> */
<ide> public function enableCrypto($type, $clientOrServer = 'client', $enable = true) {
<ide> if (!array_key_exists($type . '_' . $clientOrServer, $this->_encryptMethods)) {
<ide> public function enableCrypto($type, $clientOrServer = 'client', $enable = true)
<ide> $this->setLastError(null, $errorMessage);
<ide> throw new SocketException($errorMessage);
<ide> }
<del> }
<del>}
<ide>\ No newline at end of file
<add> }
<add>
<add>}
<ide><path>lib/Cake/Test/Case/Network/CakeSocketTest.php
<ide> public function testReset() {
<ide>
<ide> /**
<ide> * testEncrypt
<del> *
<add> *
<ide> * @expectedException SocketException
<ide> * @return void
<del> */
<add> */
<ide> public function testEnableCryptoSocketExceptionNoSsl() {
<ide> $configNoSslOrTls = array('host' => 'localhost', 'port' => 80, 'timeout' => 0.1);
<ide>
<ide> public function testEnableCryptoSocketExceptionNoSsl() {
<ide>
<ide> /**
<ide> * testEnableCryptoSocketExceptionNoTls
<del> *
<add> *
<ide> * @expectedException SocketException
<ide> * @return void
<del> */
<add> */
<ide> public function testEnableCryptoSocketExceptionNoTls() {
<ide> $configNoSslOrTls = array('host' => 'localhost', 'port' => 80, 'timeout' => 0.1);
<ide>
<ide> public function testEnableCryptoSocketExceptionNoTls() {
<ide>
<ide> /**
<ide> * _connectSocketToSslTls
<del> *
<add> *
<ide> * @return void
<del> */
<add> */
<ide> protected function _connectSocketToSslTls() {
<ide> $configSslTls = array('host' => 'smtp.gmail.com', 'port' => 465, 'timeout' => 5);
<ide> $this->Socket = new CakeSocket($configSslTls);
<ide> protected function _connectSocketToSslTls() {
<ide>
<ide> /**
<ide> * testEnableCryptoBadMode
<del> *
<add> *
<ide> * @expectedException InvalidArgumentException
<ide> * @return void
<del> */
<add> */
<ide> public function testEnableCryptoBadMode() {
<ide> // testing wrong encryption mode
<ide> $this->_connectSocketToSslTls();
<ide> $this->Socket->enableCrypto('doesntExistMode', 'server');
<ide> $this->Socket->disconnect();
<ide> }
<del>
<add>
<ide> /**
<ide> * testEnableCrypto
<del> *
<add> *
<ide> * @return void
<del> */
<add> */
<ide> public function testEnableCrypto() {
<ide> // testing on ssl server
<ide> $this->_connectSocketToSslTls();
<ide> public function testEnableCrypto() {
<ide> $this->assertTrue($this->Socket->enableCrypto('tls', 'client'));
<ide> $this->Socket->disconnect();
<ide> }
<del>
<add>
<ide> /**
<ide> * testEnableCryptoExceptionEnableTwice
<del> *
<add> *
<ide> * @expectedException SocketException
<ide> * @return void
<del> */
<add> */
<ide> public function testEnableCryptoExceptionEnableTwice() {
<ide> // testing on tls server
<ide> $this->_connectSocketToSslTls();
<ide> public function testEnableCryptoExceptionEnableTwice() {
<ide>
<ide> /**
<ide> * testEnableCryptoExceptionDisableTwice
<del> *
<add> *
<ide> * @expectedException SocketException
<ide> * @return void
<del> */
<add> */
<ide> public function testEnableCryptoExceptionDisableTwice() {
<ide> // testing on tls server
<ide> $this->_connectSocketToSslTls();
<ide> $this->Socket->enableCrypto('tls', 'client', false);
<del> }
<add> }
<ide>
<ide> /**
<ide> * testEnableCryptoEnableStatus
<del> *
<add> *
<ide> * @return void
<del> */
<add> */
<ide> public function testEnableCryptoEnableStatus() {
<ide> // testing on tls server
<ide> $this->_connectSocketToSslTls();
<ide> $this->assertFalse($this->Socket->encrypted);
<ide> $this->Socket->enableCrypto('tls', 'client', true);
<ide> $this->assertTrue($this->Socket->encrypted);
<del> }
<add> }
<add>
<ide> }
<ide><path>lib/Cake/Test/Case/Network/Email/SmtpTransportTest.php
<ide> public function testConnectEhloTlsOnNonTlsServer() {
<ide> $this->socket->expects($this->at(7))->method('read')->will($this->returnValue("500 5.3.3 Unrecognized command\r\n"));
<ide> $this->SmtpTransport->connect();
<ide> }
<del>
<add>
<ide> /**
<ide> * testConnectEhloNoTlsOnRequiredTlsServer method
<ide> *
<ide> public function testConnectEhloNoTlsOnRequiredTlsServer() {
<ide> $this->SmtpTransport->connect();
<ide> $this->SmtpTransport->auth();
<ide> }
<del>
<add>
<ide> /**
<ide> * testConnectHelo method
<ide> * | 3 |
Text | Text | fix typo in reconciliation.md | 2ba571c24618b97049898532e2e220897f9b4c43 | <ide><path>docs/docs/reconciliation.md
<ide> Whenever the root elements have different types, React will tear down the old tr
<ide>
<ide> When tearing down a tree, old DOM nodes are destroyed. Component instances receive `componentWillUnmount()`. When building up a new tree, new DOM nodes are inserted into the DOM. Component instances receive `componentWillMount()` and then `componentDidMount()`. Any state associated with the old tree is lost.
<ide>
<del>Any componts below the root will also get unmounted and have their state destroyed. For example, when diffing:
<add>Any components below the root will also get unmounted and have their state destroyed. For example, when diffing:
<ide>
<ide> ```xml
<ide> <div> | 1 |
Mixed | Python | update helm chart release docs | 339eb0ae41adb3a3b20459ab6ea4c7f6aef87360 | <ide><path>dev/README_RELEASE_HELM_CHART.md
<ide>
<ide> - [Prepare the Apache Airflow Helm Chart Release Candidate](#prepare-the-apache-airflow-helm-chart-release-candidate)
<ide> - [Pre-requisites](#pre-requisites)
<add> - [Build Changelog](#build-changelog)
<ide> - [Build RC artifacts](#build-rc-artifacts)
<ide> - [Prepare Vote email on the Apache Airflow release candidate](#prepare-vote-email-on-the-apache-airflow-release-candidate)
<ide> - [Verify the release candidate by PMCs](#verify-the-release-candidate-by-pmcs)
<ide> - [Publish the final release](#publish-the-final-release)
<ide> - [Summarize the voting for the release](#summarize-the-voting-for-the-release)
<ide> - [Publish release to SVN](#publish-release-to-svn)
<add> - [Publish release tag](#publish-release-tag)
<ide> - [Publish documentation](#publish-documentation)
<del> - [Update `index.yaml` to Airflow Website](#update-indexyaml-to-airflow-website)
<ide> - [Notify developers of release](#notify-developers-of-release)
<ide> - [Update Announcements page](#update-announcements-page)
<ide> - [Remove old releases](#remove-old-releases)
<ide> details the steps for releasing Helm Chart.
<ide>
<ide> - Helm version >= 3.5.4
<ide>
<add>## Build Changelog
<add>
<add>Before creating the RC, you need to build and commit the changelog for the release. For example, to list the
<add>commits between the last release, `1.1.0`, and `main`:
<add>
<add>```shell
<add>git log --oneline helm-chart/1.1.0..main --pretty='format:- %s' -- chart/ docs/helm-chart/
<add>```
<ide>
<ide> ## Build RC artifacts
<ide>
<ide> official Apache releases must not include the rcN suffix.
<ide>
<ide> Subject:
<ide>
<del>```
<del>[VOTE] Release Apache Airflow Helm Chart 1.0.1 based on 1.0.1rc1
<add>```shell
<add>cat <<EOF
<add>[VOTE] Release Apache Airflow Helm Chart ${VERSION_WITHOUT_RC} based on ${VERSION}
<add>EOF
<ide> ```
<ide>
<ide> Body:
<ide>
<del>```
<add>```shell
<add>cat <<EOF
<ide> Hello Apache Airflow Community,
<ide>
<del>This is a call for the vote to release Helm Chart version 1.0.1.
<add>This is a call for the vote to release Helm Chart version ${VERSION_WITHOUT_RC}.
<ide>
<ide> The release candidate is available at:
<del>https://dist.apache.org/repos/dist/dev/airflow/helm-chart/1.0.1rc1/
<add>https://dist.apache.org/repos/dist/dev/airflow/helm-chart/$VERSION/
<ide>
<del>airflow-chart-1.0.1-source.tar.gz - is the "main source release" that comes with INSTALL instructions.
<del>airflow-1.0.1.tgz - is the binary Helm Chart release.
<add>airflow-chart-${VERSION_WITHOUT_RC}-source.tar.gz - is the "main source release" that comes with INSTALL instructions.
<add>airflow-${VERSION_WITHOUT_RC}.tgz - is the binary Helm Chart release.
<ide>
<ide> Public keys are available at: https://www.apache.org/dist/airflow/KEYS
<ide>
<ide> For convenience "index.yaml" has been uploaded (though excluded from voting), so you can also run the below commands.
<ide>
<del>helm repo add apache-airflow-dev https://dist.apache.org/repos/dist/dev/airflow/helm-chart/1.0.1rc1/
<add>helm repo add apache-airflow-dev https://dist.apache.org/repos/dist/dev/airflow/helm-chart/$VERSION/
<ide> helm repo update
<ide> helm install airflow apache-airflow-dev/airflow
<ide>
<del>airflow-1.0.1.tgz.prov - is also uploaded for verifying Chart Integrity, though not strictly required for releasing the artifact based on ASF Guidelines.
<add>airflow-${VERSION_WITHOUT_RC}.tgz.prov - is also uploaded for verifying Chart Integrity, though not strictly required for releasing the artifact based on ASF Guidelines.
<ide>
<del>$ helm verify airflow-1.0.1.tgz --keyring ~/.gnupg/secring.gpg
<add>$ helm verify airflow-${VERSION_WITHOUT_RC}.tgz --keyring ~/.gnupg/secring.gpg
<ide> Signed by: Kaxil Naik <[email protected]>
<ide> Signed by: Kaxil Naik <[email protected]>
<ide> Using Key With Fingerprint: CDE15C6E4D3A8EC4ECF4BA4B6674E08AD7DE406F
<ide> encouraged to test the release and vote with "(non-binding)".
<ide>
<ide> For license checks, the .rat-excludes files is included, so you can run the following to verify licenses (just update $PATH_TO_RAT):
<ide>
<del>tar -xvf airflow-chart-1.0.1-source.tar.gz
<del>cd airflow-chart-1.0.1
<add>tar -xvf airflow-chart-${VERSION_WITHOUT_RC}-source.tar.gz
<add>cd airflow-chart-${VERSION_WITHOUT_RC}
<ide> java -jar $PATH_TO_RAT/apache-rat-0.13/apache-rat-0.13.jar chart -E .rat-excludes
<ide>
<del>Please note that the version number excludes the `rcX` string, so it's now
<del>simply 1.0.1. This will allow us to rename the artifact without modifying
<add>Please note that the version number excludes the \`rcX\` string, so it's now
<add>simply ${VERSION_WITHOUT_RC}. This will allow us to rename the artifact without modifying
<ide> the artifact checksums when we actually release.
<ide>
<ide> Thanks,
<ide> <your name>
<add>EOF
<ide> ```
<ide>
<add>Note, you need to update the `helm verify` output and the end of the voting period in the body.
<ide>
<ide> # Verify the release candidate by PMCs
<ide>
<ide> svn commit -m "Release Airflow Helm Chart Check ${VERSION} from ${RC}"
<ide>
<ide> Verify that the packages appear in [Airflow Helm Chart](https://dist.apache.org/repos/dist/release/airflow/helm-chart/).
<ide>
<add>## Publish release tag
<add>
<add>Create and push the release tag:
<add>
<add>```shell
<add>cd "${AIRFLOW_REPO_ROOT}"
<add>git checkout helm-chart/${RC}
<add>git tag -s helm-chart/${VERSION}
<add>git push origin helm-chart/${VERSION}
<add>```
<add>
<ide> ## Publish documentation
<ide>
<ide> In our cases, documentation for the released versions is published in a separate repository -
<ide> between the two repositories to be able to build the documentation.
<ide>
<ide> ```shell
<ide> cd "${AIRFLOW_REPO_ROOT}"
<add> git checkout helm-chart/${VERSION}
<ide> ./breeze build-docs -- --package-filter helm-chart --for-production
<ide> ```
<ide>
<del>- We upload `index.yaml` to the Airflow website to allow: `helm repo add https://airflow.apache.org`.
<add>- Update `index.yaml`
<add>
<add> We upload `index.yaml` to the Airflow website to allow: `helm repo add https://airflow.apache.org`.
<add>
<add> ```shell
<add> cd "${AIRFLOW_SITE_DIRECTORY}"
<add> curl https://dist.apache.org/repos/dist/dev/airflow/helm-chart/${RC}/index.yaml -o index.yaml
<add> https://dist.apache.org/repos/dist/dev/airflow/helm-chart/${VERSION}
<add> sed -i "s|https://dist.apache.org/repos/dist/dev/airflow/helm-chart/$RC|https://downloads.apache.org/airflow/helm-chart/$VERSION|" index.yaml
<add>
<add> git commit -m "Add documentation for Apache Airflow Helm Chart ${VERSION}"
<add> git push
<add> ```
<ide>
<ide> - Now you can preview the documentation.
<ide>
<ide> between the two repositories to be able to build the documentation.
<ide> - Copy the documentation to the ``airflow-site`` repository.
<ide>
<ide> ```shell
<del> ./docs/publish_docs.py --package-filter apache-airflow --package-filter docker-stack
<add> ./docs/publish_docs.py --package-filter helm-chart
<ide> cd "${AIRFLOW_SITE_DIRECTORY}"
<ide> git commit -m "Add documentation for Apache Airflow Helm Chart ${VERSION}"
<ide> git push
<ide> ```
<ide>
<del>## Update `index.yaml` to Airflow Website
<del>
<del>We upload `index.yaml` to the Airflow website to allow: `helm repo add https://airflow.apache.org`.
<del>
<del> ```shell
<del> cd "${AIRFLOW_SITE_DIRECTORY}"
<del> curl https://dist.apache.org/repos/dist/dev/airflow/helm-chart/${RC}/index.yaml -o index.yaml
<del> https://dist.apache.org/repos/dist/dev/airflow/helm-chart/${VERSION}
<del> sed -i "s|https://dist.apache.org/repos/dist/dev/airflow/helm-chart/$RC|https://downloads.apache.org/airflow/helm-chart/$VERSION|" index.yaml
<del>
<del> git commit -m "Add documentation for Apache Airflow Helm Chart ${VERSION}"
<del> git push
<del> ```
<del>
<ide> ## Notify developers of release
<ide>
<ide> - Notify [email protected] (cc'ing [email protected] and [email protected]) that
<ide> The source release, as well as the "binary" Helm Chart release, are available:
<ide> π¦ Official Sources: https://airflow.apache.org/helm-chart/installing-helm-chart-from-sources.html
<ide> π¦ ArtifactHub: https://artifacthub.io/packages/helm/apache-airflow/airflow
<ide> π Docs: https://airflow.apache.org/docs/helm-chart/$VERSION/
<add>π Quick Start Installation Guide: https://airflow.apache.org/docs/helm-chart/$VERSION/quick-start.html
<add>π οΈ Changelog: https://airflow.apache.org/docs/helm-chart/$VERSION/changelog.html
<ide>
<ide> Thanks to all the contributors who made this possible.
<ide>
<ide><path>docs/exts/docs_build/docs_builder.py
<ide> pretty_format_path,
<ide> )
<ide> from docs.exts.docs_build.errors import DocBuildError, parse_sphinx_warnings
<add>from docs.exts.docs_build.helm_chart_utils import chart_version
<ide> from docs.exts.docs_build.spelling_checks import SpellingError, parse_spelling_warnings
<ide>
<ide> console = Console(force_terminal=True, color_system="standard", width=CONSOLE_WIDTH)
<ide> def _current_version(self):
<ide> if self.package_name.startswith('apache-airflow-providers-'):
<ide> provider = next(p for p in ALL_PROVIDER_YAMLS if p['package-name'] == self.package_name)
<ide> return provider['versions'][0]
<add> if self.package_name == 'helm-chart':
<add> return chart_version()
<ide> return Exception(f"Unsupported package: {self.package_name}")
<ide>
<ide> @property
<ide><path>docs/exts/docs_build/helm_chart_utils.py
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>
<add>import os
<add>
<add>import yaml
<add>
<add>CHART_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, "chart"))
<add>CHART_YAML_PATH = os.path.join(CHART_DIR, "Chart.yaml")
<add>
<add>
<add>def chart_yaml() -> dict:
<add> with open(CHART_YAML_PATH) as f:
<add> return yaml.safe_load(f)
<add>
<add>
<add>def chart_version() -> str:
<add> return chart_yaml()["version"]
<ide><path>docs/publish_docs.py
<ide> def get_available_packages():
<ide> """Get list of all available packages to build."""
<ide> provider_package_names = [provider['package-name'] for provider in ALL_PROVIDER_YAMLS]
<del> return ["apache-airflow", "docker-stack", *provider_package_names, "apache-airflow-providers"]
<add> return [
<add> "apache-airflow",
<add> "docker-stack",
<add> *provider_package_names,
<add> "apache-airflow-providers",
<add> "helm-chart",
<add> ]
<ide>
<ide>
<ide> def _get_parser(): | 4 |
Python | Python | remove some unusefull import | 491eb4cfc24bd4e2709da1b124ee72eed1943efc | <ide><path>glances/core/glances_main.py
<ide> import argparse
<ide>
<ide> # Import Glances libs
<del># !!! Todo: rename class
<del># GlancesExemple
<ide> from glances.core.glances_globals import __appname__, __version__, __author__, __license__
<ide> from glances.core.glances_globals import *
<add># !!! Todo: rename class
<ide> from glances.core.glances_config import Config
<del>from glances.core.glances_stats import GlancesStats, GlancesStatsServer
<add>
<ide>
<ide> class GlancesMain(object):
<ide> """ | 1 |
Go | Go | fix error message for pause a restarting container | 2c63ac3a974a7ab56ffeddece76cc29710ef2996 | <ide><path>daemon/pause.go
<ide> func (daemon *Daemon) containerPause(container *container.Container) error {
<ide> return derr.ErrorCodeAlreadyPaused.WithArgs(container.ID)
<ide> }
<ide>
<add> // We cannot Pause the container which is restarting
<add> if container.Restarting {
<add> return derr.ErrorCodeContainerRestarting.WithArgs(container.ID)
<add> }
<add>
<ide> if err := daemon.execDriver.Pause(container.Command); err != nil {
<ide> return err
<ide> } | 1 |
Ruby | Ruby | fix tap issue url | 54fc1946f96cf9f4391e33f9c692b5aba317ebac | <ide><path>Library/Homebrew/exceptions.rb
<ide> def dump
<ide> puts "#{Tty.red}READ THIS#{Tty.reset}: #{Tty.em}#{ISSUES_URL}#{Tty.reset}"
<ide> if formula.tap?
<ide> user, repo = formula.tap.split '/'
<del> tap_issues_url = "https://github.com/#{user}/homebrew-#{repo}/issues"
<add> tap_issues_url = "https://github.com/#{user}/#{repo}/issues"
<ide> puts "If reporting this issue please do so at (not Homebrew/homebrew):"
<ide> puts " #{tap_issues_url}"
<ide> end | 1 |
Javascript | Javascript | remove the `customstyle` class | d36c46b2c9b0dc526804aacea97609f2fdd49dad | <ide><path>src/display/annotation_layer.js
<ide> */
<ide>
<ide> import {
<del> addLinkAttributes, CustomStyle, DOMSVGFactory, getDefaultSetting,
<del> getFilenameFromUrl, LinkTarget
<add> addLinkAttributes, DOMSVGFactory, getDefaultSetting, getFilenameFromUrl,
<add> LinkTarget
<ide> } from './dom_utils';
<ide> import {
<ide> AnnotationBorderStyleType, AnnotationType, stringToPDFString, unreachable,
<ide> class AnnotationElement {
<ide> page.view[3] - data.rect[3] + page.view[1]
<ide> ]);
<ide>
<del> CustomStyle.setProp('transform', container,
<del> 'matrix(' + viewport.transform.join(',') + ')');
<del> CustomStyle.setProp('transformOrigin', container,
<del> -rect[0] + 'px ' + -rect[1] + 'px');
<add> container.style.transform = 'matrix(' + viewport.transform.join(',') + ')';
<add> container.style.transformOrigin = -rect[0] + 'px ' + -rect[1] + 'px';
<ide>
<ide> if (!ignoreBorder && data.borderStyle.width > 0) {
<ide> container.style.borderWidth = data.borderStyle.width + 'px';
<ide> class AnnotationElement {
<ide> let verticalRadius = data.borderStyle.verticalCornerRadius;
<ide> if (horizontalRadius > 0 || verticalRadius > 0) {
<ide> let radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
<del> CustomStyle.setProp('borderRadius', container, radius);
<add> container.style.borderRadius = radius;
<ide> }
<ide>
<ide> switch (data.borderStyle.style) {
<ide> class PopupAnnotationElement extends AnnotationElement {
<ide> // PDF viewers ignore a popup annotation's rectangle.
<ide> let parentLeft = parseFloat(parentElement.style.left);
<ide> let parentWidth = parseFloat(parentElement.style.width);
<del> CustomStyle.setProp('transformOrigin', this.container,
<del> -(parentLeft + parentWidth) + 'px -' +
<del> parentElement.style.top);
<add> this.container.style.transformOrigin =
<add> -(parentLeft + parentWidth) + 'px -' + parentElement.style.top;
<ide> this.container.style.left = (parentLeft + parentWidth) + 'px';
<ide>
<ide> this.container.appendChild(popup.render());
<ide> class AnnotationLayer {
<ide> let element = parameters.div.querySelector(
<ide> '[data-annotation-id="' + data.id + '"]');
<ide> if (element) {
<del> CustomStyle.setProp('transform', element,
<del> 'matrix(' + parameters.viewport.transform.join(',') + ')');
<add> element.style.transform =
<add> 'matrix(' + parameters.viewport.transform.join(',') + ')';
<ide> }
<ide> }
<ide> parameters.div.removeAttribute('hidden');
<ide><path>src/display/dom_utils.js
<ide> class SimpleXMLParser {
<ide> }
<ide> }
<ide>
<del>/**
<del> * Optimised CSS custom property getter/setter.
<del> * @class
<del> */
<del>var CustomStyle = (function CustomStyleClosure() {
<del>
<del> // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
<del> // animate-css-transforms-firefox-webkit.html
<del> // in some versions of IE9 it is critical that ms appear in this list
<del> // before Moz
<del> var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
<del> var _cache = Object.create(null);
<del>
<del> function CustomStyle() {}
<del>
<del> CustomStyle.getProp = function get(propName, element) {
<del> // check cache only when no element is given
<del> if (arguments.length === 1 && typeof _cache[propName] === 'string') {
<del> return _cache[propName];
<del> }
<del>
<del> element = element || document.documentElement;
<del> var style = element.style, prefixed, uPropName;
<del>
<del> // test standard property first
<del> if (typeof style[propName] === 'string') {
<del> return (_cache[propName] = propName);
<del> }
<del>
<del> // capitalize
<del> uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
<del>
<del> // test vendor specific properties
<del> for (var i = 0, l = prefixes.length; i < l; i++) {
<del> prefixed = prefixes[i] + uPropName;
<del> if (typeof style[prefixed] === 'string') {
<del> return (_cache[propName] = prefixed);
<del> }
<del> }
<del>
<del> // If all fails then set to undefined.
<del> return (_cache[propName] = 'undefined');
<del> };
<del>
<del> CustomStyle.setProp = function set(propName, element, str) {
<del> var prop = this.getProp(propName);
<del> if (prop !== 'undefined') {
<del> element.style[prop] = str;
<del> }
<del> };
<del>
<del> return CustomStyle;
<del>})();
<del>
<ide> var RenderingCancelledException = (function RenderingCancelledException() {
<ide> function RenderingCancelledException(msg, type) {
<ide> this.message = msg;
<ide> class DummyStatTimer {
<ide> }
<ide>
<ide> export {
<del> CustomStyle,
<ide> RenderingCancelledException,
<ide> addLinkAttributes,
<ide> isExternalLinkTargetSet,
<ide><path>src/display/global.js
<ide> */
<ide>
<ide> import {
<del> addLinkAttributes, CustomStyle, DEFAULT_LINK_REL, getFilenameFromUrl,
<add> addLinkAttributes, DEFAULT_LINK_REL, getFilenameFromUrl,
<ide> isExternalLinkTargetSet, isValidUrl, LinkTarget
<ide> } from './dom_utils';
<ide> import {
<ide> PDFJS.LoopbackPort = LoopbackPort;
<ide> PDFJS.PDFDataRangeTransport = PDFDataRangeTransport;
<ide> PDFJS.PDFWorker = PDFWorker;
<ide>
<del>PDFJS.CustomStyle = CustomStyle;
<ide> PDFJS.LinkTarget = LinkTarget;
<ide> PDFJS.addLinkAttributes = addLinkAttributes;
<ide> PDFJS.getFilenameFromUrl = getFilenameFromUrl;
<ide><path>src/display/text_layer.js
<ide> */
<ide>
<ide> import { AbortException, createPromiseCapability, Util } from '../shared/util';
<del>import { CustomStyle, getDefaultSetting } from './dom_utils';
<add>import { getDefaultSetting } from './dom_utils';
<ide>
<ide> /**
<ide> * Text layer render parameters.
<ide> var renderTextLayer = (function renderTextLayerClosure() {
<ide> }
<ide> if (transform !== '') {
<ide> textDivProperties.originalTransform = transform;
<del> CustomStyle.setProp('transform', textDiv, transform);
<add> textDiv.style.transform = transform;
<ide> }
<ide> this._textDivProperties.set(textDiv, textDivProperties);
<ide> textLayerFrag.appendChild(textDiv);
<ide> var renderTextLayer = (function renderTextLayerClosure() {
<ide> div.setAttribute('style', divProperties.style + padding);
<ide> }
<ide> if (transform !== '') {
<del> CustomStyle.setProp('transform', div, transform);
<add> div.style.transform = transform;
<ide> }
<ide> } else {
<ide> div.style.padding = 0;
<del> CustomStyle.setProp('transform', div,
<del> divProperties.originalTransform || '');
<add> div.style.transform = divProperties.originalTransform || '';
<ide> }
<ide> }
<ide> },
<ide><path>src/pdf.js
<ide> exports.PDFDataRangeTransport = pdfjsDisplayAPI.PDFDataRangeTransport;
<ide> exports.PDFWorker = pdfjsDisplayAPI.PDFWorker;
<ide> exports.renderTextLayer = pdfjsDisplayTextLayer.renderTextLayer;
<ide> exports.AnnotationLayer = pdfjsDisplayAnnotationLayer.AnnotationLayer;
<del>exports.CustomStyle = pdfjsDisplayDOMUtils.CustomStyle;
<ide> exports.createPromiseCapability = pdfjsSharedUtil.createPromiseCapability;
<ide> exports.PasswordResponses = pdfjsSharedUtil.PasswordResponses;
<ide> exports.InvalidPDFException = pdfjsSharedUtil.InvalidPDFException;
<ide><path>web/pdf_page_view.js
<ide> import {
<ide> RendererType, roundToDivide
<ide> } from './ui_utils';
<ide> import {
<del> createPromiseCapability, CustomStyle, PDFJS, RenderingCancelledException,
<del> SVGGraphics
<add> createPromiseCapability, PDFJS, RenderingCancelledException, SVGGraphics
<ide> } from 'pdfjs-lib';
<ide> import { getGlobalEventBus } from './dom_events';
<ide> import { RenderingStates } from './pdf_rendering_queue';
<ide> class PDFPageView {
<ide> }
<ide> let cssTransform = 'rotate(' + relativeRotation + 'deg) ' +
<ide> 'scale(' + scaleX + ',' + scaleY + ')';
<del> CustomStyle.setProp('transform', target, cssTransform);
<add> target.style.transform = cssTransform;
<ide>
<ide> if (this.textLayer) {
<ide> // Rotating the text layer is more complicated since the divs inside the
<ide> class PDFPageView {
<ide> console.error('Bad rotation value.');
<ide> break;
<ide> }
<del> CustomStyle.setProp('transform', textLayerDiv,
<del> 'rotate(' + textAbsRotation + 'deg) ' +
<del> 'scale(' + scale + ', ' + scale + ') ' +
<del> 'translate(' + transX + ', ' + transY + ')');
<del> CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
<add>
<add> textLayerDiv.style.transform =
<add> 'rotate(' + textAbsRotation + 'deg) ' +
<add> 'scale(' + scale + ', ' + scale + ') ' +
<add> 'translate(' + transX + ', ' + transY + ')';
<add> textLayerDiv.style.transformOrigin = '0% 0%';
<ide> }
<ide>
<ide> if (redrawAnnotations && this.annotationLayer) { | 6 |
Ruby | Ruby | use fullpaths to file and strip | 1c28de653805994814937c5e1b1aa4932134c731 | <ide><path>Library/Homebrew/cleaner.rb
<ide> def strip path, args=''
<ide> puts "strip #{path}" if ARGV.verbose?
<ide> path.chmod 0644 # so we can strip
<ide> unless path.stat.nlink > 1
<del> system "strip", *(args+path)
<add> system "/usr/bin/strip", *(args+path)
<ide> else
<ide> path = path.to_s.gsub ' ', '\\ '
<ide>
<ide> def strip path, args=''
<ide>
<ide> def clean_file path
<ide> perms = 0444
<del> case `file -h '#{path}'`
<add> case `/usr/bin/file -h '#{path}'`
<ide> when /Mach-O dynamically linked shared library/
<ide> # Stripping libraries is causing no end of trouble. Lets just give up,
<ide> # and try to do it manually in instances where it makes sense. | 1 |
Go | Go | pull scratch for pull test | 77d29847e2a59a7b3e56144c774c28a3b7370c91 | <ide><path>integration-cli/docker_cli_pull_test.go
<ide> import (
<ide>
<ide> // pulling an image from the central registry should work
<ide> func TestPullImageFromCentralRegistry(t *testing.T) {
<del> pullCmd := exec.Command(dockerBinary, "pull", "busybox:latest")
<add> pullCmd := exec.Command(dockerBinary, "pull", "scratch")
<ide> out, exitCode, err := runCommandWithOutput(pullCmd)
<ide> errorOut(err, t, fmt.Sprintf("%s %s", out, err))
<ide> | 1 |
Javascript | Javascript | add attributes to editorcontrols | ba347be773d0226a01e99940b6cc4b755c3d662a | <ide><path>examples/js/controls/EditorControls.js
<ide> THREE.EditorControls = function ( object, domElement ) {
<ide>
<ide> this.enabled = true;
<ide> this.center = new THREE.Vector3();
<add> this.panSpeed = 0.001
<add> this.zoomSpeed = 0.001
<add> this.rotationSpeed = 0.005
<ide>
<ide> // internals
<ide>
<ide> THREE.EditorControls = function ( object, domElement ) {
<ide>
<ide> var distance = object.position.distanceTo( center );
<ide>
<del> delta.multiplyScalar( distance * 0.001 );
<add> delta.multiplyScalar( distance * this.panSpeed );
<ide> delta.applyMatrix3( normalMatrix.getNormalMatrix( object.matrix ) );
<ide>
<ide> object.position.add( delta );
<ide> THREE.EditorControls = function ( object, domElement ) {
<ide>
<ide> var distance = object.position.distanceTo( center );
<ide>
<del> delta.multiplyScalar( distance * 0.001 );
<add> delta.multiplyScalar( distance * this.zoomSpeed );
<ide>
<ide> if ( delta.length() > distance ) return;
<ide>
<ide> THREE.EditorControls = function ( object, domElement ) {
<ide>
<ide> if ( state === STATE.ROTATE ) {
<ide>
<del> scope.rotate( new THREE.Vector3( - movementX * 0.005, - movementY * 0.005, 0 ) );
<add> scope.rotate( new THREE.Vector3( - movementX * this.rotationSpeed, - movementY * this.rotationSpeed, 0 ) );
<ide>
<ide> } else if ( state === STATE.ZOOM ) {
<ide>
<ide> THREE.EditorControls = function ( object, domElement ) {
<ide> case 1:
<ide> touches[ 0 ].set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY, 0 );
<ide> touches[ 1 ].set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY, 0 );
<del> scope.rotate( touches[ 0 ].sub( getClosest( touches[ 0 ], prevTouches ) ).multiplyScalar( - 0.005 ) );
<add> scope.rotate( touches[ 0 ].sub( getClosest( touches[ 0 ], prevTouches ) ).multiplyScalar( - this.rotationSpeed ) );
<ide> break;
<ide>
<ide> case 2: | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.