content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Python | Python | fix lint error | fc9c3960c173f3ed7fcabcac1e7b0c6d5ffed6cd | <ide><path>libcloud/compute/drivers/dimensiondata.py
<ide> def create_node(self, name,
<ide> >>> images = driver.list_images(location=location)
<ide> >>> image = images[0]
<ide> >>>
<del> >>> node = driver.create_node(name='test_blah_2', image=image, auth=root_pw,
<add> >>> node = driver.create_node(name='test_blah_2', image=image,
<add> >>> auth=root_pw,
<ide> >>> ex_description='test3 node',
<ide> >>> ex_network=my_network,
<ide> >>> ex_is_started=False)
<ide> def create_node(self, name,
<ide> 'additionalNic')
<ide>
<ide> if (nic.private_ip_v4 is None and
<del> nic.vlan is None):
<add> nic.vlan is None):
<ide> raise ValueError("Either a vlan or private_ip_v4 "
<ide> "must be specified for each "
<ide> "additional nic.")
<ide>
<ide> if (nic.private_ip_v4 is not None and
<del> nic.vlan is not None):
<add> nic.vlan is not None):
<ide> raise ValueError("Either a vlan or private_ip_v4 "
<ide> "must be specified for each "
<ide> "additional nic. Not both.")
<ide><path>libcloud/test/compute/test_dimensiondata.py
<ide> def test_ex_list_customer_images(self):
<ide> self.assertEqual(images[0].extra['cpu'].cpu_count, 4)
<ide> self.assertEqual(images[0].extra['OS_displayName'], 'REDHAT6/64')
<ide>
<del> def test_create_node_response(self):
<del> rootPw = NodeAuthPassword('pass123')
<del> image = self.driver.list_images()[0]
<del> network = self.driver.ex_list_networks()[0]
<del> node = self.driver.create_node(name='test2', image=image, auth=rootPw,
<del> ex_description='test2 node', ex_network=network,
<del> ex_is_started=False)
<del> self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
<del> self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
<del>
<ide> def test_create_mcp1_node_optional_param(self):
<ide> root_pw = NodeAuthPassword('pass123')
<ide> image = self.driver.list_images()[0]
<ide> def test_create_mcp1_node_response_no_pass_random_gen(self):
<ide> image = self.driver.list_images()[0]
<ide> network = self.driver.ex_list_networks()[0]
<ide> node = self.driver.create_node(name='test2', image=image, auth=None,
<del> ex_description='test2 node', ex_network=network,
<add> ex_description='test2 node',
<add> ex_network=network,
<ide> ex_is_started=False)
<ide> self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
<ide> self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
<ide> def test_create_node_mcp2_additional_nics_legacy(self):
<ide> self.assertEqual(node.id, 'e75ead52-692f-4314-8725-c8a4f4d13a87')
<ide> self.assertEqual(node.extra['status'].action, 'DEPLOY_SERVER')
<ide>
<del> def test_create_node_network_domain_no_vlan_no_ipv4_fail(self):
<del> rootPw = NodeAuthPassword('pass123')
<del> image = self.driver.list_images()[0]
<del> with self.assertRaises(ValueError):
<del> self.driver.create_node(name='test2',
<del> image=image,
<del> auth=rootPw,
<del> ex_description='test2 node',
<del> ex_network_domain='fake_network_domain',
<del> ex_is_started=False)
<del>
<ide> def test_create_node_bad_additional_nics_ipv4(self):
<ide> rootPw = NodeAuthPassword('pass123')
<ide> image = self.driver.list_images()[0] | 2 |
PHP | PHP | add comments to all lua scripts | e5bd04140d609964b10ff75d41ed101173a07f90 | <ide><path>src/Illuminate/Queue/LuaScripts.php
<ide> class LuaScripts
<ide> /**
<ide> * Get the Lua script for computing the size of queue.
<ide> *
<add> * KEYS[1] - The name of the primary queue
<add> * KEYS[2] - The name of the "delayed" queue
<add> * KEYS[3] - The name of the "reserved" queue
<add> *
<ide> * @return string
<ide> */
<ide> public static function size()
<ide> public static function size()
<ide> /**
<ide> * Get the Lua script for popping the next job off of the queue.
<ide> *
<add> * KEYS[1] - The queue to pop jobs from, for example: queues:foo
<add> * KEYS[2] - The queue to place reserved jobs on, for example: queues:foo:reserved
<add> * ARGV[1] - The time at which the reserved job will expire
<add> *
<ide> * @return string
<ide> */
<ide> public static function pop()
<ide> {
<ide> return <<<'LUA'
<add>-- Pop the first job off of the queue...
<ide> local job = redis.call('lpop', KEYS[1])
<ide> local reserved = false
<add>
<ide> if(job ~= false) then
<add> -- Increment the attempt count and place job on the reserved queue...
<ide> reserved = cjson.decode(job)
<ide> reserved['attempts'] = reserved['attempts'] + 1
<ide> reserved = cjson.encode(reserved)
<ide> redis.call('zadd', KEYS[2], ARGV[1], reserved)
<ide> end
<add>
<ide> return {job, reserved}
<ide> LUA;
<ide> }
<ide>
<ide> /**
<ide> * Get the Lua script for releasing reserved jobs.
<ide> *
<add> * KEYS[1] - The "delayed" queue we release jobs onto, for example: queues:foo:delayed
<add> * KEYS[2] - The queue the jobs are currently on, for example: queues:foo:reserved
<add> * ARGV[1] - The raw payload of the job to add to the "delayed" queue
<add> * ARGV[2] - The UNIX timestamp at which the job should become available
<add> *
<ide> * @return string
<ide> */
<ide> public static function release()
<ide> {
<ide> return <<<'LUA'
<add>-- Remove the job from the current queue...
<ide> redis.call('zrem', KEYS[2], ARGV[1])
<add>
<add>-- Add the job onto the "delayed" queue...
<ide> redis.call('zadd', KEYS[1], ARGV[2], ARGV[1])
<add>
<ide> return true
<ide> LUA;
<ide> }
<ide> public static function release()
<ide> public static function migrateExpiredJobs()
<ide> {
<ide> return <<<'LUA'
<add>-- Get all of the jobs with an expired "score"...
<ide> local val = redis.call('zrangebyscore', KEYS[1], '-inf', ARGV[1])
<ide>
<ide> -- If we have values in the array, we will remove them from the first queue | 1 |
Text | Text | remove dtrace from tierlist | 574ad6d89dd9db2cb7a4b449118d4f8befab9b05 | <ide><path>doc/contributing/diagnostic-tooling-support-tiers.md
<ide> The tools are currently assigned to Tiers as follows:
<ide> | Debugger | Command line Debug Client | ? | Yes | 1 |
<ide> | Tracing | trace\_events (API) | No | Yes | 1 |
<ide> | Tracing | trace\_gc | No | Yes | 1 |
<del>| Tracing | DTrace | No | Partial | 3 |
<ide> | Tracing | LTTng | No | Removed? | N/A |
<ide> | Tracing | Systemtap | No | Partial | ? |
<del>| Profiling | DTrace | No | Partial | 3 |
<ide> | Profiling | Windows Xperf | No | ? | ? |
<ide> | F/P/T | appmetrics | No | No | ? |
<ide> | M/T | eBPF tracing tool | No | No | ? | | 1 |
PHP | PHP | remove redundant condition | e0904abe80a0cfb340e6e8b450a4251bdf824af5 | <ide><path>src/Datasource/Paginator.php
<ide> protected function _prefix(RepositoryInterface $object, array $order, bool $allo
<ide> public function checkLimit(array $options): array
<ide> {
<ide> $options['limit'] = (int)$options['limit'];
<del> if (empty($options['limit']) || $options['limit'] < 1) {
<add> if ($options['limit'] < 1) {
<ide> $options['limit'] = 1;
<ide> }
<ide> $options['limit'] = max(min($options['limit'], $options['maxLimit']), 1); | 1 |
Go | Go | normalize comment formatting | ec4bc832589046118b6f1332f0a99664c6e42059 | <ide><path>daemon/graphdriver/btrfs/btrfs.go
<ide> func parseOptions(opt []string) (btrfsOptions, bool, error) {
<ide>
<ide> // Driver contains information about the filesystem mounted.
<ide> type Driver struct {
<del> //root of the file system
<add> // root of the file system
<ide> home string
<ide> uidMaps []idtools.IDMap
<ide> gidMaps []idtools.IDMap
<ide><path>daemon/graphdriver/copy/copy.go
<ide> func DirCopy(srcDir, dstDir string, copyMode Mode, copyXattrs bool) error {
<ide>
<ide> switch mode := f.Mode(); {
<ide> case mode.IsRegular():
<del> //the type is 32bit on mips
<add> // the type is 32bit on mips
<ide> id := fileID{dev: uint64(stat.Dev), ino: stat.Ino} // nolint: unconvert
<ide> if copyMode == Hardlink {
<ide> isHardlink = true
<ide><path>daemon/graphdriver/copy/copy_test.go
<ide> func TestCopyDir(t *testing.T) {
<ide> if srcFileSys.Dev == dstFileSys.Dev {
<ide> assert.Check(t, srcFileSys.Ino != dstFileSys.Ino)
<ide> }
<del> // Todo: check size, and ctim is not equal
<del> /// on filesystems that have granular ctimes
<add> // Todo: check size, and ctim is not equal on filesystems that have granular ctimes
<ide> assert.Check(t, is.DeepEqual(srcFileSys.Mode, dstFileSys.Mode))
<ide> assert.Check(t, is.DeepEqual(srcFileSys.Uid, dstFileSys.Uid))
<ide> assert.Check(t, is.DeepEqual(srcFileSys.Gid, dstFileSys.Gid))
<ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> type DeviceSet struct {
<ide> deletionWorkerTicker *time.Ticker
<ide> uidMaps []idtools.IDMap
<ide> gidMaps []idtools.IDMap
<del> minFreeSpacePercent uint32 //min free space percentage in thinpool
<add> minFreeSpacePercent uint32 // min free space percentage in thinpool
<ide> xfsNospaceRetries string // max retries when xfs receives ENOSPC
<ide> lvmSetupConfig directLVMConfig
<ide> }
<ide> func (devices *DeviceSet) initDevmapper(doInit bool) (retErr error) {
<ide> }
<ide> }
<ide>
<del> //create the root dir of the devmapper driver ownership to match this
<del> //daemon's remapped root uid/gid so containers can start properly
<add> // create the root dir of the devmapper driver ownership to match this
<add> // daemon's remapped root uid/gid so containers can start properly
<ide> uid, gid, err := idtools.GetRootUIDGID(devices.uidMaps, devices.gidMaps)
<ide> if err != nil {
<ide> return err
<ide><path>daemon/graphdriver/devmapper/devmapper_test.go
<ide> func testChangeLoopBackSize(t *testing.T, delta, expectDataSize, expectMetaDataS
<ide> if err := driver.Cleanup(); err != nil {
<ide> t.Fatal(err)
<ide> }
<del> //Reload
<add> // Reload
<ide> d, err := Init(driver.home, []string{
<ide> fmt.Sprintf("dm.loopdatasize=%d", defaultDataLoopbackSize+delta),
<ide> fmt.Sprintf("dm.loopmetadatasize=%d", defaultMetaDataLoopbackSize+delta),
<ide><path>daemon/graphdriver/driver.go
<ide> var (
<ide> drivers map[string]InitFunc
<ide> )
<ide>
<del>//CreateOpts contains optional arguments for Create() and CreateReadWrite()
<add>// CreateOpts contains optional arguments for Create() and CreateReadWrite()
<ide> // methods.
<ide> type CreateOpts struct {
<ide> MountLabel string
<ide><path>daemon/graphdriver/overlay2/mount.go
<ide> func mountFrom(dir, device, target, mType string, flags uintptr, label string) e
<ide> w.Close()
<ide> return fmt.Errorf("mountfrom error on re-exec cmd: %v", err)
<ide> }
<del> //write the options to the pipe for the untar exec to read
<add> // write the options to the pipe for the untar exec to read
<ide> if err := json.NewEncoder(w).Encode(options); err != nil {
<ide> w.Close()
<ide> return fmt.Errorf("mountfrom json encode to pipe failed: %v", err) | 7 |
Text | Text | fix typo in index.md | faf6f226cd001648fc421eea62e7cadcc14597f1 | <ide><path>docs/index.md
<ide> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<ide> [versioning]: api-guide/versioning.md
<ide> [contentnegotiation]: api-guide/content-negotiation.md
<ide> [metadata]: api-guide/metadata.md
<del>[schemas]: 'api-guide/schemas.md'
<add>[schemas]: api-guide/schemas.md
<ide> [formatsuffixes]: api-guide/format-suffixes.md
<ide> [reverse]: api-guide/reverse.md
<ide> [exceptions]: api-guide/exceptions.md | 1 |
Text | Text | add changelog entry for [ci skip] | ddaeaefc2a454be9d893ef3c546793cc47b0db84 | <ide><path>activerecord/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Fix bug when call `store_accessor` multiple times.
<add> Fixes #7532.
<add>
<add> *Matt Jones*
<add>
<add>* Fix store attributes that show the changes incorrectly.
<add> Fixes #7532.
<add>
<add> *Matt Jones*
<add>
<ide> * Fix `ActiveRecord::Relation#pluck` when columns or tables are reserved words.
<ide>
<ide> *Ian Lesperance* | 1 |
Javascript | Javascript | start native watchers when attached | 21e381033c65d62428499d2880bdfb8a63c0c1e9 | <ide><path>src/filesystem-manager.js
<ide> class Watcher {
<ide> this.subs.add(native.onDidStart(payload => {
<ide> this.emitter.emit('did-start', payload)
<ide> }))
<add>
<add> native.start()
<ide> }
<ide>
<ide> this.subs.add(native.onDidChange(events => { | 1 |
Python | Python | add update_zone method to the base dns api | cb2e93fbf137c6f601540f93e1b26b095dd64098 | <ide><path>libcloud/dns/base.py
<ide> def list_records(self):
<ide> def create_record(self, name, type, data, extra=None):
<ide> self.driver.create_record(name=name, type=type, data=data, extra=extra)
<ide>
<add> def update(self, domain, type='master', ttl=None, extra=None):
<add> self.driver.update_zone(zone=self, domain=domain, type=type, ttl=ttl,
<add> extra=extra)
<add>
<ide> def delete(self):
<ide> return self.driver.delete_zone(zone=self)
<ide>
<ide> def __init__(self, id, name, type, data, extra, zone, driver):
<ide>
<ide> def update(self, name, type, data, extra):
<ide> return self.driver.update_record(record=self, name=name, type=type,
<del> data=data, extra=extra)
<add> data=data, extra=extra)
<ide>
<ide> def delete(self):
<ide> return self.driver.delete_record(record=self)
<ide> def create_zone(self, domain, type='master', ttl=None, extra=None):
<ide> raise NotImplementedError(
<ide> 'create_zone not implemented for this driver')
<ide>
<add> def update_zone(self, zone, domain, type='master', ttl=None, extra=None):
<add> """
<add> Update en existing zone.
<add>
<add> @type zone: C{Zone}
<add> @param zone: Zone to update.
<add>
<add> @type domain: C{string}
<add> @param domain: Zone domain name.
<add>
<add> @type type: C{string}
<add> @param type: Zone type (master / slave).
<add>
<add> @param ttl: C{int}
<add> @param ttl: (optional) TTL for new records.
<add>
<add> @type extra: C{dict}
<add> @param extra: (optional) Extra attributes (driver specific).
<add> """
<add> raise NotImplementedError(
<add> 'update_zone not implemented for this driver')
<add>
<ide> def create_record(self, name, zone, type, data, extra=None):
<ide> """
<ide> Create a new record. | 1 |
Javascript | Javascript | fix imports in locale files | bb3f3af31445f4836c3b8527c057787adce8754a | <ide><path>src/test/locale/af.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('af');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/ar-ma.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('ar-ma');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/ar-sa.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('ar-sa');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/ar-tn.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('ar-tn');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/ar.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('ar');
<ide>
<ide> var months = [
<ide><path>src/test/locale/az.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('az');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/be.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('be');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/bg.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('bg');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/bn.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('bn');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/bo.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('bo');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/br.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('br');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/bs.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('bs');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/ca.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('ca');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/cs.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('cs');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/cv.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('cv');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/cy.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('cy');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/da.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('da');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/de-at.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('de-at');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/de.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('de');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/el.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('el');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/en-au.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('en-au');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/en-ca.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('en-ca');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/en-gb.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('en-gb');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/en.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('en');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/eo.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('eo');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/es.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('es');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/et.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('et');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/eu.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('eu');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/fa.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('fa');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/fi.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('fi');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/fo.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('fo');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/fr-ca.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('fr-ca');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/fr.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('fr');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/fy.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('fy');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/gl.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('gl');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/he.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('he');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/hi.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('hi');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/hr.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('hr');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/hu.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('hu');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/hy-am.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('hy-am');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/id.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('id');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/is.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('is');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/it.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('it');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/ja.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('ja');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/jv.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('jv');
<ide>
<ide>
<ide><path>src/test/locale/ka.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('ka');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/km.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('km');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/ko.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('ko');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/lb.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('lb');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/lt.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('lt');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/lv.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('lv');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/me.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('me');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/mk.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('mk');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/ml.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('ml');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/mr.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('mr');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/ms-my.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('ms-my');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/my.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('my');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/nb.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('nb');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/ne.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('ne');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/nl.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('nl');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/nn.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('nn');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/pl.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('pl');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/pt-br.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('pt-br');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/pt.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('pt');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/ro.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('ro');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/ru.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('ru');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/si.js
<del>import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import {localeModule, test} from '../qunit';
<add>import moment from '../../moment';
<ide> localeModule('si');
<ide>
<ide> /*jshint -W100*/
<ide><path>src/test/locale/sk.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('sk');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/sl.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('sl');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/sq.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('sq');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/sr-cyrl.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('sr-cyrl');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/sr.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('sr');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/sv.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('sv');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/ta.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('ta');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/th.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('th');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/tl-ph.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('tl-ph');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/tr.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('tr');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/tzm-latn.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('tzm-latn');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/tzm.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('tzm');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/uk.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('uk');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/uz.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('uz');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/vi.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('vi');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/zh-cn.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('zh-cn');
<ide>
<ide> test('parse', function (assert) {
<ide><path>src/test/locale/zh-tw.js
<ide> import {localeModule, test} from '../qunit';
<del>import {moment} from '../../moment';
<add>import moment from '../../moment';
<ide> localeModule('zh-tw');
<ide>
<ide> test('parse', function (assert) { | 84 |
Ruby | Ruby | change the method description | d1c5e4b28b49da31d23768ba4671553f14e3be42 | <ide><path>actionpack/test/dispatch/uploaded_file_test.rb
<ide> def test_tempfile
<ide> assert_equal 'foo', uf.tempfile
<ide> end
<ide>
<del> def test_delegates_to_io_to_tempfile
<add> def test_to_io_returns_the_tempfile
<ide> tf = Object.new
<ide> uf = Http::UploadedFile.new(:tempfile => tf)
<ide> assert_equal tf, uf.to_io | 1 |
Javascript | Javascript | remove unnecessary comma in gammacorrectionshader | e40766b5e819230f6ecfc6b8b6b8d83ca7f37b5e | <ide><path>examples/js/shaders/GammaCorrectionShader.js
<ide> THREE.GammaCorrectionShader = {
<ide>
<ide> uniforms: {
<ide>
<del> "tDiffuse": { value: null },
<add> "tDiffuse": { value: null }
<ide>
<ide> },
<ide> | 1 |
Javascript | Javascript | add test for invalid ref in link | e61c1952c8beb591e07b9360585927491bf446aa | <ide><path>test/integration/preload-viewport/pages/invalid-ref.js
<add>import React from 'react'
<add>import Link from 'next/link'
<add>
<add>class Button extends React.Component {
<add> render () {
<add> return <button {...this.props}>Click me</button>
<add> }
<add>}
<add>
<add>export default () => (
<add> <div>
<add> <Link href='/another'>
<add> <Button id='btn-link' />
<add> </Link>
<add> </div>
<add>)
<ide><path>test/integration/preload-viewport/test/index.test.js
<ide> describe('Prefetching Links in viewport', () => {
<ide> let browser
<ide> try {
<ide> browser = await webdriver(appPort, '/')
<add> await waitFor(2 * 1000)
<ide> const links = await browser.elementsByCss('link[rel=preload]')
<ide> let found = false
<ide>
<ide> describe('Prefetching Links in viewport', () => {
<ide> try {
<ide> browser = await webdriver(appPort, '/')
<ide> await browser.elementByCss('button').click()
<del> await waitFor(1000)
<add> await waitFor(2 * 1000)
<ide>
<ide> const links = await browser.elementsByCss('link[rel=preload]')
<ide> let foundFirst = false
<ide> describe('Prefetching Links in viewport', () => {
<ide> }
<ide> })
<ide>
<del> it('should prefetch with link in viewport onload', async () => {
<add> it('should prefetch with link in viewport on scroll', async () => {
<ide> let browser
<ide> try {
<ide> browser = await webdriver(appPort, '/')
<ide> await browser.elementByCss('#scroll-to-another').click()
<del> await waitFor(1000)
<add> await waitFor(2 * 1000)
<ide>
<ide> const links = await browser.elementsByCss('link[rel=preload]')
<ide> let found = false
<ide>
<ide> for (const link of links) {
<ide> const href = await link.getAttribute('href')
<del> if (href.includes('first')) {
<add> if (href.includes('another')) {
<add> found = true
<add> break
<add> }
<add> }
<add> expect(found).toBe(true)
<add> } finally {
<add> if (browser) await browser.close()
<add> }
<add> })
<add>
<add> it('should fallback to prefetching onMouseEnter with invalid ref', async () => {
<add> let browser
<add> try {
<add> browser = await webdriver(appPort, '/invalid-ref')
<add> await browser.elementByCss('#btn-link').moveTo()
<add> await waitFor(2 * 1000)
<add>
<add> const links = await browser.elementsByCss('link[rel=preload]')
<add> let found = false
<add>
<add> for (const link of links) {
<add> const href = await link.getAttribute('href')
<add> if (href.includes('another')) {
<ide> found = true
<ide> break
<ide> } | 2 |
Ruby | Ruby | use f.recursive_dependencies in stdlib check | 4a9cf0dd14bdcf08edbe0c1b2e180b08cb570c5b | <ide><path>Library/Homebrew/formula_installer.rb
<ide> def install
<ide> # This is probably accurate, but could possibly stand to be
<ide> # more robust.
<ide> stdlib_in_use = CxxStdlib.new(MacOS.default_cxx_stdlib, MacOS.default_compiler)
<del> stdlib_in_use.check_dependencies(f, effective_deps)
<add> stdlib_in_use.check_dependencies(f, f.recursive_dependencies)
<ide> end
<ide>
<ide> oh1 "Installing #{Tty.green}#{f}#{Tty.reset}" if show_header | 1 |
Javascript | Javascript | add new `forkevent`/`unforkevent` api | 5257c35d05578bab0233254da81f1216f461f18d | <ide><path>Libraries/Animated/src/AnimatedImplementation.js
<ide> function attachNativeEvent(viewRef: any, eventName: string, argMapping: Array<?M
<ide> };
<ide> }
<ide>
<add>function forkEvent(event: ?AnimatedEvent | ?Function, listener: Function): AnimatedEvent | Function {
<add> if (!event) {
<add> return listener;
<add> } else if (event instanceof AnimatedEvent) {
<add> event.__addListener(listener);
<add> return event;
<add> } else {
<add> return (...args) => {
<add> typeof event === 'function' && event(...args);
<add> listener(...args);
<add> };
<add> }
<add>}
<add>
<add>function unforkEvent(event: ?AnimatedEvent | ?Function, listener: Function): void {
<add> if (event && event instanceof AnimatedEvent) {
<add> event.__removeListener(listener);
<add> }
<add>}
<add>
<ide> class AnimatedEvent {
<ide> _argMapping: Array<?Mapping>;
<del> _listener: ?Function;
<add> _listeners: Array<Function> = [];
<ide> _attachedEvent: ?{
<ide> detach: () => void,
<ide> };
<ide> class AnimatedEvent {
<ide> config?: EventConfig = {}
<ide> ) {
<ide> this._argMapping = argMapping;
<del> this._listener = config.listener;
<add> if (config.listener) {
<add> this.__addListener(config.listener);
<add> }
<ide> this._attachedEvent = null;
<ide> this.__isNative = shouldUseNativeDriver(config);
<ide>
<ide> class AnimatedEvent {
<ide> }
<ide> }
<ide>
<add> __addListener(callback: Function): void {
<add> this._listeners.push(callback);
<add> }
<add>
<add> __removeListener(callback: Function): void {
<add> this._listeners = this._listeners.filter((listener) => listener !== callback);
<add> }
<add>
<ide> __attach(viewRef, eventName) {
<ide> invariant(this.__isNative, 'Only native driven events need to be attached.');
<ide>
<ide> class AnimatedEvent {
<ide>
<ide> __getHandler() {
<ide> if (this.__isNative) {
<del> return this._listener;
<add> return this._callListeners;
<ide> }
<ide>
<ide> return (...args) => {
<ide> class AnimatedEvent {
<ide> traverse(mapping, args[idx], 'arg' + idx);
<ide> });
<ide> }
<del>
<del> if (this._listener) {
<del> this._listener.apply(null, args);
<del> }
<add> this._callListeners(...args);
<ide> };
<ide> }
<ide>
<add> _callListeners = (...args) => {
<add> this._listeners.forEach(listener => listener(...args));
<add> };
<add>
<ide> _validateMapping() {
<ide> const traverse = (recMapping, recEvt, key) => {
<ide> if (typeof recEvt === 'number') {
<ide> module.exports = {
<ide> */
<ide> attachNativeEvent,
<ide>
<add> /**
<add> * Advanced imperative API for snooping on animated events that are passed in through props. Use
<add> * values directly where possible.
<add> */
<add> forkEvent,
<add> unforkEvent,
<add>
<ide> __PropsOnlyForTests: AnimatedProps,
<ide> };
<ide><path>Libraries/Animated/src/__tests__/Animated-test.js
<ide> describe('Animated tests', () => {
<ide> expect(listener.mock.calls.length).toBe(1);
<ide> expect(listener).toBeCalledWith({foo: 42});
<ide> });
<add> it('should call forked event listeners', () => {
<add> var value = new Animated.Value(0);
<add> var listener = jest.fn();
<add> var handler = Animated.event(
<add> [{foo: value}],
<add> {listener},
<add> );
<add> var listener2 = jest.fn();
<add> var forkedHandler = Animated.forkEvent(handler, listener2);
<add> forkedHandler({foo: 42});
<add> expect(value.__getValue()).toBe(42);
<add> expect(listener.mock.calls.length).toBe(1);
<add> expect(listener).toBeCalledWith({foo: 42});
<add> expect(listener2.mock.calls.length).toBe(1);
<add> expect(listener2).toBeCalledWith({foo: 42});
<add> });
<ide> });
<ide>
<ide> describe('Animated Interactions', () => { | 2 |
Javascript | Javascript | use const in ui_utils.js | cd03fe014d0fcf039e506f5f0bcf457ceae60513 | <ide><path>web/ui_utils.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<add>/* eslint no-var: error, prefer-const: error */
<ide>
<ide> const CSS_UNITS = 96.0 / 72.0;
<ide> const DEFAULT_SCALE_VALUE = 'auto';
<ide> function formatL10nValue(text, args) {
<ide> * No-op implementation of the localization service.
<ide> * @implements {IL10n}
<ide> */
<del>let NullL10n = {
<add>const NullL10n = {
<ide> async getLanguage() {
<ide> return 'en-us';
<ide> },
<ide> let NullL10n = {
<ide> * not required, true otherwise.
<ide> */
<ide> function getOutputScale(ctx) {
<del> let devicePixelRatio = window.devicePixelRatio || 1;
<del> let backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
<del> ctx.mozBackingStorePixelRatio ||
<del> ctx.msBackingStorePixelRatio ||
<del> ctx.oBackingStorePixelRatio ||
<del> ctx.backingStorePixelRatio || 1;
<del> let pixelRatio = devicePixelRatio / backingStoreRatio;
<add> const devicePixelRatio = window.devicePixelRatio || 1;
<add> const backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
<add> ctx.mozBackingStorePixelRatio ||
<add> ctx.msBackingStorePixelRatio ||
<add> ctx.oBackingStorePixelRatio ||
<add> ctx.backingStorePixelRatio || 1;
<add> const pixelRatio = devicePixelRatio / backingStoreRatio;
<ide> return {
<ide> sx: pixelRatio,
<ide> sy: pixelRatio,
<ide> function scrollIntoView(element, spot, skipOverflowHiddenElements = false) {
<ide> * PDF.js friendly one: with scroll debounce and scroll direction.
<ide> */
<ide> function watchScroll(viewAreaElement, callback) {
<del> let debounceScroll = function(evt) {
<add> const debounceScroll = function(evt) {
<ide> if (rAF) {
<ide> return;
<ide> }
<ide> // schedule an invocation of scroll for next animation frame.
<ide> rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
<ide> rAF = null;
<ide>
<del> let currentX = viewAreaElement.scrollLeft;
<del> let lastX = state.lastX;
<add> const currentX = viewAreaElement.scrollLeft;
<add> const lastX = state.lastX;
<ide> if (currentX !== lastX) {
<ide> state.right = currentX > lastX;
<ide> }
<ide> state.lastX = currentX;
<del> let currentY = viewAreaElement.scrollTop;
<del> let lastY = state.lastY;
<add> const currentY = viewAreaElement.scrollTop;
<add> const lastY = state.lastY;
<ide> if (currentY !== lastY) {
<ide> state.down = currentY > lastY;
<ide> }
<ide> function watchScroll(viewAreaElement, callback) {
<ide> });
<ide> };
<ide>
<del> let state = {
<add> const state = {
<ide> right: true,
<ide> down: true,
<ide> lastX: viewAreaElement.scrollLeft,
<ide> function watchScroll(viewAreaElement, callback) {
<ide> * Helper function to parse query string (e.g. ?param1=value&parm2=...).
<ide> */
<ide> function parseQueryString(query) {
<del> let parts = query.split('&');
<del> let params = Object.create(null);
<add> const parts = query.split('&');
<add> const params = Object.create(null);
<ide> for (let i = 0, ii = parts.length; i < ii; ++i) {
<del> let param = parts[i].split('=');
<del> let key = param[0].toLowerCase();
<del> let value = param.length > 1 ? param[1] : null;
<add> const param = parts[i].split('=');
<add> const key = param[0].toLowerCase();
<add> const value = param.length > 1 ? param[1] : null;
<ide> params[decodeURIComponent(key)] = decodeURIComponent(value);
<ide> }
<ide> return params;
<ide> function binarySearchFirstItem(items, condition) {
<ide> }
<ide>
<ide> while (minIndex < maxIndex) {
<del> let currentIndex = (minIndex + maxIndex) >> 1;
<del> let currentItem = items[currentIndex];
<add> const currentIndex = (minIndex + maxIndex) >> 1;
<add> const currentItem = items[currentIndex];
<ide> if (condition(currentItem)) {
<ide> maxIndex = currentIndex;
<ide> } else {
<ide> function approximateFraction(x) {
<ide> if (Math.floor(x) === x) {
<ide> return [x, 1];
<ide> }
<del> let xinv = 1 / x;
<del> let limit = 8;
<add> const xinv = 1 / x;
<add> const limit = 8;
<ide> if (xinv > limit) {
<ide> return [1, limit];
<ide> } else if (Math.floor(xinv) === xinv) {
<ide> return [1, xinv];
<ide> }
<ide>
<del> let x_ = x > 1 ? xinv : x;
<add> const x_ = x > 1 ? xinv : x;
<ide> // a/b and c/d are neighbours in Farey sequence.
<ide> let a = 0, b = 1, c = 1, d = 1;
<ide> // Limiting search to order 8.
<ide> while (true) {
<ide> // Generating next term in sequence (order of q).
<del> let p = a + c, q = b + d;
<add> const p = a + c, q = b + d;
<ide> if (q > limit) {
<ide> break;
<ide> }
<ide> function approximateFraction(x) {
<ide> }
<ide>
<ide> function roundToDivide(x, div) {
<del> let r = x % div;
<add> const r = x % div;
<ide> return r === 0 ? x : Math.round(x - r + div);
<ide> }
<ide>
<ide> function getVisibleElements(scrollEl, views, sortByVisibility = false,
<ide>
<ide> if (sortByVisibility) {
<ide> visible.sort(function(a, b) {
<del> let pc = a.percent - b.percent;
<add> const pc = a.percent - b.percent;
<ide> if (Math.abs(pc) > 0.001) {
<ide> return -pc;
<ide> }
<ide> function noContextMenuHandler(evt) {
<ide> }
<ide>
<ide> function isDataSchema(url) {
<del> let i = 0, ii = url.length;
<add> let i = 0;
<add> const ii = url.length;
<ide> while (i < ii && url[i].trim() === '') {
<ide> i++;
<ide> }
<ide> function getPDFFileNameFromURL(url, defaultFilename = 'document.pdf') {
<ide> // SCHEME HOST 1.PATH 2.QUERY 3.REF
<ide> // Pattern to get last matching NAME.pdf
<ide> const reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
<del> let splitURI = reURI.exec(url);
<add> const splitURI = reURI.exec(url);
<ide> let suggestedFilename = reFilename.exec(splitURI[1]) ||
<ide> reFilename.exec(splitURI[2]) ||
<ide> reFilename.exec(splitURI[3]);
<ide> function getPDFFileNameFromURL(url, defaultFilename = 'document.pdf') {
<ide>
<ide> function normalizeWheelEventDelta(evt) {
<ide> let delta = Math.sqrt(evt.deltaX * evt.deltaX + evt.deltaY * evt.deltaY);
<del> let angle = Math.atan2(evt.deltaY, evt.deltaX);
<add> const angle = Math.atan2(evt.deltaY, evt.deltaX);
<ide> if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) {
<ide> // All that is left-up oriented has to change the sign.
<ide> delta = -delta;
<ide> function waitOnEventOrTimeout({ target, name, delay = 0, }) {
<ide> }
<ide>
<ide> const timeoutHandler = handler.bind(null, WaitOnType.TIMEOUT);
<del> let timeout = setTimeout(timeoutHandler, delay);
<add> const timeout = setTimeout(timeoutHandler, delay);
<ide> });
<ide> }
<ide>
<ide> /**
<ide> * Promise that is resolved when DOM window becomes visible.
<ide> */
<del>let animationStarted = new Promise(function (resolve) {
<add>const animationStarted = new Promise(function (resolve) {
<ide> if ((typeof PDFJSDev !== 'undefined' && PDFJSDev.test('LIB')) &&
<ide> typeof window === 'undefined') {
<ide> // Prevent "ReferenceError: window is not defined" errors when running the
<ide> class EventBus {
<ide> }
<ide>
<ide> off(eventName, listener) {
<del> let eventListeners = this._listeners[eventName];
<add> const eventListeners = this._listeners[eventName];
<ide> let i;
<ide> if (!eventListeners || ((i = eventListeners.indexOf(listener)) < 0)) {
<ide> return;
<ide> class EventBus {
<ide> }
<ide>
<ide> dispatch(eventName) {
<del> let eventListeners = this._listeners[eventName];
<add> const eventListeners = this._listeners[eventName];
<ide> if (!eventListeners || eventListeners.length === 0) {
<ide> if (this._dispatchToDOM) {
<ide> const args = Array.prototype.slice.call(arguments, 1);
<ide> class EventBus {
<ide> const details = Object.create(null);
<ide> if (args && args.length > 0) {
<ide> const obj = args[0];
<del> for (let key in obj) {
<add> for (const key in obj) {
<ide> const value = obj[key];
<ide> if (key === 'source') {
<ide> if (value === window || value === document) {
<ide> class ProgressBar {
<ide> }
<ide>
<ide> this.div.classList.remove('indeterminate');
<del> let progressSize = this.width * this._percent / 100;
<add> const progressSize = this.width * this._percent / 100;
<ide> this.div.style.width = progressSize + this.units;
<ide> }
<ide>
<ide> class ProgressBar {
<ide> if (!viewer) {
<ide> return;
<ide> }
<del> let container = viewer.parentNode;
<del> let scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
<add> const container = viewer.parentNode;
<add> const scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
<ide> if (scrollbarWidth > 0) {
<ide> this.bar.setAttribute('style', 'width: calc(100% - ' +
<ide> scrollbarWidth + 'px);'); | 1 |
Go | Go | fix spelling error in test | 61ac745d7a7dd192948e0c1cfbdff87af7715c92 | <ide><path>integration-cli/docker_cli_run_test.go
<ide> func TestCreateVolume(t *testing.T) {
<ide>
<ide> deleteAllContainers()
<ide>
<del> logDone("run - create docker mangaed volume")
<add> logDone("run - create docker managed volume")
<ide> }
<ide>
<ide> // Test that creating a volume with a symlink in its path works correctly. Test for #5152. | 1 |
Ruby | Ruby | remove ivars from the "protected" list | a50d55a7eee89dbbcf831c3717d9837462f7a70f | <ide><path>actionpack/lib/action_controller/base.rb
<ide> def self.without_modules(*modules)
<ide>
<ide> # Define some internal variables that should not be propagated to the view.
<ide> PROTECTED_IVARS = AbstractController::Rendering::DEFAULT_PROTECTED_INSTANCE_VARIABLES + [
<del> :@_status, :@_headers, :@_params, :@_response, :@_request,
<add> :@_params, :@_response, :@_request,
<ide> :@_view_runtime, :@_stream, :@_url_options, :@_action_has_layout ]
<ide>
<ide> def _protected_ivars # :nodoc: | 1 |
Ruby | Ruby | make a singleton for associationscope | 213b2fbf40f6a1ce8381749bd5ba734f20bd4b21 | <ide><path>activerecord/lib/active_record/associations/association.rb
<ide> def scope
<ide> # actually gets built.
<ide> def association_scope
<ide> if klass
<del> @association_scope ||= AssociationScope.new.scope(self, klass.connection)
<add> @association_scope ||= AssociationScope.scope(self, klass.connection)
<ide> end
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/associations/association_scope.rb
<ide> module ActiveRecord
<ide> module Associations
<ide> class AssociationScope #:nodoc:
<add> INSTANCE = new
<add>
<add> def self.scope(association, connection)
<add> INSTANCE.scope association, connection
<add> end
<add>
<ide> def scope(association, connection)
<ide> klass = association.klass
<ide> reflection = association.reflection
<ide><path>activerecord/test/cases/associations/association_scope_test.rb
<ide> module ActiveRecord
<ide> module Associations
<ide> class AssociationScopeTest < ActiveRecord::TestCase
<ide> test 'does not duplicate conditions' do
<del> association_scope = AssociationScope.new
<del> scope = association_scope.scope(Author.new.association(:welcome_posts),
<add> scope = AssociationScope.scope(Author.new.association(:welcome_posts),
<ide> Author.connection)
<ide> wheres = scope.where_values.map(&:right)
<ide> assert_equal wheres.uniq, wheres | 3 |
PHP | PHP | move test classes into their own files | 003657662c6079c05c8de658e2d01a36e8f4f034 | <ide><path>tests/TestCase/Controller/ControllerTest.php
<ide> use PHPUnit\Framework\Error\Notice;
<ide> use PHPUnit\Framework\Error\Warning;
<ide> use TestApp\Controller\Admin\PostsController;
<add>use TestApp\Controller\TestController;
<ide> use TestPlugin\Controller\TestPluginController;
<ide>
<ide> /**
<ide> public function testAutoRender(): void
<ide> $this->assertTrue($controller->isAutoRenderEnabled());
<ide> }
<ide> }
<del>
<del>/**
<del> * AppController class
<del> */
<del>class ControllerTestAppController extends Controller
<del>{
<del> /**
<del> * modelClass property
<del> *
<del> * @var string
<del> */
<del> public $modelClass = 'Posts';
<del>}
<del>
<del>/**
<del> * TestController class
<del> */
<del>class TestController extends ControllerTestAppController
<del>{
<del> /**
<del> * Theme property
<del> *
<del> * @var string
<del> */
<del> public $theme = 'Foo';
<del>
<del> /**
<del> * modelClass property
<del> *
<del> * @var string
<del> */
<del> public $modelClass = 'Comments';
<del>
<del> /**
<del> * beforeFilter handler
<del> *
<del> * @param \Cake\Event\EventInterface $event
<del> * @return \Cake\Http\Response|null
<del> */
<del> public function beforeFilter(EventInterface $event): ?Response
<del> {
<del> }
<del>
<del> /**
<del> * index method
<del> *
<del> * @param mixed $testId
<del> * @param mixed $testTwoId
<del> * @return void
<del> */
<del> public function index($testId, $testTwoId): void
<del> {
<del> $this->request = $this->request->withParsedBody([
<del> 'testId' => $testId,
<del> 'test2Id' => $testTwoId,
<del> ]);
<del> }
<del>
<del> /**
<del> * view method
<del> *
<del> * @param mixed $testId
<del> * @param mixed $testTwoId
<del> * @return void
<del> */
<del> public function view($testId, $testTwoId): void
<del> {
<del> $this->request = $this->request->withParsedBody([
<del> 'testId' => $testId,
<del> 'test2Id' => $testTwoId,
<del> ]);
<del> }
<del>
<del> public function returner()
<del> {
<del> return 'I am from the controller.';
<del> }
<del>
<del> // phpcs:disable
<del> protected function protected_m()
<del> {
<del> }
<del>
<del> private function private_m()
<del> {
<del> }
<del>
<del> public function _hidden()
<del> {
<del> }
<del> // phpcs:enable
<del>
<del> public function admin_add(): void
<del> {
<del> }
<del>}
<del>
<del>/**
<del> * TestComponent class
<del> */
<del>class TestComponent extends Component
<del>{
<del> /**
<del> * beforeRedirect method
<del> *
<del> * @return void
<del> */
<del> public function beforeRedirect(): void
<del> {
<del> }
<del>
<del> /**
<del> * initialize method
<del> *
<del> * @param array $config
<del> * @return void
<del> */
<del> public function initialize(array $config): void
<del> {
<del> }
<del>
<del> /**
<del> * startup method
<del> *
<del> * @param \Cake\Event\EventInterface $event
<del> * @return void
<del> */
<del> public function startup(EventInterface $event): void
<del> {
<del> }
<del>
<del> /**
<del> * shutdown method
<del> *
<del> * @param \Cake\Event\EventInterface $event
<del> * @return void
<del> */
<del> public function shutdown(EventInterface $event): void
<del> {
<del> }
<del>
<del> /**
<del> * beforeRender callback
<del> *
<del> * @param \Cake\Event\EventInterface $event
<del> * @return void
<del> */
<del> public function beforeRender(EventInterface $event): void
<del> {
<del> $controller = $event->getSubject();
<del> if ($this->viewclass) {
<del> $controller->viewClass = $this->viewclass;
<del> }
<del> }
<del>}
<del>
<del>/**
<del> * AnotherTestController class
<del> */
<del>class AnotherTestController extends ControllerTestAppController
<del>{
<del>}
<ide><path>tests/TestCase/Error/ExceptionRendererTest.php
<ide> public function testPDOException()
<ide> $this->assertContains("'seven' => (int) 7", $result);
<ide> }
<ide> }
<del>
<del>class TestErrorController extends Controller
<del>{
<del> /**
<del> * uses property
<del> *
<del> * @var array
<del> */
<del> public $uses = [];
<del>
<del> /**
<del> * components property
<del> *
<del> * @return void
<del> */
<del> public $components = ['Blueberry'];
<del>
<del> /**
<del> * beforeRender method
<del> *
<del> * @return \Cake\Http\Response|null
<del> */
<del> public function beforeRender(EventInterface $event): ?Response
<del> {
<del> echo $this->Blueberry->testName;
<del>
<del> return null;
<del> }
<del>
<del> /**
<del> * index method
<del> *
<del> * @return array
<del> */
<del> public function index()
<del> {
<del> $this->autoRender = false;
<del>
<del> return 'what up';
<del> }
<del>}
<ide><path>tests/TestCase/Utility/MergeVariablesTraitTest.php
<ide>
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\MergeVariablesTrait;
<add>use TestApp\Utility\Base;
<add>use TestApp\Utility\Child;
<add>use TestApp\Utility\Grandchild;
<ide>
<ide> /**
<ide> * MergeVariablesTrait test case
<ide> public function testMergeVarsWithBoolean()
<ide> $this->assertEquals(['test'], $object->hasBoolean);
<ide> }
<ide> }
<del>
<del>class Base
<del>{
<del> use MergeVariablesTrait;
<del>
<del> public $hasBoolean = false;
<del>
<del> public $listProperty = ['One'];
<del>
<del> public $assocProperty = ['Red'];
<del>
<del> public function mergeVars($properties, $options = [])
<del> {
<del> return $this->_mergeVars($properties, $options);
<del> }
<del>}
<del>
<del>class Child extends Base
<del>{
<del> public $hasBoolean = ['test'];
<del>
<del> public $listProperty = ['Two', 'Three'];
<del>
<del> public $assocProperty = [
<del> 'Green' => ['lime'],
<del> 'Orange',
<del> ];
<del>
<del> public $nestedProperty = [
<del> 'Red' => [
<del> 'apple' => 'gala',
<del> ],
<del> 'Green' => [
<del> 'citrus' => 'lime',
<del> ],
<del> ];
<del>}
<del>
<del>class Grandchild extends Child
<del>{
<del> public $listProperty = ['Four', 'Five'];
<del>
<del> public $assocProperty = [
<del> 'Green' => ['apple'],
<del> 'Yellow' => ['banana'],
<del> ];
<del>
<del> public $nestedProperty = [
<del> 'Red' => [
<del> 'citrus' => 'blood orange',
<del> ],
<del> 'Green' => [
<del> 'citrus' => 'key lime',
<del> ],
<del> ];
<del>}
<ide><path>tests/test_app/TestApp/Controller/ControllerTestAppController.php
<add><?php
<add>declare(strict_types=1);
<add>namespace TestApp\Controller;
<add>
<add>use Cake\Controller\Controller;
<add>
<add>/**
<add> * AppController class
<add> */
<add>class ControllerTestAppController extends Controller
<add>{
<add> /**
<add> * modelClass property
<add> *
<add> * @var string
<add> */
<add> public $modelClass = 'Posts';
<add>}
<ide><path>tests/test_app/TestApp/Controller/TestController.php
<add><?php
<add>declare(strict_types=1);
<add>namespace TestApp\Controller;
<add>
<add>use Cake\Event\EventInterface;
<add>
<add>/**
<add> * TestController class
<add> */
<add>class TestController extends ControllerTestAppController
<add>{
<add> /**
<add> * Theme property
<add> *
<add> * @var string
<add> */
<add> public $theme = 'Foo';
<add>
<add> /**
<add> * modelClass property
<add> *
<add> * @var string
<add> */
<add> public $modelClass = 'Comments';
<add>
<add> /**
<add> * beforeFilter handler
<add> *
<add> * @param \Cake\Event\EventInterface $event
<add> * @return \Cake\Http\Response|null
<add> */
<add> public function beforeFilter(EventInterface $event): ?Response
<add> {
<add> }
<add>
<add> /**
<add> * index method
<add> *
<add> * @param mixed $testId
<add> * @param mixed $testTwoId
<add> * @return void
<add> */
<add> public function index($testId, $testTwoId): void
<add> {
<add> $this->request = $this->request->withParsedBody([
<add> 'testId' => $testId,
<add> 'test2Id' => $testTwoId,
<add> ]);
<add> }
<add>
<add> /**
<add> * view method
<add> *
<add> * @param mixed $testId
<add> * @param mixed $testTwoId
<add> * @return void
<add> */
<add> public function view($testId, $testTwoId): void
<add> {
<add> $this->request = $this->request->withParsedBody([
<add> 'testId' => $testId,
<add> 'test2Id' => $testTwoId,
<add> ]);
<add> }
<add>
<add> public function returner()
<add> {
<add> return 'I am from the controller.';
<add> }
<add>
<add> // phpcs:disable
<add> protected function protected_m()
<add> {
<add> }
<add>
<add> private function private_m()
<add> {
<add> }
<add>
<add> public function _hidden()
<add> {
<add> }
<add> // phpcs:enable
<add>
<add> public function admin_add(): void
<add> {
<add> }
<add>}
<ide><path>tests/test_app/TestApp/Utility/Base.php
<add><?php
<add>declare(strict_types=1);
<add>namespace TestApp\Utility;
<add>
<add>use Cake\Utility\MergeVariablesTrait;
<add>
<add>class Base
<add>{
<add> use MergeVariablesTrait;
<add>
<add> public $hasBoolean = false;
<add>
<add> public $listProperty = ['One'];
<add>
<add> public $assocProperty = ['Red'];
<add>
<add> public function mergeVars($properties, $options = [])
<add> {
<add> return $this->_mergeVars($properties, $options);
<add> }
<add>}
<ide><path>tests/test_app/TestApp/Utility/Child.php
<add><?php
<add>declare(strict_types=1);
<add>namespace TestApp\Utility;
<add>
<add>class Child extends Base
<add>{
<add> public $hasBoolean = ['test'];
<add>
<add> public $listProperty = ['Two', 'Three'];
<add>
<add> public $assocProperty = [
<add> 'Green' => ['lime'],
<add> 'Orange',
<add> ];
<add>
<add> public $nestedProperty = [
<add> 'Red' => [
<add> 'apple' => 'gala',
<add> ],
<add> 'Green' => [
<add> 'citrus' => 'lime',
<add> ],
<add> ];
<add>}
<ide><path>tests/test_app/TestApp/Utility/Grandchild.php
<add><?php
<add>declare(strict_types=1);
<add>namespace TestApp\Utility;
<add>
<add>class Grandchild extends Child
<add>{
<add> public $listProperty = ['Four', 'Five'];
<add>
<add> public $assocProperty = [
<add> 'Green' => ['apple'],
<add> 'Yellow' => ['banana'],
<add> ];
<add>
<add> public $nestedProperty = [
<add> 'Red' => [
<add> 'citrus' => 'blood orange',
<add> ],
<add> 'Green' => [
<add> 'citrus' => 'key lime',
<add> ],
<add> ];
<add>} | 8 |
PHP | PHP | name for middleware | b0bd7da50d2d4923734e9c3f865d2988954fc536 | <ide><path>src/Illuminate/Foundation/Console/AppNameCommand.php
<ide> protected function replaceNamespace($path)
<ide> */
<ide> protected function setServiceProviderNamespaceReferences()
<ide> {
<del> $this->setReferencedFilterNamespaces();
<add> $this->setReferencedMiddlewareNamespaces();
<ide>
<ide> $this->setReferencedConsoleNamespaces();
<ide>
<ide> $this->setReferencedRouteNamespaces();
<ide> }
<ide>
<ide> /**
<del> * Set the namespace on the referenced filters in the filter service provider.
<add> * Set the namespace on the referenced middleware.
<ide> *
<ide> * @return void
<ide> */
<del> protected function setReferencedFilterNamespaces()
<add> protected function setReferencedMiddlewareNamespaces()
<ide> {
<ide> $this->replaceIn(
<del> $this->laravel['path'].'/Providers/FilterServiceProvider.php',
<del> $this->currentRoot.'\\Http\\Filters', $this->argument('name').'\\Http\\Filters'
<add> $this->laravel['path'].'/Providers/AppServiceProvider.php',
<add> $this->currentRoot.'\\Http\\Middleware', $this->argument('name').'\\Http\\Middleware'
<ide> );
<ide> }
<ide> | 1 |
PHP | PHP | update doc block | 9bdf02648e994adabb3363e63a0dbc1ab7fe250d | <ide><path>laravel/input.php
<ide> public static function has_file($key)
<ide> * @param string $key
<ide> * @param string $directory
<ide> * @param string $name
<del> * @return bool
<add> * @return Symfony\Component\HttpFoundation\File\File
<ide> */
<ide> public static function upload($key, $directory, $name = null)
<ide> { | 1 |
Javascript | Javascript | remove dead test file | 761afebab21e495cc64ec398c9ef529b0af78515 | <ide><path>test/hotCases/harmony/auto-import-default/out/bundle.js
<del>/******/ (function(modules) { // webpackBootstrap
<del>/******/ function hotDisposeChunk(chunkId) {
<del>/******/ delete installedChunks[chunkId];
<del>/******/ }
<del>/******/ var parentHotUpdateCallback = this["webpackHotUpdate"];
<del>/******/ this["webpackHotUpdate"] = function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars
<del>/******/ hotAddUpdateChunk(chunkId, moreModules);
<del>/******/ if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules);
<del>/******/ } ;
<del>/******/
<del>/******/ function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars
<del>/******/ var head = document.getElementsByTagName("head")[0];
<del>/******/ var script = document.createElement("script");
<del>/******/ script.charset = "utf-8";
<del>/******/ script.src = __webpack_require__.p + "" + chunkId + "." + hotCurrentHash + ".hot-update.js";
<del>/******/ ;
<del>/******/ head.appendChild(script);
<del>/******/ }
<del>/******/
<del>/******/ function hotDownloadManifest(requestTimeout) { // eslint-disable-line no-unused-vars
<del>/******/ requestTimeout = requestTimeout || 10000;
<del>/******/ return new Promise(function(resolve, reject) {
<del>/******/ if(typeof XMLHttpRequest === "undefined")
<del>/******/ return reject(new Error("No browser support"));
<del>/******/ try {
<del>/******/ var request = new XMLHttpRequest();
<del>/******/ var requestPath = __webpack_require__.p + "" + hotCurrentHash + ".hot-update.json";
<del>/******/ request.open("GET", requestPath, true);
<del>/******/ request.timeout = requestTimeout;
<del>/******/ request.send(null);
<del>/******/ } catch(err) {
<del>/******/ return reject(err);
<del>/******/ }
<del>/******/ request.onreadystatechange = function() {
<del>/******/ if(request.readyState !== 4) return;
<del>/******/ if(request.status === 0) {
<del>/******/ // timeout
<del>/******/ reject(new Error("Manifest request to " + requestPath + " timed out."));
<del>/******/ } else if(request.status === 404) {
<del>/******/ // no update available
<del>/******/ resolve();
<del>/******/ } else if(request.status !== 200 && request.status !== 304) {
<del>/******/ // other failure
<del>/******/ reject(new Error("Manifest request to " + requestPath + " failed."));
<del>/******/ } else {
<del>/******/ // success
<del>/******/ try {
<del>/******/ var update = JSON.parse(request.responseText);
<del>/******/ } catch(e) {
<del>/******/ reject(e);
<del>/******/ return;
<del>/******/ }
<del>/******/ resolve(update);
<del>/******/ }
<del>/******/ };
<del>/******/ });
<del>/******/ }
<del>/******/
<del>/******/
<del>/******/ var hotApplyOnUpdate = true;
<del>/******/ var hotCurrentHash = "9e66a96510409aa06627"; // eslint-disable-line no-unused-vars
<del>/******/ var hotRequestTimeout = 10000;
<del>/******/ var hotCurrentModuleData = {};
<del>/******/ var hotCurrentChildModule; // eslint-disable-line no-unused-vars
<del>/******/ var hotCurrentParents = []; // eslint-disable-line no-unused-vars
<del>/******/ var hotCurrentParentsTemp = []; // eslint-disable-line no-unused-vars
<del>/******/
<del>/******/ function hotCreateRequire(moduleId) { // eslint-disable-line no-unused-vars
<del>/******/ var me = installedModules[moduleId];
<del>/******/ if(!me) return __webpack_require__;
<del>/******/ var fn = function(request) {
<del>/******/ if(me.hot.active) {
<del>/******/ if(installedModules[request]) {
<del>/******/ if(installedModules[request].parents.indexOf(moduleId) < 0)
<del>/******/ installedModules[request].parents.push(moduleId);
<del>/******/ } else {
<del>/******/ hotCurrentParents = [moduleId];
<del>/******/ hotCurrentChildModule = request;
<del>/******/ }
<del>/******/ if(me.children.indexOf(request) < 0)
<del>/******/ me.children.push(request);
<del>/******/ } else {
<del>/******/ console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
<del>/******/ hotCurrentParents = [];
<del>/******/ }
<del>/******/ return __webpack_require__(request);
<del>/******/ };
<del>/******/ var ObjectFactory = function ObjectFactory(name) {
<del>/******/ return {
<del>/******/ configurable: true,
<del>/******/ enumerable: true,
<del>/******/ get: function() {
<del>/******/ return __webpack_require__[name];
<del>/******/ },
<del>/******/ set: function(value) {
<del>/******/ __webpack_require__[name] = value;
<del>/******/ }
<del>/******/ };
<del>/******/ };
<del>/******/ for(var name in __webpack_require__) {
<del>/******/ if(Object.prototype.hasOwnProperty.call(__webpack_require__, name) && name !== "e") {
<del>/******/ Object.defineProperty(fn, name, ObjectFactory(name));
<del>/******/ }
<del>/******/ }
<del>/******/ fn.e = function(chunkId) {
<del>/******/ if(hotStatus === "ready")
<del>/******/ hotSetStatus("prepare");
<del>/******/ hotChunksLoading++;
<del>/******/ return __webpack_require__.e(chunkId).then(finishChunkLoading, function(err) {
<del>/******/ finishChunkLoading();
<del>/******/ throw err;
<del>/******/ });
<del>/******/
<del>/******/ function finishChunkLoading() {
<del>/******/ hotChunksLoading--;
<del>/******/ if(hotStatus === "prepare") {
<del>/******/ if(!hotWaitingFilesMap[chunkId]) {
<del>/******/ hotEnsureUpdateChunk(chunkId);
<del>/******/ }
<del>/******/ if(hotChunksLoading === 0 && hotWaitingFiles === 0) {
<del>/******/ hotUpdateDownloaded();
<del>/******/ }
<del>/******/ }
<del>/******/ }
<del>/******/ };
<del>/******/ return fn;
<del>/******/ }
<del>/******/
<del>/******/ function hotCreateModule(moduleId) { // eslint-disable-line no-unused-vars
<del>/******/ var hot = {
<del>/******/ // private stuff
<del>/******/ _acceptedDependencies: {},
<del>/******/ _declinedDependencies: {},
<del>/******/ _selfAccepted: false,
<del>/******/ _selfDeclined: false,
<del>/******/ _disposeHandlers: [],
<del>/******/ _main: hotCurrentChildModule !== moduleId,
<del>/******/
<del>/******/ // Module API
<del>/******/ active: true,
<del>/******/ accept: function(dep, callback) {
<del>/******/ if(typeof dep === "undefined")
<del>/******/ hot._selfAccepted = true;
<del>/******/ else if(typeof dep === "function")
<del>/******/ hot._selfAccepted = dep;
<del>/******/ else if(typeof dep === "object")
<del>/******/ for(var i = 0; i < dep.length; i++)
<del>/******/ hot._acceptedDependencies[dep[i]] = callback || function() {};
<del>/******/ else
<del>/******/ hot._acceptedDependencies[dep] = callback || function() {};
<del>/******/ },
<del>/******/ decline: function(dep) {
<del>/******/ if(typeof dep === "undefined")
<del>/******/ hot._selfDeclined = true;
<del>/******/ else if(typeof dep === "object")
<del>/******/ for(var i = 0; i < dep.length; i++)
<del>/******/ hot._declinedDependencies[dep[i]] = true;
<del>/******/ else
<del>/******/ hot._declinedDependencies[dep] = true;
<del>/******/ },
<del>/******/ dispose: function(callback) {
<del>/******/ hot._disposeHandlers.push(callback);
<del>/******/ },
<del>/******/ addDisposeHandler: function(callback) {
<del>/******/ hot._disposeHandlers.push(callback);
<del>/******/ },
<del>/******/ removeDisposeHandler: function(callback) {
<del>/******/ var idx = hot._disposeHandlers.indexOf(callback);
<del>/******/ if(idx >= 0) hot._disposeHandlers.splice(idx, 1);
<del>/******/ },
<del>/******/
<del>/******/ // Management API
<del>/******/ check: hotCheck,
<del>/******/ apply: hotApply,
<del>/******/ status: function(l) {
<del>/******/ if(!l) return hotStatus;
<del>/******/ hotStatusHandlers.push(l);
<del>/******/ },
<del>/******/ addStatusHandler: function(l) {
<del>/******/ hotStatusHandlers.push(l);
<del>/******/ },
<del>/******/ removeStatusHandler: function(l) {
<del>/******/ var idx = hotStatusHandlers.indexOf(l);
<del>/******/ if(idx >= 0) hotStatusHandlers.splice(idx, 1);
<del>/******/ },
<del>/******/
<del>/******/ //inherit from previous dispose call
<del>/******/ data: hotCurrentModuleData[moduleId]
<del>/******/ };
<del>/******/ hotCurrentChildModule = undefined;
<del>/******/ return hot;
<del>/******/ }
<del>/******/
<del>/******/ var hotStatusHandlers = [];
<del>/******/ var hotStatus = "idle";
<del>/******/
<del>/******/ function hotSetStatus(newStatus) {
<del>/******/ hotStatus = newStatus;
<del>/******/ for(var i = 0; i < hotStatusHandlers.length; i++)
<del>/******/ hotStatusHandlers[i].call(null, newStatus);
<del>/******/ }
<del>/******/
<del>/******/ // while downloading
<del>/******/ var hotWaitingFiles = 0;
<del>/******/ var hotChunksLoading = 0;
<del>/******/ var hotWaitingFilesMap = {};
<del>/******/ var hotRequestedFilesMap = {};
<del>/******/ var hotAvailableFilesMap = {};
<del>/******/ var hotDeferred;
<del>/******/
<del>/******/ // The update info
<del>/******/ var hotUpdate, hotUpdateNewHash;
<del>/******/
<del>/******/ function toModuleId(id) {
<del>/******/ var isNumber = (+id) + "" === id;
<del>/******/ return isNumber ? +id : id;
<del>/******/ }
<del>/******/
<del>/******/ function hotCheck(apply) {
<del>/******/ if(hotStatus !== "idle") throw new Error("check() is only allowed in idle status");
<del>/******/ hotApplyOnUpdate = apply;
<del>/******/ hotSetStatus("check");
<del>/******/ return hotDownloadManifest(hotRequestTimeout).then(function(update) {
<del>/******/ if(!update) {
<del>/******/ hotSetStatus("idle");
<del>/******/ return null;
<del>/******/ }
<del>/******/ hotRequestedFilesMap = {};
<del>/******/ hotWaitingFilesMap = {};
<del>/******/ hotAvailableFilesMap = update.c;
<del>/******/ hotUpdateNewHash = update.h;
<del>/******/
<del>/******/ hotSetStatus("prepare");
<del>/******/ var promise = new Promise(function(resolve, reject) {
<del>/******/ hotDeferred = {
<del>/******/ resolve: resolve,
<del>/******/ reject: reject
<del>/******/ };
<del>/******/ });
<del>/******/ hotUpdate = {};
<del>/******/ var chunkId = "main";
<del>/******/ { // eslint-disable-line no-lone-blocks
<del>/******/ /*globals chunkId */
<del>/******/ hotEnsureUpdateChunk(chunkId);
<del>/******/ }
<del>/******/ if(hotStatus === "prepare" && hotChunksLoading === 0 && hotWaitingFiles === 0) {
<del>/******/ hotUpdateDownloaded();
<del>/******/ }
<del>/******/ return promise;
<del>/******/ });
<del>/******/ }
<del>/******/
<del>/******/ function hotAddUpdateChunk(chunkId, moreModules) { // eslint-disable-line no-unused-vars
<del>/******/ if(!hotAvailableFilesMap[chunkId] || !hotRequestedFilesMap[chunkId])
<del>/******/ return;
<del>/******/ hotRequestedFilesMap[chunkId] = false;
<del>/******/ for(var moduleId in moreModules) {
<del>/******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
<del>/******/ hotUpdate[moduleId] = moreModules[moduleId];
<del>/******/ }
<del>/******/ }
<del>/******/ if(--hotWaitingFiles === 0 && hotChunksLoading === 0) {
<del>/******/ hotUpdateDownloaded();
<del>/******/ }
<del>/******/ }
<del>/******/
<del>/******/ function hotEnsureUpdateChunk(chunkId) {
<del>/******/ if(!hotAvailableFilesMap[chunkId]) {
<del>/******/ hotWaitingFilesMap[chunkId] = true;
<del>/******/ } else {
<del>/******/ hotRequestedFilesMap[chunkId] = true;
<del>/******/ hotWaitingFiles++;
<del>/******/ hotDownloadUpdateChunk(chunkId);
<del>/******/ }
<del>/******/ }
<del>/******/
<del>/******/ function hotUpdateDownloaded() {
<del>/******/ hotSetStatus("ready");
<del>/******/ var deferred = hotDeferred;
<del>/******/ hotDeferred = null;
<del>/******/ if(!deferred) return;
<del>/******/ if(hotApplyOnUpdate) {
<del>/******/ // Wrap deferred object in Promise to mark it as a well-handled Promise to
<del>/******/ // avoid triggering uncaught exception warning in Chrome.
<del>/******/ // See https://bugs.chromium.org/p/chromium/issues/detail?id=465666
<del>/******/ Promise.resolve().then(function() {
<del>/******/ return hotApply(hotApplyOnUpdate);
<del>/******/ }).then(
<del>/******/ function(result) {
<del>/******/ deferred.resolve(result);
<del>/******/ },
<del>/******/ function(err) {
<del>/******/ deferred.reject(err);
<del>/******/ }
<del>/******/ );
<del>/******/ } else {
<del>/******/ var outdatedModules = [];
<del>/******/ for(var id in hotUpdate) {
<del>/******/ if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) {
<del>/******/ outdatedModules.push(toModuleId(id));
<del>/******/ }
<del>/******/ }
<del>/******/ deferred.resolve(outdatedModules);
<del>/******/ }
<del>/******/ }
<del>/******/
<del>/******/ function hotApply(options) {
<del>/******/ if(hotStatus !== "ready") throw new Error("apply() is only allowed in ready status");
<del>/******/ options = options || {};
<del>/******/
<del>/******/ var cb;
<del>/******/ var i;
<del>/******/ var j;
<del>/******/ var module;
<del>/******/ var moduleId;
<del>/******/
<del>/******/ function getAffectedStuff(updateModuleId) {
<del>/******/ var outdatedModules = [updateModuleId];
<del>/******/ var outdatedDependencies = {};
<del>/******/
<del>/******/ var queue = outdatedModules.slice().map(function(id) {
<del>/******/ return {
<del>/******/ chain: [id],
<del>/******/ id: id
<del>/******/ };
<del>/******/ });
<del>/******/ while(queue.length > 0) {
<del>/******/ var queueItem = queue.pop();
<del>/******/ var moduleId = queueItem.id;
<del>/******/ var chain = queueItem.chain;
<del>/******/ module = installedModules[moduleId];
<del>/******/ if(!module || module.hot._selfAccepted)
<del>/******/ continue;
<del>/******/ if(module.hot._selfDeclined) {
<del>/******/ return {
<del>/******/ type: "self-declined",
<del>/******/ chain: chain,
<del>/******/ moduleId: moduleId
<del>/******/ };
<del>/******/ }
<del>/******/ if(module.hot._main) {
<del>/******/ return {
<del>/******/ type: "unaccepted",
<del>/******/ chain: chain,
<del>/******/ moduleId: moduleId
<del>/******/ };
<del>/******/ }
<del>/******/ for(var i = 0; i < module.parents.length; i++) {
<del>/******/ var parentId = module.parents[i];
<del>/******/ var parent = installedModules[parentId];
<del>/******/ if(!parent) continue;
<del>/******/ if(parent.hot._declinedDependencies[moduleId]) {
<del>/******/ return {
<del>/******/ type: "declined",
<del>/******/ chain: chain.concat([parentId]),
<del>/******/ moduleId: moduleId,
<del>/******/ parentId: parentId
<del>/******/ };
<del>/******/ }
<del>/******/ if(outdatedModules.indexOf(parentId) >= 0) continue;
<del>/******/ if(parent.hot._acceptedDependencies[moduleId]) {
<del>/******/ if(!outdatedDependencies[parentId])
<del>/******/ outdatedDependencies[parentId] = [];
<del>/******/ addAllToSet(outdatedDependencies[parentId], [moduleId]);
<del>/******/ continue;
<del>/******/ }
<del>/******/ delete outdatedDependencies[parentId];
<del>/******/ outdatedModules.push(parentId);
<del>/******/ queue.push({
<del>/******/ chain: chain.concat([parentId]),
<del>/******/ id: parentId
<del>/******/ });
<del>/******/ }
<del>/******/ }
<del>/******/
<del>/******/ return {
<del>/******/ type: "accepted",
<del>/******/ moduleId: updateModuleId,
<del>/******/ outdatedModules: outdatedModules,
<del>/******/ outdatedDependencies: outdatedDependencies
<del>/******/ };
<del>/******/ }
<del>/******/
<del>/******/ function addAllToSet(a, b) {
<del>/******/ for(var i = 0; i < b.length; i++) {
<del>/******/ var item = b[i];
<del>/******/ if(a.indexOf(item) < 0)
<del>/******/ a.push(item);
<del>/******/ }
<del>/******/ }
<del>/******/
<del>/******/ // at begin all updates modules are outdated
<del>/******/ // the "outdated" status can propagate to parents if they don't accept the children
<del>/******/ var outdatedDependencies = {};
<del>/******/ var outdatedModules = [];
<del>/******/ var appliedUpdate = {};
<del>/******/
<del>/******/ var warnUnexpectedRequire = function warnUnexpectedRequire() {
<del>/******/ console.warn("[HMR] unexpected require(" + result.moduleId + ") to disposed module");
<del>/******/ };
<del>/******/
<del>/******/ for(var id in hotUpdate) {
<del>/******/ if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) {
<del>/******/ moduleId = toModuleId(id);
<del>/******/ var result;
<del>/******/ if(hotUpdate[id]) {
<del>/******/ result = getAffectedStuff(moduleId);
<del>/******/ } else {
<del>/******/ result = {
<del>/******/ type: "disposed",
<del>/******/ moduleId: id
<del>/******/ };
<del>/******/ }
<del>/******/ var abortError = false;
<del>/******/ var doApply = false;
<del>/******/ var doDispose = false;
<del>/******/ var chainInfo = "";
<del>/******/ if(result.chain) {
<del>/******/ chainInfo = "\nUpdate propagation: " + result.chain.join(" -> ");
<del>/******/ }
<del>/******/ switch(result.type) {
<del>/******/ case "self-declined":
<del>/******/ if(options.onDeclined)
<del>/******/ options.onDeclined(result);
<del>/******/ if(!options.ignoreDeclined)
<del>/******/ abortError = new Error("Aborted because of self decline: " + result.moduleId + chainInfo);
<del>/******/ break;
<del>/******/ case "declined":
<del>/******/ if(options.onDeclined)
<del>/******/ options.onDeclined(result);
<del>/******/ if(!options.ignoreDeclined)
<del>/******/ abortError = new Error("Aborted because of declined dependency: " + result.moduleId + " in " + result.parentId + chainInfo);
<del>/******/ break;
<del>/******/ case "unaccepted":
<del>/******/ if(options.onUnaccepted)
<del>/******/ options.onUnaccepted(result);
<del>/******/ if(!options.ignoreUnaccepted)
<del>/******/ abortError = new Error("Aborted because " + moduleId + " is not accepted" + chainInfo);
<del>/******/ break;
<del>/******/ case "accepted":
<del>/******/ if(options.onAccepted)
<del>/******/ options.onAccepted(result);
<del>/******/ doApply = true;
<del>/******/ break;
<del>/******/ case "disposed":
<del>/******/ if(options.onDisposed)
<del>/******/ options.onDisposed(result);
<del>/******/ doDispose = true;
<del>/******/ break;
<del>/******/ default:
<del>/******/ throw new Error("Unexception type " + result.type);
<del>/******/ }
<del>/******/ if(abortError) {
<del>/******/ hotSetStatus("abort");
<del>/******/ return Promise.reject(abortError);
<del>/******/ }
<del>/******/ if(doApply) {
<del>/******/ appliedUpdate[moduleId] = hotUpdate[moduleId];
<del>/******/ addAllToSet(outdatedModules, result.outdatedModules);
<del>/******/ for(moduleId in result.outdatedDependencies) {
<del>/******/ if(Object.prototype.hasOwnProperty.call(result.outdatedDependencies, moduleId)) {
<del>/******/ if(!outdatedDependencies[moduleId])
<del>/******/ outdatedDependencies[moduleId] = [];
<del>/******/ addAllToSet(outdatedDependencies[moduleId], result.outdatedDependencies[moduleId]);
<del>/******/ }
<del>/******/ }
<del>/******/ }
<del>/******/ if(doDispose) {
<del>/******/ addAllToSet(outdatedModules, [result.moduleId]);
<del>/******/ appliedUpdate[moduleId] = warnUnexpectedRequire;
<del>/******/ }
<del>/******/ }
<del>/******/ }
<del>/******/
<del>/******/ // Store self accepted outdated modules to require them later by the module system
<del>/******/ var outdatedSelfAcceptedModules = [];
<del>/******/ for(i = 0; i < outdatedModules.length; i++) {
<del>/******/ moduleId = outdatedModules[i];
<del>/******/ if(installedModules[moduleId] && installedModules[moduleId].hot._selfAccepted)
<del>/******/ outdatedSelfAcceptedModules.push({
<del>/******/ module: moduleId,
<del>/******/ errorHandler: installedModules[moduleId].hot._selfAccepted
<del>/******/ });
<del>/******/ }
<del>/******/
<del>/******/ // Now in "dispose" phase
<del>/******/ hotSetStatus("dispose");
<del>/******/ Object.keys(hotAvailableFilesMap).forEach(function(chunkId) {
<del>/******/ if(hotAvailableFilesMap[chunkId] === false) {
<del>/******/ hotDisposeChunk(chunkId);
<del>/******/ }
<del>/******/ });
<del>/******/
<del>/******/ var idx;
<del>/******/ var queue = outdatedModules.slice();
<del>/******/ while(queue.length > 0) {
<del>/******/ moduleId = queue.pop();
<del>/******/ module = installedModules[moduleId];
<del>/******/ if(!module) continue;
<del>/******/
<del>/******/ var data = {};
<del>/******/
<del>/******/ // Call dispose handlers
<del>/******/ var disposeHandlers = module.hot._disposeHandlers;
<del>/******/ for(j = 0; j < disposeHandlers.length; j++) {
<del>/******/ cb = disposeHandlers[j];
<del>/******/ cb(data);
<del>/******/ }
<del>/******/ hotCurrentModuleData[moduleId] = data;
<del>/******/
<del>/******/ // disable module (this disables requires from this module)
<del>/******/ module.hot.active = false;
<del>/******/
<del>/******/ // remove module from cache
<del>/******/ delete installedModules[moduleId];
<del>/******/
<del>/******/ // when disposing there is no need to call dispose handler
<del>/******/ delete outdatedDependencies[moduleId];
<del>/******/
<del>/******/ // remove "parents" references from all children
<del>/******/ for(j = 0; j < module.children.length; j++) {
<del>/******/ var child = installedModules[module.children[j]];
<del>/******/ if(!child) continue;
<del>/******/ idx = child.parents.indexOf(moduleId);
<del>/******/ if(idx >= 0) {
<del>/******/ child.parents.splice(idx, 1);
<del>/******/ }
<del>/******/ }
<del>/******/ }
<del>/******/
<del>/******/ // remove outdated dependency from module children
<del>/******/ var dependency;
<del>/******/ var moduleOutdatedDependencies;
<del>/******/ for(moduleId in outdatedDependencies) {
<del>/******/ if(Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) {
<del>/******/ module = installedModules[moduleId];
<del>/******/ if(module) {
<del>/******/ moduleOutdatedDependencies = outdatedDependencies[moduleId];
<del>/******/ for(j = 0; j < moduleOutdatedDependencies.length; j++) {
<del>/******/ dependency = moduleOutdatedDependencies[j];
<del>/******/ idx = module.children.indexOf(dependency);
<del>/******/ if(idx >= 0) module.children.splice(idx, 1);
<del>/******/ }
<del>/******/ }
<del>/******/ }
<del>/******/ }
<del>/******/
<del>/******/ // Not in "apply" phase
<del>/******/ hotSetStatus("apply");
<del>/******/
<del>/******/ hotCurrentHash = hotUpdateNewHash;
<del>/******/
<del>/******/ // insert new code
<del>/******/ for(moduleId in appliedUpdate) {
<del>/******/ if(Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) {
<del>/******/ modules[moduleId] = appliedUpdate[moduleId];
<del>/******/ }
<del>/******/ }
<del>/******/
<del>/******/ // call accept handlers
<del>/******/ var error = null;
<del>/******/ for(moduleId in outdatedDependencies) {
<del>/******/ if(Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) {
<del>/******/ module = installedModules[moduleId];
<del>/******/ if(module) {
<del>/******/ moduleOutdatedDependencies = outdatedDependencies[moduleId];
<del>/******/ var callbacks = [];
<del>/******/ for(i = 0; i < moduleOutdatedDependencies.length; i++) {
<del>/******/ dependency = moduleOutdatedDependencies[i];
<del>/******/ cb = module.hot._acceptedDependencies[dependency];
<del>/******/ if(cb) {
<del>/******/ if(callbacks.indexOf(cb) >= 0) continue;
<del>/******/ callbacks.push(cb);
<del>/******/ }
<del>/******/ }
<del>/******/ for(i = 0; i < callbacks.length; i++) {
<del>/******/ cb = callbacks[i];
<del>/******/ try {
<del>/******/ cb(moduleOutdatedDependencies);
<del>/******/ } catch(err) {
<del>/******/ if(options.onErrored) {
<del>/******/ options.onErrored({
<del>/******/ type: "accept-errored",
<del>/******/ moduleId: moduleId,
<del>/******/ dependencyId: moduleOutdatedDependencies[i],
<del>/******/ error: err
<del>/******/ });
<del>/******/ }
<del>/******/ if(!options.ignoreErrored) {
<del>/******/ if(!error)
<del>/******/ error = err;
<del>/******/ }
<del>/******/ }
<del>/******/ }
<del>/******/ }
<del>/******/ }
<del>/******/ }
<del>/******/
<del>/******/ // Load self accepted modules
<del>/******/ for(i = 0; i < outdatedSelfAcceptedModules.length; i++) {
<del>/******/ var item = outdatedSelfAcceptedModules[i];
<del>/******/ moduleId = item.module;
<del>/******/ hotCurrentParents = [moduleId];
<del>/******/ try {
<del>/******/ __webpack_require__(moduleId);
<del>/******/ } catch(err) {
<del>/******/ if(typeof item.errorHandler === "function") {
<del>/******/ try {
<del>/******/ item.errorHandler(err);
<del>/******/ } catch(err2) {
<del>/******/ if(options.onErrored) {
<del>/******/ options.onErrored({
<del>/******/ type: "self-accept-error-handler-errored",
<del>/******/ moduleId: moduleId,
<del>/******/ error: err2,
<del>/******/ originalError: err
<del>/******/ });
<del>/******/ }
<del>/******/ if(!options.ignoreErrored) {
<del>/******/ if(!error)
<del>/******/ error = err2;
<del>/******/ }
<del>/******/ if(!error)
<del>/******/ error = err;
<del>/******/ }
<del>/******/ } else {
<del>/******/ if(options.onErrored) {
<del>/******/ options.onErrored({
<del>/******/ type: "self-accept-errored",
<del>/******/ moduleId: moduleId,
<del>/******/ error: err
<del>/******/ });
<del>/******/ }
<del>/******/ if(!options.ignoreErrored) {
<del>/******/ if(!error)
<del>/******/ error = err;
<del>/******/ }
<del>/******/ }
<del>/******/ }
<del>/******/ }
<del>/******/
<del>/******/ // handle errors in accept handlers and self accepted module load
<del>/******/ if(error) {
<del>/******/ hotSetStatus("fail");
<del>/******/ return Promise.reject(error);
<del>/******/ }
<del>/******/
<del>/******/ hotSetStatus("idle");
<del>/******/ return new Promise(function(resolve) {
<del>/******/ resolve(outdatedModules);
<del>/******/ });
<del>/******/ }
<del>/******/
<del>/******/ // The module cache
<del>/******/ var installedModules = {};
<del>/******/
<del>/******/ // The require function
<del>/******/ function __webpack_require__(moduleId) {
<del>/******/
<del>/******/ // Check if module is in cache
<del>/******/ if(installedModules[moduleId]) {
<del>/******/ return installedModules[moduleId].exports;
<del>/******/ }
<del>/******/ // Create a new module (and put it into the cache)
<del>/******/ var module = installedModules[moduleId] = {
<del>/******/ i: moduleId,
<del>/******/ l: false,
<del>/******/ exports: {},
<del>/******/ hot: hotCreateModule(moduleId),
<del>/******/ parents: (hotCurrentParentsTemp = hotCurrentParents, hotCurrentParents = [], hotCurrentParentsTemp),
<del>/******/ children: []
<del>/******/ };
<del>/******/
<del>/******/ // Execute the module function
<del>/******/ modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
<del>/******/
<del>/******/ // Flag the module as loaded
<del>/******/ module.l = true;
<del>/******/
<del>/******/ // Return the exports of the module
<del>/******/ return module.exports;
<del>/******/ }
<del>/******/
<del>/******/
<del>/******/ // expose the modules object (__webpack_modules__)
<del>/******/ __webpack_require__.m = modules;
<del>/******/
<del>/******/ // expose the module cache
<del>/******/ __webpack_require__.c = installedModules;
<del>/******/
<del>/******/ // define getter function for harmony exports
<del>/******/ __webpack_require__.d = function(exports, name, getter) {
<del>/******/ if(!__webpack_require__.o(exports, name)) {
<del>/******/ Object.defineProperty(exports, name, {
<del>/******/ configurable: false,
<del>/******/ enumerable: true,
<del>/******/ get: getter
<del>/******/ });
<del>/******/ }
<del>/******/ };
<del>/******/
<del>/******/ // getDefaultExport function for compatibility with non-harmony modules
<del>/******/ __webpack_require__.n = function(module) {
<del>/******/ var getter = module && module.__esModule ?
<del>/******/ function getDefault() { return module['default']; } :
<del>/******/ function getModuleExports() { return module; };
<del>/******/ __webpack_require__.d(getter, 'a', getter);
<del>/******/ return getter;
<del>/******/ };
<del>/******/
<del>/******/ // Object.prototype.hasOwnProperty.call
<del>/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
<del>/******/
<del>/******/ // __webpack_public_path__
<del>/******/ __webpack_require__.p = "";
<del>/******/
<del>/******/ // __webpack_hash__
<del>/******/ __webpack_require__.h = function() { return hotCurrentHash; };
<del>/******/
<del>/******/ // Load entry module and return exports
<del>/******/ return hotCreateRequire("./index.js")(__webpack_require__.s = "./index.js");
<del>/******/ })
<del>/************************************************************************/
<del>/******/ ({
<del>
<del>/***/ "../../update.js":
<del>/*!*****************************************!*\
<del> !*** (webpack)/test/hotCases/update.js ***!
<del> \*****************************************/
<del>/***/ (function(module, exports) {
<del>
<del>module.exports = function(done, options, callback) {
<del> return function(stats) {
<del> module.hot.check(options || true).then(function() {
<del> if(callback)
<del> callback(stats);
<del> }).catch(function(err) {
<del> done(err);
<del> });
<del> }
<del>};
<del>
<del>
<del>/***/ }),
<del>
<del>/***/ "./file.js":
<del>/*!*****************!*\
<del> !*** ./file.js ***!
<del> \*****************/
<del>/***/ (function(module, exports) {
<del>
<del>throw new Error("Module parse failed: Unexpected token (3:0)\nYou may need an appropriate loader to handle this file type.\n| export var value = 1;\r\n| ---\r\n| export var value = 2;\r\n| ");
<del>
<del>/***/ }),
<del>
<del>/***/ "./index.js":
<del>/*!******************!*\
<del> !*** ./index.js ***!
<del> \******************/
<del>/***/ (function(module, __webpack_exports__, __webpack_require__) {
<del>
<del>"use strict";
<del>/* harmony import */ var _file__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./file */"./file.js");
<del>/* harmony import */ var _file__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_file__WEBPACK_IMPORTED_MODULE_0__);
<del>
<del>
<del>it("should auto-import a ES6 imported value on accept", function(done) {
<del> expect(_file__WEBPACK_IMPORTED_MODULE_0__["value"]).toEqual(1);
<del> module.hot.accept(/*! ./file */ "./file.js", function(__WEBPACK_OUTDATED_DEPENDENCIES__) { /* harmony import */ _file__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./file */"./file.js"); /* harmony import */ _file__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_file__WEBPACK_IMPORTED_MODULE_0__); (function() {
<del> expect(_file__WEBPACK_IMPORTED_MODULE_0__["value"]).toEqual(2);
<del> outside();
<del> done();
<del> })(__WEBPACK_OUTDATED_DEPENDENCIES__); });
<del> NEXT(__webpack_require__(/*! ../../update */ "../../update.js")(done));
<del>});
<del>
<del>function outside() {
<del> expect(_file__WEBPACK_IMPORTED_MODULE_0__["value"]).toEqual(2);
<del>}
<del>
<del>
<del>/***/ })
<del>
<del>/******/ });
<ide>\ No newline at end of file | 1 |
PHP | PHP | remember embedded files to remove duplication | 616baa33e8c2775f2896f062f8a439f8fe8b56b6 | <ide><path>src/Illuminate/Mail/Message.php
<ide> class Message
<ide> * @var \Swift_Message
<ide> */
<ide> protected $swift;
<add>
<add> /**
<add> * CIDs of files embedded in the message.
<add> *
<add> * @var array
<add> */
<add> protected $embeddedFiles = [];
<ide>
<ide> /**
<ide> * Create a new message instance.
<ide> protected function createAttachmentFromData($data, $name)
<ide> */
<ide> public function embed($file)
<ide> {
<del> return $this->swift->embed(Swift_Image::fromPath($file));
<add> if(isset($this->embeddedFiles[$file])) {
<add> return $this->embeddedFiles[$file];
<add> }
<add>
<add> $cid = $this->swift->embed(Swift_Image::fromPath($file));
<add>
<add> $this->embeddedFiles[$file] = $cid;
<add>
<add> return $cid;
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | add design decisions to faq document | c8c788c0036893f55f99d85ff920745f4db34c62 | <ide><path>docs/FAQ.md
<ide> - [Do I have to deep-clone my state in a reducer? Isn't copying my state going to be slow?](/docs/faq/Performance.md#performance-clone-state)
<ide> - [How can I reduce the number of store update events?](/docs/faq/Performance.md#performance-update-events)
<ide> - [Will having “one state tree” cause memory problems? Will dispatching many actions take up memory?](/docs/faq/Performance.md#performance-state-memory)
<add>- **Design Decisions**
<add> - [Why doesn't Redux pass the state and action to subscribers?](/docs/faq/DesignDecisions.md#does-not-pass-state-action-to-subscribers)
<add> - [Why doesn't Redux support using classes for actions and reducers?](/docs/faq/DesignDecisions.md#does-not-support-classes)
<add> - [Why does the middleware signature use currying?](/docs/faq/DesignDecisions.md#why-currying)
<add> - [Why does applyMiddleware use a closure for dispatch?](/docs/faq/DesignDecisions.md#closure-dispatch)
<add> - [Can you please change combineReducers to support nested state trees?](/docs/faq/DesignDecisions.md#combineReducers-limitations)
<add> - [Why doesn't mapDispatchToProps allow use of return values from getState() or mapStateToProps()?](/docs/faq/DesignDecisions.md#no-asynch-in-mapDispatchToProps)
<ide> - **React Redux**
<ide> - [Why isn't my component re-rendering, or my mapStateToProps running?](/docs/faq/ReactRedux.md#react-not-rerendering)
<ide> - [Why is my component re-rendering too often?](/docs/faq/ReactRedux.md#react-rendering-too-often)
<ide><path>docs/faq/DesignDecisions.md
<add># Redux FAQ: Design Decisions
<add>
<add>## Table of Contents
<add>
<add>- [Why doesn't Redux pass the state and action to subscribers?](#does-not-pass-state-action-to-subscribers)
<add>- [Why doesn't Redux support using classes for actions and reducers?](#does-not-support-classes)
<add>- [Why does the middleware signature use currying?](#why-currying)
<add>- [Why does applyMiddleware use a closure for dispatch?](#closure-dispatch)
<add>- [Can you please change combineReducers to support nested state trees?](#combineReducers-limitations)
<add>- [Why doesn't mapDispatchToProps allow use of return values from getState() or mapStateToProps()?](#no-asynch-in-mapDispatchToProps)
<add>
<add>
<add>## Design Decisions
<add>
<add><a id="does-not-pass-state-action-to-subscribers"></a>
<add>### Why doesn't Redux pass the state and action to subscribers?
<add>Subscribers are intended to respond to the state value itself, not the action. Updates to the state are not always processed synchronously, because Redux sometimes processes actions in batches to optimize performance and repeated re-rendering. The intended guarantee is that Redux eventually calls all subscribers with the most recent state, but not that it always calls each subscriber for each action. The store state is available in the subscriber simply by calling store.getState(). The action cannot be made available in the subsribers without breaking the way that actions are batched.
<add>
<add>A potential use-case for using the action inside a subscriber -- which is an unsupported feature -- is to ensure that a component only re-renders after certain kinds of actions. Re-rendering should instead be controlled instead through:
<add>1.) the [shouldComponentUpdate](https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate) lifecycle method
<add>2.) the [virtual DOM equality check (vDOMEq)](https://facebook.github.io/react/docs/optimizing-performance.html#avoid-reconciliation)
<add>3.) [React.PureComponent](https://facebook.github.io/react/docs/optimizing-performance.html#examples)
<add>4.) Using React-Redux: use [mapStateToProps](https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options) to subscribe components to only the parts of the store that they need.
<add>
<add><a id="does-not-support-classes"></a>
<add>### Why doesn't Redux support using classes for actions and reducers?
<add>The pattern of using functions, called action creators, to return action objects may seem counterintuitive to programmers with a lot of Object Oriented Programming experience, who would see this is a strong use-case for Classes and instances. Class instances for action objects and reducers are not supported because class instances make serialization and deserialization tricky. Deserialization methods like JSON.parse(string) will return a plain old Javascript object rather than class instances.
<add>
<add>Serialization enables the brower to store all actions that have been dispatched, as well as the previous store states, with much less memory. Rewinding and 'hot reloading' the store is central to the Redux developer experience and the function of Redux DevTools. This also enables deserialized actions to be stored on the server and re-serialized in the brower in the case of server-side rendering with Redux.
<add>
<add><a id="why-currying"></a>
<add>### Why does the middleware signature use currying?
<add>The [curried function signature](https://github.com/reactjs/redux/issues/1744) of declaring middleware is [deemed unnecessary](https://github.com/reactjs/redux/pull/784) by some, because both store and next are available when the applyMiddleware function is executed. This issue has been determined to not be [worth introducing breaking changes](https://github.com/reactjs/redux/issues/1744).
<add>
<add><a id="closure-dispatch"></a>
<add>### Why does applyMiddleware use a closure for dispatch?
<add>applyMiddleware takes the existing dispatch from the store and closes over it to create the initial chain of middlewares that have been invoked with an object that exposes the getState and dispatch functions, which enables middlewares that [rely on dispatch during initialization](https://github.com/reactjs/redux/pull/1592) to run.
<add>
<add><a id="combineReducers-limitations"></a>
<add>### Can you please change combineReducers to support nested state trees?
<add>No, but there are some limits to combineReducers that are worth knowing.
<add>- combineReducers receives an object where the values are all reducer names. Additional nesting is not possible, which limits the state shape. The following code is not possible:
<add>```
<add>const rootReducer = combineReducers({
<add> a : reducerA,
<add> b : {
<add> b1 : reducerB1,
<add> b2 : reducerB2
<add> }
<add>});
<add>```
<add>- reducers within combineReducers are only passed the part of the state that they modify, and not the top state.
<add>
<add>The default utility combineReducers is only one way to build a complex reducer. Consider using libraries like [combineSectionReducers](https://github.com/ryo33/combine-section-reducers) or [reduceReducers](https://github.com/acdlite/reduce-reducers) if you want your reducers to have a nested tree structure.
<add>
<add><a id="no-asynch-in-mapDispatchToProps"></a>
<add>### Why doesn't mapDispatchToProps allow use of return values from getState() or mapStateToProps()?
<add>In general, connect provides some way to generate a props object out of a closure that is injected with both the current state and dispatch. Asynchronous logic does not belong in the mapStateToProps and mapDispatchToProps functions at all. They should be only pure functions which transform the state to props and bind action creators to dispatch.
<add>
<add>You cannot modify the state during the execution of mapStateToProps, because modifying the state from these functions could lead to infinite loops because every update would reinvoke the map functions. Calling getState() inside mapStateToProps would always just return the same state that is passed to the function.
<add>
<add>The designed way to handle this use-case (needing to alter props based on the current state and mapDispatchToProps functions) is to work from the third argument to the connect function, mergeProps. If specified, it is passed the result of mapStateToProps(), mapDispatchToProps(), and the container component's props. The plain object you return from it will be passed as props to the wrapped component.
<add>
<add>#### Further information
<add>**Discussions**
<add>* [#580: Why doesn't Redux pass the state to subscribers?](https://github.com/reactjs/redux/issues/580)
<add>* [#2214: Alternate Proof of Concept: Enhancer Overhaul -- more on debouncing](https://github.com/reactjs/redux/pull/2214)
<add>
<add>* [#1171: Why doesn't Redux use classes for actions and reducers?](https://github.com/reactjs/redux/issues/1171#issuecomment-196819727)
<add>* Why does the middleware signature use currying?
<add> * See - [#55](https://github.com/reactjs/redux/pull/55), [#534](https://github.com/reactjs/redux/issues/534), [#784](https://github.com/reactjs/redux/pull/784), [#922](https://github.com/reactjs/redux/issues/922), [#1744](https://github.com/reactjs/redux/issues/1744)
<add>* Why does applyMiddleware use a closure for dispatch?
<add> * See - [#1592](https://github.com/reactjs/redux/pull/1592) and [#2097](https://github.com/reactjs/redux/issues/2097)
<add>* [#1768 Can you please change combineReducers to support nested state trees?](https://github.com/reactjs/redux/pull/1768)
<add>* [#237 Why doesn't mapDispatchToProps allow use of return values from getState() or mapStateToProps()?](https://github.com/reactjs/react-redux/issues/237) | 2 |
Javascript | Javascript | use mediumdate as default | c6c3949b14f4003ecab291243edfca61262f2c3d | <ide><path>src/filters.js
<ide> var GET_TIME_ZONE = /[A-Z]{3}(?![+\-])/,
<ide> * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
<ide> * number) or ISO 8601 extended datetime string (yyyy-MM-ddTHH:mm:ss.SSSZ).
<ide> * @param {string=} format Formatting rules (see Description). If not specified,
<del> * `fullDate` is used.
<add> * `mediumDate` is used.
<ide> * @returns {string} Formatted string or the input if input is not recognized as date/millis.
<ide> *
<ide> * @example
<ide> angularFilter.date = function(date, format) {
<ide> parts = [],
<ide> fn, match;
<ide>
<del> format = format || 'fullDate'
<add> format = format || 'mediumDate'
<ide> format = $locale.DATETIME_FORMATS[format] || format;
<ide> if (isString(date)) {
<ide> if (NUMBER_STRING.test(date)) {
<ide><path>test/FiltersSpec.js
<ide> describe('filter', function() {
<ide> });
<ide>
<ide> it('should do basic filter', function() {
<del> expect(date(noon)).toEqual(date(noon, 'fullDate'));
<del> expect(date(noon, '')).toEqual(date(noon, 'fullDate'));
<add> expect(date(noon)).toEqual(date(noon, 'mediumDate'));
<add> expect(date(noon, '')).toEqual(date(noon, 'mediumDate'));
<ide> });
<ide>
<ide> it('should accept number or number string representing milliseconds as input', function() {
<del> expect(date(noon.getTime())).toEqual(date(noon.getTime(), 'fullDate'));
<del> expect(date(noon.getTime() + "")).toEqual(date(noon.getTime() + "", 'fullDate'));
<add> expect(date(noon.getTime())).toEqual(date(noon.getTime(), 'mediumDate'));
<add> expect(date(noon.getTime() + "")).toEqual(date(noon.getTime() + "", 'mediumDate'));
<ide> });
<ide>
<ide> it('should accept various format strings', function() {
<ide> describe('filter', function() {
<ide> it('should be able to parse ISO 8601 dates/times using', function() {
<ide> var isoString = '2010-09-03T05:05:08.872Z';
<ide> expect(date(isoString)).
<del> toEqual(date(isoString, 'fullDate'));
<add> toEqual(date(isoString, 'mediumDate'));
<ide> });
<ide>
<ide> it('should parse format ending with non-replaced string', function() { | 2 |
Text | Text | use code markup/markdown in headers | 1c33523032a72ed1e25ba4678a65d367e134f5e0 | <ide><path>doc/api/punycode.md
<ide> The `punycode` module is a third-party dependency used by Node.js and
<ide> made available to developers as a convenience. Fixes or other modifications to
<ide> the module must be directed to the [Punycode.js][] project.
<ide>
<del>## punycode.decode(string)
<add>## `punycode.decode(string)`
<ide> <!-- YAML
<ide> added: v0.5.1
<ide> -->
<ide> punycode.decode('maana-pta'); // 'mañana'
<ide> punycode.decode('--dqo34k'); // '☃-⌘'
<ide> ```
<ide>
<del>## punycode.encode(string)
<add>## `punycode.encode(string)`
<ide> <!-- YAML
<ide> added: v0.5.1
<ide> -->
<ide> punycode.encode('mañana'); // 'maana-pta'
<ide> punycode.encode('☃-⌘'); // '--dqo34k'
<ide> ```
<ide>
<del>## punycode.toASCII(domain)
<add>## `punycode.toASCII(domain)`
<ide> <!-- YAML
<ide> added: v0.6.1
<ide> -->
<ide> punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'
<ide> punycode.toASCII('example.com'); // 'example.com'
<ide> ```
<ide>
<del>## punycode.toUnicode(domain)
<add>## `punycode.toUnicode(domain)`
<ide> <!-- YAML
<ide> added: v0.6.1
<ide> -->
<ide> punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'
<ide> punycode.toUnicode('example.com'); // 'example.com'
<ide> ```
<ide>
<del>## punycode.ucs2
<add>## `punycode.ucs2`
<ide> <!-- YAML
<ide> added: v0.7.0
<ide> -->
<ide>
<del>### punycode.ucs2.decode(string)
<add>### `punycode.ucs2.decode(string)`
<ide> <!-- YAML
<ide> added: v0.7.0
<ide> -->
<ide> punycode.ucs2.decode('abc'); // [0x61, 0x62, 0x63]
<ide> punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306]
<ide> ```
<ide>
<del>### punycode.ucs2.encode(codePoints)
<add>### `punycode.ucs2.encode(codePoints)`
<ide> <!-- YAML
<ide> added: v0.7.0
<ide> -->
<ide> punycode.ucs2.encode([0x61, 0x62, 0x63]); // 'abc'
<ide> punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06'
<ide> ```
<ide>
<del>## punycode.version
<add>## `punycode.version`
<ide> <!-- YAML
<ide> added: v0.6.1
<ide> --> | 1 |
Text | Text | fix minor typos, improve clarity of readme | e2abdaec7441686550aab64ccbafd38970646f0b | <ide><path>examples/http2-aggressive-splitting/template.md
<del>This example demonstrates the AggressiveSplittingPlugin for splitting the bundle into multiple smaller chunks to improve caching. This works best with a HTTP2 web server elsewise there is an overhead for the increased number of requests.
<add>This example demonstrates the AggressiveSplittingPlugin for splitting the bundle into multiple smaller chunks to improve caching. This works best with a HTTP2 web server, otherwise there is an overhead for the increased number of requests.
<ide>
<del>The AggressiveSplittingPlugin split every chunk until it reaches the specified `maxSize`. In this example it tries to create chunks with <50kB code (after minimizing this reduces to ~10kB). It groups modules together by folder structure. We assume modules in the same folder as similar likely to change and minimize and gzip good together.
<add>AggressiveSplittingPlugin splits every chunk until it reaches the specified `maxSize`. In this example it tries to create chunks with <50kB raw code, which typically minimizes to ~10kB. It groups modules together by folder structure, because modules in the same folder are likely to have similar repetitive text, making them gzip efficiently together. They are also likely to change together.
<ide>
<del>The AggressiveSplittingPlugin records it's splitting in the webpack records and try to restore splitting from records. This ensures that after changes to the application old splittings (and chunks) are reused. They are probably already in the clients cache. Therefore it's heavily recommended to use records!
<add>AggressiveSplittingPlugin records its splitting in the webpack records. When it is next run, it tries to use the last recorded splitting. Since changes to application code between one run and the next are usually in only a few modules (or just one), re-using the old splittings (and chunks, which are probably still in the client's cache), is highly advantageous.
<ide>
<del>Only chunks which are bigger than the specified `minSize` are stored into the records. This ensures that these chunks fill up as your application grows, instead of creating too many chunks for every change.
<add>Only chunks which are bigger than the specified `minSize` are stored into the records. This ensures that these chunks fill up as your application grows, instead of creating many records of small chunks for every change.
<ide>
<del>Chunks can get invalid if a module changes. Modules from invalid chunks go back into the module pool and new chunks are created from all modules in the pool.
<add>If a module changes, its chunks are declared to be invalid, and are put back into the module pool. New chunks are created from all modules in the pool.
<ide>
<ide> There is a tradeoff here:
<ide> | 1 |
Go | Go | clean the teardown process of network test | 57d85e7e54f7d074af8c496cba43ee18d3815207 | <ide><path>integration-cli/docker_experimental_network_test.go
<ide> func (s *DockerNetworkSuite) TestDockerNetworkMacvlanPersistance(c *check.C) {
<ide> master := "dm-dummy0"
<ide> // simulate the master link the vlan tagged subinterface parent link will use
<ide> createMasterDummy(c, master)
<add> // cleanup the master interface that also collects the slave dev
<add> defer deleteInterface(c, master)
<ide> // create a network specifying the desired sub-interface name
<ide> dockerCmd(c, "network", "create", "--driver=macvlan", "-o", "parent=dm-dummy0.60", "dm-persist")
<ide> assertNwIsAvailable(c, "dm-persist")
<ide> // Restart docker daemon to test the config has persisted to disk
<ide> s.d.Restart(c)
<ide> // verify network is recreated from persistence
<ide> assertNwIsAvailable(c, "dm-persist")
<del> // cleanup the master interface that also collects the slave dev
<del> deleteInterface(c, "dm-dummy0")
<ide> }
<ide>
<ide> func (s *DockerNetworkSuite) TestDockerNetworkIpvlanPersistance(c *check.C) {
<ide> func (s *DockerNetworkSuite) TestDockerNetworkIpvlanPersistance(c *check.C) {
<ide> master := "di-dummy0"
<ide> // simulate the master link the vlan tagged subinterface parent link will use
<ide> createMasterDummy(c, master)
<add> // cleanup the master interface that also collects the slave dev
<add> defer deleteInterface(c, master)
<ide> // create a network specifying the desired sub-interface name
<ide> dockerCmd(c, "network", "create", "--driver=ipvlan", "-o", "parent=di-dummy0.70", "di-persist")
<ide> assertNwIsAvailable(c, "di-persist")
<ide> // Restart docker daemon to test the config has persisted to disk
<ide> s.d.Restart(c)
<ide> // verify network is recreated from persistence
<ide> assertNwIsAvailable(c, "di-persist")
<del> // cleanup the master interface that also collects the slave dev
<del> deleteInterface(c, "di-dummy0")
<ide> }
<ide>
<ide> func (s *DockerNetworkSuite) TestDockerNetworkMacvlanSubIntCreate(c *check.C) {
<ide> func (s *DockerNetworkSuite) TestDockerNetworkMacvlanSubIntCreate(c *check.C) {
<ide> master := "dm-dummy0"
<ide> // simulate the master link the vlan tagged subinterface parent link will use
<ide> createMasterDummy(c, master)
<add> // cleanup the master interface which also collects the slave dev
<add> defer deleteInterface(c, master)
<ide> // create a network specifying the desired sub-interface name
<ide> dockerCmd(c, "network", "create", "--driver=macvlan", "-o", "parent=dm-dummy0.50", "dm-subinterface")
<ide> assertNwIsAvailable(c, "dm-subinterface")
<del> // cleanup the master interface which also collects the slave dev
<del> deleteInterface(c, "dm-dummy0")
<ide> }
<ide>
<ide> func (s *DockerNetworkSuite) TestDockerNetworkIpvlanSubIntCreate(c *check.C) {
<ide> func (s *DockerNetworkSuite) TestDockerNetworkIpvlanSubIntCreate(c *check.C) {
<ide> master := "di-dummy0"
<ide> // simulate the master link the vlan tagged subinterface parent link will use
<ide> createMasterDummy(c, master)
<add> // cleanup the master interface which also collects the slave dev
<add> defer deleteInterface(c, master)
<ide> // create a network specifying the desired sub-interface name
<ide> dockerCmd(c, "network", "create", "--driver=ipvlan", "-o", "parent=di-dummy0.60", "di-subinterface")
<ide> assertNwIsAvailable(c, "di-subinterface")
<del> // cleanup the master interface which also collects the slave dev
<del> deleteInterface(c, "di-dummy0")
<ide> }
<ide>
<ide> func (s *DockerNetworkSuite) TestDockerNetworkMacvlanOverlapParent(c *check.C) {
<ide> func (s *DockerNetworkSuite) TestDockerNetworkMacvlanOverlapParent(c *check.C) {
<ide> // master dummy interface 'dm' abbreviation represents 'docker macvlan'
<ide> master := "dm-dummy0"
<ide> createMasterDummy(c, master)
<add> // cleanup the master interface which also collects the slave dev
<add> defer deleteInterface(c, master)
<ide> createVlanInterface(c, master, "dm-dummy0.40", "40")
<ide> // create a network using an existing parent interface
<ide> dockerCmd(c, "network", "create", "--driver=macvlan", "-o", "parent=dm-dummy0.40", "dm-subinterface")
<ide> func (s *DockerNetworkSuite) TestDockerNetworkMacvlanOverlapParent(c *check.C) {
<ide> out, _, err := dockerCmdWithError("network", "create", "--driver=macvlan", "-o", "parent=dm-dummy0.40", "dm-parent-net-overlap")
<ide> // verify that the overlap returns an error
<ide> c.Assert(err, check.NotNil, check.Commentf(out))
<del> // cleanup the master interface which also collects the slave dev
<del> deleteInterface(c, "dm-dummy0")
<ide> }
<ide>
<ide> func (s *DockerNetworkSuite) TestDockerNetworkIpvlanOverlapParent(c *check.C) {
<ide> func (s *DockerNetworkSuite) TestDockerNetworkIpvlanOverlapParent(c *check.C) {
<ide> // master dummy interface 'dm' abbreviation represents 'docker ipvlan'
<ide> master := "di-dummy0"
<ide> createMasterDummy(c, master)
<add> // cleanup the master interface which also collects the slave dev
<add> defer deleteInterface(c, master)
<ide> createVlanInterface(c, master, "di-dummy0.30", "30")
<ide> // create a network using an existing parent interface
<ide> dockerCmd(c, "network", "create", "--driver=ipvlan", "-o", "parent=di-dummy0.30", "di-subinterface")
<ide> func (s *DockerNetworkSuite) TestDockerNetworkIpvlanOverlapParent(c *check.C) {
<ide> out, _, err := dockerCmdWithError("network", "create", "--driver=ipvlan", "-o", "parent=di-dummy0.30", "di-parent-net-overlap")
<ide> // verify that the overlap returns an error
<ide> c.Assert(err, check.NotNil, check.Commentf(out))
<del> // cleanup the master interface which also collects the slave dev
<del> deleteInterface(c, "di-dummy0")
<ide> }
<ide>
<ide> func (s *DockerNetworkSuite) TestDockerNetworkMacvlanMultiSubnet(c *check.C) {
<ide> func (s *DockerSuite) TestDockerNetworkMacVlanExistingParent(c *check.C) {
<ide> testRequires(c, DaemonIsLinux, macvlanKernelSupport, NotUserNamespace, NotArm, ExperimentalDaemon)
<ide> netName := "dm-parent-exists"
<ide> createMasterDummy(c, "dm-dummy0")
<add> defer deleteInterface(c, "dm-dummy0")
<ide> //out, err := createVlanInterface(c, "dm-parent", "dm-slave", "macvlan", "bridge")
<ide> // create a network using an existing parent interface
<ide> dockerCmd(c, "network", "create", "--driver=macvlan", "-o", "parent=dm-dummy0", netName)
<ide> func (s *DockerSuite) TestDockerNetworkMacVlanExistingParent(c *check.C) {
<ide> assertNwNotAvailable(c, netName)
<ide> // verify the network delete did not delete the predefined link
<ide> linkExists(c, "dm-dummy0")
<del> deleteInterface(c, "dm-dummy0")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestDockerNetworkMacVlanSubinterface(c *check.C) {
<ide> // macvlan bridge mode - empty parent interface containers can reach each other internally but not externally
<ide> testRequires(c, DaemonIsLinux, macvlanKernelSupport, NotUserNamespace, NotArm, ExperimentalDaemon)
<ide> netName := "dm-subinterface"
<ide> createMasterDummy(c, "dm-dummy0")
<add> // delete the parent interface which also collects the slave
<add> defer deleteInterface(c, "dm-dummy0")
<ide> createVlanInterface(c, "dm-dummy0", "dm-dummy0.20", "20")
<ide> // create a network using an existing parent interface
<ide> dockerCmd(c, "network", "create", "--driver=macvlan", "-o", "parent=dm-dummy0.20", netName)
<ide> func (s *DockerSuite) TestDockerNetworkMacVlanSubinterface(c *check.C) {
<ide> assertNwNotAvailable(c, netName)
<ide> // verify the network delete did not delete the predefined sub-interface
<ide> linkExists(c, "dm-dummy0.20")
<del> // delete the parent interface which also collects the slave
<del> deleteInterface(c, "dm-dummy0")
<ide> }
<ide>
<ide> func createMasterDummy(c *check.C, master string) { | 1 |
PHP | PHP | fix bcc sends on mailgun | 7d2e774bf959933a5835762a7e6b1e3e45fdd75c | <ide><path>src/Illuminate/Mail/Transport/MailgunTransport.php
<ide> public function send(Swift_Mime_Message $message, &$failedRecipients = null)
<ide> {
<ide> $this->beforeSendPerformed($message);
<ide>
<add> $to = $this->getTo($message);
<add>
<ide> $message->setBcc([]);
<ide>
<del> $this->client->post($this->url, $this->payload($message));
<add> $this->client->post($this->url, $this->payload($message, $to));
<ide>
<ide> $this->sendPerformed($message);
<ide>
<ide> public function send(Swift_Mime_Message $message, &$failedRecipients = null)
<ide> * @param \Swift_Mime_Message $message
<ide> * @return array
<ide> */
<del> protected function payload(Swift_Mime_Message $message)
<add> protected function payload(Swift_Mime_Message $message, $to)
<ide> {
<ide> return [
<ide> 'auth' => [
<ide> protected function payload(Swift_Mime_Message $message)
<ide> 'multipart' => [
<ide> [
<ide> 'name' => 'to',
<del> 'contents' => $this->getTo($message),
<add> 'contents' => $to,
<ide> ],
<ide> [
<ide> 'name' => 'message', | 1 |
Javascript | Javascript | fix forwardref displayname on text and view | ddf2c2ffd6f58743f25253289297bfe19fa17c75 | <ide><path>Libraries/Components/View/View.js
<ide> const RCTView = requireNativeComponent('RCTView');
<ide>
<ide> let ViewToExport = RCTView;
<ide> if (__DEV__) {
<add> const View = (props: Props, forwardedRef: ?React.Ref<'RCTView'>) => {
<add> return (
<add> <TextAncestor.Consumer>
<add> {hasTextAncestor => {
<add> invariant(
<add> !hasTextAncestor,
<add> 'Nesting of <View> within <Text> is not currently supported.',
<add> );
<add> return <RCTView {...props} ref={forwardedRef} />;
<add> }}
<add> </TextAncestor.Consumer>
<add> );
<add> };
<add> View.displayName = 'View'; // TODO(T30332650) remove bug workaround
<ide> // $FlowFixMe - TODO T29156721 `React.forwardRef` is not defined in Flow, yet.
<del> ViewToExport = React.forwardRef((props, ref) => (
<del> <TextAncestor.Consumer>
<del> {hasTextAncestor => {
<del> invariant(
<del> !hasTextAncestor,
<del> 'Nesting of <View> within <Text> is not currently supported.',
<del> );
<del> return <RCTView {...props} ref={ref} />;
<del> }}
<del> </TextAncestor.Consumer>
<del> ));
<del> ViewToExport.displayName = 'View';
<add> ViewToExport = React.forwardRef(View);
<ide> }
<ide>
<del>module.exports = ((ViewToExport: any): Class<NativeComponent<ViewProps>>);
<add>module.exports = ((ViewToExport: $FlowFixMe): Class<
<add> NativeComponent<ViewProps>,
<add>>);
<ide><path>Libraries/Text/Text.js
<ide> const RCTVirtualText =
<ide> uiViewClassName: 'RCTVirtualText',
<ide> }));
<ide>
<add>const Text = (
<add> props: TextProps,
<add> forwardedRef: ?React.Ref<'RCTText' | 'RCTVirtualText'>,
<add>) => {
<add> return <TouchableText {...props} forwardedRef={forwardedRef} />;
<add>};
<add>Text.displayName = 'Text'; // TODO(T30332650) remove bug workaround
<ide> // $FlowFixMe - TODO T29156721 `React.forwardRef` is not defined in Flow, yet.
<del>const Text = React.forwardRef((props, ref) => (
<del> <TouchableText {...props} forwardedRef={ref} />
<del>));
<del>Text.displayName = 'Text';
<add>const TextToExport = React.forwardRef(Text);
<ide>
<ide> // TODO: Deprecate this.
<del>Text.propTypes = TextPropTypes;
<add>TextToExport.propTypes = TextPropTypes;
<ide>
<del>module.exports = ((Text: any): Class<NativeComponent<TextProps>>);
<add>module.exports = (TextToExport: Class<NativeComponent<TextProps>>);
<ide><path>jest/mockComponent.js
<ide> module.exports = (moduleName, instanceMethods) => {
<ide>
<ide> const Component = class extends SuperClass {
<ide> render() {
<del> const name = RealComponent.displayName || RealComponent.name;
<add> const name =
<add> RealComponent.displayName ||
<add> RealComponent.name ||
<add> (RealComponent.render // handle React.forwardRef
<add> ? RealComponent.render.displayName || RealComponent.render.name
<add> : 'Unknown');
<ide>
<ide> const props = Object.assign({}, RealComponent.defaultProps);
<ide> | 3 |
Text | Text | add countdown module to writing tests guide | cf76176476911c6f0bd8465cf10d9e1dcf2b4a98 | <ide><path>doc/guides/writing-tests.md
<ide> platforms.
<ide>
<ide> ### The *common* API
<ide>
<del>Make use of the helpers from the `common` module as much as possible.
<add>Make use of the helpers from the `common` module as much as possible. Please refer
<add>to the [common file documentation](https://github.com/nodejs/node/tree/master/test/common)
<add>for the full details of the helpers.
<ide>
<del>One interesting case is `common.mustCall`. The use of `common.mustCall` may
<del>avoid the use of extra variables and the corresponding assertions. Let's explain
<del>this with a real test from the test suite.
<add>#### common.mustCall
<add>
<add>One interesting case is `common.mustCall`. The use of `common.mustCall` may avoid
<add>the use of extra variables and the corresponding assertions. Let's explain this
<add>with a real test from the test suite.
<ide>
<ide> ```javascript
<ide> 'use strict';
<ide> const server = http.createServer(common.mustCall(function(req, res) {
<ide> });
<ide>
<ide> ```
<add>#### Countdown Module
<add>
<add>The common [Countdown module](https://github.com/nodejs/node/tree/master/test/common#countdown-module) provides a simple countdown mechanism for tests that
<add>require a particular action to be taken after a given number of completed tasks
<add>(for instance, shutting down an HTTP server after a specific number of requests).
<add>
<add>```javascript
<add>const Countdown = require('../common/countdown');
<add>
<add>const countdown = new Countdown(2, function() {
<add> console.log('.');
<add>});
<add>
<add>countdown.dec();
<add>countdown.dec(); // The countdown callback will be invoked now.
<add>```
<add>
<ide>
<ide> ### Flags
<ide> | 1 |
PHP | PHP | apply fixes from styleci | 09e9f8ee8132a727bfe4e0f1c8e36ed67952bad7 | <ide><path>tests/Queue/QueueBeanstalkdQueueTest.php
<ide> use Illuminate\Container\Container;
<ide> use Illuminate\Queue\BeanstalkdQueue;
<ide> use Illuminate\Queue\Jobs\BeanstalkdJob;
<del>use Pheanstalk\Contract\PheanstalkInterface;
<ide>
<ide> class QueueBeanstalkdQueueTest extends TestCase
<ide> { | 1 |
Ruby | Ruby | add test for installrenamed on directories | 8a8de3a29678eb64e7686bc5e35701edb84e9946 | <ide><path>Library/Homebrew/test/test_pathname.rb
<ide> def test_install_renamed
<ide> assert_equal "a", File.read(@dst+@file.basename)
<ide> assert_equal "b", File.read(@dst+"#{@file.basename}.default")
<ide> end
<add>
<add> def test_install_renamed_directory
<add> @dst.extend(InstallRenamed)
<add> @file.write "a"
<add> @dst.install @src
<add> assert_equal "a", File.read(@dst+@src.basename+@file.basename)
<add> end
<ide> end
<ide>
<ide> class PathnameInstallTests < Homebrew::TestCase | 1 |
Python | Python | add xfailing test for out-of-bounds heads | 819768483f7eeafaf0ab5c162c4884a7b982fdd5 | <ide><path>spacy/tests/doc/test_doc_spilt.py
<ide> def test_split_heads_error(en_vocab):
<ide> retokenizer.split(doc[0], ["Los", "Angeles"], [0, 0])
<ide>
<ide>
<add>@pytest.mark.xfail
<add>def test_split_heads_out_of_bounds(en_vocab):
<add> """Test that the retokenizer raises an error for out-of-bounds heads. The
<add> indices are relative, so head 1 for "Angeles" would be the token following
<add> it, which is out-of-bounds. Previously, the retokenizer would accept this
<add> and spaCy would then fail later.
<add> """
<add> doc = Doc(en_vocab, words=["Start", "LosAngeles"])
<add> with pytest.raises(ValueError):
<add> with doc.retokenize() as retokenizer:
<add> retokenizer.split(doc[1], ["Los", "Angeles"], [0, 1])
<add>
<add>
<ide> def test_spans_entity_merge_iob():
<ide> # Test entity IOB stays consistent after merging
<ide> words = ["abc", "d", "e"] | 1 |
Text | Text | fix typo in method name [ci skip] | 341151da5b298d95133b7ac1dae35a54faf0763f | <ide><path>guides/source/action_controller_overview.md
<ide> There are a couple of things to notice in the above example. We need to make
<ide> sure to close the response stream. Forgetting to close the stream will leave
<ide> the socket open forever. We also have to set the content type to `text/event-stream`
<ide> before we write to the response stream. This is because headers cannot be written
<del>after the response has been committed (when `response.committed` returns a truthy
<add>after the response has been committed (when `response.committed?` returns a truthy
<ide> value), which occurs when you `write` or `commit` the response stream.
<ide>
<ide> #### Example Usage | 1 |
Ruby | Ruby | improve application quitting | f61b963744c41b62c0253ee8cdbeb5f7b576dafe | <ide><path>Library/Homebrew/cask/artifact/abstract_uninstall.rb
<ide> def uninstall_launchctl(*services, command: nil, **_)
<ide> command.run!("/bin/launchctl", args: ["remove", service], sudo: with_sudo)
<ide> sleep 1
<ide> end
<del> paths = ["/Library/LaunchAgents/#{service}.plist",
<del> "/Library/LaunchDaemons/#{service}.plist"]
<add> paths = [
<add> "/Library/LaunchAgents/#{service}.plist",
<add> "/Library/LaunchDaemons/#{service}.plist",
<add> ]
<ide> paths.each { |elt| elt.prepend(ENV["HOME"]) } unless with_sudo
<ide> paths = paths.map { |elt| Pathname(elt) }.select(&:exist?)
<ide> paths.each do |path|
<ide> def uninstall_quit(*bundle_ids, command: nil, **_)
<ide> next
<ide> end
<ide>
<del> ohai "Quitting application ID '#{bundle_id}'."
<del> command.run!("/usr/bin/osascript", args: ["-e", %Q(tell application id "#{bundle_id}" to quit)], sudo: true)
<add> ohai "Quitting application '#{bundle_id}'..."
<ide>
<ide> begin
<del> Timeout.timeout(3) do
<add> Timeout.timeout(10) do
<ide> Kernel.loop do
<del> break if running_processes(bundle_id, command: command).empty?
<add> next unless quit(bundle_id).success?
<add> if running_processes(bundle_id, command: command).empty?
<add> puts "Application '#{bundle_id}' quit successfully."
<add> break
<add> end
<ide> end
<ide> end
<ide> rescue Timeout::Error
<add> opoo "Application '#{bundle_id}' did not quit."
<ide> next
<ide> end
<ide> end
<ide> end
<ide>
<add> def quit(bundle_id)
<add> script = <<~JAVASCRIPT
<add> 'use strict';
<add>
<add> ObjC.import('stdlib')
<add>
<add> function run(argv) {
<add> var app = Application(argv[0])
<add>
<add> try {
<add> app.quit()
<add> } catch (err) {
<add> if (app.running()) {
<add> $.exit(1)
<add> }
<add> }
<add>
<add> $.exit(0)
<add> }
<add> JAVASCRIPT
<add>
<add> system_command "osascript", args: ["-l", "JavaScript", "-e", script, bundle_id],
<add> print_stderr: false,
<add> sudo: true
<add> end
<add> private :quit
<add>
<ide> # :signal should come after :quit so it can be used as a backup when :quit fails
<ide> def uninstall_signal(*signals, command: nil, **_)
<ide> signals.each do |pair|
<ide> def uninstall_login_item(*login_items, command: nil, upgrade: false, **_)
<ide> login_items.each do |name|
<ide> ohai "Removing login item #{name}"
<ide> command.run!(
<del> "/usr/bin/osascript",
<add> "osascript",
<ide> args: [
<ide> "-e",
<ide> %Q(tell application "System Events" to delete every login item whose name is "#{name}"),
<ide> def uninstall_trash(*paths, **options)
<ide> end
<ide>
<ide> def trash_paths(*paths, command: nil, **_)
<del> result = command.run!("/usr/bin/osascript", args: ["-e", <<~APPLESCRIPT, *paths])
<add> result = command.run!("osascript", args: ["-e", <<~APPLESCRIPT, *paths])
<ide> on run argv
<ide> repeat with i from 1 to (count argv)
<ide> set item i of argv to (item i of argv as POSIX file)
<ide><path>Library/Homebrew/test/cask/artifact/uninstall_zap_shared_examples.rb
<ide>
<ide> it "is supported" do
<ide> FakeSystemCommand.expects_command(
<del> ["/usr/bin/osascript", "-e", 'tell application "System Events" to delete every login ' \
<del> 'item whose name is "Fancy"'],
<add> ["osascript", "-e", 'tell application "System Events" to delete every login item whose name is "Fancy"'],
<ide> )
<ide>
<ide> subject | 2 |
PHP | PHP | remove useless mock | 35ab21af36861b27bd3621bccef4e15696aa2e73 | <ide><path>tests/Auth/AuthEloquentUserProviderTest.php
<ide> public function testCredentialValidation()
<ide>
<ide> public function testModelsCanBeCreated()
<ide> {
<del> $conn = m::mock('Illuminate\Database\Connection');
<ide> $hasher = m::mock('Illuminate\Contracts\Hashing\Hasher');
<ide> $provider = new Illuminate\Auth\EloquentUserProvider($hasher, 'EloquentProviderUserStub');
<ide> $model = $provider->createModel(); | 1 |
PHP | PHP | remove extra fi | 98c4cef6fc141f4a02a117b087538476657fedff | <ide><path>src/Console/ConsoleOptionParser.php
<ide> protected function _parseOption($name, $params)
<ide> if ($option->validChoice($value)) {
<ide> if ($option->acceptsMultiple($value)) {
<ide> $params[$name][] = $value;
<del>fi } else {
<add> } else {
<ide> $params[$name] = $value;
<ide> }
<ide> | 1 |
Ruby | Ruby | remove deprecate #all usage | b30996307d3b8d0d519c7ddcfa28fdeed428b602 | <ide><path>activerecord/test/cases/associations/eager_load_nested_include_test.rb
<ide> def test_missing_data_in_a_nested_include_should_not_cause_errors_when_construct
<ide> assert_nothing_raised do
<ide> # @davey_mcdave doesn't have any author_favorites
<ide> includes = {:posts => :comments, :categorizations => :category, :author_favorites => :favorite_author }
<del> Author.all :include => includes, :conditions => {:authors => {:name => @davey_mcdave.name}}, :order => 'categories.name'
<add> Author.scoped(:includes => includes, :where => {:authors => {:name => @davey_mcdave.name}}, :order => 'categories.name').to_a
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/finder_test.rb
<ide> def test_find_with_hash_conditions_on_joined_table
<ide> end
<ide>
<ide> def test_find_with_hash_conditions_on_joined_table_and_with_range
<del> firms = DependentFirm.all :joins => :account, :conditions => {:name => 'RailsCore', :accounts => { :credit_limit => 55..60 }}
<add> firms = DependentFirm.scoped :joins => :account, :where => {:name => 'RailsCore', :accounts => { :credit_limit => 55..60 }}
<ide> assert_equal 1, firms.size
<ide> assert_equal companies(:rails_core), firms.first
<ide> end
<ide><path>activerecord/test/cases/persistence_test.rb
<ide> def test_increment_attribute_by
<ide>
<ide> def test_destroy_all
<ide> conditions = "author_name = 'Mary'"
<del> topics_by_mary = Topic.all(:conditions => conditions, :order => 'id')
<add> topics_by_mary = Topic.scoped(:where => conditions, :order => 'id').to_a
<ide> assert ! topics_by_mary.empty?
<ide>
<ide> assert_difference('Topic.count', -topics_by_mary.size) do
<ide><path>activerecord/test/cases/relations_test.rb
<ide> def test_intersection_with_array
<ide> assert_equal [rails_author], relation & [rails_author]
<ide> end
<ide>
<del> def test_removing_limit_with_options
<del> assert_not_equal 1, Post.limit(1).all(:limit => nil).count
<del> end
<del>
<ide> def test_primary_key
<ide> assert_equal "id", Post.scoped.primary_key
<ide> end | 4 |
PHP | PHP | remove setter of passedargs | c71b11d9f05952803568b8c9ce4ac9ac138f17a1 | <ide><path>src/View/View.php
<ide> public function getRequest()
<ide> *
<ide> * - $this->request - To the $request parameter
<ide> * - $this->plugin - To the value returned by $request->getParam('plugin')
<del> * - $this->passedArgs - Same as $request->params['pass]
<ide> *
<ide> * @param \Cake\Http\ServerRequest $request Request instance.
<ide> * @return $this
<ide> public function setRequest(ServerRequest $request)
<ide> $this->request = $request;
<ide> $this->plugin = $request->getParam('plugin');
<ide>
<del> if ($request->getParam('pass')) {
<del> $this->passedArgs = $request->getParam('pass');
<del> }
<del>
<ide> return $this;
<ide> }
<ide> | 1 |
Java | Java | introduce messagecodeformatter abstraction | 38bfb2bd893f062a9d90d3cfd14a2b0d619a4b5a | <ide><path>spring-context/src/main/java/org/springframework/validation/DefaultMessageCodesResolver.java
<ide> * Default implementation of the {@link MessageCodesResolver} interface.
<ide> *
<ide> * <p>Will create two message codes for an object error, in the following order (when
<del> * using the {@link Style#PREFIX_ERROR_CODE prefixed} {@link #setStyle(Style) style}):
<add> * using the {@link Format#PREFIX_ERROR_CODE prefixed}
<add> * {@link #setMessageCodeFormatter(MessageCodeFormatter) formatter}):
<ide> * <ul>
<ide> * <li>1.: code + "." + object name
<ide> * <li>2.: code
<ide> * </ul>
<ide> *
<ide> * <p>By default the {@code errorCode}s will be placed at the beginning of constructed
<del> * message strings. The {@link #setStyle(Style) style} property can be used to specify
<del> * alternative {@link Style styles} of concatination.
<add> * message strings. The {@link #setMessageCodeFormatter(MessageCodeFormatter)
<add> * messageCodeFormatter} property can be used to specify an alternative concatenation
<add> * {@link MessageCodeFormatter format}.
<ide> *
<ide> * <p>In order to group all codes into a specific category within your resource bundles,
<ide> * e.g. "validation.typeMismatch.name" instead of the default "typeMismatch.name",
<ide> * consider specifying a {@link #setPrefix prefix} to be applied.
<ide> *
<ide> * @author Juergen Hoeller
<ide> * @author Phillip Webb
<add> * @author Chris Beams
<ide> * @since 1.0.1
<ide> */
<ide> @SuppressWarnings("serial")
<ide> public class DefaultMessageCodesResolver implements MessageCodesResolver, Serial
<ide> */
<ide> public static final String CODE_SEPARATOR = ".";
<ide>
<del> private static final Style DEFAULT_STYLE = Style.PREFIX_ERROR_CODE;
<add> private static final MessageCodeFormatter DEFAULT_FORMATTER = Format.PREFIX_ERROR_CODE;
<ide>
<ide>
<ide> private String prefix = "";
<ide>
<del> private Style style = DEFAULT_STYLE;
<add> private MessageCodeFormatter formatter = DEFAULT_FORMATTER;
<ide>
<ide>
<ide> /**
<ide> public void setPrefix(String prefix) {
<ide> }
<ide>
<ide> /**
<del> * Specify the style of message code that will be built by this resolver.
<del> * <p>Default is {@link Style#PREFIX_ERROR_CODE}.
<add> * Specify the format for message codes built by this resolver.
<add> * <p>The default is {@link Format#PREFIX_ERROR_CODE}.
<add> * @since 3.2
<ide> */
<del> public void setStyle(Style style) {
<del> this.style = (style == null ? DEFAULT_STYLE : style);
<add> public void setMessageCodeFormatter(MessageCodeFormatter formatter) {
<add> this.formatter = (formatter == null ? DEFAULT_FORMATTER : formatter);
<ide> }
<ide>
<ide> /**
<ide> private void addCodes(Collection<String> codeList, String errorCode, String obje
<ide> }
<ide>
<ide> private void addCode(Collection<String> codeList, String errorCode, String objectName, String field) {
<del> String code = getCode(errorCode, objectName, field);
<del> codeList.add(postProcessMessageCode(code));
<del> }
<del>
<del> private String getCode(String errorCode, String objectName, String field) {
<del> switch (this.style) {
<del> case PREFIX_ERROR_CODE:
<del> return toDelimitedString(errorCode, objectName, field);
<del> case POSTFIX_ERROR_CODE:
<del> return toDelimitedString(objectName, field, errorCode);
<del> }
<del> throw new IllegalStateException("Unknown style " + this.style);
<del> }
<del>
<del> private String toDelimitedString(String... elements) {
<del> StringBuilder rtn = new StringBuilder();
<del> for (String element : elements) {
<del> if(StringUtils.hasLength(element)) {
<del> rtn.append(rtn.length() == 0 ? "" : CODE_SEPARATOR);
<del> rtn.append(element);
<del> }
<del> }
<del> return rtn.toString();
<add> codeList.add(postProcessMessageCode(this.formatter.format(errorCode, objectName, field)));
<ide> }
<ide>
<ide> /**
<ide> protected String postProcessMessageCode(String code) {
<ide>
<ide>
<ide> /**
<del> * The various styles that can be used to construct message codes.
<add> * Common message code formats.
<add> *
<add> * @author Phil Webb
<add> * @author Chris Beams
<add> * @since 3.2
<add> * @see MessageCodeFormatter
<add> * @see DefaultMessageCodesResolver#setMessageCodeFormatter(MessageCodeFormatter)
<ide> */
<del> public static enum Style {
<add> public static enum Format implements MessageCodeFormatter {
<ide>
<ide> /**
<del> * Prefix the error code at the beginning of the generated message code. eg:
<add> * Prefix the error code at the beginning of the generated message code. e.g.:
<ide> * {@code errorCode + "." + object name + "." + field}
<ide> */
<del> PREFIX_ERROR_CODE,
<add> PREFIX_ERROR_CODE {
<add> public String format(String errorCode, String objectName, String field) {
<add> return toDelimitedString(errorCode, objectName, field);
<add> }
<add> },
<ide>
<ide> /**
<del> * Postfix the error code at the end of the generated message code. eg:
<add> * Postfix the error code at the end of the generated message code. e.g.:
<ide> * {@code object name + "." + field + "." + errorCode}
<ide> */
<del> POSTFIX_ERROR_CODE
<add> POSTFIX_ERROR_CODE {
<add> public String format(String errorCode, String objectName, String field) {
<add> return toDelimitedString(objectName, field, errorCode);
<add> }
<add> };
<add>
<add> /**
<add> * Concatenate the given elements, delimiting each with
<add> * {@link DefaultMessageCodesResolver#CODE_SEPARATOR}, skipping zero-length or
<add> * null elements altogether.
<add> */
<add> public static String toDelimitedString(String... elements) {
<add> StringBuilder rtn = new StringBuilder();
<add> for (String element : elements) {
<add> if(StringUtils.hasLength(element)) {
<add> rtn.append(rtn.length() == 0 ? "" : CODE_SEPARATOR);
<add> rtn.append(element);
<add> }
<add> }
<add> return rtn.toString();
<add> }
<ide> }
<ide>
<ide> }
<ide><path>spring-context/src/main/java/org/springframework/validation/MessageCodeFormatter.java
<add>/*
<add> * Copyright 2002-2012 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.validation;
<add>
<add>/**
<add> * A strategy interface for formatting message codes.
<add> *
<add> * @author Chris Beams
<add> * @since 3.2
<add> * @see DefaultMessageCodesResolver
<add> */
<add>public interface MessageCodeFormatter {
<add>
<add> /**
<add> * Build and return a message code consisting of the given fields, usually delimited
<add> * by {@link DefaultMessageCodesResolver#CODE_SEPARATOR}.
<add> * @param errorCode e.g.: "typeMismatch"
<add> * @param objectName e.g.: "user"
<add> * @param field e.g. "age"
<add> * @return concatenated message code, e.g.: "typeMismatch.user.age"
<add> * @see DefaultMessageCodesResolver.Format
<add> */
<add> String format(String errorCode, String objectName, String field);
<add>}
<ide>\ No newline at end of file
<ide><path>spring-context/src/test/java/org/springframework/validation/DefaultMessageCodesResolverTests.java
<ide>
<ide> import org.junit.Test;
<ide> import org.springframework.beans.TestBean;
<del>import org.springframework.validation.DefaultMessageCodesResolver.Style;
<add>import org.springframework.validation.DefaultMessageCodesResolver.Format;
<ide>
<ide> /**
<ide> * Tests for {@link DefaultMessageCodesResolver}.
<ide> public void shouldSupportNullFieldType() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void shouldSupportPostfixStyle() throws Exception {
<del> resolver.setStyle(Style.POSTFIX_ERROR_CODE);
<add> public void shouldSupportPostfixFormat() throws Exception {
<add> resolver.setMessageCodeFormatter(Format.POSTFIX_ERROR_CODE);
<ide> String[] codes = resolver.resolveMessageCodes("errorCode", "objectName");
<ide> assertThat(codes, is(equalTo(new String[] {
<ide> "objectName.errorCode",
<ide> "errorCode" })));
<ide> }
<ide>
<ide> @Test
<del> public void shouldSupportFieldPostfixStyle() throws Exception {
<del> resolver.setStyle(Style.POSTFIX_ERROR_CODE);
<add> public void shouldSupportFieldPostfixFormat() throws Exception {
<add> resolver.setMessageCodeFormatter(Format.POSTFIX_ERROR_CODE);
<ide> String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field",
<ide> TestBean.class);
<ide> assertThat(codes, is(equalTo(new String[] {
<ide> public void shouldSupportFieldPostfixStyle() throws Exception {
<ide> "org.springframework.beans.TestBean.errorCode",
<ide> "errorCode" })));
<ide> }
<add>
<add> @Test
<add> public void shouldSupportCustomFormat() throws Exception {
<add> resolver.setMessageCodeFormatter(new MessageCodeFormatter() {
<add> public String format(String errorCode, String objectName, String field) {
<add> return DefaultMessageCodesResolver.Format.toDelimitedString(
<add> "CUSTOM-" + errorCode, objectName, field);
<add> }
<add> });
<add> String[] codes = resolver.resolveMessageCodes("errorCode", "objectName");
<add> assertThat(codes, is(equalTo(new String[] {
<add> "CUSTOM-errorCode.objectName",
<add> "CUSTOM-errorCode" })));
<add> }
<ide> } | 3 |
Javascript | Javascript | update hashes for all library names | 913b18b4bb2e9ec4e8cef1ac05c37d383148c991 | <ide><path>lib/UmdMainTemplatePlugin.js
<ide> class UmdMainTemplatePlugin {
<ide> }.bind(this));
<ide> mainTemplate.plugin("global-hash-paths", function(paths) {
<ide> if(this.names.root) paths = paths.concat(this.names.root);
<add> if(this.names.amd) paths = paths.concat(this.names.amd);
<add> if(this.names.commonjs) paths = paths.concat(this.names.commonjs);
<ide> return paths;
<ide> }.bind(this));
<ide> mainTemplate.plugin("hash", function(hash) {
<ide> hash.update("umd");
<ide> hash.update(`${this.names.root}`);
<add> hash.update(`${this.names.amd}`);
<add> hash.update(`${this.names.commonjs}`);
<ide> }.bind(this));
<ide> }
<ide> } | 1 |
Python | Python | remove unused error | 2d520d3b45d2c997eeeaad8451c742dc01ae4f5c | <ide><path>spacy/errors.py
<ide> class Errors:
<ide> "existing extension, set `force=True` on `{obj}.set_extension`.")
<ide> E091 = ("Invalid extension attribute {name}: expected callable or None, "
<ide> "but got: {value}")
<del> E092 = ("Could not find or assign name for word vectors. Ususally, the "
<del> "name is read from the model's meta.json in vector.name. "
<del> "Alternatively, it is built from the 'lang' and 'name' keys in "
<del> "the meta.json. Vector names are required to avoid issue #1660.")
<ide> E093 = ("token.ent_iob values make invalid sequence: I without B\n{seq}")
<ide> E094 = ("Error reading line {line_num} in vectors file {loc}.")
<ide> E095 = ("Can't write to frozen dictionary. This is likely an internal " | 1 |
Text | Text | fix spelling of contributors | dd7c2b77a32a0b8bc86262989f6ee0d1e94eed4e | <ide><path>COLLABORATOR_GUIDE.md
<ide>
<ide> * [Issues and Pull Requests](#issues-and-pull-requests)
<ide> - [Managing Issues and Pull Requests](#managing-issues-and-pull-requests)
<del> - [Welcoming First-Time Contributiors](#welcoming-first-time-contributiors)
<add> - [Welcoming First-Time Contributors](#welcoming-first-time-contributors)
<ide> - [Closing Issues and Pull Requests](#closing-issues-and-pull-requests)
<ide> * [Accepting Modifications](#accepting-modifications)
<ide> - [Code Reviews and Consensus Seeking](#code-reviews-and-consensus-seeking)
<ide> may also notify other qualified parties for more input on an issue
<ide> or a pull request.
<ide> [See "Who to CC in issues"](./doc/onboarding-extras.md#who-to-cc-in-issues)
<ide>
<del>### Welcoming First-Time Contributiors
<add>### Welcoming First-Time Contributors
<ide>
<ide> Courtesy should always be shown to individuals submitting issues and pull
<ide> requests to the Node.js project. Be welcoming to first-time contributors, | 1 |
PHP | PHP | use the compiled config path | 16f1e53a47f3edc3d7cc1c73fe1dd0e7622a4a56 | <ide><path>src/Illuminate/View/ViewServiceProvider.php
<ide> public function registerBladeEngine($resolver)
<ide> // instance to pass into the engine so it can compile the views properly.
<ide> $app->bindShared('blade.compiler', function($app)
<ide> {
<del> $cache = $app['path.storage'].'/views';
<add> $cache = $app['config']['view.compiled'];
<ide>
<ide> return new BladeCompiler($app['files'], $cache);
<ide> }); | 1 |
Python | Python | fix missing return statement | ee795bff201648453bf53de2c72caf8b9a2a50db | <ide><path>libcloud/compute/drivers/ec2.py
<ide> def _get_billing_product_params(self, billing_products):
<ide> idx += 1 # We want 1-based indexes
<ide> params['BillingProduct.%d' % (idx)] = str(v)
<ide>
<add> return params
<add>
<ide> def _get_disk_container_params(self, disk_container):
<ide> """
<ide> Return a list of dictionaries with query parameters for | 1 |
Java | Java | add dematerialize(selector), deprecate old | acd5466c4440961da905d0c1c0e78752bda155ef | <ide><path>src/main/java/io/reactivex/Flowable.java
<ide> import io.reactivex.internal.fuseable.*;
<ide> import io.reactivex.internal.operators.flowable.*;
<ide> import io.reactivex.internal.operators.mixed.*;
<del>import io.reactivex.internal.operators.observable.ObservableFromPublisher;
<add>import io.reactivex.internal.operators.observable.*;
<ide> import io.reactivex.internal.schedulers.ImmediateThinScheduler;
<ide> import io.reactivex.internal.subscribers.*;
<ide> import io.reactivex.internal.util.*;
<ide> public final Flowable<T> delaySubscription(long delay, TimeUnit unit, Scheduler
<ide> * <pre><code>
<ide> * Flowable.just(createOnNext(1), createOnComplete(), createOnNext(2))
<ide> * .doOnCancel(() -> System.out.println("Cancelled!"));
<add> * .dematerialize()
<ide> * .test()
<ide> * .assertResult(1);
<ide> * </code></pre>
<ide> * If the upstream signals {@code onError} or {@code onComplete} directly, the flow is terminated
<ide> * with the same event.
<ide> * <pre><code>
<ide> * Flowable.just(createOnNext(1), createOnNext(2))
<add> * .dematerialize()
<ide> * .test()
<ide> * .assertResult(1, 2);
<ide> * </code></pre>
<ide> public final Flowable<T> delaySubscription(long delay, TimeUnit unit, Scheduler
<ide> * @return a Flowable that emits the items and notifications embedded in the {@link Notification} objects
<ide> * emitted by the source Publisher
<ide> * @see <a href="http://reactivex.io/documentation/operators/materialize-dematerialize.html">ReactiveX operators documentation: Dematerialize</a>
<add> * @see #dematerialize(Function)
<add> * @deprecated in 2.2.4; inherently type-unsafe as it overrides the output generic type. Use {@link #dematerialize(Function)} instead.
<ide> */
<ide> @CheckReturnValue
<del> @BackpressureSupport(BackpressureKind.FULL)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<add> @BackpressureSupport(BackpressureKind.PASS_THROUGH)
<add> @Deprecated
<add> @SuppressWarnings({ "unchecked", "rawtypes" })
<ide> public final <T2> Flowable<T2> dematerialize() {
<del> @SuppressWarnings("unchecked")
<del> Flowable<Notification<T2>> m = (Flowable<Notification<T2>>)this;
<del> return RxJavaPlugins.onAssembly(new FlowableDematerialize<T2>(m));
<add> return RxJavaPlugins.onAssembly(new FlowableDematerialize(this, Functions.identity()));
<add> }
<add>
<add> /**
<add> * Returns a Flowable that reverses the effect of {@link #materialize materialize} by transforming the
<add> * {@link Notification} objects extracted from the source items via a selector function
<add> * into their respective {@code Subscriber} signal types.
<add> * <p>
<add> * <img width="640" height="335" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/dematerialize.png" alt="">
<add> * <p>
<add> * The intended use of the {@code selector} function is to perform a
<add> * type-safe identity mapping (see example) on a source that is already of type
<add> * {@code Notification<T>}. The Java language doesn't allow
<add> * limiting instance methods to a certain generic argument shape, therefore,
<add> * a function is used to ensure the conversion remains type safe.
<add> * <p>
<add> * When the upstream signals an {@link Notification#createOnError(Throwable) onError} or
<add> * {@link Notification#createOnComplete() onComplete} item, the
<add> * returned Flowable cancels of the flow and terminates with that type of terminal event:
<add> * <pre><code>
<add> * Flowable.just(createOnNext(1), createOnComplete(), createOnNext(2))
<add> * .doOnCancel(() -> System.out.println("Canceled!"));
<add> * .dematerialize(notification -> notification)
<add> * .test()
<add> * .assertResult(1);
<add> * </code></pre>
<add> * If the upstream signals {@code onError} or {@code onComplete} directly, the flow is terminated
<add> * with the same event.
<add> * <pre><code>
<add> * Flowable.just(createOnNext(1), createOnNext(2))
<add> * .dematerialize(notification -> notification)
<add> * .test()
<add> * .assertResult(1, 2);
<add> * </code></pre>
<add> * If this behavior is not desired, the completion can be suppressed by applying {@link #concatWith(Publisher)}
<add> * with a {@link #never()} source.
<add> * <dl>
<add> * <dt><b>Backpressure:</b></dt>
<add> * <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s
<add> * backpressure behavior.</dd>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code dematerialize} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param <R> the output value type
<add> * @param selector function that returns the upstream item and should return a Notification to signal
<add> * the corresponding {@code Subscriber} event to the downstream.
<add> * @return a Flowable that emits the items and notifications embedded in the {@link Notification} objects
<add> * selected from the items emitted by the source Flowable
<add> * @see <a href="http://reactivex.io/documentation/operators/materialize-dematerialize.html">ReactiveX operators documentation: Dematerialize</a>
<add> * @since 2.2.4 - experimental
<add> */
<add> @Experimental
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @BackpressureSupport(BackpressureKind.PASS_THROUGH)
<add> public final <R> Flowable<R> dematerialize(Function<? super T, Notification<R>> selector) {
<add> ObjectHelper.requireNonNull(selector, "selector is null");
<add> return RxJavaPlugins.onAssembly(new FlowableDematerialize<T, R>(this, selector));
<ide> }
<ide>
<ide> /**
<ide> public final <R> Flowable<R> map(Function<? super T, ? extends R> mapper) {
<ide> * @return a Flowable that emits items that are the result of materializing the items and notifications
<ide> * of the source Publisher
<ide> * @see <a href="http://reactivex.io/documentation/operators/materialize-dematerialize.html">ReactiveX operators documentation: Materialize</a>
<add> * @see #dematerialize(Function)
<ide> */
<ide> @CheckReturnValue
<ide> @BackpressureSupport(BackpressureKind.FULL)
<ide><path>src/main/java/io/reactivex/Observable.java
<ide> public final Observable<T> delaySubscription(long delay, TimeUnit unit, Schedule
<ide> * <pre><code>
<ide> * Observable.just(createOnNext(1), createOnComplete(), createOnNext(2))
<ide> * .doOnDispose(() -> System.out.println("Disposed!"));
<add> * .dematerialize()
<ide> * .test()
<ide> * .assertResult(1);
<ide> * </code></pre>
<ide> * If the upstream signals {@code onError} or {@code onComplete} directly, the flow is terminated
<ide> * with the same event.
<ide> * <pre><code>
<ide> * Observable.just(createOnNext(1), createOnNext(2))
<add> * .dematerialize()
<ide> * .test()
<ide> * .assertResult(1, 2);
<ide> * </code></pre>
<ide> public final Observable<T> delaySubscription(long delay, TimeUnit unit, Schedule
<ide> * @return an Observable that emits the items and notifications embedded in the {@link Notification} objects
<ide> * emitted by the source ObservableSource
<ide> * @see <a href="http://reactivex.io/documentation/operators/materialize-dematerialize.html">ReactiveX operators documentation: Dematerialize</a>
<add> * @see #dematerialize(Function)
<add> * @deprecated in 2.2.4; inherently type-unsafe as it overrides the output generic type. Use {@link #dematerialize(Function)} instead.
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Deprecated
<add> @SuppressWarnings({ "unchecked", "rawtypes" })
<ide> public final <T2> Observable<T2> dematerialize() {
<del> @SuppressWarnings("unchecked")
<del> Observable<Notification<T2>> m = (Observable<Notification<T2>>)this;
<del> return RxJavaPlugins.onAssembly(new ObservableDematerialize<T2>(m));
<add> return RxJavaPlugins.onAssembly(new ObservableDematerialize(this, Functions.identity()));
<add> }
<add>
<add> /**
<add> * Returns an Observable that reverses the effect of {@link #materialize materialize} by transforming the
<add> * {@link Notification} objects extracted from the source items via a selector function
<add> * into their respective {@code Observer} signal types.
<add> * <p>
<add> * <img width="640" height="335" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/dematerialize.png" alt="">
<add> * <p>
<add> * The intended use of the {@code selector} function is to perform a
<add> * type-safe identity mapping (see example) on a source that is already of type
<add> * {@code Notification<T>}. The Java language doesn't allow
<add> * limiting instance methods to a certain generic argument shape, therefore,
<add> * a function is used to ensure the conversion remains type safe.
<add> * <p>
<add> * When the upstream signals an {@link Notification#createOnError(Throwable) onError} or
<add> * {@link Notification#createOnComplete() onComplete} item, the
<add> * returned Observable disposes of the flow and terminates with that type of terminal event:
<add> * <pre><code>
<add> * Observable.just(createOnNext(1), createOnComplete(), createOnNext(2))
<add> * .doOnDispose(() -> System.out.println("Disposed!"));
<add> * .dematerialize(notification -> notification)
<add> * .test()
<add> * .assertResult(1);
<add> * </code></pre>
<add> * If the upstream signals {@code onError} or {@code onComplete} directly, the flow is terminated
<add> * with the same event.
<add> * <pre><code>
<add> * Observable.just(createOnNext(1), createOnNext(2))
<add> * .dematerialize(notification -> notification)
<add> * .test()
<add> * .assertResult(1, 2);
<add> * </code></pre>
<add> * If this behavior is not desired, the completion can be suppressed by applying {@link #concatWith(ObservableSource)}
<add> * with a {@link #never()} source.
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code dematerialize} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param <R> the output value type
<add> * @param selector function that returns the upstream item and should return a Notification to signal
<add> * the corresponding {@code Observer} event to the downstream.
<add> * @return an Observable that emits the items and notifications embedded in the {@link Notification} objects
<add> * selected from the items emitted by the source ObservableSource
<add> * @see <a href="http://reactivex.io/documentation/operators/materialize-dematerialize.html">ReactiveX operators documentation: Dematerialize</a>
<add> * @since 2.2.4 - experimental
<add> */
<add> @Experimental
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public final <R> Observable<R> dematerialize(Function<? super T, Notification<R>> selector) {
<add> ObjectHelper.requireNonNull(selector, "selector is null");
<add> return RxJavaPlugins.onAssembly(new ObservableDematerialize<T, R>(this, selector));
<ide> }
<ide>
<ide> /**
<ide> public final <R> Observable<R> map(Function<? super T, ? extends R> mapper) {
<ide> * @return an Observable that emits items that are the result of materializing the items and notifications
<ide> * of the source ObservableSource
<ide> * @see <a href="http://reactivex.io/documentation/operators/materialize-dematerialize.html">ReactiveX operators documentation: Materialize</a>
<add> * @see #dematerialize(Function)
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableDematerialize.java
<ide> import org.reactivestreams.*;
<ide>
<ide> import io.reactivex.*;
<add>import io.reactivex.exceptions.Exceptions;
<add>import io.reactivex.functions.Function;
<add>import io.reactivex.internal.functions.ObjectHelper;
<ide> import io.reactivex.internal.subscriptions.SubscriptionHelper;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide>
<del>public final class FlowableDematerialize<T> extends AbstractFlowableWithUpstream<Notification<T>, T> {
<add>public final class FlowableDematerialize<T, R> extends AbstractFlowableWithUpstream<T, R> {
<ide>
<del> public FlowableDematerialize(Flowable<Notification<T>> source) {
<add> final Function<? super T, ? extends Notification<R>> selector;
<add>
<add> public FlowableDematerialize(Flowable<T> source, Function<? super T, ? extends Notification<R>> selector) {
<ide> super(source);
<add> this.selector = selector;
<ide> }
<ide>
<ide> @Override
<del> protected void subscribeActual(Subscriber<? super T> s) {
<del> source.subscribe(new DematerializeSubscriber<T>(s));
<add> protected void subscribeActual(Subscriber<? super R> subscriber) {
<add> source.subscribe(new DematerializeSubscriber<T, R>(subscriber, selector));
<ide> }
<ide>
<del> static final class DematerializeSubscriber<T> implements FlowableSubscriber<Notification<T>>, Subscription {
<del> final Subscriber<? super T> downstream;
<add> static final class DematerializeSubscriber<T, R> implements FlowableSubscriber<T>, Subscription {
<add>
<add> final Subscriber<? super R> downstream;
<add>
<add> final Function<? super T, ? extends Notification<R>> selector;
<ide>
<ide> boolean done;
<ide>
<ide> Subscription upstream;
<ide>
<del> DematerializeSubscriber(Subscriber<? super T> downstream) {
<add> DematerializeSubscriber(Subscriber<? super R> downstream, Function<? super T, ? extends Notification<R>> selector) {
<ide> this.downstream = downstream;
<add> this.selector = selector;
<ide> }
<ide>
<ide> @Override
<ide> public void onSubscribe(Subscription s) {
<ide> }
<ide>
<ide> @Override
<del> public void onNext(Notification<T> t) {
<add> public void onNext(T item) {
<ide> if (done) {
<del> if (t.isOnError()) {
<del> RxJavaPlugins.onError(t.getError());
<add> if (item instanceof Notification) {
<add> Notification<?> notification = (Notification<?>)item;
<add> if (notification.isOnError()) {
<add> RxJavaPlugins.onError(notification.getError());
<add> }
<ide> }
<ide> return;
<ide> }
<del> if (t.isOnError()) {
<add>
<add> Notification<R> notification;
<add>
<add> try {
<add> notification = ObjectHelper.requireNonNull(selector.apply(item), "The selector returned a null Notification");
<add> } catch (Throwable ex) {
<add> Exceptions.throwIfFatal(ex);
<ide> upstream.cancel();
<del> onError(t.getError());
<add> onError(ex);
<add> return;
<ide> }
<del> else if (t.isOnComplete()) {
<add> if (notification.isOnError()) {
<add> upstream.cancel();
<add> onError(notification.getError());
<add> } else if (notification.isOnComplete()) {
<ide> upstream.cancel();
<ide> onComplete();
<ide> } else {
<del> downstream.onNext(t.getValue());
<add> downstream.onNext(notification.getValue());
<ide> }
<ide> }
<ide>
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableDematerialize.java
<ide>
<ide> import io.reactivex.*;
<ide> import io.reactivex.disposables.Disposable;
<add>import io.reactivex.exceptions.Exceptions;
<add>import io.reactivex.functions.Function;
<ide> import io.reactivex.internal.disposables.DisposableHelper;
<add>import io.reactivex.internal.functions.ObjectHelper;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide>
<del>public final class ObservableDematerialize<T> extends AbstractObservableWithUpstream<Notification<T>, T> {
<add>public final class ObservableDematerialize<T, R> extends AbstractObservableWithUpstream<T, R> {
<ide>
<del> public ObservableDematerialize(ObservableSource<Notification<T>> source) {
<add> final Function<? super T, ? extends Notification<R>> selector;
<add>
<add> public ObservableDematerialize(ObservableSource<T> source, Function<? super T, ? extends Notification<R>> selector) {
<ide> super(source);
<add> this.selector = selector;
<ide> }
<ide>
<ide> @Override
<del> public void subscribeActual(Observer<? super T> t) {
<del> source.subscribe(new DematerializeObserver<T>(t));
<add> public void subscribeActual(Observer<? super R> observer) {
<add> source.subscribe(new DematerializeObserver<T, R>(observer, selector));
<ide> }
<ide>
<del> static final class DematerializeObserver<T> implements Observer<Notification<T>>, Disposable {
<del> final Observer<? super T> downstream;
<add> static final class DematerializeObserver<T, R> implements Observer<T>, Disposable {
<add> final Observer<? super R> downstream;
<add>
<add> final Function<? super T, ? extends Notification<R>> selector;
<ide>
<ide> boolean done;
<ide>
<ide> Disposable upstream;
<ide>
<del> DematerializeObserver(Observer<? super T> downstream) {
<add> DematerializeObserver(Observer<? super R> downstream, Function<? super T, ? extends Notification<R>> selector) {
<ide> this.downstream = downstream;
<add> this.selector = selector;
<ide> }
<ide>
<ide> @Override
<ide> public boolean isDisposed() {
<ide> }
<ide>
<ide> @Override
<del> public void onNext(Notification<T> t) {
<add> public void onNext(T item) {
<ide> if (done) {
<del> if (t.isOnError()) {
<del> RxJavaPlugins.onError(t.getError());
<add> if (item instanceof Notification) {
<add> Notification<?> notification = (Notification<?>)item;
<add> if (notification.isOnError()) {
<add> RxJavaPlugins.onError(notification.getError());
<add> }
<ide> }
<ide> return;
<ide> }
<del> if (t.isOnError()) {
<add>
<add> Notification<R> notification;
<add>
<add> try {
<add> notification = ObjectHelper.requireNonNull(selector.apply(item), "The selector returned a null Notification");
<add> } catch (Throwable ex) {
<add> Exceptions.throwIfFatal(ex);
<add> upstream.dispose();
<add> onError(ex);
<add> return;
<add> }
<add> if (notification.isOnError()) {
<ide> upstream.dispose();
<del> onError(t.getError());
<add> onError(notification.getError());
<ide> }
<del> else if (t.isOnComplete()) {
<add> else if (notification.isOnComplete()) {
<ide> upstream.dispose();
<ide> onComplete();
<ide> } else {
<del> downstream.onNext(t.getValue());
<add> downstream.onNext(notification.getValue());
<ide> }
<ide> }
<ide>
<ide><path>src/test/java/io/reactivex/flowable/FlowableTests.java
<ide> package io.reactivex.flowable;
<ide>
<ide> import static org.junit.Assert.*;
<add>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide> import java.util.concurrent.*;
<ide> import java.util.concurrent.atomic.*;
<ide>
<del>import io.reactivex.Observable;
<ide> import org.junit.*;
<ide> import org.mockito.InOrder;
<ide> import org.reactivestreams.*;
<ide>
<ide> import io.reactivex.*;
<add>import io.reactivex.Observable;
<ide> import io.reactivex.disposables.Disposable;
<ide> import io.reactivex.exceptions.*;
<ide> import io.reactivex.flowables.ConnectableFlowable;
<ide> import io.reactivex.functions.*;
<add>import io.reactivex.internal.functions.Functions;
<ide> import io.reactivex.internal.subscriptions.BooleanSubscription;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide> import io.reactivex.processors.*;
<ide> public void testOnSubscribeFails() {
<ide> @Test
<ide> public void testMaterializeDematerializeChaining() {
<ide> Flowable<Integer> obs = Flowable.just(1);
<del> Flowable<Integer> chained = obs.materialize().dematerialize();
<add> Flowable<Integer> chained = obs.materialize()
<add> .dematerialize(Functions.<Notification<Integer>>identity());
<ide>
<ide> Subscriber<Integer> subscriber = TestHelper.mockSubscriber();
<ide>
<ide> public void testErrorThrownIssue1685() {
<ide> Flowable.error(new RuntimeException("oops"))
<ide> .materialize()
<ide> .delay(1, TimeUnit.SECONDS)
<del> .dematerialize()
<add> .dematerialize(Functions.<Notification<Object>>identity())
<ide> .subscribe(processor);
<ide>
<ide> processor.subscribe();
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableDematerializeTest.java
<ide> import io.reactivex.*;
<ide> import io.reactivex.exceptions.TestException;
<ide> import io.reactivex.functions.Function;
<add>import io.reactivex.internal.functions.Functions;
<ide> import io.reactivex.internal.subscriptions.BooleanSubscription;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide> import io.reactivex.subscribers.TestSubscriber;
<ide>
<add>@SuppressWarnings("deprecation")
<ide> public class FlowableDematerializeTest {
<ide>
<add> @Test
<add> public void simpleSelector() {
<add> Flowable<Notification<Integer>> notifications = Flowable.just(1, 2).materialize();
<add> Flowable<Integer> dematerialize = notifications.dematerialize(Functions.<Notification<Integer>>identity());
<add>
<add> Subscriber<Integer> subscriber = TestHelper.mockSubscriber();
<add>
<add> dematerialize.subscribe(subscriber);
<add>
<add> verify(subscriber, times(1)).onNext(1);
<add> verify(subscriber, times(1)).onNext(2);
<add> verify(subscriber, times(1)).onComplete();
<add> verify(subscriber, never()).onError(any(Throwable.class));
<add> }
<add>
<add> @Test
<add> public void selectorCrash() {
<add> Flowable.just(1, 2)
<add> .materialize()
<add> .dematerialize(new Function<Notification<Integer>, Notification<Object>>() {
<add> @Override
<add> public Notification<Object> apply(Notification<Integer> v) throws Exception {
<add> throw new TestException();
<add> }
<add> })
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void selectorNull() {
<add> Flowable.just(1, 2)
<add> .materialize()
<add> .dematerialize(new Function<Notification<Integer>, Notification<Object>>() {
<add> @Override
<add> public Notification<Object> apply(Notification<Integer> v) throws Exception {
<add> return null;
<add> }
<add> })
<add> .test()
<add> .assertFailure(NullPointerException.class);
<add> }
<add>
<ide> @Test
<ide> public void testDematerialize1() {
<ide> Flowable<Notification<Integer>> notifications = Flowable.just(1, 2).materialize();
<ide> protected void subscribeActual(Subscriber<? super Object> subscriber) {
<ide> RxJavaPlugins.reset();
<ide> }
<ide> }
<add>
<add> @Test
<add> public void nonNotificationInstanceAfterDispose() {
<add> new Flowable<Object>() {
<add> @Override
<add> protected void subscribeActual(Subscriber<? super Object> subscriber) {
<add> subscriber.onSubscribe(new BooleanSubscription());
<add> subscriber.onNext(Notification.createOnComplete());
<add> subscriber.onNext(1);
<add> }
<add> }
<add> .dematerialize()
<add> .test()
<add> .assertResult();
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableDematerializeTest.java
<ide> import io.reactivex.disposables.Disposables;
<ide> import io.reactivex.exceptions.TestException;
<ide> import io.reactivex.functions.Function;
<add>import io.reactivex.internal.functions.Functions;
<ide> import io.reactivex.observers.TestObserver;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide>
<add>@SuppressWarnings("deprecation")
<ide> public class ObservableDematerializeTest {
<ide>
<add> @Test
<add> public void simpleSelector() {
<add> Observable<Notification<Integer>> notifications = Observable.just(1, 2).materialize();
<add> Observable<Integer> dematerialize = notifications.dematerialize(Functions.<Notification<Integer>>identity());
<add>
<add> Observer<Integer> observer = TestHelper.mockObserver();
<add>
<add> dematerialize.subscribe(observer);
<add>
<add> verify(observer, times(1)).onNext(1);
<add> verify(observer, times(1)).onNext(2);
<add> verify(observer, times(1)).onComplete();
<add> verify(observer, never()).onError(any(Throwable.class));
<add> }
<add>
<add> @Test
<add> public void selectorCrash() {
<add> Observable.just(1, 2)
<add> .materialize()
<add> .dematerialize(new Function<Notification<Integer>, Notification<Object>>() {
<add> @Override
<add> public Notification<Object> apply(Notification<Integer> v) throws Exception {
<add> throw new TestException();
<add> }
<add> })
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void selectorNull() {
<add> Observable.just(1, 2)
<add> .materialize()
<add> .dematerialize(new Function<Notification<Integer>, Notification<Object>>() {
<add> @Override
<add> public Notification<Object> apply(Notification<Integer> v) throws Exception {
<add> return null;
<add> }
<add> })
<add> .test()
<add> .assertFailure(NullPointerException.class);
<add> }
<add>
<ide> @Test
<ide> public void testDematerialize1() {
<ide> Observable<Notification<Integer>> notifications = Observable.just(1, 2).materialize();
<ide> protected void subscribeActual(Observer<? super Object> observer) {
<ide> RxJavaPlugins.reset();
<ide> }
<ide> }
<add>
<add> @Test
<add> public void nonNotificationInstanceAfterDispose() {
<add> new Observable<Object>() {
<add> @Override
<add> protected void subscribeActual(Observer<? super Object> observer) {
<add> observer.onSubscribe(Disposables.empty());
<add> observer.onNext(Notification.createOnComplete());
<add> observer.onNext(1);
<add> }
<add> }
<add> .dematerialize()
<add> .test()
<add> .assertResult();
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/observable/ObservableTest.java
<ide> package io.reactivex.observable;
<ide>
<ide> import static org.junit.Assert.*;
<add>import static org.mockito.ArgumentMatchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide> import io.reactivex.Observer;
<ide> import io.reactivex.disposables.*;
<ide> import io.reactivex.functions.*;
<add>import io.reactivex.internal.functions.Functions;
<ide> import io.reactivex.observables.ConnectableObservable;
<ide> import io.reactivex.observers.*;
<ide> import io.reactivex.schedulers.*;
<ide> public void testOnSubscribeFails() {
<ide> @Test
<ide> public void testMaterializeDematerializeChaining() {
<ide> Observable<Integer> obs = Observable.just(1);
<del> Observable<Integer> chained = obs.materialize().dematerialize();
<add> Observable<Integer> chained = obs.materialize()
<add> .dematerialize(Functions.<Notification<Integer>>identity());
<ide>
<ide> Observer<Integer> observer = TestHelper.mockObserver();
<ide>
<ide> public void testErrorThrownIssue1685() {
<ide> Observable.error(new RuntimeException("oops"))
<ide> .materialize()
<ide> .delay(1, TimeUnit.SECONDS)
<del> .dematerialize()
<add> .dematerialize(Functions.<Notification<Object>>identity())
<ide> .subscribe(subject);
<ide>
<ide> subject.subscribe(); | 8 |
Javascript | Javascript | add test for transition.selectall and nodelists | 68f555bfc23f4bd9c07f008eb8bd3c9c6784459a | <ide><path>test/core/transition-test-selectAll.js
<ide> module.exports = {
<ide> t1 = transition.selectAll("span");
<ide> assert.equal(t0.id, id);
<ide> assert.equal(t1.id, id);
<add> },
<add> "groups are not instances of NodeList": function(transition) {
<add> var t = transition.selectAll(function() { return this.getElementsByClassName("span"); });
<add> assert.isFalse(t[0] instanceof window.NodeList);
<ide> }
<ide> }; | 1 |
Java | Java | reduce api surface in pathpatternregistry | 8d43f45515d0261e6e0255a12c282a503902a97a | <ide><path>spring-web/src/main/java/org/springframework/web/cors/reactive/UrlBasedCorsConfigurationSource.java
<ide>
<ide> import java.util.Collections;
<ide> import java.util.LinkedHashMap;
<add>import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.SortedSet;
<ide>
<ide> public void setHttpRequestPathHelper(HttpRequestPathHelper pathHelper) {
<ide> /**
<ide> * Set CORS configuration based on URL patterns.
<ide> */
<del> public void setCorsConfigurations(Map<PathPattern, CorsConfiguration> corsConfigurations) {
<add> public void setCorsConfigurations(Map<String, CorsConfiguration> corsConfigurations) {
<ide> this.patternRegistry.clear();
<ide> this.corsConfigurations.clear();
<ide> if (corsConfigurations != null) {
<del> this.patternRegistry.addAll(corsConfigurations.keySet());
<del> this.corsConfigurations.putAll(corsConfigurations);
<add> corsConfigurations.forEach((pattern, config) -> {
<add> List<PathPattern> registered = this.patternRegistry.register(pattern);
<add> registered.forEach(p -> this.corsConfigurations.put(p, config));
<add> });
<ide> }
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/util/patterns/PathPatternRegistry.java
<ide> package org.springframework.web.util.patterns;
<ide>
<ide> import java.util.ArrayList;
<del>import java.util.Collection;
<ide> import java.util.Collections;
<ide> import java.util.Comparator;
<ide> import java.util.HashSet;
<ide> public PathPatternRegistry() {
<ide> this.patterns = new HashSet<>();
<ide> }
<ide>
<add> public PathPatternRegistry(Set<PathPattern> patterns) {
<add> this();
<add> this.patterns.addAll(patterns);
<add> }
<add>
<ide> /**
<ide> * Whether to match to paths irrespective of the presence of a trailing slash.
<ide> */
<ide> public PathPattern parsePattern(String pathPattern) {
<ide> return this.pathPatternParser.parse(pathPattern);
<ide> }
<ide>
<del> /**
<del> * Add a {@link PathPattern} instance to this registry
<del> * @return true if this registry did not already contain the specified {@code PathPattern}
<del> */
<del> public boolean add(PathPattern pathPattern) {
<del> return this.patterns.add(pathPattern);
<del> }
<del>
<del> /**
<del> * Add all {@link PathPattern}s instance to this registry
<del> * @return true if this registry did not already contain at least one of the given {@code PathPattern}s
<del> */
<del> public boolean addAll(Collection<PathPattern> pathPatterns) {
<del> return this.patterns.addAll(pathPatterns);
<del> }
<del>
<del> /**
<del> * Remove the given {@link PathPattern} from this registry
<del> * @return true if this registry contained the given {@code PathPattern}
<del> */
<del> public boolean remove(PathPattern pathPattern) {
<del> return this.patterns.remove(pathPattern);
<del> }
<del>
<ide> /**
<ide> * Remove all {@link PathPattern}s from this registry
<ide> */
<ide> public void clear() {
<ide> * @return the list of {@link PathPattern} that were registered as a result
<ide> */
<ide> public List<PathPattern> register(String rawPattern) {
<add> List<PathPattern> newPatterns = generatePathPatterns(rawPattern);
<add> this.patterns.addAll(newPatterns);
<add> return newPatterns;
<add> }
<add>
<add> private String prependLeadingSlash(String pattern) {
<add> if (StringUtils.hasLength(pattern) && !pattern.startsWith("/")) {
<add> return "/" + pattern;
<add> }
<add> else {
<add> return pattern;
<add> }
<add> }
<add>
<add> private List<PathPattern> generatePathPatterns(String rawPattern) {
<ide> String fixedPattern = prependLeadingSlash(rawPattern);
<del> List<PathPattern> newPatterns = new ArrayList<>();
<add> List<PathPattern> patterns = new ArrayList<>();
<ide> PathPattern pattern = this.pathPatternParser.parse(fixedPattern);
<del> newPatterns.add(pattern);
<add> patterns.add(pattern);
<ide> if (StringUtils.hasLength(fixedPattern) && !pattern.isCatchAll()) {
<ide> if (this.useSuffixPatternMatch) {
<ide> if (this.fileExtensions != null && !this.fileExtensions.isEmpty()) {
<ide> for (String extension : this.fileExtensions) {
<del> newPatterns.add(this.pathPatternParser.parse(fixedPattern + extension));
<add> patterns.add(this.pathPatternParser.parse(fixedPattern + extension));
<ide> }
<ide> }
<ide> else {
<del> newPatterns.add(this.pathPatternParser.parse(fixedPattern + ".*"));
<add> patterns.add(this.pathPatternParser.parse(fixedPattern + ".*"));
<ide> }
<ide> }
<ide> if (this.useTrailingSlashMatch && !fixedPattern.endsWith("/")) {
<del> newPatterns.add(this.pathPatternParser.parse(fixedPattern + "/"));
<add> patterns.add(this.pathPatternParser.parse(fixedPattern + "/"));
<ide> }
<ide> }
<del> this.patterns.addAll(newPatterns);
<del> return newPatterns;
<add> return patterns;
<ide> }
<ide>
<del> private String prependLeadingSlash(String pattern) {
<del> if (StringUtils.hasLength(pattern) && !pattern.startsWith("/")) {
<del> return "/" + pattern;
<del> }
<del> else {
<del> return pattern;
<del> }
<add> /**
<add> * Parse the given {@code rawPattern} and removes it to this registry,
<add> * as well as pattern variants, depending on the given options and
<add> * the nature of the input pattern.
<add> *
<add> * @param rawPattern raw path pattern to parse and unregister
<add> * @return the list of {@link PathPattern} that were unregistered as a result
<add> */
<add> public List<PathPattern> unregister(String rawPattern) {
<add> List<PathPattern> unregisteredPatterns = generatePathPatterns(rawPattern);
<add> this.patterns.removeAll(unregisteredPatterns);
<add> return unregisteredPatterns;
<ide> }
<ide>
<add>
<ide> /**
<ide> * Combine the patterns contained in the current registry
<ide> * with the ones in the other, into a new {@code PathPatternRegistry} instance.
<ide><path>spring-web/src/test/java/org/springframework/web/util/patterns/PathPatternRegistryTests.java
<ide> public void registerPatternsWithSameSpecificity() {
<ide> PathPattern fooTwo = this.registry.parsePattern("/f?o");
<ide> assertThat(fooOne.compareTo(fooTwo), is(0));
<ide>
<del> this.registry.add(fooOne);
<del> this.registry.add(fooTwo);
<add> this.registry.register("/fo?");
<add> this.registry.register("/f?o");
<ide> Set<PathPattern> matches = this.registry.findMatches("/foo");
<ide> assertThat(getPatternList(matches), Matchers.contains("/f?o", "/fo?"));
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/resource/ResourceUrlProvider.java
<ide> public HttpRequestPathHelper getUrlPathHelper() {
<ide> * from the Spring {@code ApplicationContext}. However if this property is
<ide> * used, the auto-detection is turned off.
<ide> */
<del> public void setHandlerMap(Map<PathPattern, ResourceWebHandler> handlerMap) {
<add> public void setHandlerMap(Map<String, ResourceWebHandler> handlerMap) {
<ide> if (handlerMap != null) {
<ide> this.patternRegistry.clear();
<del> this.patternRegistry.addAll(handlerMap.keySet());
<ide> this.handlerMap.clear();
<del> this.handlerMap.putAll(handlerMap);
<add>
<add> handlerMap.forEach((pattern, handler) -> {
<add> this.patternRegistry
<add> .register(pattern)
<add> .forEach(pathPattern -> this.handlerMap.put(pathPattern, handler));
<add> });
<ide> this.autodetect = false;
<ide> }
<ide> }
<ide> protected void detectResourceHandlers(ApplicationContext appContext) {
<ide> "locations=" + resourceHandler.getLocations() + ", " +
<ide> "resolvers=" + resourceHandler.getResourceResolvers());
<ide> }
<del> this.patternRegistry.add(pattern);
<add> this.patternRegistry.register(pattern.getPatternString());
<ide> this.handlerMap.put(pattern, resourceHandler);
<ide> }
<ide> }
<ide> private int getLookupPathIndex(ServerWebExchange exchange) {
<ide> private int getEndPathIndex(String lookupPath) {
<ide> int suffixIndex = lookupPath.length();
<ide> int queryIndex = lookupPath.indexOf("?");
<del> if(queryIndex > 0) {
<add> if (queryIndex > 0) {
<ide> suffixIndex = queryIndex;
<ide> }
<ide> int hashIndex = lookupPath.indexOf("#");
<del> if(hashIndex > 0) {
<add> if (hashIndex > 0) {
<ide> suffixIndex = Math.min(suffixIndex, hashIndex);
<ide> }
<ide> return suffixIndex;
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/PatternsRequestCondition.java
<ide> public PatternsRequestCondition getMatchingCondition(ServerWebExchange exchange)
<ide> SortedSet<PathPattern> matches = getMatchingPatterns(lookupPath);
<ide>
<ide> if(!matches.isEmpty()) {
<del> PathPatternRegistry registry = new PathPatternRegistry();
<del> registry.addAll(matches);
<add> PathPatternRegistry registry = new PathPatternRegistry(matches);
<ide> return new PatternsRequestCondition(registry, this.pathHelper);
<ide> }
<ide> return null;
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/AbstractHandlerMethodMapping.java
<ide> private final MultiValueMap<PathPattern, T> mappingLookup = new LinkedMultiValueMap<>();
<ide>
<ide> private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
<del>
<add>
<ide> private final MappingRegistry mappingRegistry = new MappingRegistry();
<ide>
<ide>
<ide> MappingRegistry getMappingRegistry() {
<ide> public void registerMapping(T mapping, Object handler, Method method) {
<ide> this.readWriteLock.writeLock().lock();
<ide> try {
<del> Set<PathPattern> patterns = getMappingPathPatterns(mapping);
<del> getPatternRegistry().addAll(patterns);
<del> patterns.forEach(pathPattern -> {
<del> this.mappingLookup.add(pathPattern, mapping);
<add> getMappingPathPatterns(mapping).forEach(pattern -> {
<add> getPatternRegistry().register(pattern).forEach(
<add> pathPattern -> this.mappingLookup.add(pathPattern, mapping)
<add> );
<ide> });
<ide> this.mappingRegistry.register(mapping, handler, method);
<ide> }
<ide> public void registerMapping(T mapping, Object handler, Method method) {
<ide> public void unregisterMapping(T mapping) {
<ide> this.readWriteLock.writeLock().lock();
<ide> try {
<del> getMappingPathPatterns(mapping)
<del> .forEach(pathPattern -> getPatternRegistry().remove(pathPattern));
<add> getMappingPathPatterns(mapping).forEach(pattern -> {
<add> getPatternRegistry().unregister(pattern).forEach(
<add> pathPattern -> this.mappingLookup.remove(pathPattern, mapping)
<add> );
<add> });
<ide> this.mappingRegistry.unregister(mapping);
<ide> }
<ide> finally {
<ide> protected CorsConfiguration getCorsConfiguration(Object handler, ServerWebExchan
<ide> /**
<ide> * Extract and return the URL paths contained in a mapping.
<ide> */
<del> protected abstract Set<PathPattern> getMappingPathPatterns(T mapping);
<add> protected abstract Set<String> getMappingPathPatterns(T mapping);
<ide>
<ide> /**
<ide> * Check if a mapping matches the current request and return a (potentially
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/RequestMappingInfoHandlerMapping.java
<ide> public abstract class RequestMappingInfoHandlerMapping extends AbstractHandlerMe
<ide> * Get the URL path patterns associated with this {@link RequestMappingInfo}.
<ide> */
<ide> @Override
<del> protected Set<PathPattern> getMappingPathPatterns(RequestMappingInfo info) {
<del> return info.getPatternsCondition().getPatterns();
<add> protected Set<String> getMappingPathPatterns(RequestMappingInfo info) {
<add> return info.getPatternsCondition().getPatterns().stream()
<add> .map(p -> p.getPatternString())
<add> .collect(Collectors.toSet());
<ide> }
<ide>
<ide> /**
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/resource/AppCacheManifestTransformerTests.java
<ide> import org.springframework.util.FileCopyUtils;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.server.adapter.DefaultServerWebExchange;
<del>import org.springframework.web.util.patterns.PathPatternParser;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<ide> import static org.junit.Assert.assertThat;
<ide> public void setup() {
<ide> ClassPathResource allowedLocation = new ClassPathResource("test/", getClass());
<ide> ResourceWebHandler resourceHandler = new ResourceWebHandler();
<ide> ResourceUrlProvider resourceUrlProvider = new ResourceUrlProvider();
<del> PathPatternParser parser = new PathPatternParser();
<del> resourceUrlProvider.setHandlerMap(Collections.singletonMap(parser.parse("/static/**"), resourceHandler));
<add> resourceUrlProvider.setHandlerMap(Collections.singletonMap("/static/**", resourceHandler));
<ide>
<ide> VersionResourceResolver versionResolver = new VersionResourceResolver();
<ide> versionResolver.setStrategyMap(Collections.singletonMap("/**", new ContentVersionStrategy()));
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/resource/CssLinkResourceTransformerTests.java
<ide> public void setUp() {
<ide> ResourceWebHandler resourceHandler = new ResourceWebHandler();
<ide>
<ide> ResourceUrlProvider resourceUrlProvider = new ResourceUrlProvider();
<del> PathPatternParser parser = new PathPatternParser();
<del> resourceUrlProvider.setHandlerMap(Collections.singletonMap(parser.parse("/static/**"), resourceHandler));
<add> resourceUrlProvider.setHandlerMap(Collections.singletonMap("/static/**", resourceHandler));
<ide>
<ide> VersionResourceResolver versionResolver = new VersionResourceResolver();
<ide> versionResolver.setStrategyMap(Collections.singletonMap("/**", new ContentVersionStrategy()));
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceTransformerSupportTests.java
<ide> import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.server.adapter.DefaultServerWebExchange;
<del>import org.springframework.web.util.patterns.PathPatternParser;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<ide>
<ide> private ResourceUrlProvider createResourceUrlProvider(List<ResourceResolver> res
<ide> handler.setLocations(Collections.singletonList(new ClassPathResource("test/", getClass())));
<ide> handler.setResourceResolvers(resolvers);
<ide> ResourceUrlProvider urlProvider = new ResourceUrlProvider();
<del> PathPatternParser parser = new PathPatternParser();
<del> urlProvider.setHandlerMap(Collections.singletonMap(parser.parse("/resources/**"), handler));
<add> urlProvider.setHandlerMap(Collections.singletonMap("/resources/**", handler));
<ide> return urlProvider;
<ide> }
<ide>
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceUrlProviderTests.java
<ide> import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.server.adapter.DefaultServerWebExchange;
<del>import org.springframework.web.server.session.DefaultWebSessionManager;
<del>import org.springframework.web.server.session.WebSessionManager;
<del>import org.springframework.web.util.patterns.PathPattern;
<ide> import org.springframework.web.util.patterns.PathPatternParser;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<ide> public class ResourceUrlProviderTests {
<ide>
<ide> private final ResourceWebHandler handler = new ResourceWebHandler();
<ide>
<del> private final Map<PathPattern, ResourceWebHandler> handlerMap = new HashMap<>();
<add> private final Map<String, ResourceWebHandler> handlerMap = new HashMap<>();
<ide>
<ide> private final ResourceUrlProvider urlProvider = new ResourceUrlProvider();
<ide>
<ide> public void setUp() throws Exception {
<ide> this.locations.add(new ClassPathResource("testalternatepath/", getClass()));
<ide> this.handler.setLocations(locations);
<ide> this.handler.afterPropertiesSet();
<del> PathPattern staticResources = new PathPatternParser().parse("/resources/**");
<del> this.handlerMap.put(staticResources, this.handler);
<add> this.handlerMap.put("/resources/**", this.handler);
<ide> this.urlProvider.setHandlerMap(this.handlerMap);
<ide> }
<ide>
<ide> public void bestPatternMatch() throws Exception {
<ide> resolvers.add(new PathResourceResolver());
<ide> otherHandler.setResourceResolvers(resolvers);
<ide>
<del> PathPattern staticResources = new PathPatternParser().parse("/resources/*.css");
<del> this.handlerMap.put(staticResources, otherHandler);
<add> this.handlerMap.put("/resources/*.css", otherHandler);
<ide> this.urlProvider.setHandlerMap(this.handlerMap);
<ide>
<ide> String url = this.urlProvider.getForLookupPath("/resources/foo.css").blockMillis(5000);
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/HandlerMethodMappingTests.java
<ide>
<ide> import java.lang.reflect.Method;
<ide> import java.net.URISyntaxException;
<add>import java.util.Collections;
<ide> import java.util.Comparator;
<add>import java.util.Set;
<ide> import java.util.SortedSet;
<ide> import java.util.TreeSet;
<ide>
<ide> import org.springframework.web.server.session.MockWebSessionManager;
<ide> import org.springframework.web.server.session.WebSessionManager;
<ide> import org.springframework.web.util.patterns.PathPattern;
<add>import org.springframework.web.util.patterns.PathPatternComparator;
<ide> import org.springframework.web.util.patterns.PathPatternParser;
<ide> import org.springframework.web.util.patterns.PatternComparatorConsideringPath;
<ide>
<ide> public class HandlerMethodMappingTests {
<ide>
<ide> private PathPatternParser patternParser = new PathPatternParser();
<ide>
<del> private AbstractHandlerMethodMapping<PathPattern> mapping;
<add> private AbstractHandlerMethodMapping<String> mapping;
<ide>
<ide> private MyHandler handler;
<ide>
<ide> public void setUp() throws Exception {
<ide>
<ide> @Test(expected = IllegalStateException.class)
<ide> public void registerDuplicates() {
<del> this.mapping.registerMapping(this.patternParser.parse("/foo"), this.handler, this.method1);
<del> this.mapping.registerMapping(this.patternParser.parse("/foo"), this.handler, this.method2);
<add> this.mapping.registerMapping("/foo", this.handler, this.method1);
<add> this.mapping.registerMapping("/foo", this.handler, this.method2);
<ide> }
<ide>
<ide> @Test
<ide> public void directMatch() throws Exception {
<del> String key = "foo";
<del> this.mapping.registerMapping(this.patternParser.parse(key), this.handler, this.method1);
<add> String key = "/foo";
<add> this.mapping.registerMapping(key, this.handler, this.method1);
<ide> Mono<Object> result = this.mapping.getHandler(createExchange(HttpMethod.GET, key));
<ide>
<ide> assertEquals(this.method1, ((HandlerMethod) result.block()).getMethod());
<ide> }
<ide>
<ide> @Test
<ide> public void patternMatch() throws Exception {
<del> this.mapping.registerMapping(this.patternParser.parse("/fo*"), this.handler, this.method1);
<del> this.mapping.registerMapping(this.patternParser.parse("/f*"), this.handler, this.method2);
<add> this.mapping.registerMapping("/fo*", this.handler, this.method1);
<add> this.mapping.registerMapping("/f*", this.handler, this.method2);
<ide>
<ide> Mono<Object> result = this.mapping.getHandler(createExchange(HttpMethod.GET, "/foo"));
<ide> assertEquals(this.method1, ((HandlerMethod) result.block()).getMethod());
<ide> }
<ide>
<ide> @Test
<ide> public void ambiguousMatch() throws Exception {
<del> this.mapping.registerMapping(this.patternParser.parse("/f?o"), this.handler, this.method1);
<del> this.mapping.registerMapping(this.patternParser.parse("/fo?"), this.handler, this.method2);
<add> this.mapping.registerMapping("/f?o", this.handler, this.method1);
<add> this.mapping.registerMapping("/fo?", this.handler, this.method2);
<ide> Mono<Object> result = this.mapping.getHandler(createExchange(HttpMethod.GET, "/foo"));
<ide>
<ide> StepVerifier.create(result).expectError(IllegalStateException.class).verify();
<ide> }
<ide>
<ide> @Test
<ide> public void registerMapping() throws Exception {
<del> PathPattern key1 = this.patternParser.parse("/foo");
<del> PathPattern key2 = this.patternParser.parse("/foo*");
<add> String key1 = "/foo";
<add> String key2 = "/foo*";
<ide> this.mapping.registerMapping(key1, this.handler, this.method1);
<ide> this.mapping.registerMapping(key2, this.handler, this.method2);
<ide>
<ide> public void registerMapping() throws Exception {
<ide>
<ide> @Test
<ide> public void registerMappingWithSameMethodAndTwoHandlerInstances() throws Exception {
<del> PathPattern key1 = this.patternParser.parse("/foo");
<del> PathPattern key2 = this.patternParser.parse("/bar");
<add> String key1 = "/foo";
<add> String key2 = "/bar";
<ide> MyHandler handler1 = new MyHandler();
<ide> MyHandler handler2 = new MyHandler();
<ide> this.mapping.registerMapping(key1, handler1, this.method1);
<ide> public void registerMappingWithSameMethodAndTwoHandlerInstances() throws Excepti
<ide>
<ide> @Test
<ide> public void unregisterMapping() throws Exception {
<del> String key = "foo";
<del> this.mapping.registerMapping(this.patternParser.parse(key), this.handler, this.method1);
<add> String key = "/foo";
<add> this.mapping.registerMapping(key, this.handler, this.method1);
<ide> Mono<Object> result = this.mapping.getHandler(createExchange(HttpMethod.GET, key));
<ide>
<ide> assertNotNull(result.block());
<ide>
<del> this.mapping.unregisterMapping(this.patternParser.parse(key));
<add> this.mapping.unregisterMapping(key);
<ide> result = this.mapping.getHandler(createExchange(HttpMethod.GET, key));
<ide>
<ide> assertNull(result.block());
<ide> private ServerWebExchange createExchange(HttpMethod httpMethod, String path) thr
<ide> }
<ide>
<ide>
<del> private static class MyHandlerMethodMapping extends AbstractHandlerMethodMapping<PathPattern> {
<add> private static class MyHandlerMethodMapping extends AbstractHandlerMethodMapping<String> {
<ide>
<ide> private PathPatternParser patternParser = new PathPatternParser();
<ide>
<ide> protected boolean isHandler(Class<?> beanType) {
<ide> }
<ide>
<ide> @Override
<del> protected PathPattern getMappingForMethod(Method method, Class<?> handlerType) {
<add> protected String getMappingForMethod(Method method, Class<?> handlerType) {
<ide> String methodName = method.getName();
<del> return methodName.startsWith("handler") ? this.patternParser.parse(methodName) : null;
<add> return methodName.startsWith("handler") ? methodName : null;
<ide> }
<ide>
<ide> @Override
<del> protected SortedSet<PathPattern> getMappingPathPatterns(PathPattern key) {
<del> TreeSet<PathPattern> patterns = new TreeSet<>();
<del> patterns.add(key);
<del> return patterns;
<add> protected Set<String> getMappingPathPatterns(String key) {
<add> return Collections.singleton(key);
<ide> }
<ide>
<ide> @Override
<del> protected PathPattern getMatchingMapping(PathPattern pattern, ServerWebExchange exchange) {
<add> protected String getMatchingMapping(String pattern, ServerWebExchange exchange) {
<ide> String lookupPath = exchange.getRequest().getURI().getPath();
<del> return (pattern.matches(lookupPath) ? pattern : null);
<add> PathPattern pathPattern = this.patternParser.parse(pattern);
<add> return (pathPattern.matches(lookupPath) ? pattern : null);
<ide> }
<ide>
<ide> @Override
<del> protected Comparator<PathPattern> getMappingComparator(ServerWebExchange exchange) {
<add> protected Comparator<String> getMappingComparator(ServerWebExchange exchange) {
<ide> String lookupPath = exchange.getRequest().getURI().getPath();
<del> return new PatternComparatorConsideringPath(lookupPath);
<add> PatternComparatorConsideringPath comparator = new PatternComparatorConsideringPath(lookupPath);
<add> return new Comparator<String>() {
<add> @Override
<add> public int compare(String o1, String o2) {
<add>
<add> return comparator.compare(patternParser.parse(o1), patternParser.parse(o2));
<add> }
<add> };
<ide> }
<ide>
<ide> }
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/RequestMappingInfoHandlerMappingTests.java
<ide> import java.util.Map;
<ide> import java.util.Optional;
<ide> import java.util.Set;
<del>import java.util.SortedSet;
<ide> import java.util.function.Consumer;
<del>import java.util.stream.Collectors;
<ide>
<ide> import org.hamcrest.Matchers;
<ide> import org.junit.Before;
<ide> public void setUp() throws Exception {
<ide> public void getMappingPathPatterns() throws Exception {
<ide> String[] patterns = {"/foo/*", "/foo", "/bar/*", "/bar"};
<ide> RequestMappingInfo info = paths(patterns).build();
<del> Set<PathPattern> actual = this.handlerMapping.getMappingPathPatterns(info);
<add> Set<String> actual = this.handlerMapping.getMappingPathPatterns(info);
<ide>
<del> assertThat(actual.stream().map(PathPattern::getPatternString).collect(Collectors.toList()),
<del> Matchers.containsInAnyOrder(new String[]{"/foo/*", "/foo", "/bar/*", "/bar",
<del> "/foo/*/", "/foo/", "/bar/*/", "/bar/"}));
<add> assertThat(actual, Matchers.containsInAnyOrder("/foo/*", "/foo", "/bar/*", "/bar",
<add> "/foo/*/", "/foo/", "/bar/*/", "/bar/"));
<ide> }
<ide>
<ide> @Test
<ide> public void getHandlerTestInvalidContentType() throws Exception {
<ide>
<ide> assertError(mono, UnsupportedMediaTypeStatusException.class,
<ide> ex -> assertEquals("Request failure [status: 415, " +
<del> "reason: \"Invalid mime type \"bogus\": does not contain '/'\"]",
<add> "reason: \"Invalid mime type \"bogus\": does not contain '/'\"]",
<ide> ex.getMessage()));
<ide> }
<ide>
<ide> public void getHandlerProducibleMediaTypesAttribute() throws Exception {
<ide> exchange.getAttributes().get(name));
<ide> }
<ide>
<del> @Test @SuppressWarnings("unchecked")
<add> @Test
<add> @SuppressWarnings("unchecked")
<ide> public void handleMatchUriTemplateVariables() throws Exception {
<ide> String lookupPath = "/1/2";
<ide> this.request = MockServerHttpRequest.get(lookupPath).build();
<ide> private ServerWebExchange createExchange() {
<ide> }
<ide>
<ide> @SuppressWarnings("unchecked")
<del> private <T> void assertError(Mono<Object> mono, final Class<T> exceptionClass, final Consumer<T> consumer) {
<add> private <T> void assertError(Mono<Object> mono, final Class<T> exceptionClass, final Consumer<T> consumer) {
<ide>
<ide> StepVerifier.create(mono)
<ide> .consumeErrorWith(error -> {
<ide> private static class TestController {
<ide> public void foo() {
<ide> }
<ide>
<del> @GetMapping(path = "/foo", params="p")
<add> @GetMapping(path = "/foo", params = "p")
<ide> public void fooParam() {
<ide> }
<ide>
<del> @RequestMapping(path = "/ba*", method = { GET, HEAD })
<add> @RequestMapping(path = "/ba*", method = {GET, HEAD})
<ide> public void bar() {
<ide> }
<ide>
<ide> @RequestMapping(path = "")
<ide> public void empty() {
<ide> }
<ide>
<del> @PutMapping(path = "/person/{id}", consumes="application/xml")
<add> @PutMapping(path = "/person/{id}", consumes = "application/xml")
<ide> public void consumes(@RequestBody String text) {
<ide> }
<ide>
<del> @RequestMapping(path = "/persons", produces="application/xml")
<add> @RequestMapping(path = "/persons", produces = "application/xml")
<ide> public String produces() {
<ide> return "";
<ide> }
<ide>
<del> @RequestMapping(path = "/params", params="foo=bar")
<add> @RequestMapping(path = "/params", params = "foo=bar")
<ide> public String param() {
<ide> return "";
<ide> }
<ide>
<del> @RequestMapping(path = "/params", params="bar=baz")
<add> @RequestMapping(path = "/params", params = "bar=baz")
<ide> public String param2() {
<ide> return "";
<ide> }
<ide>
<del> @RequestMapping(path = "/content", produces="application/xml")
<add> @RequestMapping(path = "/content", produces = "application/xml")
<ide> public String xmlContent() {
<ide> return "";
<ide> }
<ide>
<del> @RequestMapping(path = "/content", produces="!application/xml")
<add> @RequestMapping(path = "/content", produces = "!application/xml")
<ide> public String nonXmlContent() {
<ide> return "";
<ide> } | 13 |
Mixed | Ruby | allow spaces in postgres table names | 03fadebe0ed1fd384a14e46ba4c828b9a36ab4bf | <ide><path>activerecord/CHANGELOG.md
<add>* Allow spaces in postgres table names.
<add>
<add> Fixes issue where "user post" is misinterpreted as "\"user\".\"post\"" when quoting table names with the postgres adapter.
<add>
<add> *Gannon McGibbon*
<add>
<ide> * Cached columns_hash fields should be excluded from ResultSet#column_types
<ide>
<ide> PR #34528 addresses the inconsistent behaviour when attribute is defined for an ignored column. The following test
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/utils.rb
<ide> module Utils # :nodoc:
<ide> # * <tt>"schema_name".table_name</tt>
<ide> # * <tt>"schema.name"."table name"</tt>
<ide> def extract_schema_qualified_name(string)
<del> schema, table = string.scan(/[^".\s]+|"[^"]*"/)
<add> schema, table = string.scan(/[^".]+|"[^"]*"/)
<ide> if table.nil?
<ide> table = schema
<ide> schema = nil
<ide><path>activerecord/test/cases/adapters/postgresql/quoting_test.rb
<ide> def test_quote_bit_string
<ide> type = OID::Bit.new
<ide> assert_nil @conn.quote(type.serialize(value))
<ide> end
<add>
<add> def test_quote_table_name_with_spaces
<add> value = "user posts"
<add> assert_equal "\"user posts\"", @conn.quote_table_name(value)
<add> end
<ide> end
<ide> end
<ide> end | 3 |
PHP | PHP | work --daemon processing when app down | 6b0985dab4f39dc243e1894d1049ab1e4951409d | <ide><path>src/Illuminate/Queue/QueueManager.php
<ide> public function getName($connection = null)
<ide> return $connection ?: $this->getDefaultDriver();
<ide> }
<ide>
<add> /**
<add> * Determine if the worker should run in maintenance mode.
<add> *
<add> * @return bool
<add> */
<add> public function isDownForMaintenance()
<add> {
<add> return $this->app->isDownForMaintenance();
<add> }
<add>
<ide> /**
<ide> * Dynamically pass calls to the default connection.
<ide> *
<ide><path>src/Illuminate/Queue/Worker.php
<ide> protected function runNextJobForDaemon($connectionName, $queue, $delay, $sleep,
<ide> */
<ide> protected function daemonShouldRun()
<ide> {
<add> if ($this->manager->isDownForMaintenance())
<add> {
<add> return false;
<add> }
<add>
<ide> return $this->events->until('illuminate.queue.looping') !== false;
<ide> }
<ide> | 2 |
Text | Text | fix bug in data-fetching.md's example | 356e5caf0ee4d23498a3caab3d71eb2bbbf84e7a | <ide><path>docs/basic-features/data-fetching.md
<ide> import useSWR from 'swr'
<ide>
<ide> const API_URL = 'https://api.github.com'
<ide> async function fetcher(path) {
<del> const res = fetch(API_URL + path)
<add> const res = await fetch(API_URL + path)
<ide> const json = await res.json()
<ide> return json
<ide> } | 1 |
Text | Text | improve readability of collaborator_guide.md | 5b4a5c82567da30156452151bc4627a7fc79d81a | <ide><path>COLLABORATOR_GUIDE.md
<ide> can be fast-tracked and may be landed after a shorter delay:
<ide> * Changes that fix regressions.
<ide>
<ide> When a pull request is deemed suitable to be fast-tracked, label it with
<del>`fast-track`. The pull request can be landed once 2 or more collaborators
<add>`fast-track`. The pull request can be landed once 2 or more Collaborators
<ide> approve both the pull request and the fast-tracking request, and the necessary
<ide> CI testing is done.
<ide>
<ide> on how to handle those types of changes.
<ide> ### Breaking Changes
<ide>
<ide> Backwards-incompatible changes may land on the master branch at any time after
<del>sufficient review by collaborators and approval of at least two TSC members.
<del>
<del>Examples of breaking changes include, but are not necessarily limited to,
<del>removal or redefinition of existing API arguments, changing return values
<del>(except when return values do not currently exist), removing or modifying
<del>existing properties on an options argument, adding or removing errors,
<del>changing error messages in any way, altering expected timing of an event (e.g.
<del>moving from sync to async responses or vice versa), and changing the
<del>non-internal side effects of using a particular API.
<add>sufficient review by Collaborators and approval of at least two TSC members.
<add>
<add>Examples of breaking changes include:
<add>
<add>* removal or redefinition of existing API arguments
<add>* changing return values
<add>* removing or modifying existing properties on an options argument
<add>* adding or removing errors
<add>* altering expected timing of an event
<add>* changing the side effects of using a particular API
<ide>
<ide> Purely additive changes (e.g. adding new events to `EventEmitter`
<ide> implementations, adding new arguments to a method in a way that allows | 1 |
Javascript | Javascript | add a |textlayerrendered| event | 3f061cef86a5b9f92e9c5f73ee399397cbaba263 | <ide><path>web/text_layer_builder.js
<ide> var TextLayerBuilder = (function TextLayerBuilderClosure() {
<ide> this.renderingDone = false;
<ide> this.divContentDone = false;
<ide> this.pageIdx = options.pageIndex;
<add> this.pageNumber = this.pageIdx + 1;
<ide> this.matches = [];
<ide> this.viewport = options.viewport;
<ide> this.textDivs = [];
<ide> this.findController = options.findController || null;
<ide> }
<ide>
<ide> TextLayerBuilder.prototype = {
<add> _finishRendering: function TextLayerBuilder_finishRendering() {
<add> this.renderingDone = true;
<add>
<add> var event = document.createEvent('CustomEvent');
<add> event.initCustomEvent('textlayerrendered', true, true, {
<add> pageNumber: this.pageNumber
<add> });
<add> this.textLayerDiv.dispatchEvent(event);
<add> },
<add>
<ide> renderLayer: function TextLayerBuilder_renderLayer() {
<ide> var textLayerFrag = document.createDocumentFragment();
<ide> var textDivs = this.textDivs;
<ide> var TextLayerBuilder = (function TextLayerBuilderClosure() {
<ide> // No point in rendering many divs as it would make the browser
<ide> // unusable even after the divs are rendered.
<ide> if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
<del> this.renderingDone = true;
<add> this._finishRendering();
<ide> return;
<ide> }
<ide>
<ide> var TextLayerBuilder = (function TextLayerBuilderClosure() {
<ide> }
<ide>
<ide> this.textLayerDiv.appendChild(textLayerFrag);
<del> this.renderingDone = true;
<add> this._finishRendering();
<ide> this.updateMatches();
<ide> },
<ide>
<ide><path>web/viewer.js
<ide> document.addEventListener('pagerendered', function (e) {
<ide> Stats.add(pageNumber, pageView.stats);
<ide> }
<ide>
<del>//#if (FIREFOX || MOZCENTRAL)
<del>//if (pageView.textLayer && pageView.textLayer.textDivs &&
<del>// pageView.textLayer.textDivs.length > 0 &&
<del>// !PDFViewerApplication.supportsDocumentColors) {
<del>// console.error(mozL10n.get('document_colors_disabled', null,
<del>// 'PDF documents are not allowed to use their own colors: ' +
<del>// '\'Allow pages to choose their own colors\' ' +
<del>// 'is deactivated in the browser.'));
<del>// PDFViewerApplication.fallback();
<del>//}
<del>//#endif
<del>
<ide> if (pageView.error) {
<ide> PDFViewerApplication.error(mozL10n.get('rendering_error', null,
<ide> 'An error occurred while rendering the page.'), pageView.error);
<ide> document.addEventListener('pagerendered', function (e) {
<ide> }
<ide> }, true);
<ide>
<add>document.addEventListener('textlayerrendered', function (e) {
<add> var pageIndex = e.detail.pageNumber - 1;
<add> var pageView = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
<add>
<add>//#if (FIREFOX || MOZCENTRAL)
<add>//if (pageView.textLayer && pageView.textLayer.textDivs &&
<add>// pageView.textLayer.textDivs.length > 0 &&
<add>// !PDFViewerApplication.supportsDocumentColors) {
<add>// console.error(mozL10n.get('document_colors_disabled', null,
<add>// 'PDF documents are not allowed to use their own colors: ' +
<add>// '\'Allow pages to choose their own colors\' ' +
<add>// 'is deactivated in the browser.'));
<add>// PDFViewerApplication.fallback();
<add>//}
<add>//#endif
<add>}, true);
<add>
<ide> window.addEventListener('presentationmodechanged', function (e) {
<ide> var active = e.detail.active;
<ide> var switchInProgress = e.detail.switchInProgress; | 2 |
Javascript | Javascript | remove the .version from library version logging | f4897d73bb65c789a08d73cabd9d882e48a68332 | <ide><path>packages/ember-application/lib/system/application.js
<ide> var Application = Ember.Application = Ember.Namespace.extend(Ember.DeferredMixin
<ide> Ember.debug('-------------------------------');
<ide> Ember.libraries.each(function(name, version) {
<ide> var spaces = new Array(maxNameLength - name.length + 1).join(" ");
<del> Ember.debug([name, '.VERSION', spaces, ' : ', version].join(""));
<add> Ember.debug([name, spaces, ' : ', version].join(""));
<ide> });
<ide> Ember.debug('-------------------------------');
<ide> }
<ide><path>packages/ember-application/tests/system/application_test.js
<ide> test('enable log of libraries with an ENV var', function() {
<ide> });
<ide> });
<ide>
<del> equal(messages[1], "Ember.VERSION : " + Ember.VERSION);
<del> equal(messages[2], "Handlebars.VERSION : " + Handlebars.VERSION);
<del> equal(messages[3], "jQuery.VERSION : " + Ember.$().jquery);
<del> equal(messages[4], "my-lib.VERSION : " + "2.0.0a");
<add> equal(messages[1], "Ember : " + Ember.VERSION);
<add> equal(messages[2], "Handlebars : " + Handlebars.VERSION);
<add> equal(messages[3], "jQuery : " + Ember.$().jquery);
<add> equal(messages[4], "my-lib : " + "2.0.0a");
<ide>
<ide> Ember.libraries.deRegister("my-lib");
<ide> Ember.LOG_VERSION = false; | 2 |
Python | Python | check layer types for optimizer construction | 3ced9b3eb946f4338ace7da66fc2fcdcc2705080 | <ide><path>src/transformers/trainer.py
<ide> SequentialDistributedSampler,
<ide> distributed_broadcast_scalars,
<ide> distributed_concat,
<add> get_parameter_names,
<ide> nested_concat,
<ide> nested_detach,
<ide> nested_numpify,
<ide> def create_optimizer_and_scheduler(self, num_training_steps: int):
<ide> Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass.
<ide> """
<ide> if self.optimizer is None:
<del> no_decay = ["bias", "LayerNorm.weight"]
<add> decay_parameters = get_parameter_names(self.model, [torch.nn.LayerNorm])
<add> decay_parameters = [name for name in decay_parameters if "bias" not in name]
<ide> optimizer_grouped_parameters = [
<ide> {
<del> "params": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay)],
<add> "params": [p for n, p in self.model.named_parameters() if n in decay_parameters],
<ide> "weight_decay": self.args.weight_decay,
<ide> },
<ide> {
<del> "params": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay)],
<add> "params": [p for n, p in self.model.named_parameters() if n not in decay_parameters],
<ide> "weight_decay": 0.0,
<ide> },
<ide> ]
<ide><path>src/transformers/trainer_pt_utils.py
<ide> def save_state(self):
<ide>
<ide> path = os.path.join(self.args.output_dir, "trainer_state.json")
<ide> self.state.save_to_json(path)
<add>
<add>
<add>def get_parameter_names(model, forbidden_layer_types):
<add> """
<add> Returns the names of the model parameters that are not inside a forbidden layer.
<add> """
<add> result = []
<add> for name, child in model.named_children():
<add> result += [
<add> f"{name}.{n}"
<add> for n in get_parameter_names(child, forbidden_layer_types)
<add> if not isinstance(child, tuple(forbidden_layer_types))
<add> ]
<add> # Add model specific parameters (defined with nn.Parameter) since they are not in any child.
<add> result += list(model._parameters.keys())
<add> return result
<ide><path>tests/test_trainer.py
<ide> def forward(self, input_x, labels=None, **kwargs):
<ide> loss = torch.nn.functional.mse_loss(y, labels)
<ide> return (loss, y, y) if self.double_output else (loss, y)
<ide>
<add> class TstLayer(torch.nn.Module):
<add> def __init__(self, hidden_size):
<add> super().__init__()
<add> self.linear1 = torch.nn.Linear(hidden_size, hidden_size)
<add> self.ln1 = torch.nn.LayerNorm(hidden_size)
<add> self.linear2 = torch.nn.Linear(hidden_size, hidden_size)
<add> self.ln2 = torch.nn.LayerNorm(hidden_size)
<add> self.bias = torch.nn.Parameter(torch.zeros(hidden_size))
<add>
<add> def forward(self, x):
<add> h = self.ln1(torch.nn.functional.relu(self.linear1(x)))
<add> h = torch.nn.functional.relu(self.linear2(x))
<add> return self.ln2(x + h + self.bias)
<add>
<ide> def get_regression_trainer(a=0, b=0, double_output=False, train_len=64, eval_len=64, pretrained=True, **kwargs):
<ide> label_names = kwargs.get("label_names", None)
<ide> train_dataset = RegressionDataset(length=train_len, label_names=label_names)
<ide> def test_fp16_full_eval(self):
<ide> # perfect world: fp32_init/2 == fp16_eval
<ide> self.assertAlmostEqual(fp16_eval, fp32_init / 2, delta=5_000)
<ide>
<add> def test_no_wd_param_group(self):
<add> model = torch.nn.Sequential(TstLayer(128), torch.nn.ModuleList([TstLayer(128), TstLayer(128)]))
<add> trainer = Trainer(model=model)
<add> trainer.create_optimizer_and_scheduler(10)
<add> # fmt: off
<add> wd_names = ['0.linear1.weight', '0.linear2.weight', '1.0.linear1.weight', '1.0.linear2.weight', '1.1.linear1.weight', '1.1.linear2.weight']
<add> # fmt: on
<add> wd_params = [p for n, p in model.named_parameters() if n in wd_names]
<add> no_wd_params = [p for n, p in model.named_parameters() if n not in wd_names]
<add> self.assertListEqual(trainer.optimizer.param_groups[0]["params"], wd_params)
<add> self.assertListEqual(trainer.optimizer.param_groups[1]["params"], no_wd_params)
<add>
<ide>
<ide> @require_torch
<ide> @require_optuna
<ide><path>tests/test_trainer_utils.py
<ide> DistributedTensorGatherer,
<ide> LabelSmoother,
<ide> LengthGroupedSampler,
<add> get_parameter_names,
<ide> )
<ide>
<add> class TstLayer(torch.nn.Module):
<add> def __init__(self, hidden_size):
<add> super().__init__()
<add> self.linear1 = torch.nn.Linear(hidden_size, hidden_size)
<add> self.ln1 = torch.nn.LayerNorm(hidden_size)
<add> self.linear2 = torch.nn.Linear(hidden_size, hidden_size)
<add> self.ln2 = torch.nn.LayerNorm(hidden_size)
<add> self.bias = torch.nn.Parameter(torch.zeros(hidden_size))
<add>
<add> def forward(self, x):
<add> h = self.ln1(torch.nn.functional.relu(self.linear1(x)))
<add> h = torch.nn.functional.relu(self.linear2(x))
<add> return self.ln2(x + h + self.bias)
<add>
<ide>
<ide> @require_torch
<ide> class TrainerUtilsTest(unittest.TestCase):
<ide> def test_distributed_length_grouped(self):
<ide> self.assertEqual(lengths[indices_process_0[0]], 50)
<ide> # The indices should be a permutation of range(100)
<ide> self.assertEqual(list(sorted(indices_process_0 + indices_process_1)), list(range(100)))
<add>
<add> def test_get_parameter_names(self):
<add> model = torch.nn.Sequential(TstLayer(128), torch.nn.ModuleList([TstLayer(128), TstLayer(128)]))
<add> # fmt: off
<add> self.assertEqual(
<add> get_parameter_names(model, [torch.nn.LayerNorm]),
<add> ['0.linear1.weight', '0.linear1.bias', '0.linear2.weight', '0.linear2.bias', '0.bias', '1.0.linear1.weight', '1.0.linear1.bias', '1.0.linear2.weight', '1.0.linear2.bias', '1.0.bias', '1.1.linear1.weight', '1.1.linear1.bias', '1.1.linear2.weight', '1.1.linear2.bias', '1.1.bias']
<add> )
<add> # fmt: on | 4 |
Text | Text | add v3.25.0-beta.4 to changelog | 8959f88b8678fe03660eba203af9b58220a4c053 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.25.0-beta.4 (February 01, 2021)
<add>
<add>- [#19363](https://github.com/emberjs/ember.js/pull/19363) [BUGFIX] Update VM, fix component name preprocessing
<add>
<ide> ### v3.25.0-beta.3 (January 25, 2021)
<ide>
<ide> - [#19351](https://github.com/emberjs/ember.js/pull/19351) [BUGFIX] Ensure locals do not clobber components of the same name | 1 |
Python | Python | remove bertconfig inheritance from robertaconfig | 0946ed94fd2df3b514a728f267f9a448441d9a3a | <ide><path>src/transformers/models/roberta/configuration_roberta.py
<ide> from collections import OrderedDict
<ide> from typing import Mapping
<ide>
<add>from ...configuration_utils import PretrainedConfig
<ide> from ...onnx import OnnxConfig
<ide> from ...utils import logging
<del>from ..bert.configuration_bert import BertConfig
<ide>
<ide>
<ide> logger = logging.get_logger(__name__)
<ide> }
<ide>
<ide>
<del>class RobertaConfig(BertConfig):
<add>class RobertaConfig(PretrainedConfig):
<ide> r"""
<ide> This is the configuration class to store the configuration of a [`RobertaModel`] or a [`TFRobertaModel`]. It is
<ide> used to instantiate a RoBERTa model according to the specified arguments, defining the model architecture.
<ide> class RobertaConfig(BertConfig):
<ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
<ide> documentation from [`PretrainedConfig`] for more information.
<ide>
<del> The [`RobertaConfig`] class directly inherits [`BertConfig`]. It reuses the same defaults. Please check the parent
<del> class for more information.
<add>
<add> Args:
<add> vocab_size (`int`, *optional*, defaults to 30522):
<add> Vocabulary size of the RoBERTa model. Defines the number of different tokens that can be represented by the
<add> `inputs_ids` passed when calling [`RobertaModel`] or [`TFRobertaModel`].
<add> hidden_size (`int`, *optional*, defaults to 768):
<add> Dimensionality of the encoder layers and the pooler layer.
<add> num_hidden_layers (`int`, *optional*, defaults to 12):
<add> Number of hidden layers in the Transformer encoder.
<add> num_attention_heads (`int`, *optional*, defaults to 12):
<add> Number of attention heads for each attention layer in the Transformer encoder.
<add> intermediate_size (`int`, *optional*, defaults to 3072):
<add> Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
<add> hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
<add> The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
<add> `"relu"`, `"silu"` and `"gelu_new"` are supported.
<add> hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
<add> The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
<add> attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
<add> The dropout ratio for the attention probabilities.
<add> max_position_embeddings (`int`, *optional*, defaults to 512):
<add> The maximum sequence length that this model might ever be used with. Typically set this to something large
<add> just in case (e.g., 512 or 1024 or 2048).
<add> type_vocab_size (`int`, *optional*, defaults to 2):
<add> The vocabulary size of the `token_type_ids` passed when calling [`RobertaModel`] or [`TFRobertaModel`].
<add> initializer_range (`float`, *optional*, defaults to 0.02):
<add> The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
<add> layer_norm_eps (`float`, *optional*, defaults to 1e-12):
<add> The epsilon used by the layer normalization layers.
<add> position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
<add> Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
<add> positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
<add> [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
<add> For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
<add> with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
<add> use_cache (`bool`, *optional*, defaults to `True`):
<add> Whether or not the model should return the last key/values attentions (not used by all models). Only
<add> relevant if `config.is_decoder=True`.
<add> classifier_dropout (`float`, *optional*):
<add> The dropout ratio for the classification head.
<ide>
<ide> Examples:
<ide>
<ide> class for more information.
<ide> ```"""
<ide> model_type = "roberta"
<ide>
<del> def __init__(self, pad_token_id=1, bos_token_id=0, eos_token_id=2, **kwargs):
<del> """Constructs RobertaConfig."""
<add> def __init__(
<add> self,
<add> vocab_size=30522,
<add> hidden_size=768,
<add> num_hidden_layers=12,
<add> num_attention_heads=12,
<add> intermediate_size=3072,
<add> hidden_act="gelu",
<add> hidden_dropout_prob=0.1,
<add> attention_probs_dropout_prob=0.1,
<add> max_position_embeddings=512,
<add> type_vocab_size=2,
<add> initializer_range=0.02,
<add> layer_norm_eps=1e-12,
<add> pad_token_id=1,
<add> bos_token_id=0,
<add> eos_token_id=2,
<add> position_embedding_type="absolute",
<add> use_cache=True,
<add> classifier_dropout=None,
<add> **kwargs
<add> ):
<ide> super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
<ide>
<add> self.vocab_size = vocab_size
<add> self.hidden_size = hidden_size
<add> self.num_hidden_layers = num_hidden_layers
<add> self.num_attention_heads = num_attention_heads
<add> self.hidden_act = hidden_act
<add> self.intermediate_size = intermediate_size
<add> self.hidden_dropout_prob = hidden_dropout_prob
<add> self.attention_probs_dropout_prob = attention_probs_dropout_prob
<add> self.max_position_embeddings = max_position_embeddings
<add> self.type_vocab_size = type_vocab_size
<add> self.initializer_range = initializer_range
<add> self.layer_norm_eps = layer_norm_eps
<add> self.position_embedding_type = position_embedding_type
<add> self.use_cache = use_cache
<add> self.classifier_dropout = classifier_dropout
<add>
<ide>
<ide> class RobertaOnnxConfig(OnnxConfig):
<ide> @property | 1 |
PHP | PHP | define qualifycolumns method | d373a1c3c17fb8b830e5e8e3949016694f0713ff | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function qualifyColumn($column)
<ide> return $this->getTable().'.'.$column;
<ide> }
<ide>
<add> /**
<add> * Qualify the column's lists name by the model's table.
<add> *
<add> * @param array|mixed $columns
<add> * @return array
<add> */
<add> public function qualifyColumns(...$columns) {
<add> $qualifiedArray = [];
<add> foreach($columns as $column) {
<add> $qualifiedArray[] = $this->qualifyColumn($column);
<add> }
<add> return $qualifiedArray;
<add> }
<add>
<ide> /**
<ide> * Create a new instance of the given model.
<ide> * | 1 |
Python | Python | rewrite class_weight and sample_weight tests | 1d586440a8649e0e0e0b19220040c4b210bcea1b | <ide><path>keras/models.py
<ide> def load_weights(self, filepath):
<ide> g = f['layer_{}'.format(k)]
<ide> weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])]
<ide> self.layers[k].set_weights(weights)
<del> f.close()
<del>
<del>
<add> f.close()
<ide>\ No newline at end of file
<ide><path>keras/objectives.py
<ide>
<ide> def mean_squared_error(y_true, y_pred, weight=None):
<ide> if weight is not None:
<del> return T.sqr(weight.reshape((weight.shape[0], 1))*(y_pred - y_true)).mean()
<add> return T.sqr(weight.reshape((weight.shape[0], 1)) * (y_pred - y_true)).mean()
<ide> else:
<ide> return T.sqr(y_pred - y_true).mean()
<ide>
<ide> def mean_absolute_error(y_true, y_pred, weight=None):
<ide> if weight is not None:
<del> return T.abs_(weight.reshape((weight.shape[0], 1))*(y_pred - y_true)).mean()
<add> return T.abs_(weight.reshape((weight.shape[0], 1)) * (y_pred - y_true)).mean()
<ide> else:
<ide> return T.abs_(y_pred - y_true).mean()
<ide>
<ide> def squared_hinge(y_true, y_pred, weight=None):
<ide> if weight is not None:
<ide> weight = weight.reshape((weight.shape[0], 1))
<del> return T.sqr(weight*T.maximum(1. - (y_true * y_pred), 0.)).mean()
<add> return T.sqr(weight * T.maximum(1. - (y_true * y_pred), 0.)).mean()
<ide> else:
<ide> return T.sqr(T.maximum(1. - y_true * y_pred, 0.)).mean()
<ide>
<ide> def hinge(y_true, y_pred, weight=None):
<ide> if weight is not None:
<ide> weight = weight.reshape((weight.shape[0], 1))
<del> return (weight*T.maximum(1. - (y_true * y_pred), 0.)).mean()
<add> return (weight * T.maximum(1. - (y_true * y_pred), 0.)).mean()
<ide> else:
<ide> return T.maximum(1. - y_true * y_pred, 0.).mean()
<ide>
<ide> def categorical_crossentropy(y_true, y_pred, weight=None):
<ide> cce = T.nnet.categorical_crossentropy(y_pred, y_true)
<ide> if weight is not None:
<ide> # return avg. of scaled cat. crossentropy
<del> return (weight*cce).mean()
<add> return (weight * cce).mean()
<ide> else:
<ide> return cce.mean()
<ide>
<ide> def binary_crossentropy(y_true, y_pred, weight=None):
<ide> y_pred = T.clip(y_pred, epsilon, 1.0 - epsilon)
<ide> bce = T.nnet.binary_crossentropy(y_pred, y_true)
<ide> if weight is not None:
<del> return (weight.reshape((weight.shape[0], 1))*bce).mean()
<add> return (weight.reshape((weight.shape[0], 1)) * bce).mean()
<ide> else:
<ide> return bce.mean()
<ide>
<ide> def binary_crossentropy(y_true, y_pred, weight=None):
<ide>
<ide> from .utils.generic_utils import get_from_module
<ide> def get(identifier):
<del> return get_from_module(identifier, globals(), 'objective')
<del>
<del>def to_categorical(y):
<del> '''Convert class vector (integers from 0 to nb_classes)
<del> to binary class matrix, for use with categorical_crossentropy
<del> '''
<del> nb_classes = np.max(y)+1
<del> Y = np.zeros((len(y), nb_classes))
<del> for i in range(len(y)):
<del> Y[i, y[i]] = 1.
<del> return Y
<add> return get_from_module(identifier, globals(), 'objective')
<ide>\ No newline at end of file
<ide><path>test/test_lossweights.py
<ide> from __future__ import print_function
<ide> from keras.datasets import mnist
<ide> from keras.models import Sequential
<del>from keras.layers.core import Dense, Activation, Merge, Dropout
<del>from keras.optimizers import SGD
<add>from keras.layers.core import Dense, Activation
<ide> from keras.utils import np_utils
<ide> import numpy as np
<ide>
<ide> nb_classes = 10
<ide> batch_size = 128
<del>nb_epoch = 15
<del>
<del>max_train_samples = 5000
<del>max_test_samples = 1000
<add>nb_epoch = 5
<add>weighted_class = 9
<add>standard_weight = 1
<add>high_weight = 5
<add>max_train_samples = 10000
<add>max_test_samples = 10000
<ide>
<ide> np.random.seed(1337) # for reproducibility
<ide>
<ide> # the data, shuffled and split between tran and test sets
<ide> (X_train, y_train), (X_test, y_test) = mnist.load_data()
<del>
<ide> X_train = X_train.reshape(60000,784)[:max_train_samples]
<ide> X_test = X_test.reshape(10000,784)[:max_test_samples]
<del>X_train = X_train.astype("float32")
<del>X_test = X_test.astype("float32")
<del>X_train /= 255
<del>X_test /= 255
<add>X_train = X_train.astype("float32") / 255
<add>X_test = X_test.astype("float32") / 255
<ide>
<ide> # convert class vectors to binary class matrices
<ide> y_train = y_train[:max_train_samples]
<ide> y_test = y_test[:max_test_samples]
<ide> Y_train = np_utils.to_categorical(y_train, nb_classes)
<ide> Y_test = np_utils.to_categorical(y_test, nb_classes)
<add>test_ids = np.where(y_test == np.array(weighted_class))[0]
<ide>
<del>def createMNISTModel():
<add>def create_model():
<ide> model = Sequential()
<ide> model.add(Dense(784, 50))
<ide> model.add(Activation('relu'))
<ide> model.add(Dense(50, 10))
<ide> model.add(Activation('softmax'))
<del> model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
<del> return model
<del>
<del>model_classweights_fit = createMNISTModel()
<del>model_fit = createMNISTModel()
<del>
<del>model_classweights_train = createMNISTModel()
<del>model_train = createMNISTModel()
<del>
<del>high_weight = 100
<del>class_weight = {0:1,1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:1,9:high_weight}
<del>
<del>############################
<del># categorical crossentropy #
<del>############################
<del>
<del>print("Testing fit methods with and without classweights")
<del># fit
<del>model_classweights_fit.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0, validation_data=(X_test, Y_test), class_weight=class_weight)
<del>model_fit.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0, validation_data=(X_test, Y_test))
<del>print("Testing train methods with and without classweights")
<del># train
<del>model_classweights_train.train(X_train, Y_train, class_weight=class_weight)
<del>model_train.train(X_train, Y_train)
<del>
<del>print('MNIST Classification accuracies on test set for fitted models:')
<del>for nb in range(nb_classes):
<del> testIdcs = np.where(y_test == np.array(nb))[0]
<del> X_temp = X_test[testIdcs, :]
<del> Y_temp = Y_test[testIdcs,:]
<del> # eval model which was trained with fit()
<del> score_cw = model_classweights_fit.evaluate(X_temp, Y_temp, show_accuracy=True, verbose=0)
<del> score = model_fit.evaluate(X_temp, Y_temp, show_accuracy=True, verbose=0)
<del> # eval model which was trained with train()
<del> score_cw_train = model_classweights_train.evaluate(X_temp, Y_temp, show_accuracy=True, verbose=0)
<del> score_train = model_train.evaluate(X_temp, Y_temp, show_accuracy=True, verbose=0)
<del> # print test accuracies for class weighted model vs. uniform weights
<del> print("Digit %d: class_weight = %d -> %.3f \t class_weight = %d -> %.3f" % (nb, class_weight[nb], score_cw[1], 1, score[1]))
<del> if class_weight[nb] == high_weight and (score_cw[1] <= score[1] or score_cw_train[1] <= score_train[1]):
<del> raise Exception('Class weights are not implemented correctly')
<del>
<del>####################################################
<del># test cases for all remaining objective functions #
<del>####################################################
<del>batch_size = 64
<del>nb_epoch = 10
<del>
<del>def generateData(n_samples, n_dim):
<del> A_feats = np.random.randn(n_samples, n_dim)
<del> B_feats = np.random.randn(n_samples, n_dim)
<del> A_label = np.zeros((n_samples,1))
<del> B_label = np.ones((n_samples,1))
<del> X = np.vstack((A_feats, B_feats))
<del> y = np.vstack((A_label, B_label)).squeeze()
<del> return X, y
<del>
<del>n_dim = 100
<del>X_train, y_train = generateData(1000, n_dim)
<del>X_test, y_test = generateData(5000, n_dim)
<del>
<del>def createModel(ls, n_dim, activation="sigmoid"):
<del> model = Sequential()
<del> model.add(Dense(n_dim, 50))
<del> model.add(Activation('relu'))
<del> model.add(Dropout(0.5))
<del> model.add(Dense(50, 1))
<del> model.add(Activation(activation))
<del> sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
<del> model.compile(loss=ls, optimizer=sgd, class_mode="binary")
<ide> return model
<ide>
<del>verbosity = 0
<del>cw = {0: 1.5, 1: 1}
<del># binary crossentropy
<del>model = createModel('binary_crossentropy', n_dim)
<del>model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=verbosity, validation_data=(X_test, y_test), class_weight=cw)
<del>res = model.predict(X_test, verbose=verbosity).round()
<del>neg_preds, pos_preds = (1.0*np.sum(res == 0)/res.shape[0], 1.0*np.sum(res == 1)/res.shape[0])
<del>assert(neg_preds > pos_preds)
<del>print("binary crossentropy: %0.2f VS %0.2f" % (neg_preds, pos_preds))
<del>
<del># MAE
<del>model = createModel('mean_absolute_error', n_dim)
<del>model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=verbosity, validation_data=(X_test, y_test), class_weight=cw)
<del>res = model.predict(X_test, verbose=verbosity).round()
<del>neg_preds, pos_preds = (1.0*np.sum(res == 0)/res.shape[0], 1.0*np.sum(res == 1)/res.shape[0])
<del>assert(neg_preds > pos_preds)
<del>print("MAE: %0.2f VS %0.2f" % (neg_preds, pos_preds))
<del>
<del># MSE
<del>model = createModel('mean_squared_error', n_dim)
<del>model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=verbosity, validation_data=(X_test, y_test), class_weight=cw)
<del>res = model.predict(X_test, verbose=verbosity).round()
<del>neg_preds, pos_preds = (1.0*np.sum(res == 0)/res.shape[0], 1.0*np.sum(res == 1)/res.shape[0])
<del>assert(neg_preds > pos_preds)
<del>print("MSE: %0.2f VS %0.2f" % (neg_preds, pos_preds))
<del>
<del># hinge losses, map labels
<del>y_train[y_train == 0] = -1
<del>y_test[y_test == 0] = -1
<del>cw = {-1: 1.5, 1: 1}
<del>
<del># hinge
<del>model = createModel('hinge', n_dim, "tanh")
<del>model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=verbosity, validation_data=(X_test, y_test), class_weight=cw)
<del>res = model.predict(X_test, verbose=verbosity)
<del>res[res < 0] = -1
<del>res[res >= 0] = 1
<del>neg_preds, pos_preds = (1.0*np.sum(res == -1)/res.shape[0], 1.0*np.sum(res == 1)/res.shape[0])
<del>assert(neg_preds > pos_preds)
<del>print("hinge: %0.2f VS %0.2f" % (neg_preds, pos_preds))
<add>def test_weights(model, class_weight=None, sample_weight=None):
<add> model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0, \
<add> class_weight=class_weight, sample_weight=sample_weight)
<add> score = model.evaluate(X_test[test_ids, :], Y_test[test_ids, :], verbose=0)
<add> return score
<ide>
<del># squared hinge
<del>model = createModel('squared_hinge', n_dim, "tanh")
<del>model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=verbosity, validation_data=(X_test, y_test), class_weight=cw)
<del>res = model.predict(X_test, verbose=verbosity)
<del>res[res < 0] = -1
<del>res[res >= 0] = 1
<del>neg_preds, pos_preds = (1.0*np.sum(res == -1)/res.shape[0], 1.0*np.sum(res == 1)/res.shape[0])
<del>assert(neg_preds > pos_preds)
<del>print("sqr hinge: %0.2f VS %0.2f" % (neg_preds, pos_preds))
<add>class_weight = dict([(i, standard_weight) for i in range(nb_classes)])
<add>class_weight[weighted_class] = high_weight
<ide>
<add>sample_weight = np.ones((y_train.shape[0])) * standard_weight
<add>sample_weight[y_train == weighted_class] = high_weight
<ide>
<del>############################
<del># sample weight test cases #
<del>############################
<del>
<del>batch_size = 128
<del>nb_epoch = 15
<del>
<del># the data, shuffled and split between tran and test sets
<del>(X_train, y_train), (X_test, y_test) = mnist.load_data()
<del>
<del>X_train = X_train.reshape(60000,784)[:max_train_samples]
<del>X_test = X_test.reshape(10000,784)[:max_test_samples]
<del>X_train = X_train.astype("float32")
<del>X_test = X_test.astype("float32")
<del>X_train /= 255
<del>X_test /= 255
<del>
<del># convert class vectors to binary class matrices
<del>y_train = y_train[:max_train_samples]
<del>y_test = y_test[:max_test_samples]
<del>Y_train = np_utils.to_categorical(y_train, nb_classes)
<del>Y_test = np_utils.to_categorical(y_test, nb_classes)
<del>
<del>print("Sample weight test cases")
<del>
<del># categorical crossentropy
<del>model_sampleweights_fit = createMNISTModel()
<del>model_sampleweights_train = createMNISTModel()
<del>model_fit = createMNISTModel()
<del>model_train = createMNISTModel()
<del>
<del>sample_weight = np.ones((Y_train.shape[0]))
<del>sample_weight[y_train == 9] = high_weight
<del>
<del>model_sampleweights_fit.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0, validation_data=(X_test, Y_test), sample_weight=sample_weight)
<del>model_fit.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0, validation_data=(X_test, Y_test))
<del>model_sampleweights_train.train(X_train, Y_train, sample_weight=sample_weight)
<del>model_train.train(X_train, Y_train)
<del>
<del>print('MNIST Classification accuracies on test set for fitted models:')
<del>for nb in range(nb_classes):
<del> testIdcs = np.where(y_test == np.array(nb))[0]
<del> X_temp = X_test[testIdcs, :]
<del> Y_temp = Y_test[testIdcs,:]
<del> # eval model which was trained with fit()
<del> score_sw = model_sampleweights_fit.evaluate(X_temp, Y_temp, show_accuracy=True, verbose=0)
<del> score = model_fit.evaluate(X_temp, Y_temp, show_accuracy=True, verbose=0)
<del> # eval model which was trained with train()
<del> score_sw_train = model_sampleweights_train.evaluate(X_temp, Y_temp, show_accuracy=True, verbose=0)
<del> score_train = model_train.evaluate(X_temp, Y_temp, show_accuracy=True, verbose=0)
<del> # print test accuracies for class weighted model vs. uniform weights
<del> print("Digit %d: sample_weight = %d -> %.3f \t sample_weight = %d -> %.3f" % (nb, 100 if nb == 9 else 1, score_sw[1], 1, score[1]))
<del> if nb == 9 and (score_sw[1] <= score[1] or score_sw_train[1] <= score_train[1]):
<del> raise Exception('Sample weights are not implemented correctly')
<del>
<del>
<del>n_dim = 100
<del>X_train, y_train = generateData(1000, n_dim)
<del>X_test, y_test = generateData(5000, n_dim)
<del>
<del>y_train[y_train == -1] = 0
<del>y_test[y_test == -1] = 0
<del>
<del>sample_weight = np.ones((y_train.shape[0]))
<del>sample_weight[y_train == 0] = 1.5
<del>
<del># binary crossentropy
<del>model = createModel('binary_crossentropy', n_dim)
<del>model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=verbosity, validation_data=(X_test, y_test), sample_weight=sample_weight)
<del>res = model.predict(X_test, verbose=verbosity).round()
<del>neg_preds, pos_preds = (1.0*np.sum(res == 0)/res.shape[0], 1.0*np.sum(res == 1)/res.shape[0])
<del>assert(neg_preds > pos_preds)
<del>print("binary crossentropy: %0.2f VS %0.2f" % (neg_preds, pos_preds))
<del>
<del># MAE
<del>model = createModel('mean_absolute_error', n_dim)
<del>model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=verbosity, validation_data=(X_test, y_test), sample_weight=sample_weight)
<del>res = model.predict(X_test, verbose=verbosity).round()
<del>neg_preds, pos_preds = (1.0*np.sum(res == 0)/res.shape[0], 1.0*np.sum(res == 1)/res.shape[0])
<del>assert(neg_preds > pos_preds)
<del>print("MAE: %0.2f VS %0.2f" % (neg_preds, pos_preds))
<del>
<del># MSE
<del>model = createModel('mean_squared_error', n_dim)
<del>model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=verbosity, validation_data=(X_test, y_test), sample_weight=sample_weight)
<del>res = model.predict(X_test, verbose=verbosity).round()
<del>neg_preds, pos_preds = (1.0*np.sum(res == 0)/res.shape[0], 1.0*np.sum(res == 1)/res.shape[0])
<del>assert(neg_preds > pos_preds)
<del>print("MSE: %0.2f VS %0.2f" % (neg_preds, pos_preds))
<del>
<del># hinge losses, map labels
<del>y_train[y_train == 0] = -1
<del>y_test[y_test == 0] = -1
<del>sample_weight = np.ones((y_train.shape[0]))
<del>sample_weight[y_train == -1] = 1.5
<del>
<del># hinge
<del>model = createModel('hinge', n_dim, "tanh")
<del>model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=verbosity, validation_data=(X_test, y_test), sample_weight=sample_weight)
<del>res = model.predict(X_test, verbose=verbosity)
<del>res[res < 0] = -1
<del>res[res >= 0] = 1
<del>neg_preds, pos_preds = (1.0*np.sum(res == -1)/res.shape[0], 1.0*np.sum(res == 1)/res.shape[0])
<del>assert(neg_preds > pos_preds)
<del>print("hinge: %0.2f VS %0.2f" % (neg_preds, pos_preds))
<del>
<del># squared hinge
<del>model = createModel('squared_hinge', n_dim, "tanh")
<del>model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=verbosity, validation_data=(X_test, y_test), sample_weight=sample_weight)
<del>res = model.predict(X_test, verbose=verbosity)
<del>res[res < 0] = -1
<del>res[res >= 0] = 1
<del>neg_preds, pos_preds = (1.0*np.sum(res == -1)/res.shape[0], 1.0*np.sum(res == 1)/res.shape[0])
<del>assert(neg_preds > pos_preds)
<del>print("sqr hinge: %0.2f VS %0.2f" % (neg_preds, pos_preds))
<del>
<add>for loss in ['mae', 'mse', 'categorical_crossentropy']:
<add> print('loss:', loss)
<add> # no weights: reference point
<add> model = create_model()
<add> model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
<add> standard_score = test_weights(model)
<add> # test class_weight
<add> model = create_model()
<add> model.compile(loss=loss, optimizer='rmsprop')
<add> score = test_weights(model, class_weight=class_weight)
<add> print('score:', score, ' vs.', standard_score)
<add> assert(score < standard_score)
<add> # test sample_weight
<add> model = create_model()
<add> model.compile(loss=loss, optimizer='rmsprop')
<add> score = test_weights(model, sample_weight=sample_weight)
<add> print('score:', score, ' vs.', standard_score)
<add> assert(score < standard_score) | 3 |
Javascript | Javascript | prevent stalls by using read(0) | ac2263b77f3f346458d06fc019de27e24c63cee0 | <ide><path>lib/tls.js
<ide> CryptoStream.prototype._read = function read(size) {
<ide> if (this.ondata) {
<ide> this.ondata(pool, start, start + bytesRead);
<ide>
<del> // Consume data automatically
<del> // simple/test-https-drain fails without it
<del> this.push(pool.slice(start, start + bytesRead));
<del> this.read(bytesRead);
<add> // Deceive streams2
<add> var self = this;
<add>
<add> setImmediate(function() {
<add> // Force state.reading to set to false
<add> self.push('');
<add>
<add> // Try reading more, we most likely have some data
<add> self.read(0);
<add> });
<ide> } else {
<ide> this.push(pool.slice(start, start + bytesRead));
<ide> }
<ide><path>test/simple/test-https-req-split.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>if (!process.versions.openssl) {
<add> console.error('Skipping because node compiled without OpenSSL.');
<add> process.exit(0);
<add>}
<add>
<add>// disable strict server certificate validation by the client
<add>process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var https = require('https');
<add>var tls = require('tls');
<add>var fs = require('fs');
<add>
<add>var seen_req = false;
<add>
<add>var options = {
<add> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'),
<add> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem')
<add>};
<add>
<add>// Force splitting incoming data
<add>tls.SLAB_BUFFER_SIZE = 1;
<add>
<add>var server = https.createServer(options);
<add>server.on('upgrade', function(req, socket, upgrade) {
<add> socket.on('data', function(data) {
<add> throw new Error('Unexpected data: ' + data);
<add> });
<add> socket.end('HTTP/1.1 200 Ok\r\n\r\n');
<add> seen_req = true;
<add>});
<add>
<add>server.listen(common.PORT, function() {
<add> var req = https.request({
<add> host: '127.0.0.1',
<add> port: common.PORT,
<add> agent: false,
<add> headers: {
<add> Connection: 'Upgrade',
<add> Upgrade: 'Websocket'
<add> }
<add> }, function() {
<add> req.socket.destroy();
<add> server.close();
<add> });
<add>
<add> req.end();
<add>});
<add>
<add>process.on('exit', function() {
<add> assert(seen_req);
<add> console.log('ok');
<add>}); | 2 |
Javascript | Javascript | add tests for selection.{attr,property,style} | 53326dac6cd809c29c43c426dd55413b97b2441f | <ide><path>test/core/selection-attr-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.attr");
<add>
<add>suite.addBatch({
<add> "select": {
<add> topic: function() {
<add> return d3.select("body");
<add> },
<add> "sets an attribute as a string": function(body) {
<add> body.attr("bgcolor", "red");
<add> assert.equal(body[0][0].getAttribute("bgcolor"), "red");
<add> },
<add> "sets an attribute as a number": function(body) {
<add> body.attr("opacity", 1);
<add> assert.equal(body[0][0].getAttribute("opacity"), "1");
<add> },
<add> "sets an attribute as a function": function(body) {
<add> body.attr("bgcolor", function() { return "orange"; });
<add> assert.equal(body[0][0].getAttribute("bgcolor"), "orange");
<add> },
<add> "sets an attribute as a function of data": function(body) {
<add> body.data(["cyan"]).attr("bgcolor", String);
<add> assert.equal(body[0][0].getAttribute("bgcolor"), "cyan");
<add> },
<add> "sets an attribute as a function of index": function(body) {
<add> body.attr("bgcolor", function(d, i) { return "orange-" + i; });
<add> assert.equal(body[0][0].getAttribute("bgcolor"), "orange-0");
<add> },
<add> "gets an attribute value": function(body) {
<add> body[0][0].setAttribute("bgcolor", "yellow");
<add> assert.equal(body.attr("bgcolor"), "yellow");
<add> }
<add> }
<add>});
<add>
<add>suite.addBatch({
<add> "selectAll": {
<add> topic: function() {
<add> return d3.select("body").html("").selectAll("div").data(d3.range(2)).enter().append("div");
<add> },
<add> "sets an attribute as a string": function(div) {
<add> div.attr("bgcolor", "red");
<add> assert.equal(div[0][0].getAttribute("bgcolor"), "red");
<add> assert.equal(div[0][1].getAttribute("bgcolor"), "red");
<add> },
<add> "sets an attribute as a number": function(div) {
<add> div.attr("opacity", 0.4);
<add> assert.equal(div[0][0].getAttribute("opacity"), "0.4");
<add> assert.equal(div[0][1].getAttribute("opacity"), "0.4");
<add> },
<add> "sets an attribute as a function": function(div) {
<add> div.attr("bgcolor", function() { return "coral"; });
<add> assert.equal(div[0][0].getAttribute("bgcolor"), "coral");
<add> assert.equal(div[0][1].getAttribute("bgcolor"), "coral");
<add> },
<add> "sets an attribute as a function of data": function(div) {
<add> div.attr("bgcolor", d3.interpolateRgb("brown", "steelblue"));
<add> assert.equal(div[0][0].getAttribute("bgcolor"), "rgb(165,42,42)");
<add> assert.equal(div[0][1].getAttribute("bgcolor"), "rgb(70,130,180)");
<add> },
<add> "sets an attribute as a function of index": function(div) {
<add> div.attr("bgcolor", function(d, i) { return "color-" + i; });
<add> assert.equal(div[0][0].getAttribute("bgcolor"), "color-0");
<add> assert.equal(div[0][1].getAttribute("bgcolor"), "color-1");
<add> },
<add> "gets an attribute value": function(div) {
<add> div[0][0].setAttribute("bgcolor", "purple");
<add> assert.equal(div.attr("bgcolor"), "purple");
<add> }
<add> }
<add>});
<add>
<add>suite.export(module);
<ide><path>test/core/selection-property-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.property");
<add>
<add>suite.addBatch({
<add> "select(body)": {
<add> topic: function() {
<add> return d3.select("body").html("");
<add> },
<add> "sets a property as a string": function(body) {
<add> body.property("bgcolor", "red");
<add> assert.equal(body[0][0].bgcolor, "red");
<add> },
<add> "sets a property as a number": function(body) {
<add> body.property("opacity", 1);
<add> assert.equal(body[0][0].opacity, "1");
<add> },
<add> "sets a property as a function": function(body) {
<add> body.property("bgcolor", function() { return "orange"; });
<add> assert.equal(body[0][0].bgcolor, "orange");
<add> },
<add> "gets a property value": function(body) {
<add> body[0][0].bgcolor = "yellow";
<add> assert.equal(body.property("bgcolor"), "yellow");
<add> }
<add> }
<add>});
<add>
<add>suite.addBatch({
<add> "selectAll(div)": {
<add> topic: function() {
<add> return d3.select("body").html("").selectAll("div").data(d3.range(2)).enter().append("div");
<add> },
<add> "sets a property as a string": function(div) {
<add> div.property("bgcolor", "red");
<add> assert.equal(div[0][0].bgcolor, "red");
<add> assert.equal(div[0][1].bgcolor, "red");
<add> },
<add> "sets a property as a number": function(div) {
<add> div.property("opacity", 0.4);
<add> assert.equal(div[0][0].opacity, "0.4");
<add> assert.equal(div[0][1].opacity, "0.4");
<add> },
<add> "sets a property as a function": function(div) {
<add> div.property("bgcolor", d3.interpolateRgb("brown", "steelblue"));
<add> assert.equal(div[0][0].bgcolor, "rgb(165,42,42)");
<add> assert.equal(div[0][1].bgcolor, "rgb(70,130,180)");
<add> },
<add> "gets a property value": function(div) {
<add> div[0][0].bgcolor = "purple";
<add> assert.equal(div.property("bgcolor"), "purple");
<add> }
<add> }
<add>});
<add>
<add>suite.export(module);
<ide><path>test/core/selection-style-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.style");
<add>
<add>suite.addBatch({
<add> "select(body)": {
<add> topic: function() {
<add> return d3.select("body").html("");
<add> },
<add> "sets a property as a string": function(body) {
<add> body.style("background-color", "red");
<add> assert.equal(body[0][0].style["background-color"], "red");
<add> },
<add> "sets a property as a number": function(body) {
<add> body.style("opacity", .3);
<add> assert.equal(body[0][0].style["opacity"], ".3");
<add> },
<add> "sets a property as a function": function(body) {
<add> body.style("background-color", function() { return "orange"; });
<add> assert.equal(body[0][0].style["background-color"], "orange");
<add> },
<add> "gets a property value": function(body) {
<add> body[0][0].style.setProperty("background-color", "yellow", "");
<add> assert.equal(body.style("background-color"), "yellow");
<add> },
<add> "observes the specified priority": function(body) {
<add> body.style("background-color", "green", "important");
<add> assert.equal(body[0][0].style.getPropertyPriority("background-color"), "important");
<add> }
<add> }
<add>});
<add>
<add>suite.addBatch({
<add> "selectAll(div)": {
<add> topic: function() {
<add> return d3.select("body").html("").selectAll("div").data(d3.range(2)).enter().append("div");
<add> },
<add> "sets a property as a string": function(div) {
<add> div.style("background-color", "red");
<add> assert.equal(div[0][0].style["background-color"], "red");
<add> assert.equal(div[0][1].style["background-color"], "red");
<add> },
<add> "sets a property as a number": function(div) {
<add> div.style("opacity", .5);
<add> assert.equal(div[0][0].style["opacity"], ".5");
<add> assert.equal(div[0][1].style["opacity"], ".5");
<add> },
<add> "sets a property as a function": function(div) {
<add> div.style("background-color", d3.interpolateRgb("orange", "yellow"));
<add> assert.equal(div[0][0].style["background-color"], "rgb(255,165,0)");
<add> assert.equal(div[0][1].style["background-color"], "rgb(255,255,0)");
<add> },
<add> "gets a property value": function(div) {
<add> div[0][0].style.setProperty("background-color", "green", "");
<add> assert.equal(div.style("background-color"), "green");
<add> },
<add> "observes the specified priority": function(div) {
<add> div.style("background-color", "blue", "important");
<add> assert.equal(div[0][0].style.getPropertyPriority("background-color"), "important");
<add> assert.equal(div[0][1].style.getPropertyPriority("background-color"), "important");
<add> }
<add> }
<add>});
<add>
<add>suite.export(module); | 3 |
Ruby | Ruby | update copyright notice for 2016 | 012f42a8b9b9576791109e435616a5dc5250c47b | <ide><path>actionmailer/lib/action_mailer.rb
<ide> #--
<del># Copyright (c) 2004-2015 David Heinemeier Hansson
<add># Copyright (c) 2004-2016 David Heinemeier Hansson
<ide> #
<ide> # Permission is hereby granted, free of charge, to any person obtaining
<ide> # a copy of this software and associated documentation files (the | 1 |
Ruby | Ruby | enhance unscoped tests | 36a45230dac4546b71b145681cf553a5a4f9eccb | <ide><path>activerecord/test/cases/relation_scoping_test.rb
<ide> def test_unscoped_with_named_scope_should_not_have_default_scope
<ide> assert_equal [DeveloperCalledJamis.find(developers(:poor_jamis).id)], DeveloperCalledJamis.poor
<ide>
<ide> assert DeveloperCalledJamis.unscoped.poor.include?(developers(:david).becomes(DeveloperCalledJamis))
<add>
<add> assert_equal 11, DeveloperCalledJamis.unscoped.length
<add> assert_equal 1, DeveloperCalledJamis.poor.length
<ide> assert_equal 10, DeveloperCalledJamis.unscoped.poor.length
<add> assert_equal 10, DeveloperCalledJamis.unscoped { DeveloperCalledJamis.poor }.length
<ide> end
<ide>
<ide> def test_default_scope_select_ignored_by_aggregations | 1 |
Ruby | Ruby | remove unnecessary `package.json` deletion | 8ba3da87672ad243ce0ef378369b1a3719192a58 | <ide><path>railties/lib/rails/generators/rails/app/app_generator.rb
<ide> def create_tmp_files
<ide>
<ide> def create_vendor_files
<ide> build(:vendor)
<del>
<del> if options[:skip_yarn]
<del> remove_file "package.json"
<del> end
<ide> end
<ide>
<ide> def delete_app_assets_if_api_option | 1 |
Python | Python | add test for callback threadsafety | d7b3177ea12ef950daa162380695f54496a7c483 | <ide><path>numpy/f2py/tests/test_callback.py
<ide> import textwrap
<ide> import sys
<ide> import pytest
<add>import threading
<add>import traceback
<add>import time
<add>import random
<ide>
<ide> import numpy as np
<ide> from numpy.testing import assert_, assert_equal, IS_PYPY
<ide> def callback(cu, lencu):
<ide> f = getattr(self.module, 'string_callback_array')
<ide> res = f(callback, cu, len(cu))
<ide> assert_(res == 0, repr(res))
<add>
<add> def test_threadsafety(self):
<add> # Segfaults if the callback handling is not threadsafe
<add>
<add> errors = []
<add>
<add> def cb():
<add> # Sleep here to make it more likely for another thread
<add> # to call their callback at the same time.
<add> time.sleep(1e-3)
<add>
<add> # Check reentrancy
<add> r = self.module.t(lambda: 123)
<add> assert_(r == 123)
<add>
<add> return 42
<add>
<add> def runner(name):
<add> try:
<add> for j in range(50):
<add> r = self.module.t(cb)
<add> assert_(r == 42)
<add> self.check_function(name)
<add> except Exception:
<add> errors.append(traceback.format_exc())
<add>
<add> threads = [threading.Thread(target=runner, args=(arg,))
<add> for arg in ("t", "t2") for n in range(20)]
<add>
<add> for t in threads:
<add> t.start()
<add>
<add> for t in threads:
<add> t.join()
<add>
<add> errors = "\n\n".join(errors)
<add> if errors:
<add> raise AssertionError(errors)
<add>
<add>
<add>class TestF77CallbackPythonTLS(TestF77Callback):
<add> """
<add> Callback tests using Python thread-local storage instead of
<add> compiler-provided
<add> """
<add> options = ["-DF2PY_USE_PYTHON_TLS"] | 1 |
Ruby | Ruby | play nice with case-sensitive filesystems | fb9b263bc3b35f0b8735c7c2495d75c0cab43a34 | <ide><path>Library/Homebrew/cmd/--config.rb
<ide> def sha
<ide>
<ide> def describe_x11
<ide> return "N/A" unless x11_installed?
<del> return case x11_path = Pathname.new("/usr/x11").realpath.to_s
<del> when "/usr/x11" then "/usr/x11"
<del> else "/usr/x11 => #{x11_path}"
<add> return case x11_path = Pathname.new("/usr/X11").realpath.to_s
<add> when "/usr/X11" then "/usr/X11"
<add> else "/usr/X11 => #{x11_path}"
<ide> end
<ide> end
<ide> | 1 |
Python | Python | remove duplicate convert_to_tensor | 1589a843bac4390c8377db05cbd6ae650b6210cc | <ide><path>keras/losses.py
<ide> def sparse_categorical_crossentropy(
<ide> Returns:
<ide> Sparse categorical crossentropy loss value.
<ide> """
<del> y_pred = tf.convert_to_tensor(y_pred)
<del>
<ide> return backend.sparse_categorical_crossentropy(
<ide> y_true,
<ide> y_pred, | 1 |
Ruby | Ruby | disambiguate show_header usage | e1da727a4e1952156be851816cc377bb9704fc02 | <ide><path>Library/Homebrew/formula_installer.rb
<ide> class FormulaInstaller
<ide> def initialize ff, tab=nil
<ide> @f = ff
<ide> @tab = tab
<del> @show_header = true
<add> @show_header = false
<ide> @ignore_deps = ARGV.ignore_deps? || ARGV.interactive?
<ide> @install_bottle = install_bottle? ff
<ide>
<ide> def install
<ide> end
<ide> end
<ide> # now show header as all the deps stuff has clouded the original issue
<del> show_header = true
<add> @show_header = true
<ide> end
<ide> end
<ide> | 1 |
PHP | PHP | add a note to offsetset() on why it cannot chain | cb0ac6f9f334217e4e33b072b1958dcf3d47bc50 | <ide><path>lib/Cake/Model/Validator/CakeValidationSet.php
<ide> public function offsetGet($index) {
<ide> }
<ide>
<ide> /**
<del> * Sets or replace a validation rule
<add> * Sets or replace a validation rule.
<add> *
<add> * This is a wrapper for ArrayAccess. Use setRule() directly for
<add> * chainable access.
<add> *
<add> * @see http://www.php.net/manual/en/arrayobject.offsetset.php
<ide> *
<ide> * @param string $index name of the rule
<ide> * @param CakeValidationRule|array rule to add to $index | 1 |
Javascript | Javascript | avoid inline access to symbol.iterator | 550e8149036358713be8d5c8a91f7ad8f01d7f6d | <ide><path>lib/internal/util/inspect.js
<ide> function formatRaw(ctx, value, recurseTimes, typedArray) {
<ide> // Iterators and the rest are split to reduce checks.
<ide> // We have to check all values in case the constructor is set to null.
<ide> // Otherwise it would not possible to identify all types properly.
<del> if (value[SymbolIterator] || constructor === null) {
<add> if (SymbolIterator in value || constructor === null) {
<ide> noIterator = false;
<ide> if (ArrayIsArray(value)) {
<ide> // Only set the constructor for non ordinary ("Array [...]") arrays.
<ide><path>test/parallel/test-util-inspect.js
<ide> assert.strictEqual(
<ide> '-123_456_789.123_456_78'
<ide> );
<ide> }
<add>
<add>// Regression test for https://github.com/nodejs/node/issues/41244
<add>{
<add> assert.strictEqual(util.inspect({
<add> get [Symbol.iterator]() {
<add> throw new Error();
<add> }
<add> }), '{ [Symbol(Symbol.iterator)]: [Getter] }');
<add>} | 2 |
Python | Python | remove unused type comment that upsets mypy | 5cc8e9826bef303723b82ee28f020a26506dac7b | <ide><path>airflow/models/dagrun.py
<ide> class DagRun(Base, LoggingMixin):
<ide>
<ide> task_instances = relationship(
<ide> TI,
<del> primaryjoin=and_(TI.dag_id == dag_id, TI.execution_date == execution_date), # type: ignore
<add> primaryjoin=and_(TI.dag_id == dag_id, TI.execution_date == execution_date),
<ide> foreign_keys=(dag_id, execution_date),
<ide> backref=backref('dag_run', uselist=False),
<ide> ) | 1 |
Python | Python | add join to valid merge modes | 6f620712b5448643aceb4961475a41ffe6157746 | <ide><path>keras/layers/core.py
<ide> def __init__(self, layers, mode='sum', concat_axis=-1):
<ide> '''
<ide> if len(layers) < 2:
<ide> raise Exception("Please specify two or more input layers (or containers) to merge")
<del> if mode not in {'sum', 'mul', 'concat', 'ave'}:
<add> if mode not in {'sum', 'mul', 'concat', 'ave', 'join'}:
<ide> raise Exception("Invalid merge mode: " + str(mode))
<ide> self.mode = mode
<ide> self.concat_axis = concat_axis
<ide> def output_shape(self):
<ide> for shape in input_shapes[1:]:
<ide> output_shape[self.concat_axis] += shape[self.concat_axis]
<ide> return tuple(output_shape)
<add> elif self.mode == 'join':
<add> return None
<ide>
<ide> def get_params(self):
<ide> return self.params, self.regularizers, self.constraints, self.updates | 1 |
PHP | PHP | fix parse error in 7.2 | 3fb470233cffec5de7cb570efe85c21d82e308cb | <ide><path>tests/TestCase/Console/ConsoleOptionParserTest.php
<ide> public function testHelpUnknownSubcommand()
<ide> "Other valid choices:\n" .
<ide> "\n" .
<ide> "- method",
<del> $result,
<add> $result
<ide> );
<ide> }
<ide> } | 1 |
Javascript | Javascript | remove odd inject from describe | 6c4f1391bc10ebfd76bb39d3cb7f7b3b3bff4dd5 | <ide><path>test/widgetsSpec.js
<ide> describe('widget', function() {
<ide> dealoc(element);
<ide> });
<ide>
<del> describe('ng:switch', inject(function($rootScope, $compile) {
<add> describe('ng:switch', function() {
<ide> it('should switch on value change', inject(function($rootScope, $compile) {
<ide> element = $compile(
<ide> '<ng:switch on="select">' +
<ide> describe('widget', function() {
<ide> expect($rootScope.name).toEqual(undefined);
<ide> expect(element.text()).toEqual('works');
<ide> }));
<del> }));
<add> });
<ide>
<ide>
<ide> describe('ng:include', function() { | 1 |
Text | Text | fix typo in upgrading_ruby_on_rails.md [ci-skip] | eb1a9ddd914158eb41cbb74611732652ff7f0952 | <ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> The private API of `ActiveSupport::Dependencies` has been deleted. That includes
<ide>
<ide> A few of highlights:
<ide>
<del>* If you used `ActiveSupport::Dependencies.constantize` or ``ActiveSupport::Dependencies.safe_constantize`, just change them to `String#constantize` or `String#safe_constantize`.
<add>* If you used `ActiveSupport::Dependencies.constantize` or `ActiveSupport::Dependencies.safe_constantize`, just change them to `String#constantize` or `String#safe_constantize`.
<ide>
<ide> ```ruby
<ide> ActiveSupport::Dependencies.constantize("User") # NO LONGER POSSIBLE | 1 |
Javascript | Javascript | fix bug with 'not' selectors in specifity.js | 5bce8f00d78f1cde7188156d486a89072a549a12 | <ide><path>vendor/specificity.js
<ide> // source: MooTools DOM branch -> https://raw.github.com/arian/DOM/matcher-specificity/Source/specificity.js
<ide> // changed to be compatible with our require system
<add>// change line
<add>// for (var ii = nots.length; ii--;) s += this.specificity(nots[ii]);
<add>// for (var ii = nots.length; ii--;) s += nots[ii];
<ide>
<ide> var Slick = require('slick');
<ide>
<ide> module.exports = function(selector){
<del>
<ide> var parsed = Slick.parse(selector);
<ide> var expressions = parsed.expressions;
<ide> var specificity = -1;
<ide> module.exports = function(selector){
<ide> }
<ide> }
<ide> s = b * 1e6 + c * 1e3 + d;
<del> for (var ii = nots.length; ii--;) s += this.specificity(nots[ii]);
<add> for (var ii = nots.length; ii--;) s += nots[ii];
<ide> if (s > specificity) specificity = s;
<ide> }
<ide> return specificity; | 1 |
Javascript | Javascript | update doc samples for changed file name | 185f83aca3f01020616468d98be05ad8b6a774eb | <ide><path>docs/docusaurus.config.js
<ide> module.exports = {
<ide> organizationName: 'chartjs', // Usually your GitHub org/user name.
<ide> projectName: 'chartjs.github.io', // Usually your repo name.
<ide> plugins: [require.resolve('@docusaurus/plugin-google-analytics')],
<del> scripts: ['https://www.chartjs.org/dist/VERSION/Chart.min.js'],
<add> scripts: ['https://www.chartjs.org/dist/VERSION/chart.min.js'],
<ide> themes: [require.resolve('@docusaurus/theme-live-codeblock')],
<ide> themeConfig: {
<ide> algolia: { | 1 |
Ruby | Ruby | convert non-`numeric` values to floats | 57fb74e081005806f729cb7b03320f050fa6e67b | <ide><path>activemodel/lib/active_model/validations/numericality.rb
<ide> def validate_each(record, attr_name, value)
<ide> return
<ide> end
<ide>
<del> if raw_value.is_a?(String)
<add> unless raw_value.is_a?(Numeric)
<ide> value = parse_raw_value_as_a_number(raw_value)
<ide> end
<ide> | 1 |
Python | Python | remove the async helper method | 2889da67cb15ac6d5d882781d54014286d9ae010 | <ide><path>src/flask/app.py
<ide> from werkzeug.exceptions import BadRequestKeyError
<ide> from werkzeug.exceptions import HTTPException
<ide> from werkzeug.exceptions import InternalServerError
<add>from werkzeug.local import ContextVar
<ide> from werkzeug.routing import BuildError
<ide> from werkzeug.routing import Map
<ide> from werkzeug.routing import MapAdapter
<ide> from .globals import g
<ide> from .globals import request
<ide> from .globals import session
<del>from .helpers import async_to_sync
<ide> from .helpers import get_debug_flag
<ide> from .helpers import get_env
<ide> from .helpers import get_flashed_messages
<ide> def ensure_sync(self, func: t.Callable) -> t.Callable:
<ide> .. versionadded:: 2.0
<ide> """
<ide> if iscoroutinefunction(func):
<del> return async_to_sync(func)
<add> return self.async_to_sync(func)
<ide>
<ide> return func
<ide>
<add> def async_to_sync(
<add> self, func: t.Callable[..., t.Coroutine]
<add> ) -> t.Callable[..., t.Any]:
<add> """Return a sync function that will run the coroutine function.
<add>
<add> .. code-block:: python
<add>
<add> result = app.async_to_sync(func)(*args, **kwargs)
<add>
<add> Override this method to change how the app converts async code
<add> to be synchronously callable.
<add>
<add> .. versionadded:: 2.0
<add> """
<add> try:
<add> from asgiref.sync import async_to_sync as asgiref_async_to_sync
<add> except ImportError:
<add> raise RuntimeError(
<add> "Install Flask with the 'async' extra in order to use async views."
<add> )
<add>
<add> # Check that Werkzeug isn't using its fallback ContextVar class.
<add> if ContextVar.__module__ == "werkzeug.local":
<add> raise RuntimeError(
<add> "Async cannot be used with this combination of Python "
<add> "and Greenlet versions."
<add> )
<add>
<add> return asgiref_async_to_sync(func)
<add>
<ide> def make_response(self, rv: ResponseReturnValue) -> Response:
<ide> """Convert the return value from a view function to an instance of
<ide> :attr:`response_class`.
<ide><path>src/flask/helpers.py
<ide>
<ide> import werkzeug.utils
<ide> from werkzeug.exceptions import NotFound
<del>from werkzeug.local import ContextVar
<ide> from werkzeug.routing import BuildError
<ide> from werkzeug.urls import url_quote
<ide>
<ide> def is_ip(value: str) -> bool:
<ide> return True
<ide>
<ide> return False
<del>
<del>
<del>def async_to_sync(func: t.Callable[..., t.Coroutine]) -> t.Callable[..., t.Any]:
<del> """Return a sync function that will run the coroutine function *func*.
<del>
<del> This can be used as so
<del>
<del> result = async_to_async(func)(*args, **kwargs)
<del> """
<del> try:
<del> from asgiref.sync import async_to_sync as asgiref_async_to_sync
<del> except ImportError:
<del> raise RuntimeError(
<del> "Install Flask with the 'async' extra in order to use async views."
<del> )
<del>
<del> # Check that Werkzeug isn't using its fallback ContextVar class.
<del> if ContextVar.__module__ == "werkzeug.local":
<del> raise RuntimeError(
<del> "Async cannot be used with this combination of Python & Greenlet versions."
<del> )
<del>
<del> return asgiref_async_to_sync(func)
<ide><path>tests/test_async.py
<ide> from flask import Blueprint
<ide> from flask import Flask
<ide> from flask import request
<del>from flask.helpers import async_to_sync
<ide>
<ide> pytest.importorskip("asgiref")
<ide>
<ide> async def bp_after(response):
<ide>
<ide> @pytest.mark.skipif(sys.version_info >= (3, 7), reason="should only raise Python < 3.7")
<ide> def test_async_runtime_error():
<add> app = Flask(__name__)
<ide> with pytest.raises(RuntimeError):
<del> async_to_sync(None)
<add> app.async_to_sync(None) | 3 |
Javascript | Javascript | fix error messages in server/export.js | 27f517d27d1d261eb7209e244536c5b7659ee1cc | <ide><path>server/export.js
<ide> export default async function (dir, options) {
<ide> // Get the exportPathMap from the `next.config.js`
<ide> if (typeof config.exportPathMap !== 'function') {
<ide> printAndExit(
<del> '> Could not found "exportPathMap" function inside "next.config.js"\n' +
<del> '> "next export" uses that function build html pages.'
<add> '> Could not find "exportPathMap" function inside "next.config.js"\n' +
<add> '> "next export" uses that function to build html pages.'
<ide> )
<ide> }
<ide> | 1 |
Javascript | Javascript | remove unnecessary asserts in core | 01a55ee8cb2798217c8507fac8ac65249c105d54 | <ide><path>lib/internal/http2/core.js
<ide> function onSessionTrailers(id) {
<ide> assert(stream !== undefined,
<ide> 'Internal HTTP/2 Failure. Stream does not exist. Please ' +
<ide> 'report this as a bug in Node.js');
<del> const getTrailers = stream[kState].getTrailers;
<del> // We should not have been able to get here at all if getTrailers
<del> // was not a function, and there's no code that could have changed
<del> // it between there and here.
<del> assert.strictEqual(typeof getTrailers, 'function');
<ide> const trailers = Object.create(null);
<del> getTrailers.call(stream, trailers);
<add> stream[kState].getTrailers.call(stream, trailers);
<ide> const headersList = mapToHeaders(trailers, assertValidPseudoHeaderTrailer);
<ide> if (!Array.isArray(headersList)) {
<ide> process.nextTick(emit, stream, 'error', headersList);
<ide> function onGoawayData(code, lastStreamID, buf) {
<ide> // maxPayloadLen. The method must return a numeric value within the range
<ide> // frameLen <= n <= maxPayloadLen.
<ide> function onSelectPadding(fn) {
<del> assert(typeof fn === 'function',
<del> 'options.selectPadding must be a function. Please report this as a ' +
<del> 'bug in Node.js');
<ide> return function getPadding() {
<ide> debug('fetching padding for frame');
<ide> const frameLen = paddingBuffer[PADDING_BUF_FRAME_LENGTH]; | 1 |
Mixed | Javascript | restrict addendpoint to before quicsocket bind | b80108c033325c00dabbde945522e7f3535a3977 | <ide><path>doc/api/quic.md
<ide> added: REPLACEME
<ide> **Default**: `'udp4'`.
<ide> * Returns: {QuicEndpoint}
<ide>
<del>Creates and adds a new `QuicEndpoint` to the `QuicSocket` instance.
<add>Creates and adds a new `QuicEndpoint` to the `QuicSocket` instance. An
<add>error will be thrown if `quicsock.addEndpoint()` is called either after
<add>the `QuicSocket` has already started binding to the local ports or after
<add>the `QuicSocket` has been destroyed.
<ide>
<ide> #### quicsocket.bound
<ide> <!-- YAML
<ide><path>lib/internal/quic/core.js
<ide> class QuicSocket extends EventEmitter {
<ide> });
<ide> }
<ide>
<add> // A QuicSocket will typically bind only to a single local port, but it is
<add> // possible to bind to multiple, even if those use different IP families
<add> // (e.g. IPv4 or IPv6). Calls to addEndpoint() must be made before the
<add> // QuicSocket is bound (e.g. before any calls to listen() or connect()).
<ide> addEndpoint(options = {}) {
<ide> const state = this[kInternalState];
<ide> if (this.destroyed)
<ide> throw new ERR_INVALID_STATE('QuicSocket is already destroyed');
<del>
<del> // TODO(@jasnell): Also forbid adding an endpoint if
<del> // the QuicSocket is closing.
<add> if (state.state !== kSocketUnbound)
<add> throw new ERR_INVALID_STATE('QuicSocket is already being bound');
<ide>
<ide> const endpoint = new QuicEndpoint(this, options);
<ide> state.endpoints.add(endpoint);
<del>
<del> // If the QuicSocket is already bound at this point,
<del> // also bind the newly created QuicEndpoint.
<del> if (state.state !== kSocketUnbound)
<del> endpoint[kMaybeBind]();
<del>
<ide> return endpoint;
<ide> }
<ide>
<ide><path>test/parallel/test-quic-quicendpoint-address.js
<ide> async function Test2() {
<ide>
<ide> server.listen({ key, cert, ca, alpn: 'zzz' });
<ide>
<add> // Attempting to add an endpoint after fails.
<add> assert.throws(() => server.addEndpoint(), {
<add> code: 'ERR_INVALID_STATE'
<add> });
<add>
<ide> await once(server, 'ready');
<ide>
<ide> assert.strictEqual(server.endpoints.length, 2); | 3 |
Javascript | Javascript | buffer data to only emit 'line' on '\n' | e28f77cbad1dea617aeda18513b61e6ecce8e294 | <ide><path>lib/readline.js
<ide> Interface.prototype.write = function(d, key) {
<ide> this.terminal ? this._ttyWrite(d, key) : this._normalWrite(d, key);
<ide> };
<ide>
<add>// telnet on windows sends every single keystroke seperately, so we need
<add>// to buffer them and only fire the 'line' event when a \n is sent
<add>Interface.prototype._line_buffer = '';
<ide>
<ide> Interface.prototype._normalWrite = function(b) {
<del> // Very simple implementation right now. Should try to break on
<del> // new lines.
<del> if (b !== undefined)
<del> this._onLine(b.toString());
<add> if (b === undefined) {
<add> return;
<add> }
<add> this._line_buffer += b.toString();
<add> if (this._line_buffer.indexOf('\n') !== -1) {
<add> var lines = this._line_buffer.split('\n');
<add> // either '' or (concievably) the unfinished portion of the next line
<add> this._line_buffer = lines.pop();
<add> lines.forEach(function(line) {
<add> this._onLine(line + '\n');
<add> }, this);
<add> }
<ide> };
<ide>
<ide> Interface.prototype._insertString = function(c) {
<ide><path>test/simple/test-readline-interface.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>
<add>
<add>var assert = require('assert');
<add>var readline = require('readline');
<add>var EventEmitter = require('events').EventEmitter;
<add>var inherits = require('util').inherits;
<add>
<add>function FakeInput() {
<add> EventEmitter.call(this);
<add>}
<add>inherits(FakeInput, EventEmitter);
<add>FakeInput.prototype.resume = function() {};
<add>
<add>var fi;
<add>var rli;
<add>var called;
<add>
<add>// sending a full line
<add>fi = new FakeInput();
<add>rli = new readline.Interface(fi, {});
<add>called = false;
<add>rli.on('line', function(line) {
<add> called = true;
<add> assert.equal(line, 'asdf\n');
<add>});
<add>fi.emit('data', 'asdf\n');
<add>assert.ok(called);
<add>
<add>// sending a blank line
<add>fi = new FakeInput();
<add>rli = new readline.Interface(fi, {});
<add>called = false;
<add>rli.on('line', function(line) {
<add> called = true;
<add> assert.equal(line, '\n');
<add>});
<add>fi.emit('data', '\n');
<add>assert.ok(called);
<add>
<add>// sending a single character with no newline
<add>fi = new FakeInput();
<add>rli = new readline.Interface(fi, {});
<add>called = false;
<add>rli.on('line', function(line) {
<add> called = true;
<add>});
<add>fi.emit('data', 'a');
<add>assert.ok(!called);
<add>
<add>// sending a single character with no newline and then a newline
<add>fi = new FakeInput();
<add>rli = new readline.Interface(fi, {});
<add>called = false;
<add>rli.on('line', function(line) {
<add> called = true;
<add> assert.equal(line, 'a\n');
<add>});
<add>fi.emit('data', 'a');
<add>assert.ok(!called);
<add>fi.emit('data', '\n');
<add>assert.ok(called);
<add>
<add>// sending multiple newlines at once
<add>fi = new FakeInput();
<add>rli = new readline.Interface(fi, {});
<add>var expectedLines = ['foo\n', 'bar\n', 'baz\n'];
<add>var callCount = 0;
<add>rli.on('line', function(line) {
<add> assert.equal(line, expectedLines[callCount]);
<add> callCount++;
<add>});
<add>fi.emit('data', expectedLines.join(''));
<add>assert.equal(callCount, expectedLines.length);
<add>
<add>// sending multiple newlines at once that does not end with a new line
<add>fi = new FakeInput();
<add>rli = new readline.Interface(fi, {});
<add>var expectedLines = ['foo\n', 'bar\n', 'baz\n', 'bat'];
<add>var callCount = 0;
<add>rli.on('line', function(line) {
<add> assert.equal(line, expectedLines[callCount]);
<add> callCount++;
<add>});
<add>fi.emit('data', expectedLines.join(''));
<add>assert.equal(callCount, expectedLines.length - 1); | 2 |
Javascript | Javascript | make diff across dst work | efa67e82c0f1f0fb939e458c15a7e41b235b42d3 | <ide><path>moment.js
<ide>
<ide> diff : function (input, val, asFloat) {
<ide> var inputMoment = moment(input),
<del> diff = this._d - inputMoment._d,
<add> zoneDiff = (this.zone() - inputMoment.zone()) * 6e4,
<add> diff = this._d - inputMoment._d - zoneDiff,
<ide> year = this.year() - inputMoment.year(),
<ide> month = this.month() - inputMoment.month(),
<ide> date = this.date() - inputMoment.date(),
<ide> output;
<add>
<ide> if (val === 'months') {
<ide> output = year * 12 + month + date / 30;
<ide> } else if (val === 'years') {
<ide><path>sitesrc/js/unit-tests.js
<ide> test("diff month", 1, function() {
<ide> equal(moment([2011, 0, 31]).diff([2011, 2, 1], 'months'), -1, "month diff");
<ide> });
<ide>
<del>test("diff week", 1, function() {
<del> equal(moment([2012, 2, 18]).diff([2012], 'weeks'), 12, "week diff");
<add>test("diff across DST", 2, function() {
<add> equal(moment([2012, 2, 24]).diff([2012, 2, 10], 'weeks', true), 2, "diff weeks across DST");
<add> equal(moment([2012, 2, 24]).diff([2012, 2, 10], 'days', true), 14, "diff weeks across DST");
<ide> });
<ide>
<ide> test("diff overflow", 4, function() { | 2 |
Go | Go | replace "sleep" by "top" in test implementation | e5b7f61f090bfc951590dd5dad3f6bb1ce3888ba | <ide><path>integration-cli/docker_api_containers_test.go
<ide> type containerPs struct {
<ide> func (s *DockerSuite) TestContainerPsOmitFields(c *check.C) {
<ide> name := "pstest"
<ide> port := 80
<del> runCmd := exec.Command(dockerBinary, "run", "-d", "--name", name, "--expose", strconv.Itoa(port), "busybox", "sleep", "5")
<add> runCmd := exec.Command(dockerBinary, "run", "-d", "--name", name, "--expose", strconv.Itoa(port), "busybox", "top")
<ide> _, err := runCommand(runCmd)
<ide> c.Assert(err, check.IsNil)
<ide> | 1 |
Javascript | Javascript | update current challenge logic | 42aae365f6ef33d2f1851c1ba66e9476082c7c8d | <ide><path>server/boot/challenge.js
<ide> module.exports = function(app) {
<ide> req.user.currentChallenge.challengeBlock = '0';
<ide> req.user.currentChallenge.dashedName =
<ide> challengeMapWithDashedNames['0'][0];
<del> req.user.save(function(err) {
<del> if (err) {
<del> return next(err);
<del> }
<del> });
<ide> }
<ide>
<del> var nameString = req.user.currentChallenge.dashedName =
<del> challengeMapWithDashedNames['0'][0];
<add> var nameString = req.user.currentChallenge.dashedName;
<ide>
<ide> req.user.save(function(err) {
<ide> if (err) { | 1 |
Ruby | Ruby | add rubocop to combine multiple calls | 06518ec6132d4191daed18ee4352d5746af6573b | <ide><path>Library/Homebrew/rubocops/lines.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> EOS
<ide> end
<ide>
<add> # This cop makes sure that the `generate_completions_from_executable` DSL is used with only
<add> # a single, combined call for all shells.
<add> #
<add> # @api private
<add> class SingleGenerateCompletionsDSLCall < FormulaCop
<add> extend AutoCorrector
<add>
<add> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<add> install = find_method_def(body_node, :install)
<add>
<add> methods = find_every_method_call_by_name(install, :generate_completions_from_executable)
<add> return if methods.length <= 1
<add>
<add> offenses = []
<add> shells = []
<add> methods.each do |method|
<add> next unless method.source.include?("shells:")
<add>
<add> shells << method.source.match(/shells: \[(:bash|:zsh|:fish)\]/).captures.first
<add> offenses << method
<add> end
<add>
<add> return if offenses.blank?
<add>
<add> offenses[0...-1].each do |node|
<add> offending_node(node)
<add> problem "Use a single `generate_completions_from_executable` call
<add> combining all specified shells" do |corrector|
<add> corrector.replace(@offensive_node.source_range, "")
<add> end
<add> end
<add>
<add> offending_node(offenses.last)
<add> replacement = if (shells - %w[:bash :zsh :fish]).empty?
<add> @offensive_node.source.sub(/shells: \[(:bash|:zsh|:fish)\]/, "")
<add> .gsub(",,", ",")
<add> .sub(", )", ")")
<add> .sub("(, ", "(")
<add> .sub("()", "")
<add> else
<add> @offensive_node.source.sub(/shells: \[(:bash|:zsh|:fish)\]/,
<add> "shells: [#{shells.join(", ")}]")
<add> end
<add>
<add> problem "Use `#{replacement}` instead of `#{@offensive_node.source}`." do |corrector|
<add> corrector.replace(@offensive_node.source_range, replacement)
<add> end
<add> end
<add> end
<add>
<ide> # This cop checks for other miscellaneous style violations.
<ide> #
<ide> # @api private | 1 |
PHP | PHP | use makelistener for wildcards | 4acd4185d2c672e55e24891c7c5483f987790a29 | <ide><path>src/Illuminate/Events/Dispatcher.php
<ide> public function listen($event, $listener, $priority = 0)
<ide> */
<ide> protected function setupWildcardListen($event, $listener, $priority)
<ide> {
<del> $this->wildcards[$event][] = $listener;
<add> $this->wildcards[$event][] = $this->makeListener($listener);
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | use callback form for redux batch example | e3f8dceac3fb6dc6485e5de29a7c0fe34813be1a | <ide><path>docs/introduction/Ecosystem.md
<ide> const store = configureStore({
<ide> Store enhancer that allows dispatching arrays of actions
<ide>
<ide> ```js
<del>const store = configureStore({ reducer, enhancers: [reduxBatch] })
<add>const store = configureStore({ reducer, enhancers: (existingEnhancersArray) => [reduxBatch, ...existingEnhancersArray, reduxBatch] })
<ide> store.dispatch([{ type: 'INCREMENT' }, { type: 'INCREMENT' }])
<ide> ```
<ide> | 1 |
Text | Text | fix code examples in `crypto.md` | ade5fd41002cefe1c0c299d9a8eb75a978e48dc8 | <ide><path>doc/api/crypto.md
<ide> Example: Using `Cipher` and piped streams:
<ide> import {
<ide> createReadStream,
<ide> createWriteStream,
<del>} from 'fs';
<add>} from 'node:fs';
<ide>
<ide> import {
<ide> pipeline
<del>} from 'stream';
<add>} from 'node:stream';
<ide>
<ide> const {
<ide> scrypt,
<ide> const decipher = createDecipheriv(algorithm, key, iv);
<ide>
<ide> let decrypted = '';
<ide> decipher.on('readable', () => {
<add> let chunk;
<ide> while (null !== (chunk = decipher.read())) {
<ide> decrypted += chunk.toString('utf8');
<ide> }
<ide> const decipher = createDecipheriv(algorithm, key, iv);
<ide>
<ide> let decrypted = '';
<ide> decipher.on('readable', () => {
<add> let chunk;
<ide> while (null !== (chunk = decipher.read())) {
<ide> decrypted += chunk.toString('utf8');
<ide> }
<ide> Example: Using `Decipher` and piped streams:
<ide> import {
<ide> createReadStream,
<ide> createWriteStream,
<del>} from 'fs';
<add>} from 'node:fs';
<ide> import { Buffer } from 'node:buffer';
<ide> const {
<ide> scryptSync,
<ide> Example: generating the sha256 sum of a file
<ide> ```mjs
<ide> import {
<ide> createReadStream
<del>} from 'fs';
<add>} from 'node:fs';
<ide> import { argv } from 'node:process';
<ide> const {
<ide> createHash
<ide> Example: generating the sha256 HMAC of a file
<ide> ```mjs
<ide> import {
<ide> createReadStream
<del>} from 'fs';
<add>} from 'node:fs';
<ide> import { argv } from 'node:process';
<ide> const {
<ide> createHmac | 1 |
Python | Python | honor the newline parameter | 1c6b56a92267a4fb5092dd6df1e6ccf113115944 | <ide><path>celery/bin/celeryd_multi.py
<ide> def execute_from_commandline(self, argv, cmd='celeryd'):
<ide> return self.retcode
<ide>
<ide> def say(self, m, newline=True):
<del> self.fh.write('%s\n' % m if m else m)
<add> self.fh.write('%s%s' % (m, '\n' if newline else ''))
<ide>
<ide> def names(self, argv, cmd):
<ide> p = NamespacedOptionParser(argv) | 1 |
Text | Text | fix small grammar issue introduced in | cd6605438dd1c765d206ff4bd54ea2d33884821d | <ide><path>guides/source/5_0_release_notes.md
<ide> Please refer to the [Changelog][active-record] for detailed changes.
<ide> were getting rescued and printed in the logs, unless you used
<ide> the (newly deprecated) `raise_in_transactional_callbacks = true` option.
<ide>
<del> Now these errors are not rescued anymore and just bubble up, as the other callbacks.
<add> Now these errors are not rescued anymore and just bubble up, matching the
<add> behavior of other callbacks.
<ide> ([commit](https://github.com/rails/rails/commit/07d3d402341e81ada0214f2cb2be1da69eadfe72))
<ide>
<ide> Active Model | 1 |
Javascript | Javascript | add flow libdefs for `global` | b931aa735fcbefe40eccd8344ae28ab6eec06930 | <ide><path>flow/global.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow strict
<add> * @format
<add> */
<add>
<add>/**
<add> * `global` is a object containing all the global variables for React Native.
<add> *
<add> * NOTE: Consider cross-platform as well as JS environments compatibility
<add> * when defining the types here. Consider both presence (`?`) as well as
<add> * writeability (`+`) when defining types.
<add> */
<add>declare var global: {
<add> // Undeclared properties are implicitly `any`.
<add> [string | symbol]: any,
<add>}; | 1 |
PHP | PHP | add missing @return tags | 474339881d2d757d13b741d1d3abd5ea001a3c95 | <ide><path>src/Model/Behavior/TimestampBehavior.php
<ide> class TimestampBehavior extends Behavior {
<ide> * overwrite the events to listen on
<ide> *
<ide> * @param array $config The config for this behavior.
<add> * @return void
<ide> */
<ide> public function initialize(array $config) {
<ide> if (isset($config['events'])) {
<ide><path>src/Model/Behavior/TranslateBehavior.php
<ide> public function __construct(Table $table, array $config = []) {
<ide> * Initialize hook
<ide> *
<ide> * @param array $config The config for this behavior.
<add> * @return void
<ide> */
<ide> public function initialize(array $config) {
<ide> $this->setupFieldAssociations( | 2 |
Ruby | Ruby | restore autoloading test for sti | 194866854f9c38d3ff45f283a2eae835077a7152 | <ide><path>activerecord/test/cases/inheritance_test.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "active_support/inflector"
<add>require "zeitwerk"
<ide> require "cases/helper"
<ide> require "models/author"
<ide> require "models/company"
<ide> def test_new_without_storing_full_sti_class
<ide> end
<ide> end
<ide>
<add> def test_new_with_autoload_paths
<add> path = File.expand_path("../models/autoloadable", __dir__)
<add> Zeitwerk.with_loader do |loader|
<add> loader.push_dir(path)
<add> loader.setup
<add>
<add> firm = Company.new(type: "ExtraFirm")
<add> assert_equal ExtraFirm, firm.class
<add> ensure
<add> loader.unload
<add> end
<add> end
<add>
<ide> def test_inheritance_condition
<ide> assert_equal 12, Company.count
<ide> assert_equal 3, Firm.count | 1 |
Java | Java | update stomp support to reactor-netty 0.6 | 70bab23609a63903dde7112983a324748c371146 | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/ReactorNettyTcpConnection.java
<ide> public ReactorNettyTcpConnection(NettyInbound inbound, NettyOutbound outbound,
<ide>
<ide> @Override
<ide> public ListenableFuture<Void> send(Message<P> message) {
<del> ByteBuf byteBuf = this.inbound.channel().alloc().buffer();
<add> ByteBuf byteBuf = this.inbound.alloc()
<add> .buffer();
<ide> this.encoder.accept(byteBuf, message);
<del> return new MonoToListenableFutureAdapter<>(this.outbound.send(Mono.just(byteBuf)));
<add> return new MonoToListenableFutureAdapter<>(this.outbound.send(Mono.just(byteBuf)
<add> .then()));
<ide> }
<ide>
<ide> @Override | 1 |
Python | Python | fix scimath.power for negative integer input | 1031df26af6d9b209458fb229a987247bf2d5497 | <ide><path>numpy/lib/scimath.py
<ide> def _fix_real_lt_zero(x):
<ide> x = _tocomplex(x)
<ide> return x
<ide>
<add>def _fix_int_lt_zero(x):
<add> x = asarray(x)
<add> if any(isreal(x) & (x < 0)):
<add> x = x * 1.0
<add> return x
<add>
<ide> def _fix_real_abs_gt_1(x):
<ide> x = asarray(x)
<ide> if any(isreal(x) & (abs(x)>1)):
<ide> def log2(x):
<ide>
<ide> def power(x, p):
<ide> x = _fix_real_lt_zero(x)
<add> p = _fix_int_lt_zero(p)
<ide> return nx.power(x, p)
<ide>
<ide> def arccos(x): | 1 |
Ruby | Ruby | avoid intermediate option objects | 11f880801c1ccf11a9fc2a1d0dc469dbba8b2a15 | <ide><path>Library/Homebrew/formula_installer.rb
<ide> def sanitized_ARGV_options
<ide> end
<ide>
<ide> def build_argv
<del> Options.create(sanitized_ARGV_options) + options
<add> sanitized_ARGV_options + options.as_flags
<ide> end
<ide>
<ide> def build | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.