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
PHP
PHP
refactor the url class
c145e6cbaac90eeae1364923def4a4a3e076a89f
<ide><path>system/url.php <ide> class URL { <ide> */ <ide> public static function to($url = '', $https = false, $asset = false) <ide> { <del> if (filter_var($url, FILTER_VALIDATE_URL) !== false) <del> { <del> return $url; <del> } <add> if (filter_var($url, FILTER_VALIDATE_URL) !== false) return $url; <ide> <ide> $base = Config::get('application.url').'/'.Config::get('application.index'); <ide> <ide> public static function __callStatic($method, $parameters) <ide> { <ide> $parameters = (isset($parameters[0])) ? $parameters[0] : array(); <ide> <del> // Dynamically create a secure route URL. <ide> if (strpos($method, 'to_secure_') === 0) <ide> { <ide> return static::to_route(substr($method, 10), $parameters, true); <ide> } <ide> <del> // Dynamically create a route URL. <ide> if (strpos($method, 'to_') === 0) <ide> { <ide> return static::to_route(substr($method, 3), $parameters);
1
Python
Python
add missing license headers
03a8b2f744a8d962b338a10a9a3a5ced0d79d12d
<ide><path>libcloud/test/common/test_cloudstack.py <add># Licensed to the Apache Software Foundation (ASF) under one or more <add># contributor license agreements. See the NOTICE file distributed with <add># this work for additional information regarding copyright ownership. <add># The ASF licenses this file to You under the Apache License, Version 2.0 <add># (the "License"); you may not use this file except in compliance with <add># the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add> <ide> import sys <ide> import unittest <ide> <ide><path>libcloud/test/common/test_gandi.py <add># Licensed to the Apache Software Foundation (ASF) under one or more <add># contributor license agreements. See the NOTICE file distributed with <add># this work for additional information regarding copyright ownership. <add># The ASF licenses this file to You under the Apache License, Version 2.0 <add># (the "License"); you may not use this file except in compliance with <add># the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add> <ide> from libcloud.utils.py3 import xmlrpclib <ide> from libcloud.test import MockHttp <ide> <ide><path>libcloud/test/common/test_openstack.py <add># Licensed to the Apache Software Foundation (ASF) under one or more <add># contributor license agreements. See the NOTICE file distributed with <add># this work for additional information regarding copyright ownership. <add># The ASF licenses this file to You under the Apache License, Version 2.0 <add># (the "License"); you may not use this file except in compliance with <add># the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add> <ide> import sys <ide> import unittest <ide>
3
Javascript
Javascript
fix redbox on ios
f107d3b78c95ed0313b39e55976cf6b6be36775e
<ide><path>Libraries/Core/NativeExceptionsManager.js <ide> export interface Spec extends TurboModule { <ide> stack: Array<StackFrame>, <ide> exceptionId: number, <ide> ) => void; <add> // TODO(T53311281): This is a noop on iOS now. Implement it. <ide> +reportException?: (data: ExceptionData) => void; <ide> +updateExceptionMessage: ( <ide> message: string, <ide> stack: Array<StackFrame>, <ide> exceptionId: number, <ide> ) => void; <del> // Android only <add> // TODO(T53311281): This is a noop on iOS now. Implement it. <ide> +dismissRedbox?: () => void; <ide> } <ide> <add>const Platform = require('../Utilities/Platform'); <add> <ide> const NativeModule = TurboModuleRegistry.getEnforcing<Spec>( <ide> 'ExceptionsManager', <ide> ); <ide> const ExceptionsManager = { <ide> NativeModule.updateExceptionMessage(message, stack, exceptionId); <ide> }, <ide> dismissRedbox(): void { <del> if (NativeModule.dismissRedbox) { <add> if (Platform.OS !== 'ios' && NativeModule.dismissRedbox) { <add> // TODO(T53311281): This is a noop on iOS now. Implement it. <ide> NativeModule.dismissRedbox(); <ide> } <ide> }, <ide> reportException(data: ExceptionData): void { <del> if (NativeModule.reportException) { <add> if (Platform.OS !== 'ios' && NativeModule.reportException) { <add> // TODO(T53311281): This is a noop on iOS now. Implement it. <ide> NativeModule.reportException(data); <ide> return; <ide> }
1
Mixed
Javascript
add {read|write}big[u]int64{be|le} methods
3d8532f851f2f7a2f8380e717281eaa08b02fb35
<ide><path>benchmark/buffers/buffer-read.js <ide> const common = require('../common.js'); <ide> <ide> const types = [ <add> 'BigUInt64LE', <add> 'BigUInt64BE', <add> 'BigInt64LE', <add> 'BigInt64BE', <ide> 'UInt8', <ide> 'UInt16LE', <ide> 'UInt16BE', <ide><path>benchmark/buffers/buffer-write.js <ide> const common = require('../common.js'); <ide> <ide> const types = [ <add> 'BigUInt64LE', <add> 'BigUInt64BE', <add> 'BigInt64LE', <add> 'BigInt64BE', <ide> 'UInt8', <ide> 'UInt16LE', <ide> 'UInt16BE', <ide> const INT8 = 0x7f; <ide> const INT16 = 0x7fff; <ide> const INT32 = 0x7fffffff; <ide> const INT48 = 0x7fffffffffff; <add>const INT64 = 0x7fffffffffffffffn; <ide> const UINT8 = 0xff; <ide> const UINT16 = 0xffff; <ide> const UINT32 = 0xffffffff; <add>const UINT64 = 0xffffffffffffffffn; <ide> <ide> const mod = { <add> writeBigInt64BE: INT64, <add> writeBigInt64LE: INT64, <add> writeBigUInt64BE: UINT64, <add> writeBigUInt64LE: UINT64, <ide> writeInt8: INT8, <ide> writeInt16BE: INT16, <ide> writeInt16LE: INT16, <ide> function main({ n, buf, type }) { <ide> <ide> if (!/\d/.test(fn)) <ide> benchSpecialInt(buff, fn, n); <add> else if (/BigU?Int/.test(fn)) <add> benchBigInt(buff, fn, BigInt(n)); <ide> else if (/Int/.test(fn)) <ide> benchInt(buff, fn, n); <ide> else <ide> benchFloat(buff, fn, n); <ide> } <ide> <add>function benchBigInt(buff, fn, n) { <add> const m = mod[fn]; <add> bench.start(); <add> for (var i = 0n; i !== n; i++) { <add> buff[fn](i & m, 0); <add> } <add> bench.end(Number(n)); <add>} <add> <ide> function benchInt(buff, fn, n) { <ide> const m = mod[fn]; <ide> bench.start(); <ide><path>doc/api/buffer.md <ide> deprecated: v8.0.0 <ide> <ide> The `buf.parent` property is a deprecated alias for `buf.buffer`. <ide> <add>### buf.readBigInt64BE([offset]) <add>### buf.readBigInt64LE([offset]) <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>* `offset` {integer} Number of bytes to skip before starting to read. Must <add> satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`. <add>* Returns: {bigint} <add> <add>Reads a signed 64-bit integer from `buf` at the specified `offset` with <add>the specified endian format (`readBigInt64BE()` returns big endian, <add>`readBigInt64LE()` returns little endian). <add> <add>Integers read from a `Buffer` are interpreted as two's complement signed values. <add> <add>### buf.readBigUInt64BE([offset]) <add>### buf.readBigUInt64LE([offset]) <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>* `offset` {integer} Number of bytes to skip before starting to read. Must <add> satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`. <add>* Returns: {bigint} <add> <add>Reads an unsigned 64-bit integer from `buf` at the specified `offset` with <add>specified endian format (`readBigUInt64BE()` returns big endian, <add>`readBigUInt64LE()` returns little endian). <add> <add>```js <add>const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); <add> <add>console.log(buf.readBigUInt64BE(0)); <add>// Prints: 4294967295n <add> <add>console.log(buf.readBigUInt64LE(0)); <add>// Prints: 18446744069414584320n <add>``` <add> <ide> ### buf.readDoubleBE([offset]) <ide> ### buf.readDoubleLE([offset]) <ide> <!-- YAML <ide> console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); <ide> // Prints: 12 bytes: ½ + ¼ = ¾ <ide> ``` <ide> <add>### buf.writeBigInt64BE(value[, offset]) <add>### buf.writeBigInt64LE(value[, offset]) <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>* `value` {bigint} Number to be written to `buf`. <add>* `offset` {integer} Number of bytes to skip before starting to write. Must <add> satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`. <add>* Returns: {integer} `offset` plus the number of bytes written. <add> <add>Writes `value` to `buf` at the specified `offset` with specified endian <add>format (`writeBigInt64BE()` writes big endian, `writeBigInt64LE()` writes little <add>endian). <add> <add>`value` is interpreted and written as a two's complement signed integer. <add> <add>```js <add>const buf = Buffer.allocUnsafe(8); <add> <add>buf.writeBigInt64BE(0x0102030405060708n, 0); <add> <add>console.log(buf); <add>// Prints: <Buffer 01 02 03 04 05 06 07 08> <add>``` <add> <add>### buf.writeBigUInt64BE(value[, offset]) <add>### buf.writeBigUInt64LE(value[, offset]) <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>* `value` {bigint} Number to be written to `buf`. <add>* `offset` {integer} Number of bytes to skip before starting to write. Must <add> satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`. <add>* Returns: {integer} `offset` plus the number of bytes written. <add> <add>Writes `value` to `buf` at the specified `offset` with specified endian <add>format (`writeBigUInt64BE()` writes big endian, `writeBigUInt64LE()` writes <add>little endian). <add> <add>```js <add>const buf = Buffer.allocUnsafe(8); <add> <add>buf.writeBigUInt64LE(0xdecafafecacefaden, 0); <add> <add>console.log(buf); <add>// Prints: <Buffer de fa ce ca fe fa ca de> <add>``` <add> <ide> ### buf.writeDoubleBE(value[, offset]) <ide> ### buf.writeDoubleLE(value[, offset]) <ide> <!-- YAML <ide><path>lib/internal/buffer.js <ide> function boundsError(value, length, type) { <ide> } <ide> <ide> // Read integers. <add>function readBigUInt64LE(offset = 0) { <add> validateNumber(offset, 'offset'); <add> const first = this[offset]; <add> const last = this[offset + 7]; <add> if (first === undefined || last === undefined) <add> boundsError(offset, this.length - 8); <add> <add> const lo = first + <add> this[++offset] * 2 ** 8 + <add> this[++offset] * 2 ** 16 + <add> this[++offset] * 2 ** 24; <add> <add> const hi = this[++offset] + <add> this[++offset] * 2 ** 8 + <add> this[++offset] * 2 ** 16 + <add> last * 2 ** 24; <add> <add> return BigInt(lo) + (BigInt(hi) << 32n); <add>} <add> <add>function readBigUInt64BE(offset = 0) { <add> validateNumber(offset, 'offset'); <add> const first = this[offset]; <add> const last = this[offset + 7]; <add> if (first === undefined || last === undefined) <add> boundsError(offset, this.length - 8); <add> <add> const hi = first * 2 ** 24 + <add> this[++offset] * 2 ** 16 + <add> this[++offset] * 2 ** 8 + <add> this[++offset]; <add> <add> const lo = this[++offset] * 2 ** 24 + <add> this[++offset] * 2 ** 16 + <add> this[++offset] * 2 ** 8 + <add> last; <add> <add> return (BigInt(hi) << 32n) + BigInt(lo); <add>} <add> <add>function readBigInt64LE(offset = 0) { <add> validateNumber(offset, 'offset'); <add> const first = this[offset]; <add> const last = this[offset + 7]; <add> if (first === undefined || last === undefined) <add> boundsError(offset, this.length - 8); <add> <add> const val = this[offset + 4] + <add> this[offset + 5] * 2 ** 8 + <add> this[offset + 6] * 2 ** 16 + <add> (last << 24); // Overflow <add> return (BigInt(val) << 32n) + <add> BigInt(first + <add> this[++offset] * 2 ** 8 + <add> this[++offset] * 2 ** 16 + <add> this[++offset] * 2 ** 24); <add>} <add> <add>function readBigInt64BE(offset = 0) { <add> validateNumber(offset, 'offset'); <add> const first = this[offset]; <add> const last = this[offset + 7]; <add> if (first === undefined || last === undefined) <add> boundsError(offset, this.length - 8); <add> <add> const val = (first << 24) + // Overflow <add> this[++offset] * 2 ** 16 + <add> this[++offset] * 2 ** 8 + <add> this[++offset]; <add> return (BigInt(val) << 32n) + <add> BigInt(this[++offset] * 2 ** 24 + <add> this[++offset] * 2 ** 16 + <add> this[++offset] * 2 ** 8 + <add> last); <add>} <add> <ide> function readUIntLE(offset, byteLength) { <ide> if (offset === undefined) <ide> throw new ERR_INVALID_ARG_TYPE('offset', 'number', offset); <ide> function readDoubleForwards(offset = 0) { <ide> } <ide> <ide> // Write integers. <add>function writeBigU_Int64LE(buf, value, offset, min, max) { <add> checkInt(value, min, max, buf, offset, 7); <add> <add> let lo = Number(value & 0xffffffffn); <add> buf[offset++] = lo; <add> lo = lo >> 8; <add> buf[offset++] = lo; <add> lo = lo >> 8; <add> buf[offset++] = lo; <add> lo = lo >> 8; <add> buf[offset++] = lo; <add> let hi = Number(value >> 32n & 0xffffffffn); <add> buf[offset++] = hi; <add> hi = hi >> 8; <add> buf[offset++] = hi; <add> hi = hi >> 8; <add> buf[offset++] = hi; <add> hi = hi >> 8; <add> buf[offset++] = hi; <add> return offset; <add>} <add> <add>function writeBigUInt64LE(value, offset = 0) { <add> return writeBigU_Int64LE(this, value, offset, 0n, 0xffffffffffffffffn); <add>} <add> <add>function writeBigU_Int64BE(buf, value, offset, min, max) { <add> checkInt(value, min, max, buf, offset, 7); <add> <add> let lo = Number(value & 0xffffffffn); <add> buf[offset + 7] = lo; <add> lo = lo >> 8; <add> buf[offset + 6] = lo; <add> lo = lo >> 8; <add> buf[offset + 5] = lo; <add> lo = lo >> 8; <add> buf[offset + 4] = lo; <add> let hi = Number(value >> 32n & 0xffffffffn); <add> buf[offset + 3] = hi; <add> hi = hi >> 8; <add> buf[offset + 2] = hi; <add> hi = hi >> 8; <add> buf[offset + 1] = hi; <add> hi = hi >> 8; <add> buf[offset] = hi; <add> return offset + 8; <add>} <add> <add>function writeBigUInt64BE(value, offset = 0) { <add> return writeBigU_Int64BE(this, value, offset, 0n, 0xffffffffffffffffn); <add>} <add> <add>function writeBigInt64LE(value, offset = 0) { <add> return writeBigU_Int64LE( <add> this, value, offset, -0x8000000000000000n, 0x7fffffffffffffffn); <add>} <add> <add>function writeBigInt64BE(value, offset = 0) { <add> return writeBigU_Int64BE( <add> this, value, offset, -0x8000000000000000n, 0x7fffffffffffffffn); <add>} <add> <ide> function writeUIntLE(value, offset, byteLength) { <ide> if (byteLength === 6) <ide> return writeU_Int48LE(this, value, offset, 0, 0xffffffffffff); <ide> function writeFloatBackwards(val, offset = 0) { <ide> class FastBuffer extends Uint8Array {} <ide> <ide> function addBufferPrototypeMethods(proto) { <add> proto.readBigUInt64LE = readBigUInt64LE, <add> proto.readBigUInt64BE = readBigUInt64BE, <add> proto.readBigInt64LE = readBigInt64LE, <add> proto.readBigInt64BE = readBigInt64BE, <add> proto.writeBigUInt64LE = writeBigUInt64LE, <add> proto.writeBigUInt64BE = writeBigUInt64BE, <add> proto.writeBigInt64LE = writeBigInt64LE, <add> proto.writeBigInt64BE = writeBigInt64BE, <add> <ide> proto.readUIntLE = readUIntLE; <ide> proto.readUInt32LE = readUInt32LE; <ide> proto.readUInt16LE = readUInt16LE; <ide><path>test/parallel/test-buffer-bigint64.js <add>'use strict'; <add>require('../common'); <add>const assert = require('assert'); <add> <add>const buf = Buffer.allocUnsafe(8); <add> <add>['LE', 'BE'].forEach(function(endianness) { <add> // Should allow simple BigInts to be written and read <add> let val = 123456789n; <add> buf['writeBigInt64' + endianness](val, 0); <add> let rtn = buf['readBigInt64' + endianness](0); <add> assert.strictEqual(val, rtn); <add> <add> // Should allow INT64_MAX to be written and read <add> val = 0x7fffffffffffffffn; <add> buf['writeBigInt64' + endianness](val, 0); <add> rtn = buf['readBigInt64' + endianness](0); <add> assert.strictEqual(val, rtn); <add> <add> // Should read and write a negative signed 64-bit integer <add> val = -123456789n; <add> buf['writeBigInt64' + endianness](val, 0); <add> assert.strictEqual(val, buf['readBigInt64' + endianness](0)); <add> <add> // Should read and write an unsigned 64-bit integer <add> val = 123456789n; <add> buf['writeBigUInt64' + endianness](val, 0); <add> assert.strictEqual(val, buf['readBigUInt64' + endianness](0)); <add> <add> // Should throw a RangeError upon INT64_MAX+1 being written <add> assert.throws(function() { <add> const val = 0x8000000000000000n; <add> buf['writeBigInt64' + endianness](val, 0); <add> }, RangeError); <add> <add> // Should throw a RangeError upon UINT64_MAX+1 being written <add> assert.throws(function() { <add> const val = 0x10000000000000000n; <add> buf['writeBigUInt64' + endianness](val, 0); <add> }, RangeError); <add> <add> // Should throw a TypeError upon invalid input <add> assert.throws(function() { <add> buf['writeBigInt64' + endianness]('bad', 0); <add> }, TypeError); <add> <add> // Should throw a TypeError upon invalid input <add> assert.throws(function() { <add> buf['writeBigUInt64' + endianness]('bad', 0); <add> }, TypeError); <add>});
5
Javascript
Javascript
fix 'null' mirroring
b20c98e42708668c564d5f83bad83cf074cf4f58
<ide><path>lib/_debugger.js <ide> Client.prototype.mirrorObject = function(handle, depth, cb) { <ide> return; <ide> } else if (handle.type === 'function') { <ide> val = function() {}; <add> } else if (handle.type === 'null') { <add> val = null; <ide> } else if (handle.value !== undefined) { <ide> val = handle.value; <ide> } else if (handle.type === 'undefined') {
1
Go
Go
add some tests to the volume store
834d0e262ac248191c09bcdb2b86ee92edb6aaf0
<ide><path>integration/volume/volume_test.go <ide> func TestVolumesCreateAndList(t *testing.T) { <ide> Driver: "local", <ide> Scope: "local", <ide> Name: name, <del> Options: map[string]string{}, <ide> Mountpoint: fmt.Sprintf("%s/volumes/%s/_data", testEnv.DaemonInfo.DockerRootDir, name), <ide> } <ide> assert.Equal(t, vol, expected) <ide> func TestVolumesInspect(t *testing.T) { <ide> Driver: "local", <ide> Scope: "local", <ide> Name: name, <del> Options: map[string]string{}, <ide> Mountpoint: fmt.Sprintf("%s/volumes/%s/_data", testEnv.DaemonInfo.DockerRootDir, name), <ide> } <ide> assert.Equal(t, vol, expected) <ide><path>volume/store/db.go <ide> import ( <ide> "encoding/json" <ide> <ide> "github.com/boltdb/bolt" <add> "github.com/docker/docker/errdefs" <ide> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> func setMeta(tx *bolt.Tx, name string, meta volumeMetadata) error { <ide> if err != nil { <ide> return err <ide> } <del> b := tx.Bucket(volumeBucketName) <add> b, err := tx.CreateBucketIfNotExists(volumeBucketName) <add> if err != nil { <add> return errors.Wrap(err, "error creating volume bucket") <add> } <ide> return errors.Wrap(b.Put([]byte(name), metaJSON), "error setting volume metadata") <ide> } <ide> <ide> func (s *VolumeStore) getMeta(name string) (volumeMetadata, error) { <ide> <ide> func getMeta(tx *bolt.Tx, name string, meta *volumeMetadata) error { <ide> b := tx.Bucket(volumeBucketName) <add> if b == nil { <add> return errdefs.NotFound(errors.New("volume bucket does not exist")) <add> } <ide> val := b.Get([]byte(name)) <del> if string(val) == "" { <add> if len(val) == 0 { <ide> return nil <ide> } <ide> if err := json.Unmarshal(val, meta); err != nil { <ide><path>volume/store/db_test.go <add>package store <add> <add>import ( <add> "io/ioutil" <add> "os" <add> "path/filepath" <add> "testing" <add> "time" <add> <add> "github.com/boltdb/bolt" <add> "github.com/stretchr/testify/require" <add>) <add> <add>func TestSetGetMeta(t *testing.T) { <add> t.Parallel() <add> <add> dir, err := ioutil.TempDir("", "test-set-get") <add> require.NoError(t, err) <add> defer os.RemoveAll(dir) <add> <add> db, err := bolt.Open(filepath.Join(dir, "db"), 0600, &bolt.Options{Timeout: 1 * time.Second}) <add> require.NoError(t, err) <add> <add> store := &VolumeStore{db: db} <add> <add> _, err = store.getMeta("test") <add> require.Error(t, err) <add> <add> err = db.Update(func(tx *bolt.Tx) error { <add> _, err := tx.CreateBucket(volumeBucketName) <add> return err <add> }) <add> require.NoError(t, err) <add> <add> meta, err := store.getMeta("test") <add> require.NoError(t, err) <add> require.Equal(t, volumeMetadata{}, meta) <add> <add> testMeta := volumeMetadata{ <add> Name: "test", <add> Driver: "fake", <add> Labels: map[string]string{"a": "1", "b": "2"}, <add> Options: map[string]string{"foo": "bar"}, <add> } <add> err = store.setMeta("test", testMeta) <add> require.NoError(t, err) <add> <add> meta, err = store.getMeta("test") <add> require.NoError(t, err) <add> require.Equal(t, testMeta, meta) <add>} <ide><path>volume/store/restore_test.go <add>package store <add> <add>import ( <add> "io/ioutil" <add> "os" <add> "testing" <add> <add> "github.com/docker/docker/volume" <add> volumedrivers "github.com/docker/docker/volume/drivers" <add> volumetestutils "github.com/docker/docker/volume/testutils" <add> "github.com/stretchr/testify/require" <add>) <add> <add>func TestRestore(t *testing.T) { <add> t.Parallel() <add> <add> dir, err := ioutil.TempDir("", "test-restore") <add> require.NoError(t, err) <add> defer os.RemoveAll(dir) <add> <add> driverName := "test-restore" <add> volumedrivers.Register(volumetestutils.NewFakeDriver(driverName), driverName) <add> defer volumedrivers.Unregister("test-restore") <add> <add> s, err := New(dir) <add> require.NoError(t, err) <add> defer s.Shutdown() <add> <add> _, err = s.Create("test1", driverName, nil, nil) <add> require.NoError(t, err) <add> <add> testLabels := map[string]string{"a": "1"} <add> testOpts := map[string]string{"foo": "bar"} <add> _, err = s.Create("test2", driverName, testOpts, testLabels) <add> require.NoError(t, err) <add> <add> s.Shutdown() <add> <add> s, err = New(dir) <add> require.NoError(t, err) <add> <add> v, err := s.Get("test1") <add> require.NoError(t, err) <add> <add> dv := v.(volume.DetailedVolume) <add> var nilMap map[string]string <add> require.Equal(t, nilMap, dv.Options()) <add> require.Equal(t, nilMap, dv.Labels()) <add> <add> v, err = s.Get("test2") <add> require.NoError(t, err) <add> dv = v.(volume.DetailedVolume) <add> require.Equal(t, testOpts, dv.Options()) <add> require.Equal(t, testLabels, dv.Labels()) <add>} <ide><path>volume/store/store.go <ide> type volumeWrapper struct { <ide> } <ide> <ide> func (v volumeWrapper) Options() map[string]string { <del> options := map[string]string{} <add> if v.options == nil { <add> return nil <add> } <add> options := make(map[string]string, len(v.options)) <ide> for key, value := range v.options { <ide> options[key] = value <ide> } <ide> return options <ide> } <ide> <ide> func (v volumeWrapper) Labels() map[string]string { <del> return v.labels <add> if v.labels == nil { <add> return nil <add> } <add> <add> labels := make(map[string]string, len(v.labels)) <add> for key, value := range v.labels { <add> labels[key] = value <add> } <add> return labels <ide> } <ide> <ide> func (v volumeWrapper) Scope() string { <ide><path>volume/store/store_test.go <ide> import ( <ide> "github.com/docker/docker/volume" <ide> "github.com/docker/docker/volume/drivers" <ide> volumetestutils "github.com/docker/docker/volume/testutils" <add> "github.com/stretchr/testify/assert" <add> "github.com/stretchr/testify/require" <ide> ) <ide> <ide> func TestCreate(t *testing.T) { <ide> func TestDefererencePluginOnCreateError(t *testing.T) { <ide> <ide> pg := volumetestutils.NewFakePluginGetter(p) <ide> volumedrivers.RegisterPluginGetter(pg) <add> defer volumedrivers.RegisterPluginGetter(nil) <ide> <ide> dir, err := ioutil.TempDir("", "test-plugin-deref-err") <ide> if err != nil { <ide> func TestDefererencePluginOnCreateError(t *testing.T) { <ide> t.Fatalf("expected 1 plugin reference, got: %d", refs) <ide> } <ide> } <add> <add>func TestRefDerefRemove(t *testing.T) { <add> t.Parallel() <add> <add> driverName := "test-ref-deref-remove" <add> s, cleanup := setupTest(t, driverName) <add> defer cleanup(t) <add> <add> v, err := s.CreateWithRef("test", driverName, "test-ref", nil, nil) <add> require.NoError(t, err) <add> <add> err = s.Remove(v) <add> require.Error(t, err) <add> require.Equal(t, errVolumeInUse, err.(*OpErr).Err) <add> <add> s.Dereference(v, "test-ref") <add> err = s.Remove(v) <add> require.NoError(t, err) <add>} <add> <add>func TestGet(t *testing.T) { <add> t.Parallel() <add> <add> driverName := "test-get" <add> s, cleanup := setupTest(t, driverName) <add> defer cleanup(t) <add> <add> _, err := s.Get("not-exist") <add> require.Error(t, err) <add> require.Equal(t, errNoSuchVolume, err.(*OpErr).Err) <add> <add> v1, err := s.Create("test", driverName, nil, map[string]string{"a": "1"}) <add> require.NoError(t, err) <add> <add> v2, err := s.Get("test") <add> require.NoError(t, err) <add> require.Equal(t, v1, v2) <add> <add> dv := v2.(volume.DetailedVolume) <add> require.Equal(t, "1", dv.Labels()["a"]) <add> <add> err = s.Remove(v1) <add> require.NoError(t, err) <add>} <add> <add>func TestGetWithRef(t *testing.T) { <add> t.Parallel() <add> <add> driverName := "test-get-with-ref" <add> s, cleanup := setupTest(t, driverName) <add> defer cleanup(t) <add> <add> _, err := s.GetWithRef("not-exist", driverName, "test-ref") <add> require.Error(t, err) <add> <add> v1, err := s.Create("test", driverName, nil, map[string]string{"a": "1"}) <add> require.NoError(t, err) <add> <add> v2, err := s.GetWithRef("test", driverName, "test-ref") <add> require.NoError(t, err) <add> require.Equal(t, v1, v2) <add> <add> err = s.Remove(v2) <add> require.Error(t, err) <add> require.Equal(t, errVolumeInUse, err.(*OpErr).Err) <add> <add> s.Dereference(v2, "test-ref") <add> err = s.Remove(v2) <add> require.NoError(t, err) <add>} <add> <add>func setupTest(t *testing.T, name string) (*VolumeStore, func(*testing.T)) { <add> t.Helper() <add> s, cleanup := newTestStore(t) <add> <add> volumedrivers.Register(volumetestutils.NewFakeDriver(name), name) <add> return s, func(t *testing.T) { <add> cleanup(t) <add> volumedrivers.Unregister(name) <add> } <add>} <add> <add>func newTestStore(t *testing.T) (*VolumeStore, func(*testing.T)) { <add> t.Helper() <add> <add> dir, err := ioutil.TempDir("", "store-root") <add> require.NoError(t, err) <add> <add> cleanup := func(t *testing.T) { <add> err := os.RemoveAll(dir) <add> assert.NoError(t, err) <add> } <add> <add> s, err := New(dir) <add> assert.NoError(t, err) <add> return s, func(t *testing.T) { <add> s.Shutdown() <add> cleanup(t) <add> } <add>}
6
Python
Python
add dot_axes argument to graph
455d7d10db1b105e082747dedeae0352a6bb0f99
<ide><path>keras/layers/containers.py <ide> def add_input(self, name, input_shape, dtype='float'): <ide> 'dtype': dtype}) <ide> <ide> def add_node(self, layer, name, input=None, inputs=[], <del> merge_mode='concat', concat_axis=-1, create_output=False): <add> merge_mode='concat', concat_axis=-1, dot_axes=-1, create_output=False): <ide> if hasattr(layer, 'set_name'): <ide> layer.set_name(name) <ide> if name in self.namespace: <ide> def add_node(self, layer, name, input=None, inputs=[], <ide> to_merge.append(self.inputs[n]) <ide> else: <ide> raise Exception('Unknown identifier: ' + n) <del> merge = Merge(to_merge, mode=merge_mode, concat_axis=concat_axis) <add> merge = Merge(to_merge, mode=merge_mode, concat_axis=concat_axis, dot_axes=dot_axes) <ide> layer.set_previous(merge) <ide> <ide> self.namespace.add(name) <ide> def add_node(self, layer, name, input=None, inputs=[], <ide> 'inputs': inputs, <ide> 'merge_mode': merge_mode, <ide> 'concat_axis': concat_axis, <add> 'dot_axes': dot_axes, <ide> 'create_output': create_output}) <ide> <ide> if create_output: <ide> self.add_output(name, input=name) <ide> <ide> def add_output(self, name, input=None, inputs=[], <del> merge_mode='concat', concat_axis=-1): <add> merge_mode='concat', concat_axis=-1, dot_axes=-1): <ide> if name in self.output_order: <ide> raise Exception('Duplicate output identifier: ' + name) <ide> if input: <ide> def add_output(self, name, input=None, inputs=[], <ide> if n not in self.nodes: <ide> raise Exception('Unknown identifier: ' + n) <ide> to_merge.append(self.nodes[n]) <del> merge = Merge(to_merge, mode=merge_mode, concat_axis=concat_axis) <add> merge = Merge(to_merge, mode=merge_mode, concat_axis=concat_axis, dot_axes=dot_axes) <ide> self.outputs[name] = merge <ide> <ide> self.output_order.append(name) <ide> self.output_config.append({'name': name, <ide> 'input': input, <ide> 'inputs': inputs, <ide> 'merge_mode': merge_mode, <del> 'concat_axis': concat_axis}) <add> 'concat_axis': concat_axis, <add> 'dot_axes': dot_axes}) <ide> <ide> def get_config(self): <ide> return {"name": self.__class__.__name__,
1
Ruby
Ruby
ignore cc script
e224006b4979c78c2966d7c1ef7df9b5f9dbc7d2
<ide><path>Library/Homebrew/test/bash_spec.rb <ide> next if path.directory? <ide> next if path.symlink? <ide> next unless path.executable? <add> next if path.basename.to_s == "cc" # `bash -n` tries to parse the Ruby part <ide> next unless path.read(12) == "#!/bin/bash\n" <ide> <ide> expect(path).to have_valid_bash_syntax
1
Text
Text
fix a typos in docs of networking guide
55b172401851a6338a325ef7930d50ace9efb067
<ide><path>docs/userguide/networking/dockernetworks.md <ide> docker0 Link encap:Ethernet HWaddr 02:42:47:bc:3a:eb <ide> RX bytes:1100 (1.1 KB) TX bytes:648 (648.0 B) <ide> ``` <ide> <del>The `none` network adds a container to a container-specific network stack. That container lacks a network interface. Attaching to such a container and looking at it's stack you see this: <add>The `none` network adds a container to a container-specific network stack. That container lacks a network interface. Attaching to such a container and looking at its stack you see this: <ide> <ide> ``` <ide> $ docker attach nonenetcontainer
1
Text
Text
fix descriptions of sync methods in fs.md
2d48f97ddda4fce9a03397c89ab5dc329280e9ed
<ide><path>doc/api/fs.md <ide> Synchronous readdir(3). <ide> <ide> The optional `options` argument can be a string specifying an encoding, or an <ide> object with an `encoding` property specifying the character encoding to use for <del>the filenames passed to the callback. If the `encoding` is set to `'buffer'`, <add>the filenames returned. If the `encoding` is set to `'buffer'`, <ide> the filenames returned will be passed as `Buffer` objects. <ide> <ide> ## fs.readFile(path[, options], callback) <ide> Synchronous readlink(2). Returns the symbolic link's string value. <ide> <ide> The optional `options` argument can be a string specifying an encoding, or an <ide> object with an `encoding` property specifying the character encoding to use for <del>the link path passed to the callback. If the `encoding` is set to `'buffer'`, <add>the link path returned. If the `encoding` is set to `'buffer'`, <ide> the link path returned will be passed as a `Buffer` object. <ide> <ide> ## fs.readSync(fd, buffer, offset, length, position) <ide> Only paths that can be converted to UTF8 strings are supported. <ide> <ide> The optional `options` argument can be a string specifying an encoding, or an <ide> object with an `encoding` property specifying the character encoding to use for <del>the path passed to the callback. If the `encoding` is set to `'buffer'`, <add>the path returned. If the `encoding` is set to `'buffer'`, <ide> the path returned will be passed as a `Buffer` object. <ide> <ide> On Linux, when Node.js is linked against musl libc, the procfs file system must
1
Ruby
Ruby
replace "overwrite" with "override" [ci-skip]
0d3effc97e3871a9ea49dfea06673f0b06f4821a
<ide><path>actioncable/lib/action_cable/channel/base.rb <ide> def subscribe_to_channel <ide> end <ide> <ide> # Called by the cable connection when it's cut, so the channel has a chance to cleanup with callbacks. <del> # This method is not intended to be called directly by the user. Instead, overwrite the #unsubscribed callback. <add> # This method is not intended to be called directly by the user. Instead, override the #unsubscribed callback. <ide> def unsubscribe_from_channel # :nodoc: <ide> run_callbacks :unsubscribe do <ide> unsubscribed <ide><path>actionmailbox/lib/action_mailbox/base.rb <ide> module ActionMailbox <ide> # routing :all => :backstop <ide> # end <ide> # <del> # Application mailboxes need to overwrite the +#process+ method, which is invoked by the framework after <add> # Application mailboxes need to override the +#process+ method, which is invoked by the framework after <ide> # callbacks have been run. The callbacks available are: +before_processing+, +after_processing+, and <ide> # +around_processing+. The primary use case is ensure certain preconditions to processing are fulfilled <ide> # using +before_processing+ callbacks. <ide> def perform_processing # :nodoc: <ide> end <ide> <ide> def process <del> # Overwrite in subclasses <add> # Override in subclasses <ide> end <ide> <ide> def finished_processing? # :nodoc: <ide><path>actionpack/lib/action_controller/metal/helpers.rb <ide> def helpers <ide> end <ide> end <ide> <del> # Overwrite modules_for_helpers to accept :all as argument, which loads <add> # Override modules_for_helpers to accept :all as argument, which loads <ide> # all helpers in helpers_path. <ide> # <ide> # ==== Parameters <ide><path>actionpack/lib/action_controller/metal/rendering.rb <ide> def render(*args) # :nodoc: <ide> super <ide> end <ide> <del> # Overwrite render_to_string because body can now be set to a Rack body. <add> # Override render_to_string because body can now be set to a Rack body. <ide> def render_to_string(*) <ide> result = super <ide> if result.respond_to?(:each) <ide><path>actionview/lib/action_view/helpers/rendering_helper.rb <ide> def render(options = {}, locals = {}, &block) <ide> end <ide> end <ide> <del> # Overwrites _layout_for in the context object so it supports the case a block is <add> # Overrides _layout_for in the context object so it supports the case a block is <ide> # passed to a partial. Returns the contents that are yielded to a layout, given a <ide> # name or a block. <ide> # <ide><path>actionview/lib/action_view/record_identifier.rb <ide> def dom_id(record, prefix = nil) <ide> # on the default implementation (which just joins all key attributes with '_') or on your own <ide> # overwritten version of the method. By default, this implementation passes the key string through a <ide> # method that replaces all characters that are invalid inside DOM ids, with valid ones. You need to <del> # make sure yourself that your dom ids are valid, in case you overwrite this method. <add> # make sure yourself that your dom ids are valid, in case you override this method. <ide> def record_key_for_dom_id(record) # :doc: <ide> key = convert_to_model(record).to_key <ide> key ? key.join(JOIN) : key <ide><path>actionview/lib/action_view/rendering.rb <ide> def initialize <ide> super <ide> end <ide> <del> # Overwrite process to set up I18n proxy. <add> # Override process to set up I18n proxy. <ide> def process(*) # :nodoc: <ide> old_config, I18n.config = I18n.config, I18nProxy.new(I18n.config, lookup_context) <ide> super <ide><path>activemodel/lib/active_model/translation.rb <ide> module ActiveModel <ide> module Translation <ide> include ActiveModel::Naming <ide> <del> # Returns the +i18n_scope+ for the class. Overwrite if you want custom lookup. <add> # Returns the +i18n_scope+ for the class. Override if you want custom lookup. <ide> def i18n_scope <ide> :activemodel <ide> end <ide><path>activemodel/lib/active_model/validations/callbacks.rb <ide> def set_options_for_callback(options) <ide> end <ide> <ide> private <del> # Overwrite run_validations! to include callbacks. <add> # Override run_validations! to include callbacks. <ide> def run_validations! <ide> _run_validation_callbacks { super } <ide> end <ide><path>activerecord/lib/active_record/attribute_methods.rb <ide> def instance_method_already_implemented?(method_name) <ide> super <ide> else <ide> # If ThisClass < ... < SomeSuperClass < ... < Base and SomeSuperClass <del> # defines its own attribute method, then we don't want to overwrite that. <add> # defines its own attribute method, then we don't want to override that. <ide> defined = method_defined_within?(method_name, superclass, Base) && <ide> ! superclass.instance_method(method_name).owner.is_a?(GeneratedAttributeMethods) <ide> defined || super <ide><path>activerecord/lib/active_record/base.rb <ide> module ActiveRecord # :nodoc: <ide> # anonymous = User.new(name: "") <ide> # anonymous.name? # => false <ide> # <del> # Query methods will also respect any overwrites of default accessors: <add> # Query methods will also respect any overrides of default accessors: <ide> # <ide> # class User <ide> # # Has admin boolean column <ide> module ActiveRecord # :nodoc: <ide> # user.read_attribute(:admin) # => true, gets the column value <ide> # user[:admin] # => true, also gets the column value <ide> # <del> # user.admin # => false, due to the getter overwrite <del> # user.admin? # => false, due to the getter overwrite <add> # user.admin # => false, due to the getter override <add> # user.admin? # => false, due to the getter override <ide> # <ide> # == Accessing attributes before they have been typecasted <ide> # <ide><path>activerecord/lib/active_record/core.rb <ide> def inspect # :nodoc: <ide> end <ide> end <ide> <del> # Overwrite the default class equality method to provide support for decorated models. <add> # Override the default class equality method to provide support for decorated models. <ide> def ===(object) # :nodoc: <ide> object.is_a?(self) <ide> end <ide><path>activerecord/lib/active_record/translation.rb <ide> def lookup_ancestors # :nodoc: <ide> classes <ide> end <ide> <del> # Set the i18n scope to overwrite ActiveModel. <add> # Set the i18n scope to override ActiveModel. <ide> def i18n_scope # :nodoc: <ide> :activerecord <ide> end <ide><path>activesupport/lib/active_support/core_ext/hash/indifferent_access.rb <ide> def with_indifferent_access <ide> # Called when object is nested under an object that receives <ide> # #with_indifferent_access. This method will be called on the current object <ide> # by the enclosing object and is aliased to #with_indifferent_access by <del> # default. Subclasses of Hash may overwrite this method to return +self+ if <add> # default. Subclasses of Hash may override this method to return +self+ if <ide> # converting to an <tt>ActiveSupport::HashWithIndifferentAccess</tt> would not be <ide> # desirable. <ide> # <ide><path>activesupport/lib/active_support/core_ext/object/json.rb <ide> # frozen_string_literal: true <ide> <del># Hack to load json gem first so we can overwrite its to_json. <add># Hack to load json gem first so we can override its to_json. <ide> require "json" <ide> require "bigdecimal" <ide> require "ipaddr"
15
Text
Text
add initial documentation of rntesterplatformtest
fba485af837a48b53c584cca99ae7a230239628f
<ide><path>packages/rn-tester/js/examples/Experimental/PlatformTest/README.md <add># RNTester PlatformTest <add> <add>A barebones manual testing framework designed to work as a mechanism for recreating [Web Platform Tests](https://github.com/web-platform-tests/wpt) in React Native in order to verify their compliance with W3C specifications. <add> <add>## Usage <add> <add>Any new test case will start as a new React component which at the very least accepts a `harness` prop which will contain all of the framework's testing APIs. This component you write will be passed into the `component` prop of a `RNTesterPlatformTest` element whose other props are used for documenting your test. Rendering this `RNTesterPlatformTest` will look similar to something like this: <add> <add>```js <add>function ExampleTestCase ({ harness }) { /* ... */ } <add> <add><RNTesterPlatformTest <add> title="Example Test" <add> description="Imagine there's a detailed description of this example test here" <add> instructions={[ <add> "This is the example test's first step", <add> "A second step", <add> "A third step", <add> ]} <add> component={ExampleTestCase} <add>/> <add>``` <add> <add> <add>As of writting this README there are 2 different types of tests that the `harness` prop provides: <add> <add>### `test(testcase: (TestContext) => void, testName: string)` <add> <add>This is a method to create "regular" test reminicent of other frameworks such as Jest. These are meant to be run imperatively, and while that means that they technically could work in a `useEffect` hook as a way to run the test "on mount" — it is instead recommended to try and keep these tests in callbacks instead. A good alternative to running the test on mount would be to instead put the test in a callback and render a "Start Test" button which executes the callback. <add> <add>The first argument is the closure in which you will run your test and make assertions. The assertions are contained in the `TestContext` object which is provided in the test closure's first argument and contains the following assertions: <add> <add>* `assert_true(a: boolean, description: string): void` <add>* `assert_equals(a: any, b: any, description: string): void` <add>* `assert_greater_than_equal(a: number, b: number, description: string): void` <add>* `assert_less_than_equal(a: number, b: number, description: string): void` <add> <add>Here's what a basic/contrived example which verifies the layout of a basic view: <add> <add>```js <add>const EXPECTED_WIDTH = 100; <add>const EXPECTED_HEIGHT = 200; <add> <add>function BasicLayoutTestCase({harness}) { <add> const viewRef = useRef(null); <add> <add> const runTest = useCallback(() => { <add> const view = viewRef.current; <add> if (view != null) { <add> view.measureInWindow(({width, height}) => { <add> harness.test(({assert_equals}) => { <add> assert_equals( <add> width, <add> EXPECTED_WIDTH, <add> `view's computed width should be ${EXPECTED_WIDTH}`, <add> ); <add> assert_equals( <add> height, <add> EXPECTED_HEIGHT, <add> `view's computed width should be ${EXPECTED_HEIGHT}`, <add> ); <add> }, "view's width and height are correct"); <add> }); <add> } <add> }, [harness]); <add> <add> return ( <add> <> <add> <View <add> ref={viewRef} <add> style={{width: EXPECTED_WIDTH, height: EXPECTED_HEIGHT}} <add> /> <add> <Button title="Start Test" onPress={runTest} /> <add> </> <add> ); <add>} <add>``` <add> <add>### `useAsyncTest(description: string, timeoutMs?: number): AsyncPlatformTest` <add> <add>This is a hook which can be used to represent tests that expect something to happen *some time* in the future. If the test isn't marked as "done" within a certain amount of time (10 seconds by default but can be optionally specified in the hook's second argument). This hook returns an object containing a `done` function which is used for marking the completion of the async test. <add> <add>Here's what a basic example would look like for verifying that `pointermove` events are emitted: <add> <add>```js <add>function BasicPointerMoveTestCase({harness}) { <add> const testPointerMove = harness.useAsyncTest('pointermove event recieved'); <add> <add> return ( <add> <View <add> style={{width: 100, height: 100, backgroundColor: 'black'}} <add> onPointerMove={() => testPointerMove.done()} <add> /> <add> ); <add>} <add>```
1
Python
Python
remove duplicated lines in example code
236c3ebed52f9eb224657206d7aebfc1c1478f72
<ide><path>examples/cifar10_resnet.py <ide> (x_train, y_train), (x_test, y_test) = cifar10.load_data() <ide> <ide> # Input image dimensions. <del># We assume data format "channels_last". <del>img_rows = x_train.shape[1] <del>img_cols = x_train.shape[2] <del>channels = x_train.shape[3] <del> <ide> if K.image_data_format() == 'channels_first': <ide> img_rows = x_train.shape[2] <ide> img_cols = x_train.shape[3]
1
Mixed
Javascript
add setter for module.parent
aaf225a2a0175178f3b55add5f20f16bdb8ef01c
<ide><path>doc/api/modules.md <ide> deprecated: <ide> <ide> The module that first required this one, or `null` if the current module is the <ide> entry point of the current process, or `undefined` if the module was loaded by <del>something that is not a CommonJS module (E.G.: REPL or `import`). Read only. <add>something that is not a CommonJS module (E.G.: REPL or `import`). <ide> <ide> ### `module.path` <ide> <!-- YAML <ide><path>lib/internal/modules/cjs/loader.js <ide> ObjectDefineProperty(Module, 'wrapper', { <ide> function getModuleParent() { <ide> return moduleParentCache.get(this); <ide> } <add> <add>function setModuleParent(value) { <add> moduleParentCache.set(this, value); <add>} <add> <ide> ObjectDefineProperty(Module.prototype, 'parent', { <ide> get: pendingDeprecation ? deprecate( <ide> getModuleParent, <ide> 'module.parent is deprecated due to accuracy issues. Please use ' + <ide> 'require.main to find program entry point instead.', <ide> 'DEP0144' <del> ) : getModuleParent <add> ) : getModuleParent, <add> set: pendingDeprecation ? deprecate( <add> setModuleParent, <add> 'module.parent is deprecated due to accuracy issues. Please use ' + <add> 'require.main to find program entry point instead.', <add> 'DEP0144' <add> ) : setModuleParent, <ide> }); <ide> <ide> let debug = require('internal/util/debuglog').debuglog('module', (fn) => { <ide><path>test/parallel/test-module-parent-setter-deprecation.js <add>// Flags: --pending-deprecation <add> <add>'use strict'; <add>const common = require('../common'); <add> <add>common.expectWarning( <add> 'DeprecationWarning', <add> 'module.parent is deprecated due to accuracy issues. Please use ' + <add> 'require.main to find program entry point instead.', <add> 'DEP0144' <add>); <add> <add>module.parent = undefined;
3
Python
Python
add new map_index field to log message
cfd6ca6d425e26288bc5d8db59fd886896e9885c
<ide><path>airflow/jobs/scheduler_job.py <ide> def _process_executor_events(self, session: Session = None) -> int: <ide> continue <ide> <ide> msg = ( <del> "TaskInstance Finished: dag_id=%s, task_id=%s, run_id=%s, " <add> "TaskInstance Finished: dag_id=%s, task_id=%s, run_id=%s, map_index=%s, " <ide> "run_start_date=%s, run_end_date=%s, " <ide> "run_duration=%s, state=%s, executor_state=%s, try_number=%s, max_tries=%s, job_id=%s, " <ide> "pool=%s, queue=%s, priority_weight=%d, operator=%s" <ide> def _process_executor_events(self, session: Session = None) -> int: <ide> ti.dag_id, <ide> ti.task_id, <ide> ti.run_id, <add> ti.map_index, <ide> ti.start_date, <ide> ti.end_date, <ide> ti.duration,
1
PHP
PHP
add tests to filesystemadapter
4ab34a2b39d47053816c757c331b8100764cdbd8
<ide><path>tests/Filesystem/FilesystemAdapterTest.php <ide> use League\Flysystem\Adapter\Local; <ide> use Illuminate\Filesystem\FilesystemAdapter; <ide> use Symfony\Component\HttpFoundation\StreamedResponse; <add>use Illuminate\Contracts\Filesystem\FileNotFoundException; <ide> <ide> class FilesystemAdapterTest extends TestCase <ide> { <ide> private $filesystem; <ide> <ide> public function setUp() <ide> { <del> $this->filesystem = new Filesystem(new Local(__DIR__.'/tmp')); <add> $this->tempDir = __DIR__.'/tmp'; <add> $this->filesystem = new Filesystem(new Local($this->tempDir)); <ide> } <ide> <ide> public function tearDown() <ide> { <del> $filesystem = new Filesystem(new Local(__DIR__)); <del> $filesystem->deleteDir('tmp'); <add> $filesystem = new Filesystem(new Local(dirname($this->tempDir))); <add> $filesystem->deleteDir(basename($this->tempDir)); <ide> } <ide> <ide> public function testResponse() <ide> public function testDownload() <ide> $this->assertInstanceOf(StreamedResponse::class, $response); <ide> $this->assertEquals('attachment; filename="hello.txt"', $response->headers->get('content-disposition')); <ide> } <add> <add> public function testExists() <add> { <add> $this->filesystem->write('file.txt', 'Hello World'); <add> $filesystemAdapter = new FilesystemAdapter($this->filesystem); <add> $this->assertTrue($filesystemAdapter->exists('file.txt')); <add> } <add> <add> public function testPath() <add> { <add> $this->filesystem->write('file.txt', 'Hello World'); <add> $filesystemAdapter = new FilesystemAdapter($this->filesystem); <add> $this->assertEquals($this->tempDir.'/file.txt', $filesystemAdapter->path('file.txt')); <add> } <add> <add> public function testGet() <add> { <add> $this->filesystem->write('file.txt', 'Hello World'); <add> $filesystemAdapter = new FilesystemAdapter($this->filesystem); <add> $this->assertEquals('Hello World', $filesystemAdapter->get('file.txt')); <add> } <add> <add> public function testGetFileNotFound() <add> { <add> $filesystemAdapter = new FilesystemAdapter($this->filesystem); <add> $this->expectException(FileNotFoundException::class); <add> $filesystemAdapter->get('file.txt'); <add> } <add> <add> public function testPut() <add> { <add> $filesystemAdapter = new FilesystemAdapter($this->filesystem); <add> $filesystemAdapter->put('file.txt', 'Something inside'); <add> $this->assertStringEqualsFile($this->tempDir.'/file.txt', 'Something inside'); <add> } <add> <add> public function testPrepend() <add> { <add> file_put_contents($this->tempDir.'/file.txt', 'World'); <add> $filesystemAdapter = new FilesystemAdapter($this->filesystem); <add> $filesystemAdapter->prepend('file.txt', 'Hello '); <add> $this->assertStringEqualsFile($this->tempDir.'/file.txt', "Hello \nWorld"); <add> } <add> <add> public function testAppend() <add> { <add> file_put_contents($this->tempDir.'/file.txt', 'Hello '); <add> $filesystemAdapter = new FilesystemAdapter($this->filesystem); <add> $filesystemAdapter->append('file.txt', 'Moon'); <add> $this->assertStringEqualsFile($this->tempDir.'/file.txt', "Hello \nMoon"); <add> } <ide> }
1
Mixed
Javascript
add readme page in tests and fix typos
a666176d52bcc7e551a1ead756d8bb64381c3715
<ide><path>test/diff/README.md <add># Three.js automatic regression testing with CI <add> <add>You probably shouldn't run this tests on PC because right now it's not optimized for local usage and you can get different results on different GPUs. Goal is to make quick automated testing inside CI and keep screenshot pack updated for it. <add> <add>### Local usage <add>```shell <add># generate new screenshots <add>npm run make-screenshot <example1_name> ... <exampleN_name> <add> <add># check examples <add>npm run test-diff <example1_name> ... <exampleN_name> <add> <add># check all examples in browser <add>npx cross-env VISIBLE=ture npm run test-diff <add>``` <add> <add>### How it works <add>- ci configs with parallelism <add>- deterministic random/timer/rAF/video for screenshots <add>- increased robustness with hided text, datgui, different flags and timeouts. <add>- pipeline: turn off rAF -> 'networkidle0' -> networkTax -> turn on rAF -> render promise <add>- added 3 progressive attempts for robustness <add> <add>### Status <add>97% examples are covered with tests. Random robusness in CI ~85%. Robustness on different machines ~97%. For example in Windows webgl_effects_ascii example always fails or on integrated GPU you will have additional artifacts: webgl_materials_texture_anisotropy, webgl_postprocessing_procedural, webgl_shaders_tonemapping. <add> <add>### Probably wrong screenshots <add>webgl2_multisampled_renderbuffers, webgl_simple_gi, webgl_postprocessing_dof2, webgl_loader_texture_pvrtc <add> <add>### Contribution <add>You can help to simplify puppeteer script by suggesting example with [HeadlessExperimental.beginFrame](https://chromedevtools.github.io/devtools-protocol/tot/HeadlessExperimental) CDP API. <ide><path>test/diff/puppeteer.js <ide> const port = 1234; <ide> const pixelThreshold = 0.2; <ide> const maxFailedPixels = 0.05; <ide> const networkTimeout = 600; <del>const networkTax = 2000; // additional timout tax for resources size <add>const networkTax = 2000; // additional timeout for resources size <ide> const pageSizeMinTax = 1.0; // in mb, when networkTax = 0 <ide> const pageSizeMaxTax = 5.0; // in mb, when networkTax = networkTax <ide> const renderTimeout = 1200; <ide> const maxAttemptId = 3; // progresseve attempts <ide> const exceptionList = [ <ide> <ide> 'index', <del> 'webgl_loader_texture_pvrtc', // not supported in CI, usless <add> 'webgl_loader_texture_pvrtc', // not supported in CI, useless <ide> 'webgl_materials_envmaps_parallax', <ide> 'webgl_test_memory2', // gives fatal error in puppeteer <ide> 'webgl_worker_offscreencanvas', // in a worker, not robust <ide> <ide> ].concat( ( process.platform === "win32" ) ? [ <ide> <del> 'webgl_effects_ascii' // windows fonts <add> 'webgl_effects_ascii' // windows fonts not supported <ide> <ide> ] : [] ); <ide>
2
Javascript
Javascript
add ist & npt test for time.hours
4ee4398d6f6affcc670829de50163ebf9f03b177
<ide><path>test/time/hours-test.js <ide> suite.addBatch({ <ide> utc(2011, 10, 6, 9) <ide> ]); <ide> }, <del> "utc": { <add> "NPT": { <add> "observes 15-minute offset": tz("Asia/Kathmandu", function(range) { <add> assert.deepEqual(range(local(2011, 10, 7, 0), local(2011, 10, 7, 3)), [ <add> utc(2011, 10, 6, 18, 15), <add> utc(2011, 10, 6, 19, 15), <add> utc(2011, 10, 6, 20, 15) <add> ]); <add> }) <add> }, <add> "IST": { <add> "observes 30-minute offset": tz("Asia/Calcutta", function(range) { <add> assert.deepEqual(range(local(2011, 10, 7, 0), local(2011, 10, 7, 3)), [ <add> utc(2011, 10, 6, 18, 30), <add> utc(2011, 10, 6, 19, 30), <add> utc(2011, 10, 6, 20, 30) <add> ]); <add> }) <add> }, <add> "UTC": { <ide> topic: function(range) { <ide> return range.utc; <ide> }, <ide> function utc(year, month, day, hours, minutes, seconds) { <ide> return new Date(Date.UTC(year, month, day, hours || 0, minutes || 0, seconds || 0)); <ide> } <ide> <add>function tz(tz, scope) { <add> return function() { <add> var o = process.env.TZ; <add> try { <add> process.env.TZ = tz; <add> new Date(0).toString(); // invalidate node's dst cache <add> new Date().toString(); <add> scope.apply(this, arguments); <add> } finally { <add> process.env.TZ = o; <add> new Date(0).toString(); // invalidate node's dst cache <add> new Date().toString(); <add> } <add> }; <add>} <add> <ide> suite.export(module);
1
Javascript
Javascript
socket timeout for global cache
e2a5bc1a3557c3b6bc5121bdeca0ddbbfbc868bb
<ide><path>packager/react-packager/src/lib/GlobalTransformCache.js <ide> class GlobalTransformCache { <ide> * megabytes each. <ide> */ <ide> _fetchFromURI(uri: string, callback: FetchCallback) { <del> request.get({uri, json: true}, (error, response, unvalidatedResult) => { <add> request.get({uri, json: true, timeout: 4000}, (error, response, unvalidatedResult) => { <ide> if (error != null) { <ide> callback(error); <ide> return;
1
Text
Text
remove bold style from command examples
84da1699490c08ee3de636956a446b7f9194f76b
<ide><path>README.md <ide> Make sure you have `grunt` installed by testing: <ide> <ide> Then, to get a complete, minified (w/ Uglify.js), linted (w/ JSHint) version of jQuery, type the following: <ide> <del>#### `grunt` #### <add>`grunt` <ide> <ide> <ide> The built version of jQuery will be put in the `dist/` subdirectory. <ide> To create a custom build, use the following special `grunt` commands: <ide> <ide> Exclude `dimensions`: <ide> <del>#### `grunt build:*:*:-dimensions` #### <add>`grunt build:*:*:-dimensions` <ide> <ide> Exclude `effects`: <ide> <del>#### `grunt build:*:*:-effects` #### <add>`grunt build:*:*:-effects` <ide> <ide> Exclude `offset`: <ide> <del>#### `grunt build:*:*:-offset` #### <add>`grunt build:*:*:-offset` <ide> <ide> <ide> Exclude **all** optional modules: <ide> <del>#### `grunt build:*:*:-dimensions:-effects:-offset` #### <add>`grunt build:*:*:-dimensions:-effects:-offset` <ide> <ide> <ide> <ide> Running the Unit Tests <ide> <ide> Start grunt to auto-build jQuery as you work: <ide> <del>#### `cd jquery && grunt watch` #### <add>`cd jquery && grunt watch` <ide> <ide> <ide> <ide> Building to a different directory <ide> <ide> If you want to build jQuery to a directory that is different from the default location: <ide> <del>#### `grunt && grunt dist:/path/to/special/location/` #### <add>`grunt && grunt dist:/path/to/special/location/` <ide> <ide> With this example, the output files would be: <ide> <ide> Updating Submodules <ide> <ide> Update the submodules to what is probably the latest upstream code. <ide> <del>#### `grunt submodules` #### <add>`grunt submodules` <ide> <ide> <ide> Note: This task will also be run any time the default `grunt` command is used.
1
Python
Python
update the typing tests
6345920701a16c83a561f45edd7caf701a130a4d
<ide><path>numpy/typing/tests/data/fail/constants.py <ide> np.Inf = np.Inf # E: Cannot assign to final <ide> np.ALLOW_THREADS = np.ALLOW_THREADS # E: Cannot assign to final <ide> np.little_endian = np.little_endian # E: Cannot assign to final <del>np.UFUNC_PYVALS_NAME = np.UFUNC_PYVALS_NAME # E: Cannot assign to final <add>np.UFUNC_PYVALS_NAME = "bob" # E: Incompatible types <ide> np.CLIP = 2 # E: Incompatible types <ide><path>numpy/typing/tests/data/reveal/constants.py <ide> reveal_type(np.ALLOW_THREADS) # E: int <ide> reveal_type(np.BUFSIZE) # E: Literal[8192] <ide> reveal_type(np.CLIP) # E: Literal[0] <del>reveal_type(np.ERR_CALL) # E: int <del>reveal_type(np.ERR_DEFAULT) # E: int <del>reveal_type(np.ERR_IGNORE) # E: int <del>reveal_type(np.ERR_LOG) # E: int <del>reveal_type(np.ERR_PRINT) # E: int <del>reveal_type(np.ERR_RAISE) # E: int <del>reveal_type(np.ERR_WARN) # E: int <del>reveal_type(np.FLOATING_POINT_SUPPORT) # E: int <del>reveal_type(np.FPE_DIVIDEBYZERO) # E: int <del>reveal_type(np.FPE_INVALID) # E: int <del>reveal_type(np.FPE_OVERFLOW) # E: int <del>reveal_type(np.FPE_UNDERFLOW) # E: int <add>reveal_type(np.ERR_CALL) # E: Literal[3] <add>reveal_type(np.ERR_DEFAULT) # E: Literal[521] <add>reveal_type(np.ERR_IGNORE) # E: Literal[0] <add>reveal_type(np.ERR_LOG) # E: Literal[5] <add>reveal_type(np.ERR_PRINT) # E: Literal[4] <add>reveal_type(np.ERR_RAISE) # E: Literal[2] <add>reveal_type(np.ERR_WARN) # E: Literal[1] <add>reveal_type(np.FLOATING_POINT_SUPPORT) # E: Literal[1] <add>reveal_type(np.FPE_DIVIDEBYZERO) # E: Literal[1] <add>reveal_type(np.FPE_INVALID) # E: Literal[8] <add>reveal_type(np.FPE_OVERFLOW) # E: Literal[2] <add>reveal_type(np.FPE_UNDERFLOW) # E: Literal[4] <ide> reveal_type(np.MAXDIMS) # E: Literal[32] <ide> reveal_type(np.MAY_SHARE_BOUNDS) # E: Literal[0] <ide> reveal_type(np.MAY_SHARE_EXACT) # E: Literal[-1] <ide> reveal_type(np.RAISE) # E: Literal[2] <del>reveal_type(np.SHIFT_DIVIDEBYZERO) # E: int <del>reveal_type(np.SHIFT_INVALID) # E: int <del>reveal_type(np.SHIFT_OVERFLOW) # E: int <del>reveal_type(np.SHIFT_UNDERFLOW) # E: int <del>reveal_type(np.UFUNC_BUFSIZE_DEFAULT) # E: int <add>reveal_type(np.SHIFT_DIVIDEBYZERO) # E: Literal[0] <add>reveal_type(np.SHIFT_INVALID) # E: Literal[9] <add>reveal_type(np.SHIFT_OVERFLOW) # E: Literal[3] <add>reveal_type(np.SHIFT_UNDERFLOW) # E: Literal[6] <add>reveal_type(np.UFUNC_BUFSIZE_DEFAULT) # E: Literal[8192] <ide> reveal_type(np.WRAP) # E: Literal[1] <ide> reveal_type(np.tracemalloc_domain) # E: Literal[389047] <ide> <ide> reveal_type(np.little_endian) # E: bool <ide> reveal_type(np.True_) # E: numpy.bool_ <ide> reveal_type(np.False_) # E: numpy.bool_ <ide> <del>reveal_type(np.UFUNC_PYVALS_NAME) # E: str <add>reveal_type(np.UFUNC_PYVALS_NAME) # E: Literal['UFUNC_PYVALS'] <ide> <ide> reveal_type(np.sctypeDict) # E: dict <ide> reveal_type(np.sctypes) # E: TypedDict
2
Python
Python
remove length cap on sentences
de13fe030548acf86e759e2c16c85712ab8e30bb
<ide><path>spacy/cli/train.py <ide> def train(_, lang, output_dir, train_data, dev_data, n_iter=20, n_sents=0, <ide> <ide> optimizer = nlp.begin_training(lambda: corpus.train_tuples, use_gpu=use_gpu) <ide> <del> print("Itn.\tDep. Loss\tUAS\tNER P.\tNER R.\tNER F.\tTag %\tToken %") <add> print("Itn.\tLoss\tUAS\tNER P.\tNER R.\tNER F.\tTag %\tToken %") <ide> try: <ide> for i in range(n_iter): <ide> with tqdm.tqdm(total=corpus.count_train(), leave=False) as pbar: <ide> train_docs = corpus.train_docs(nlp, projectivize=True, <del> gold_preproc=False, max_length=1000) <add> gold_preproc=False, max_length=0) <ide> losses = {} <ide> for batch in minibatch(train_docs, size=batch_sizes): <ide> docs, golds = zip(*batch)
1
Go
Go
fix id -> id api
54072dbbd6260a9d8a7249cae0bd17513f15c3fc
<ide><path>commands.go <ide> func (cli *DockerCli) CmdHistory(args ...string) error { <ide> } <ide> <ide> for _, out := range outs.Data { <del> outID := out.Get("ID") <add> outID := out.Get("Id") <ide> if !*quiet { <ide> if *noTrunc { <ide> fmt.Fprintf(w, "%s\t", outID) <ide> func (cli *DockerCli) CmdImages(args ...string) error { <ide> } <ide> <ide> if filter != "" { <del> if filter == image.Get("ID") || filter == utils.TruncateID(image.Get("ID")) { <add> if filter == image.Get("Id") || filter == utils.TruncateID(image.Get("Id")) { <ide> startImage = image <ide> } <ide> <ide> func (cli *DockerCli) CmdImages(args ...string) error { <ide> for _, repotag := range out.GetList("RepoTags") { <ide> <ide> repo, tag := utils.ParseRepositoryTag(repotag) <del> outID := out.Get("ID") <add> outID := out.Get("Id") <ide> if !*noTrunc { <ide> outID = utils.TruncateID(outID) <ide> } <ide> func (cli *DockerCli) WalkTree(noTrunc bool, images *engine.Table, byParent map[ <ide> for index, image := range images.Data { <ide> if index+1 == length { <ide> printNode(cli, noTrunc, image, prefix+"└─") <del> if subimages, exists := byParent[image.Get("ID")]; exists { <add> if subimages, exists := byParent[image.Get("Id")]; exists { <ide> cli.WalkTree(noTrunc, subimages, byParent, prefix+" ", printNode) <ide> } <ide> } else { <ide> printNode(cli, noTrunc, image, prefix+"\u251C─") <del> if subimages, exists := byParent[image.Get("ID")]; exists { <add> if subimages, exists := byParent[image.Get("Id")]; exists { <ide> cli.WalkTree(noTrunc, subimages, byParent, prefix+"\u2502 ", printNode) <ide> } <ide> } <ide> } <ide> } else { <ide> for _, image := range images.Data { <ide> printNode(cli, noTrunc, image, prefix+"└─") <del> if subimages, exists := byParent[image.Get("ID")]; exists { <add> if subimages, exists := byParent[image.Get("Id")]; exists { <ide> cli.WalkTree(noTrunc, subimages, byParent, prefix+" ", printNode) <ide> } <ide> } <ide> func (cli *DockerCli) printVizNode(noTrunc bool, image *engine.Env, prefix strin <ide> parentID string <ide> ) <ide> if noTrunc { <del> imageID = image.Get("ID") <add> imageID = image.Get("Id") <ide> parentID = image.Get("ParentId") <ide> } else { <del> imageID = utils.TruncateID(image.Get("ID")) <add> imageID = utils.TruncateID(image.Get("Id")) <ide> parentID = utils.TruncateID(image.Get("ParentId")) <ide> } <ide> if parentID == "" { <ide> func (cli *DockerCli) printVizNode(noTrunc bool, image *engine.Env, prefix strin <ide> func (cli *DockerCli) printTreeNode(noTrunc bool, image *engine.Env, prefix string) { <ide> var imageID string <ide> if noTrunc { <del> imageID = image.Get("ID") <add> imageID = image.Get("Id") <ide> } else { <del> imageID = utils.TruncateID(image.Get("ID")) <add> imageID = utils.TruncateID(image.Get("Id")) <ide> } <ide> <ide> fmt.Fprintf(cli.out, "%s%s Virtual Size: %s", prefix, imageID, utils.HumanSize(image.GetInt64("VirtualSize"))) <ide> func (cli *DockerCli) CmdPs(args ...string) error { <ide> <ide> for _, out := range outs.Data { <ide> var ( <del> outID = out.Get("ID") <add> outID = out.Get("Id") <ide> outNames = out.GetList("Names") <ide> ) <ide> <ide><path>integration/api_test.go <ide> func TestGetImagesJSON(t *testing.T) { <ide> } <ide> assertHttpNotError(r2, t) <ide> <del> images2 := engine.NewTable("ID", 0) <add> images2 := engine.NewTable("Id", 0) <ide> if _, err := images2.ReadListFrom(r2.Body.Bytes()); err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestGetImagesJSON(t *testing.T) { <ide> <ide> found = false <ide> for _, img := range images2.Data { <del> if img.Get("ID") == unitTestImageID { <add> if img.Get("Id") == unitTestImageID { <ide> found = true <ide> break <ide> } <ide> func TestGetImagesJSON(t *testing.T) { <ide> } <ide> assertHttpNotError(r3, t) <ide> <del> images3 := engine.NewTable("ID", 0) <add> images3 := engine.NewTable("Id", 0) <ide> if _, err := images3.ReadListFrom(r3.Body.Bytes()); err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestGetContainersJSON(t *testing.T) { <ide> if len(containers.Data) != beginLen+1 { <ide> t.Fatalf("Expected %d container, %d found (started with: %d)", beginLen+1, len(containers.Data), beginLen) <ide> } <del> if id := containers.Data[0].Get("ID"); id != containerID { <add> if id := containers.Data[0].Get("Id"); id != containerID { <ide> t.Fatalf("Container ID mismatch. Expected: %s, received: %s\n", containerID, id) <ide> } <ide> } <ide><path>integration/runtime_test.go <ide> func cleanup(eng *engine.Engine, t *testing.T) error { <ide> t.Fatal(err) <ide> } <ide> for _, image := range images.Data { <del> if image.Get("ID") != unitTestImageID { <del> mkServerFromEngine(eng, t).DeleteImage(image.Get("ID"), false) <add> if image.Get("Id") != unitTestImageID { <add> mkServerFromEngine(eng, t).DeleteImage(image.Get("Id"), false) <ide> } <ide> } <ide> return nil <ide><path>integration/server_test.go <ide> func TestRestartKillWait(t *testing.T) { <ide> } <ide> <ide> setTimeout(t, "Waiting on stopped container timedout", 5*time.Second, func() { <del> job = srv.Eng.Job("wait", outs.Data[0].Get("ID")) <add> job = srv.Eng.Job("wait", outs.Data[0].Get("Id")) <ide> var statusStr string <ide> job.Stdout.AddString(&statusStr) <ide> if err := job.Run(); err != nil { <ide> func TestRmi(t *testing.T) { <ide> } <ide> <ide> for _, image := range images.Data { <del> if strings.Contains(unitTestImageID, image.Get("ID")) { <add> if strings.Contains(unitTestImageID, image.Get("Id")) { <ide> continue <ide> } <ide> if image.GetList("RepoTags")[0] == "<none>:<none>" { <ide> func assertContainerList(srv *docker.Server, all bool, limit int, since, before <ide> return false <ide> } <ide> for i := 0; i < len(outs.Data); i++ { <del> if outs.Data[i].Get("ID") != expected[i] { <add> if outs.Data[i].Get("Id") != expected[i] { <ide> return false <ide> } <ide> } <ide><path>server.go <ide> func (srv *Server) Images(job *engine.Job) engine.Status { <ide> delete(allImages, id) <ide> out.Set("ParentId", image.Parent) <ide> out.SetList("RepoTags", []string{fmt.Sprintf("%s:%s", name, tag)}) <del> out.Set("ID", image.ID) <add> out.Set("Id", image.ID) <ide> out.SetInt64("Created", image.Created.Unix()) <ide> out.SetInt64("Size", image.Size) <ide> out.SetInt64("VirtualSize", image.getParentsSize(0)+image.Size) <ide> func (srv *Server) Images(job *engine.Job) engine.Status { <ide> out := &engine.Env{} <ide> out.Set("ParentId", image.Parent) <ide> out.SetList("RepoTags", []string{"<none>:<none>"}) <del> out.Set("ID", image.ID) <add> out.Set("Id", image.ID) <ide> out.SetInt64("Created", image.Created.Unix()) <ide> out.SetInt64("Size", image.Size) <ide> out.SetInt64("VirtualSize", image.getParentsSize(0)+image.Size) <ide> func (srv *Server) ImageHistory(job *engine.Job) engine.Status { <ide> outs := engine.NewTable("Created", 0) <ide> err = image.WalkHistory(func(img *Image) error { <ide> out := &engine.Env{} <del> out.Set("ID", img.ID) <add> out.Set("Id", img.ID) <ide> out.SetInt64("Created", img.Created.Unix()) <ide> out.Set("CreatedBy", strings.Join(img.ContainerConfig.Cmd, " ")) <ide> out.SetList("Tags", lookupMap[img.ID]) <ide> func (srv *Server) Containers(job *engine.Job) engine.Status { <ide> } <ide> displayed++ <ide> out := &engine.Env{} <del> out.Set("ID", container.ID) <add> out.Set("Id", container.ID) <ide> out.SetList("Names", names[container.ID]) <ide> out.Set("Image", srv.runtime.repositories.ImageName(container.Image)) <ide> out.Set("Command", fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " ")))
5
Java
Java
add perftest dev support manager
f0b7cbe22e2d67c102149d6d118b563b71a7fbb5
<ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DefaultDevSupportManagerFactory.java <ide> public DevSupportManager create( <ide> if (!enableOnCreate) { <ide> return new DisabledDevSupportManager(); <ide> } <add> // Developer support is enabled, we now must choose whether to return a DevSupportManager, <add> // or a more lean profiling-only PerftestDevSupportManager. We make the choice by first <add> // trying to return the full support DevSupportManager and if it fails, then just <add> // return PerftestDevSupportManager. <ide> try { <ide> // ProGuard is surprisingly smart in this case and will keep a class if it detects a call to <ide> // Class.forName() with a static string. So instead we generate a quasi-dynamic string to <ide> public DevSupportManager create( <ide> customPackagerCommandHandlers, <ide> surfaceDelegateFactory); <ide> } catch (Exception e) { <del> throw new RuntimeException( <del> "Requested enabled DevSupportManager, but BridgeDevSupportManager class was not found" <del> + " or could not be created", <del> e); <add> return new PerftestDevSupportManager(applicationContext); <ide> } <ide> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/PerftestDevSupportManager.java <add>/* <add> * Copyright (c) Meta Platforms, Inc. and affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> */ <add> <add>package com.facebook.react.devsupport; <add> <add>import android.content.Context; <add> <add>/** <add> * Interface for accessing and interacting with development features related to performance testing. <add> * Communication is enabled via the Inspector, but everything else is disabled. <add> */ <add>public final class PerftestDevSupportManager extends DisabledDevSupportManager { <add> private final DevServerHelper mDevServerHelper; <add> private final DevInternalSettings mDevSettings; <add> private final InspectorPackagerConnection.BundleStatus mBundleStatus; <add> <add> public PerftestDevSupportManager(Context applicationContext) { <add> mDevSettings = <add> new DevInternalSettings( <add> applicationContext, <add> new DevInternalSettings.Listener() { <add> @Override <add> public void onInternalSettingsChanged() {} <add> }); <add> mBundleStatus = new InspectorPackagerConnection.BundleStatus(); <add> mDevServerHelper = <add> new DevServerHelper( <add> mDevSettings, <add> applicationContext.getPackageName(), <add> new InspectorPackagerConnection.BundleStatusProvider() { <add> @Override <add> public InspectorPackagerConnection.BundleStatus getBundleStatus() { <add> return mBundleStatus; <add> } <add> }); <add> } <add> <add> @Override <add> public DevInternalSettings getDevSettings() { <add> return mDevSettings; <add> } <add> <add> @Override <add> public void startInspector() { <add> mDevServerHelper.openInspectorConnection(); <add> } <add> <add> @Override <add> public void stopInspector() { <add> mDevServerHelper.closeInspectorConnection(); <add> } <add>}
2
Text
Text
update 4mb api routes warning error guide.
c480726da2ed8385a792e2155fa09282436bfa3c
<ide><path>errors/api-routes-response-size-limit.md <ide> <ide> #### Why This Error Occurred <ide> <del>API Routes are meant to respond quickly and are not intended to support responding with large amounts of data. The maximum size of responses is 4 MB. <add>API Routes are meant to respond quickly and are not intended to support responding with large amounts of data. The maximum size of responses is 4MB. <ide> <ide> #### Possible Ways to Fix It <ide> <del>Limit your API Route responses to less than 4 MB. If you need to support sending large files to the client, you should consider using a dedicated media host for those assets. See link below for suggestions. <add>If you are not using Next.js in a serverless environment, and understand the performance implications of not using a CDN or dedicated media host, you can set this limit to `false` inside your API Route. <ide> <del>### Useful Links <add>```js <add>export const config = { <add> api: { <add> responseLimit: false, <add> }, <add>} <add>``` <ide> <del>[Tips to avoid the 5 MB limit](https://vercel.com/support/articles/how-to-bypass-vercel-5mb-body-size-limit-serverless-functions) <add>`responseLimit` can also take the number of bytes or any string format supported by `bytes`, for example `1000`, `'500kb'` or `'3mb'`. <add>This value will be the maximum response size before a warning is displayed. The default value is 4MB. <add> <add>```js <add>export const config = { <add> api: { <add> responseLimit: '8mb', <add> }, <add>} <add>```
1
Python
Python
add try-except for torch_scatter
ab7551cd7ff84cb5b7328bc37a06e06fa19f02bb
<ide><path>src/transformers/models/tapas/modeling_tapas.py <ide> from .configuration_tapas import TapasConfig <ide> <ide> <add>logger = logging.get_logger(__name__) <add> <ide> # soft dependency <ide> if is_scatter_available(): <del> from torch_scatter import scatter <del> <del>logger = logging.get_logger(__name__) <add> try: <add> from torch_scatter import scatter <add> except OSError: <add> logger.error( <add> "TAPAS models are not usable since `torch_scatter` can't be loaded." <add> "It seems you have `torch_scatter` installed with the wrong CUDA version." <add> "Please try to reinstall it following the instructions here: https://github.com/rusty1s/pytorch_scatter." <add> ) <ide> <ide> _CONFIG_FOR_DOC = "TapasConfig" <ide> _TOKENIZER_FOR_DOC = "TapasTokenizer"
1
PHP
PHP
update cipher tests
87b7fa721edd87c092916053f5f831ef619038e0
<ide><path>src/Illuminate/Encryption/Encrypter.php <ide> public function decrypt($payload, $unserialize = true) <ide> <ide> $tag = empty($payload['tag']) ? null : base64_decode($payload['tag']); <ide> <add> if (self::$supportedCiphers[$this->cipher]['aead'] && strlen($tag) !== 16) { <add> throw new DecryptException('Could not decrypt the data.'); <add> } <add> <ide> // Here we will decrypt the value. If we are able to successfully decrypt it <ide> // we will then unserialize it and return it out to the caller. If we are <ide> // unable to decrypt this value we will throw out an exception message. <ide><path>tests/Encryption/EncrypterTest.php <ide> public function testThatAnAeadCipherIncludesTag() <ide> $this->assertNotEmpty($data->tag); <ide> } <ide> <add> public function testThatAnAeadTagMustBeProvidedInFullLength() <add> { <add> $e = new Encrypter(str_repeat('b', 32), 'AES-256-GCM'); <add> $encrypted = $e->encrypt('foo'); <add> $data = json_decode(base64_decode($encrypted)); <add> <add> $this->expectException(DecryptException::class); <add> $this->expectExceptionMessage('Could not decrypt the data.'); <add> <add> $data->tag = substr($data->tag, 0, 4); <add> $encrypted = base64_encode(json_encode($data)); <add> $e->decrypt($encrypted); <add> } <add> <add> public function testThatAnAeadTagCantBeModified() <add> { <add> $e = new Encrypter(str_repeat('b', 32), 'AES-256-GCM'); <add> $encrypted = $e->encrypt('foo'); <add> $data = json_decode(base64_decode($encrypted)); <add> <add> $this->expectException(DecryptException::class); <add> $this->expectExceptionMessage('Could not decrypt the data.'); <add> <add> $data->tag = 'A'.substr($data->tag, 1, 23); <add> $encrypted = base64_encode(json_encode($data)); <add> $e->decrypt($encrypted); <add> } <add> <ide> public function testThatANonAeadCipherIncludesMac() <ide> { <ide> $e = new Encrypter(str_repeat('b', 32), 'AES-256-CBC');
2
Ruby
Ruby
reuse formulaauditor to check cask's urls
5ed5e500e5680bb2276320070ce685f04df33c55
<ide><path>Library/Homebrew/cask/lib/hbc/audit.rb <ide> require "hbc/download" <ide> require "digest" <ide> require "utils/git" <add>require "dev-cmd/audit" <ide> <ide> module Hbc <ide> class Audit <ide> def core_formula_url <ide> end <ide> <ide> def check_https_availability <del> check_url_for_https_availability(cask.homepage) unless cask.url.to_s.empty? <add> check_url_for_https_availability(cask.url) unless cask.url.to_s.empty? <ide> check_url_for_https_availability(cask.appcast) unless cask.appcast.to_s.empty? <ide> check_url_for_https_availability(cask.homepage) unless cask.homepage.to_s.empty? <ide> end <ide> <ide> def check_url_for_https_availability(url_to_check) <del> if schema_http?(url_to_check) <del> result, effective_url = access_url(url_to_check.sub(/^http:/, 'https:')) <del> if schema_https?(effective_url) && result == 1 <del> add_error "Change #{url_to_check} to #{url_to_check.sub(/^http:/, 'https:')}" <del> else <del> result, effective_url = access_url(url_to_check) <del> <del> if result == 0 <del> add_error "URL is not reachable #{url_to_check}" <del> end <del> end <del> else <del> result, effective_url = access_url(url_to_check) <del> if result == 1 && schema_https?(effective_url) <del> return <del> else <del> result, effective_url = access_url(url_to_check.sub(/^https:/, 'http:')) <del> if result == 1 && schema_http?(effective_url) <del> add_error "Change #{url_to_check} to #{url_to_check.sub(/^https:/, 'http:')}" <del> else <del> add_error "URL is not reachable #{url_to_check}" <del> end <del> end <del> end <del> end <del> <del> def access_url(url_to_access) <del> # return values: <del> # 1, effective URL : URL reachable, no schema change <del> # 0, nil : URL unreachable <del> # -1, effective URL : URL reachable, but schema changed <del> <del> curl_executable, *args = curl_args( <del> "--compressed", "--location", "--fail", <del> "--write-out", "%{http_code} %{url_effective}", <del> "--output", "/dev/null", "--head", <del> url_to_access, <del> user_agent: :fake <del> ) <del> result = @command.run(curl_executable, args: args, print_stderr: false) <del> if result.success? <del> http_code, url_effective = result.stdout.chomp.split(' ') <del> odebug "input: #{url_to_access} effective: #{url_effective} code: #{http_code}" <del> <del> # Fail if return code not 2XX or 3XX <del> return 0, nil if http_code.to_i < 200 && http_code.to_i > 300 <del> <del> # Fail if URL schema changed <del> # ([4] is either http[s]:// or http[:]// ) <del> return -1, url_effective if url_to_access[4] != url_effective[4] <del> <del> return 1, url_effective <del> else <del> return 0, nil <del> end <del> end <del> <del> def schema_http?(url) <del> url[/^http:/] ? 1 : nil <del> end <del> <del> def schema_https?(url) <del> url[/^https:/] ? 1 : nil <add> problem = FormulaAuditor.check_http_content(url_to_check.to_s) <add> add_error problem unless problem.nil? <ide> end <ide> <ide> def check_download
1
Go
Go
remove failing overlay test
0e74aabbb9aa5cea0b6bf7342f9e325f989468fa
<ide><path>daemon/graphdriver/overlay/overlay_test.go <ide> func TestOverlay50LayerRead(t *testing.T) { <ide> graphtest.DriverTestDeepLayerRead(t, 50, "overlay") <ide> } <ide> <add>// Fails due to bug in calculating changes after apply <add>// likely related to https://github.com/docker/docker/issues/21555 <ide> func TestOverlayDiffApply10Files(t *testing.T) { <add> t.Skipf("Fails to compute changes after apply intermittently") <ide> graphtest.DriverTestDiffApply(t, 10, "overlay") <ide> } <ide> <ide> func TestOverlayChanges(t *testing.T) { <add> t.Skipf("Fails to compute changes intermittently") <ide> graphtest.DriverTestChanges(t, "overlay") <ide> } <ide>
1
Javascript
Javascript
expose e2e test results
70c3dc81665191cd065a5303e5e26639a0023a73
<ide><path>src/scenario/Runner.js <ide> angular.scenario.Runner = function(scope, jQuery){ <ide> var self = scope.$scenario = this; <ide> this.scope = scope; <ide> this.jQuery = jQuery; <add> this.scope.$testrun = {done: false, results: []}; <ide> <ide> var specs = this.specs = {}; <ide> var path = []; <ide> angular.scenario.Runner = function(scope, jQuery){ <ide> self.currentSpec = null; <ide> }; <ide> this.logger = function returnNoop(){ <del> return extend(returnNoop, {close:noop, fail:noop});; <add> return extend(returnNoop, {close:noop, fail:noop}); <ide> }; <ide> }; <ide> <ide> angular.scenario.Runner.prototype = { <ide> var next = specNames.shift(); <ide> if(next) { <ide> self.execute(next, callback); <add> } else { <add> self.scope.$testrun.done = true; <ide> } <ide> }; <ide> callback(); <ide> angular.scenario.Runner.prototype = { <ide> execute: function(name, callback) { <ide> var spec = this.specs[name], <ide> self = this, <add> stepsDone = [], <ide> result = { <ide> passed: false, <ide> failed: false, <ide> angular.scenario.Runner.prototype = { <ide> if (step) { <ide> spec.nextStepIndex ++; <ide> result.log = stepLogger('step', step.name); <add> stepsDone.push(step.name); <ide> try { <ide> step.fn.call(specThis, next); <ide> } catch (e) { <ide> console.error(e); <ide> result.fail(e); <add> self.scope.$testrun.results.push( <add> {name: name, passed: false, error: e, steps: stepsDone}); <ide> done(); <ide> } <ide> } else { <ide> result.passed = !result.failed; <add> self.scope.$testrun.results.push({ <add> name: name, <add> passed: !result.failed, <add> error: result.error, <add> steps: stepsDone}); <ide> done(); <ide> } <ide> }; <ide><path>test/scenario/RunnerSpec.js <ide> describe('Runner', function(){ <ide> it('should handle exceptions in a step', function(){ <ide> $scenario.specs['spec'] = { <ide> steps: [ <add> {name: 'first step', fn: function(done) { <add> done(); <add> }}, <ide> {name:'error', fn:function(done) { <ide> throw "MyError"; <add> }}, <add> {name: 'should not execute', fn: function(done) { <add> done(); <ide> }} <ide> ] <ide> }; <ide> describe('Runner', function(){ <ide> expect(spec.result.failed).toEqual(true); <ide> expect(spec.result.finished).toEqual(true); <ide> expect(spec.result.error).toEqual("MyError"); <add> expect(scenario.$testrun.results).toEqual([{ <add> name: 'spec', <add> passed: false, <add> error: 'MyError', <add> steps: ['first step', 'error']}]); <ide> }); <ide> }); <ide> <ide> describe('run', function(){ <ide> var next; <del> it('should execute all specs', function(){ <add> beforeEach(function() { <ide> Describe('d1', function(){ <ide> It('it1', function(){ $scenario.addStep('s1', logger('s1,')); }); <ide> It('it2', function(){ <ide> describe('Runner', function(){ <ide> It('it3', function(){ $scenario.addStep('s3', logger('s3,')); }); <ide> It('it4', function(){ $scenario.addStep('s4', logger('s4,')); }); <ide> }); <del> <add> }); <add> it('should execute all specs', function(){ <ide> $scenario.run(body); <ide> <ide> expect(log).toEqual('s1,s2,'); <ide> next(); <ide> expect(log).toEqual('s1,s2,s3,s4,'); <del> <add> }); <add> it('should publish done state and results as tests are run', function() { <add> expect(scenario.$testrun.done).toBeFalsy(); <add> expect(scenario.$testrun.results).toEqual([]); <add> $scenario.run(body); <add> expect(scenario.$testrun.done).toBeFalsy(); <add> expect(scenario.$testrun.results).toEqual([ <add> {name: 'd1: it it1', passed: true, steps: ['s1']} <add> ]); <add> next(); <add> expect(scenario.$testrun.done).toBeTruthy(); <add> expect(scenario.$testrun.results).toEqual([ <add> {name: 'd1: it it1', passed: true, steps: ['s1']}, <add> {name: 'd1: it it2', passed: true, steps: ['s2', 's2.2']}, <add> {name: 'd2: it it3', passed: true, steps: ['s3']}, <add> {name: 'd2: it it4', passed: true, steps: ['s4']} <add> ]); <ide> }); <ide> }); <ide>
2
PHP
PHP
add test with new lines
a6209ea0f81a1be448d28c38b815c1750ff96d12
<ide><path>tests/Validation/ValidationInRuleTest.php <ide> public function testItCorrectlyFormatsAStringVersionOfTheRule() <ide> <ide> $this->assertEquals('in:"Life, the Universe and Everything","this is a ""quote"""', (string) $rule); <ide> <add> $rule = new In(["a,b\nc,d"]); <add> <add> $this->assertEquals("in:\"a,b\nc,d\"", (string) $rule); <add> <ide> $rule = Rule::in([1, 2, 3, 4]); <ide> <ide> $this->assertEquals('in:"1","2","3","4"', (string) $rule); <ide><path>tests/Validation/ValidationValidatorTest.php <ide> public function testValidateIn() <ide> $v = new Validator($trans, ['name' => ['foo,bar', 'qux']], ['name' => 'Array|In:"foo,bar",baz,qux']); <ide> $this->assertTrue($v->passes()); <ide> <del> $v = new Validator($trans, ['name' => ['f"o"o', 'qux']], ['name' => 'Array|In:"f""o""o",baz,qux']); <add> $v = new Validator($trans, ['name' => 'f"o"o'], ['name' => 'In:"f""o""o",baz,qux']); <add> $this->assertTrue($v->passes()); <add> <add> $v = new Validator($trans, ['name' => "a,b\nc,d"], ['name' => "in:\"a,b\nc,d\""]); <ide> $this->assertTrue($v->passes()); <ide> <ide> $v = new Validator($trans, ['name' => ['foo', 'bar']], ['name' => 'Alpha|In:foo,bar']);
2
Ruby
Ruby
remove dependency from _template
bebaccdf4a3a17f2ead349cca891032e245655ff
<ide><path>actionpack/lib/action_view/base.rb <ide> def cache_template_loading=(value) <ide> end <ide> end <ide> <del> attr_accessor :_template, :_view_flow <add> attr_accessor :_view_flow <ide> attr_internal :request, :controller, :config, :assigns, :lookup_context <ide> <ide> # TODO Consider removing those setters once we have the renderer in place. <ide> def initialize(lookup_context = nil, assigns_for_first_render = {}, controller = <ide> @_virtual_path = nil <ide> @_view_flow = OutputFlow.new <ide> @output_buffer = nil <add> @virtual_path = nil <ide> <ide> if @_controller = controller <ide> @_request = controller.request if controller.respond_to?(:request) <ide><path>actionpack/lib/action_view/helpers/form_helper.rb <ide> def sanitized_method_name <ide> class FormBuilder <ide> # The methods which wrap a form helper call. <ide> class_attribute :field_helpers <del> self.field_helpers = (FormHelper.instance_method_names - ['form_for']) <add> self.field_helpers = FormHelper.instance_method_names - %w(form_for convert_to_model) <ide> <ide> attr_accessor :object_name, :object, :options <ide> <ide><path>actionpack/lib/action_view/helpers/translation_helper.rb <ide> def localize(*args) <ide> private <ide> def scope_key_by_partial(key) <ide> if key.to_s.first == "." <del> if (path = @_template && @_template.virtual_path) <del> path.gsub(%r{/_?}, ".") + key.to_s <add> if @virtual_path <add> @virtual_path.gsub(%r{/_?}, ".") + key.to_s <ide> else <ide> raise "Cannot use t(#{key.inspect}) shortcut because path is not available" <ide> end <ide><path>actionpack/lib/action_view/template.rb <ide> def supports_streaming? <ide> # we use a bang in this instrumentation because you don't want to <ide> # consume this in production. This is only slow if it's being listened to. <ide> def render(view, locals, buffer=nil, &block) <del> old_template, view._template = view._template, self <ide> ActiveSupport::Notifications.instrument("!render_template.action_view", :virtual_path => @virtual_path) do <ide> compile!(view) <ide> view.send(method_name, locals, buffer, &block) <ide> end <ide> rescue Exception => e <ide> handle_render_error(view, e) <del> ensure <del> view._template = old_template <ide> end <ide> <ide> def mime_type <ide> def refresh(view) <ide> end <ide> <ide> def inspect <del> @inspect ||= <del> if defined?(Rails.root) <del> identifier.sub("#{Rails.root}/", '') <del> else <del> identifier <del> end <add> @inspect ||= defined?(Rails.root) ? identifier.sub("#{Rails.root}/", '') : identifier <ide> end <ide> <ide> protected <ide> def compile(view, mod) #:nodoc: <ide> # encoding of the code <ide> source = <<-end_src <ide> def #{method_name}(local_assigns, output_buffer) <del> _old_output_buffer = @output_buffer;#{locals_code};#{code} <add> _old_virtual_path, @virtual_path = @virtual_path, #{@virtual_path.inspect};_old_output_buffer = @output_buffer;#{locals_code};#{code} <ide> ensure <del> @output_buffer = _old_output_buffer <add> @virtual_path, @output_buffer = _old_virtual_path, _old_output_buffer <ide> end <ide> end_src <ide> <ide><path>actionpack/lib/action_view/test_case.rb <ide> def make_test_case_available_to_view! <ide> module Locals <ide> attr_accessor :locals <ide> <del> def _render_partial(options) <del> locals[options[:partial]] = options[:locals] <del> super(options) <add> def render(options = {}, local_assigns = {}) <add> case options <add> when Hash <add> if block_given? <add> locals[options[:layout]] = options[:locals] <add> elsif options.key?(:partial) <add> locals[options[:partial]] = options[:locals] <add> end <add> else <add> locals[options] = local_assigns <add> end <add> <add> super <ide> end <ide> end <ide> <ide><path>actionpack/test/template/template_test.rb <ide> def disable_cache <ide> end <ide> <ide> class Context <del> attr_accessor :_template <del> <ide> def initialize <ide> @output_buffer = "original" <del> @_virtual_path = nil <add> @virtual_path = nil <ide> end <ide> <ide> def hello <ide> def hello <ide> <ide> def partial <ide> ActionView::Template.new( <del> "<%= @_template.virtual_path %>", <add> "<%= @virtual_path %>", <ide> "partial", <ide> ERBHandler, <ide> :virtual_path => "partial" <ide> def test_restores_buffer <ide> end <ide> <ide> def test_virtual_path <del> @template = new_template("<%= @_template.virtual_path %>" \ <add> @template = new_template("<%= @virtual_path %>" \ <ide> "<%= partial.render(self, {}) %>" \ <del> "<%= @_template.virtual_path %>") <add> "<%= @virtual_path %>") <ide> assert_equal "hellopartialhello", render <ide> end <ide> <ide><path>actionpack/test/template/url_helper_test.rb <ide> class UrlHelperTest < ActiveSupport::TestCase <ide> # or request. <ide> # <ide> # In those cases, we'll set up a simple mock <del> attr_accessor :controller, :request, :_template <add> attr_accessor :controller, :request <ide> <ide> routes = ActionDispatch::Routing::RouteSet.new <ide> routes.draw do
7
Ruby
Ruby
catch new style gist urls
dc8218fdb50a303f5441e7a54866932f67669b0f
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_patches <ide> <ide> def audit_patch(patch) <ide> case patch.url <del> when %r[raw\.github\.com], %r[gist\.github\.com/raw], %r[gist\.github\.com/.+/raw] <add> when %r[raw\.github\.com], %r[gist\.github\.com/raw], %r[gist\.github\.com/.+/raw], <add> %r[gist\.githubusercontent\.com/.+/raw] <ide> unless patch.url =~ /[a-fA-F0-9]{40}/ <ide> problem "GitHub/Gist patches should specify a revision:\n#{patch.url}" <ide> end
1
Javascript
Javascript
add tests for em.view#nearestoftype
4260efe344c02a8a3b195162746a7d40bb95d5fb
<ide><path>packages/ember-views/tests/views/view/nearest_of_type_test.js <add>var set = Ember.set, get = Ember.get; <add> <add>module("Ember.View#nearestOfType"); <add> <add>(function() { <add> var Mixin = Ember.Mixin.create({}), <add> Parent = Ember.View.extend(Mixin, { <add> render: function(buffer) { <add> this.appendChild( Ember.View.create() ); <add> } <add> }); <add> <add> test("nearestOfType should find the closest view by view class", function() { <add> var parent, child; <add> <add> Ember.run(function() { <add> parent = Parent.create(); <add> parent.appendTo('#qunit-fixture'); <add> }); <add> <add> child = parent.get('childViews')[0]; <add> equal(child.nearestOfType(Parent), parent, "finds closest view in the hierarchy by class"); <add> }); <add> <add> test("nearestOfType should find the closest view by mixin", function() { <add> var parent, child; <add> <add> Ember.run(function() { <add> parent = Parent.create(); <add> parent.appendTo('#qunit-fixture'); <add> }); <add> <add> child = parent.get('childViews')[0]; <add> equal(child.nearestOfType(Mixin), parent, "finds closest view in the hierarchy by class"); <add> }); <add> <add>}()); <ide>\ No newline at end of file
1
Python
Python
fix transformer inference savedmodel
54832af86a4f756ec95124511483966a2575f95d
<ide><path>official/nlp/modeling/models/seq2seq_transformer.py <ide> def call(self, inputs): <ide> Raises: <ide> NotImplementedError: If try to use padded decode method on CPU/GPUs. <ide> """ <add> inputs = inputs if isinstance(inputs, list) else [inputs] <ide> if len(inputs) == 2: <ide> sources, targets = inputs[0], inputs[1] <ide> else: <ide> # Decoding path. <ide> sources, targets = inputs[0], None <del> <ide> attention_bias = model_utils.get_padding_bias(sources) <ide> attention_bias = tf.cast(attention_bias, self._dtype) <ide> # Prepare inputs to the layer stack by adding positional encodings and <ide> def call(self, inputs): <ide> encoder_decoder_attention_bias = attention_bias <ide> encoder_outputs = tf.cast(encoder_outputs, self._dtype) <ide> if self._padded_decode: <del> batch_size = encoder_outputs.shape.as_list()[0] <ide> max_decode_length = self._decode_max_length <ide> else: <del> batch_size = tf.shape(encoder_outputs)[0] <ide> max_decode_length = self._decode_max_length or ( <ide> tf.shape(encoder_outputs)[1] + self._extra_decode_length) <ide> encoder_decoder_attention_bias = tf.cast(encoder_decoder_attention_bias, <ide> self._dtype) <del> <ide> symbols_to_logits_fn = self._get_symbols_to_logits_fn(max_decode_length) <ide> <add> batch_size = tf.shape(encoder_outputs)[0] <ide> # Create initial set of IDs that will be passed to symbols_to_logits_fn. <ide> initial_ids = tf.zeros([batch_size], dtype=tf.int32) <ide> <ide><path>official/nlp/modeling/models/seq2seq_transformer_test.py <ide> def _step_fn(inputs): <ide> logging.info("local_outputs=%s", local_outputs) <ide> self.assertEqual(local_outputs[0].shape, (4, 8, 100)) <ide> <add> @parameterized.parameters(True, False) <add> def test_create_savedmodel(self, padded_decode): <add> decode_max_length = 10 <add> model = self._build_model(padded_decode, decode_max_length) <add> <add> class SaveModule(tf.Module): <add> <add> def __init__(self, model): <add> super(SaveModule, self).__init__() <add> self.model = model <add> <add> @tf.function <add> def serve(self, inputs): <add> return self.model.call([inputs]) <add> <add> save_module = SaveModule(model) <add> if padded_decode: <add> tensor_shape = (4, 10) <add> else: <add> tensor_shape = (None, None) <add> signatures = dict( <add> serving_default=save_module.serve.get_concrete_function( <add> tf.TensorSpec(shape=tensor_shape, dtype=tf.int32, name="inputs"))) <add> tf.saved_model.save(save_module, self.get_temp_dir(), signatures=signatures) <add> <ide> <ide> if __name__ == "__main__": <ide> tf.test.main() <ide><path>official/nlp/transformer/transformer.py <ide> def call(self, inputs, training): <ide> Raises: <ide> NotImplementedError: If try to use padded decode method on CPU/GPUs. <ide> """ <add> inputs = inputs if isinstance(inputs, list) else [inputs] <ide> if len(inputs) == 2: <ide> inputs, targets = inputs[0], inputs[1] <ide> else:
3
PHP
PHP
set incremented value on model
b18c7258f7ae8ba3a01a41c272cbf2f7e0b75005
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> protected function incrementOrDecrement($column, $amount, $method) <ide> return $query->{$method}($column, $amount); <ide> } <ide> <add> $this->incrementOrDecrementAttributeValue($column, $amount, $method); <add> <ide> return $query->where($this->getKeyName(), $this->getKey())->{$method}($column, $amount); <ide> } <ide> <add> /** <add> * Increment the underlying attribute value and sync with original. <add> * <add> * @param string $column <add> * @param int $amount <add> * @param string $method <add> * @return void <add> */ <add> protected function incrementOrDecrementAttributeValue($column, $amount, $method) <add> { <add> $this->{$column} = $this->{$column} + ($method == 'increment' ? $amount : $amount * -1); <add> <add> $this->syncOriginalAttribute($column); <add> } <add> <ide> /** <ide> * Update the model in the database. <ide> * <ide> public function syncOriginal() <ide> return $this; <ide> } <ide> <add> /** <add> * Sync a single original attribute with its current value. <add> * <add> * @param string $attribute <add> * @return \Illuminate\Database\Eloquent\Model <add> */ <add> public function syncOriginalAttribute($attribute) <add> { <add> $this->original[$attribute] = $this->attributes[$attribute]; <add> <add> return $this; <add> } <add> <ide> /** <ide> * Determine if the model or a given attribute has been modified. <ide> * <ide><path>tests/Database/DatabaseEloquentModelTest.php <ide> public function testReplicateCreatesANewModelInstanceWithSameAttributeValues() <ide> } <ide> <ide> <add> public function testIncrementOnExistingModelCallsQueryAndSetsAttribute() <add> { <add> $model = m::mock('EloquentModelStub[newQuery]'); <add> $model->exists = true; <add> $model->id = 1; <add> $model->syncOriginalAttribute('id'); <add> $model->foo = 2; <add> <add> $model->shouldReceive('newQuery')->andReturn($query = m::mock('StdClass')); <add> $query->shouldReceive('where')->andReturn($query); <add> $query->shouldReceive('increment'); <add> <add> $model->publicIncrement('foo'); <add> <add> $this->assertEquals(3, $model->foo); <add> $this->assertFalse($model->isDirty()); <add> } <add> <add> <ide> protected function addMockConnection($model) <ide> { <ide> $model->setConnectionResolver($resolver = m::mock('Illuminate\Database\ConnectionResolverInterface')); <ide> public function setPasswordAttribute($value) <ide> { <ide> $this->attributes['password_hash'] = md5($value); <ide> } <add> public function publicIncrement($column, $amount = 1) <add> { <add> return $this->increment($column, $amount); <add> } <ide> public function belongsToStub() <ide> { <ide> return $this->belongsTo('EloquentModelSaveStub');
2
Javascript
Javascript
make abort-fatal-error more robust
2f5e77f55bb7af8ba0b9643a83abdb81b4255d9b
<ide><path>test/simple/test-abort-fatal-error.js <ide> cmdline += ' --max-old-space-size=4 --max-new-space-size=1'; <ide> cmdline += ' -e "a = []; for (i = 0; i < 1e9; i++) { a.push({}) }"'; <ide> <ide> exec(cmdline, function(err, stdout, stderr) { <del> assert(err); <del> assert(stderr.toString().match(/abort/i)); <add> if (!err) { <add> console.log(stdout); <add> console.log(stderr); <add> assert(false, 'this test should fail'); <add> return; <add> } <add> <add> if (err.code !== 134 || err.signal !== 'SIGABRT') { <add> console.log(stdout); <add> console.log(stderr); <add> console.log(err); <add> assert(false, err); <add> } <ide> });
1
Text
Text
move sysctls to correct api version
7cdd693d5d2094f73383145eb74d81c6b9bb9b24
<ide><path>docs/reference/api/docker_remote_api_v1.21.md <ide> Create a container <ide> "RestartPolicy": { "Name": "", "MaximumRetryCount": 0 }, <ide> "NetworkMode": "bridge", <ide> "Devices": [], <del> "Sysctls": { "net.ipv4.ip_forward": "1" }, <ide> "Ulimits": [{}], <ide> "LogConfig": { "Type": "json-file", "Config": {} }, <ide> "SecurityOpt": [], <ide><path>docs/reference/api/docker_remote_api_v1.24.md <ide> Create a container <ide> "RestartPolicy": { "Name": "", "MaximumRetryCount": 0 }, <ide> "NetworkMode": "bridge", <ide> "Devices": [], <add> "Sysctls": { "net.ipv4.ip_forward": "1" }, <ide> "Ulimits": [{}], <ide> "LogConfig": { "Type": "json-file", "Config": {} }, <ide> "SecurityOpt": [],
2
Python
Python
fix a number of pep8 errors
1f5455e29efa4579eebbf894e97ee53cd1257529
<ide><path>keras/backend/tensorflow_backend.py <ide> def rnn(step_function, inputs, initial_states, <ide> # TODO: remove later. <ide> if hasattr(tf, 'select'): <ide> tf.where = tf.select <del> <add> <ide> if unroll: <ide> if not inputs.get_shape()[0]: <ide> raise ValueError('Unrolling requires a ' <ide><path>keras/backend/theano_backend.py <ide> def rnn(step_function, inputs, initial_states, <ide> constants = [] <ide> <ide> if mask is not None: <del> if mask.ndim == ndim-1: <add> if mask.ndim == ndim - 1: <ide> mask = expand_dims(mask) <ide> assert mask.ndim == ndim <ide> mask = mask.dimshuffle(axes) <ide> def random_binomial(shape, p=0.0, dtype=None, seed=None): <ide> # Note that tensorflow's native CTC code is significantly <ide> # faster than this <ide> <add> <ide> def ctc_interleave_blanks(Y): <ide> Y_ = T.alloc(-1, Y.shape[0] * 2 + 1) <ide> Y_ = T.set_subtensor(Y_[T.arange(Y.shape[0]) * 2 + 1], Y) <ide><path>keras/constraints.py <ide> def __init__(self, axis=0): <ide> <ide> def __call__(self, p): <ide> return p / (K.epsilon() + K.sqrt(K.sum(K.square(p), <del> axis=self.axis, <del> keepdims=True))) <add> axis=self.axis, <add> keepdims=True))) <ide> <ide> def get_config(self): <ide> return {'name': self.__class__.__name__, <ide><path>keras/engine/topology.py <ide> class InputSpec(object): <ide> A None entry in a shape is compatible with any dimension, <ide> a None shape is compatible with any shape. <ide> """ <add> <ide> def __init__(self, dtype=None, shape=None, ndim=None): <ide> if isinstance(ndim, str): <ide> if '+' not in ndim: <ide> class Node(object): <ide> A.outbound_nodes <ide> B.inbound_nodes <ide> """ <add> <ide> def __init__(self, outbound_layer, <ide> inbound_layers, node_indices, tensor_indices, <ide> input_tensors, output_tensors, <ide> class Layer(object): <ide> create_input_layer() <ide> assert_input_compatibility() <ide> """ <add> <ide> def __init__(self, **kwargs): <ide> # These properties should have been set <ide> # by the child class, as appropriate. <ide> class InputLayer(Layer): <ide> is meant to be sparse. <ide> name: Name of the layer (string). <ide> """ <add> <ide> def __init__(self, input_shape=None, batch_input_shape=None, <ide> input_dtype=None, input_tensor=None, sparse=False, name=None): <ide> self.input_spec = None <ide> class Merge(Layer): <ide> if merge mode is a lambda/function). If the latter case, it should <ide> take as input a list of masks and return a single mask. <ide> """ <add> <ide> def __init__(self, layers=None, mode='sum', concat_axis=-1, <ide> dot_axes=-1, output_shape=None, output_mask=None, <ide> arguments=None, node_indices=None, tensor_indices=None, <ide> class Container(Layer): <ide> # Class Methods <ide> from_config <ide> """ <add> <ide> def __init__(self, input, output, name=None): <ide> # Handle name argument. <ide> if not name: <ide> def load_weights_from_hdf5_group_by_name(self, f): <ide> flattened_layers = self.layers <ide> <ide> if 'nb_layers' in f.attrs: <del> raise ValueError('The weight file you are trying to load is' <del> ' in a legacy format that does not support' <del> ' name-based weight loading.') <add> raise ValueError('The weight file you are trying to load is' <add> ' in a legacy format that does not support' <add> ' name-based weight loading.') <ide> else: <ide> # New file format. <ide> layer_names = [n.decode('utf8') for n in f.attrs['layer_names']] <ide><path>keras/engine/training.py <ide> def compile(self, optimizer, loss, metrics=None, loss_weights=None, <ide> shape = self.internal_output_shapes[i] <ide> name = self.output_names[i] <ide> self.targets.append(K.placeholder(ndim=len(shape), <del> name=name + '_target', <del> sparse=K.is_sparse(self.outputs[i]), <del> dtype=K.dtype(self.outputs[i]))) <add> name=name + '_target', <add> sparse=K.is_sparse(self.outputs[i]), <add> dtype=K.dtype(self.outputs[i]))) <ide> <ide> # prepare metrics <ide> self.metrics = metrics <ide><path>keras/layers/core.py <ide> def get_output_shape_for(self, input_shape): <ide> output_shape = copy.copy(input_shape) <ide> for i, dim in enumerate(self.dims): <ide> target_dim = input_shape[dim] <del> output_shape[i+1] = target_dim <add> output_shape[i + 1] = target_dim <ide> return tuple(output_shape) <ide> <ide> def call(self, x, mask=None): <ide><path>keras/metrics.py <ide> def categorical_accuracy(y_true, y_pred): <ide> multiclass classification problems. <ide> """ <ide> return K.mean(K.equal(K.argmax(y_true, axis=-1), <del> K.argmax(y_pred, axis=-1))) <add> K.argmax(y_pred, axis=-1))) <ide> <ide> <ide> def sparse_categorical_accuracy(y_true, y_pred): <ide><path>keras/models.py <ide> class Sequential(Model): <ide> model.add(Dense(32)) <ide> ``` <ide> """ <add> <ide> def __init__(self, layers=None, name=None): <ide> self.layers = [] # stack of layers <ide> self.model = None # internal Model instance <ide><path>keras/optimizers.py <ide> class Optimizer(object): <ide> clipvalue: float >= 0. Gradients will be clipped <ide> when their absolute value exceeds this value. <ide> """ <add> <ide> def __init__(self, **kwargs): <ide> allowed_kwargs = {'clipnorm', 'clipvalue'} <ide> for k in kwargs: <ide> class SGD(Optimizer): <ide> decay: float >= 0. Learning rate decay over each update. <ide> nesterov: boolean. Whether to apply Nesterov momentum. <ide> """ <add> <ide> def __init__(self, lr=0.01, momentum=0., decay=0., <ide> nesterov=False, **kwargs): <ide> super(SGD, self).__init__(**kwargs) <ide> class RMSprop(Optimizer): <ide> epsilon: float >= 0. Fuzz factor. <ide> decay: float >= 0. Learning rate decay over each update. <ide> """ <add> <ide> def __init__(self, lr=0.001, rho=0.9, epsilon=1e-8, decay=0., <ide> **kwargs): <ide> super(RMSprop, self).__init__(**kwargs) <ide> class Adagrad(Optimizer): <ide> # References <ide> - [Adaptive Subgradient Methods for Online Learning and Stochastic Optimization](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf) <ide> """ <add> <ide> def __init__(self, lr=0.01, epsilon=1e-8, decay=0., **kwargs): <ide> super(Adagrad, self).__init__(**kwargs) <ide> self.lr = K.variable(lr) <ide> class Adadelta(Optimizer): <ide> # References <ide> - [Adadelta - an adaptive learning rate method](http://arxiv.org/abs/1212.5701) <ide> """ <add> <ide> def __init__(self, lr=1.0, rho=0.95, epsilon=1e-8, decay=0., <ide> **kwargs): <ide> super(Adadelta, self).__init__(**kwargs) <ide> class Adam(Optimizer): <ide> # References <ide> - [Adam - A Method for Stochastic Optimization](http://arxiv.org/abs/1412.6980v8) <ide> """ <add> <ide> def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999, <ide> epsilon=1e-8, decay=0., **kwargs): <ide> super(Adam, self).__init__(**kwargs) <ide> class Adamax(Optimizer): <ide> # References <ide> - [Adam - A Method for Stochastic Optimization](http://arxiv.org/abs/1412.6980v8) <ide> """ <add> <ide> def __init__(self, lr=0.002, beta_1=0.9, beta_2=0.999, <ide> epsilon=1e-8, decay=0., **kwargs): <ide> super(Adamax, self).__init__(**kwargs) <ide> class Nadam(Optimizer): <ide> - [Nadam report](http://cs229.stanford.edu/proj2015/054_report.pdf) <ide> - [On the importance of initialization and momentum in deep learning](http://www.cs.toronto.edu/~fritz/absps/momentum.pdf) <ide> """ <add> <ide> def __init__(self, lr=0.002, beta_1=0.9, beta_2=0.999, <ide> epsilon=1e-8, schedule_decay=0.004, **kwargs): <ide> super(Nadam, self).__init__(**kwargs) <ide><path>keras/preprocessing/image.py <ide> def random_channel_shift(x, intensity, channel_index=0): <ide> channel_images = [np.clip(x_channel + np.random.uniform(-intensity, intensity), min_x, max_x) <ide> for x_channel in x] <ide> x = np.stack(channel_images, axis=0) <del> x = np.rollaxis(x, 0, channel_index+1) <add> x = np.rollaxis(x, 0, channel_index + 1) <ide> return x <ide> <ide> <ide> def apply_transform(x, transform_matrix, channel_index=0, fill_mode='nearest', c <ide> final_affine_matrix = transform_matrix[:2, :2] <ide> final_offset = transform_matrix[:2, 2] <ide> channel_images = [ndi.interpolation.affine_transform(x_channel, final_affine_matrix, <del> final_offset, order=0, mode=fill_mode, cval=cval) for x_channel in x] <add> final_offset, order=0, mode=fill_mode, cval=cval) for x_channel in x] <ide> x = np.stack(channel_images, axis=0) <del> x = np.rollaxis(x, 0, channel_index+1) <add> x = np.rollaxis(x, 0, channel_index + 1) <ide> return x <ide> <ide> <ide> class ImageDataGenerator(object): <ide> Keras config file at `~/.keras/keras.json`. <ide> If you never set it, then it will be "th". <ide> """ <add> <ide> def __init__(self, <ide> featurewise_center=False, <ide> samplewise_center=False, <ide><path>keras/preprocessing/sequence.py <ide> def make_sampling_table(size, sampling_factor=1e-5): <ide> gamma = 0.577 <ide> rank = np.array(list(range(size))) <ide> rank[0] = 1 <del> inv_fq = rank * (np.log(rank) + gamma) + 0.5 - 1./(12.*rank) <add> inv_fq = rank * (np.log(rank) + gamma) + 0.5 - 1. / (12. * rank) <ide> f = sampling_factor * inv_fq <ide> <ide> return np.minimum(1., f / np.sqrt(f)) <ide> def skipgrams(sequence, vocabulary_size, <ide> if sampling_table[wi] < random.random(): <ide> continue <ide> <del> window_start = max(0, i-window_size) <del> window_end = min(len(sequence), i+window_size+1) <add> window_start = max(0, i - window_size) <add> window_end = min(len(sequence), i + window_size + 1) <ide> for j in range(window_start, window_end): <ide> if j != i: <ide> wj = sequence[j] <ide> def skipgrams(sequence, vocabulary_size, <ide> words = [c[0] for c in couples] <ide> random.shuffle(words) <ide> <del> couples += [[words[i %len(words)], random.randint(1, vocabulary_size-1)] for i in range(nb_negative_samples)] <add> couples += [[words[i % len(words)], random.randint(1, vocabulary_size - 1)] for i in range(nb_negative_samples)] <ide> if categorical: <del> labels += [[1, 0]]*nb_negative_samples <add> labels += [[1, 0]] * nb_negative_samples <ide> else: <del> labels += [0]*nb_negative_samples <add> labels += [0] * nb_negative_samples <ide> <ide> if shuffle: <ide> seed = random.randint(0, 10e6) <ide><path>keras/preprocessing/text.py <ide> def text_to_word_sequence(text, filters=base_filter(), lower=True, split=" "): <ide> """ <ide> if lower: <ide> text = text.lower() <del> text = text.translate(maketrans(filters, split*len(filters))) <add> text = text.translate(maketrans(filters, split * len(filters))) <ide> seq = text.split(split) <ide> return [_f for _f in seq if _f] <ide> <ide> def one_hot(text, n, filters=base_filter(), lower=True, split=" "): <ide> <ide> <ide> class Tokenizer(object): <add> <ide> def __init__(self, nb_words=None, filters=base_filter(), <ide> lower=True, split=' ', char_level=False): <ide> """The class allows to vectorize a text corpus, by turning each <ide><path>keras/utils/generic_utils.py <ide> def update(self, current, values=[], force=False): <ide> prog = float(current) / self.target <ide> prog_width = int(self.width * prog) <ide> if prog_width > 0: <del> bar += ('=' * (prog_width-1)) <add> bar += ('=' * (prog_width - 1)) <ide> if current < self.target: <ide> bar += '>' <ide> else: <ide><path>keras/utils/io_utils.py <ide> def __len__(self): <ide> def __getitem__(self, key): <ide> if isinstance(key, slice): <ide> if key.stop + self.start <= self.end: <del> idx = slice(key.start+self.start, key.stop + self.start) <add> idx = slice(key.start + self.start, key.stop + self.start) <ide> else: <ide> raise IndexError <ide> elif isinstance(key, int): <ide><path>keras/utils/np_utils.py <ide> def to_categorical(y, nb_classes=None): <ide> """ <ide> y = np.array(y, dtype='int').ravel() <ide> if not nb_classes: <del> nb_classes = np.max(y)+1 <add> nb_classes = np.max(y) + 1 <ide> n = y.shape[0] <ide> categorical = np.zeros((n, nb_classes)) <ide> categorical[np.arange(n), y] = 1 <ide> def normalize(a, axis=-1, order=2): <ide> def binary_logloss(p, y): <ide> epsilon = 1e-15 <ide> p = sp.maximum(epsilon, p) <del> p = sp.minimum(1-epsilon, p) <add> p = sp.minimum(1 - epsilon, p) <ide> res = sum(y * sp.log(p) + sp.subtract(1, y) * sp.log(sp.subtract(1, p))) <ide> res *= -1.0 / len(y) <ide> return res <ide> <ide> <ide> def multiclass_logloss(P, Y): <del> npreds = [P[i][Y[i]-1] for i in range(len(Y))] <add> npreds = [P[i][Y[i] - 1] for i in range(len(Y))] <ide> score = -(1. / len(Y)) * np.sum(np.log(npreds)) <ide> return score <ide>
15
Javascript
Javascript
add test for selection.sort
94800d39d2f6b22bef10c6921ee44906dcaa85d3
<ide><path>test/core/selection-sort-test.js <add>require("../env"); <add>require("../../d3"); <add> <add>var vows = require("vows"), <add> assert = require("assert"); <add> <add>var suite = vows.describe("selection.sort"); <add> <add>suite.addBatch({ <add> "selectAll(div).selectAll(span)": { <add> topic: function() { <add> return d3.select("body").html("").selectAll("div") <add> .data([1, 2, 10, 20]) <add> .enter().append("div").selectAll("span") <add> .data(function(d) { return [20 + d, 2 + d, 10, 1]; }) <add> .enter().append("span") <add> .attr("class", String); <add> }, <add> "sorts elements by natural order": function(span) { <add> span.sort(); <add> assert.domNull(span[0][0].previousSibling); <add> assert.domEqual(span[0][1].previousSibling, span[0][0]); <add> assert.domEqual(span[0][2].previousSibling, span[0][1]); <add> assert.domEqual(span[0][3].previousSibling, span[0][2]); <add> assert.domNull(span[0][3].nextSibling); <add> }, <add> "sorts each group independently": function(span) { <add> span.sort(d3.descending); <add> assert.deepEqual(span[0].map(data), [21, 10, 3, 1]); <add> assert.deepEqual(span[1].map(data), [22, 10, 4, 1]); <add> assert.deepEqual(span[2].map(data), [30, 12, 10, 1]); <add> assert.deepEqual(span[3].map(data), [40, 22, 10, 1]); <add> }, <add> "sorts using the specified comparator": function(span) { <add> span.sort(function(a, b) { return d3.ascending(a+"", b+""); }); <add> assert.deepEqual(span[0].map(data), [1, 10, 21, 3]); <add> assert.deepEqual(span[1].map(data), [1, 10, 22, 4]); <add> assert.deepEqual(span[2].map(data), [1, 10, 12, 30]); <add> assert.deepEqual(span[3].map(data), [1, 10, 22, 40]); <add> }, <add> "treats null nodes as null data": function(span) { <add> var some = d3.selectAll("div:first-child span"), nulls = false; <add> some[0][0] = null; <add> some.sort(function(a, b) { if ((a === null) || (b === null)) ++nulls; return a - b; }); <add> assert.isTrue(nulls > 0); <add> assert.domNull(span[0][0].previousSibling); <add> assert.deepEqual(some[0].slice(1).map(data), [3, 10, 21]); <add> } <add> } <add>}); <add> <add>function data(d) { <add> return d.__data__; <add>} <add> <add>suite.export(module); <ide><path>test/env.js <ide> require("../lib/sizzle/sizzle"); <ide> Sizzle = window.Sizzle; <ide> <ide> process.env.TZ = "America/Los_Angeles"; <add> <add>var assert = require("assert"); <add> <add>assert.domNull = function(actual, message) { <add> if (actual !== null) { <add> assert.fail(actual+"", null, message || "expected null, got {actual}", "===", assert.domNull); <add> } <add>}; <add> <add>assert.domEqual = function(actual, expected, message) { <add> if (actual !== expected) { <add> assert.fail(actual+"", expected+"", message || "expected {expected}, got {actual}", "===", assert.domEqual); <add> } <add>};
2
Javascript
Javascript
use datatextureloader and custom onload
fa43b759e76cc81aeebbe6e9e7df743e50773c1f
<ide><path>examples/js/loaders/TGALoader.js <ide> THREE.TGALoader = function ( manager ) { <ide> <del> THREE.Loader.call( this, manager ); <add> THREE.DataTextureLoader.call( this, manager ); <ide> <ide> }; <ide> <del>THREE.TGALoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { <add>THREE.TGALoader.prototype = Object.assign( Object.create( THREE.DataTextureLoader.prototype ), { <ide> <ide> constructor: THREE.TGALoader, <ide> <ide> load: function ( url, onLoad, onProgress, onError ) { <ide> <del> var scope = this; <add> function onDataTextureLoad( texture, texData ) { <ide> <del> var texture = new THREE.DataTexture(); <del> texture.flipY = true; <del> texture.generateMipmaps = true; <del> texture.unpackAlignment = 4; <del> texture.magFilter = THREE.LinearFilter; <del> texture.minFilter = THREE.LinearMipmapLinearFilter; <add> texture.flipY = true; <add> texture.generateMipmaps = true; <add> texture.unpackAlignment = 4; <add> texture.magFilter = THREE.LinearFilter; <add> texture.minFilter = THREE.LinearMipmapLinearFilter; <ide> <del> var loader = new THREE.FileLoader( this.manager ); <del> loader.setResponseType( 'arraybuffer' ); <del> loader.setPath( this.path ); <del> loader.setWithCredentials( this.withCredentials ); <add> if ( onLoad ) onLoad( texture, texData ); <ide> <del> loader.load( url, function ( buffer ) { <del> <del> texture.image = scope.parse( buffer ); <del> texture.needsUpdate = true; <del> <del> if ( onLoad !== undefined ) { <del> <del> onLoad( texture ); <del> <del> } <del> <del> }, onProgress, onError ); <add> } <ide> <del> return texture; <add> return THREE.DataTextureLoader.prototype.load.call( this, url, onDataTextureLoad, onProgress, onError ); <ide> <ide> }, <ide> <ide><path>examples/jsm/loaders/TGALoader.js <ide> import { <del> DataTexture, <del> FileLoader, <add> DataTextureLoader, <ide> LinearFilter, <del> LinearMipmapLinearFilter, <del> Loader <add> LinearMipmapLinearFilter <ide> } from '../../../build/three.module.js'; <ide> <ide> var TGALoader = function ( manager ) { <ide> <del> Loader.call( this, manager ); <add> DataTextureLoader.call( this, manager ); <ide> <ide> }; <ide> <del>TGALoader.prototype = Object.assign( Object.create( Loader.prototype ), { <add>TGALoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype ), { <ide> <ide> constructor: TGALoader, <ide> <ide> load: function ( url, onLoad, onProgress, onError ) { <ide> <del> var scope = this; <add> function onDataTextureLoad( texture, texData ) { <ide> <del> var texture = new DataTexture(); <del> texture.flipY = true; <del> texture.generateMipmaps = true; <del> texture.unpackAlignment = 4; <del> texture.minFilter = LinearMipmapLinearFilter; <del> texture.magFilter = LinearFilter; <add> texture.flipY = true; <add> texture.generateMipmaps = true; <add> texture.unpackAlignment = 4; <add> texture.magFilter = LinearFilter; <add> texture.minFilter = LinearMipmapLinearFilter; <ide> <del> var loader = new FileLoader( this.manager ); <del> loader.setResponseType( 'arraybuffer' ); <del> loader.setPath( this.path ); <del> loader.setWithCredentials( this.withCredentials ); <add> if ( onLoad ) onLoad( texture, texData ); <ide> <del> loader.load( url, function ( buffer ) { <del> <del> texture.image = scope.parse( buffer ); <del> texture.needsUpdate = true; <del> <del> if ( onLoad !== undefined ) { <del> <del> onLoad( texture ); <del> <del> } <del> <del> }, onProgress, onError ); <add> } <ide> <del> return texture; <add> return DataTextureLoader.prototype.load.call( this, url, onDataTextureLoad, onProgress, onError ); <ide> <ide> }, <ide>
2
Javascript
Javascript
add check for bounding sphere
c5f771fbb43056dd862ba1d87d531fa2418030c4
<ide><path>editor/js/Sidebar.Geometry.js <ide> Sidebar.Geometry = function ( editor ) { <ide> <ide> } <ide> <add> if ( geometry.boundingSphere === null ) { <add> <add> geometry.computeBoundingSphere(); <add> <add> } <ide> geometryBoundingSphere.setValue( Math.floor( geometry.boundingSphere.radius * 1000 ) / 1000 ); <ide> <ide> } else {
1
Ruby
Ruby
use new autocorrect flag
f804a22dc0ea5f9d5c0fb4a2a337be3060ce0e91
<ide><path>Library/Homebrew/style.rb <ide> def run_rubocop(files, output_type, <ide> --force-exclusion <ide> ] <ide> args << if fix <del> "--auto-correct-all" <add> "--autocorrect-all" <ide> else <ide> "--parallel" <ide> end
1
Ruby
Ruby
handle paths with spaces when editing credentials
5ca37eae126a541ba561034e79a8fcc5d1d0b712
<ide><path>railties/lib/rails/commands/credentials/credentials_command.rb <ide> # frozen_string_literal: true <ide> <ide> require "pathname" <add>require "shellwords" <ide> require "active_support" <ide> require "rails/command/helpers/editor" <ide> require "rails/command/environment_argument" <ide> def ensure_credentials_have_been_added <ide> <ide> def change_credentials_in_system_editor <ide> credentials.change do |tmp_path| <del> system("#{ENV["EDITOR"]} #{tmp_path}") <add> system("#{ENV["EDITOR"]} #{Shellwords.escape(tmp_path)}") <ide> end <ide> end <ide>
1
Go
Go
add /proc/keys to masked paths
de23cb939858a66829d5b75057c7ac664c5acda5
<ide><path>oci/defaults.go <ide> func DefaultLinuxSpec() specs.Spec { <ide> s.Linux = &specs.Linux{ <ide> MaskedPaths: []string{ <ide> "/proc/kcore", <add> "/proc/keys", <ide> "/proc/latency_stats", <ide> "/proc/timer_list", <ide> "/proc/timer_stats",
1
PHP
PHP
use table macro in routesshell
454146acfc0135b93eed5a7c6ffb8dce814e5060
<ide><path>src/Shell/RoutesShell.php <ide> class RoutesShell extends Shell <ide> */ <ide> public function main() <ide> { <del> $output = []; <add> $output = [ <add> ['Route name', 'URI template', 'Defaults'] <add> ]; <ide> foreach (Router::routes() as $route) { <ide> $output[] = [$route->getName(), $route->template, json_encode($route->defaults)]; <ide> } <del> <del> $this->_outWithColumns($output); <add> $this->_io->macro('table', $output); <ide> } <ide> <ide> /** <ide> public function check($url) <ide> { <ide> try { <ide> $route = Router::parse($url); <del> $this->_outWithColumns(['', $url, json_encode($route)]); <add> $output = [ <add> ['Route name', 'URI template', 'Defaults'], <add> ['', $url, json_encode($route)] <add> ]; <add> $this->_io->macro('table', $output); <ide> } catch (MissingRouteException $e) { <ide> $this->err("<warning>'$url' did not match any routes.</warning>"); <ide> return false; <ide> protected function _splitArgs($args) <ide> } <ide> return $out; <ide> } <del> <del> /** <del> * Takes an array to represent rows, of arrays to represent columns. <del> * Will pad strings to the maximum character length of each column. <del> * <del> * @param array $rows The rows to print <del> * @return void <del> */ <del> protected function _outWithColumns($rows) <del> { <del> if (!is_array($rows[0])) { <del> $rows = [$rows]; <del> } <del> $maxCharacterLength = []; <del> array_unshift($rows, ['Route name', 'URI template', 'Defaults']); <del> <del> foreach ($rows as $line) { <del> for ($i = 0, $len = count($line); $i < $len; $i++) { <del> $elementLength = strlen($line[$i]); <del> if ($elementLength > (isset($maxCharacterLength[$i]) ? $maxCharacterLength[$i] : 0)) { <del> $maxCharacterLength[$i] = $elementLength; <del> } <del> } <del> } <del> <del> foreach ($rows as $line) { <del> for ($i = 0, $len = count($line); $i < $len; $i++) { <del> $line[$i] = str_pad($line[$i], $maxCharacterLength[$i], " ", STR_PAD_RIGHT); <del> } <del> $this->out(implode(' ', $line)); <del> } <del> <del> $this->out(); <del> } <ide> } <ide><path>tests/TestCase/Shell/RoutesShellTest.php <ide> public function tearDown() <ide> public function testMain() <ide> { <ide> $this->io->expects($this->at(0)) <del> ->method('out') <del> ->with($this->logicalAnd( <del> $this->stringContains('Route name'), <del> $this->stringContains('URI template'), <del> $this->stringContains('Defaults') <del> )); <del> $this->io->expects($this->at(1)) <del> ->method('out') <del> ->with($this->logicalAnd( <del> $this->stringContains('articles:_action'), <del> $this->stringContains('/articles/:action'), <del> $this->stringContains('"controller":"Articles",') <del> )); <add> ->method('macro') <add> ->with( <add> 'table', <add> $this->logicalAnd( <add> $this->contains(['Route name', 'URI template', 'Defaults']), <add> $this->contains([ <add> 'articles:_action', <add> '/articles/:action/*', <add> '{"controller":"Articles","action":"index","plugin":null}' <add> ]) <add> ) <add> ); <ide> $this->shell->main(); <ide> } <ide> <ide> public function testMain() <ide> */ <ide> public function testCheck() <ide> { <del> $this->io->expects($this->at(1)) <del> ->method('out') <del> ->with($this->logicalAnd( <del> $this->stringContains('/articles/index'), <del> $this->stringContains('"controller":"Articles",') <del> )); <add> $this->io->expects($this->at(0)) <add> ->method('macro') <add> ->with( <add> 'table', <add> $this->logicalAnd( <add> $this->contains(['Route name', 'URI template', 'Defaults']), <add> $this->contains([ <add> '', <add> '/articles/index', <add> '{"action":"index","pass":[],"controller":"Articles","plugin":null}' <add> ]) <add> ) <add> ); <ide> $this->shell->check('/articles/index'); <ide> } <ide>
2
Ruby
Ruby
fix rosetta2 cocoapods warning on apple silicon
e918362be3cb03ae9dee3b8d50a240c599f6723f
<ide><path>scripts/react_native_pods.rb <ide> def use_react_native! (options={}) <ide> # Include Hermes dependencies <ide> hermes_enabled = options[:hermes_enabled] ||= false <ide> <del> if `/usr/sbin/sysctl -n hw.optional.arm64 2>&1`.to_i == 1 && !RUBY_PLATFORM.start_with?('arm64') <add> if `/usr/sbin/sysctl -n hw.optional.arm64 2>&1`.to_i == 1 && !RUBY_PLATFORM.include?('arm64') <ide> Pod::UI.warn 'Do not use "pod install" from inside Rosetta2 (x86_64 emulation on arm64).' <ide> Pod::UI.warn ' - Emulated x86_64 is slower than native arm64' <ide> Pod::UI.warn ' - May result in mixed architectures in rubygems (eg: ffi_c.bundle files may be x86_64 with an arm64 interpreter)'
1
PHP
PHP
revert previous changes to eloquent
00b064c7d52d8f43af819a5d62b1c35f01856748
<ide><path>system/db/eloquent.php <ide> public function has_and_belongs_to_many($model, $table = null) <ide> $this->relating_key = strtolower(get_class($this)).'_id'; <ide> <ide> return static::make($model) <del> ->select(array(static::table($model).'.*')) <add> ->select(static::table($model).'.*') <ide> ->join($this->relating_table, static::table($model).'.id', '=', $this->relating_table.'.'.strtolower($model).'_id') <ide> ->where($this->relating_table.'.'.$this->relating_key, '=', $this->id); <ide> }
1
Python
Python
trigger a build
819408ac338e95c8293b69a1bcbd28ac7240988b
<ide><path>setup.py <ide> # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <del> <ide> import os <ide> import sys <ide> import doctest
1
Python
Python
fix paver execution on windows 7 for python 2.6
0132351b0073f464060e1bac8b0595198c31a4e9
<ide><path>pavement.py <ide> "2.6": ["C:\Python26\python.exe"], <ide> "2.5": ["C:\Python25\python.exe"], <ide> } <del> WINDOWS_ENV = {} <add> # XXX: find out which env variable is necessary to avoid the pb with python <add> # 2.6 and random module when importing tempfile <add> WINDOWS_ENV = os.environ <ide> MAKENSIS = ["makensis"] <ide> else: <ide> WINDOWS_PYTHON = {
1
Mixed
Ruby
fix bug on non empty defaults for pg array columns
78e4862f6f7079c10af44c269bf98046a41bc8cf
<ide><path>activerecord/CHANGELOG.md <add>* Fixed error when specifying a non-empty default value on a PostgreSQL array column. <add> <add> Fixes #10613. <add> <add> *Luke Steensen* <add> <ide> * Make possible to change `record_timestamps` inside Callbacks. <ide> <ide> *Tieg Zaharia* <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb <ide> def type_to_sql(type, limit, precision, scale) <ide> end <ide> <ide> def add_column_options!(sql, options) <del> sql << " DEFAULT #{@conn.quote(options[:default], options[:column])}" if options_include_default?(options) <add> sql << " DEFAULT #{quote_value(options[:default], options[:column])}" if options_include_default?(options) <ide> # must explicitly check for :null to allow change_column to work on migrations <ide> if options[:null] == false <ide> sql << " NOT NULL" <ide> def add_column_options!(sql, options) <ide> sql <ide> end <ide> <add> def quote_value(value, column) <add> column.sql_type ||= type_to_sql(column.type, column.limit, column.precision, column.scale) <add> <add> @conn.quote(value, column) <add> end <add> <ide> def options_include_default?(options) <ide> options.include?(:default) && !(options[:null] == false && options[:default].nil?) <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb <ide> class IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths, : <ide> # are typically created by methods in TableDefinition, and added to the <ide> # +columns+ attribute of said TableDefinition object, in order to be used <ide> # for generating a number of table creation or table changing SQL statements. <del> class ColumnDefinition < Struct.new(:name, :type, :limit, :precision, :scale, :default, :null, :first, :after, :primary_key) #:nodoc: <add> class ColumnDefinition < Struct.new(:name, :type, :limit, :precision, :scale, :default, :null, :first, :after, :primary_key, :sql_type) #:nodoc: <ide> <ide> def primary_key? <ide> primary_key || type.to_sym == :primary_key <ide><path>activerecord/test/cases/adapters/postgresql/array_test.rb <ide> def test_default <ide> PgArray.reset_column_information <ide> end <ide> <add> def test_default_strings <add> @connection.add_column 'pg_arrays', 'names', :string, array: true, default: ["foo", "bar"] <add> PgArray.reset_column_information <add> column = PgArray.columns_hash["names"] <add> <add> assert_equal(["foo", "bar"], column.default) <add> assert_equal(["foo", "bar"], PgArray.new.names) <add> ensure <add> PgArray.reset_column_information <add> end <add> <ide> def test_change_column_with_array <ide> @connection.add_column :pg_arrays, :snippets, :string, array: true, default: [] <ide> @connection.change_column :pg_arrays, :snippets, :text, array: true, default: "{}"
4
Text
Text
fix nits in child_process.md
bf692ce1e61948be8f258402768efe280069459b
<ide><path>doc/api/child_process.md <ide> ls.stdout.on('data', (data) => { <ide> }); <ide> <ide> ls.stderr.on('data', (data) => { <del> console.log(`stderr: ${data}`); <add> console.error(`stderr: ${data}`); <ide> }); <ide> <ide> ls.on('close', (code) => { <ide> When running on Windows, `.bat` and `.cmd` files can be invoked using <ide> spaces it needs to be quoted. <ide> <ide> ```js <del>// On Windows Only ... <add>// On Windows Only... <ide> const { spawn } = require('child_process'); <ide> const bat = spawn('cmd.exe', ['/c', 'my.bat']); <ide> <ide> bat.stdout.on('data', (data) => { <ide> }); <ide> <ide> bat.stderr.on('data', (data) => { <del> console.log(data.toString()); <add> console.error(data.toString()); <ide> }); <ide> <ide> bat.on('exit', (code) => { <ide> need to be dealt with accordingly: <ide> ```js <ide> exec('"/path/to/test file/test.sh" arg1 arg2'); <ide> // Double quotes are used so that the space in the path is not interpreted as <del>// multiple arguments <add>// a delimiter of multiple arguments. <ide> <ide> exec('echo "The \\$HOME variable is $HOME"'); <del>// The $HOME variable is escaped in the first instance, but not in the second <add>// The $HOME variable is escaped in the first instance, but not in the second. <ide> ``` <ide> <ide> **Never pass unsanitized user input to this function. Any input containing shell <ide> exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { <ide> return; <ide> } <ide> console.log(`stdout: ${stdout}`); <del> console.log(`stderr: ${stderr}`); <add> console.error(`stderr: ${stderr}`); <ide> }); <ide> ``` <ide> <ide> a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned <ide> `ChildProcess` instance is attached to the `Promise` as a `child` property. In <ide> case of an error (including any error resulting in an exit code other than 0), a <ide> rejected promise is returned, with the same `error` object given in the <del>callback, but with an additional two properties `stdout` and `stderr`. <add>callback, but with two additional properties `stdout` and `stderr`. <ide> <ide> ```js <ide> const util = require('util'); <ide> const exec = util.promisify(require('child_process').exec); <ide> async function lsExample() { <ide> const { stdout, stderr } = await exec('ls'); <ide> console.log('stdout:', stdout); <del> console.log('stderr:', stderr); <add> console.error('stderr:', stderr); <ide> } <ide> lsExample(); <ide> ``` <ide> a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned <ide> `ChildProcess` instance is attached to the `Promise` as a `child` property. In <ide> case of an error (including any error resulting in an exit code other than 0), a <ide> rejected promise is returned, with the same `error` object given in the <del>callback, but with an additional two properties `stdout` and `stderr`. <add>callback, but with two additional properties `stdout` and `stderr`. <ide> <ide> ```js <ide> const util = require('util'); <ide> ls.stdout.on('data', (data) => { <ide> }); <ide> <ide> ls.stderr.on('data', (data) => { <del> console.log(`stderr: ${data}`); <add> console.error(`stderr: ${data}`); <ide> }); <ide> <ide> ls.on('close', (code) => { <ide> ps.stdout.on('data', (data) => { <ide> }); <ide> <ide> ps.stderr.on('data', (data) => { <del> console.log(`ps stderr: ${data}`); <add> console.error(`ps stderr: ${data}`); <ide> }); <ide> <ide> ps.on('close', (code) => { <ide> grep.stdout.on('data', (data) => { <ide> }); <ide> <ide> grep.stderr.on('data', (data) => { <del> console.log(`grep stderr: ${data}`); <add> console.error(`grep stderr: ${data}`); <ide> }); <ide> <ide> grep.on('close', (code) => { <ide> const { spawn } = require('child_process'); <ide> const subprocess = spawn('bad_command'); <ide> <ide> subprocess.on('error', (err) => { <del> console.log('Failed to start subprocess.'); <add> console.error('Failed to start subprocess.'); <ide> }); <ide> ``` <ide> <ide> pipes between the parent and child. The value is one of the following: <ide> <ide> 1. `'pipe'` - Create a pipe between the child process and the parent process. <ide> The parent end of the pipe is exposed to the parent as a property on the <del> `child_process` object as [`subprocess.stdio[fd]`][`stdio`]. Pipes created <del> for fds 0 - 2 are also available as [`subprocess.stdin`][], <add> `child_process` object as [`subprocess.stdio[fd]`][`subprocess.stdio`]. Pipes <add> created for fds 0 - 2 are also available as [`subprocess.stdin`][], <ide> [`subprocess.stdout`][] and [`subprocess.stderr`][], respectively. <ide> 2. `'ipc'` - Create an IPC channel for passing messages/file descriptors <ide> between parent and child. A [`ChildProcess`][] may have at most one IPC <ide> pipes between the parent and child. The value is one of the following: <ide> ```js <ide> const { spawn } = require('child_process'); <ide> <del>// Child will use parent's stdios <add>// Child will use parent's stdios. <ide> spawn('prg', [], { stdio: 'inherit' }); <ide> <del>// Spawn child sharing only stderr <add>// Spawn child sharing only stderr. <ide> spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] }); <ide> <ide> // Open an extra fd=4, to interact with programs presenting a <ide> process of being received. This will most often be triggered immediately after <ide> calling `subprocess.disconnect()`. <ide> <ide> When the child process is a Node.js instance (e.g. spawned using <del>[`child_process.fork()`]), the `process.disconnect()` method can be invoked <add>[`child_process.fork()`][]), the `process.disconnect()` method can be invoked <ide> within the child process to close the IPC channel as well. <ide> <ide> ### subprocess.kill([signal]) <ide> grep.on('close', (code, signal) => { <ide> `child process terminated due to receipt of signal ${signal}`); <ide> }); <ide> <del>// Send SIGHUP to process <add>// Send SIGHUP to process. <ide> grep.kill('SIGHUP'); <ide> ``` <ide> <ide> const subprocess = spawn( <ide> ); <ide> <ide> setTimeout(() => { <del> subprocess.kill(); // Does not terminate the node process in the shell <add> subprocess.kill(); // Does not terminate the Node.js process in the shell. <ide> }, 2000); <ide> ``` <ide> <ide> const special = fork('subprocess.js', ['special']); <ide> const server = require('net').createServer({ pauseOnConnect: true }); <ide> server.on('connection', (socket) => { <ide> <del> // If this is special priority <add> // If this is special priority... <ide> if (socket.remoteAddress === '74.125.127.100') { <ide> special.send('socket', socket); <ide> return; <ide> } <del> // This is normal priority <add> // This is normal priority. <ide> normal.send('socket', socket); <ide> }); <ide> server.listen(1337); <ide> const child_process = require('child_process'); <ide> <ide> const subprocess = child_process.spawn('ls', { <ide> stdio: [ <del> 0, // Use parent's stdin for child <del> 'pipe', // Pipe child's stdout to parent <del> fs.openSync('err.out', 'w') // Direct child's stderr to a file <add> 0, // Use parent's stdin for child. <add> 'pipe', // Pipe child's stdout to parent. <add> fs.openSync('err.out', 'w') // Direct child's stderr to a file. <ide> ] <ide> }); <ide> <ide> unavailable. <ide> [`subprocess.send()`]: #child_process_subprocess_send_message_sendhandle_options_callback <ide> [`subprocess.stderr`]: #child_process_subprocess_stderr <ide> [`subprocess.stdin`]: #child_process_subprocess_stdin <add>[`subprocess.stdio`]: #child_process_subprocess_stdio <ide> [`subprocess.stdout`]: #child_process_subprocess_stdout <ide> [`util.promisify()`]: util.html#util_util_promisify_original <ide> [Default Windows Shell]: #child_process_default_windows_shell
1
Javascript
Javascript
add hashes to monaco workers
7a8d6b250461649eb26e25398934972bf809a895
<ide><path>client/gatsby-node.js <ide> exports.onCreateWebpackConfig = ({ stage, plugins, actions }) => { <ide> // involved in SSR. Also, if the plugin is used during the 'build-html' stage <ide> // it overwrites the minfied files with ordinary ones. <ide> if (stage !== 'build-html') { <del> newPlugins.push(new MonacoWebpackPlugin()); <add> newPlugins.push( <add> new MonacoWebpackPlugin({ filename: '[name].worker-[contenthash].js' }) <add> ); <ide> } <ide> actions.setWebpackConfig({ <ide> resolve: {
1
PHP
PHP
define hasabilities trait on default user
72a10c64c2772df7e30cbeb9cfd09d85e9f24f7b
<ide><path>app/User.php <ide> use Illuminate\Auth\Authenticatable; <ide> use Illuminate\Database\Eloquent\Model; <ide> use Illuminate\Auth\Passwords\CanResetPassword; <add>use Illuminate\Foundation\Auth\Access\HasAbilities; <ide> use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; <ide> use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; <ide> <ide> class User extends Model implements AuthenticatableContract, CanResetPasswordContract <ide> { <del> use Authenticatable, CanResetPassword; <add> use Authenticatable, CanResetPassword, HasAbilities; <ide> <ide> /** <ide> * The database table used by the model.
1
PHP
PHP
remove hasproperty() & update doc blocks
10e347d0666523761dd809966e123ec80f757645
<ide><path>src/Datasource/EntityTrait.php <ide> public function getOriginalValues() <ide> * <ide> * ``` <ide> * $entity = new Entity(['id' => 1, 'name' => null]); <del> * $entity->hasProperty('id'); // true <del> * $entity->hasProperty('name'); // false <del> * $entity->hasProperty('last_name'); // false <add> * $entity->has('id'); // true <add> * $entity->has('name'); // false <add> * $entity->has('last_name'); // false <ide> * ``` <ide> * <ide> * You can check multiple properties by passing an array: <ide> * <ide> * ``` <del> * $entity->hasProperty(['name', 'last_name']); <add> * $entity->has(['name', 'last_name']); <ide> * ``` <ide> * <ide> * All properties must not be null to get a truthy result. <ide> public function getOriginalValues() <ide> * @param string|array $property The property or properties to check. <ide> * @return bool <ide> */ <del> public function hasProperty($property) <add> public function has($property) <ide> { <ide> foreach ((array)$property as $prop) { <ide> if ($this->get($prop) === null) { <ide> public function hasProperty($property) <ide> return true; <ide> } <ide> <del> /** <del> * Returns whether this entity contains a property named $property <del> * that contains a non-null value. <del> * <del> * ### Example: <del> * <del> * ``` <del> * $entity = new Entity(['id' => 1, 'name' => null]); <del> * $entity->has('id'); // true <del> * $entity->has('name'); // false <del> * $entity->has('last_name'); // false <del> * ``` <del> * <del> * You can check multiple properties by passing an array: <del> * <del> * ``` <del> * $entity->has(['name', 'last_name']); <del> * ``` <del> * <del> * All properties must not be null to get a truthy result. <del> * <del> * When checking multiple properties. All properties must not be null <del> * in order for true to be returned. <del> * <del> * @param string|array $property The property or properties to check. <del> * @return bool <del> */ <del> public function has($property) <del> { <del> return $this->hasProperty($property); <del> } <del> <ide> /** <ide> * Checks that a property is empty <ide> * <del> * This is not working like the built in empty() of php. The method will <add> * This is not working like the PHP `empty()` function. The method will <ide> * return true for: <ide> * <del> * - '' (empty string) <del> * - null <del> * - [] <add> * - `''` (empty string) <add> * - `null` <add> * - `[]` <ide> * <del> * but false on any other case. <add> * and false in all other cases. <ide> * <ide> * @param string $property The property to check. <ide> * @return bool <ide> public function isEmpty($property) <ide> * <ide> * This method will return true for <ide> * <del> * - 'foo' (non empty string) <del> * - ['foo', 'bar'] <del> * - Object <del> * - Integer, even 0 (Zero) <del> * - Float <add> * - Non-empty strings <add> * - Non-empty arrays <add> * - Any object <add> * - Integer, even `0` <add> * - Float, even 0.0 <ide> * <del> * false on any other case <add> * and false in all other cases. <ide> * <ide> * @param string $property The property to check. <ide> * @return bool <ide><path>tests/TestCase/ORM/EntityTest.php <ide> public function testIndirectModification() <ide> public function testHas() <ide> { <ide> $entity = new Entity(['id' => 1, 'name' => 'Juan', 'foo' => null]); <del> $this->assertTrue($entity->hasProperty('id')); <del> $this->assertTrue($entity->hasProperty('name')); <del> $this->assertFalse($entity->hasProperty('foo')); <del> $this->assertFalse($entity->hasProperty('last_name')); <add> $this->assertTrue($entity->has('id')); <add> $this->assertTrue($entity->has('name')); <add> $this->assertFalse($entity->has('foo')); <add> $this->assertFalse($entity->has('last_name')); <ide> <del> $this->assertTrue($entity->hasProperty(['id'])); <del> $this->assertTrue($entity->hasProperty(['id', 'name'])); <del> $this->assertFalse($entity->hasProperty(['id', 'foo'])); <del> $this->assertFalse($entity->hasProperty(['id', 'nope'])); <add> $this->assertTrue($entity->has(['id'])); <add> $this->assertTrue($entity->has(['id', 'name'])); <add> $this->assertFalse($entity->has(['id', 'foo'])); <add> $this->assertFalse($entity->has(['id', 'nope'])); <ide> <ide> $entity = $this->getMockBuilder('\Cake\ORM\Entity') <ide> ->setMethods(['_getThings']) <ide> ->getMock(); <ide> $entity->expects($this->once())->method('_getThings') <ide> ->will($this->returnValue(0)); <del> $this->assertTrue($entity->hasProperty('things')); <add> $this->assertTrue($entity->has('things')); <ide> } <ide> <ide> /**
2
Javascript
Javascript
use process.hrtime() for clock in node.js builds
4691b5f1b0460bfc5c0e26c28e8f7a8fa9acca05
<ide><path>utils/npm/header.js <ide> <ide> var window = window || {}; <ide> var self = self || {}; <add> <add>// High-resulution counter: emulate window.performance.now() for THREE.CLOCK <add>if( window.performance === undefined ) { <add> <add> window.performance = { }; <add> <add>} <add> <add>if( window.performance.now === undefined ) { <add> <add> window.performance.now = function () { <add> <add> var time = process.hrtime(); <add> return ( time[0] + time[1] / 1e9 ) * 1000; <add> <add> }; <add> <add>}
1
Ruby
Ruby
need the byte helpers
8d17bb4bb01600711d144a643d608c2fba95b9b3
<ide><path>lib/active_storage/service/disk_service.rb <ide> require "fileutils" <ide> require "pathname" <add>require "active_support/core_ext/numeric/bytes" <ide> <ide> class ActiveStorage::Service::DiskService < ActiveStorage::Service <ide> attr_reader :root <ide><path>lib/active_storage/service/s3_service.rb <ide> require "aws-sdk" <add>require "active_support/core_ext/numeric/bytes" <ide> <ide> class ActiveStorage::Service::S3Service < ActiveStorage::Service <ide> attr_reader :client, :bucket
2
PHP
PHP
add test case
d083346a1278b9d09414824bc10deb6c5b3502cb
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testDatetimeEmptyArrayForm() <ide> $this->assertHtml($expected, $result); <ide> } <ide> <add> /** <add> * Test datetime with array empty value, ensuring <add> * empty options aren't duplicated. <add> * <add> * @return void <add> */ <add> public function testDatetimeEmptyArrayFormKeyValue() <add> { <add> extract($this->dateRegex); <add> <add> $result = $this->Form->dateTime('Contact.date', [ <add> 'minYear' => '2017', <add> 'maxYear' => '2019', <add> 'empty' => [ <add> '' => '-', <add> ], <add> 'hour' => false, <add> 'minute' => false, <add> 'second' => false, <add> 'meridian' => false, <add> ]); <add> $expected = [ <add> ['select' => ['name' => 'Contact[date][year]']], <add> ['option' => ['value' => '', 'selected' => 'selected']], '-', '/option', <add> '*/select', <add> <add> ['select' => ['name' => 'Contact[date][month]']], <add> ['option' => ['value' => '', 'selected' => 'selected']], '-', '/option', <add> $monthsRegex, <add> '*/select', <add> <add> ['select' => ['name' => 'Contact[date][day]']], <add> ['option' => ['value' => '', 'selected' => 'selected']], '-', '/option', <add> $daysRegex, <add> '*/select', <add> ]; <add> $this->assertHtml($expected, $result); <add> } <add> <ide> /** <ide> * testDatetimeMinuteInterval method <ide> *
1
Ruby
Ruby
use new finder methods for association preloading
cfdfd899262c79c37ac89e030f4d90c8f9868b50
<ide><path>activerecord/lib/active_record/association_preload.rb <ide> def preload_has_and_belongs_to_many_association(records, reflection, preload_opt <ide> conditions << append_conditions(reflection, preload_options) <ide> <ide> associated_records = reflection.klass.with_exclusive_scope do <del> reflection.klass.find(:all, :conditions => [conditions, ids], <del> :include => options[:include], <del> :joins => "INNER JOIN #{connection.quote_table_name options[:join_table]} t0 ON #{reflection.klass.quoted_table_name}.#{reflection.klass.primary_key} = t0.#{reflection.association_foreign_key}", <del> :select => "#{options[:select] || table_name+'.*'}, t0.#{reflection.primary_key_name} as the_parent_record_id", <del> :order => options[:order]) <add> reflection.klass.where([conditions, ids]). <add> includes(options[:include]). <add> joins("INNER JOIN #{connection.quote_table_name options[:join_table]} t0 ON #{reflection.klass.quoted_table_name}.#{reflection.klass.primary_key} = t0.#{reflection.association_foreign_key}"). <add> select("#{options[:select] || table_name+'.*'}, t0.#{reflection.primary_key_name} as the_parent_record_id"). <add> order(options[:order]).to_a <ide> end <ide> set_association_collection_records(id_to_record_map, reflection.name, associated_records, 'the_parent_record_id') <ide> end <ide> def preload_belongs_to_association(records, reflection, preload_options={}) <ide> table_name = klass.quoted_table_name <ide> primary_key = klass.primary_key <ide> column_type = klass.columns.detect{|c| c.name == primary_key}.type <add> <ide> ids = id_map.keys.map do |id| <ide> if column_type == :integer <ide> id.to_i <ide> def preload_belongs_to_association(records, reflection, preload_options={}) <ide> id <ide> end <ide> end <add> <ide> conditions = "#{table_name}.#{connection.quote_column_name(primary_key)} #{in_or_equals_for_ids(ids)}" <ide> conditions << append_conditions(reflection, preload_options) <add> <ide> associated_records = klass.with_exclusive_scope do <del> klass.find(:all, :conditions => [conditions, ids], <del> :include => options[:include], <del> :select => options[:select], <del> :joins => options[:joins], <del> :order => options[:order]) <add> klass.where([conditions, ids]).apply_finder_options(options.slice(:include, :select, :joins, :order)).to_a <ide> end <add> <ide> set_association_single_records(id_map, reflection.name, associated_records, primary_key) <ide> end <ide> end <ide> def find_associated_records(ids, reflection, preload_options) <ide> conditions << append_conditions(reflection, preload_options) <ide> <ide> reflection.klass.with_exclusive_scope do <del> reflection.klass.find(:all, <del> :select => (preload_options[:select] || options[:select] || "#{table_name}.*"), <del> :include => preload_options[:include] || options[:include], <del> :conditions => [conditions, ids], <del> :joins => options[:joins], <del> :group => preload_options[:group] || options[:group], <del> :order => preload_options[:order] || options[:order]) <add> reflection.klass.select(preload_options[:select] || options[:select] || "#{table_name}.*"). <add> includes(preload_options[:include] || options[:include]). <add> where([conditions, ids]). <add> joins(options[:joins]). <add> group(preload_options[:group] || options[:group]). <add> order(preload_options[:order] || options[:order]) <ide> end <ide> end <ide>
1
Javascript
Javascript
remove unreachable code
58066d16d56ea58d4139bc865349fec9346b12ba
<ide><path>lib/events.js <ide> EventEmitter.prototype.removeListener = <ide> if (position < 0) <ide> return this; <ide> <del> if (list.length === 1) { <del> if (--this._eventsCount === 0) { <del> this._events = Object.create(null); <del> return this; <del> } else { <del> delete events[type]; <del> } <del> } else if (position === 0) { <add> if (position === 0) <ide> list.shift(); <del> if (list.length === 1) <del> events[type] = list[0]; <del> } else { <add> else <ide> spliceOne(list, position); <del> if (list.length === 1) <del> events[type] = list[0]; <del> } <add> <add> if (list.length === 1) <add> events[type] = list[0]; <ide> <ide> if (events.removeListener) <ide> this.emit('removeListener', type, originalListener || listener);
1
Go
Go
switch swarmmode services to nanocpu
8a60a1e14a5e98b7ed0fbea57369615a766a1ae9
<ide><path>daemon/cluster/executor/container/container.go <ide> import ( <ide> "net" <ide> "strconv" <ide> "strings" <del> "time" <ide> <ide> "github.com/sirupsen/logrus" <ide> <ide> import ( <ide> ) <ide> <ide> const ( <del> // Explicitly use the kernel's default setting for CPU quota of 100ms. <del> // https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt <del> cpuQuotaPeriod = 100 * time.Millisecond <del> <ide> // systemLabelPrefix represents the reserved namespace for system labels. <ide> systemLabelPrefix = "com.docker.swarm" <ide> ) <ide> func (c *containerConfig) resources() enginecontainer.Resources { <ide> } <ide> <ide> if r.Limits.NanoCPUs > 0 { <del> // CPU Period must be set in microseconds. <del> resources.CPUPeriod = int64(cpuQuotaPeriod / time.Microsecond) <del> resources.CPUQuota = r.Limits.NanoCPUs * resources.CPUPeriod / 1e9 <add> resources.NanoCPUs = r.Limits.NanoCPUs <ide> } <ide> <ide> return resources
1
Mixed
Ruby
update counter cache when pushing into association
1e27f1c5d5d177089fbda03ba31f2f55fa622a39
<ide><path>activerecord/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <add>* Fix for a regression bug in which counter cache columns were not being updated <add> when record was pushed into a has_many association. For example: <add> <add> Post.first.comments << Comment.create <add> <add> Fixes #3891. <add> <add> *Matthew Robertson* <add> <ide> * If a model was instantiated from the database using `select`, `respond_to?` <ide> returns false for non-selected attributes. For example: <ide> <ide><path>activerecord/lib/active_record/associations/builder/belongs_to.rb <ide> def add_counter_cache_callbacks(reflection) <ide> <ide> mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 <ide> def belongs_to_counter_cache_after_create_for_#{name} <del> record = #{name} <del> record.class.increment_counter(:#{cache_column}, record.id) unless record.nil? <del> @_after_create_counter_called = true <add> if record = #{name} <add> record.class.increment_counter(:#{cache_column}, record.id) <add> @_after_create_counter_called = true <add> end <ide> end <ide> <ide> def belongs_to_counter_cache_before_destroy_for_#{name} <ide><path>activerecord/test/cases/associations/has_many_associations_test.rb <ide> def test_deleting_updates_counter_cache <ide> assert_equal topic.replies.to_a.size, topic.replies_count <ide> end <ide> <add> def test_pushing_association_updates_counter_cache <add> topic = Topic.order("id ASC").first <add> reply = Reply.create! <add> <add> assert_difference "topic.reload.replies_count", 1 do <add> topic.replies << reply <add> end <add> end <add> <ide> def test_deleting_updates_counter_cache_without_dependent_option <ide> post = posts(:welcome) <ide>
3
Text
Text
add link to triage guide
aaed4381651588feb8eb0b29a8d48a75a366e767
<ide><path>README.md <ide> maintaining the Node.js project. <ide> * [VoltrexMaster](https://github.com/VoltrexMaster) - <ide> **Mohammed Keyvanzadeh** <<[email protected]>> (he/him) <ide> <add>Triagers follow the [Triage Guide](./doc/contributing/issues.md#triaging-a-bug-report) when <add>responding to new issues. <add> <ide> ### Release keys <ide> <ide> Primary GPG keys for Node.js Releasers (some Releasers sign with subkeys):
1
Ruby
Ruby
remove extra class_eval for ruby 1.9
fc12655be5affa692a80d9439e93c7e897f06eef
<ide><path>activesupport/lib/active_support/core_ext/module/attr_internal.rb <ide> def attr_internal_ivar_name(attr) <ide> <ide> def attr_internal_define(attr_name, type) <ide> internal_name = attr_internal_ivar_name(attr_name).sub(/\A@/, '') <del> # class_eval is necessary on 1.9 or else the methods are made private <del> class_eval do <del> # use native attr_* methods as they are faster on some Ruby implementations <del> send("attr_#{type}", internal_name) <del> end <add> # use native attr_* methods as they are faster on some Ruby implementations <add> send("attr_#{type}", internal_name) <ide> attr_name, internal_name = "#{attr_name}=", "#{internal_name}=" if type == :writer <ide> alias_method attr_name, internal_name <ide> remove_method internal_name
1
Python
Python
fix openstack tests
404e73a7252d41a5c572f89916544029b1e4d08d
<ide><path>libcloud/test/__init__.py <ide> def __init__(self, action): <ide> StorageMockHttp = MockHttp <ide> <ide> <del>def make_response(status=200, headers={}, connection=None): <add>def make_response(status=200, headers={}, body=None, connection=None): <ide> response = requests.Response() <ide> response.status_code = status <ide> response.headers = headers <add> response.text = body <ide> return Response(response, connection) <ide> <ide> <ide><path>libcloud/test/compute/test_openstack.py <ide> from libcloud.pricing import set_pricing, clear_pricing_data <ide> <ide> from libcloud.common.base import Response <del>from libcloud.test import MockHttp, XML_HEADERS <add>from libcloud.test import MockHttp, XML_HEADERS, make_response <ide> from libcloud.test.file_fixtures import ComputeFileFixtures, OpenStackFixtures <ide> from libcloud.test.compute import TestCaseMixin <ide> <ide> BASE_DIR = os.path.abspath(os.path.split(__file__)[0]) <ide> <ide> <del>class OpenStack_1_0_ResponseTestCase(unittest.TestCase): <del> XML = """<?xml version="1.0" encoding="UTF-8"?><root/>""" <del> <del> def test_simple_xml_content_type_handling(self): <del> http_response = Response(200, <del> OpenStack_1_0_ResponseTestCase.XML, headers={'content-type': 'application/xml'}) <del> body = OpenStack_1_0_Response(http_response, None).parse_body() <del> <del> self.assertTrue(hasattr(body, 'tag'), "Body should be parsed as XML") <del> <del> def test_extended_xml_content_type_handling(self): <del> http_response = Response(200, <del> OpenStack_1_0_ResponseTestCase.XML, <del> headers={'content-type': 'application/xml; charset=UTF-8'}) <del> body = OpenStack_1_0_Response(http_response, None).parse_body() <del> <del> self.assertTrue(hasattr(body, 'tag'), "Body should be parsed as XML") <del> <del> def test_non_xml_content_type_handling(self): <del> RESPONSE_BODY = "Accepted" <del> <del> http_response = Response(202, RESPONSE_BODY, headers={'content-type': 'text/html'}) <del> body = OpenStack_1_0_Response(http_response, None).parse_body() <del> <del> self.assertEqual( <del> body, RESPONSE_BODY, "Non-XML body should be returned as is") <del> <del> <ide> class OpenStack_1_0_Tests(TestCaseMixin): <ide> should_list_locations = False <ide> should_list_volumes = False <ide> class OpenStack_1_1_FactoryMethodTests(OpenStack_1_1_Tests): <ide> driver_kwargs = {'ex_force_auth_version': '2.0'} <ide> <ide> <del>class OpenStack_1_1_MockHttp(MockHttp): <add>class OpenStack_1_1_MockHttp(MockHttp, unittest.TestCase): <ide> fixtures = ComputeFileFixtures('openstack_v1.1') <ide> auth_fixtures = OpenStackFixtures() <ide> json_content_headers = {'content-type': 'application/json; charset=UTF-8'}
2
Javascript
Javascript
add missing test flags
2097a6fc053823a8585cdbe858ade70f62c6bb1d
<ide><path>test/wasi/test-wasi-start-validation.js <add>// Flags: --experimental-wasi-unstable-preview0 <ide> 'use strict'; <ide> <ide> require('../common');
1
PHP
PHP
apply fixes from styleci
e12cb1327ee652180a8fa918e025aa1f6a5d173e
<ide><path>tests/Foundation/FoundationApplicationTest.php <ide> use Illuminate\Foundation\Application; <ide> use Illuminate\Foundation\Bootstrap\RegisterFacades; <ide> use Illuminate\Foundation\Events\LocaleUpdated; <del>use Illuminate\Support\Facades\App; <ide> use Illuminate\Support\ServiceProvider; <ide> use Mockery as m; <ide> use PHPUnit\Framework\TestCase; <ide> public function testEnvPathsAreAbsoluteInWindows() <ide> ); <ide> } <ide> <del> /** @test */ <del> public function testMacroable(): void <del> { <del> $app = new Application; <del> $app['env'] = 'foo'; <add> /** @test */ <add> public function testMacroable(): void <add> { <add> $app = new Application; <add> $app['env'] = 'foo'; <ide> <del> $app->macro('foo', function() { <del> return $this->environment('foo'); <del> }); <add> $app->macro('foo', function () { <add> return $this->environment('foo'); <add> }); <ide> <del> $this->assertTrue($app->foo()); <add> $this->assertTrue($app->foo()); <ide> <del> $app['env'] = 'bar'; <add> $app['env'] = 'bar'; <ide> <del> $this->assertFalse($app->foo()); <del> } <add> $this->assertFalse($app->foo()); <add> } <ide> } <ide> <ide> class ApplicationBasicServiceProviderStub extends ServiceProvider
1
Text
Text
improve sigint error text
91f05448894e07831eb91118e5ab361a1c350116
<ide><path>doc/api/errors.md <ide> An attempt was made to `require()` an [ES Module][]. <ide> <a id="ERR_SCRIPT_EXECUTION_INTERRUPTED"></a> <ide> ### `ERR_SCRIPT_EXECUTION_INTERRUPTED` <ide> <del>Script execution was interrupted by `SIGINT` (For example, when Ctrl+C was <del>pressed). <add>Script execution was interrupted by `SIGINT` (For example, <add><kbd>Ctrl</kbd>+<kbd>C</kbd> was pressed.) <ide> <ide> <a id="ERR_SCRIPT_EXECUTION_TIMEOUT"></a> <ide> ### `ERR_SCRIPT_EXECUTION_TIMEOUT`
1
PHP
PHP
allow fallback_locale in translator
bf062fee1e0b67b2d646f37a7ef734ea5391c34c
<ide><path>src/Illuminate/Translation/TranslationServiceProvider.php <ide> public function register() <ide> <ide> $trans = new Translator($loader, $locale); <ide> <add> $trans->setFallback($app['config']['app.fallback_locale']); <add> <ide> return $trans; <ide> }); <ide> } <ide><path>src/Illuminate/Translation/Translator.php <ide> class Translator extends NamespacedItemResolver implements TranslatorInterface { <ide> */ <ide> protected $locale; <ide> <add> /** <add> * The fallback locale used by the translator. <add> * <add> * @var string <add> */ <add> protected $fallback; <add> <ide> /** <ide> * The array of loaded translation groups. <ide> * <ide> public function get($key, array $replace = array(), $locale = null) <ide> // Here we will get the locale that should be used for the language line. If one <ide> // was not passed, we will use the default locales which was given to us when <ide> // the translator was instantiated. Then, we can load the lines and return. <del> $locale = $locale ?: $this->getLocale(); <add> foreach ($this->parseLocale($locale) as $locale) <add> { <add> $this->load($namespace, $group, $locale); <ide> <del> $this->load($namespace, $group, $locale); <add> $line = $this->getLine( <add> $namespace, $group, $locale, $item, $replace <add> ); <ide> <del> $line = $this->getLine( <del> $namespace, $group, $locale, $item, $replace <del> ); <add> if ( ! is_null($line)) break; <add> } <ide> <ide> // If the line doesn't exist, we will return back the key which was requested as <ide> // that will be quick to spot in the UI if language keys are wrong or missing <ide> public function parseKey($key) <ide> return $segments; <ide> } <ide> <add> /** <add> * Get the array of locales to be checked. <add> * <add> * @return array <add> */ <add> protected function parseLocale($locale) <add> { <add> if ( ! is_null($locale)) <add> { <add> return array_filter(array($locale, $this->fallback)); <add> } <add> else <add> { <add> return array_filter(array($this->locale, $this->fallback)); <add> } <add> } <add> <ide> /** <ide> * Get the message selector instance. <ide> * <ide> public function setLocale($locale) <ide> $this->locale = $locale; <ide> } <ide> <add> /** <add> * Set the fallback locale being used. <add> * <add> * @return string <add> */ <add> public function getFallback() <add> { <add> return $this->fallback; <add> } <add> <add> /** <add> * Set the fallback locale being used. <add> * <add> * @param string $fallback <add> * @return void <add> */ <add> public function setFallback($fallback) <add> { <add> $this->fallback = $fallback; <add> } <add> <ide> }
2
Python
Python
capitalize occurrences of 'flask'
77af942b982a3b07669362cc6bc223026bf039cd
<ide><path>flask/__init__.py <ide> # it. <ide> from . import json <ide> <del># This was the only thing that flask used to export at one point and it had <add># This was the only thing that Flask used to export at one point and it had <ide> # a more generic name. <ide> jsonify = json.jsonify <ide> <ide><path>flask/cli.py <ide> def get_version(ctx, param, value): <ide> is_flag=True, is_eager=True) <ide> <ide> class DispatchingApp(object): <del> """Special application that dispatches to a flask application which <add> """Special application that dispatches to a Flask application which <ide> is imported by name in a background thread. If an error happens <del> it is is recorded and shows as part of the WSGI handling which in case <add> it is recorded and shown as part of the WSGI handling which in case <ide> of the Werkzeug debugger means that it shows up in the browser. <ide> """ <ide> <ide><path>flask/sessions.py <ide> class Session(dict, SessionMixin): <ide> null_session_class = NullSession <ide> <ide> #: A flag that indicates if the session interface is pickle based. <del> #: This can be used by flask extensions to make a decision in regards <add> #: This can be used by Flask extensions to make a decision in regards <ide> #: to how to deal with the session object. <ide> #: <ide> #: .. versionadded:: 0.10 <ide><path>flask/signals.py <ide> def _fail(self, *args, **kwargs): <ide> temporarily_connected_to = connected_to = _fail <ide> del _fail <ide> <del># The namespace for code signals. If you are not flask code, do <add># The namespace for code signals. If you are not Flask code, do <ide> # not put signals in here. Create your own namespace instead. <ide> _signals = Namespace() <ide>
4
Python
Python
add regression test for
2251993805670563e641cfcc420de302930ba190
<ide><path>numpy/core/tests/test_regression.py <ide> def test_misaligned_objects_segfault(self): <ide> a2 = np.zeros((10,), 'S10') <ide> a1['o'] = a2 <ide> <add> def test_byteswap_complex_scalar(self): <add> """Ticket #1259""" <add> x = np.array([-1j], '<c8') <add> y = x[0].byteswap() <add> assert_equal(x, np.fromstring(y.tostring(), dtype='>c8')) <add> <ide> if __name__ == "__main__": <ide> run_module_suite()
1
Python
Python
remove duplicated code (function extract rmap)
6ef5ec39cdfaf77aa4600ec2e3bf9f679a4fd527
<ide><path>numpy/lib/arraypad.py <ide> def _get_linear_ramps(padded, axis, width_pair, end_value_pair): <ide> """ <ide> edge_pair = _get_edges(padded, axis, width_pair) <ide> <del> left_ramp = np.linspace( <del> start=end_value_pair[0], <del> stop=edge_pair[0].squeeze(axis), # Dimensions is replaced by linspace <del> num=width_pair[0], <del> endpoint=False, <del> dtype=padded.dtype, <del> axis=axis, <del> ) <del> <del> right_ramp = np.linspace( <del> start=end_value_pair[1], <del> stop=edge_pair[1].squeeze(axis), # Dimension is replaced by linspace <del> num=width_pair[1], <del> endpoint=False, <del> dtype=padded.dtype, <del> axis=axis, <add> left_ramp, right_ramp = ( <add> np.linspace( <add> start=end_value, <add> stop=edge.squeeze(axis), # Dimension is replaced by linspace <add> num=width, <add> endpoint=False, <add> dtype=padded.dtype, <add> axis=axis <add> ) <add> for end_value, edge, width in zip( <add> end_value_pair, edge_pair, width_pair <add> ) <ide> ) <add> <ide> # Reverse linear space in appropriate dimension <ide> right_ramp = right_ramp[_slice_at_axis(slice(None, None, -1), axis)] <ide>
1
Python
Python
apply copy only to guaranteed dict
c15adf9944558b25fc74e14827c9720fbf00be5f
<ide><path>keras/engine/compile_utils.py <ide> def __init__(self, losses, loss_weights=None, output_names=None): <ide> self._user_losses = losses <ide> self._user_loss_weights = loss_weights <ide> <del> self._losses = copy.copy(losses) <add> self._losses = losses <ide> self._loss_weights = loss_weights <ide> self._per_output_metrics = None # Per-output losses become metrics. <ide> self._loss_metric = metrics_mod.Mean(name='loss') # Total loss. <ide> def __init__(self, metrics=None, weighted_metrics=None, output_names=None, <ide> self._user_metrics = metrics <ide> self._user_weighted_metrics = weighted_metrics <ide> <del> self._metrics = copy.copy(metrics) <add> self._metrics = metrics <ide> self._weighted_metrics = weighted_metrics <ide> self._built = False <ide> <ide> def map_missing_dict_keys(y_pred, struct): <ide> """Replaces missing dict keys in `struct` with `None` placeholders.""" <ide> if not isinstance(y_pred, dict) or not isinstance(struct, dict): <ide> return struct <add> struct = copy.copy(struct) <ide> for k in y_pred.keys(): <ide> if k not in struct: <ide> struct[k] = None
1
Go
Go
add partial flag into record
3ed3b33e558490db088103404e03539f5a3df832
<ide><path>daemon/logger/fluentd/fluentd.go <ide> func (f *fluentd) Log(msg *logger.Message) error { <ide> for k, v := range f.extra { <ide> data[k] = v <ide> } <add> if msg.Partial { <add> data["partial_message"] = "true" <add> } <ide> <ide> ts := msg.Timestamp <ide> logger.PutMessage(msg)
1
Python
Python
remove inaccurate comment regarding language names
efa3f71cc4d35afe7e1ca479de2eca7808215d6f
<ide><path>django/conf/global_settings.py <ide> # http://www.i18nguy.com/unicode/language-identifiers.html <ide> LANGUAGE_CODE = 'en-us' <ide> <del># Languages we provide translations for, out of the box. The language name <del># should be the utf-8 encoded local name for the language. <add># Languages we provide translations for, out of the box. <ide> LANGUAGES = ( <ide> ('ar', gettext_noop('Arabic')), <ide> ('az', gettext_noop('Azerbaijani')),
1
PHP
PHP
fix merge conflicts
8fc1942fcb11fdd5f501a959accd23f3c10ca1e7
<ide><path>src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php <ide> protected function runningUnitTests() <ide> */ <ide> protected function tokensMatch($request) <ide> { <add> $sessionToken = $request->session()->token(); <add> <ide> $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN'); <ide> <ide> if (! $token && $header = $request->header('X-XSRF-TOKEN')) { <ide> $token = $this->encrypter->decrypt($header); <ide> } <ide> <add> if (! is_string($sessionToken) || ! is_string($token)) { <add> return false; <add> } <add> <ide> return hash_equals((string) $request->session()->token(), (string) $token); <ide> } <ide> <ide><path>src/Illuminate/Queue/Connectors/SqsConnector.php <ide> class SqsConnector implements ConnectorInterface <ide> */ <ide> public function connect(array $config) <ide> { <del> $config = array_merge([ <add> $config = $this->getDefaultConfiguration($config); <add> <add> if ($config['key'] && $config['secret']) { <add> $config['credentials'] = Arr::only($config, ['key', 'secret']); <add> } <add> <add> return new SqsQueue( <add> new SqsClient($config), $config['queue'], Arr::get($config, 'prefix', '') <add> ); <add> } <add> <add> /** <add> * Get the default configuration for SQS. <add> * <add> * @param array $config <add> * @return array <add> */ <add> protected function getDefaultConfiguration(array $config) <add> { <add> return array_merge([ <ide> 'version' => 'latest', <ide> 'http' => [ <ide> 'timeout' => 60, <ide> 'connect_timeout' => 60, <ide> ], <ide> ], $config); <del> <del> if ($config['key'] && $config['secret']) { <del> $config['credentials'] = Arr::only($config, ['key', 'secret']); <del> } <del> <del> return new SqsQueue(new SqsClient($config), $config['queue']); <ide> } <ide> } <ide><path>src/Illuminate/Queue/SqsQueue.php <ide> class SqsQueue extends Queue implements QueueContract <ide> */ <ide> protected $default; <ide> <add> /** <add> * The sqs prefix url. <add> * <add> * @var string <add> */ <add> protected $prefix; <add> <ide> /** <ide> * The job creator callback. <ide> * <ide> class SqsQueue extends Queue implements QueueContract <ide> * <ide> * @param \Aws\Sqs\SqsClient $sqs <ide> * @param string $default <add> * @param string $prefix <ide> * @return void <ide> */ <del> public function __construct(SqsClient $sqs, $default) <add> public function __construct(SqsClient $sqs, $default, $prefix = '') <ide> { <ide> $this->sqs = $sqs; <add> $this->prefix = $prefix; <ide> $this->default = $default; <ide> } <ide> <ide> public function createJobsUsing(callable $callback) <ide> */ <ide> public function getQueue($queue) <ide> { <del> return $queue ?: $this->default; <add> if (filter_var($queue, FILTER_VALIDATE_URL) !== false) { <add> return $queue; <add> } <add> <add> return rtrim($this->prefix, '/').'/'.($queue ?: $this->default); <ide> } <ide> <ide> /** <ide><path>tests/Queue/QueueSqsQueueTest.php <ide> public function testPushProperlyPushesJobOntoSqs() <ide> $id = $queue->push($this->mockedJob, $this->mockedData, $this->queueName); <ide> $this->assertEquals($this->mockedMessageId, $id); <ide> } <add> <add> public function testGetQueueProperlyResolvesName() <add> { <add> $queue = new Illuminate\Queue\SqsQueue($this->sqs, $this->queueName, $this->baseUrl.'/'.$this->account.'/'); <add> $this->assertEquals($this->queueUrl, $queue->getQueue($this->queueName)); <add> $queueUrl = $this->baseUrl.'/'.$this->account.'/test'; <add> $this->assertEquals($queueUrl, $queue->getQueue($queueUrl)); <add> } <ide> }
4
Java
Java
fix regression in classpathresource descriptions
b50f6e19a6820a8e735a89dfee1a85077e804ec5
<ide><path>spring-core/src/main/java/org/springframework/core/io/ClassPathResource.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> * Always supports resolution as URL. <ide> * <ide> * @author Juergen Hoeller <add> * @author Sam Brannen <ide> * @since 28.12.2003 <ide> * @see java.lang.ClassLoader#getResourceAsStream(String) <ide> * @see java.lang.Class#getResourceAsStream(String) <ide> protected ClassPathResource(String path, ClassLoader classLoader, Class<?> clazz <ide> this.clazz = clazz; <ide> } <ide> <del> <ide> /** <ide> * Return the path for this resource (as resource path within the class path). <ide> */ <ide> public final ClassLoader getClassLoader() { <ide> return (this.classLoader != null ? this.classLoader : this.clazz.getClassLoader()); <ide> } <ide> <del> <ide> /** <ide> * This implementation checks for the resolution of a resource URL. <ide> * @see java.lang.ClassLoader#getResource(String) <ide> public InputStream getInputStream() throws IOException { <ide> is = this.classLoader.getResourceAsStream(this.path); <ide> } <ide> if (is == null) { <del> throw new FileNotFoundException( <del> getDescription() + " cannot be opened because it does not exist"); <add> throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist"); <ide> } <ide> return is; <ide> } <ide> public URL getURL() throws IOException { <ide> url = this.classLoader.getResource(this.path); <ide> } <ide> if (url == null) { <del> throw new FileNotFoundException( <del> getDescription() + " cannot be resolved to URL because it does not exist"); <add> throw new FileNotFoundException(getDescription() + " cannot be resolved to URL because it does not exist"); <ide> } <ide> return url; <ide> } <ide> public String getFilename() { <ide> public String getDescription() { <ide> StringBuilder builder = new StringBuilder("class path resource ["); <ide> <del> if (this.clazz != null) { <add> String pathToUse = path; <add> <add> if (this.clazz != null && !pathToUse.startsWith("/")) { <ide> builder.append(ClassUtils.classPackageAsResourcePath(this.clazz)); <ide> builder.append('/'); <ide> } <ide> <del> builder.append(this.path); <add> if (pathToUse.startsWith("/")) { <add> pathToUse = pathToUse.substring(1); <add> } <add> <add> builder.append(pathToUse); <ide> builder.append(']'); <ide> return builder.toString(); <ide> } <ide> <del> <ide> /** <ide> * This implementation compares the underlying class path locations. <ide> */ <ide> public boolean equals(Object obj) { <ide> } <ide> if (obj instanceof ClassPathResource) { <ide> ClassPathResource otherRes = (ClassPathResource) obj; <del> return (this.path.equals(otherRes.path) && <del> ObjectUtils.nullSafeEquals(this.classLoader, otherRes.classLoader) && <del> ObjectUtils.nullSafeEquals(this.clazz, otherRes.clazz)); <add> return (this.path.equals(otherRes.path) <add> && ObjectUtils.nullSafeEquals(this.classLoader, otherRes.classLoader) && ObjectUtils.nullSafeEquals( <add> this.clazz, otherRes.clazz)); <ide> } <ide> return false; <ide> } <ide><path>spring-core/src/test/java/org/springframework/core/io/ClassPathResourceTests.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> package org.springframework.core.io; <ide> <ide> import static org.hamcrest.CoreMatchers.instanceOf; <add>import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.assertThat; <add>import static org.junit.Assert.assertTrue; <ide> import static org.junit.Assert.fail; <ide> import static org.junit.internal.matchers.StringContains.containsString; <ide> <ide> import java.io.FileNotFoundException; <ide> import java.io.IOException; <add>import java.util.regex.Matcher; <add>import java.util.regex.Pattern; <ide> <ide> import org.junit.Test; <ide> <ide> /** <del> * Unit tests cornering bug SPR-6888. <add> * Unit tests that serve as regression tests for the bugs described in SPR-6888 <add> * and SPR-9413. <ide> * <ide> * @author Chris Beams <add> * @author Sam Brannen <ide> */ <ide> public class ClassPathResourceTests { <add> <ide> private static final String PACKAGE_PATH = "org/springframework/core/io"; <del> private static final String RESOURCE_NAME = "notexist.xml"; <del> private static final String FQ_RESOURCE_PATH = PACKAGE_PATH + '/' + RESOURCE_NAME; <add> private static final String NONEXISTENT_RESOURCE_NAME = "nonexistent.xml"; <add> private static final String FQ_RESOURCE_PATH = PACKAGE_PATH + '/' + NONEXISTENT_RESOURCE_NAME; <add> <add> /** <add> * Absolute path version of {@link #FQ_RESOURCE_PATH}. <add> */ <add> private static final String FQ_RESOURCE_PATH_WITH_LEADING_SLASH = '/' + FQ_RESOURCE_PATH; <add> <add> private static final Pattern DESCRIPTION_PATTERN = Pattern.compile("^class path resource \\[(.+?)\\]$"); <add> <add> <add> private void assertDescriptionContainsExpectedPath(ClassPathResource resource, String expectedPath) { <add> Matcher matcher = DESCRIPTION_PATTERN.matcher(resource.getDescription()); <add> assertTrue(matcher.matches()); <add> assertEquals(1, matcher.groupCount()); <add> String match = matcher.group(1); <add> <add> assertEquals(expectedPath, match); <add> } <add> <add> private void assertExceptionContainsFullyQualifiedPath(ClassPathResource resource) { <add> try { <add> resource.getInputStream(); <add> fail("FileNotFoundException expected for resource: " + resource); <add> } <add> catch (IOException ex) { <add> assertThat(ex, instanceOf(FileNotFoundException.class)); <add> assertThat(ex.getMessage(), containsString(FQ_RESOURCE_PATH)); <add> } <add> } <ide> <ide> @Test <ide> public void stringConstructorRaisesExceptionWithFullyQualifiedPath() { <ide> public void stringConstructorRaisesExceptionWithFullyQualifiedPath() { <ide> <ide> @Test <ide> public void classLiteralConstructorRaisesExceptionWithFullyQualifiedPath() { <del> assertExceptionContainsFullyQualifiedPath(new ClassPathResource(RESOURCE_NAME, this.getClass())); <add> assertExceptionContainsFullyQualifiedPath(new ClassPathResource(NONEXISTENT_RESOURCE_NAME, this.getClass())); <ide> } <ide> <ide> @Test <ide> public void classLoaderConstructorRaisesExceptionWithFullyQualifiedPath() { <del> assertExceptionContainsFullyQualifiedPath(new ClassPathResource(FQ_RESOURCE_PATH, this.getClass().getClassLoader())); <add> assertExceptionContainsFullyQualifiedPath(new ClassPathResource(FQ_RESOURCE_PATH, <add> this.getClass().getClassLoader())); <ide> } <ide> <del> private void assertExceptionContainsFullyQualifiedPath(ClassPathResource resource) { <del> try { <del> resource.getInputStream(); <del> fail("FileNotFoundException expected for resource: " + resource); <del> } catch (IOException ex) { <del> assertThat(ex, instanceOf(FileNotFoundException.class)); <del> assertThat(ex.getMessage(), containsString(FQ_RESOURCE_PATH)); <del> } <add> @Test <add> public void getDescriptionWithStringConstructor() { <add> assertDescriptionContainsExpectedPath(new ClassPathResource(FQ_RESOURCE_PATH), FQ_RESOURCE_PATH); <add> } <add> <add> @Test <add> public void getDescriptionWithStringConstructorAndLeadingSlash() { <add> assertDescriptionContainsExpectedPath(new ClassPathResource(FQ_RESOURCE_PATH_WITH_LEADING_SLASH), <add> FQ_RESOURCE_PATH); <add> } <add> <add> @Test <add> public void getDescriptionWithClassLiteralConstructor() { <add> assertDescriptionContainsExpectedPath(new ClassPathResource(NONEXISTENT_RESOURCE_NAME, this.getClass()), <add> FQ_RESOURCE_PATH); <ide> } <add> <add> @Test <add> public void getDescriptionWithClassLiteralConstructorAndLeadingSlash() { <add> assertDescriptionContainsExpectedPath( <add> new ClassPathResource(FQ_RESOURCE_PATH_WITH_LEADING_SLASH, this.getClass()), FQ_RESOURCE_PATH); <add> } <add> <add> @Test <add> public void getDescriptionWithClassLoaderConstructor() { <add> assertDescriptionContainsExpectedPath( <add> new ClassPathResource(FQ_RESOURCE_PATH, this.getClass().getClassLoader()), FQ_RESOURCE_PATH); <add> } <add> <add> @Test <add> public void getDescriptionWithClassLoaderConstructorAndLeadingSlash() { <add> assertDescriptionContainsExpectedPath(new ClassPathResource(FQ_RESOURCE_PATH_WITH_LEADING_SLASH, <add> this.getClass().getClassLoader()), FQ_RESOURCE_PATH); <add> } <add> <ide> }
2
Text
Text
use erb in the changelog [ci skip]
0e9f0bd6f710e510496fafc402f5a74a03a502fd
<ide><path>actionview/CHANGELOG.md <ide> * Ability to pass block to `select` helper <ide> <del> = select(report, "campaign_ids") do <del> - available_campaigns.each do |c| <del> %option{:data => {:tags => c.tags.to_json}, :value => c.id}= c.name <add> <%= select(report, "campaign_ids") do %> <add> <% available_campaigns.each do |c| -%> <add> <%= content_tag(:option, c.name, value: c.id, data: { tags: c.tags.to_json }) %> <add> <% end -%> <add> <% end -%> <ide> <ide> *Bogdan Gusiev* <ide>
1
Python
Python
fix application tests
b300bfb198cb1c4967b912009e18ada1affa8c38
<ide><path>tests/keras/applications/applications_test.py <ide> <ide> pytestmark = pytest.mark.skipif( <ide> os.environ.get('CORE_CHANGED', 'True') == 'False' and <del> os.environ('APP_CHANGED', 'True') == 'False', <add> os.environ.get('APP_CHANGED', 'True') == 'False', <ide> reason='Runs only when the relevant files have been modified.') <ide> <ide>
1
Python
Python
remove tt_ + celery_redis_ config
a86f32440022c1a4c8376d0dc05cadfc17ede5fb
<ide><path>celery/tests/config.py <ide> <ide> CELERYD_LOG_COLOR = False <ide> <del># Tyrant results tests (only executed if installed and running) <del>TT_HOST = os.environ.get('TT_HOST') or 'localhost' <del>TT_PORT = int(os.environ.get('TT_PORT') or 1978) <del> <del># Redis results tests (only executed if installed and running) <del>CELERY_REDIS_HOST = os.environ.get('REDIS_HOST') or 'localhost' <del>CELERY_REDIS_PORT = int(os.environ.get('REDIS_PORT') or 6379) <del>CELERY_REDIS_DB = os.environ.get('REDIS_DB') or 0 <del>CELERY_REDIS_PASSWORD = os.environ.get('REDIS_PASSWORD') <del> <ide> # Mongo results tests (only executed if installed and running) <ide> CELERY_MONGODB_BACKEND_SETTINGS = { <ide> 'host': os.environ.get('MONGO_HOST') or 'localhost',
1
Text
Text
improve wording of the engines guide
a8d4e2788b977da39f1b8a3ed7fb67fafecbcd0f
<ide><path>guides/source/engines.md <ide> What are engines? <ide> <ide> Engines can be considered miniature applications that provide functionality to their host applications. A Rails application is actually just a "supercharged" engine, with the `Rails::Application` class inheriting a lot of its behavior from `Rails::Engine`. <ide> <del>Therefore, engines and applications can be thought of almost the same thing, just with very minor differences, as you'll see throughout this guide. Engines and applications also share a common structure. <add>Therefore, engines and applications can be thought of almost the same thing, just with subtle differences, as you'll see throughout this guide. Engines and applications also share a common structure. <ide> <ide> Engines are also closely related to plugins where the two share a common `lib` directory structure and are both generated using the `rails plugin new` generator. The difference being that an engine is considered a "full plugin" by Rails as indicated by the `--full` option that's passed to the generator command, but this guide will refer to them simply as "engines" throughout. An engine **can** be a plugin, and a plugin **can** be an engine. <ide> <ide> Blorgh::Engine.routes.draw do <ide> end <ide> ``` <ide> <del>Note here that the routes are drawn upon the `Blorgh::Engine` object rather than the `YourApp::Application` class. This is so that the engine routes are confined to the engine itself and can be mounted at a specific point as shown in the [test directory](#test-directory) section. This is also what causes the engine's routes to be isolated from those routes that are within the application. This is discussed further in the [Routes](#routes) section of this guide. <add>Note here that the routes are drawn upon the `Blorgh::Engine` object rather than the `YourApp::Application` class. This is so that the engine routes are confined to the engine itself and can be mounted at a specific point as shown in the [test directory](#test-directory) section. It also causes the engine's routes to be isolated from those routes that are within the application. The [Routes](#routes) section of <add>this guide describes it in details. <ide> <ide> Next, the `scaffold_controller` generator is invoked, generating a controller called `Blorgh::PostsController` (at `app/controllers/blorgh/posts_controller.rb`) and its related views at `app/views/blorgh/posts`. This generator also generates a test for the controller (`test/controllers/blorgh/posts_controller_test.rb`) and a helper (`app/helpers/blorgh/posts_controller.rb`). <ide> <ide> module Blorgh <ide> end <ide> ``` <ide> <del>This helps prevent conflicts with any other engine or application that may have a post resource also. <add>This helps prevent conflicts with any other engine or application that may have a post resource as well. <ide> <ide> Finally, two files that are the assets for this resource are generated, `app/assets/javascripts/blorgh/posts.js` and `app/assets/javascripts/blorgh/posts.css`. You'll see how to use these a little later. <ide> <ide> For more information, read the [Asset Pipeline guide](http://guides.rubyonrails. <ide> <ide> ### Other gem dependencies <ide> <del>Gem dependencies inside an engine should be specified inside the `.gemspec` file at the root of the engine. The reason for this is because the engine may <add>Gem dependencies inside an engine should be specified inside the <add>`.gemspec` file at the root of the engine. The reason is that the engine may <ide> be installed as a gem. If dependencies were to be specified inside the `Gemfile`, <del>these would not be recognised by a traditional gem install and so they would not <add>these would not be recognized by a traditional gem install and so they would not <ide> be installed, causing the engine to malfunction. <ide> <ide> To specify a dependency that should be installed with the engine during a
1
Text
Text
add ssr caching example to the readme. (#503)
fb3612a941931837a976b8443b03512ae992a49d
<ide><path>README.md <ide> export default ({ url }) => ( <ide> <li><a href="./examples/custom-server">Basic custom server</a></li> <ide> <li><a href="./examples/custom-server-express">Express integration</a></li> <ide> <li><a href="./examples/parameterized-routing">Parameterized routing</a></li> <add> <li><a href="./examples/ssr-caching">SSR caching</a></li> <ide> </ul> <ide> </details></p> <ide>
1
Text
Text
apply proper formatting on note paragraph
7453131461f5073d9160bbc1402bcb0e052579c0
<ide><path>curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/perform-classic-updates-by-running-find-edit-then-save.english.md <ide> In the good old days this was what you needed to do if you wanted to edit a docu <ide> <ide> Find a person by <code>_id</code> ( use any of the above methods ) with the parameter <code>personId</code> as search key. Add &quot;hamburger&quot; to the list of the person&apos;s <code>favoriteFoods</code> (you can use <code>Array.push()</code>). Then - inside the find callback - <code>save()</code> the updated <code>Person</code>. <ide> <del><strong>Note:</strong> This may be tricky, if in your Schema, you declared <code>favoriteFoods</code> as an Array, without specifying the type (i.e. <code>[String]</code>). In that <code>casefavoriteFoods</code> defaults to Mixed type, and you have to manually mark it as edited using <code>document.markModified('edited-field')</code>. See [Mongoose documentation](https://mongoosejs.com/docs/schematypes.html#Mixed) <add><strong>Note:</strong> This may be tricky, if in your Schema, you declared <code>favoriteFoods</code> as an Array, without specifying the type (i.e. <code>[String]</code>). In that case, <code>favoriteFoods</code> defaults to Mixed type, and you have to manually mark it as edited using <code>document.markModified('edited-field')</code>. See [Mongoose documentation](https://mongoosejs.com/docs/schematypes.html#Mixed) <ide> <ide> </section> <ide>
1
Text
Text
create readme for spentaur/yelp model
53f5ef6df5290b46a60cca9560379216b80c73ab
<ide><path>model_cards/spentaur/yelp/README.md <add># DistilBERT Yelp Review Sentiment <add>This model is used for sentiment analysis on english yelp reviews. <add>It is a DistilBERT model trained on 1 million reviews from the yelp open dataset. <add>It is a regression model, with outputs in the range of ~-2 to ~2. With -2 being 1 star and 2 being 5 stars. <add>It was trained using the [ktrain](https://github.com/amaiya/ktrain) because of it's ease of use. <add> <add>Example use: <add> <add>``` <add>tokenizer = AutoTokenizer.from_pretrained( <add> 'distilbert-base-uncased', use_fast=True) <add>model = TFAutoModelForSequenceClassification.from_pretrained( <add> "spentaur/yelp") <add> <add>review = "This place is great!" <add>input_ids = tokenizer.encode(review, return_tensors='tf') <add>pred = model(input_ids)[0][0][0].numpy() <add># pred should === 1.9562385 <add>```
1
PHP
PHP
remove unused import
bc91b6c997491e029c0d9bb1828cbe89d66f76ff
<ide><path>src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php <ide> <ide> namespace Illuminate\Foundation\Testing\Concerns; <ide> <del>use Illuminate\Http\Testing\NullMiddleware; <ide> use Illuminate\Support\Str; <ide> use Illuminate\Http\Request; <ide> use Illuminate\Foundation\Testing\TestResponse;
1
Javascript
Javascript
make it so that you can filter tests by keyword
fbd2b066a71c8c2371e11f7f6b201a9000b564e4
<ide><path>build/test/data/testrunner.js <ide> function test(name, callback, nowait) { <ide> name = _config.currentModule + " module: " + name; <ide> <ide> var filter = location.search.slice(1); <del> if ( filter && encodeURIComponent(name) != filter ) <add> if ( filter && encodeURIComponent(name).indexOf(filter) == -1 ) <ide> return; <ide> <ide> synchronize(function() {
1
Text
Text
add changelog for 1.3.0-beta.3
3f2d7565322a0c8bf72a1ed9da90885a8707161c
<ide><path>CHANGELOG.md <add><a name="1.3.0-beta.3"></a> <add># 1.3.0-beta.3 emotional-waffles (2014-03-21) <add> <add> <add>## Bug Fixes <add> <add>- **ngAnimate:** support `webkitCancelRequestAnimationFrame` in addition to `webkitCancelAnimationFrame` <add> ([c839f78b](https://github.com/angular/angular.js/commit/c839f78b8f2d8d910bc2bfc9e41b3e3b67090ec1), <add> [#6526](https://github.com/angular/angular.js/issues/6526)) <add>- **$http:** allow sending Blob data using `$http` <add> ([b8cc71d4](https://github.com/angular/angular.js/commit/b8cc71d476f76ff51e719fb76fb2348027c858ce), <add> [#5012](https://github.com/angular/angular.js/issues/5012)) <add>- **$httpBackend:** don't error when JSONP callback is called with no parameter <add> ([6680b7b9](https://github.com/angular/angular.js/commit/6680b7b97c0326a80bdccaf0a35031e4af641e0e), <add> [#4987](https://github.com/angular/angular.js/issues/4987), [#6735](https://github.com/angular/angular.js/issues/6735)) <add>- **$rootScope:** ng-repeat can't handle `NaN` values. #4605 <add> ([fb6062fb](https://github.com/angular/angular.js/commit/fb6062fb9d83545730b993e94ac7482ffd43a62c), <add> [#4605](https://github.com/angular/angular.js/issues/4605)) <add>- **$rootScope:** `$watchCollection` should call listener with old value <add> ([78057a94](https://github.com/angular/angular.js/commit/78057a945ef84cbb05f9417fe884cb8c28e67b44), <add> [#2621](https://github.com/angular/angular.js/issues/2621), [#5661](https://github.com/angular/angular.js/issues/5661), [#5688](https://github.com/angular/angular.js/issues/5688), [#6736](https://github.com/angular/angular.js/issues/6736)) <add>- **angular.bootstrap:** allow angular to load only once <add> ([748a6c8d](https://github.com/angular/angular.js/commit/748a6c8d9d8d61c3ee18eec462abe8ff245d6a98), <add> [#5863](https://github.com/angular/angular.js/issues/5863), [#5587](https://github.com/angular/angular.js/issues/5587)) <add>- **jqLite:** `inheritedData()` now traverses Shadow DOM boundaries via the `host` property of `DocumentFragment` <add> ([8a96f317](https://github.com/angular/angular.js/commit/8a96f317e594a5096d4fa56ceae4c685eec8ac8b), <add> [#6637](https://github.com/angular/angular.js/issues/6637)) <add>- **ngCookie:** convert non-string values to string <add> ([36528310](https://github.com/angular/angular.js/commit/3652831084c3788f786046b907a7361d2e89c520), <add> [#6151](https://github.com/angular/angular.js/issues/6151), [#6220](https://github.com/angular/angular.js/issues/6220)) <add>- **ngTouch:** update workaround for Webkit quirk <add> ([bc42950b](https://github.com/angular/angular.js/commit/bc42950b514b60f319812eeb87aae2915e394237), <add> [#6302](https://github.com/angular/angular.js/issues/6302)) <add>- **orderBy:** support string predicates containing non-ident characters <add> ([37bc5ef4](https://github.com/angular/angular.js/commit/37bc5ef4d87f19da47d3ab454c43d1e532c4f924), <add> [#6143](https://github.com/angular/angular.js/issues/6143), [#6144](https://github.com/angular/angular.js/issues/6144)) <add>- **select:** avoid checking option element's `selected` property in render <add> ([f40f54c6](https://github.com/angular/angular.js/commit/f40f54c6da4a5399fe18a89d068634bb491e9f1a), <add> [#2448](https://github.com/angular/angular.js/issues/2448), [#5994](https://github.com/angular/angular.js/issues/5994)) <add> <add> <add>## Features <add> <add>- **$compile:** add support for `$observer` deregistration <add> ([299b220f](https://github.com/angular/angular.js/commit/299b220f5e05e1d4e26bfd58d0b2fd7329ca76b1), <add> [#5609](https://github.com/angular/angular.js/issues/5609)) <add>- **ngMock.$httpBackend:** added support for function as URL matcher <add> ([d6cfcace](https://github.com/angular/angular.js/commit/d6cfcacee101f2738e0a224a3377232ff85f78a4), <add> [#4580](https://github.com/angular/angular.js/issues/4580)) <add> <add> <add>## Breaking Changes <add> <add>- **$compile:** due to [299b220f](https://github.com/angular/angular.js/commit/299b220f5e05e1d4e26bfd58d0b2fd7329ca76b1), <add> calling `attr.$observe` no longer returns the observer function, but a <add> deregistration function instead. To migrate the code follow the example below: <add> <add>Before: <add> <add> directive('directiveName', function() { <add> return { <add> link: function(scope, elm, attr) { <add> var observer = attr.$observe('someAttr', function(value) { <add> console.log(value); <add> }); <add> } <add> }; <add> }); <add> <add>After: <add> <add> directive('directiveName', function() { <add> return { <add> link: function(scope, elm, attr) { <add> var observer = function(value) { <add> console.log(value); <add> }; <add> <add> attr.$observe('someAttr', observer); <add> } <add> }; <add> }); <add> <add>- **$httpBackend:** due to [6680b7b9](https://github.com/angular/angular.js/commit/6680b7b97c0326a80bdccaf0a35031e4af641e0e), the JSONP behavior for erroneous and empty responses changed: <add> Previously, a JSONP response was regarded as erroneous if it was empty. Now Angular is listening to the <add> correct events to detect errors, i.e. even empty responses can be successful. <add> <add> <add> <ide> <a name="1.3.0-beta.2"></a> <ide> # 1.3.0-beta.2 silent-ventriloquism (2014-03-14) <ide> <ide> The animation mock module has been renamed from `mock.animate` to `ngAnimateMock <ide> ## Breaking Changes <ide> <ide> - **$http:** due to [e1cfb195](https://github.com/angular/angular.js/commit/e1cfb1957feaf89408bccf48fae6f529e57a82fe), <del> it is now necessary to separately specify default HTTP headers for PUT, POST and PATCH requests, as these no longer share a single object. <add> it is now necessary to separately specify default HTTP headers for PUT, POST and PATCH requests, as these no longer share a single object. <ide> <del> To migrate your code, follow the example below: <add> To migrate your code, follow the example below: <ide> <del> Before: <add> Before: <ide> <del> // Will apply to POST, PUT and PATCH methods <del> $httpProvider.defaults.headers.post = { <del> "X-MY-CSRF-HEADER": "..." <del> }; <add> // Will apply to POST, PUT and PATCH methods <add> $httpProvider.defaults.headers.post = { <add> "X-MY-CSRF-HEADER": "..." <add> }; <ide> <del> After: <add> After: <ide> <del> // POST, PUT and PATCH default headers must be specified separately, <del> // as they do not share data. <del> $httpProvider.defaults.headers.post = <del> $httpProvider.defaults.headers.put = <del> $httpProviders.defaults.headers.patch = { <del> "X-MY-CSRF-HEADER": "..." <del> }; <add> // POST, PUT and PATCH default headers must be specified separately, <add> // as they do not share data. <add> $httpProvider.defaults.headers.post = <add> $httpProvider.defaults.headers.put = <add> $httpProviders.defaults.headers.patch = { <add> "X-MY-CSRF-HEADER": "..." <add> }; <ide> <ide> <a name="1.2.8"></a> <ide> # 1.2.8 interdimensional-cartography (2014-01-10)
1
Javascript
Javascript
convert the rendering queue to es6 syntax
24d44b2a341266eec932a0975c764fee69aa6103
<ide><path>web/pdf_rendering_queue.js <ide> * limitations under the License. <ide> */ <ide> <del>var CLEANUP_TIMEOUT = 30000; <add>const CLEANUP_TIMEOUT = 30000; <ide> <del>var RenderingStates = { <add>const RenderingStates = { <ide> INITIAL: 0, <ide> RUNNING: 1, <ide> PAUSED: 2, <del> FINISHED: 3 <add> FINISHED: 3, <ide> }; <ide> <ide> /** <ide> * Controls rendering of the views for pages and thumbnails. <del> * @class <ide> */ <del>var PDFRenderingQueue = (function PDFRenderingQueueClosure() { <del> /** <del> * @constructs <del> */ <del> function PDFRenderingQueue() { <add>class PDFRenderingQueue { <add> constructor() { <ide> this.pdfViewer = null; <ide> this.pdfThumbnailViewer = null; <ide> this.onIdle = null; <del> <ide> this.highestPriorityPage = null; <ide> this.idleTimeout = null; <ide> this.printing = false; <ide> this.isThumbnailViewEnabled = false; <ide> } <ide> <del> PDFRenderingQueue.prototype = /** @lends PDFRenderingQueue.prototype */ { <del> /** <del> * @param {PDFViewer} pdfViewer <del> */ <del> setViewer: function PDFRenderingQueue_setViewer(pdfViewer) { <del> this.pdfViewer = pdfViewer; <del> }, <add> /** <add> * @param {PDFViewer} pdfViewer <add> */ <add> setViewer(pdfViewer) { <add> this.pdfViewer = pdfViewer; <add> } <ide> <del> /** <del> * @param {PDFThumbnailViewer} pdfThumbnailViewer <del> */ <del> setThumbnailViewer: <del> function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) { <del> this.pdfThumbnailViewer = pdfThumbnailViewer; <del> }, <add> /** <add> * @param {PDFThumbnailViewer} pdfThumbnailViewer <add> */ <add> setThumbnailViewer(pdfThumbnailViewer) { <add> this.pdfThumbnailViewer = pdfThumbnailViewer; <add> } <ide> <del> /** <del> * @param {IRenderableView} view <del> * @returns {boolean} <del> */ <del> isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) { <del> return this.highestPriorityPage === view.renderingId; <del> }, <del> <del> renderHighestPriority: function <del> PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) { <del> if (this.idleTimeout) { <del> clearTimeout(this.idleTimeout); <del> this.idleTimeout = null; <del> } <add> /** <add> * @param {IRenderableView} view <add> * @returns {boolean} <add> */ <add> isHighestPriority(view) { <add> return this.highestPriorityPage === view.renderingId; <add> } <ide> <del> // Pages have a higher priority than thumbnails, so check them first. <del> if (this.pdfViewer.forceRendering(currentlyVisiblePages)) { <add> /** <add> * @param {Object} currentlyVisiblePages <add> */ <add> renderHighestPriority(currentlyVisiblePages) { <add> if (this.idleTimeout) { <add> clearTimeout(this.idleTimeout); <add> this.idleTimeout = null; <add> } <add> <add> // Pages have a higher priority than thumbnails, so check them first. <add> if (this.pdfViewer.forceRendering(currentlyVisiblePages)) { <add> return; <add> } <add> // No pages needed rendering, so check thumbnails. <add> if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) { <add> if (this.pdfThumbnailViewer.forceRendering()) { <ide> return; <ide> } <del> // No pages needed rendering so check thumbnails. <del> if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) { <del> if (this.pdfThumbnailViewer.forceRendering()) { <del> return; <del> } <del> } <add> } <ide> <del> if (this.printing) { <del> // If printing is currently ongoing do not reschedule cleanup. <del> return; <del> } <add> if (this.printing) { <add> // If printing is currently ongoing do not reschedule cleanup. <add> return; <add> } <ide> <del> if (this.onIdle) { <del> this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT); <del> } <del> }, <del> <del> getHighestPriority: function <del> PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) { <del> // The state has changed figure out which page has the highest priority to <del> // render next (if any). <del> // Priority: <del> // 1 visible pages <del> // 2 if last scrolled down page after the visible pages <del> // 2 if last scrolled up page before the visible pages <del> var visibleViews = visible.views; <del> <del> var numVisible = visibleViews.length; <del> if (numVisible === 0) { <del> return false; <add> if (this.onIdle) { <add> this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT); <add> } <add> } <add> <add> /** <add> * @param {Object} visible <add> * @param {Array} views <add> * @param {boolean} scrolledDown <add> */ <add> getHighestPriority(visible, views, scrolledDown) { <add> /** <add> * The state has changed. Figure out which page has the highest priority to <add> * render next (if any). <add> * <add> * Priority: <add> * 1. visible pages <add> * 2. if last scrolled down, the page after the visible pages, or <add> * if last scrolled up, the page before the visible pages <add> */ <add> var visibleViews = visible.views; <add> <add> var numVisible = visibleViews.length; <add> if (numVisible === 0) { <add> return false; <add> } <add> for (var i = 0; i < numVisible; ++i) { <add> var view = visibleViews[i].view; <add> if (!this.isViewFinished(view)) { <add> return view; <ide> } <del> for (var i = 0; i < numVisible; ++i) { <del> var view = visibleViews[i].view; <del> if (!this.isViewFinished(view)) { <del> return view; <del> } <add> } <add> <add> // All the visible views have rendered; try to render next/previous pages. <add> if (scrolledDown) { <add> var nextPageIndex = visible.last.id; <add> // IDs start at 1, so no need to add 1. <add> if (views[nextPageIndex] && !this.isViewFinished(views[nextPageIndex])) { <add> return views[nextPageIndex]; <ide> } <del> <del> // All the visible views have rendered, try to render next/previous pages. <del> if (scrolledDown) { <del> var nextPageIndex = visible.last.id; <del> // ID's start at 1 so no need to add 1. <del> if (views[nextPageIndex] && <del> !this.isViewFinished(views[nextPageIndex])) { <del> return views[nextPageIndex]; <del> } <del> } else { <del> var previousPageIndex = visible.first.id - 2; <del> if (views[previousPageIndex] && <add> } else { <add> var previousPageIndex = visible.first.id - 2; <add> if (views[previousPageIndex] && <ide> !this.isViewFinished(views[previousPageIndex])) { <del> return views[previousPageIndex]; <del> } <add> return views[previousPageIndex]; <ide> } <del> // Everything that needs to be rendered has been. <del> return null; <del> }, <del> <del> /** <del> * @param {IRenderableView} view <del> * @returns {boolean} <del> */ <del> isViewFinished: function PDFRenderingQueue_isViewFinished(view) { <del> return view.renderingState === RenderingStates.FINISHED; <del> }, <add> } <add> // Everything that needs to be rendered has been. <add> return null; <add> } <ide> <del> /** <del> * Render a page or thumbnail view. This calls the appropriate function <del> * based on the views state. If the view is already rendered it will return <del> * false. <del> * @param {IRenderableView} view <del> */ <del> renderView: function PDFRenderingQueue_renderView(view) { <del> var state = view.renderingState; <del> switch (state) { <del> case RenderingStates.FINISHED: <del> return false; <del> case RenderingStates.PAUSED: <del> this.highestPriorityPage = view.renderingId; <del> view.resume(); <del> break; <del> case RenderingStates.RUNNING: <del> this.highestPriorityPage = view.renderingId; <del> break; <del> case RenderingStates.INITIAL: <del> this.highestPriorityPage = view.renderingId; <del> var continueRendering = function () { <del> this.renderHighestPriority(); <del> }.bind(this); <del> view.draw().then(continueRendering, continueRendering); <del> break; <del> } <del> return true; <del> }, <del> }; <add> /** <add> * @param {IRenderableView} view <add> * @returns {boolean} <add> */ <add> isViewFinished(view) { <add> return view.renderingState === RenderingStates.FINISHED; <add> } <ide> <del> return PDFRenderingQueue; <del>})(); <add> /** <add> * Render a page or thumbnail view. This calls the appropriate function <add> * based on the views state. If the view is already rendered it will return <add> * `false`. <add> * <add> * @param {IRenderableView} view <add> */ <add> renderView(view) { <add> switch (view.renderingState) { <add> case RenderingStates.FINISHED: <add> return false; <add> case RenderingStates.PAUSED: <add> this.highestPriorityPage = view.renderingId; <add> view.resume(); <add> break; <add> case RenderingStates.RUNNING: <add> this.highestPriorityPage = view.renderingId; <add> break; <add> case RenderingStates.INITIAL: <add> this.highestPriorityPage = view.renderingId; <add> var continueRendering = () => { <add> this.renderHighestPriority(); <add> }; <add> view.draw().then(continueRendering, continueRendering); <add> break; <add> } <add> return true; <add> } <add>} <ide> <ide> export { <ide> RenderingStates,
1
Javascript
Javascript
check result as early as possible
3ba4f71fc4a1b3acdcaaa250bc5ba81442257e09
<ide><path>test/parallel/test-http-get-pipeline-problem.js <ide> server.listen(common.PORT, function() { <ide> var s = fs.createWriteStream(common.tmpDir + '/' + x + '.jpg'); <ide> res.pipe(s); <ide> <del> // TODO there should be a callback to pipe() that will allow <del> // us to get a callback when the pipe is finished. <del> res.on('end', function() { <add> s.on('finish', function() { <ide> console.error('done ' + x); <ide> if (++responses == total) { <del> s.on('close', checkFiles); <add> checkFiles(); <ide> } <ide> }); <ide> }).on('error', function(e) {
1
Ruby
Ruby
reduce cache misses on sti subclasses
1a15fda02159487371a0cb4c36311345dec7b46b
<ide><path>activerecord/lib/active_record/base.rb <ide> def reset_column_information <ide> undefine_attribute_methods <ide> reset_column_cache <ide> @column_names = @content_columns = @dynamic_methods_hash = @inheritance_column = nil <del> @arel_engine = @relation = @arel_table = nil <add> @arel_engine = @relation = nil <ide> end <ide> <ide> def reset_column_cache # :nodoc: <ide> @@columns.delete table_name <ide> @@columns_hash.delete table_name <add> @@arel_tables.delete table_name <ide> end <ide> <ide> def attribute_method?(attribute) <ide> def sti_name <ide> end <ide> <ide> def arel_table <del> @arel_table ||= Arel::Table.new(table_name, arel_engine) <add> @@arel_tables[table_name] ||= Arel::Table.new(table_name, arel_engine) <ide> end <ide> <ide> def arel_engine <ide> def encode_quoted_value(value) #:nodoc: <ide> end <ide> @@columns_hash = {} <ide> @@columns = {} <add> @@arel_tables = {} <ide> <ide> public <ide> # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
1
Python
Python
improve handling of 'empty' values for choicefield
53258908210b1eabd0ee204653a589d6579ac772
<ide><path>rest_framework/fields.py <ide> class ChoiceField(WritableField): <ide> } <ide> <ide> def __init__(self, choices=(), *args, **kwargs): <add> self.empty = kwargs.pop('empty', '') <ide> super(ChoiceField, self).__init__(*args, **kwargs) <ide> self.choices = choices <ide> if not self.required: <ide> def valid_value(self, value): <ide> return False <ide> <ide> def from_native(self, value): <del> if value in validators.EMPTY_VALUES: <del> return None <del> return super(ChoiceField, self).from_native(value) <add> value = super(ChoiceField, self).from_native(value) <add> if value == self.empty or value in validators.EMPTY_VALUES: <add> return self.empty <add> return value <ide> <ide> <ide> class EmailField(CharField): <ide><path>rest_framework/serializers.py <ide> def get_field(self, model_field): <ide> # TODO: TypedChoiceField? <ide> if model_field.flatchoices: # This ModelField contains choices <ide> kwargs['choices'] = model_field.flatchoices <add> if model_field.null: <add> kwargs['empty'] = None <ide> return ChoiceField(**kwargs) <ide> <ide> # put this below the ChoiceField because min_value isn't a valid initializer <ide><path>rest_framework/tests/test_fields.py <ide> class Meta: <ide> model = TimeFieldModel <ide> <ide> <add>SAMPLE_CHOICES = [ <add> ('red', 'Red'), <add> ('green', 'Green'), <add> ('blue', 'Blue'), <add>] <add> <add> <add>class ChoiceFieldModel(models.Model): <add> choice = models.CharField(choices=SAMPLE_CHOICES, blank=True, max_length=255) <add> <add> <add>class ChoiceFieldModelSerializer(serializers.ModelSerializer): <add> class Meta: <add> model = ChoiceFieldModel <add> <add> <add>class ChoiceFieldModelWithNull(models.Model): <add> choice = models.CharField(choices=SAMPLE_CHOICES, blank=True, null=True, max_length=255) <add> <add> <add>class ChoiceFieldModelWithNullSerializer(serializers.ModelSerializer): <add> class Meta: <add> model = ChoiceFieldModelWithNull <add> <add> <ide> class BasicFieldTests(TestCase): <ide> def test_auto_now_fields_read_only(self): <ide> """ <ide> class ChoiceFieldTests(TestCase): <ide> """ <ide> Tests for the ChoiceField options generator <ide> """ <del> <del> SAMPLE_CHOICES = [ <del> ('red', 'Red'), <del> ('green', 'Green'), <del> ('blue', 'Blue'), <del> ] <del> <ide> def test_choices_required(self): <ide> """ <ide> Make sure proper choices are rendered if field is required <ide> """ <del> f = serializers.ChoiceField(required=True, choices=self.SAMPLE_CHOICES) <del> self.assertEqual(f.choices, self.SAMPLE_CHOICES) <add> f = serializers.ChoiceField(required=True, choices=SAMPLE_CHOICES) <add> self.assertEqual(f.choices, SAMPLE_CHOICES) <ide> <ide> def test_choices_not_required(self): <ide> """ <ide> Make sure proper choices (plus blank) are rendered if the field isn't required <ide> """ <del> f = serializers.ChoiceField(required=False, choices=self.SAMPLE_CHOICES) <del> self.assertEqual(f.choices, models.fields.BLANK_CHOICE_DASH + self.SAMPLE_CHOICES) <add> f = serializers.ChoiceField(required=False, choices=SAMPLE_CHOICES) <add> self.assertEqual(f.choices, models.fields.BLANK_CHOICE_DASH + SAMPLE_CHOICES) <add> <add> def test_invalid_choice_model(self): <add> s = ChoiceFieldModelSerializer(data={'choice' : 'wrong_value'}) <add> self.assertFalse(s.is_valid()) <add> self.assertEqual(s.errors, {'choice': [u'Select a valid choice. wrong_value is not one of the available choices.']}) <add> self.assertEqual(s.data['choice'], '') <add> <add> def test_empty_choice_model(self): <add> """ <add> Test that the 'empty' value is correctly passed and used depending on the 'null' property on the model field. <add> """ <add> s = ChoiceFieldModelSerializer(data={'choice' : ''}) <add> self.assertTrue(s.is_valid()) <add> self.assertEqual(s.data['choice'], '') <add> <add> s = ChoiceFieldModelWithNullSerializer(data={'choice' : ''}) <add> self.assertTrue(s.is_valid()) <add> self.assertEqual(s.data['choice'], None) <ide> <ide> def test_from_native_empty(self): <ide> """ <del> Make sure from_native() returns None on empty param. <add> Make sure from_native() returns an empty string on empty param by default. <ide> """ <del> f = serializers.ChoiceField(choices=self.SAMPLE_CHOICES) <del> result = f.from_native('') <del> self.assertEqual(result, None) <add> f = serializers.ChoiceField(choices=SAMPLE_CHOICES) <add> self.assertEqual(f.from_native(''), '') <add> self.assertEqual(f.from_native(None), '') <add> <add> def test_from_native_empty_override(self): <add> """ <add> Make sure you can override from_native() behavior regarding empty values. <add> """ <add> f = serializers.ChoiceField(choices=SAMPLE_CHOICES, empty=None) <add> self.assertEqual(f.from_native(''), None) <add> self.assertEqual(f.from_native(None), None) <ide> <ide> <ide> class EmailFieldTests(TestCase):
3
PHP
PHP
name" command
d4b6cea0ae1a67e48425c427d48b71f5d078cb90
<ide><path>src/Illuminate/Foundation/Console/AppNameCommand.php <ide> public function fire() <ide> $this->info('Application namespace set!'); <ide> <ide> $this->composer->dumpAutoloads(); <add> <add> $this->call('clear-compiled'); <add> <add> $this->call('optimize'); <ide> } <ide> <ide> /**
1
Ruby
Ruby
add #rendered_format method to controllers
7d810049fe8905e3e96d0b2e989f562bb961e59e
<ide><path>actionpack/lib/abstract_controller/rendering.rb <ide> def render_to_body(options = {}) <ide> def render(*args, &block) <ide> end <ide> <add> # Return Content-Type of rendered content <add> # :api: public <add> def rendered_format <add> end <add> <ide> # This method should return a hash with assigns. <ide> # You can overwrite this configuration per controller. <ide> # :api: public <ide><path>actionpack/lib/action_controller/metal/rendering.rb <ide> def process_action(*) #:nodoc: <ide> <ide> # Check for double render errors and set the content_type after rendering. <ide> def render(*args) #:nodoc: <del> raise ::AbstractController::DoubleRenderError if response_body <add> raise ::AbstractController::DoubleRenderError if self.response_body <ide> super <del> self.content_type ||= Mime[lookup_context.rendered_format].to_s <del> response_body <add> self.content_type ||= rendered_format.to_s <add> self.response_body <ide> end <ide> <ide> # Overwrite render_to_string because body can now be set to a rack body. <ide> def render_to_string(*) <ide> if self.response_body = super <ide> string = "" <del> response_body.each { |r| string << r } <add> self.response_body.each { |r| string << r } <ide> string <ide> end <ide> ensure <ide><path>actionview/lib/action_view/rendering.rb <ide> def _render_template(options) #:nodoc: <ide> view_renderer.render(view_context, options) <ide> end <ide> <add> def rendered_format <add> Mime[lookup_context.rendered_format] <add> end <add> <ide> def default_protected_instance_vars <ide> super.concat([:@_view_context_class, :@_view_renderer, :@_lookup_context]) <ide> end
3
Javascript
Javascript
move script loading into separate runtime module
531f7b47f624250c88851b198795c71c7b300f3c
<ide><path>lib/RuntimeGlobals.js <ide> exports.uncaughtErrorHandler = "__webpack_require__.oe"; <ide> */ <ide> exports.scriptNonce = "__webpack_require__.nc"; <ide> <add>/** <add> * function to load a script tag. <add> * Arguments: (url: string, done: (event) => void), key?: string | number) => void <add> * done function is called when loading has finished or timeout occurred. <add> * It will attach to existing script tags with data-webpack == key or src == url. <add> */ <add>exports.loadScript = "__webpack_require__.l"; <add> <ide> /** <ide> * the chunk name of the chunk with the runtime <ide> */ <ide><path>lib/RuntimePlugin.js <ide> const GetChunkFilenameRuntimeModule = require("./runtime/GetChunkFilenameRuntime <ide> const GetMainFilenameRuntimeModule = require("./runtime/GetMainFilenameRuntimeModule"); <ide> const GlobalRuntimeModule = require("./runtime/GlobalRuntimeModule"); <ide> const HasOwnPropertyRuntimeModule = require("./runtime/HasOwnPropertyRuntimeModule"); <add>const LoadScriptRuntimeModule = require("./runtime/LoadScriptRuntimeModule"); <ide> const MakeNamespaceObjectRuntimeModule = require("./runtime/MakeNamespaceObjectRuntimeModule"); <ide> const PublicPathRuntimeModule = require("./runtime/PublicPathRuntimeModule"); <ide> const SystemContextRuntimeModule = require("./runtime/SystemContextRuntimeModule"); <ide> const GLOBALS_ON_REQUIRE = [ <ide> RuntimeGlobals.wasmInstances, <ide> RuntimeGlobals.instantiateWasm, <ide> RuntimeGlobals.shareScopeMap, <del> RuntimeGlobals.initializeSharing <add> RuntimeGlobals.initializeSharing, <add> RuntimeGlobals.loadScript <ide> ]; <ide> <ide> const MODULE_DEPENDENCIES = { <ide> class RuntimePlugin { <ide> compilation.addRuntimeModule(chunk, new ShareRuntimeModule()); <ide> return true; <ide> }); <add> compilation.hooks.runtimeRequirementInTree <add> .for(RuntimeGlobals.loadScript) <add> .tap("RuntimePlugin", (chunk, set) => { <add> compilation.addRuntimeModule(chunk, new LoadScriptRuntimeModule()); <add> return true; <add> }); <ide> // TODO webpack 6: remove CompatRuntimePlugin <ide> compilation.hooks.additionalTreeRuntimeRequirements.tap( <ide> "RuntimePlugin", <ide><path>lib/runtime/LoadScriptRuntimeModule.js <add>/* <add> MIT License http://www.opensource.org/licenses/mit-license.php <add>*/ <add> <add>"use strict"; <add> <add>const { SyncWaterfallHook } = require("tapable"); <add>const Compilation = require("../Compilation"); <add>const RuntimeGlobals = require("../RuntimeGlobals"); <add>const Template = require("../Template"); <add>const HelperRuntimeModule = require("./HelperRuntimeModule"); <add> <add>/** @typedef {import("../Chunk")} Chunk */ <add>/** @typedef {import("../Compilation")} Compilation */ <add>/** @typedef {import("../Compiler")} Compiler */ <add> <add>/** <add> * @typedef {Object} LoadScriptCompilationHooks <add> * @property {SyncWaterfallHook<[string, Chunk]>} createScript <add> */ <add> <add>/** @type {WeakMap<Compilation, LoadScriptCompilationHooks>} */ <add>const compilationHooksMap = new WeakMap(); <add> <add>class LoadScriptRuntimeModule extends HelperRuntimeModule { <add> /** <add> * @param {Compilation} compilation the compilation <add> * @returns {LoadScriptCompilationHooks} hooks <add> */ <add> static getCompilationHooks(compilation) { <add> if (!(compilation instanceof Compilation)) { <add> throw new TypeError( <add> "The 'compilation' argument must be an instance of Compilation" <add> ); <add> } <add> let hooks = compilationHooksMap.get(compilation); <add> if (hooks === undefined) { <add> hooks = { <add> createScript: new SyncWaterfallHook(["source", "chunk"]) <add> }; <add> compilationHooksMap.set(compilation, hooks); <add> } <add> return hooks; <add> } <add> <add> constructor() { <add> super("load script"); <add> } <add> <add> /** <add> * @returns {string} runtime code <add> */ <add> generate() { <add> const { compilation } = this; <add> const { runtimeTemplate, outputOptions } = compilation; <add> const { <add> jsonpScriptType: scriptType, <add> chunkLoadTimeout: loadTimeout, <add> crossOriginLoading <add> } = outputOptions; <add> const fn = RuntimeGlobals.loadScript; <add> <add> const { createScript } = LoadScriptRuntimeModule.getCompilationHooks( <add> compilation <add> ); <add> <add> const code = Template.asString([ <add> "script = document.createElement('script');", <add> scriptType ? `script.type = ${JSON.stringify(scriptType)};` : "", <add> "script.charset = 'utf-8';", <add> `script.timeout = ${loadTimeout / 1000};`, <add> `if (${RuntimeGlobals.scriptNonce}) {`, <add> Template.indent( <add> `script.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` <add> ), <add> "}", <add> 'script.setAttribute("data-webpack", key);', <add> `script.src = url;`, <add> crossOriginLoading <add> ? Template.asString([ <add> "if (script.src.indexOf(window.location.origin + '/') !== 0) {", <add> Template.indent( <add> `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};` <add> ), <add> "}" <add> ]) <add> : "" <add> ]); <add> <add> return Template.asString([ <add> "var inProgress = {};", <add> "// loadScript function to load a script via script tag", <add> `${fn} = ${runtimeTemplate.basicFunction("url, done, key", [ <add> "if(inProgress[url]) { inProgress[url].push(done); return; }", <add> "var script, needAttach;", <add> "if(key !== undefined) {", <add> Template.indent([ <add> 'var scripts = document.getElementsByTagName("script");', <add> "for(var i = 0; i < scripts.length; i++) {", <add> Template.indent([ <add> "var s = scripts[i];", <add> 'if(s.getAttribute("src") == url || s.getAttribute("data-webpack") == key) { script = s; break; }' <add> ]), <add> "}" <add> ]), <add> "}", <add> "if(!script) {", <add> Template.indent([ <add> "needAttach = true;", <add> createScript.call(code, this.chunk) <add> ]), <add> "}", <add> "inProgress[url] = [done];", <add> "var onScriptComplete = " + <add> runtimeTemplate.basicFunction( <add> "event", <add> Template.asString([ <add> `onScriptComplete = ${runtimeTemplate.basicFunction("", "")}`, <add> "// avoid mem leaks in IE.", <add> "script.onerror = script.onload = null;", <add> "clearTimeout(timeout);", <add> "var doneFns = inProgress[url];", <add> "delete inProgress[url];", <add> "script.parentNode.removeChild(script);", <add> `doneFns && doneFns.forEach(${runtimeTemplate.returningFunction( <add> "fn(event)", <add> "fn" <add> )});` <add> ]) <add> ), <add> ";", <add> `var timeout = setTimeout(${runtimeTemplate.basicFunction( <add> "", <add> "onScriptComplete({ type: 'timeout', target: script })" <add> )}, ${loadTimeout});`, <add> "script.onerror = script.onload = onScriptComplete;", <add> "needAttach && document.head.appendChild(script);" <add> ])};` <add> ]); <add> } <add>} <add> <add>module.exports = LoadScriptRuntimeModule; <ide><path>lib/web/JsonpChunkLoadingRuntimeModule.js <ide> class JsonpChunkLoadingRuntimeModule extends RuntimeModule { <ide> constructor(runtimeRequirements, jsonpScript, linkPreload, linkPrefetch) { <ide> super("jsonp chunk loading", 10); <ide> this.runtimeRequirements = runtimeRequirements; <del> this.jsonpScript = jsonpScript; <ide> this.linkPreload = linkPreload; <ide> this.linkPrefetch = linkPrefetch; <ide> } <ide> class JsonpChunkLoadingRuntimeModule extends RuntimeModule { <ide> * @returns {string} runtime code <ide> */ <ide> generate() { <del> const { compilation, chunk, jsonpScript, linkPreload, linkPrefetch } = this; <add> const { compilation, chunk, linkPreload, linkPrefetch } = this; <ide> const { runtimeTemplate, chunkGraph, outputOptions } = compilation; <ide> const fn = RuntimeGlobals.ensureChunkHandlers; <ide> const withLoading = this.runtimeRequirements.has( <ide> class JsonpChunkLoadingRuntimeModule extends RuntimeModule { <ide> "", <ide> "// start chunk loading", <ide> `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`, <add> "// create error before stack unwound to get useful stacktrace later", <add> "var error = new Error();", <ide> `var loadingEnded = ${runtimeTemplate.basicFunction( <del> "", <add> "event", <ide> [ <ide> `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`, <ide> Template.indent([ <ide> "installedChunkData = installedChunks[chunkId];", <ide> "if(installedChunkData !== 0) installedChunks[chunkId] = undefined;", <del> "if(installedChunkData) return installedChunkData[1];" <add> "if(installedChunkData) {", <add> Template.indent([ <add> "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", <add> "var realSrc = event && event.target && event.target.src;", <add> "error.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", <add> "error.name = 'ChunkLoadError';", <add> "error.type = errorType;", <add> "error.request = realSrc;", <add> "installedChunkData[1](error);" <add> ]), <add> "}" <ide> ]), <ide> "}" <ide> ] <ide> )};`, <del> jsonpScript.call("", chunk), <del> "document.head.appendChild(script);" <add> `${RuntimeGlobals.loadScript}(url, loadingEnded, "chunk-" + chunkId);` <ide> ]), <ide> "} else installedChunks[chunkId] = 0;" <ide> ]), <ide> class JsonpChunkLoadingRuntimeModule extends RuntimeModule { <ide> "waitingUpdateResolves[chunkId] = resolve;", <ide> "// start update chunk loading", <ide> `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId);`, <del> `var loadingEnded = ${runtimeTemplate.basicFunction("", [ <add> "// create error before stack unwound to get useful stacktrace later", <add> "var error = new Error();", <add> `var loadingEnded = ${runtimeTemplate.basicFunction("event", [ <ide> "if(waitingUpdateResolves[chunkId]) {", <ide> Template.indent([ <ide> "waitingUpdateResolves[chunkId] = undefined", <del> "return reject;" <add> "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", <add> "var realSrc = event && event.target && event.target.src;", <add> "error.message = 'Loading hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", <add> "error.name = 'ChunkLoadError';", <add> "error.type = errorType;", <add> "error.request = realSrc;", <add> "reject(error);" <ide> ]), <ide> "}" <ide> ])};`, <del> jsonpScript.call("", chunk), <del> "document.head.appendChild(script);" <add> `${RuntimeGlobals.loadScript}(url, loadingEnded);` <ide> ] <ide> )});` <ide> ]), <ide><path>lib/web/JsonpTemplatePlugin.js <ide> class JsonpTemplatePlugin { <ide> onceForChunkSet.add(chunk); <ide> set.add(RuntimeGlobals.moduleFactoriesAddOnly); <ide> set.add(RuntimeGlobals.hasOwnProperty); <add> set.add(RuntimeGlobals.loadScript); <ide> compilation.addRuntimeModule( <ide> chunk, <ide> new JsonpChunkLoadingRuntimeModule( <ide><path>test/configCases/web/attach-existing/chunk.js <add>export default "ok"; <ide><path>test/configCases/web/attach-existing/index.js <add>const doImport = () => import(/* webpackChunkName: "the-chunk" */ "./chunk"); <add> <add>it("should be able to attach to an existing script tag", () => { <add> const script = document.createElement("script"); <add> script.setAttribute("data-webpack", "chunk-the-chunk"); <add> script.src = "/somewhere/else.js"; <add> document.head.appendChild(script); <add> <add> const promise = doImport(); <add> <add> expect(document.head._children).toHaveLength(1); <add> <add> __non_webpack_require__("./the-chunk.js"); <add> script.onload(); <add> <add> return promise.then(module => { <add> expect(module).toEqual(nsObj({ default: "ok" })); <add> <add> const promise = doImport(); <add> <add> expect(document.head._children).toHaveLength(0); <add> <add> return promise.then(module2 => { <add> expect(module2).toBe(module); <add> }); <add> }); <add>}); <ide><path>test/configCases/web/attach-existing/webpack.config.js <add>/** @type {import("../../../../").Configuration} */ <add>module.exports = { <add> target: "web", <add> output: { <add> chunkFilename: "[name].js" <add> }, <add> performance: { <add> hints: false <add> }, <add> optimization: { <add> chunkIds: "named", <add> minimize: false <add> } <add>}; <ide><path>test/configCases/web/prefetch-preload/index.js <ide> __webpack_nonce__ = "nonce"; <ide> __webpack_public_path__ = "https://example.com/public/path/"; <ide> <ide> it("should prefetch and preload child chunks on chunk load", () => { <del> <ide> let link, script; <ide> <ide> expect(document.head._children).toHaveLength(1); <ide> it("should prefetch and preload child chunks on chunk load", () => { <ide> expect(link.rel).toBe("prefetch"); <ide> expect(link.href).toBe("https://example.com/public/path/chunk1.js"); <ide> <del> const promise = import(/* webpackChunkName: "chunk1", webpackPrefetch: true */ "./chunk1"); <add> const promise = import( <add> /* webpackChunkName: "chunk1", webpackPrefetch: true */ "./chunk1" <add> ); <ide> <ide> expect(document.head._children).toHaveLength(3); <ide> <ide> // Test normal script loading <ide> script = document.head._children[1]; <ide> expect(script._type).toBe("script"); <ide> expect(script.src).toBe("https://example.com/public/path/chunk1.js"); <del> expect(script.getAttribute("nonce")).toBe("nonce") <add> expect(script.getAttribute("nonce")).toBe("nonce"); <ide> expect(script.crossOrigin).toBe("anonymous"); <ide> expect(script.onload).toBeTypeOf("function"); <ide> <ide> it("should prefetch and preload child chunks on chunk load", () => { <ide> script.onload(); <ide> <ide> return promise.then(() => { <del> expect(document.head._children).toHaveLength(5); <add> expect(document.head._children).toHaveLength(4); <ide> <ide> // Test prefetching for chunk1-c and chunk1-a in this order <del> link = document.head._children[3]; <add> link = document.head._children[2]; <ide> expect(link._type).toBe("link"); <ide> expect(link.rel).toBe("prefetch"); <ide> expect(link.href).toBe("https://example.com/public/path/chunk1-c.js"); <ide> expect(link.crossOrigin).toBe("anonymous"); <ide> <del> link = document.head._children[4]; <add> link = document.head._children[3]; <ide> expect(link._type).toBe("link"); <ide> expect(link.rel).toBe("prefetch"); <ide> expect(link.href).toBe("https://example.com/public/path/chunk1-a.js"); <ide> expect(link.crossOrigin).toBe("anonymous"); <ide> <del> const promise2 = import(/* webpackChunkName: "chunk1", webpackPrefetch: true */ "./chunk1"); <add> const promise2 = import( <add> /* webpackChunkName: "chunk1", webpackPrefetch: true */ "./chunk1" <add> ); <ide> <ide> // Loading chunk1 again should not trigger prefetch/preload <del> expect(document.head._children).toHaveLength(5); <add> expect(document.head._children).toHaveLength(4); <ide> <ide> const promise3 = import(/* webpackChunkName: "chunk2" */ "./chunk2"); <ide> <del> expect(document.head._children).toHaveLength(6); <add> expect(document.head._children).toHaveLength(5); <ide> <ide> // Test normal script loading <del> script = document.head._children[5]; <add> script = document.head._children[4]; <ide> expect(script._type).toBe("script"); <ide> expect(script.src).toBe("https://example.com/public/path/chunk2.js"); <del> expect(script.getAttribute("nonce")).toBe("nonce") <add> expect(script.getAttribute("nonce")).toBe("nonce"); <ide> expect(script.crossOrigin).toBe("anonymous"); <ide> expect(script.onload).toBeTypeOf("function"); <ide> <ide> it("should prefetch and preload child chunks on chunk load", () => { <ide> <ide> return promise3.then(() => { <ide> // Loading chunk2 again should not trigger prefetch/preload as it's already prefetch/preloaded <del> expect(document.head._children).toHaveLength(6); <add> expect(document.head._children).toHaveLength(4); <ide> }); <ide> }); <del>}) <add>}); <ide><path>test/configCases/web/retry-failed-import/index.js <ide> it("should be able to retry a failed import()", () => { <ide> <ide> const promise = doImport(); <ide> <del> expect(document.head._children).toHaveLength(2); <add> expect(document.head._children).toHaveLength(1); <ide> <del> const script = document.head._children[1]; <add> const script = document.head._children[0]; <ide> expect(script.onload).toBeTypeOf("function"); <ide> <ide> script.onload(); <ide> it("should be able to retry a failed import()", () => { <ide> <ide> const promise = doImport(); <ide> <del> expect(document.head._children).toHaveLength(3); <add> expect(document.head._children).toHaveLength(1); <ide> <ide> __non_webpack_require__("./the-chunk.js"); <add> document.head._children[0].onload(); <ide> <ide> return promise.then(module => { <ide> expect(module).toEqual(nsObj({ default: "ok" })); <ide> <ide> const promise = doImport(); <ide> <del> expect(document.head._children).toHaveLength(3); <add> expect(document.head._children).toHaveLength(0); <ide> <ide> return promise.then(module2 => { <ide> expect(module2).toBe(module); <ide><path>test/helpers/FakeDocument.js <ide> module.exports = class FakeDocument { <ide> list.push(element); <ide> } <ide> <add> _onElementRemoved(element) { <add> const type = element._type; <add> let list = this._elementsByTagName.get(type); <add> const idx = list.indexOf(element); <add> list.splice(idx, 1); <add> } <add> <ide> getElementsByTagName(name) { <ide> return this._elementsByTagName.get(name) || []; <ide> } <ide> class FakeElement { <ide> this._attributes = Object.create(null); <ide> this._src = undefined; <ide> this._href = undefined; <add> this.parentNode = undefined; <ide> } <ide> <ide> appendChild(node) { <ide> this._document._onElementAttached(node); <ide> this._children.push(node); <add> node.parentNode = this; <add> } <add> <add> removeChild(node) { <add> const idx = this._children.indexOf(node); <add> if (idx >= 0) { <add> this._children.splice(idx, 1); <add> this._document._onElementRemoved(node); <add> node.parentNode = undefined; <add> } <ide> } <ide> <ide> setAttribute(name, value) {
11
Text
Text
add new sub-section about using pipes in component
96a424820278b2a7532f1a2272b1ff15826ba2a8
<ide><path>guide/english/angular/pipes/index.md <ide> export class AppComponent { <ide> <h6>{{ someValue | example:‘lowercase’ }}</h6> <ide> ``` <ide> <del>Understanding the above example means you understand Angular pipes. There is only one more topic left to discuss. <add>### Using Pipes in Components or Services <add>Other than using pipes in the html template as detailed above, we also can call the pipe programmatically in our components or services. <add> <add>Consider the `ExamplePipe` created above. To use it in a component, we need to provide it to the `@NgModule` where our component is declared. <add> <add>```typescript <add>// app.module.ts <add>import { ExamplePipe } from 'example.pipe'; <add> <add>@NgModule({ <add> ... <add> providers: [ExamplePipe], <add> ... <add>}) <add>export class AppModule { } <add>``` <add> <add>In our component, we need to inject it into the constructor. Then we simply call the transform method on the pipe and passing in the arguments like so: <add> <add>```typescript <add>// app.component.ts <add>import { ExamplePipe } from 'example.pipe'; <add> <add>@Component({ <add> templateUrl: 'app.component.html' <add>}) <add>export class AppComponent { <add> <add> constructor(private examplePipe:ExamplePipe) <add> someValue:string = "HeLlO WoRlD!"; <add> <add> // we can call toUpperCase programmatically to convert the string to uppercase <add> toUpperCase(){ <add> this.someValue = this.examplePipe.transform(this.someValue, 'uppercase'); <add> } <add> <add>} <add>``` <add> <add>Understanding the above examples means you understand Angular pipes. There is only one more topic left to discuss. <ide> <ide> #### Pure and Impure Pipes <ide>
1
Javascript
Javascript
use a different name depending on channel
2d6cc4f17227ca22cfeeefdbd257813c8aff1435
<ide><path>script/config.js <ide> const computedAppVersion = computeAppVersion( <ide> const channel = getChannel(computedAppVersion); <ide> const appName = getAppName(channel); <ide> const executableName = getExecutableName(channel, appName); <add>const channelName = getChannelName(channel); <ide> <ide> module.exports = { <ide> appMetadata, <ide> apmMetadata, <ide> channel, <add> channelName, <ide> appName, <ide> executableName, <ide> computedAppVersion, <ide> module.exports = { <ide> snapshotAuxiliaryData: {} <ide> }; <ide> <add>function getChannelName(channel) { <add> return channel === 'stable' <add> ? 'atom' <add> : `atom-${channel}`; <add>} <add> <ide> function getChannel(version) { <ide> const match = version.match(/\d+\.\d+\.\d+(-([a-z]+)(\d+|-\w{4,})?)?$/); <ide> if (!match) { <ide><path>script/lib/create-windows-installer.js <ide> module.exports = packagedAppPath => { <ide> const updateUrlPrefix = <ide> process.env.ATOM_UPDATE_URL_PREFIX || 'https://atom.io'; <ide> const options = { <add> name: CONFIG.channelName, <ide> title: CONFIG.appName, <ide> exe: CONFIG.executableName, <ide> appDirectory: packagedAppPath,
2
Python
Python
use moveaxis instead of rollaxis internally
029863eae86b9df2de4b9a9843ca8f88c99130df
<ide><path>numpy/core/numeric.py <ide> def rollaxis(a, axis, start=0): <ide> """ <ide> Roll the specified axis backwards, until it lies in a given position. <ide> <add> This function continues to be supported for backward compatibility, but you <add> should prefer `moveaxis`. The `moveaxis` function was added in NumPy <add> 1.11. <add> <ide> Parameters <ide> ---------- <ide> a : ndarray <ide> def moveaxis(a, source, destination): <ide> <ide> # fix hack in scipy which imports this function <ide> def _move_axis_to_0(a, axis): <del> return rollaxis(a, axis, 0) <add> return moveaxis(a, axis, 0) <ide> <ide> <ide> def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): <ide> def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): <ide> axisb = normalize_axis_index(axisb, b.ndim, msg_prefix='axisb') <ide> <ide> # Move working axis to the end of the shape <del> a = rollaxis(a, axisa, a.ndim) <del> b = rollaxis(b, axisb, b.ndim) <add> a = moveaxis(a, axisa, -1) <add> b = moveaxis(b, axisb, -1) <ide> msg = ("incompatible dimensions for cross product\n" <ide> "(dimension must be 2 or 3)") <ide> if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3): <ide> def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): <ide> multiply(a0, b1, out=cp2) <ide> cp2 -= a1 * b0 <ide> <del> # This works because we are moving the last axis <del> return rollaxis(cp, -1, axisc) <add> return moveaxis(cp, -1, axisc) <ide> <ide> <ide> # Use numarray's printing function <ide><path>numpy/core/tests/test_shape_base.py <ide> def test_exceptions(self): <ide> np.concatenate((a, b), axis=axis[0]) # OK <ide> assert_raises(ValueError, np.concatenate, (a, b), axis=axis[1]) <ide> assert_raises(ValueError, np.concatenate, (a, b), axis=axis[2]) <del> a = np.rollaxis(a, -1) <del> b = np.rollaxis(b, -1) <add> a = np.moveaxis(a, -1, 0) <add> b = np.moveaxis(b, -1, 0) <ide> axis.append(axis.pop(0)) <ide> <ide> # No arrays to concatenate raises ValueError <ide><path>numpy/lib/function_base.py <ide> def _percentile(a, q, axis=None, out=None, <ide> <ide> ap.partition(indices, axis=axis) <ide> # ensure axis with qth is first <del> ap = np.rollaxis(ap, axis, 0) <add> ap = np.moveaxis(ap, axis, 0) <ide> axis = 0 <ide> <ide> # Check if the array contains any nan's <ide> def _percentile(a, q, axis=None, out=None, <ide> ap.partition(concatenate((indices_below, indices_above)), axis=axis) <ide> <ide> # ensure axis with qth is first <del> ap = np.rollaxis(ap, axis, 0) <del> weights_below = np.rollaxis(weights_below, axis, 0) <del> weights_above = np.rollaxis(weights_above, axis, 0) <add> ap = np.moveaxis(ap, axis, 0) <add> weights_below = np.moveaxis(weights_below, axis, 0) <add> weights_above = np.moveaxis(weights_above, axis, 0) <ide> axis = 0 <ide> <ide> # Check if the array contains any nan's <ide> def _percentile(a, q, axis=None, out=None, <ide> x2 = take(ap, indices_above, axis=axis) * weights_above <ide> <ide> # ensure axis with qth is first <del> x1 = np.rollaxis(x1, axis, 0) <del> x2 = np.rollaxis(x2, axis, 0) <add> x1 = np.moveaxis(x1, axis, 0) <add> x2 = np.moveaxis(x2, axis, 0) <ide> <ide> if zerod: <ide> x1 = x1.squeeze(0) <ide> def insert(arr, obj, values, axis=None): <ide> # broadcasting is very different here, since a[:,0,:] = ... behaves <ide> # very different from a[:,[0],:] = ...! This changes values so that <ide> # it works likes the second case. (here a[:,0:1,:]) <del> values = np.rollaxis(values, 0, (axis % values.ndim) + 1) <add> values = np.moveaxis(values, 0, axis) <ide> numnew = values.shape[axis] <ide> newshape[axis] += numnew <ide> new = empty(newshape, arr.dtype, arrorder) <ide><path>numpy/lib/nanfunctions.py <ide> def _nanpercentile(a, q, axis=None, out=None, overwrite_input=False, <ide> # Move that axis to the beginning to match percentile's <ide> # convention. <ide> if q.ndim != 0: <del> result = np.rollaxis(result, axis) <add> result = np.moveaxis(result, axis, 0) <ide> <ide> if out is not None: <ide> out[...] = result <ide><path>numpy/lib/tests/test_function_base.py <ide> def test_extended_axis(self): <ide> o = np.random.normal(size=(71, 23)) <ide> x = np.dstack([o] * 10) <ide> assert_equal(np.percentile(x, 30, axis=(0, 1)), np.percentile(o, 30)) <del> x = np.rollaxis(x, -1, 0) <add> x = np.moveaxis(x, -1, 0) <ide> assert_equal(np.percentile(x, 30, axis=(-2, -1)), np.percentile(o, 30)) <ide> x = x.swapaxes(0, 1).copy() <ide> assert_equal(np.percentile(x, 30, axis=(0, -1)), np.percentile(o, 30)) <ide> def test_extended_axis(self): <ide> o = np.random.normal(size=(71, 23)) <ide> x = np.dstack([o] * 10) <ide> assert_equal(np.median(x, axis=(0, 1)), np.median(o)) <del> x = np.rollaxis(x, -1, 0) <add> x = np.moveaxis(x, -1, 0) <ide> assert_equal(np.median(x, axis=(-2, -1)), np.median(o)) <ide> x = x.swapaxes(0, 1).copy() <ide> assert_equal(np.median(x, axis=(0, -1)), np.median(o)) <ide><path>numpy/lib/utils.py <ide> def _median_nancheck(data, result, axis, out): <ide> """ <ide> if data.size == 0: <ide> return result <del> data = np.rollaxis(data, axis, data.ndim) <add> data = np.moveaxis(data, axis, -1) <ide> n = np.isnan(data[..., -1]) <ide> # masked NaN values are ok <ide> if np.ma.isMaskedArray(n): <ide><path>numpy/linalg/linalg.py <ide> array, asarray, zeros, empty, empty_like, transpose, intc, single, double, <ide> csingle, cdouble, inexact, complexfloating, newaxis, ravel, all, Inf, dot, <ide> add, multiply, sqrt, maximum, fastCopyAndTranspose, sum, isfinite, size, <del> finfo, errstate, geterrobj, longdouble, rollaxis, amin, amax, product, abs, <add> finfo, errstate, geterrobj, longdouble, moveaxis, amin, amax, product, abs, <ide> broadcast, atleast_2d, intp, asanyarray, isscalar, object_, ones <ide> ) <ide> from numpy.core.multiarray import normalize_axis_index <ide> def _multi_svd_norm(x, row_axis, col_axis, op): <ide> is `numpy.amin` or `numpy.amax` or `numpy.sum`. <ide> <ide> """ <del> if row_axis > col_axis: <del> row_axis -= 1 <del> y = rollaxis(rollaxis(x, col_axis, x.ndim), row_axis, -1) <add> y = moveaxis(x, (row_axis, col_axis), (-2, -1)) <ide> result = op(svd(y, compute_uv=0), axis=-1) <ide> return result <ide> <ide><path>numpy/polynomial/chebyshev.py <ide> def chebder(c, m=1, scl=1, axis=0): <ide> if cnt == 0: <ide> return c <ide> <del> c = np.rollaxis(c, iaxis) <add> c = np.moveaxis(c, iaxis, 0) <ide> n = len(c) <ide> if cnt >= n: <ide> c = c[:1]*0 <ide> def chebder(c, m=1, scl=1, axis=0): <ide> der[1] = 4*c[2] <ide> der[0] = c[1] <ide> c = der <del> c = np.rollaxis(c, 0, iaxis + 1) <add> c = np.moveaxis(c, 0, iaxis) <ide> return c <ide> <ide> <ide> def chebint(c, m=1, k=[], lbnd=0, scl=1, axis=0): <ide> if cnt == 0: <ide> return c <ide> <del> c = np.rollaxis(c, iaxis) <add> c = np.moveaxis(c, iaxis, 0) <ide> k = list(k) + [0]*(cnt - len(k)) <ide> for i in range(cnt): <ide> n = len(c) <ide> def chebint(c, m=1, k=[], lbnd=0, scl=1, axis=0): <ide> tmp[j - 1] -= c[j]/(2*(j - 1)) <ide> tmp[0] += k[i] - chebval(lbnd, tmp) <ide> c = tmp <del> c = np.rollaxis(c, 0, iaxis + 1) <add> c = np.moveaxis(c, 0, iaxis) <ide> return c <ide> <ide> <ide> def chebvander(x, deg): <ide> v[1] = x <ide> for i in range(2, ideg + 1): <ide> v[i] = v[i-1]*x2 - v[i-2] <del> return np.rollaxis(v, 0, v.ndim) <add> return np.moveaxis(v, 0, -1) <ide> <ide> <ide> def chebvander2d(x, y, deg): <ide><path>numpy/polynomial/hermite.py <ide> def hermder(c, m=1, scl=1, axis=0): <ide> if cnt == 0: <ide> return c <ide> <del> c = np.rollaxis(c, iaxis) <add> c = np.moveaxis(c, iaxis, 0) <ide> n = len(c) <ide> if cnt >= n: <ide> c = c[:1]*0 <ide> def hermder(c, m=1, scl=1, axis=0): <ide> for j in range(n, 0, -1): <ide> der[j - 1] = (2*j)*c[j] <ide> c = der <del> c = np.rollaxis(c, 0, iaxis + 1) <add> c = np.moveaxis(c, 0, iaxis) <ide> return c <ide> <ide> <ide> def hermint(c, m=1, k=[], lbnd=0, scl=1, axis=0): <ide> if cnt == 0: <ide> return c <ide> <del> c = np.rollaxis(c, iaxis) <add> c = np.moveaxis(c, iaxis, 0) <ide> k = list(k) + [0]*(cnt - len(k)) <ide> for i in range(cnt): <ide> n = len(c) <ide> def hermint(c, m=1, k=[], lbnd=0, scl=1, axis=0): <ide> tmp[j + 1] = c[j]/(2*(j + 1)) <ide> tmp[0] += k[i] - hermval(lbnd, tmp) <ide> c = tmp <del> c = np.rollaxis(c, 0, iaxis + 1) <add> c = np.moveaxis(c, 0, iaxis) <ide> return c <ide> <ide> <ide> def hermvander(x, deg): <ide> v[1] = x2 <ide> for i in range(2, ideg + 1): <ide> v[i] = (v[i-1]*x2 - v[i-2]*(2*(i - 1))) <del> return np.rollaxis(v, 0, v.ndim) <add> return np.moveaxis(v, 0, -1) <ide> <ide> <ide> def hermvander2d(x, y, deg): <ide><path>numpy/polynomial/hermite_e.py <ide> def hermeder(c, m=1, scl=1, axis=0): <ide> if cnt == 0: <ide> return c <ide> <del> c = np.rollaxis(c, iaxis) <add> c = np.moveaxis(c, iaxis, 0) <ide> n = len(c) <ide> if cnt >= n: <ide> return c[:1]*0 <ide> def hermeder(c, m=1, scl=1, axis=0): <ide> for j in range(n, 0, -1): <ide> der[j - 1] = j*c[j] <ide> c = der <del> c = np.rollaxis(c, 0, iaxis + 1) <add> c = np.moveaxis(c, 0, iaxis) <ide> return c <ide> <ide> <ide> def hermeint(c, m=1, k=[], lbnd=0, scl=1, axis=0): <ide> if cnt == 0: <ide> return c <ide> <del> c = np.rollaxis(c, iaxis) <add> c = np.moveaxis(c, iaxis, 0) <ide> k = list(k) + [0]*(cnt - len(k)) <ide> for i in range(cnt): <ide> n = len(c) <ide> def hermeint(c, m=1, k=[], lbnd=0, scl=1, axis=0): <ide> tmp[j + 1] = c[j]/(j + 1) <ide> tmp[0] += k[i] - hermeval(lbnd, tmp) <ide> c = tmp <del> c = np.rollaxis(c, 0, iaxis + 1) <add> c = np.moveaxis(c, 0, iaxis) <ide> return c <ide> <ide> <ide> def hermevander(x, deg): <ide> v[1] = x <ide> for i in range(2, ideg + 1): <ide> v[i] = (v[i-1]*x - v[i-2]*(i - 1)) <del> return np.rollaxis(v, 0, v.ndim) <add> return np.moveaxis(v, 0, -1) <ide> <ide> <ide> def hermevander2d(x, y, deg): <ide><path>numpy/polynomial/laguerre.py <ide> def lagder(c, m=1, scl=1, axis=0): <ide> if cnt == 0: <ide> return c <ide> <del> c = np.rollaxis(c, iaxis) <add> c = np.moveaxis(c, iaxis, 0) <ide> n = len(c) <ide> if cnt >= n: <ide> c = c[:1]*0 <ide> def lagder(c, m=1, scl=1, axis=0): <ide> c[j - 1] += c[j] <ide> der[0] = -c[1] <ide> c = der <del> c = np.rollaxis(c, 0, iaxis + 1) <add> c = np.moveaxis(c, 0, iaxis) <ide> return c <ide> <ide> <ide> def lagint(c, m=1, k=[], lbnd=0, scl=1, axis=0): <ide> if cnt == 0: <ide> return c <ide> <del> c = np.rollaxis(c, iaxis) <add> c = np.moveaxis(c, iaxis, 0) <ide> k = list(k) + [0]*(cnt - len(k)) <ide> for i in range(cnt): <ide> n = len(c) <ide> def lagint(c, m=1, k=[], lbnd=0, scl=1, axis=0): <ide> tmp[j + 1] = -c[j] <ide> tmp[0] += k[i] - lagval(lbnd, tmp) <ide> c = tmp <del> c = np.rollaxis(c, 0, iaxis + 1) <add> c = np.moveaxis(c, 0, iaxis) <ide> return c <ide> <ide> <ide> def lagvander(x, deg): <ide> v[1] = 1 - x <ide> for i in range(2, ideg + 1): <ide> v[i] = (v[i-1]*(2*i - 1 - x) - v[i-2]*(i - 1))/i <del> return np.rollaxis(v, 0, v.ndim) <add> return np.moveaxis(v, 0, -1) <ide> <ide> <ide> def lagvander2d(x, y, deg): <ide><path>numpy/polynomial/legendre.py <ide> def legder(c, m=1, scl=1, axis=0): <ide> if cnt == 0: <ide> return c <ide> <del> c = np.rollaxis(c, iaxis) <add> c = np.moveaxis(c, iaxis, 0) <ide> n = len(c) <ide> if cnt >= n: <ide> c = c[:1]*0 <ide> def legder(c, m=1, scl=1, axis=0): <ide> der[1] = 3*c[2] <ide> der[0] = c[1] <ide> c = der <del> c = np.rollaxis(c, 0, iaxis + 1) <add> c = np.moveaxis(c, 0, iaxis) <ide> return c <ide> <ide> <ide> def legint(c, m=1, k=[], lbnd=0, scl=1, axis=0): <ide> if cnt == 0: <ide> return c <ide> <del> c = np.rollaxis(c, iaxis) <add> c = np.moveaxis(c, iaxis, 0) <ide> k = list(k) + [0]*(cnt - len(k)) <ide> for i in range(cnt): <ide> n = len(c) <ide> def legint(c, m=1, k=[], lbnd=0, scl=1, axis=0): <ide> tmp[j - 1] -= t <ide> tmp[0] += k[i] - legval(lbnd, tmp) <ide> c = tmp <del> c = np.rollaxis(c, 0, iaxis + 1) <add> c = np.moveaxis(c, 0, iaxis) <ide> return c <ide> <ide> <ide> def legvander(x, deg): <ide> v[1] = x <ide> for i in range(2, ideg + 1): <ide> v[i] = (v[i-1]*x*(2*i - 1) - v[i-2]*(i - 1))/i <del> return np.rollaxis(v, 0, v.ndim) <add> return np.moveaxis(v, 0, -1) <ide> <ide> <ide> def legvander2d(x, y, deg): <ide><path>numpy/polynomial/polynomial.py <ide> def polyder(c, m=1, scl=1, axis=0): <ide> if cnt == 0: <ide> return c <ide> <del> c = np.rollaxis(c, iaxis) <add> c = np.moveaxis(c, iaxis, 0) <ide> n = len(c) <ide> if cnt >= n: <ide> c = c[:1]*0 <ide> def polyder(c, m=1, scl=1, axis=0): <ide> for j in range(n, 0, -1): <ide> der[j - 1] = j*c[j] <ide> c = der <del> c = np.rollaxis(c, 0, iaxis + 1) <add> c = np.moveaxis(c, 0, iaxis) <ide> return c <ide> <ide> <ide> def polyint(c, m=1, k=[], lbnd=0, scl=1, axis=0): <ide> return c <ide> <ide> k = list(k) + [0]*(cnt - len(k)) <del> c = np.rollaxis(c, iaxis) <add> c = np.moveaxis(c, iaxis, 0) <ide> for i in range(cnt): <ide> n = len(c) <ide> c *= scl <ide> def polyint(c, m=1, k=[], lbnd=0, scl=1, axis=0): <ide> tmp[j + 1] = c[j]/(j + 1) <ide> tmp[0] += k[i] - polyval(lbnd, tmp) <ide> c = tmp <del> c = np.rollaxis(c, 0, iaxis + 1) <add> c = np.moveaxis(c, 0, iaxis) <ide> return c <ide> <ide> <ide> def polyvander(x, deg): <ide> v[1] = x <ide> for i in range(2, ideg + 1): <ide> v[i] = v[i-1]*x <del> return np.rollaxis(v, 0, v.ndim) <add> return np.moveaxis(v, 0, -1) <ide> <ide> <ide> def polyvander2d(x, y, deg):
13
Python
Python
remove dependency between bart and led (slow/fast)
6ef16f2b67bdf2797297d65f72efc68256d11e3f
<ide><path>src/transformers/models/led/tokenization_led.py <ide> # limitations under the License. <ide> """Tokenization classes for LED.""" <ide> <del>from typing import Dict, Optional, Union <add>import json <add>import os <add>from functools import lru_cache <add>from typing import Dict, List, Optional, Tuple, Union <ide> <add>import regex as re <add> <add>from ...tokenization_utils import AddedToken, PreTrainedTokenizer <ide> from ...tokenization_utils_base import BatchEncoding, EncodedInput <ide> from ...utils import PaddingStrategy, logging <del>from ..bart.tokenization_bart import BartTokenizer <ide> <ide> <ide> logger = logging.get_logger(__name__) <ide> <add> <add>VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} <add> <add># See all LED models at https://huggingface.co/models?filter=LED <ide> PRETRAINED_VOCAB_FILES_MAP = { <ide> "vocab_file": { <ide> "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json", <ide> } <ide> <ide> <del>class LEDTokenizer(BartTokenizer): <add>@lru_cache() <add># Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode <add>def bytes_to_unicode(): <add> """ <add> Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control <add> characters the bpe code barfs on. <add> <add> The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab <add> if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for <add> decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup <add> tables between utf-8 bytes and unicode strings. <ide> """ <del> Construct a LED tokenizer. <add> bs = ( <add> list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1)) <add> ) <add> cs = bs[:] <add> n = 0 <add> for b in range(2**8): <add> if b not in bs: <add> bs.append(b) <add> cs.append(2**8 + n) <add> n += 1 <add> cs = [chr(n) for n in cs] <add> return dict(zip(bs, cs)) <ide> <del> [`LEDTokenizer`] is identical to [`BartTokenizer`] and runs end-to-end tokenization: punctuation splitting and <del> wordpiece. <ide> <del> Refer to superclass [`BartTokenizer`] for usage examples and documentation concerning parameters. <add># Copied from transformers.models.bart.tokenization_bart.get_pairs <add>def get_pairs(word): <ide> """ <add> Return set of symbol pairs in a word. <add> <add> Word is represented as tuple of symbols (symbols being variable-length strings). <add> """ <add> pairs = set() <add> prev_char = word[0] <add> for char in word[1:]: <add> pairs.add((prev_char, char)) <add> prev_char = char <add> return pairs <add> <add> <add>class LEDTokenizer(PreTrainedTokenizer): <add> """ <add> Constructs a LED tokenizer, which is smilar to the ROBERTa tokenizer, using byte-level Byte-Pair-Encoding. <add> <add> This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will <add> be encoded differently whether it is at the beginning of the sentence (without space) or not: <add> <add> ``` <add> >>> from transformers import LEDTokenizer <add> >>> tokenizer = LEDTokenizer.from_pretrained("allenai/led-base-16384") <add> >>> tokenizer("Hello world")['input_ids'] <add> [0, 31414, 232, 2] <add> >>> tokenizer(" Hello world")['input_ids'] <add> [0, 20920, 232, 2] <add> ``` <add> <add> You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you <add> call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance. <add> <add> <Tip> <add> <add> When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one). <add> <add> </Tip> <add> <add> This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to <add> this superclass for more information regarding those methods. <ide> <add> Args: <add> vocab_file (`str`): <add> Path to the vocabulary file. <add> merges_file (`str`): <add> Path to the merges file. <add> errors (`str`, *optional*, defaults to `"replace"`): <add> Paradigm to follow when decoding bytes to UTF-8. See <add> [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information. <add> bos_token (`str`, *optional*, defaults to `"<s>"`): <add> The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token. <add> <add> <Tip> <add> <add> When building a sequence using special tokens, this is not the token that is used for the beginning of <add> sequence. The token used is the `cls_token`. <add> <add> </Tip> <add> <add> eos_token (`str`, *optional*, defaults to `"</s>"`): <add> The end of sequence token. <add> <add> <Tip> <add> <add> When building a sequence using special tokens, this is not the token that is used for the end of sequence. <add> The token used is the `sep_token`. <add> <add> </Tip> <add> <add> sep_token (`str`, *optional*, defaults to `"</s>"`): <add> The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for <add> sequence classification or for a text and a question for question answering. It is also used as the last <add> token of a sequence built with special tokens. <add> cls_token (`str`, *optional*, defaults to `"<s>"`): <add> The classifier token which is used when doing sequence classification (classification of the whole sequence <add> instead of per-token classification). It is the first token of the sequence when built with special tokens. <add> unk_token (`str`, *optional*, defaults to `"<unk>"`): <add> The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this <add> token instead. <add> pad_token (`str`, *optional*, defaults to `"<pad>"`): <add> The token used for padding, for example when batching sequences of different lengths. <add> mask_token (`str`, *optional*, defaults to `"<mask>"`): <add> The token used for masking values. This is the token used when training this model with masked language <add> modeling. This is the token which the model will try to predict. <add> add_prefix_space (`bool`, *optional*, defaults to `False`): <add> Whether or not to add an initial space to the input. This allows to treat the leading word just as any <add> other word. (BART tokenizer detect beginning of words by the preceding space). <add> """ <add> <add> vocab_files_names = VOCAB_FILES_NAMES <ide> pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP <ide> max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES <add> model_input_names = ["input_ids", "attention_mask"] <add> <add> # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.__init__ <add> def __init__( <add> self, <add> vocab_file, <add> merges_file, <add> errors="replace", <add> bos_token="<s>", <add> eos_token="</s>", <add> sep_token="</s>", <add> cls_token="<s>", <add> unk_token="<unk>", <add> pad_token="<pad>", <add> mask_token="<mask>", <add> add_prefix_space=False, <add> **kwargs <add> ): <add> bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token <add> eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token <add> sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token <add> cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token <add> unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token <add> pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token <add> <add> # Mask token behave like a normal word, i.e. include the space before it <add> mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token <add> <add> super().__init__( <add> errors=errors, <add> bos_token=bos_token, <add> eos_token=eos_token, <add> unk_token=unk_token, <add> sep_token=sep_token, <add> cls_token=cls_token, <add> pad_token=pad_token, <add> mask_token=mask_token, <add> add_prefix_space=add_prefix_space, <add> **kwargs, <add> ) <add> <add> with open(vocab_file, encoding="utf-8") as vocab_handle: <add> self.encoder = json.load(vocab_handle) <add> self.decoder = {v: k for k, v in self.encoder.items()} <add> self.errors = errors # how to handle errors in decoding <add> self.byte_encoder = bytes_to_unicode() <add> self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} <add> with open(merges_file, encoding="utf-8") as merges_handle: <add> bpe_merges = merges_handle.read().split("\n")[1:-1] <add> bpe_merges = [tuple(merge.split()) for merge in bpe_merges] <add> self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges)))) <add> self.cache = {} <add> self.add_prefix_space = add_prefix_space <add> <add> # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions <add> self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""") <add> <add> @property <add> # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size <add> def vocab_size(self): <add> return len(self.encoder) <add> <add> # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.get_vocab <add> def get_vocab(self): <add> return dict(self.encoder, **self.added_tokens_encoder) <add> <add> # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.bpe <add> def bpe(self, token): <add> if token in self.cache: <add> return self.cache[token] <add> word = tuple(token) <add> pairs = get_pairs(word) <add> <add> if not pairs: <add> return token <add> <add> while True: <add> bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf"))) <add> if bigram not in self.bpe_ranks: <add> break <add> first, second = bigram <add> new_word = [] <add> i = 0 <add> while i < len(word): <add> try: <add> j = word.index(first, i) <add> except ValueError: <add> new_word.extend(word[i:]) <add> break <add> else: <add> new_word.extend(word[i:j]) <add> i = j <add> <add> if word[i] == first and i < len(word) - 1 and word[i + 1] == second: <add> new_word.append(first + second) <add> i += 2 <add> else: <add> new_word.append(word[i]) <add> i += 1 <add> new_word = tuple(new_word) <add> word = new_word <add> if len(word) == 1: <add> break <add> else: <add> pairs = get_pairs(word) <add> word = " ".join(word) <add> self.cache[token] = word <add> return word <add> <add> # Copied from transformers.models.bart.tokenization_bart.BartTokenizer._tokenize <add> def _tokenize(self, text): <add> """Tokenize a string.""" <add> bpe_tokens = [] <add> for token in re.findall(self.pat, text): <add> token = "".join( <add> self.byte_encoder[b] for b in token.encode("utf-8") <add> ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) <add> bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" ")) <add> return bpe_tokens <add> <add> # Copied from transformers.models.bart.tokenization_bart.BartTokenizer._convert_token_to_id <add> def _convert_token_to_id(self, token): <add> """Converts a token (str) in an id using the vocab.""" <add> return self.encoder.get(token, self.encoder.get(self.unk_token)) <add> <add> # Copied from transformers.models.bart.tokenization_bart.BartTokenizer._convert_id_to_token <add> def _convert_id_to_token(self, index): <add> """Converts an index (integer) in a token (str) using the vocab.""" <add> return self.decoder.get(index) <add> <add> # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.convert_tokens_to_string <add> def convert_tokens_to_string(self, tokens): <add> """Converts a sequence of tokens (string) in a single string.""" <add> text = "".join(tokens) <add> text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors) <add> return text <add> <add> # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.save_vocabulary <add> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: <add> if not os.path.isdir(save_directory): <add> logger.error(f"Vocabulary path ({save_directory}) should be a directory") <add> return <add> vocab_file = os.path.join( <add> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] <add> ) <add> merge_file = os.path.join( <add> save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] <add> ) <add> <add> with open(vocab_file, "w", encoding="utf-8") as f: <add> f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n") <add> <add> index = 0 <add> with open(merge_file, "w", encoding="utf-8") as writer: <add> writer.write("#version: 0.2\n") <add> for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]): <add> if index != token_index: <add> logger.warning( <add> f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive." <add> " Please check that the tokenizer is not corrupted!" <add> ) <add> index = token_index <add> writer.write(" ".join(bpe_tokens) + "\n") <add> index += 1 <add> <add> return vocab_file, merge_file <add> <add> # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.build_inputs_with_special_tokens with BART->LED <add> def build_inputs_with_special_tokens( <add> self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None <add> ) -> List[int]: <add> """ <add> Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and <add> adding special tokens. A LED sequence has the following format: <add> <add> - single sequence: `<s> X </s>` <add> - pair of sequences: `<s> A </s></s> B </s>` <add> <add> Args: <add> token_ids_0 (`List[int]`): <add> List of IDs to which the special tokens will be added. <add> token_ids_1 (`List[int]`, *optional*): <add> Optional second list of IDs for sequence pairs. <add> <add> Returns: <add> `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens. <add> """ <add> if token_ids_1 is None: <add> return [self.cls_token_id] + token_ids_0 + [self.sep_token_id] <add> cls = [self.cls_token_id] <add> sep = [self.sep_token_id] <add> return cls + token_ids_0 + sep + sep + token_ids_1 + sep <add> <add> # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.get_special_tokens_mask <add> def get_special_tokens_mask( <add> self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False <add> ) -> List[int]: <add> """ <add> Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding <add> special tokens using the tokenizer `prepare_for_model` method. <add> <add> Args: <add> token_ids_0 (`List[int]`): <add> List of IDs. <add> token_ids_1 (`List[int]`, *optional*): <add> Optional second list of IDs for sequence pairs. <add> already_has_special_tokens (`bool`, *optional*, defaults to `False`): <add> Whether or not the token list is already formatted with special tokens for the model. <add> <add> Returns: <add> `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. <add> """ <add> if already_has_special_tokens: <add> return super().get_special_tokens_mask( <add> token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True <add> ) <add> <add> if token_ids_1 is None: <add> return [1] + ([0] * len(token_ids_0)) + [1] <add> return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1] <add> <add> # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.create_token_type_ids_from_sequences with BART->LED <add> def create_token_type_ids_from_sequences( <add> self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None <add> ) -> List[int]: <add> """ <add> Create a mask from the two sequences passed to be used in a sequence-pair classification task. LED does not <add> make use of token type ids, therefore a list of zeros is returned. <add> <add> Args: <add> token_ids_0 (`List[int]`): <add> List of IDs. <add> token_ids_1 (`List[int]`, *optional*): <add> Optional second list of IDs for sequence pairs. <add> <add> Returns: <add> `List[int]`: List of zeros. <add> """ <add> sep = [self.sep_token_id] <add> cls = [self.cls_token_id] <add> <add> if token_ids_1 is None: <add> return len(cls + token_ids_0 + sep) * [0] <add> return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0] <add> <add> # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.prepare_for_tokenization <add> def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs): <add> add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space) <add> if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()): <add> text = " " + text <add> return (text, kwargs) <ide> <ide> def _pad( <ide> self, <ide><path>src/transformers/models/led/tokenization_led_fast.py <ide> # limitations under the License. <ide> """Tokenization classes for LED.""" <ide> <del>from typing import Dict, Optional, Union <add>import json <add>from typing import Dict, List, Optional, Tuple, Union <ide> <del>from ...tokenization_utils_base import BatchEncoding, EncodedInput <add>from tokenizers import pre_tokenizers, processors <add> <add>from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput <add>from ...tokenization_utils_fast import PreTrainedTokenizerFast <ide> from ...utils import PaddingStrategy, logging <del>from ..bart.tokenization_bart_fast import BartTokenizerFast <ide> from .tokenization_led import LEDTokenizer <ide> <ide> <ide> logger = logging.get_logger(__name__) <ide> <add> <add>VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} <add> <ide> PRETRAINED_VOCAB_FILES_MAP = { <ide> "vocab_file": { <ide> "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json", <ide> } <ide> <ide> <del>class LEDTokenizerFast(BartTokenizerFast): <add>class LEDTokenizerFast(PreTrainedTokenizerFast): <ide> r""" <del> Construct a "fast" LED tokenizer (backed by HuggingFace's *tokenizers* library). <add> Construct a "fast" LED tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2 tokenizer, <add> using byte-level Byte-Pair-Encoding. <add> <add> This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will <add> be encoded differently whether it is at the beginning of the sentence (without space) or not: <add> <add> ``` <add> >>> from transformers import LEDTokenizerFast <add> >>> tokenizer = LEDTokenizerFast.from_pretrained("allenai/led-base-16384") <add> >>> tokenizer("Hello world")['input_ids'] <add> [0, 31414, 232, 2] <add> >>> tokenizer(" Hello world")['input_ids'] <add> [0, 20920, 232, 2] <add> ``` <add> <add> You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you <add> call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance. <add> <add> <Tip> <add> <add> When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`. <add> <add> </Tip> <add> <add> This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should <add> refer to this superclass for more information regarding those methods. <add> <add> Args: <add> vocab_file (`str`): <add> Path to the vocabulary file. <add> merges_file (`str`): <add> Path to the merges file. <add> errors (`str`, *optional*, defaults to `"replace"`): <add> Paradigm to follow when decoding bytes to UTF-8. See <add> [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information. <add> bos_token (`str`, *optional*, defaults to `"<s>"`): <add> The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token. <add> <add> <Tip> <ide> <del> [`LEDTokenizerFast`] is identical to [`BartTokenizerFast`] and runs end-to-end tokenization: punctuation splitting <del> and wordpiece. <add> When building a sequence using special tokens, this is not the token that is used for the beginning of <add> sequence. The token used is the `cls_token`. <ide> <del> Refer to superclass [`BartTokenizerFast`] for usage examples and documentation concerning parameters. <add> </Tip> <add> <add> eos_token (`str`, *optional*, defaults to `"</s>"`): <add> The end of sequence token. <add> <add> <Tip> <add> <add> When building a sequence using special tokens, this is not the token that is used for the end of sequence. <add> The token used is the `sep_token`. <add> <add> </Tip> <add> <add> sep_token (`str`, *optional*, defaults to `"</s>"`): <add> The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for <add> sequence classification or for a text and a question for question answering. It is also used as the last <add> token of a sequence built with special tokens. <add> cls_token (`str`, *optional*, defaults to `"<s>"`): <add> The classifier token which is used when doing sequence classification (classification of the whole sequence <add> instead of per-token classification). It is the first token of the sequence when built with special tokens. <add> unk_token (`str`, *optional*, defaults to `"<unk>"`): <add> The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this <add> token instead. <add> pad_token (`str`, *optional*, defaults to `"<pad>"`): <add> The token used for padding, for example when batching sequences of different lengths. <add> mask_token (`str`, *optional*, defaults to `"<mask>"`): <add> The token used for masking values. This is the token used when training this model with masked language <add> modeling. This is the token which the model will try to predict. <add> add_prefix_space (`bool`, *optional*, defaults to `False`): <add> Whether or not to add an initial space to the input. This allows to treat the leading word just as any <add> other word. (LED tokenizer detect beginning of words by the preceding space). <add> trim_offsets (`bool`, *optional*, defaults to `True`): <add> Whether the post processing step should trim offsets to avoid including whitespaces. <ide> """ <ide> <add> vocab_files_names = VOCAB_FILES_NAMES <ide> pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP <ide> max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES <ide> slow_tokenizer_class = LEDTokenizer <add> model_input_names = ["input_ids", "attention_mask"] <add> <add> # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.__init__ <add> def __init__( <add> self, <add> vocab_file=None, <add> merges_file=None, <add> tokenizer_file=None, <add> errors="replace", <add> bos_token="<s>", <add> eos_token="</s>", <add> sep_token="</s>", <add> cls_token="<s>", <add> unk_token="<unk>", <add> pad_token="<pad>", <add> mask_token="<mask>", <add> add_prefix_space=False, <add> trim_offsets=True, <add> **kwargs <add> ): <add> super().__init__( <add> vocab_file, <add> merges_file, <add> tokenizer_file=tokenizer_file, <add> errors=errors, <add> bos_token=bos_token, <add> eos_token=eos_token, <add> sep_token=sep_token, <add> cls_token=cls_token, <add> unk_token=unk_token, <add> pad_token=pad_token, <add> mask_token=mask_token, <add> add_prefix_space=add_prefix_space, <add> trim_offsets=trim_offsets, <add> **kwargs, <add> ) <add> <add> pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) <add> if pre_tok_state.get("add_prefix_space", add_prefix_space) != add_prefix_space: <add> pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop("type")) <add> pre_tok_state["add_prefix_space"] = add_prefix_space <add> self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state) <add> <add> self.add_prefix_space = add_prefix_space <add> <add> # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` <add> tokenizer_component = "post_processor" <add> tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None) <add> if tokenizer_component_instance: <add> state = json.loads(tokenizer_component_instance.__getstate__()) <add> <add> # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` <add> if "sep" in state: <add> state["sep"] = tuple(state["sep"]) <add> if "cls" in state: <add> state["cls"] = tuple(state["cls"]) <add> <add> changes_to_apply = False <add> <add> if state.get("add_prefix_space", add_prefix_space) != add_prefix_space: <add> state["add_prefix_space"] = add_prefix_space <add> changes_to_apply = True <add> <add> if state.get("trim_offsets", trim_offsets) != trim_offsets: <add> state["trim_offsets"] = trim_offsets <add> changes_to_apply = True <add> <add> if changes_to_apply: <add> component_class = getattr(processors, state.pop("type")) <add> new_value = component_class(**state) <add> setattr(self.backend_tokenizer, tokenizer_component, new_value) <add> <add> @property <add> # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED <add> def mask_token(self) -> str: <add> """ <add> `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not <add> having been set. <add> <add> LED tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily <add> comprise the space before the *<mask>*. <add> """ <add> if self._mask_token is None: <add> if self.verbose: <add> logger.error("Using mask_token, but it is not set yet.") <add> return None <add> return str(self._mask_token) <add> <add> @mask_token.setter <add> def mask_token(self, value): <add> """ <add> Overriding the default behavior of the mask token to have it eat the space before it. <add> <add> This is needed to preserve backward compatibility with all the previously used models based on LED. <add> """ <add> # Mask token behave like a normal word, i.e. include the space before it <add> # So we set lstrip to True <add> value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value <add> self._mask_token = value <add> <add> # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast._batch_encode_plus <add> def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding: <add> is_split_into_words = kwargs.get("is_split_into_words", False) <add> <add> if is_split_into_words and not self.add_prefix_space: <add> raise ValueError( <add> f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " <add> "to use it with pretokenized inputs." <add> ) <add> <add> return super()._batch_encode_plus(*args, **kwargs) <add> <add> # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast._encode_plus <add> def _encode_plus(self, *args, **kwargs) -> BatchEncoding: <add> is_split_into_words = kwargs.get("is_split_into_words", False) <add> <add> if is_split_into_words and not self.add_prefix_space: <add> raise ValueError( <add> f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " <add> "to use it with pretokenized inputs." <add> ) <add> <add> return super()._encode_plus(*args, **kwargs) <add> <add> # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.save_vocabulary <add> def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: <add> files = self._tokenizer.model.save(save_directory, name=filename_prefix) <add> return tuple(files) <add> <add> # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.build_inputs_with_special_tokens <add> def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None): <add> output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id] <add> if token_ids_1 is None: <add> return output <add> <add> return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id] <add> <add> # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.create_token_type_ids_from_sequences with BART->LED <add> def create_token_type_ids_from_sequences( <add> self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None <add> ) -> List[int]: <add> """ <add> Create a mask from the two sequences passed to be used in a sequence-pair classification task. LED does not <add> make use of token type ids, therefore a list of zeros is returned. <add> <add> Args: <add> token_ids_0 (`List[int]`): <add> List of IDs. <add> token_ids_1 (`List[int]`, *optional*): <add> Optional second list of IDs for sequence pairs. <add> <add> Returns: <add> `List[int]`: List of zeros. <add> """ <add> sep = [self.sep_token_id] <add> cls = [self.cls_token_id] <add> <add> if token_ids_1 is None: <add> return len(cls + token_ids_0 + sep) * [0] <add> return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0] <ide> <ide> # Copied from transformers.models.led.tokenization_led.LEDTokenizer._pad <ide> def _pad(
2
Java
Java
fix cronexpression issue with dst
7276752e7cbc87aead678ae84ec8a83e7603a141
<ide><path>spring-context/src/main/java/org/springframework/scheduling/support/CronField.java <ide> public <T extends Temporal & Comparable<? super T>> T elapseUntil(T temporal, in <ide> * Roll forward the give temporal until it reaches the next higher <ide> * order field. Calling this method is equivalent to calling <ide> * {@link #elapseUntil(Temporal, int)} with goal set to the <del> * minimum value of this field's range. <add> * minimum value of this field's range, except for daylight saving. <ide> * @param temporal the temporal to roll forward <ide> * @param <T> the type of temporal <ide> * @return the rolled forward temporal <ide> public <T extends Temporal & Comparable<? super T>> T rollForward(T temporal) { <ide> int current = get(temporal); <ide> ValueRange range = temporal.range(this.field); <ide> long amount = range.getMaximum() - current + 1; <del> return this.field.getBaseUnit().addTo(temporal, amount); <add> T result = this.field.getBaseUnit().addTo(temporal, amount); <add> //adjust daylight saving <add> if (get(result) != range.getMinimum()) { <add> result = this.field.adjustInto(result,result.range(this.field).getMinimum()); <add> } <add> return result; <ide> } <ide> <ide> /** <ide><path>spring-context/src/test/java/org/springframework/scheduling/support/CronExpressionTests.java <ide> public void daylightSaving() { <ide> actual = cronExpression.next(last); <ide> assertThat(actual).isNotNull(); <ide> assertThat(actual).isEqualTo(expected); <add> <add> cronExpression = CronExpression.parse("0 5 0 * * *"); <add> <add> last = ZonedDateTime.parse("2021-03-28T01:00:00+01:00[Europe/Amsterdam]"); <add> expected = ZonedDateTime.parse("2021-03-29T00:05+02:00[Europe/Amsterdam]"); <add> actual = cronExpression.next(last); <add> assertThat(actual).isNotNull(); <add> assertThat(actual).isEqualTo(expected); <ide> } <ide> <ide> @Test
2
Python
Python
add filter for new py3k warning in python 2
1627de4baad000763ef299593e4c73d98790193e
<ide><path>numpy/core/tests/test_defchararray.py <ide> from numpy.core.multiarray import _vec_string <ide> from numpy.testing import ( <ide> run_module_suite, assert_, assert_equal, assert_array_equal, assert_raises, <add> suppress_warnings, <ide> ) <ide> <ide> kw_unicode_true = {'unicode': True} # make 2to3 work properly <ide> def test_decode(self): <ide> A = np.char.array([b'\\u03a3']) <ide> assert_(A.decode('unicode-escape')[0] == '\u03a3') <ide> else: <del> A = np.char.array(['736563726574206d657373616765']) <del> assert_(A.decode('hex_codec')[0] == 'secret message') <add> with suppress_warnings() as sup: <add> if sys.py3kwarning: <add> sup.filter(DeprecationWarning, "'hex_codec'") <add> A = np.char.array(['736563726574206d657373616765']) <add> assert_(A.decode('hex_codec')[0] == 'secret message') <ide> <ide> def test_encode(self): <ide> B = self.B.encode('unicode_escape')
1