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 | add unit tests for vectorized quicksort | 12d02f582c2f6a2694ebbe19e651d127c2bbf754 | <ide><path>numpy/core/tests/test_multiarray.py
<ide> def test_non_c_contiguous(self):
<ide> [[1284, 1798], [4368, 4882]],
<ide> [[2312, 2826], [5396, 5910]]]
<ide> assert_array_equal(x.view('<i2'), expected)
<add>
<add>
<add>## Test various array sizes that hit different code paths in quicksort-avx512
<add>@pytest.mark.parametrize("N", \
<add> [8,16,24,32,48,64,96,128,151,191,256,383,512,1023,2047])
<add>def test_sort_float(N):
<add> ## Regular data with nan sprinkled
<add> np.random.seed(42)
<add> arr = -0.5 + np.random.sample(N).astype('f')
<add> arr[np.random.choice(arr.shape[0], 3)] = np.nan
<add> assert_equal(np.sort(arr, kind='quick'), np.sort(arr, kind='heap'))
<add>
<add> ## (2) with +INF
<add> infarr = np.inf*np.ones(N, dtype='f')
<add> infarr[np.random.choice(infarr.shape[0], 5)] = -1.0
<add> assert_equal(np.sort(infarr, kind='quick'), np.sort(infarr, kind='heap'))
<add>
<add> ## (3) with -INF
<add> neginfarr = -np.inf*np.ones(N, dtype='f')
<add> neginfarr[np.random.choice(neginfarr.shape[0], 5)] = 1.0
<add> assert_equal(np.sort(neginfarr, kind='quick'),
<add> np.sort(neginfarr, kind='heap'))
<add>
<add> ## (4) with +/-INF
<add> infarr = np.inf*np.ones(N, dtype='f')
<add> infarr[np.random.choice(infarr.shape[0], (int)(N/2))] = -np.inf
<add> assert_equal(np.sort(infarr, kind='quick'), np.sort(infarr, kind='heap'))
<add>
<add>def test_sort_int():
<add> ## Random data with NPY_MAX_INT32 and NPY_MIN_INT32 sprinkled
<add> np.random.seed(42)
<add> N = 2047
<add> minv = np.iinfo(np.int32).min
<add> maxv = np.iinfo(np.int32).max
<add> arr = np.random.randint(low=minv, high=maxv, size=10).astype('int32')
<add> arr[np.random.choice(arr.shape[0], 10)] = minv
<add> arr[np.random.choice(arr.shape[0], 10)] = maxv
<add> assert_equal(np.sort(arr, kind='quick'), np.sort(arr, kind='heap'))
<add>
<add>def test_sort_uint():
<add> ## Random data with NPY_MAX_UINT32 sprinkled
<add> np.random.seed(42)
<add> N = 2047
<add> maxv = np.iinfo(np.uint32).max
<add> arr = np.random.randint(low=0, high=maxv, size=10).astype('uint32')
<add> arr[np.random.choice(arr.shape[0], 10)] = maxv
<add> assert_equal(np.sort(arr, kind='quick'), np.sort(arr, kind='heap')) | 1 |
Go | Go | ignore socket rm errors on daemon suite teardown | e34244842ca968ff96769d1b5eab52fecddee80d | <ide><path>integration-cli/check_test.go
<ide> import (
<ide> "testing"
<ide>
<ide> "github.com/docker/docker/cliconfig"
<del> "github.com/docker/docker/pkg/integration/checker"
<ide> "github.com/docker/docker/pkg/reexec"
<ide> "github.com/docker/engine-api/types/swarm"
<ide> "github.com/go-check/check"
<ide> func (s *DockerDaemonSuite) TearDownTest(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerDaemonSuite) TearDownSuite(c *check.C) {
<del> err := filepath.Walk(daemonSockRoot, func(path string, fi os.FileInfo, err error) error {
<add> filepath.Walk(daemonSockRoot, func(path string, fi os.FileInfo, err error) error {
<ide> if err != nil {
<del> return err
<add> // ignore errors here
<add> // not cleaning up sockets is not really an error
<add> return nil
<ide> }
<ide> if fi.Mode() == os.ModeSocket {
<ide> syscall.Unlink(path)
<ide> }
<ide> return nil
<ide> })
<del> c.Assert(err, checker.IsNil, check.Commentf("error while cleaning up daemon sockets"))
<del> err = os.RemoveAll(daemonSockRoot)
<del> c.Assert(err, checker.IsNil, check.Commentf("could not cleanup daemon socket root"))
<add> os.RemoveAll(daemonSockRoot)
<ide> }
<ide>
<ide> const defaultSwarmPort = 2477 | 1 |
Ruby | Ruby | allow debugging patch failures | 8cc5aabfcf2a5ae8413ec7222b971c18daa69697 | <ide><path>Library/Homebrew/debrew.rb
<ide> def raise(*)
<ide> end
<ide>
<ide> module Formula
<del> def install
<add> def brew
<ide> Debrew.debrew { super }
<ide> end
<ide> | 1 |
Javascript | Javascript | remove remnants of the load event alias handling | 38a669735d08bcbd28cfb0d77eee82c67aa89eeb | <ide><path>src/ajax/load.js
<ide> define([
<ide> "../ajax",
<ide> "../traversing",
<ide> "../manipulation",
<del> "../selector",
<del> // Optional event/alias dependency
<del> "../event/alias"
<add> "../selector"
<ide> ], function( jQuery ) {
<ide>
<del>// Keep a copy of the old load method
<del>var _load = jQuery.fn.load;
<del>
<ide> /**
<ide> * Load a url into a page
<ide> */
<ide> jQuery.fn.load = function( url, params, callback ) {
<del> if ( typeof url !== "string" && _load ) {
<del> return _load.apply( this, arguments );
<del> }
<del>
<ide> var selector, type, response,
<ide> self = this,
<ide> off = url.indexOf(" "); | 1 |
Javascript | Javascript | fix awkward wording | dc5bba861582d32e7db67be4ec383a14aff9f88d | <ide><path>src/ng/directive/ngBind.js
<ide> var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate
<ide> * @name ngBindHtml
<ide> *
<ide> * @description
<del> * Creates a binding that will innerHTML the result of evaluating the `expression` into the current
<del> * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link
<del> * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize`
<del> * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in
<del> * core Angular). In order to use {@link ngSanitize} in your module's dependencies, you need to
<del> * include "angular-sanitize.js" in your application.
<add> * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
<add> * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
<add> * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
<add> * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
<add> * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
<ide> *
<ide> * You may also bypass sanitization for values you know are safe. To do so, bind to
<ide> * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example | 1 |
Javascript | Javascript | remove incorrect debug() in test-policy-integrity | 4f7440cd88dd6e6fb08945f85fc72eec9156f5fa | <ide><path>test/pummel/test-policy-integrity.js
<ide> for (const permutation of permutations({
<ide> );
<ide> }
<ide> debug(`spawning ${tests.size} policy integrity permutations`);
<del>debug(
<del> 'use NODE_DEBUG=test:policy-integrity:NUMBER to log a specific permutation'
<del>);
<add>
<ide> for (const config of tests) {
<ide> const parsed = JSON.parse(config);
<ide> tests.delete(config); | 1 |
Javascript | Javascript | remove explicit requires of map and set | c95071e7d22115657ad9ca34321aa33d8aace443 | <ide><path>Libraries/BugReporting/BugReporting.js
<ide> 'use strict';
<ide>
<ide> const RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
<del>const Map = require('Map');
<ide> const infoLog = require('infoLog');
<ide>
<ide> import type EmitterSubscription from 'EmitterSubscription';
<ide><path>Libraries/Experimental/WindowedListView.js
<ide> const Batchinator = require('Batchinator');
<ide> const IncrementalGroup = require('IncrementalGroup');
<ide> const React = require('React');
<ide> const ScrollView = require('ScrollView');
<del>const Set = require('Set');
<ide> const StyleSheet = require('StyleSheet');
<ide> const Systrace = require('Systrace');
<ide> const View = require('View');
<ide><path>Libraries/Interaction/InteractionManager.js
<ide>
<ide> const BatchedBridge = require('BatchedBridge');
<ide> const EventEmitter = require('EventEmitter');
<del>const Set = require('Set');
<ide> const TaskQueue = require('TaskQueue');
<ide>
<ide> const infoLog = require('infoLog');
<ide><path>Libraries/JSInspector/NetworkAgent.js
<ide>
<ide> const InspectorAgent = require('InspectorAgent');
<ide> const JSInspector = require('JSInspector');
<del>const Map = require('Map');
<ide> const XMLHttpRequest = require('XMLHttpRequest');
<ide>
<ide> import type EventSender from 'InspectorAgent';
<ide><path>Libraries/Network/NetInfo.js
<ide>
<ide> 'use strict';
<ide>
<del>const Map = require('Map');
<ide> const NativeEventEmitter = require('NativeEventEmitter');
<ide> const NativeModules = require('NativeModules');
<ide> const Platform = require('Platform'); | 5 |
Ruby | Ruby | flip deferrable autoload convention | ace20bd25e3818b7f29c222643dd445c48b36425 | <ide><path>actionmailer/lib/action_mailer.rb
<ide> module ActionMailer
<ide> extend ::ActiveSupport::Autoload
<ide>
<del> autoload :AdvAttrAccessor
<del> autoload :DeprecatedBody
<del> autoload :Base
<del> autoload :DeliveryMethod
<del> autoload :MailHelper
<del> autoload :Part
<del> autoload :PartContainer
<del> autoload :Quoting
<del> autoload :TestHelper
<del> autoload :Utils
<add> eager_autoload do
<add> autoload :AdvAttrAccessor
<add> autoload :DeprecatedBody
<add> autoload :Base
<add> autoload :DeliveryMethod
<add> autoload :MailHelper
<add> autoload :Part
<add> autoload :PartContainer
<add> autoload :Quoting
<add> autoload :TestHelper
<add> autoload :Utils
<add> end
<ide> end
<ide>
<ide> module Text
<ide> extend ActiveSupport::Autoload
<ide>
<del> autoload :Format, 'action_mailer/vendor/text_format'
<add> eager_autoload do
<add> autoload :Format, 'action_mailer/vendor/text_format'
<add> end
<ide> end
<ide>
<ide> module Net
<ide> extend ActiveSupport::Autoload
<ide>
<del> autoload :SMTP
<add> eager_autoload do
<add> autoload :SMTP
<add> end
<ide> end
<ide>
<del>
<ide> require 'action_mailer/vendor/tmail'
<ide><path>actionpack/lib/abstract_controller.rb
<ide> module AbstractController
<ide> extend ActiveSupport::Autoload
<ide>
<del> deferrable do
<del> autoload :Base
<del> autoload :Callbacks
<del> autoload :Helpers
<del> autoload :Layouts
<del> autoload :LocalizedCache
<del> autoload :Logger
<del> autoload :Rendering
<del> end
<add> autoload :Base
<add> autoload :Callbacks
<add> autoload :Helpers
<add> autoload :Layouts
<add> autoload :LocalizedCache
<add> autoload :Logger
<add> autoload :Rendering
<ide> end
<ide><path>actionpack/lib/action_controller.rb
<ide> module ActionController
<ide> extend ActiveSupport::Autoload
<ide>
<del> deferrable do
<del> autoload :Base
<del> autoload :Caching
<del> autoload :PolymorphicRoutes
<del> autoload :Translation
<del> autoload :Metal
<del> autoload :Middleware
<add> autoload :Base
<add> autoload :Caching
<add> autoload :PolymorphicRoutes
<add> autoload :Translation
<add> autoload :Metal
<add> autoload :Middleware
<ide>
<del> autoload_under "metal" do
<del> autoload :Benchmarking
<del> autoload :ConditionalGet
<del> autoload :Configuration
<del> autoload :Head
<del> autoload :Helpers
<del> autoload :HideActions
<del> autoload :Layouts
<del> autoload :Logger
<del> autoload :MimeResponds
<del> autoload :RackDelegation
<del> autoload :Compatibility
<del> autoload :Redirecting
<del> autoload :Rendering
<del> autoload :Renderers
<del> autoload :Rescue
<del> autoload :Responder
<del> autoload :SessionManagement
<del> autoload :UrlFor
<del> autoload :Verification
<del> autoload :Flash
<del> autoload :RequestForgeryProtection
<del> autoload :Streaming
<del> autoload :HttpAuthentication
<del> autoload :FilterParameterLogging
<del> autoload :Cookies
<del> end
<del>
<del> autoload :Dispatcher, 'action_controller/dispatch/dispatcher'
<del> autoload :PerformanceTest, 'action_controller/deprecated/performance_test'
<del> autoload :Routing, 'action_controller/deprecated'
<del> autoload :Integration, 'action_controller/deprecated/integration_test'
<del> autoload :IntegrationTest, 'action_controller/deprecated/integration_test'
<add> autoload_under "metal" do
<add> autoload :Benchmarking
<add> autoload :ConditionalGet
<add> autoload :Configuration
<add> autoload :Head
<add> autoload :Helpers
<add> autoload :HideActions
<add> autoload :Layouts
<add> autoload :Logger
<add> autoload :MimeResponds
<add> autoload :RackDelegation
<add> autoload :Compatibility
<add> autoload :Redirecting
<add> autoload :Rendering
<add> autoload :Renderers
<add> autoload :Rescue
<add> autoload :Responder
<add> autoload :SessionManagement
<add> autoload :UrlFor
<add> autoload :Verification
<add> autoload :Flash
<add> autoload :RequestForgeryProtection
<add> autoload :Streaming
<add> autoload :HttpAuthentication
<add> autoload :FilterParameterLogging
<add> autoload :Cookies
<ide> end
<ide>
<del> autoload :RecordIdentifier
<del> autoload :UrlRewriter
<del> autoload :UrlWriter, 'action_controller/url_rewriter'
<add> autoload :Dispatcher, 'action_controller/dispatch/dispatcher'
<add> autoload :PerformanceTest, 'action_controller/deprecated/performance_test'
<add> autoload :Routing, 'action_controller/deprecated'
<add> autoload :Integration, 'action_controller/deprecated/integration_test'
<add> autoload :IntegrationTest, 'action_controller/deprecated/integration_test'
<ide>
<del> # TODO: Don't autoload exceptions, setup explicit
<del> # requires for files that need them
<del> autoload_at "action_controller/metal/exceptions" do
<del> autoload :ActionControllerError
<del> autoload :RenderError
<del> autoload :RoutingError
<del> autoload :MethodNotAllowed
<del> autoload :NotImplemented
<del> autoload :UnknownController
<del> autoload :MissingFile
<del> autoload :RenderError
<del> autoload :SessionOverflowError
<del> autoload :UnknownHttpMethod
<add> eager_autoload do
<add> autoload :RecordIdentifier
<add> autoload :UrlRewriter
<add> autoload :UrlWriter, 'action_controller/url_rewriter'
<add>
<add> # TODO: Don't autoload exceptions, setup explicit
<add> # requires for files that need them
<add> autoload_at "action_controller/metal/exceptions" do
<add> autoload :ActionControllerError
<add> autoload :RenderError
<add> autoload :RoutingError
<add> autoload :MethodNotAllowed
<add> autoload :NotImplemented
<add> autoload :UnknownController
<add> autoload :MissingFile
<add> autoload :RenderError
<add> autoload :SessionOverflowError
<add> autoload :UnknownHttpMethod
<add> end
<ide> end
<ide> end
<ide>
<ide><path>actionpack/lib/action_controller/caching.rb
<ide> module Caching
<ide> extend ActiveSupport::Concern
<ide> extend ActiveSupport::Autoload
<ide>
<del> autoload :Actions
<del> autoload :Fragments
<del> autoload :Pages
<del> autoload :Sweeper, 'action_controller/caching/sweeping'
<del> autoload :Sweeping, 'action_controller/caching/sweeping'
<add> eager_autoload do
<add> autoload :Actions
<add> autoload :Fragments
<add> autoload :Pages
<add> autoload :Sweeper, 'action_controller/caching/sweeping'
<add> autoload :Sweeping, 'action_controller/caching/sweeping'
<add> end
<ide>
<ide> included do
<ide> @@cache_store = nil
<ide><path>actionpack/lib/action_controller/vendor/html-scanner.rb
<ide> module HTML
<ide> extend ActiveSupport::Autoload
<ide>
<del> autoload :CDATA, 'html/node'
<del> autoload :Document, 'html/document'
<del> autoload :FullSanitizer, 'html/sanitizer'
<del> autoload :LinkSanitizer, 'html/sanitizer'
<del> autoload :Node, 'html/node'
<del> autoload :Sanitizer, 'html/sanitizer'
<del> autoload :Selector, 'html/selector'
<del> autoload :Tag, 'html/node'
<del> autoload :Text, 'html/node'
<del> autoload :Tokenizer, 'html/tokenizer'
<del> autoload :Version, 'html/version'
<del> autoload :WhiteListSanitizer, 'html/sanitizer'
<add> eager_autoload do
<add> autoload :CDATA, 'html/node'
<add> autoload :Document, 'html/document'
<add> autoload :FullSanitizer, 'html/sanitizer'
<add> autoload :LinkSanitizer, 'html/sanitizer'
<add> autoload :Node, 'html/node'
<add> autoload :Sanitizer, 'html/sanitizer'
<add> autoload :Selector, 'html/selector'
<add> autoload :Tag, 'html/node'
<add> autoload :Text, 'html/node'
<add> autoload :Tokenizer, 'html/tokenizer'
<add> autoload :Version, 'html/version'
<add> autoload :WhiteListSanitizer, 'html/sanitizer'
<add> end
<ide> end
<ide><path>actionpack/lib/action_dispatch.rb
<ide> module Rack
<ide> module ActionDispatch
<ide> extend ActiveSupport::Autoload
<ide>
<del> deferrable do
<del> autoload_under 'http' do
<del> autoload :Request
<del> autoload :Response
<del> end
<add> autoload_under 'http' do
<add> autoload :Request
<add> autoload :Response
<add> end
<ide>
<del> autoload_under 'middleware' do
<del> autoload :Callbacks
<del> autoload :ParamsParser
<del> autoload :Rescue
<del> autoload :ShowExceptions
<del> autoload :Static
<del> autoload :StringCoercion
<del> end
<add> autoload_under 'middleware' do
<add> autoload :Callbacks
<add> autoload :ParamsParser
<add> autoload :Rescue
<add> autoload :ShowExceptions
<add> autoload :Static
<add> autoload :StringCoercion
<add> end
<ide>
<del> autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
<del> autoload :Routing
<add> autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
<add> autoload :Routing
<ide>
<del> module Http
<del> autoload :Headers, 'action_dispatch/http/headers'
<del> end
<add> module Http
<add> autoload :Headers, 'action_dispatch/http/headers'
<add> end
<ide>
<del> module Session
<del> autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store'
<del> autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store'
<del> autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store'
<del> end
<add> module Session
<add> autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store'
<add> autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store'
<add> autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store'
<add> end
<ide>
<del> autoload_under 'testing' do
<del> autoload :Assertions
<del> autoload :Integration
<del> autoload :PerformanceTest
<del> autoload :TestProcess
<del> autoload :TestRequest
<del> autoload :TestResponse
<del> end
<add> autoload_under 'testing' do
<add> autoload :Assertions
<add> autoload :Integration
<add> autoload :PerformanceTest
<add> autoload :TestProcess
<add> autoload :TestRequest
<add> autoload :TestResponse
<ide> end
<ide> end
<ide>
<ide><path>actionpack/lib/action_view.rb
<ide> module ActionView
<ide> extend ActiveSupport::Autoload
<ide>
<del> autoload :Base
<del> autoload :Context
<del> autoload :Template
<del> autoload :Helpers
<del> autoload :SafeBuffer
<del>
<del>
<del> autoload_under "render" do
<del> autoload :Partials
<del> autoload :Rendering
<add> eager_autoload do
<add> autoload :Base
<add> autoload :Context
<add> autoload :Template
<add> autoload :Helpers
<add> autoload :SafeBuffer
<add>
<add> autoload_under "render" do
<add> autoload :Partials
<add> autoload :Rendering
<add> end
<add>
<add> autoload :MissingTemplate, 'action_view/base'
<add> autoload :Resolver, 'action_view/template/resolver'
<add> autoload :PathResolver, 'action_view/template/resolver'
<add> autoload :PathSet, 'action_view/paths'
<add> autoload :FileSystemResolverWithFallback, 'action_view/template/resolver'
<add>
<add> autoload :TemplateError, 'action_view/template/error'
<add> autoload :TemplateHandler, 'action_view/template'
<add> autoload :TemplateHandlers, 'action_view/template'
<ide> end
<del>
<del> autoload :MissingTemplate, 'action_view/base'
<del> autoload :Resolver, 'action_view/template/resolver'
<del> autoload :PathResolver, 'action_view/template/resolver'
<del> autoload :PathSet, 'action_view/paths'
<del> autoload :FileSystemResolverWithFallback, 'action_view/template/resolver'
<del>
<del> autoload :TemplateError, 'action_view/template/error'
<del> autoload :TemplateHandler, 'action_view/template'
<del> autoload :TemplateHandlers, 'action_view/template'
<ide> end
<ide>
<ide> require 'action_view/erb/util'
<ide><path>actionpack/lib/action_view/template.rb
<ide> module ActionView
<ide> class Template
<ide> extend ActiveSupport::Autoload
<del>
<del> autoload :Error
<del> autoload :Handler
<del> autoload :Handlers
<del> autoload :Text
<del>
<add>
<add> eager_autoload do
<add> autoload :Error
<add> autoload :Handler
<add> autoload :Handlers
<add> autoload :Text
<add> end
<add>
<ide> extend Template::Handlers
<ide> attr_reader :source, :identifier, :handler, :mime_type, :formats, :details
<ide>
<ide><path>activemodel/lib/active_model.rb
<ide> module ActiveModel
<ide> extend ActiveSupport::Autoload
<ide>
<del> autoload :AttributeMethods
<del> autoload :Conversion
<del> autoload :DeprecatedErrorMethods
<del> autoload :Dirty
<del> autoload :Errors
<del> autoload :Lint
<del> autoload :Name, 'active_model/naming'
<del> autoload :Naming
<del> autoload :Observer, 'active_model/observing'
<del> autoload :Observing
<del> autoload :Serialization
<del> autoload :StateMachine
<del> autoload :Translation
<del> autoload :Validations
<del> autoload :ValidationsRepairHelper
<del> autoload :Validator
<del> autoload :VERSION
<add> eager_autoload do
<add> autoload :AttributeMethods
<add> autoload :Conversion
<add> autoload :DeprecatedErrorMethods
<add> autoload :Dirty
<add> autoload :Errors
<add> autoload :Lint
<add> autoload :Name, 'active_model/naming'
<add> autoload :Naming
<add> autoload :Observer, 'active_model/observing'
<add> autoload :Observing
<add> autoload :Serialization
<add> autoload :StateMachine
<add> autoload :Translation
<add> autoload :Validations
<add> autoload :ValidationsRepairHelper
<add> autoload :Validator
<add> autoload :VERSION
<add> end
<ide>
<ide> module Serializers
<ide> extend ActiveSupport::Autoload
<ide>
<del> autoload :JSON
<del> autoload :Xml
<add> eager_autoload do
<add> autoload :JSON
<add> autoload :Xml
<add> end
<ide> end
<ide> end
<ide>
<ide><path>activerecord/lib/active_record.rb
<ide> module ActiveRecord
<ide> extend ActiveSupport::Autoload
<ide>
<del> autoload :VERSION
<del>
<del> autoload :ActiveRecordError, 'active_record/base'
<del> autoload :ConnectionNotEstablished, 'active_record/base'
<del>
<del> autoload :Aggregations
<del> autoload :AssociationPreload
<del> autoload :Associations
<del> autoload :AttributeMethods
<del> autoload :Attributes
<del> autoload :AutosaveAssociation
<del> autoload :Relation
<del> autoload :Base
<del> autoload :Batches
<del> autoload :Calculations
<del> autoload :Callbacks
<del> autoload :DynamicFinderMatch
<del> autoload :DynamicScopeMatch
<del> autoload :Migration
<del> autoload :Migrator, 'active_record/migration'
<del> autoload :NamedScope
<del> autoload :NestedAttributes
<del> autoload :Observer
<del> autoload :QueryCache
<del> autoload :Reflection
<del> autoload :Schema
<del> autoload :SchemaDumper
<del> autoload :Serialization
<del> autoload :SessionStore
<del> autoload :StateMachine
<del> autoload :Timestamp
<del> autoload :Transactions
<del> autoload :Types
<del> autoload :Validations
<add> eager_autoload do
<add> autoload :VERSION
<add>
<add> autoload :ActiveRecordError, 'active_record/base'
<add> autoload :ConnectionNotEstablished, 'active_record/base'
<add>
<add> autoload :Aggregations
<add> autoload :AssociationPreload
<add> autoload :Associations
<add> autoload :AttributeMethods
<add> autoload :Attributes
<add> autoload :AutosaveAssociation
<add> autoload :Relation
<add> autoload :Base
<add> autoload :Batches
<add> autoload :Calculations
<add> autoload :Callbacks
<add> autoload :DynamicFinderMatch
<add> autoload :DynamicScopeMatch
<add> autoload :Migration
<add> autoload :Migrator, 'active_record/migration'
<add> autoload :NamedScope
<add> autoload :NestedAttributes
<add> autoload :Observer
<add> autoload :QueryCache
<add> autoload :Reflection
<add> autoload :Schema
<add> autoload :SchemaDumper
<add> autoload :Serialization
<add> autoload :SessionStore
<add> autoload :StateMachine
<add> autoload :Timestamp
<add> autoload :Transactions
<add> autoload :Types
<add> autoload :Validations
<add> end
<ide>
<ide> module AttributeMethods
<ide> extend ActiveSupport::Autoload
<ide>
<del> autoload :BeforeTypeCast
<del> autoload :Dirty
<del> autoload :PrimaryKey
<del> autoload :Query
<del> autoload :Read
<del> autoload :TimeZoneConversion
<del> autoload :Write
<add> eager_autoload do
<add> autoload :BeforeTypeCast
<add> autoload :Dirty
<add> autoload :PrimaryKey
<add> autoload :Query
<add> autoload :Read
<add> autoload :TimeZoneConversion
<add> autoload :Write
<add> end
<ide> end
<ide>
<ide> module Attributes
<ide> extend ActiveSupport::Autoload
<ide>
<del> autoload :Aliasing
<del> autoload :Store
<del> autoload :Typecasting
<add> eager_autoload do
<add> autoload :Aliasing
<add> autoload :Store
<add> autoload :Typecasting
<add> end
<ide> end
<ide>
<ide> module Type
<ide> extend ActiveSupport::Autoload
<ide>
<del> autoload :Number, 'active_record/types/number'
<del> autoload :Object, 'active_record/types/object'
<del> autoload :Serialize, 'active_record/types/serialize'
<del> autoload :TimeWithZone, 'active_record/types/time_with_zone'
<del> autoload :Unknown, 'active_record/types/unknown'
<add> eager_autoload do
<add> autoload :Number, 'active_record/types/number'
<add> autoload :Object, 'active_record/types/object'
<add> autoload :Serialize, 'active_record/types/serialize'
<add> autoload :TimeWithZone, 'active_record/types/time_with_zone'
<add> autoload :Unknown, 'active_record/types/unknown'
<add> end
<ide> end
<ide>
<ide> module Locking
<ide> extend ActiveSupport::Autoload
<ide>
<del> autoload :Optimistic
<del> autoload :Pessimistic
<add> eager_autoload do
<add> autoload :Optimistic
<add> autoload :Pessimistic
<add> end
<ide> end
<ide>
<ide> module ConnectionAdapters
<ide> extend ActiveSupport::Autoload
<ide>
<del> autoload :AbstractAdapter
<add> eager_autoload do
<add> autoload :AbstractAdapter
<add> end
<ide> end
<ide> end
<ide>
<ide><path>activeresource/lib/active_resource.rb
<ide> module ActiveResource
<ide> extend ActiveSupport::Autoload
<ide>
<del> autoload :Base
<del> autoload :Connection
<del> autoload :CustomMethods
<del> autoload :Formats
<del> autoload :HttpMock
<del> autoload :Observing
<del> autoload :Schema
<del> autoload :Validations
<add> eager_autoload do
<add> autoload :Base
<add> autoload :Connection
<add> autoload :CustomMethods
<add> autoload :Formats
<add> autoload :HttpMock
<add> autoload :Observing
<add> autoload :Schema
<add> autoload :Validations
<add> end
<ide> end
<ide><path>activesupport/lib/active_support.rb
<ide> def load_all!; load_all_hooks.each { |hook| hook.call } end
<ide> module ActiveSupport
<ide> extend ActiveSupport::Autoload
<ide>
<del> autoload :BacktraceCleaner
<del> autoload :Base64
<del> autoload :BasicObject
<del> autoload :Benchmarkable
<del> autoload :BufferedLogger
<del> autoload :Cache
<del> autoload :Callbacks
<del> autoload :Concern
<del> autoload :Configurable
<del> autoload :DeprecatedCallbacks
<del> autoload :Deprecation
<del> autoload :Gzip
<del> autoload :Inflector
<del> autoload :Memoizable
<del> autoload :MessageEncryptor
<del> autoload :MessageVerifier
<del> autoload :Multibyte
<del> autoload :OptionMerger
<del> autoload :OrderedHash
<del> autoload :OrderedOptions
<del> autoload :Notifications
<del> autoload :Rescuable
<del> autoload :SecureRandom
<del> autoload :StringInquirer
<del> autoload :XmlMini
<add> # TODO: Narrow this list down
<add> eager_autoload do
<add> autoload :BacktraceCleaner
<add> autoload :Base64
<add> autoload :BasicObject
<add> autoload :Benchmarkable
<add> autoload :BufferedLogger
<add> autoload :Cache
<add> autoload :Callbacks
<add> autoload :Concern
<add> autoload :Configurable
<add> autoload :DeprecatedCallbacks
<add> autoload :Deprecation
<add> autoload :Gzip
<add> autoload :Inflector
<add> autoload :Memoizable
<add> autoload :MessageEncryptor
<add> autoload :MessageVerifier
<add> autoload :Multibyte
<add> autoload :OptionMerger
<add> autoload :OrderedHash
<add> autoload :OrderedOptions
<add> autoload :Notifications
<add> autoload :Rescuable
<add> autoload :SecureRandom
<add> autoload :StringInquirer
<add> autoload :XmlMini
<add> end
<ide> end
<ide>
<ide> require 'active_support/vendor'
<ide><path>activesupport/lib/active_support/dependencies/autoload.rb
<ide> module Autoload
<ide> @@autoloads = {}
<ide> @@under_path = nil
<ide> @@at_path = nil
<del> @@autoload_defer = false
<add> @@eager_autoload = false
<ide>
<ide> def autoload(const_name, path = @@at_path)
<ide> full = [self.name, @@under_path, const_name.to_s, path].compact.join("::")
<ide> location = path || Inflector.underscore(full)
<ide>
<del> unless @@autoload_defer
<add> if @@eager_autoload
<ide> @@autoloads[const_name] = location
<ide> end
<ide> super const_name, location
<ide> def autoload_at(path)
<ide> @@at_path = old_path
<ide> end
<ide>
<del> def deferrable
<del> old_defer, autoload_defer, true
<add> def eager_autoload
<add> old_eager, eager_autoload, true
<ide> yield
<ide> ensure
<del> @@autoload_defer = old_defer
<add> @@eager_autoload = old_eager
<ide> end
<ide>
<ide> def self.eager_autoload! | 13 |
PHP | PHP | fix fatal error | 2ebf5d7c9043f0fe753b1d685f5a03fd4d1170f1 | <ide><path>Cake/TestSuite/TestCase.php
<ide> protected function skipUnless($condition, $message = '') {
<ide> * @return Model
<ide> */
<ide> public function getMockForModel($model, $methods = array(), $config = array()) {
<del> $config += ClassRegistry::config('Model');
<add> $config += (array)ClassRegistry::config('Model');
<ide>
<ide> $modelClass = App::className($model, 'Model');
<ide> list(, $name) = namespaceSplit($modelClass); | 1 |
Java | Java | update reactor2 support | 7891c0d5ca208ef4f123f2dfa92cd13e6cb25042 | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/Reactor2TcpClient.java
<ide> import reactor.core.config.DispatcherConfiguration;
<ide> import reactor.core.config.ReactorConfiguration;
<ide> import reactor.core.support.NamedDaemonThreadFactory;
<del>import reactor.fn.BiFunction;
<ide> import reactor.fn.Consumer;
<ide> import reactor.fn.Function;
<ide> import reactor.fn.tuple.Tuple;
<ide> import reactor.fn.tuple.Tuple2;
<ide> import reactor.io.buffer.Buffer;
<ide> import reactor.io.codec.Codec;
<del>import reactor.io.net.*;
<add>import reactor.io.net.ChannelStream;
<add>import reactor.io.net.NetStreams;
<add>import reactor.io.net.NetStreams.TcpClientFactory;
<add>import reactor.io.net.ReactorChannelHandler;
<add>import reactor.io.net.Reconnect;
<ide> import reactor.io.net.Spec.TcpClientSpec;
<ide> import reactor.io.net.impl.netty.NettyClientSocketOptions;
<ide> import reactor.io.net.impl.netty.tcp.NettyTcpClient;
<ide> @SuppressWarnings("rawtypes")
<ide> public static final Class<NettyTcpClient> REACTOR_TCP_CLIENT_TYPE = NettyTcpClient.class;
<ide>
<del> private final NetStreams.TcpClientFactory<Message<P>, Message<P>> tcpClientSpecFactory;
<add> private final TcpClientFactory<Message<P>, Message<P>> tcpClientSpecFactory;
<ide>
<ide> private final List<TcpClient<Message<P>, Message<P>>> tcpClients =
<ide> new ArrayList<TcpClient<Message<P>, Message<P>>>();
<ide> public Reactor2TcpClient(final String host, final int port, final Codec<Buffer,
<ide>
<ide> final NioEventLoopGroup eventLoopGroup = initEventLoopGroup();
<ide>
<del> this.tcpClientSpecFactory = new NetStreams.TcpClientFactory<Message<P>, Message<P>>() {
<add> this.tcpClientSpecFactory = new TcpClientFactory<Message<P>, Message<P>>() {
<ide>
<ide> @Override
<ide> public TcpClientSpec<Message<P>, Message<P>> apply(TcpClientSpec<Message<P>, Message<P>> spec) {
<ide> private NioEventLoopGroup initEventLoopGroup() {
<ide> int ioThreadCount;
<ide> try {
<ide> ioThreadCount = Integer.parseInt(System.getProperty("reactor.tcp.ioThreadCount"));
<del> } catch (Exception i) {
<add> }
<add> catch (Exception i) {
<ide> ioThreadCount = -1;
<ide> }
<ide> if (ioThreadCount <= 0l) {
<ide> private NioEventLoopGroup initEventLoopGroup() {
<ide> *
<ide> * @param tcpClientSpecFactory the TcpClientSpec {@link Function} to use for each client creation.
<ide> */
<del> public Reactor2TcpClient(NetStreams.TcpClientFactory<Message<P>, Message<P>> tcpClientSpecFactory) {
<add> public Reactor2TcpClient(TcpClientFactory<Message<P>, Message<P>> tcpClientSpecFactory) {
<ide> Assert.notNull(tcpClientSpecFactory, "'tcpClientClientFactory' must not be null");
<ide> this.tcpClientSpecFactory = tcpClientSpecFactory;
<ide> }
<ide>
<ide>
<ide> @Override
<del> public ListenableFuture<Void> connect(TcpConnectionHandler<P> connectionHandler) {
<del> Class<NettyTcpClient> type = REACTOR_TCP_CLIENT_TYPE;
<del>
<del> TcpClient<Message<P>, Message<P>> tcpClient = NetStreams.tcpClient(type, this.tcpClientSpecFactory);
<del>
<del> Promise<Void> promise = tcpClient.start(composeConnectionHandling(tcpClient, connectionHandler));
<del>
<add> public ListenableFuture<Void> connect(final TcpConnectionHandler<P> connectionHandler) {
<add> Assert.notNull(connectionHandler, "'connectionHandler' must not be null");
<add> Promise<Void> promise = createTcpClient().start(new MessageChannelStreamHandler<P>(connectionHandler));
<ide> return new PassThroughPromiseToListenableFutureAdapter<Void>(
<ide> promise.onError(new Consumer<Throwable>() {
<ide> @Override
<ide> public void accept(Throwable throwable) {
<ide> }
<ide>
<ide> @Override
<del> public ListenableFuture<Void> connect(TcpConnectionHandler<P> handler, ReconnectStrategy strategy) {
<del> Assert.notNull(strategy, "ReconnectStrategy must not be null");
<del> Class<NettyTcpClient> type = REACTOR_TCP_CLIENT_TYPE;
<add> public ListenableFuture<Void> connect(TcpConnectionHandler<P> connectionHandler, ReconnectStrategy strategy) {
<add> Assert.notNull(connectionHandler, "'connectionHandler' must not be null");
<add> Assert.notNull(strategy, "'reconnectStrategy' must not be null");
<ide>
<del> TcpClient<Message<P>, Message<P>> tcpClient = NetStreams.tcpClient(type, this.tcpClientSpecFactory);
<del>
<del> Stream<Tuple2<InetSocketAddress, Integer>> stream = tcpClient.start(
<del> composeConnectionHandling(tcpClient, handler),
<del> new ReactorRectonnectAdapter(strategy)
<del> );
<add> Stream<Tuple2<InetSocketAddress, Integer>> stream = createTcpClient().start(
<add> new MessageChannelStreamHandler<P>(connectionHandler),
<add> new ReactorReconnectAdapter(strategy));
<ide>
<ide> return new PassThroughPromiseToListenableFutureAdapter<Void>(stream.next().after());
<ide> }
<ide>
<del> private MessageHandler<P> composeConnectionHandling(
<del> final TcpClient<Message<P>, Message<P>> tcpClient,
<del> final TcpConnectionHandler<P> connectionHandler
<del> ) {
<del>
<add> private TcpClient<Message<P>, Message<P>> createTcpClient() {
<add> Class<NettyTcpClient> type = REACTOR_TCP_CLIENT_TYPE;
<add> TcpClient<Message<P>, Message<P>> tcpClient = NetStreams.tcpClient(type, this.tcpClientSpecFactory);
<ide> synchronized (this.tcpClients) {
<ide> this.tcpClients.add(tcpClient);
<ide> }
<del>
<del> return new MessageHandler<P>() {
<del> @Override
<del> public Publisher<Void> apply(ChannelStream<Message<P>, Message<P>> connection) {
<del>
<del> Promise<Void> closePromise = Promises.prepare();
<del>
<del> connectionHandler.afterConnected(new Reactor2TcpConnection<P>(connection, closePromise));
<del>
<del> connection
<del> .finallyDo(new Consumer<Signal<Message<P>>>() {
<del>
<del> @Override
<del> public void accept(Signal<Message<P>> signal) {
<del> if (signal.isOnError()) {
<del> connectionHandler.handleFailure(signal.getThrowable());
<del> } else if (signal.isOnComplete()) {
<del> connectionHandler.afterConnectionClosed();
<del> }
<del> }
<del> })
<del> .consume(new Consumer<Message<P>>() {
<del>
<del> @Override
<del> public void accept(Message<P> message) {
<del> connectionHandler.handleMessage(message);
<del> }
<del> });
<del>
<del> return closePromise;
<del> }
<del> };
<add> return tcpClient;
<ide> }
<ide>
<ide> @Override
<ide> public ListenableFuture<Void> shutdown() {
<del>
<del> final List<TcpClient<Message<P>, Message<P>>> clients;
<del>
<add> final List<TcpClient<Message<P>, Message<P>>> readOnlyClients;
<ide> synchronized (this.tcpClients) {
<del> clients = new ArrayList<TcpClient<Message<P>, Message<P>>>(this.tcpClients);
<add> readOnlyClients = new ArrayList<TcpClient<Message<P>, Message<P>>>(this.tcpClients);
<ide> }
<del>
<del> Promise<Void> promise = Streams.from(clients)
<add> Promise<Void> promise = Streams.from(readOnlyClients)
<ide> .flatMap(new Function<TcpClient<Message<P>, Message<P>>, Promise<Void>>() {
<ide> @Override
<ide> public Promise<Void> apply(final TcpClient<Message<P>, Message<P>> client) {
<ide> public void accept(Promise<Void> voidPromise) {
<ide> }
<ide> })
<ide> .next();
<del>
<ide> return new PassThroughPromiseToListenableFutureAdapter<Void>(promise);
<ide> }
<ide>
<add>
<ide> private static class SynchronousDispatcherConfigReader implements ConfigurationReader {
<ide>
<ide> @Override
<ide> public ReactorConfiguration read() {
<ide> }
<ide> }
<ide>
<del> private static class ReactorRectonnectAdapter implements Reconnect {
<add> private static class MessageChannelStreamHandler<P>
<add> implements ReactorChannelHandler<Message<P>, Message<P>, ChannelStream<Message<P>, Message<P>>> {
<add>
<add> private final TcpConnectionHandler<P> connectionHandler;
<add>
<add> public MessageChannelStreamHandler(TcpConnectionHandler<P> connectionHandler) {
<add> this.connectionHandler = connectionHandler;
<add> }
<add>
<add> @Override
<add> public Publisher<Void> apply(ChannelStream<Message<P>, Message<P>> channelStream) {
<add>
<add> Promise<Void> closePromise = Promises.prepare();
<add>
<add> this.connectionHandler.afterConnected(new Reactor2TcpConnection<P>(channelStream, closePromise));
<add>
<add> channelStream
<add> .finallyDo(new Consumer<Signal<Message<P>>>() {
<add>
<add> @Override
<add> public void accept(Signal<Message<P>> signal) {
<add> if (signal.isOnError()) {
<add> connectionHandler.handleFailure(signal.getThrowable());
<add> }
<add> else if (signal.isOnComplete()) {
<add> connectionHandler.afterConnectionClosed();
<add> }
<add> }
<add> })
<add> .consume(new Consumer<Message<P>>() {
<add>
<add> @Override
<add> public void accept(Message<P> message) {
<add> connectionHandler.handleMessage(message);
<add> }
<add> });
<add>
<add> return closePromise;
<add> }
<add> }
<add>
<add> private static class ReactorReconnectAdapter implements Reconnect {
<ide>
<ide> private final ReconnectStrategy strategy;
<ide>
<del> public ReactorRectonnectAdapter(ReconnectStrategy strategy) {
<add> public ReactorReconnectAdapter(ReconnectStrategy strategy) {
<ide> this.strategy = strategy;
<ide> }
<ide>
<ide> @Override
<ide> public Tuple2<InetSocketAddress, Long> reconnect(InetSocketAddress address, int attempt) {
<ide> return Tuple.of(address, strategy.getTimeToNextAttempt(attempt));
<ide> }
<del>
<del> }
<del>
<del> private interface MessageHandler<P>
<del> extends ReactorChannelHandler<Message<P>, Message<P>, ChannelStream<Message<P>, Message<P>>>{
<ide> }
<ide>
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/Reactor2TcpConnection.java
<ide>
<ide> package org.springframework.messaging.tcp.reactor;
<ide>
<del>import org.reactivestreams.Subscriber;
<del>import org.reactivestreams.Subscription;
<del>import org.springframework.util.concurrent.ListenableFutureAdapter;
<ide> import reactor.fn.Functions;
<ide> import reactor.io.net.ChannelStream;
<ide> import reactor.rx.Promise;
<ide> import reactor.rx.Promises;
<ide> import reactor.rx.Streams;
<del>import reactor.rx.broadcast.Broadcaster;
<ide>
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.tcp.TcpConnection;
<ide> public class Reactor2TcpConnection<P> implements TcpConnection<P> {
<ide>
<ide> private final ChannelStream<Message<P>, Message<P>> channelStream;
<add>
<ide> private final Promise<Void> closePromise;
<ide>
<del> public Reactor2TcpConnection(ChannelStream<Message<P>, Message<P>> channelStream, Promise<Void> closePromise) {
<add>
<add> public Reactor2TcpConnection(ChannelStream<Message<P>, Message<P>> channelStream,
<add> Promise<Void> closePromise) {
<add>
<ide> this.channelStream = channelStream;
<ide> this.closePromise = closePromise;
<ide> }
<ide> public void onWriteInactivity(Runnable runnable, long inactivityDuration) {
<ide> public void close() {
<ide> this.closePromise.onComplete();
<ide> }
<add>
<ide> } | 2 |
Text | Text | add text " unlike the `while` loop," to article | 006d69e427c3487c192d2ee2e4059a60b0f5c828 | <ide><path>guide/english/java/loops/do-while-loop/index.md
<ide> Output:
<ide> iter_DoWhile Value: 21
<ide> ```
<ide>
<del>**Remember**: The condition of a `do-while` loop is checked after the code body is executed once.
<add>**Remember**: Unlike the `while` loop, the condition of a `do-while` loop is checked after the code body is executed once.
<ide>
<ide>  <a href='https://repl.it/CJYl/0' target='_blank' rel='nofollow'>Run Code</a>
<ide> | 1 |
Ruby | Ruby | remove obsolete doctor check | 4f8be5bb66033ae1cd3e15a75f1a35ac1174440b | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_for_linked_keg_only_brews
<ide> end
<ide> end
<ide>
<del>def check_for_MACOSX_DEPLOYMENT_TARGET
<del> target = ENV.fetch('MACOSX_DEPLOYMENT_TARGET') { return }
<del>
<del> unless target == MacOS.version.to_s then <<-EOS.undent
<del> MACOSX_DEPLOYMENT_TARGET was set to #{target.inspect}
<del> This is used by Fink, but having it set to a value different from the
<del> current system version (#{MacOS.version}) can cause problems, compiling
<del> Git for instance, and should probably be removed.
<del> EOS
<del> end
<del>end
<del>
<ide> def check_for_other_frameworks
<ide> # Other frameworks that are known to cause problems when present
<ide> %w{Mono.framework expat.framework libexpat.framework}. | 1 |
Text | Text | fix typo in changelog entry [ci skip] | bc7821f519cbe6ec5a1eea1801b0c6e3c44c0c1e | <ide><path>activestorage/CHANGELOG.md
<ide> * Replace `Blob.create_after_upload!` with `Blob.create_and_upload!` and deprecate the former.
<ide>
<ide> `create_after_upload!` has been removed since it could lead to data
<del> curruption by uploading to a key on the storage service which happened to
<add> corruption by uploading to a key on the storage service which happened to
<ide> be already taken. Creating the record would then correctly raise a
<ide> database uniqueness exception but the stored object would already have
<ide> overwritten another. `create_and_upload!` swaps the order of operations | 1 |
Javascript | Javascript | upgrade namedmodulesplugin to es6 | 6cad87f5fecc0db52a0a0211beb64c68eda2cadb | <ide><path>lib/NamedModulesPlugin.js
<ide> MIT License http://www.opensource.org/licenses/mit-license.php
<ide> Author Tobias Koppers @sokra
<ide> */
<del>function NamedModulesPlugin(options) {
<del> this.options = options || {};
<add>"use strict";
<add>
<add>class NamedModulesPlugin {
<add> constructor(options) {
<add> this.options = options || {};
<add> }
<add>
<add> apply(compiler) {
<add> compiler.plugin("compilation", (compilation) => {
<add> compilation.plugin("before-module-ids", (modules) => {
<add> modules.forEach((module) => {
<add> if(module.id === null && module.libIdent) {
<add> module.id = module.libIdent({
<add> context: this.options.context || compiler.options.context
<add> });
<add> }
<add> });
<add> });
<add> });
<add> }
<ide> }
<add>
<ide> module.exports = NamedModulesPlugin;
<del>NamedModulesPlugin.prototype.apply = function(compiler) {
<del> compiler.plugin("compilation", function(compilation) {
<del> compilation.plugin("before-module-ids", function(modules) {
<del> modules.forEach(function(module) {
<del> if(module.id === null && module.libIdent) {
<del> module.id = module.libIdent({
<del> context: this.options.context || compiler.options.context
<del> });
<del> }
<del> }, this);
<del> }.bind(this));
<del> }.bind(this));
<del>}; | 1 |
Mixed | Javascript | fix version picker bug in html.js | 6f64cda1ee578d121e328756ac7401f0ee8e1d62 | <ide><path>test/doctool/test-doctool-html.js
<ide> const testData = [
<ide> html: '<ol><li>fish</li><li>fish</li></ol>' +
<ide> '<ul><li>Red fish</li><li>Blue fish</li></ul>',
<ide> },
<add> {
<add> file: fixtures.path('altdocs.md'),
<add> html: '<li><a href="https://nodejs.org/docs/latest-v8.x/api/foo.html">8.x',
<add> },
<ide> ];
<ide>
<ide> const spaces = /\s/g;
<ide> testData.forEach(({ file, html }) => {
<ide> const actual = output.replace(spaces, '');
<ide> // Assert that the input stripped of all whitespace contains the
<ide> // expected markup.
<del> assert(actual.includes(expected));
<add> assert(actual.includes(expected),
<add> `ACTUAL: ${actual}\nEXPECTED: ${expected}`);
<ide> })
<ide> );
<ide> }));
<ide><path>test/fixtures/altdocs.md
<add># ALTDOCS
<add><!--introduced_in=v8.4.0-->
<ide><path>tools/doc/html.js
<ide> function altDocs(filename, docCreated) {
<ide> const [versionMajor, versionMinor] = version.num.split('.').map(Number);
<ide> if (docCreatedMajor > versionMajor) return false;
<ide> if (docCreatedMajor < versionMajor) return true;
<add> if (Number.isNaN(versionMinor)) return true;
<ide> return docCreatedMinor <= versionMinor;
<ide> }
<ide> | 3 |
Text | Text | fix casing typo in jsx-in-depth.md | 92665e2cb10598604d47d368e093f0606370768b | <ide><path>docs/docs/jsx-in-depth.md
<ide> You can pass any JavaScript expression as a prop, by surrounding it with `{}`. F
<ide> <MyComponent foo={1 + 2 + 3 + 4} />
<ide> ```
<ide>
<del>For `MyComponent`, The value of `props.foo` will be `10` because the expression `1 + 2 + 3 + 4` gets evaluated.
<add>For `MyComponent`, the value of `props.foo` will be `10` because the expression `1 + 2 + 3 + 4` gets evaluated.
<ide>
<ide> `if` statements and `for` loops are not expressions in JavaScript, so they can't be used in JSX directly. Instead, you can put these in the surrounding code. For example:
<ide> | 1 |
Javascript | Javascript | restore helpful comment about inline templates | 90e77f5af84e46ebcdc3777477d2dcf527148790 | <ide><path>packages/sproutcore-handlebars/lib/loader.js
<ide> SC.$(document).ready(function() {
<ide> view, viewPath;
<ide>
<ide> if (templateName) {
<add> // For templates which have a name, we save them and then remove them from the DOM
<ide> SC.TEMPLATES[templateName] = template;
<ide>
<ide> // Remove script tag from DOM
<ide> SC.$(document).ready(function() {
<ide> "Please provide a data-template-name attribute.\n" +
<ide> script.html());
<ide> }
<add>
<add> // For templates which will be evaluated inline in the HTML document, instantiates a new
<add> // view, and replaces the script tag holding the template with the new
<add> // view's DOM representation.
<add> //
<add> // Users can optionally specify a custom view subclass to use by setting the
<add> // data-view attribute of the script tag.
<ide> viewPath = script.attr('data-view');
<ide> view = viewPath ? SC.getPath(viewPath) : SC.View;
<ide> | 1 |
PHP | PHP | remove extra semicolon | 536fe29b6b306588536e68d188ff6482f3fab899 | <ide><path>app/Console/Kernel.php
<ide> class Kernel extends ConsoleKernel {
<ide> */
<ide> protected function schedule(Schedule $schedule)
<ide> {
<del> $schedule->artisan('inspire');
<add> $schedule->artisan('inspire')
<ide> ->hourly();
<ide> }
<ide> | 1 |
Ruby | Ruby | remove some indirection in rake dbs test | 97229c69eaa6e4aec76e9ed1d14e8eba1c66d183 | <ide><path>railties/test/application/rake/dbs_test.rb
<ide> def set_database_url
<ide> FileUtils.rm_rf("#{app_path}/config/database.yml")
<ide> end
<ide>
<del> def expected
<del> @expected ||= {}
<del> end
<del>
<del> def db_create_and_drop
<add> def db_create_and_drop(expected_database)
<ide> Dir.chdir(app_path) do
<ide> output = `bundle exec rake db:create`
<ide> assert_empty output
<del> assert File.exist?(expected[:database])
<del> assert_equal expected[:database], ActiveRecord::Base.connection_config[:database]
<add> assert File.exist?(expected_database)
<add> assert_equal expected_database, ActiveRecord::Base.connection_config[:database]
<ide> output = `bundle exec rake db:drop`
<ide> assert_empty output
<del> assert !File.exist?(expected[:database])
<add> assert !File.exist?(expected_database)
<ide> end
<ide> end
<ide>
<ide> test 'db:create and db:drop without database url' do
<ide> require "#{app_path}/config/environment"
<del> expected[:database] = ActiveRecord::Base.configurations[Rails.env]['database']
<del> db_create_and_drop
<add> db_create_and_drop ActiveRecord::Base.configurations[Rails.env]['database']
<ide> end
<ide>
<ide> test 'db:create and db:drop with database url' do
<ide> require "#{app_path}/config/environment"
<ide> set_database_url
<del> expected[:database] = database_url_db_name
<del> db_create_and_drop
<add> db_create_and_drop database_url_db_name
<ide> end
<ide>
<del> def db_migrate_and_status
<add> def db_migrate_and_status(expected_database)
<ide> Dir.chdir(app_path) do
<ide> `rails generate model book title:string;
<ide> bundle exec rake db:migrate`
<ide> output = `bundle exec rake db:migrate:status`
<del> assert_match(%r{database:\s+\S*#{Regexp.escape(expected[:database])}}, output)
<add> assert_match(%r{database:\s+\S*#{Regexp.escape(expected_database)}}, output)
<ide> assert_match(/up\s+\d{14}\s+Create books/, output)
<ide> end
<ide> end
<ide>
<ide> test 'db:migrate and db:migrate:status without database_url' do
<ide> require "#{app_path}/config/environment"
<del> expected[:database] = ActiveRecord::Base.configurations[Rails.env]['database']
<del> db_migrate_and_status
<add> db_migrate_and_status ActiveRecord::Base.configurations[Rails.env]['database']
<ide> end
<ide>
<ide> test 'db:migrate and db:migrate:status with database_url' do
<ide> require "#{app_path}/config/environment"
<ide> set_database_url
<del> expected[:database] = database_url_db_name
<del> db_migrate_and_status
<add> db_migrate_and_status database_url_db_name
<ide> end
<ide>
<ide> def db_schema_dump
<ide> def db_schema_dump
<ide> db_schema_dump
<ide> end
<ide>
<del> def db_fixtures_load
<add> def db_fixtures_load(expected_database)
<ide> Dir.chdir(app_path) do
<ide> `rails generate model book title:string;
<ide> bundle exec rake db:migrate db:fixtures:load`
<del> assert_match(/#{expected[:database]}/,
<del> ActiveRecord::Base.connection_config[:database])
<add> assert_match expected_database, ActiveRecord::Base.connection_config[:database]
<ide> require "#{app_path}/app/models/book"
<ide> assert_equal 2, Book.count
<ide> end
<ide> end
<ide>
<ide> test 'db:fixtures:load without database_url' do
<ide> require "#{app_path}/config/environment"
<del> expected[:database] = ActiveRecord::Base.configurations[Rails.env]['database']
<del> db_fixtures_load
<add> db_fixtures_load ActiveRecord::Base.configurations[Rails.env]['database']
<ide> end
<ide>
<ide> test 'db:fixtures:load with database_url' do
<ide> require "#{app_path}/config/environment"
<ide> set_database_url
<del> expected[:database] = database_url_db_name
<del> db_fixtures_load
<add> db_fixtures_load database_url_db_name
<ide> end
<ide>
<del> def db_structure_dump_and_load
<add> def db_structure_dump_and_load(expected_database)
<ide> Dir.chdir(app_path) do
<ide> `rails generate model book title:string;
<ide> bundle exec rake db:migrate db:structure:dump`
<ide> structure_dump = File.read("db/structure.sql")
<ide> assert_match(/CREATE TABLE \"books\"/, structure_dump)
<ide> `bundle exec rake environment db:drop db:structure:load`
<del> assert_match(/#{expected[:database]}/,
<del> ActiveRecord::Base.connection_config[:database])
<add> assert_match expected_database, ActiveRecord::Base.connection_config[:database]
<ide> require "#{app_path}/app/models/book"
<ide> #if structure is not loaded correctly, exception would be raised
<ide> assert_equal 0, Book.count
<ide> def db_structure_dump_and_load
<ide>
<ide> test 'db:structure:dump and db:structure:load without database_url' do
<ide> require "#{app_path}/config/environment"
<del> expected[:database] = ActiveRecord::Base.configurations[Rails.env]['database']
<del> db_structure_dump_and_load
<add> db_structure_dump_and_load ActiveRecord::Base.configurations[Rails.env]['database']
<ide> end
<ide>
<ide> test 'db:structure:dump and db:structure:load with database_url' do
<ide> require "#{app_path}/config/environment"
<ide> set_database_url
<del> expected[:database] = database_url_db_name
<del> db_structure_dump_and_load
<add> db_structure_dump_and_load database_url_db_name
<ide> end
<ide>
<ide> def db_test_load_structure
<ide> def db_test_load_structure
<ide> require "#{app_path}/app/models/book"
<ide> #if structure is not loaded correctly, exception would be raised
<ide> assert_equal 0, Book.count
<del> assert_match(/#{ActiveRecord::Base.configurations['test']['database']}/,
<del> ActiveRecord::Base.connection_config[:database])
<add> assert_match ActiveRecord::Base.configurations['test']['database'],
<add> ActiveRecord::Base.connection_config[:database]
<ide> end
<ide> end
<ide> | 1 |
Text | Text | fix serializer example in docs | be96939ec1482ce3453fb210460ab795f7704b4a | <ide><path>docs/api-guide/serializers.md
<ide> Serializer classes can also include reusable validators that are applied to the
<ide>
<ide> class Meta:
<ide> # Each room only has one event per day.
<del> validators = UniqueTogetherValidator(
<del> queryset=Event.objects.all(),
<del> fields=['room_number', 'date']
<del> )
<add> validators = [
<add> UniqueTogetherValidator(
<add> queryset=Event.objects.all(),
<add> fields=['room_number', 'date']
<add> )
<add> ]
<ide>
<ide> For more information see the [validators documentation](validators.md).
<ide> | 1 |
PHP | PHP | fix bug in form builder | 6881e798b5276134e8c278cff918070387b5085c | <ide><path>src/Illuminate/Html/FormBuilder.php
<ide> public function getValueAttribute($name, $value = null)
<ide> if ( ! is_null($value)) return $value;
<ide>
<ide> if (isset($this->model) and isset($this->model[$name]))
<add> {
<add> return $this->getModelValueAttribute($name);
<add> }
<add> }
<add>
<add> /**
<add> * Get the model value that should be assigned to the field.
<add> *
<add> * @param string $name
<add> * @return string
<add> */
<add> protected function getModelValueAttribute($name)
<add> {
<add> if (is_object($this->model))
<ide> {
<ide> return object_get($this->model, $name);
<ide> }
<add> elseif (is_array($this->model))
<add> {
<add> return array_get($this->model, $name);
<add> }
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | preach what we practise | 6a38b0189c2a321580ede867870bf10b79dc365c | <ide><path>docs/Formula-Cookbook.md
<ide> system "make", "target", "VAR2=value1", "VAR2=value2", "VAR3=values can have spa
<ide> ```
<ide>
<ide> ```ruby
<del>args = %W[
<del> CC=#{ENV.cc}
<del> PREFIX=#{prefix}
<del>]
<del>
<del>system "make", *args
<add>system "make", "CC=#{ENV.cc}", "PREFIX=#{prefix}"
<ide> ```
<ide>
<ide> Note that values *can* contain unescaped spaces if you use the multiple-argument form of `system`. | 1 |
Go | Go | move context stuff to its own package | f790496d8bd0930d7b1bc4adf120ae5ef169a958 | <ide><path>api/server/auth.go
<ide> import (
<ide> "encoding/json"
<ide> "net/http"
<ide>
<del> "golang.org/x/net/context"
<del>
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/cliconfig"
<add> "github.com/docker/docker/context"
<ide> )
<ide>
<ide> func (s *Server) postAuth(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide><path>api/server/container.go
<ide> import (
<ide> "strings"
<ide> "time"
<ide>
<del> "golang.org/x/net/context"
<ide> "golang.org/x/net/websocket"
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/context"
<ide> "github.com/docker/docker/daemon"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/signal"
<del> "github.com/docker/docker/pkg/version"
<ide> "github.com/docker/docker/runconfig"
<ide> )
<ide>
<ide> func (s *Server) postContainersKill(ctx context.Context, w http.ResponseWriter,
<ide> // Return error that's not caused because the container is stopped.
<ide> // Return error if the container is not running and the api is >= 1.20
<ide> // to keep backwards compatibility.
<del> version, _ := ctx.Value("api-version").(version.Version)
<add> version := ctx.Version()
<ide> if version.GreaterThanOrEqualTo("1.20") || !isStopped {
<ide> return fmt.Errorf("Cannot kill container %s: %v", name, err)
<ide> }
<ide> func (s *Server) postContainersCreate(ctx context.Context, w http.ResponseWriter
<ide> if err != nil {
<ide> return err
<ide> }
<del> version, _ := ctx.Value("api-version").(version.Version)
<add> version := ctx.Version()
<ide> adjustCPUShares := version.LessThan("1.19")
<ide>
<ide> container, warnings, err := s.daemon.ContainerCreate(name, config, hostConfig, adjustCPUShares)
<ide><path>api/server/copy.go
<ide> import (
<ide> "os"
<ide> "strings"
<ide>
<del> "golang.org/x/net/context"
<del>
<ide> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/context"
<ide> )
<ide>
<ide> // postContainersCopy is deprecated in favor of getContainersArchive.
<ide><path>api/server/daemon.go
<ide> import (
<ide> "strings"
<ide> "time"
<ide>
<del> "golang.org/x/net/context"
<del>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/autogen/dockerversion"
<add> "github.com/docker/docker/context"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/jsonmessage"
<ide> "github.com/docker/docker/pkg/parsers/filters"
<ide> "github.com/docker/docker/pkg/parsers/kernel"
<del> "github.com/docker/docker/pkg/version"
<ide> "github.com/docker/docker/utils"
<ide> )
<ide>
<ide> func (s *Server) getVersion(ctx context.Context, w http.ResponseWriter, r *http.
<ide> BuildTime: dockerversion.BUILDTIME,
<ide> }
<ide>
<del> version, _ := ctx.Value("api-version").(version.Version)
<add> version := ctx.Version()
<ide>
<ide> if version.GreaterThanOrEqualTo("1.19") {
<ide> v.Experimental = utils.ExperimentalBuild()
<ide><path>api/server/exec.go
<ide> import (
<ide> "net/http"
<ide> "strconv"
<ide>
<del> "golang.org/x/net/context"
<del>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/context"
<ide> "github.com/docker/docker/pkg/stdcopy"
<ide> "github.com/docker/docker/runconfig"
<ide> )
<ide><path>api/server/image.go
<ide> import (
<ide> "net/http"
<ide> "strings"
<ide>
<del> "golang.org/x/net/context"
<del>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/builder"
<ide> "github.com/docker/docker/cliconfig"
<add> "github.com/docker/docker/context"
<ide> "github.com/docker/docker/graph"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/streamformatter"
<ide> "github.com/docker/docker/pkg/ulimit"
<del> "github.com/docker/docker/pkg/version"
<ide> "github.com/docker/docker/runconfig"
<ide> "github.com/docker/docker/utils"
<ide> )
<ide> func (s *Server) postCommit(ctx context.Context, w http.ResponseWriter, r *http.
<ide> cname := r.Form.Get("container")
<ide>
<ide> pause := boolValue(r, "pause")
<del> version, _ := ctx.Value("api-version").(version.Version)
<add> version := ctx.Version()
<ide> if r.FormValue("pause") == "" && version.GreaterThanOrEqualTo("1.13") {
<ide> pause = true
<ide> }
<ide> func (s *Server) postBuild(ctx context.Context, w http.ResponseWriter, r *http.R
<ide>
<ide> w.Header().Set("Content-Type", "application/json")
<ide>
<del> version, _ := ctx.Value("api-version").(version.Version)
<add> version := ctx.Version()
<ide> if boolValue(r, "forcerm") && version.GreaterThanOrEqualTo("1.12") {
<ide> buildConfig.Remove = true
<ide> } else if r.FormValue("rm") == "" && version.GreaterThanOrEqualTo("1.12") {
<ide><path>api/server/inspect.go
<ide> import (
<ide> "fmt"
<ide> "net/http"
<ide>
<del> "golang.org/x/net/context"
<del>
<del> "github.com/docker/docker/pkg/version"
<add> "github.com/docker/docker/context"
<ide> )
<ide>
<ide> // getContainersByName inspects containers configuration and serializes it as json.
<ide> func (s *Server) getContainersByName(ctx context.Context, w http.ResponseWriter,
<ide> var json interface{}
<ide> var err error
<ide>
<del> version, _ := ctx.Value("api-version").(version.Version)
<add> version := ctx.Version()
<ide>
<ide> switch {
<ide> case version.LessThan("1.20"):
<ide><path>api/server/server.go
<ide> import (
<ide> "strings"
<ide>
<ide> "github.com/gorilla/mux"
<del> "golang.org/x/net/context"
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/autogen/dockerversion"
<add> "github.com/docker/docker/context"
<ide> "github.com/docker/docker/daemon"
<ide> "github.com/docker/docker/pkg/sockets"
<ide> "github.com/docker/docker/pkg/stringid"
<ide> func makeHTTPHandler(logging bool, localMethod string, localRoute string, handle
<ide> // as 'args' on the function call.
<ide>
<ide> reqID := stringid.TruncateID(stringid.GenerateNonCryptoID())
<del> api_version := version.Version(mux.Vars(r)["version"])
<del> if api_version == "" {
<del> api_version = api.Version
<add> apiVersion := version.Version(mux.Vars(r)["version"])
<add> if apiVersion == "" {
<add> apiVersion = api.Version
<ide> }
<ide>
<ide> ctx := context.Background()
<del> ctx = context.WithValue(ctx, "docker-request-id", reqID)
<del> ctx = context.WithValue(ctx, "api-version", api_version)
<add> ctx = context.WithValue(ctx, context.RequestID, reqID)
<add> ctx = context.WithValue(ctx, context.APIVersion, apiVersion)
<ide>
<ide> // log the request
<ide> logrus.Debugf("Calling %s %s", localMethod, localRoute)
<ide> func makeHTTPHandler(logging bool, localMethod string, localRoute string, handle
<ide> writeCorsHeaders(w, r, corsHeaders)
<ide> }
<ide>
<del> if api_version.GreaterThan(api.Version) {
<del> http.Error(w, fmt.Errorf("client is newer than server (client API version: %s, server API version: %s)", api_version, api.Version).Error(), http.StatusBadRequest)
<add> if apiVersion.GreaterThan(api.Version) {
<add> http.Error(w, fmt.Errorf("client is newer than server (client API version: %s, server API version: %s)", apiVersion, api.Version).Error(), http.StatusBadRequest)
<ide> return
<ide> }
<del> if api_version.LessThan(api.MinVersion) {
<add> if apiVersion.LessThan(api.MinVersion) {
<ide> http.Error(w, fmt.Errorf("client is too old, minimum supported API version is %s, please upgrade your client to a newer version", api.MinVersion).Error(), http.StatusBadRequest)
<ide> return
<ide> }
<ide><path>api/server/volume.go
<ide> import (
<ide> "encoding/json"
<ide> "net/http"
<ide>
<del> "golang.org/x/net/context"
<del>
<ide> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/context"
<ide> )
<ide>
<ide> func (s *Server) getVolumesList(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide><path>context/context.go
<add>package context
<add>
<add>import (
<add> "golang.org/x/net/context"
<add>
<add> "github.com/docker/docker/pkg/version"
<add>)
<add>
<add>const (
<add> // RequestID is the unique ID for each http request
<add> RequestID = "request-id"
<add>
<add> // APIVersion is the client's requested API version
<add> APIVersion = "api-version"
<add>)
<add>
<add>// Context is just our own wrapper for the golang 'Context' - mainly
<add>// so we can add our over version of the funcs.
<add>type Context struct {
<add> context.Context
<add>}
<add>
<add>// Background creates a new Context based on golang's default one.
<add>func Background() Context {
<add> return Context{context.Background()}
<add>}
<add>
<add>// WithValue will return a Context that has this new key/value pair
<add>// associated with it. Just uses the golang version but then wraps it.
<add>func WithValue(ctx Context, key, value interface{}) Context {
<add> return Context{context.WithValue(ctx, key, value)}
<add>}
<add>
<add>// RequestID is a utility func to make it easier to get the
<add>// request ID associated with this Context/request.
<add>func (ctx Context) RequestID() string {
<add> val := ctx.Value(RequestID)
<add> if val == nil {
<add> return ""
<add> }
<add>
<add> id, ok := val.(string)
<add> if !ok {
<add> // Ideally we shouldn't panic but we also should never get here
<add> panic("Context RequestID isn't a string")
<add> }
<add> return id
<add>}
<add>
<add>// Version is a utility func to make it easier to get the
<add>// API version string associated with this Context/request.
<add>func (ctx Context) Version() version.Version {
<add> val := ctx.Value(APIVersion)
<add> if val == nil {
<add> return version.Version("")
<add> }
<add>
<add> ver, ok := val.(version.Version)
<add> if !ok {
<add> // Ideally we shouldn't panic but we also should never get here
<add> panic("Context APIVersion isn't a version.Version")
<add> }
<add> return ver
<add>}
<ide><path>context/context_test.go
<add>package context
<add>
<add>import (
<add> "testing"
<add>
<add> "github.com/docker/docker/pkg/version"
<add>)
<add>
<add>func TestContext(t *testing.T) {
<add> ctx := Background()
<add>
<add> // First make sure getting non-existent values doesn't break
<add> if id := ctx.RequestID(); id != "" {
<add> t.Fatalf("RequestID() should have been '', was: %q", id)
<add> }
<add>
<add> if ver := ctx.Version(); ver != "" {
<add> t.Fatalf("Version() should have been '', was: %q", ver)
<add> }
<add>
<add> // Test basic set/get
<add> ctx = WithValue(ctx, RequestID, "123")
<add> if ctx.RequestID() != "123" {
<add> t.Fatalf("RequestID() should have been '123'")
<add> }
<add>
<add> // Now make sure after a 2nd set we can still get both
<add> ctx = WithValue(ctx, APIVersion, version.Version("x.y"))
<add> if id := ctx.RequestID(); id != "123" {
<add> t.Fatalf("RequestID() should have been '123', was %q", id)
<add> }
<add> if ver := ctx.Version(); ver != "x.y" {
<add> t.Fatalf("Version() should have been 'x.y', was %q", ver)
<add> }
<add>} | 11 |
Java | Java | introduce @suite for testng tests | 40c51efee806fbb36de4f3337d76c36cb31aac65 | <ide><path>spring-test/src/test/java/org/springframework/test/context/testng/TestNGTestSuite.java
<add>/*
<add> * Copyright 2002-2021 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> * https://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.test.context.testng;
<add>
<add>import org.junit.platform.suite.api.IncludeEngines;
<add>import org.junit.platform.suite.api.SelectPackages;
<add>import org.junit.platform.suite.api.Suite;
<add>
<add>/**
<add> * JUnit Platform based test suite for tests written in TestNG that involve the
<add> * Spring TestContext Framework.
<add> *
<add> * <p><strong>This suite is only intended to be used manually within an IDE.</strong>
<add> *
<add> * <h3>Logging Configuration</h3>
<add> *
<add> * <p>In order for our log4j2 configuration to be used in an IDE, you must set the
<add> * following system property before running any tests — for example, in
<add> * <em>Run Configurations</em> in Eclipse.
<add> *
<add> * <pre style="code">
<add> * -Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager
<add> * </pre>
<add> *
<add> * @author Sam Brannen
<add> * @since 5.3.11
<add> */
<add>@Suite
<add>@IncludeEngines("testng")
<add>@SelectPackages("org.springframework.test.context.testng")
<add>class TestNGTestSuite {
<add>} | 1 |
Text | Text | clarify availability of analytics | 6e3acddc44379eb5d13c923ec08d2f51f0475af9 | <ide><path>docs/Analytics.md
<ide> As far as we can tell it would be impossible for Google to match the randomly ge
<ide> Homebrew's analytics are sent throughout Homebrew's execution to Google Analytics over HTTPS.
<ide>
<ide> ## Who?
<del>Homebrew's analytics are accessible to Homebrew's current maintainers. Contact @MikeMcQuaid if you are a maintainer and need access.
<add>Homebrew's detailed analytics are accessible to Homebrew's current maintainers. Contact @MikeMcQuaid if you are a maintainer and need access.
<add>
<add>Summaries of installation and error analytics are publicly available [here](https://brew.sh/analytics/).
<ide>
<ide> ## How?
<ide> The code is viewable in [analytics.rb](https://github.com/Homebrew/brew/blob/master/Library/Homebrew/utils/analytics.rb) and [analytics.sh](https://github.com/Homebrew/brew/blob/master/Library/Homebrew/utils/analytics.sh). They are done in a separate background process and fail fast to avoid delaying any execution. They will fail immediately and silently if you have no network connection. | 1 |
Text | Text | clarify new use of tag revision | af66c12108466fe541403638a8742a9dc78039e3 | <ide><path>share/doc/homebrew/Formula-Cookbook.md
<ide> end
<ide>
<ide> Homebrew understands `git`, `svn`, and `hg` URLs, and has a way to specify `cvs` repositories as a URL as well. You can test whether the `HEAD` is being built with `build.head?`.
<ide>
<del>To use a specific commit, tag, or branch from a repository, specify head with the `:revision`, `:tag`, or `:branch` option, like so:
<add>To use a specific commit, tag, or branch from a repository, specify head with the `:tag` and `:revision`, `:revision`, or `:branch` option, like so:
<ide>
<ide> ```ruby
<ide> class Foo < Formula
<ide> head "https://github.com/some/package.git", :revision => "090930930295adslfknsdfsdaffnasd13"
<ide> # or :branch => "develop"
<del> # or :tag => "1_0_release"
<add> # or :tag => "1_0_release",
<add> # :revision => "090930930295adslfknsdfsdaffnasd13"
<ide> end
<ide> ```
<ide> | 1 |
Mixed | Javascript | use url module instead of punycode for idna | d85e1f070302babcb4649eae8705103eb49db7ac | <ide><path>doc/api/intl.md
<ide> option:
<ide> | `String.prototype.toLocale*Case()` | partial (not locale-aware) | full | full | full |
<ide> | [`Number.prototype.toLocaleString()`][] | partial (not locale-aware) | partial/full (depends on OS) | partial (English-only) | full |
<ide> | `Date.prototype.toLocale*String()` | partial (not locale-aware) | partial/full (depends on OS) | partial (English-only) | full |
<add>| [Legacy URL Parser][] | partial (no IDN support) | full | full | full |
<ide> | [WHATWG URL Parser][] | partial (no IDN support) | full | full | full |
<ide> | [`require('buffer').transcode()`][] | none (function does not exist) | full | full | full |
<ide> | [REPL][] | partial (inaccurate line editing) | full | full | full |
<ide> to be helpful:
<ide> [ECMA-262]: https://tc39.github.io/ecma262/
<ide> [ECMA-402]: https://tc39.github.io/ecma402/
<ide> [ICU]: http://site.icu-project.org/
<add>[Legacy URL parser]: url.md#url_legacy_url_api
<ide> [REPL]: repl.md#repl_repl
<ide> [Test262]: https://github.com/tc39/test262/tree/HEAD/test/intl402
<ide> [WHATWG URL parser]: url.md#url_the_whatwg_url_api
<ide><path>lib/internal/idna.js
<ide> if (internalBinding('config').hasIntl) {
<ide> const { toASCII, toUnicode } = internalBinding('icu');
<ide> module.exports = { toASCII, toUnicode };
<ide> } else {
<del> const { toASCII, toUnicode } = require('punycode');
<del> module.exports = { toASCII, toUnicode };
<add> const { domainToASCII, domainToUnicode } = require('internal/url');
<add> module.exports = { toASCII: domainToASCII, toUnicode: domainToUnicode };
<ide> }
<ide><path>test/parallel/test-bootstrap-modules.js
<ide> if (!common.isMainThread) {
<ide> if (common.hasIntl) {
<ide> expectedModules.add('Internal Binding icu');
<ide> } else {
<del> expectedModules.add('NativeModule punycode');
<add> expectedModules.add('NativeModule url');
<ide> }
<ide>
<ide> if (process.features.inspector) {
<ide><path>test/parallel/test-url-format.js
<ide> 'use strict';
<del>require('../common');
<add>const common = require('../common');
<ide> const assert = require('assert');
<ide> const url = require('url');
<ide>
<add>if (!common.hasIntl)
<add> common.skip('missing Intl');
<add>
<ide> // Formatting tests to verify that it'll format slightly wonky content to a
<ide> // valid URL.
<ide> const formatTests = {
<ide><path>test/parallel/test-url-parse-format.js
<ide> 'use strict';
<del>require('../common');
<add>const common = require('../common');
<add>
<add>if (!common.hasIntl)
<add> common.skip('missing Intl');
<add>
<ide> const assert = require('assert');
<ide> const inspect = require('util').inspect;
<ide> | 5 |
Javascript | Javascript | fix lint errors | 16b2fba851e851b497c9f6e7d10b61faa3c68a6f | <ide><path>src/text-editor-component.js
<ide> class LinesTileComponent {
<ide> }
<ide>
<ide> renderHighlights () {
<del> const {top, height, width, lineHeight, highlightDecorations} = this.props
<add> const {top, lineHeight, highlightDecorations} = this.props
<ide>
<ide> let children = null
<ide> if (highlightDecorations) {
<ide> class LinesTileComponent {
<ide>
<ide> createLines () {
<ide> const {
<del> element, tileStartRow, screenLines, lineDecorations,
<add> tileStartRow, screenLines, lineDecorations,
<ide> displayLayer, lineNodesByScreenLineId, textNodesByScreenLineId
<ide> } = this.props
<ide> | 1 |
Javascript | Javascript | add test for instance method on getinitialprops. | 2c916137b277f018849b6a9daa0503d71ac19f01 | <ide><path>test/integration/basic/pages/instance-get-initial-props.js
<add>import React from 'react'
<add>
<add>export default class InstanceInitialPropsPage extends React.Component {
<add> async getInitialProps () {
<add> return fetchData()
<add> }
<add>
<add> render () {
<add> return <p>{this.props.name}</p>
<add> }
<add>}
<add>
<add>function fetchData () {
<add> const p = new Promise(resolve => {
<add> setTimeout(() => resolve({ name: 'Anderson Leite' }), 10)
<add> })
<add> return p
<add>}
<ide><path>test/integration/basic/test/rendering.js
<ide> export default function ({ app }, suiteName, render, fetch) {
<ide> expect(link.text()).toBe('About')
<ide> })
<ide>
<add> test('getInitialProps should be class method', async () => {
<add> const $ = await get$('/instance-get-initial-props')
<add> const expectedErrorMessage = '"InstanceInitialPropsPage.getInitialProps()" is defined as an instance method - visit https://err.sh/zeit/next.js/get-initial-props-as-an-instance-method for more information.'
<add> expect($('pre').text().includes(expectedErrorMessage)).toBeTruthy()
<add> })
<add>
<ide> test('getInitialProps resolves to null', async () => {
<ide> const $ = await get$('/empty-get-initial-props')
<ide> const expectedErrorMessage = '"EmptyInitialPropsPage.getInitialProps()" should resolve to an object. But found "null" instead.' | 2 |
Javascript | Javascript | reduce duplication with factory | 5c6c02996b7f0d21fd92e75937dedbda0dc44ac7 | <ide><path>lib/async_hooks.js
<ide> const init_symbol = Symbol('init');
<ide> const before_symbol = Symbol('before');
<ide> const after_symbol = Symbol('after');
<ide> const destroy_symbol = Symbol('destroy');
<add>const emitBeforeNative = emitHookFactory(before_symbol, 'emitBeforeNative');
<add>const emitAfterNative = emitHookFactory(after_symbol, 'emitAfterNative');
<add>const emitDestroyNative = emitHookFactory(destroy_symbol, 'emitDestroyNative');
<ide>
<ide> // Setup the callbacks that node::AsyncWrap will call when there are hooks to
<ide> // process. They use the same functions as the JS embedder API. These callbacks
<ide> // are setup immediately to prevent async_wrap.setupHooks() from being hijacked
<ide> // and the cost of doing so is negligible.
<ide> async_wrap.setupHooks({ init,
<del> before: emitBeforeN,
<del> after: emitAfterN,
<del> destroy: emitDestroyN });
<add> before: emitBeforeNative,
<add> after: emitAfterNative,
<add> destroy: emitDestroyNative });
<ide>
<ide> // Used to fatally abort the process if a callback throws.
<ide> function fatalError(e) {
<ide> function emitInitS(asyncId, type, triggerAsyncId, resource) {
<ide> triggerAsyncId = initTriggerId();
<ide> }
<ide>
<del> // I'd prefer allowing these checks to not exist, or only throw in a debug
<del> // build, in order to improve performance.
<add> // TODO(trevnorris): I'd prefer allowing these checks to not exist, or only
<add> // throw in a debug build, in order to improve performance.
<ide> if (!Number.isSafeInteger(asyncId) || asyncId < 0)
<ide> throw new RangeError('asyncId must be an unsigned integer');
<ide> if (typeof type !== 'string' || type.length <= 0)
<ide> function emitInitS(asyncId, type, triggerAsyncId, resource) {
<ide> }
<ide> }
<ide>
<del>
<del>function emitBeforeN(asyncId) {
<del> processing_hook = true;
<del> // Use a single try/catch for all hook to avoid setting up one per iteration.
<del> try {
<del> for (var i = 0; i < active_hooks_array.length; i++) {
<del> if (typeof active_hooks_array[i][before_symbol] === 'function') {
<del> active_hooks_array[i][before_symbol](asyncId);
<add>function emitHookFactory(symbol, name) {
<add> // Called from native. The asyncId stack handling is taken care of there
<add> // before this is called.
<add> // eslint-disable-next-line func-style
<add> const fn = function(asyncId) {
<add> processing_hook = true;
<add> // Use a single try/catch for all hook to avoid setting up one per
<add> // iteration.
<add> try {
<add> for (var i = 0; i < active_hooks_array.length; i++) {
<add> if (typeof active_hooks_array[i][symbol] === 'function') {
<add> active_hooks_array[i][symbol](asyncId);
<add> }
<ide> }
<add> } catch (e) {
<add> fatalError(e);
<ide> }
<del> } catch (e) {
<del> fatalError(e);
<del> }
<del> processing_hook = false;
<add> processing_hook = false;
<ide>
<del> if (tmp_active_hooks_array !== null) {
<del> restoreTmpHooks();
<del> }
<add> if (tmp_active_hooks_array !== null) {
<add> restoreTmpHooks();
<add> }
<add> };
<add> // Set the name property of the anonymous function as it looks good in the
<add> // stack trace.
<add> Object.defineProperty(fn, 'name', {
<add> value: name
<add> });
<add> return fn;
<ide> }
<ide>
<ide>
<ide> function emitBeforeS(asyncId, triggerAsyncId = asyncId) {
<ide>
<ide> if (async_hook_fields[kBefore] === 0)
<ide> return;
<del> emitBeforeN(asyncId);
<del>}
<del>
<del>
<del>// Called from native. The asyncId stack handling is taken care of there before
<del>// this is called.
<del>function emitAfterN(asyncId) {
<del> processing_hook = true;
<del> // Use a single try/catch for all hook to avoid setting up one per iteration.
<del> try {
<del> for (var i = 0; i < active_hooks_array.length; i++) {
<del> if (typeof active_hooks_array[i][after_symbol] === 'function') {
<del> active_hooks_array[i][after_symbol](asyncId);
<del> }
<del> }
<del> } catch (e) {
<del> fatalError(e);
<del> }
<del> processing_hook = false;
<del>
<del> if (tmp_active_hooks_array !== null) {
<del> restoreTmpHooks();
<del> }
<add> emitBeforeNative(asyncId);
<ide> }
<ide>
<ide>
<ide> function emitAfterN(asyncId) {
<ide> // after callbacks.
<ide> function emitAfterS(asyncId) {
<ide> if (async_hook_fields[kAfter] > 0)
<del> emitAfterN(asyncId);
<add> emitAfterNative(asyncId);
<ide>
<ide> popAsyncIds(asyncId);
<ide> }
<ide> function emitDestroyS(asyncId) {
<ide> }
<ide>
<ide>
<del>function emitDestroyN(asyncId) {
<del> processing_hook = true;
<del> // Use a single try/catch for all hook to avoid setting up one per iteration.
<del> try {
<del> for (var i = 0; i < active_hooks_array.length; i++) {
<del> if (typeof active_hooks_array[i][destroy_symbol] === 'function') {
<del> active_hooks_array[i][destroy_symbol](asyncId);
<del> }
<del> }
<del> } catch (e) {
<del> fatalError(e);
<del> }
<del> processing_hook = false;
<del>
<del> if (tmp_active_hooks_array !== null) {
<del> restoreTmpHooks();
<del> }
<del>}
<del>
<del>
<ide> // Emit callbacks for native calls. Since some state can be setup directly from
<ide> // C++ there's no need to perform all the work here.
<ide> | 1 |
Go | Go | fix couple of panics in networkdb | 774399fd661ff5b6fba453891646001a79675535 | <ide><path>libnetwork/networkdb/cluster.go
<ide> func (nDB *NetworkDB) reapTableEntries() {
<ide> func (nDB *NetworkDB) gossip() {
<ide> networkNodes := make(map[string][]string)
<ide> nDB.RLock()
<del> for nid := range nDB.networks[nDB.config.NodeName] {
<add> thisNodeNetworks := nDB.networks[nDB.config.NodeName]
<add> for nid := range thisNodeNetworks {
<ide> networkNodes[nid] = nDB.networkNodes[nid]
<ide>
<ide> }
<ide> func (nDB *NetworkDB) gossip() {
<ide> bytesAvail := udpSendBuf - compoundHeaderOverhead
<ide>
<ide> nDB.RLock()
<del> broadcastQ := nDB.networks[nDB.config.NodeName][nid].tableBroadcasts
<add> network, ok := thisNodeNetworks[nid]
<ide> nDB.RUnlock()
<add> if !ok || network == nil {
<add> // It is normal for the network to be removed
<add> // between the time we collect the network
<add> // attachments of this node and processing
<add> // them here.
<add> continue
<add> }
<add>
<add> broadcastQ := network.tableBroadcasts
<ide>
<ide> if broadcastQ == nil {
<ide> logrus.Errorf("Invalid broadcastQ encountered while gossiping for network %s", nid)
<ide><path>libnetwork/networkdb/delegate.go
<ide> func (nDB *NetworkDB) handleTableMessage(buf []byte) {
<ide> }
<ide>
<ide> broadcastQ := n.tableBroadcasts
<add>
<add> if broadcastQ == nil {
<add> return
<add> }
<add>
<ide> broadcastQ.QueueBroadcast(&tableEventMessage{
<ide> msg: buf,
<ide> id: tEvent.NetworkID, | 2 |
Javascript | Javascript | remove redundant setupdatepriority call | 64983aab5d4dbd99ca06bb85e69bb193928ea0c7 | <ide><path>packages/react-reconciler/src/ReactFiberHooks.new.js
<ide> import {
<ide> markRootMutableRead,
<ide> } from './ReactFiberLane.new';
<ide> import {
<del> DefaultEventPriority,
<ide> ContinuousEventPriority,
<ide> getCurrentUpdatePriority,
<ide> setCurrentUpdatePriority,
<ide> function startTransition(setPending, callback) {
<ide>
<ide> setPending(true);
<ide>
<del> // TODO: Can remove this. Was only necessary because we used to give
<del> // different behavior to transitions without a config object. Now they are
<del> // all treated the same.
<del> setCurrentUpdatePriority(DefaultEventPriority);
<del>
<ide> const prevTransition = ReactCurrentBatchConfig.transition;
<ide> ReactCurrentBatchConfig.transition = 1;
<ide> try {
<ide><path>packages/react-reconciler/src/ReactFiberHooks.old.js
<ide> import {
<ide> markRootMutableRead,
<ide> } from './ReactFiberLane.old';
<ide> import {
<del> DefaultEventPriority,
<ide> ContinuousEventPriority,
<ide> getCurrentUpdatePriority,
<ide> setCurrentUpdatePriority,
<ide> function startTransition(setPending, callback) {
<ide>
<ide> setPending(true);
<ide>
<del> // TODO: Can remove this. Was only necessary because we used to give
<del> // different behavior to transitions without a config object. Now they are
<del> // all treated the same.
<del> setCurrentUpdatePriority(DefaultEventPriority);
<del>
<ide> const prevTransition = ReactCurrentBatchConfig.transition;
<ide> ReactCurrentBatchConfig.transition = 1;
<ide> try { | 2 |
PHP | PHP | add sparse insert support | f5cbbc3730865ec0f3e654ec0d26b255260ffc81 | <ide><path>lib/Cake/Model/Datasource/Database/Expression/ValuesExpression.php
<ide> class ValuesExpression implements Expression {
<ide>
<ide> protected $_values = [];
<add> protected $_columns = [];
<add>
<add> public function __construct($columns) {
<add> $this->_columns = $columns;
<add> }
<ide>
<ide> /**
<ide> * Add a row of data to be inserted.
<ide> public function add($data) {
<ide> public function bindings() {
<ide> $bindings = [];
<ide> $i = 0;
<add> $defaults = array_fill_keys($this->_columns, null);
<ide> foreach ($this->_values as $row) {
<add> $row = array_merge($defaults, $row);
<ide> foreach ($row as $column => $value) {
<ide> $bindings[] = [
<ide> // TODO add types.
<ide> public function bindings() {
<ide> */
<ide> public function sql() {
<ide> $placeholders = [];
<add> $numColumns = count($this->_columns);
<ide> foreach ($this->_values as $row) {
<ide> if (is_array($row)) {
<del> $placeholders[] = implode(', ', array_fill(0, count($row), '?'));
<add> $placeholders[] = implode(', ', array_fill(0, $numColumns, '?'));
<ide> }
<ide> }
<ide> return sprintf('(%s)', implode('), (', $placeholders));
<ide><path>lib/Cake/Model/Datasource/Database/Query.php
<ide> namespace Cake\Model\Datasource\Database;
<ide>
<ide> use IteratorAggregate;
<add>use Cake\Error;
<ide> use Cake\Model\Datasource\Database\Expression\Comparison;
<ide> use Cake\Model\Datasource\Database\Expression\OrderByExpression;
<ide> use Cake\Model\Datasource\Database\Expression\QueryExpression;
<ide> protected function _buildValuesPart($parts) {
<ide> /**
<ide> * Create an insert query.
<ide> *
<add> * Note calling this method will reset any data previously set
<add> * with Query::values()
<add> *
<ide> * @param string $table The table name to insert into.
<ide> * @param array $columns The columns to insert into.
<ide> * @return Query
<ide> public function insert($table, $columns) {
<ide> $this->_dirty = true;
<ide> $this->_type = 'insert';
<ide> $this->_parts['insert'] = [$table, $columns];
<add> $this->_parts['values'] = new ValuesExpression($columns);
<ide> return $this;
<ide> }
<ide>
<ide> public function insert($table, $columns) {
<ide> *
<ide> * @param array|Query $data The data to insert.
<ide> * @return Query
<add> * @throws Cake\Error\Exception if you try to set values before declaring columns.
<add> * Or if you try to set values on non-insert queries.
<ide> */
<ide> public function values($data) {
<del> if (empty($this->_parts['values'])) {
<del> $this->_parts['values'] = new ValuesExpression();
<add> if ($this->_type !== 'insert') {
<add> throw new Error\Exception(
<add> __d('cake_dev', 'You cannot add values before defining columns to use.')
<add> );
<add> }
<add> if (empty($this->_parts['insert'])) {
<add> throw new Error\Exception(
<add> __d('cake_dev', 'You cannot add values before defining columns to use.')
<add> );
<ide> }
<ide> $this->_dirty = true;
<ide> $this->_parts['values']->add($data);
<ide><path>lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php
<ide> public function testUpdateWithExpression() {
<ide> $this->assertCount(1, $result);
<ide> }
<ide>
<add>/**
<add> * You cannot call values() before insert() it causes all sorts of pain.
<add> *
<add> * @expectedException Cake\Error\Exception
<add> */
<add> public function testInsertValuesBeforeInsertFailure() {
<add> $query = new Query($this->connection);
<add> $query->select('*')->values([
<add> 'id' => 1,
<add> 'title' => 'mark',
<add> 'body' => 'test insert'
<add> ]);
<add> }
<add>
<ide> /**
<ide> * Test inserting a single row.
<ide> *
<ide> public function testInsertSimple() {
<ide> $this->assertEquals($expected, $result->fetchAll('assoc')[0]);
<ide> }
<ide>
<add>/**
<add> * Test an insert when not all the listed fields are provided.
<add> * Columns should be matched up where possible.
<add> *
<add> * @return void
<add> */
<ide> public function testInsertSparseRow() {
<del> $this->markTestIncomplete();
<add> $this->_createAuthorsAndArticles();
<add>
<add> $query = new Query($this->connection);
<add> $query->insert('articles', ['id', 'title', 'body'])
<add> ->values([
<add> 'body' => 'test insert',
<add> 'title' => 'mark',
<add> ]);
<add> $result = $query->sql(false);
<add> $this->assertEquals(
<add> 'INSERT INTO articles (id, title, body) VALUES (?, ?, ?)',
<add> $result
<add> );
<add>
<add> $result = $query->execute();
<add> $this->assertCount(1, $result, '1 row should be inserted');
<add>
<add> $result = (new Query($this->connection))->select('*')
<add> ->from('articles')
<add> ->execute();
<add> $this->assertCount(1, $result);
<add>
<add> $expected = [
<add> 'id' => null,
<add> 'author_id' => null,
<add> 'title' => 'mark',
<add> 'body' => 'test insert'
<add> ];
<add> $this->assertEquals($expected, $result->fetchAll('assoc')[0]);
<ide> }
<ide>
<add>/**
<add> * Test inserting multiple rows.
<add> *
<add> * @return void
<add> */
<ide> public function testInsertMultipleRows() {
<del> $this->markTestIncomplete();
<add> $this->_createAuthorsAndArticles();
<add>
<add> $query = new Query($this->connection);
<add> $query->insert('articles', ['id', 'title', 'body'])
<add> ->values([
<add> 'id' => 1,
<add> 'title' => 'mark',
<add> 'body' => 'test insert'
<add> ])
<add> ->values([
<add> 'id' => 2,
<add> 'title' => 'jose',
<add> 'body' => 'test insert'
<add> ]);
<add> $result = $query->sql(false);
<add> $this->assertEquals(
<add> 'INSERT INTO articles (id, title, body) VALUES (?, ?, ?), (?, ?, ?)',
<add> $result
<add> );
<add>
<add> $result = $query->execute();
<add> $this->assertCount(2, $result, '2 row should be inserted');
<ide> }
<ide>
<ide> public function testInsertMultipleRowsSparse() { | 3 |
Text | Text | mention `corepack prepare` supports tag or range | 4e659be9f8008db9539470e0b33bed6ab5b913b0 | <ide><path>doc/api/corepack.md
<ide> package manager version you wish to set:
<ide> corepack prepare yarn@x.y.z --activate
<ide> ```
<ide>
<add>Alternately, a tag or range may be used:
<add>
<add>```bash
<add>corepack prepare pnpm@latest --activate
<add>corepack prepare yarn@stable --activate
<add>```
<add>
<ide> ### Offline workflow
<ide>
<ide> Many production environments don't have network access. Since Corepack | 1 |
PHP | PHP | extract an interface for fixtures and connections | cefc37f9775dde7e4b92e9cbe4c2c2145c3151f2 | <ide><path>src/Database/Connection.php
<ide> */
<ide> namespace Cake\Database;
<ide>
<add>use Cake\Datasource\ConnectionInterface;
<ide> use Cake\Database\Exception\MissingConnectionException;
<ide> use Cake\Database\Exception\MissingDriverException;
<ide> use Cake\Database\Exception\MissingExtensionException;
<ide> /**
<ide> * Represents a connection with a database server.
<ide> */
<del>class Connection
<add>class Connection implements ConnectionInterface
<ide> {
<ide>
<ide> use TypeConverterTrait;
<ide><path>src/Datasource/ConnectionInterface.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since 3.1.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Datasource;
<add>
<add>/**
<add> * This interface defines the methods you can depend on in
<add> * a connection.
<add> */
<add>interface ConnectionInterface
<add>{
<add>
<add>}
<ide><path>src/Datasource/FixtureInterface.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since 3.1.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Datasource;
<add>
<add>use Cake\Datasource\ConnectionInterface;
<add>
<add>/**
<add> * Defines the interface that testing fixtures use.
<add> */
<add>interface FixtureInterface
<add>{
<add> /**
<add> * Create the fixture schema/mapping/definition
<add> *
<add> * @param Connection $db An instance of the connection the fixture should be created on.
<add> * @return bool True on success, false on failure.
<add> */
<add> public function create(ConnectionInterface $db);
<add>
<add> /**
<add> * Run after all tests executed, should remove the table/collection from the connection.
<add> *
<add> * @param Connection $db An instance of the connection the fixture should be removed from.
<add> * @return bool True on success, false on failure.
<add> */
<add> public function drop(ConnectionInterface $db);
<add>
<add> /**
<add> * Run before each test is executed.
<add> *
<add> * Should insert all the records into the test database.
<add> *
<add> * @param Connection $db An instance of the connection into which the records will be inserted.
<add> * @return bool on success or if there are no records to insert, or false on failure.
<add> */
<add> public function insert(ConnectionInterface $db);
<add>
<add> /**
<add> * Truncates the current fixture.
<add> *
<add> * @param Connection $db A reference to a db instance
<add> * @return bool
<add> */
<add> public function truncate(ConnectionInterface $db);
<add>
<add> /**
<add> * Get the connection name this fixture should be inserted into.
<add> *
<add> * @return string
<add> */
<add> public function connection();
<add>
<add> /**
<add> * Get the table/collection name for this fixture.
<add> *
<add> * @return string
<add> */
<add> public function sourceName();
<add>}
<ide><path>src/TestSuite/Fixture/FixtureManager.php
<ide> class FixtureManager
<ide> */
<ide> protected $_fixtureMap = [];
<ide>
<add> /**
<add> * A map of connection names and the fixture currently in it.
<add> *
<add> * @var array
<add> */
<add> protected $_insertionMap = [];
<add>
<ide> /**
<ide> * Inspects the test to look for unloaded fixtures and loads them
<ide> *
<ide> protected function _loadFixtures($test)
<ide> */
<ide> protected function _setupTable($fixture, $db, array $sources, $drop = true)
<ide> {
<del> if (!empty($fixture->created) && in_array($db->configName(), $fixture->created)) {
<add> $configName = $db->configName();
<add> if ($this->isFixtureSetup($configName, $fixture)) {
<ide> return;
<ide> }
<ide>
<del> $table = $fixture->table;
<add> $table = $fixture->sourceName();
<ide> $exists = in_array($table, $sources);
<ide>
<ide> if ($drop && $exists) {
<ide> protected function _setupTable($fixture, $db, array $sources, $drop = true)
<ide> } elseif (!$exists) {
<ide> $fixture->create($db);
<ide> } else {
<del> $fixture->created[] = $db->configName();
<add> $this->_insertionMap[$configName][] = $fixture;
<ide> $fixture->truncate($db);
<ide> }
<ide> }
<ide> public function load($test)
<ide> try {
<ide> $createTables = function ($db, $fixtures) use ($test) {
<ide> $tables = $db->schemaCollection()->listTables();
<add> $configName = $db->configName();
<add> if (!isset($this->_insertionMap[$configName])) {
<add> $this->_insertionMap[$configName] = [];
<add> }
<ide> foreach ($fixtures as $fixture) {
<del> if (!in_array($db->configName(), (array)$fixture->created)) {
<add> if (!in_array($fixture, $this->_insertionMap[$configName])) {
<ide> $this->_setupTable($fixture, $db, $tables, $test->dropTables);
<ide> } else {
<ide> $fixture->truncate($db);
<ide> protected function _fixtureConnections($fixtures)
<ide> foreach ($fixtures as $f) {
<ide> if (!empty($this->_loaded[$f])) {
<ide> $fixture = $this->_loaded[$f];
<del> $dbs[$fixture->connection][$f] = $fixture;
<add> $dbs[$fixture->connection()][$f] = $fixture;
<ide> }
<ide> }
<ide> return $dbs;
<ide> public function unload($test)
<ide> return;
<ide> }
<ide> $truncate = function ($db, $fixtures) {
<del> $connection = $db->configName();
<add> $configName = $db->configName();
<ide> foreach ($fixtures as $fixture) {
<del> if (!empty($fixture->created) && in_array($connection, $fixture->created)) {
<add> if ($this->isFixtureSetup($configName, $fixture)) {
<ide> $fixture->truncate($db);
<ide> }
<ide> }
<ide> public function loadSingle($name, $db = null, $dropTables = true)
<ide> if (isset($this->_fixtureMap[$name])) {
<ide> $fixture = $this->_fixtureMap[$name];
<ide> if (!$db) {
<del> $db = ConnectionManager::get($fixture->connection);
<add> $db = ConnectionManager::get($fixture->connection());
<ide> }
<ide>
<del> if (!in_array($db->configName(), (array)$fixture->created)) {
<add> if (!$this->isFixtureSetup($db->configName(), $fixture)) {
<ide> $sources = $db->schemaCollection()->listTables();
<ide> $this->_setupTable($fixture, $db, $sources, $dropTables);
<ide> }
<ide> public function shutDown()
<ide> $shutdown = function ($db, $fixtures) {
<ide> $connection = $db->configName();
<ide> foreach ($fixtures as $fixture) {
<del> if (!empty($fixture->created) && in_array($connection, $fixture->created)) {
<add> if ($this->isFixtureSetup($connection, $fixture)) {
<ide> $fixture->drop($db);
<add> $index = array_search($fixture, $this->_insertionMap[$connection]);
<add> unset($this->_insertionMap[$connection][$index]);
<ide> }
<ide> }
<ide> };
<ide> $this->_runOperation(array_keys($this->_loaded), $shutdown);
<ide> }
<add>
<add> /**
<add> * Check whether or not a fixture has been inserted in a given connection name.
<add> *
<add> * @param string $connection The connection name.
<add> * @param \Cake\Datasource\FixtureInterface $fixture The fixture to check.
<add> * @return bool
<add> */
<add> public function isFixtureSetup($connection, $fixture)
<add> {
<add> return isset($this->_insertionMap[$connection]) && in_array($fixture, $this->_insertionMap[$connection]);
<add> }
<add>
<ide> }
<ide><path>src/TestSuite/Fixture/TestFixture.php
<ide> namespace Cake\TestSuite\Fixture;
<ide>
<ide> use Cake\Core\Exception\Exception;
<del>use Cake\Database\Connection;
<add>use Cake\Datasource\ConnectionInterface;
<ide> use Cake\Database\Schema\Table;
<ide> use Cake\Datasource\ConnectionManager;
<add>use Cake\Datasource\FixtureInterface;
<ide> use Cake\Log\Log;
<ide> use Cake\Utility\Inflector;
<ide>
<ide> /**
<ide> * Cake TestFixture is responsible for building and destroying tables to be used
<ide> * during testing.
<ide> */
<del>class TestFixture
<add>class TestFixture implements FixtureInterface
<ide> {
<ide>
<ide> /**
<ide> class TestFixture
<ide> */
<ide> public $table = null;
<ide>
<del> /**
<del> * List of datasources where this fixture has been created
<del> *
<del> * @var array
<del> */
<del> public $created = [];
<del>
<ide> /**
<ide> * Fields / Schema for the fixture.
<ide> *
<ide> public function __construct()
<ide> $this->init();
<ide> }
<ide>
<add> /**
<add> * {@inheritDoc}
<add> */
<add> public function connection()
<add> {
<add> return $this->connection;
<add> }
<add>
<add> /**
<add> * {@inheritDoc}
<add> */
<add> public function sourceName()
<add> {
<add> return $this->table;
<add> }
<add>
<ide> /**
<ide> * Initialize the fixture.
<ide> *
<ide> public function schema(Table $schema = null)
<ide> }
<ide>
<ide> /**
<del> * Run before all tests execute, should return SQL statement to create table for this fixture could be executed successfully.
<del> *
<del> * @param Connection $db An instance of the database object used to create the fixture table
<del> * @return bool True on success, false on failure
<add> * {@inheritDoc}
<ide> */
<del> public function create(Connection $db)
<add> public function create(ConnectionInterface $db)
<ide> {
<ide> if (empty($this->_schema)) {
<ide> return false;
<ide> public function create(Connection $db)
<ide> }
<ide>
<ide> /**
<del> * Run after all tests executed, should return SQL statement to drop table for this fixture.
<del> *
<del> * @param Connection $db An instance of the database object used to create the fixture table
<del> * @return bool True on success, false on failure
<add> * {@inheritDoc}
<ide> */
<del> public function drop(Connection $db)
<add> public function drop(ConnectionInterface $db)
<ide> {
<ide> if (empty($this->_schema)) {
<ide> return false;
<ide> public function drop(Connection $db)
<ide> foreach ($sql as $stmt) {
<ide> $db->execute($stmt)->closeCursor();
<ide> }
<del> $this->created = array_diff($this->created, [$db->configName()]);
<ide> } catch (\Exception $e) {
<ide> return false;
<ide> }
<ide> return true;
<ide> }
<ide>
<ide> /**
<del> * Run before each tests is executed, should return a set of SQL statements to insert records for the table
<del> * of this fixture could be executed successfully.
<del> *
<del> * @param Connection $db An instance of the database into which the records will be inserted
<del> * @return bool on success or if there are no records to insert, or false on failure
<add> * {@inheritDoc}
<ide> */
<del> public function insert(Connection $db)
<add> public function insert(ConnectionInterface $db)
<ide> {
<ide> if (isset($this->records) && !empty($this->records)) {
<ide> list($fields, $values, $types) = $this->_getRecords();
<ide> protected function _getRecords()
<ide> }
<ide>
<ide> /**
<del> * Truncates the current fixture. Can be overwritten by classes extending
<del> * CakeFixture to trigger other events before / after truncate.
<del> *
<del> * @param Connection $db A reference to a db instance
<del> * @return bool
<add> * {@inheritDoc}
<ide> */
<del> public function truncate(Connection $db)
<add> public function truncate(ConnectionInterface $db)
<ide> {
<ide> $sql = $this->_schema->truncateSql($db);
<ide> foreach ($sql as $stmt) { | 5 |
Javascript | Javascript | add assets to module stats | ebda43139916569128e6def5eff0da12f9893380 | <ide><path>lib/Stats.js
<ide> Stats.prototype.toJson = function toJson(options, forToString) {
<ide> chunks: module.chunks.map(function(chunk) {
<ide> return chunk.id;
<ide> }),
<add> assets: Object.keys(module.assets || {}),
<ide> issuer: module.issuer,
<ide> profile: module.profile,
<ide> failed: !!module.error, | 1 |
PHP | PHP | move driver specific code into mysqldialect | 394321339b81900154da0b434eebd18f7af2f8cd | <ide><path>lib/Cake/Model/Datasource/Database/Connection.php
<ide> public function describe($table) {
<ide> $schema = [];
<ide>
<ide> $fieldParams = $this->_driver->extraSchemaColumns();
<del>
<del> while ($row = $statement->fetch('assoc')) {
<del> list($type, $length) = $this->_driver->columnType($row['Type']);
<del> $schema[$row['Field']] = [
<del> 'type' => $type,
<del> 'null' => $row['Null'] === 'YES' ? true : false,
<del> 'default' => $row['Default'],
<del> 'length' => $length,
<del> ];
<del> if (!empty($row['Key'])) {
<del> $schema[$row['Field']]['key'] = $this->_driver->keyType($row['Key']);
<del> }
<del> foreach ($fieldParams as $key => $metadata) {
<del> if (!empty($row[$metadata['column']])) {
<del> $schema[$row['Field']][$key] = $row[$metadata['column']];
<del> }
<del> }
<add> $rows = $statement->fetchAll('assoc');
<add> foreach ($rows as $row) {
<add> $schema += $this->_driver->convertFieldDescription($row, $fieldParams);
<ide> }
<ide> return $schema;
<ide> }
<ide><path>lib/Cake/Model/Datasource/Database/Dialect/MysqlDialectTrait.php
<ide> public function describeTableSql($table) {
<ide> * @param string $key The key type to convert.
<ide> * @return string The abstract key type (primary, unique, index)
<ide> */
<del> public function keyType($key) {
<add> public function convertIndex($key) {
<ide> if ($key === 'PRI') {
<ide> return 'primary';
<ide> }
<ide> if ($key === 'MUL') {
<ide> return 'index';
<ide> }
<del> if ($key === 'uni') {
<add> if ($key === 'UNI') {
<ide> return 'unique';
<ide> }
<ide> }
<ide> public function keyType($key) {
<ide> * @param string $column The column type + length
<ide> * @return array List of (type, length)
<ide> */
<del> public function columnType($column) {
<add> public function convertColumn($column) {
<ide> preg_match('/([a-z]+)(?:\(([0-9,]+)\))?/i', $column, $matches);
<ide> if (empty($matches)) {
<ide> throw new Error\Exception(__d('cake_dev', 'Unable to parse column type from "%s"', $column));
<ide> public function columnType($column) {
<ide> }
<ide>
<ide> if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
<del> return [$col, $length];
<add> return [$col, null];
<ide> }
<ide> if (($col === 'tinyint' && $length === 1) || $col === 'boolean') {
<ide> return ['boolean', null];
<ide> public function columnType($column) {
<ide> if (strpos($col, 'decimal') !== false) {
<ide> return ['decimal', null];
<ide> }
<del> return 'text';
<add> return ['text', null];
<add> }
<add>
<add>/**
<add> * Convert field description results into abstract schema fields.
<add> *
<add> * @return array An array of with the key/values of schema data.
<add> */
<add> public function convertFieldDescription($row, $fieldParams = []) {
<add> list($type, $length) = $this->convertColumn($row['Type']);
<add> $schema = [];
<add> $schema[$row['Field']] = [
<add> 'type' => $type,
<add> 'null' => $row['Null'] === 'YES' ? true : false,
<add> 'default' => $row['Default'],
<add> 'length' => $length,
<add> ];
<add> if (!empty($row['Key'])) {
<add> $schema[$row['Field']]['key'] = $this->convertIndex($row['Key']);
<add> }
<add> foreach ($fieldParams as $key => $metadata) {
<add> if (!empty($row[$metadata['column']])) {
<add> $schema[$row['Field']][$key] = $row[$metadata['column']];
<add> }
<add> }
<add> return $schema;
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/TestCase/Model/Datasource/Database/Driver/MysqlTest.php
<ide> public static function columnProvider() {
<ide> * @dataProvider columnProvider
<ide> * @return void
<ide> */
<del> public function testColumnType($input, $expected) {
<add> public function testConvertColumnType($input, $expected) {
<ide> $driver = $this->getMock('Cake\Model\Datasource\Database\Driver\Mysql', ['_connect']);
<del> $this->assertEquals($driver->columnType($input), $expected);
<add> $this->assertEquals($driver->convertColumn($input), $expected);
<add> }
<add>
<add>/**
<add> * Provider for testing index conversion
<add> *
<add> * @return array
<add> */
<add> public static function convertIndexProvider() {
<add> return [
<add> ['PRI', 'primary'],
<add> ['UNI', 'unique'],
<add> ['MUL', 'index'],
<add> ];
<add> }
<add>/**
<add> * Test parsing MySQL index types.
<add> *
<add> * @dataProvider convertIndexProvider
<add> * @return void
<add> */
<add> public function testConvertIndex($input, $expected) {
<add> $driver = $this->getMock('Cake\Model\Datasource\Database\Driver\Mysql', ['_connect']);
<add> $this->assertEquals($driver->convertIndex($input), $expected);
<ide> }
<ide>
<ide> /** | 3 |
Ruby | Ruby | add xcode 5.0.2 to compiler map | a82276b2cbc007f75d4aa7d9e332a7cd3e9a241c | <ide><path>Library/Homebrew/os/mac.rb
<ide> def preferred_arch
<ide> "4.6.3" => { :llvm_build => 2336, :clang => "4.2", :clang_build => 425 },
<ide> "5.0" => { :clang => "5.0", :clang_build => 500 },
<ide> "5.0.1" => { :clang => "5.0", :clang_build => 500 },
<add> "5.0.2" => { :clang => "5.0", :clang_build => 500 },
<ide> }
<ide>
<ide> def compilers_standard? | 1 |
Python | Python | fix the array_api submodule __init__.py imports | ba4e21ca150a2d8b3cc08a3e8c981f7042aacf6f | <ide><path>numpy/_array_api/__init__.py
<ide> __all__ = []
<ide>
<del>from .constants import e, inf, nan, pi
<add>from ._constants import e, inf, nan, pi
<ide>
<ide> __all__ += ['e', 'inf', 'nan', 'pi']
<ide>
<del>from .creation_functions import arange, empty, empty_like, eye, full, full_like, linspace, ones, ones_like, zeros, zeros_like
<add>from ._creation_functions import arange, empty, empty_like, eye, full, full_like, linspace, ones, ones_like, zeros, zeros_like
<ide>
<ide> __all__ += ['arange', 'empty', 'empty_like', 'eye', 'full', 'full_like', 'linspace', 'ones', 'ones_like', 'zeros', 'zeros_like']
<ide>
<del>from .dtypes import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool
<add>from ._dtypes import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool
<ide>
<ide> __all__ += ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool']
<ide>
<del>from .elementwise_functions import abs, acos, acosh, add, asin, asinh, atan, atan2, atanh, bitwise_and, bitwise_left_shift, bitwise_invert, bitwise_or, bitwise_right_shift, bitwise_xor, ceil, cos, cosh, divide, equal, exp, expm1, floor, floor_divide, greater, greater_equal, isfinite, isinf, isnan, less, less_equal, log, log1p, log2, log10, logical_and, logical_not, logical_or, logical_xor, multiply, negative, not_equal, positive, pow, remainder, round, sign, sin, sinh, square, sqrt, subtract, tan, tanh, trunc
<add>from ._elementwise_functions import abs, acos, acosh, add, asin, asinh, atan, atan2, atanh, bitwise_and, bitwise_left_shift, bitwise_invert, bitwise_or, bitwise_right_shift, bitwise_xor, ceil, cos, cosh, divide, equal, exp, expm1, floor, floor_divide, greater, greater_equal, isfinite, isinf, isnan, less, less_equal, log, log1p, log2, log10, logical_and, logical_not, logical_or, logical_xor, multiply, negative, not_equal, positive, pow, remainder, round, sign, sin, sinh, square, sqrt, subtract, tan, tanh, trunc
<ide>
<ide> __all__ += ['abs', 'acos', 'acosh', 'add', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'bitwise_and', 'bitwise_left_shift', 'bitwise_invert', 'bitwise_or', 'bitwise_right_shift', 'bitwise_xor', 'ceil', 'cos', 'cosh', 'divide', 'equal', 'exp', 'expm1', 'floor', 'floor_divide', 'greater', 'greater_equal', 'isfinite', 'isinf', 'isnan', 'less', 'less_equal', 'log', 'log1p', 'log2', 'log10', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'multiply', 'negative', 'not_equal', 'positive', 'pow', 'remainder', 'round', 'sign', 'sin', 'sinh', 'square', 'sqrt', 'subtract', 'tan', 'tanh', 'trunc']
<ide>
<del>from .linear_algebra_functions import cross, det, diagonal, inv, norm, outer, trace, transpose
<add>from ._linear_algebra_functions import cross, det, diagonal, inv, norm, outer, trace, transpose
<ide>
<ide> __all__ += ['cross', 'det', 'diagonal', 'inv', 'norm', 'outer', 'trace', 'transpose']
<ide>
<del># from .linear_algebra_functions import cholesky, cross, det, diagonal, dot, eig, eigvalsh, einsum, inv, lstsq, matmul, matrix_power, matrix_rank, norm, outer, pinv, qr, slogdet, solve, svd, trace, transpose
<add># from ._linear_algebra_functions import cholesky, cross, det, diagonal, dot, eig, eigvalsh, einsum, inv, lstsq, matmul, matrix_power, matrix_rank, norm, outer, pinv, qr, slogdet, solve, svd, trace, transpose
<ide> #
<ide> # __all__ += ['cholesky', 'cross', 'det', 'diagonal', 'dot', 'eig', 'eigvalsh', 'einsum', 'inv', 'lstsq', 'matmul', 'matrix_power', 'matrix_rank', 'norm', 'outer', 'pinv', 'qr', 'slogdet', 'solve', 'svd', 'trace', 'transpose']
<ide>
<del>from .manipulation_functions import concat, expand_dims, flip, reshape, roll, squeeze, stack
<add>from ._manipulation_functions import concat, expand_dims, flip, reshape, roll, squeeze, stack
<ide>
<ide> __all__ += ['concat', 'expand_dims', 'flip', 'reshape', 'roll', 'squeeze', 'stack']
<ide>
<del>from .searching_functions import argmax, argmin, nonzero, where
<add>from ._searching_functions import argmax, argmin, nonzero, where
<ide>
<ide> __all__ += ['argmax', 'argmin', 'nonzero', 'where']
<ide>
<del>from .set_functions import unique
<add>from ._set_functions import unique
<ide>
<ide> __all__ += ['unique']
<ide>
<del>from .sorting_functions import argsort, sort
<add>from ._sorting_functions import argsort, sort
<ide>
<ide> __all__ += ['argsort', 'sort']
<ide>
<del>from .statistical_functions import max, mean, min, prod, std, sum, var
<add>from ._statistical_functions import max, mean, min, prod, std, sum, var
<ide>
<ide> __all__ += ['max', 'mean', 'min', 'prod', 'std', 'sum', 'var']
<ide>
<del>from .utility_functions import all, any
<add>from ._utility_functions import all, any
<ide>
<ide> __all__ += ['all', 'any'] | 1 |
Mixed | Python | update examples from master | 47a7d4ec147d9411e9f5f5d382078eb07721f2b3 | <ide><path>README.md
<ide> python run_squad.py \
<ide> --num_train_epochs 2.0 \
<ide> --max_seq_length 384 \
<ide> --doc_stride 128 \
<del> --output_dir ../debug_squad/
<add> --output_dir /tmp/debug_squad/
<ide> ```
<ide>
<ide> Training with the previous hyper-parameters gave us the following results:
<ide><path>examples/run_classifier.py
<ide> def set_optimizer_params_grad(named_params_optimizer, named_params_model, test_n
<ide> if name_opti != name_model:
<ide> logger.error("name_opti != name_model: {} {}".format(name_opti, name_model))
<ide> raise ValueError
<del> if test_nan and torch.isnan(param_model.grad).sum() > 0:
<del> is_nan = True
<del> if param_opti.grad is None:
<del> param_opti.grad = torch.nn.Parameter(param_opti.data.new().resize_(*param_opti.data.size()))
<del> param_opti.grad.data.copy_(param_model.grad.data)
<add> if param_model.grad is not None:
<add> if test_nan and torch.isnan(param_model.grad).sum() > 0:
<add> is_nan = True
<add> if param_opti.grad is None:
<add> param_opti.grad = torch.nn.Parameter(param_opti.data.new().resize_(*param_opti.data.size()))
<add> param_opti.grad.data.copy_(param_model.grad.data)
<add> else:
<add> param_opti.grad = None
<ide> return is_nan
<ide>
<ide> def main():
<ide><path>examples/run_squad.py
<ide> def set_optimizer_params_grad(named_params_optimizer, named_params_model, test_n
<ide> if param_opti.grad is None:
<ide> param_opti.grad = torch.nn.Parameter(param_opti.data.new().resize_(*param_opti.data.size()))
<ide> param_opti.grad.data.copy_(param_model.grad.data)
<add> else:
<add> param_opti.grad = None
<ide> return is_nan
<ide>
<ide> def main(): | 3 |
Python | Python | fix otto example | 22012fdecc1deec6827624de1a6f4bf17e416b38 | <ide><path>examples/kaggle_otto_nn.py
<ide> def make_submission(y_prob, ids, encoder, fname):
<ide> y, encoder = preprocess_labels(labels)
<ide>
<ide> X_test, ids = load_data('test.csv', train=False)
<del>X_test, _ = preprocess_data(X_test)
<add>X_test, _ = preprocess_data(X_test, scaler)
<ide>
<ide> nb_classes = y.shape[1]
<ide> print(nb_classes, 'classes') | 1 |
Text | Text | use colon consistently in assert.md | 954fe25a58a6b7243c3c7a9510e55fbc9e02cecf | <ide><path>doc/api/assert.md
<ide> assert.notDeepEqual(obj1, obj1);
<ide> // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
<ide>
<ide> assert.notDeepEqual(obj1, obj2);
<del>// OK, obj1 and obj2 are not deeply equal
<add>// OK: obj1 and obj2 are not deeply equal
<ide>
<ide> assert.notDeepEqual(obj1, obj3);
<ide> // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
<ide>
<ide> assert.notDeepEqual(obj1, obj4);
<del>// OK, obj1 and obj4 are not deeply equal
<add>// OK: obj1 and obj4 are not deeply equal
<ide> ```
<ide>
<ide> If the values are deeply equal, an `AssertionError` is thrown with a `message` | 1 |
PHP | PHP | fix entity class inflection for mocked models | b6b8c24539d3cbc7aa9745c58b957f4f1147dcef | <ide><path>src/TestSuite/TestCase.php
<ide> public function getMockForModel($alias, array $methods = [], array $options = []
<ide>
<ide> if (empty($options['entityClass']) && $mock->getEntityClass() === Entity::class) {
<ide> $parts = explode('\\', $className);
<del> $entityAlias = Inflector::singularize(substr(array_pop($parts), 0, -5));
<add> $entityAlias = Inflector::classify(Inflector::underscore(substr(array_pop($parts), 0, -5)));
<ide> $entityClass = implode('\\', array_slice($parts, 0, -1)) . '\\Entity\\' . $entityAlias;
<ide> if (class_exists($entityClass)) {
<ide> $mock->setEntityClass($entityClass); | 1 |
Text | Text | update permanent redirect field documentation | a9ad8cbbd92ba73ae13e4b28d9851f3e240f960a | <ide><path>docs/api-reference/next.config.js/redirects.md
<ide> module.exports = {
<ide>
<ide> - `source` is the incoming request path pattern.
<ide> - `destination` is the path you want to route to.
<del>- `permanent` if the redirect is permanent or not.
<add>- `permanent` `true` or `false` - if `true` will use the 308 status code which instructs clients/search engines to cache the redirect forever, if `false` will use the 307 status code which is temporary and is not cached.
<ide> - `basePath`: `false` or `undefined` - if false the basePath won't be included when matching, can be used for external rewrites only.
<ide> - `locale`: `false` or `undefined` - whether the locale should not be included when matching.
<ide> - `has` is an array of [has objects](#header-cookie-and-query-matching) with the `type`, `key` and `value` properties. | 1 |
Ruby | Ruby | access the homepage attribute once | e717508b7b63b5bb0f84b2c62d3c621857baa67c | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_conflicts
<ide> end
<ide>
<ide> def audit_urls
<del> unless f.homepage =~ %r[^https?://]
<del> problem "The homepage should start with http or https (url is #{f.homepage})."
<add> homepage = f.homepage
<add>
<add> unless homepage =~ %r[^https?://]
<add> problem "The homepage should start with http or https (URL is #{homepage})."
<ide> end
<ide>
<ide> # Check for http:// GitHub homepage urls, https:// is preferred.
<ide> # Note: only check homepages that are repo pages, not *.github.com hosts
<del> if f.homepage =~ %r[^http://github\.com/]
<del> problem "Use https:// URLs for homepages on GitHub (url is #{f.homepage})."
<add> if homepage =~ %r[^http://github\.com/]
<add> problem "Use https:// URLs for homepages on GitHub (URL is #{homepage})."
<ide> end
<ide>
<ide> # Google Code homepages should end in a slash
<del> if f.homepage =~ %r[^https?://code\.google\.com/p/[^/]+[^/]$]
<del> problem "Google Code homepage should end with a slash (url is #{f.homepage})."
<add> if homepage =~ %r[^https?://code\.google\.com/p/[^/]+[^/]$]
<add> problem "Google Code homepage should end with a slash (URL is #{homepage})."
<ide> end
<ide>
<ide> urls = @specs.map(&:url) | 1 |
Go | Go | fix some wrong vars or funcs in builder.go | ee8a3eee4fac23fcba9f9b95c5c627419f0b230d | <ide><path>builder/builder.go
<ide> type PathFileInfo struct {
<ide> os.FileInfo
<ide> // FilePath holds the absolute path to the file.
<ide> FilePath string
<del> // Name holds the basename for the file.
<add> // FileName holds the basename for the file.
<ide> FileName string
<ide> }
<ide>
<ide> type Backend interface {
<ide>
<ide> // GetImageOnBuild looks up a Docker image referenced by `name`.
<ide> GetImageOnBuild(name string) (Image, error)
<del> // TagImage tags an image with newTag
<add> // TagImageWithReference tags an image with newTag
<ide> TagImageWithReference(image.ID, reference.Named) error
<ide> // PullOnBuild tells Docker to pull image referenced by `name`.
<ide> PullOnBuild(ctx context.Context, name string, authConfigs map[string]types.AuthConfig, output io.Writer) (Image, error)
<ide> type ImageCacheBuilder interface {
<ide> // ImageCache abstracts an image cache.
<ide> // (parent image, child runconfig) -> child image
<ide> type ImageCache interface {
<del> // GetCachedImageOnBuild returns a reference to a cached image whose parent equals `parent`
<add> // GetCache returns a reference to a cached image whose parent equals `parent`
<ide> // and runconfig equals `cfg`. A cache miss is expected to return an empty ID and a nil error.
<ide> GetCache(parentID string, cfg *container.Config) (imageID string, err error)
<ide> } | 1 |
Text | Text | describe fipsdir environment variable | 9f71a3109e8b6ff870244f89df19065d4a35025b | <ide><path>README.md
<ide> Instructions:
<ide> Appendix A in the [security policy]
<ide> (http://csrc.nist.gov/groups/STM/cmvp/documents/140-1/140sp/140sp1747.pdf).
<ide> The only exception is that `./config no-asm` can be
<del> used in place of `./config` )
<add> used in place of `./config`, and the FIPSDIR environment variable
<add> may be used to specify a non-standard install folder for the
<add> validated module, as per User Guide sections 4.2.1, 4.2.2, and 4.2.3.
<ide> 6. Get into Node.js checkout folder
<ide> 7. `./configure --openssl-fips=/path/to/openssl-fips/installdir`
<ide> For example on ubuntu 12 the installation directory was | 1 |
Javascript | Javascript | update validatebaseurl to use latest regex | 33ef82ce6dfd31e1f990d438c925a0e52723e16b | <ide><path>Libraries/Blob/URL.js
<ide> export class URLSearchParams {
<ide>
<ide> function validateBaseUrl(url: string) {
<ide> // from this MIT-licensed gist: https://gist.github.com/dperini/729294
<del> return /^(?:(?:(?:https?|ftp):)?\/\/)(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(
<add> return /^(?:(?:(?:https?|ftp):)?\/\/)(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)*(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/.test(
<ide> url,
<ide> );
<ide> } | 1 |
PHP | PHP | fix bugs in routing | b9f235706c58ff4f1a8945b5800e3386b64b5018 | <ide><path>src/Illuminate/Routing/RouteCollection.php
<ide> public function match(Request $request)
<ide> */
<ide> protected function checkForAlternateVerbs($request)
<ide> {
<del> $others = array_diff(Router::VERBS, array($request->getMethod()));
<add> $others = array_diff(Router::$verbs, array($request->getMethod()));
<ide>
<ide> // Here we will spin through all verbs except for the current request verb and
<ide> // check to see if any routes respond to them. If they do, we will return a
<ide><path>src/Illuminate/Routing/Router.php
<ide> class Router implements RouteFiltererInterface {
<ide> */
<ide> protected $groupStack = array();
<ide>
<add> /**
<add> * All of the verbs supported by the router.
<add> *
<add> * @var array
<add> */
<add> public static $verbs = array('GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
<add>
<ide> /**
<ide> * Create a new Router instance.
<ide> * | 2 |
Text | Text | remove trailing whitespace [ci skip] | fb2f8d2b75b1999b7ff7adef16ba7fb34600fa0d | <ide><path>guides/source/active_record_migrations.md
<ide> such features, the `execute` method can be used to execute arbitrary SQL.
<ide> Migrations and Seed Data
<ide> ------------------------
<ide>
<del>The main purpose of Rails' migration feature is to issue commands that modify the
<del>schema using a consistent process. Migrations can also be used
<del>to add or modify data. This is useful in an existing database that can't be destroyed
<del>and recreated, such as a production database.
<add>The main purpose of Rails' migration feature is to issue commands that modify the
<add>schema using a consistent process. Migrations can also be used
<add>to add or modify data. This is useful in an existing database that can't be destroyed
<add>and recreated, such as a production database.
<ide>
<ide> ```ruby
<ide> class AddInitialProducts < ActiveRecord::Migration[5.0]
<ide> class AddInitialProducts < ActiveRecord::Migration[5.0]
<ide> end
<ide> ```
<ide>
<del>To add initial data after a database is created, Rails has a built-in
<del>'seeds' feature that makes the process quick and easy. This is especially
<del>useful when reloading the database frequently in development and test environments.
<del>It's easy to get started with this feature: just fill up `db/seeds.rb` with some
<add>To add initial data after a database is created, Rails has a built-in
<add>'seeds' feature that makes the process quick and easy. This is especially
<add>useful when reloading the database frequently in development and test environments.
<add>It's easy to get started with this feature: just fill up `db/seeds.rb` with some
<ide> Ruby code, and run `rails db:seed`:
<ide>
<ide> ```ruby | 1 |
Javascript | Javascript | add tests for dock sizing behavior | d40a14be29d7b44ca8c63aea230509f8ab775957 | <ide><path>spec/dock-spec.js
<ide> describe('Dock', () => {
<ide> })
<ide> })
<ide> })
<add>
<add> describe('when you add an item to an empty dock', () => {
<add> describe('when the item has a preferred size', () => {
<add> it('is takes the preferred size of the item', async () => {
<add> jasmine.attachToDOM(atom.workspace.getElement())
<add>
<add> const createItem = preferredWidth => ({
<add> element: document.createElement('div'),
<add> getDefaultLocation() { return 'left' },
<add> getPreferredWidth() { return preferredWidth }
<add> })
<add>
<add> const dock = atom.workspace.getLeftDock()
<add> const dockElement = dock.getElement()
<add> expect(dock.getPaneItems()).toHaveLength(0)
<add>
<add> const item1 = createItem(111)
<add> await atom.workspace.open(item1)
<add>
<add> // It should update the width every time we go from 0 -> 1 items, not just the first.
<add> expect(dock.isVisible()).toBe(true)
<add> expect(dockElement.offsetWidth).toBe(111)
<add> dock.destroyActivePane()
<add> expect(dock.getPaneItems()).toHaveLength(0)
<add> expect(dock.isVisible()).toBe(false)
<add> const item2 = createItem(222)
<add> await atom.workspace.open(item2)
<add> expect(dock.isVisible()).toBe(true)
<add> expect(dockElement.offsetWidth).toBe(222)
<add>
<add> // Adding a second shouldn't change the size.
<add> const item3 = createItem(333)
<add> await atom.workspace.open(item3)
<add> expect(dockElement.offsetWidth).toBe(222)
<add> })
<add> })
<add>
<add> describe('when the item has no preferred size', () => {
<add> it('is still has an explicit size', async () => {
<add> jasmine.attachToDOM(atom.workspace.getElement())
<add>
<add> const item = {
<add> element: document.createElement('div'),
<add> getDefaultLocation() { return 'left' }
<add> }
<add> const dock = atom.workspace.getLeftDock()
<add> expect(dock.getPaneItems()).toHaveLength(0)
<add>
<add> expect(dock.state.size).toBe(null)
<add> await atom.workspace.open(item)
<add> expect(dock.state.size).not.toBe(null)
<add> })
<add> })
<add> })
<add>
<add> describe('a deserialized dock', () => {
<add> it('restores the serialized size', async () => {
<add> jasmine.attachToDOM(atom.workspace.getElement())
<add>
<add> const item = {
<add> element: document.createElement('div'),
<add> getDefaultLocation() { return 'left' },
<add> getPreferredWidth() { return 122 },
<add> serialize: () => ({deserializer: 'DockTestItem'})
<add> }
<add> const itemDeserializer = atom.deserializers.add({
<add> name: 'DockTestItem',
<add> deserialize: () => item
<add> })
<add> const dock = atom.workspace.getLeftDock()
<add> const dockElement = dock.getElement()
<add>
<add> await atom.workspace.open(item)
<add> dock.setState({size: 150})
<add> expect(dockElement.offsetWidth).toBe(150)
<add> const serialized = dock.serialize()
<add> dock.setState({size: 122})
<add> expect(dockElement.offsetWidth).toBe(122)
<add> dock.destroyActivePane()
<add> dock.deserialize(serialized, atom.deserializers)
<add> expect(dockElement.offsetWidth).toBe(150)
<add> })
<add>
<add> it("isn't visible if it has no items", async () => {
<add> jasmine.attachToDOM(atom.workspace.getElement())
<add>
<add> const item = {
<add> element: document.createElement('div'),
<add> getDefaultLocation() { return 'left' },
<add> getPreferredWidth() { return 122 }
<add> }
<add> const dock = atom.workspace.getLeftDock()
<add>
<add> await atom.workspace.open(item)
<add> expect(dock.isVisible()).toBe(true)
<add> const serialized = dock.serialize()
<add> dock.deserialize(serialized, atom.deserializers)
<add> expect(dock.getPaneItems()).toHaveLength(0)
<add> expect(dock.isVisible()).toBe(false)
<add> })
<add> })
<add>
<add> describe('when dragging an item over an empty dock', () => {
<add> it('has the preferred size of the item', () => {
<add> jasmine.attachToDOM(atom.workspace.getElement())
<add>
<add> const item = {
<add> element: document.createElement('div'),
<add> getDefaultLocation() { return 'left' },
<add> getPreferredWidth() { return 144 },
<add> serialize: () => ({deserializer: 'DockTestItem'})
<add> }
<add> const dock = atom.workspace.getLeftDock()
<add> const dockElement = dock.getElement()
<add>
<add> dock.setDraggingItem(item)
<add> expect(dock.wrapperElement.offsetWidth).toBe(144)
<add> })
<add> })
<ide> })
<ide><path>src/dock.js
<ide> module.exports = class Dock {
<ide> })
<ide>
<ide> this.state = {
<add> size: null,
<ide> visible: false,
<ide> shouldAnimate: false
<ide> } | 2 |
Java | Java | fix linkedcaseinsensitivemap collection methods | aa69703f3b0f92b1c7eaaf62b34ef8c7b251fc5c | <ide><path>spring-core/src/main/java/org/springframework/util/LinkedCaseInsensitiveMap.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> package org.springframework.util;
<ide>
<ide> import java.io.Serializable;
<add>import java.util.AbstractCollection;
<add>import java.util.AbstractSet;
<ide> import java.util.Collection;
<ide> import java.util.HashMap;
<add>import java.util.Iterator;
<ide> import java.util.LinkedHashMap;
<ide> import java.util.Locale;
<ide> import java.util.Map;
<ide> import java.util.Set;
<add>import java.util.Spliterator;
<add>import java.util.function.Consumer;
<ide> import java.util.function.Function;
<ide>
<ide> import org.springframework.lang.Nullable;
<ide> * <p>Does <i>not</i> support {@code null} keys.
<ide> *
<ide> * @author Juergen Hoeller
<add> * @author Phillip Webb
<ide> * @since 3.0
<ide> * @param <V> the value type
<ide> */
<ide>
<ide> private final Locale locale;
<ide>
<add> private transient Set<String> keySet;
<add>
<add> private transient Collection<V> values;
<add>
<add> private transient Set<Entry<String, V>> entrySet;
<add>
<ide>
<ide> /**
<ide> * Create a new LinkedCaseInsensitiveMap that stores case-insensitive keys
<ide> public boolean containsKey(Object key) {
<ide> protected boolean removeEldestEntry(Map.Entry<String, V> eldest) {
<ide> boolean doRemove = LinkedCaseInsensitiveMap.this.removeEldestEntry(eldest);
<ide> if (doRemove) {
<del> caseInsensitiveKeys.remove(convertKey(eldest.getKey()));
<add> removeCaseInsensitiveKey(eldest.getKey());
<ide> }
<ide> return doRemove;
<ide> }
<ide> public V computeIfAbsent(String key, Function<? super String, ? extends V> mappi
<ide> @Nullable
<ide> public V remove(Object key) {
<ide> if (key instanceof String) {
<del> String caseInsensitiveKey = this.caseInsensitiveKeys.remove(convertKey((String) key));
<add> String caseInsensitiveKey = removeCaseInsensitiveKey((String) key);
<ide> if (caseInsensitiveKey != null) {
<ide> return this.targetMap.remove(caseInsensitiveKey);
<ide> }
<ide> public void clear() {
<ide>
<ide> @Override
<ide> public Set<String> keySet() {
<del> return this.targetMap.keySet();
<add> Set<String> keySet = this.keySet;
<add> if (keySet == null) {
<add> keySet = new KeySet(this.targetMap.keySet());
<add> this.keySet = keySet;
<add> }
<add> return keySet;
<ide> }
<ide>
<ide> @Override
<ide> public Collection<V> values() {
<del> return this.targetMap.values();
<add> Collection<V> values = this.values;
<add> if (values == null) {
<add> values = new Values(this.targetMap.values());
<add> this.values = values;
<add> }
<add> return values;
<ide> }
<ide>
<ide> @Override
<ide> public Set<Entry<String, V>> entrySet() {
<del> return this.targetMap.entrySet();
<add> Set<Entry<String, V>> entrySet = this.entrySet;
<add> if (entrySet == null) {
<add> entrySet = new EntrySet(this.targetMap.entrySet());
<add> this.entrySet = entrySet;
<add> }
<add> return entrySet;
<ide> }
<ide>
<ide> @Override
<ide> protected boolean removeEldestEntry(Map.Entry<String, V> eldest) {
<ide> return false;
<ide> }
<ide>
<add> private String removeCaseInsensitiveKey(String key) {
<add> return this.caseInsensitiveKeys.remove(convertKey(key));
<add> }
<add>
<add>
<add> private class KeySet extends AbstractSet<String> {
<add>
<add> private final Set<String> delegate;
<add>
<add>
<add> KeySet(Set<String> delegate) {
<add> this.delegate = delegate;
<add> }
<add>
<add>
<add> @Override
<add> public int size() {
<add> return this.delegate.size();
<add> }
<add>
<add> @Override
<add> public boolean contains(Object o) {
<add> return this.delegate.contains(o);
<add> }
<add>
<add> @Override
<add> public Iterator<String> iterator() {
<add> return new KeySetIterator();
<add> }
<add>
<add> @Override
<add> public boolean remove(Object o) {
<add> return LinkedCaseInsensitiveMap.this.remove(o) != null;
<add> }
<add>
<add> @Override
<add> public void clear() {
<add> LinkedCaseInsensitiveMap.this.clear();
<add> }
<add>
<add> @Override
<add> public Spliterator<String> spliterator() {
<add> return this.delegate.spliterator();
<add> }
<add>
<add> @Override
<add> public void forEach(Consumer<? super String> action) {
<add> this.delegate.forEach(action);
<add> }
<add>
<add> }
<add>
<add>
<add> private class Values extends AbstractCollection<V> {
<add>
<add> private final Collection<V> delegate;
<add>
<add>
<add> Values(Collection<V> delegate) {
<add> this.delegate = delegate;
<add> }
<add>
<add>
<add> @Override
<add> public int size() {
<add> return this.delegate.size();
<add> }
<add>
<add> @Override
<add> public boolean contains(Object o) {
<add> return this.delegate.contains(o);
<add> }
<add>
<add> @Override
<add> public Iterator<V> iterator() {
<add> return new ValuesIterator();
<add> }
<add>
<add> @Override
<add> public void clear() {
<add> LinkedCaseInsensitiveMap.this.clear();
<add> }
<add>
<add> @Override
<add> public Spliterator<V> spliterator() {
<add> return this.delegate.spliterator();
<add> }
<add>
<add> @Override
<add> public void forEach(Consumer<? super V> action) {
<add> this.delegate.forEach(action);
<add> }
<add>
<add> }
<add>
<add>
<add> private class EntrySet extends AbstractSet<Entry<String, V>> {
<add>
<add> private final Set<Entry<String, V>> delegate;
<add>
<add>
<add> public EntrySet(Set<Entry<String, V>> delegate) {
<add> this.delegate = delegate;
<add> }
<add>
<add>
<add> @Override
<add> public int size() {
<add> return this.delegate.size();
<add> }
<add>
<add> @Override
<add> public boolean contains(Object o) {
<add> return this.delegate.contains(o);
<add> }
<add>
<add> @Override
<add> public Iterator<Entry<String, V>> iterator() {
<add> return new EntrySetIterator();
<add> }
<add>
<add>
<add> @Override
<add> @SuppressWarnings("unchecked")
<add> public boolean remove(Object o) {
<add> if (this.delegate.remove(o)) {
<add> removeCaseInsensitiveKey(((Map.Entry<String, V>) o).getKey());
<add> return true;
<add> }
<add> return false;
<add> }
<add>
<add>
<add> @Override
<add> public void clear() {
<add> this.delegate.clear();
<add> caseInsensitiveKeys.clear();
<add> }
<add>
<add> @Override
<add> public Spliterator<Entry<String, V>> spliterator() {
<add> return this.delegate.spliterator();
<add> }
<add>
<add> @Override
<add> public void forEach(Consumer<? super Entry<String, V>> action) {
<add> this.delegate.forEach(action);
<add> }
<add>
<add> }
<add>
<add>
<add> private class EntryIterator {
<add>
<add> private final Iterator<Entry<String, V>> delegate;
<add>
<add> private Entry<String, V> last;
<add>
<add> public EntryIterator() {
<add> this.delegate = targetMap.entrySet().iterator();
<add> }
<add>
<add> public Entry<String, V> nextEntry() {
<add> Entry<String, V> entry = this.delegate.next();
<add> this.last = entry;
<add> return entry;
<add> }
<add>
<add> public boolean hasNext() {
<add> return this.delegate.hasNext();
<add> }
<add>
<add> public void remove() {
<add> this.delegate.remove();
<add> if(this.last != null) {
<add> removeCaseInsensitiveKey(this.last.getKey());
<add> this.last = null;
<add> }
<add> }
<add>
<add> }
<add>
<add>
<add> private class KeySetIterator extends EntryIterator implements Iterator<String> {
<add>
<add> @Override
<add> public String next() {
<add> return nextEntry().getKey();
<add> }
<add>
<add> }
<add>
<add>
<add> private class ValuesIterator extends EntryIterator implements Iterator<V> {
<add>
<add> @Override
<add> public V next() {
<add> return nextEntry().getValue();
<add> }
<add>
<add> }
<add>
<add>
<add> private class EntrySetIterator extends EntryIterator implements Iterator<Entry<String, V>> {
<add>
<add> @Override
<add> public Entry<String, V> next() {
<add> return nextEntry();
<add> }
<add>
<add> }
<add>
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/util/LinkedCaseInsensitiveMapTests.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.util;
<ide>
<add>import java.util.Iterator;
<add>
<ide> import org.junit.Test;
<ide>
<ide> import static org.junit.Assert.*;
<ide>
<ide> /**
<add> * Tests for {@link LinkedCaseInsensitiveMap}.
<add> *
<ide> * @author Juergen Hoeller
<add> * @author Phillip Webb
<ide> */
<ide> public class LinkedCaseInsensitiveMapTests {
<ide>
<ide> public void mapClone() {
<ide> assertEquals("value2", copy.get("Key"));
<ide> }
<ide>
<add>
<add> @Test
<add> public void clearFromKeySet() {
<add> map.put("key", "value");
<add> map.keySet().clear();
<add> map.computeIfAbsent("key", k -> "newvalue");
<add> assertEquals("newvalue", map.get("key"));
<add> }
<add>
<add> @Test
<add> public void removeFromKeySet() {
<add> map.put("key", "value");
<add> map.keySet().remove("key");
<add> map.computeIfAbsent("key", k -> "newvalue");
<add> assertEquals("newvalue", map.get("key"));
<add> }
<add>
<add> @Test
<add> public void removeFromKeySetViaIterator() {
<add> map.put("key", "value");
<add> nextAndRemove(map.keySet().iterator());
<add> assertEquals(0, map.size());
<add> map.computeIfAbsent("key", k -> "newvalue");
<add> assertEquals("newvalue", map.get("key"));
<add> }
<add>
<add> @Test
<add> public void clearFromValues() {
<add> map.put("key", "value");
<add> map.values().clear();
<add> assertEquals(0, map.size());
<add> map.computeIfAbsent("key", k -> "newvalue");
<add> assertEquals("newvalue", map.get("key"));
<add> }
<add>
<add> @Test
<add> public void removeFromValues() {
<add> map.put("key", "value");
<add> map.values().remove("value");
<add> assertEquals(0, map.size());
<add> map.computeIfAbsent("key", k -> "newvalue");
<add> assertEquals("newvalue", map.get("key"));
<add> }
<add>
<add> @Test
<add> public void removeFromValuesViaIterator() {
<add> map.put("key", "value");
<add> nextAndRemove(map.values().iterator());
<add> assertEquals(0, map.size());
<add> map.computeIfAbsent("key", k -> "newvalue");
<add> assertEquals("newvalue", map.get("key"));
<add> }
<add>
<add> @Test
<add> public void clearFromEntrySet() {
<add> map.put("key", "value");
<add> map.entrySet().clear();
<add> assertEquals(0, map.size());
<add> map.computeIfAbsent("key", k -> "newvalue");
<add> assertEquals("newvalue", map.get("key"));
<add> }
<add>
<add> @Test
<add> public void removeFromEntrySet() {
<add> map.put("key", "value");
<add> map.entrySet().remove(map.entrySet().iterator().next());
<add> assertEquals(0, map.size());
<add> map.computeIfAbsent("key", k -> "newvalue");
<add> assertEquals("newvalue", map.get("key"));
<add> }
<add>
<add> @Test
<add> public void removeFromEntrySetViaIterator() {
<add> map.put("key", "value");
<add> nextAndRemove(map.entrySet().iterator());
<add> assertEquals(0, map.size());
<add> map.computeIfAbsent("key", k -> "newvalue");
<add> assertEquals("newvalue", map.get("key"));
<add> }
<add>
<add> private void nextAndRemove(Iterator<?> iterator) {
<add> iterator.next();
<add> iterator.remove();
<add> }
<add>
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java
<ide> import java.util.TimeZone;
<ide>
<ide> import org.hamcrest.Matchers;
<del>import org.junit.Ignore;
<ide> import org.junit.Test;
<ide>
<ide> import static org.hamcrest.Matchers.*;
<ide> public void bearerAuth() {
<ide> }
<ide>
<ide> @Test
<del> @Ignore("Disabled until gh-22821 is resolved")
<ide> public void removalFromKeySetRemovesEntryFromUnderlyingMap() {
<ide> String headerName = "MyHeader";
<ide> String headerValue = "value";
<ide> public void removalFromKeySetRemovesEntryFromUnderlyingMap() {
<ide> headers.keySet().removeIf(key -> key.equals(headerName));
<ide> assertTrue(headers.isEmpty());
<ide> headers.add(headerName, headerValue);
<del> assertEquals(headerValue, headers.get(headerName));
<add> assertEquals(headerValue, headers.get(headerName).get(0));
<ide> }
<ide>
<ide> @Test
<del> @Ignore("Disabled until gh-22821 is resolved")
<ide> public void removalFromEntrySetRemovesEntryFromUnderlyingMap() {
<ide> String headerName = "MyHeader";
<ide> String headerValue = "value";
<ide> public void removalFromEntrySetRemovesEntryFromUnderlyingMap() {
<ide> headers.entrySet().removeIf(entry -> entry.getKey().equals(headerName));
<ide> assertTrue(headers.isEmpty());
<ide> headers.add(headerName, headerValue);
<del> assertEquals(headerValue, headers.get(headerName));
<add> assertEquals(headerValue, headers.get(headerName).get(0));
<ide> }
<ide>
<ide> @Test | 3 |
Javascript | Javascript | use built-ins to format numbers | f66e59e20c7e66515bb40994b247cdb9fe29d9c1 | <ide><path>client/src/components/Supporters.js
<ide> import React, { Fragment } from 'react';
<ide> import PropTypes from 'prop-types';
<ide> import { Button, ProgressBar } from '@freecodecamp/react-bootstrap';
<ide>
<del>import { commaNumber } from '../utils';
<ide> import FullWidthRow from '../components/helpers/FullWidthRow';
<ide> import Spacer from '../components/helpers/Spacer';
<ide>
<ide> const propTypes = {
<ide> isDonating: PropTypes.bool.isRequired
<ide> };
<ide>
<add>const supporterGoal = 10000;
<add>const supportersLocale = supporterGoal.toLocaleString();
<add>
<ide> function Supporters({ isDonating, activeDonations }) {
<add> const donationsLocale = activeDonations.toLocaleString();
<ide> return (
<ide> <Fragment>
<ide> <FullWidthRow>
<ide> function Supporters({ isDonating, activeDonations }) {
<ide> <ProgressBar max={10000} now={activeDonations} />
<ide> <div id='progress-label-wrapper'>
<ide> <span className='progress-label'>
<del> {commaNumber(activeDonations)} supporters out of 10,000 supporter
<add> {donationsLocale} supporters out of {supportersLocale} supporter
<ide> goal
<ide> </span>
<ide> </div>
<ide> function Supporters({ isDonating, activeDonations }) {
<ide> them to join the community.
<ide> </Fragment>
<ide> ) : (
<del> `Join ${commaNumber(
<del> activeDonations
<del> )} supporters. Your $5 / month donation will help ` +
<add> `Join ${donationsLocale} supporters. Your $5 / month donation will help ` +
<ide> 'keep tech education free and open.'
<ide> )}
<ide> </p>
<ide><path>client/src/utils/index.js
<ide> export const getShortIdFromSlug = (slug = '') => {
<ide> const [, maybeShortId = ''] = operableSlug.split('--');
<ide> return maybeShortId.replace(/\/*$/, '');
<ide> };
<del>
<del>export function commaNumber(num) {
<del> if (typeof num !== 'number') {
<del> console.warn(
<del> 'Expected a Number to be passed to `commaNumber`, instead received %s',
<del> typeof num
<del> );
<del> return '';
<del> }
<del> const stringNum = String(num).replace(/^-/, '');
<del> const isNegative = num < 0;
<del> const commaSpearated = stringNum
<del> .split('')
<del> .reverse()
<del> .reduce((string, current, index, thisArray) => {
<del> const withComma =
<del> string.replace(/,/g, '').length % 3 === 0 &&
<del> index !== 0 &&
<del> index !== thisArray.length;
<del> return `${withComma ? `${current},` : current}${string}`;
<del> }, '');
<del> return `${isNegative ? '-' : ''}${commaSpearated}`;
<del>}
<ide><path>client/src/utils/utils.test.js
<ide> import {
<ide> mockId
<ide> } from '../__mocks__/news-article';
<ide>
<del>import { getShortIdFromSlug, commaNumber } from './';
<add>import { getShortIdFromSlug } from './';
<ide>
<ide> describe('client/src utilities', () => {
<ide> describe('getShortIdFromSlug', () => {
<ide> describe('client/src utilities', () => {
<ide> expect(result).toEqual(mockId);
<ide> });
<ide> });
<del>
<del> describe('commaNumber', () => {
<del> it('returns a string', () => {
<del> expect(typeof commaNumber(1)).toEqual('string');
<del> });
<del>
<del> it('returns a comma separated number, positive', () => {
<del> expect.assertions(6);
<del> expect(commaNumber(1000)).toEqual('1,000');
<del> expect(commaNumber(10000)).toEqual('10,000');
<del> expect(commaNumber(100000)).toEqual('100,000');
<del> expect(commaNumber(1000000)).toEqual('1,000,000');
<del> expect(commaNumber(1234567890)).toEqual('1,234,567,890');
<del> expect(commaNumber(Number.MAX_SAFE_INTEGER)).toEqual(
<del> '9,007,199,254,740,991'
<del> );
<del> });
<del>
<del> it('returns a comma separated number, negative', () => {
<del> expect.assertions(6);
<del> expect(commaNumber(-1000)).toEqual('-1,000');
<del> expect(commaNumber(-10000)).toEqual('-10,000');
<del> expect(commaNumber(-100000)).toEqual('-100,000');
<del> expect(commaNumber(-1000000)).toEqual('-1,000,000');
<del> expect(commaNumber(-1234567890)).toEqual('-1,234,567,890');
<del> expect(commaNumber(Number.MIN_SAFE_INTEGER)).toEqual(
<del> '-9,007,199,254,740,991'
<del> );
<del> });
<del>
<del> });
<ide> }); | 3 |
Mixed | Python | add feminine form of word "one" in french | 028cbad05ef215e124ebe4c71ec5ad62fd038ba7 | <ide><path>.github/contributors/fonfonx.md
<add># spaCy contributor agreement
<add>
<add>This spaCy Contributor Agreement (**"SCA"**) is based on the
<add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf).
<add>The SCA applies to any contribution that you make to any product or project
<add>managed by us (the **"project"**), and sets out the intellectual property rights
<add>you grant to us in the contributed materials. The term **"us"** shall mean
<add>[ExplosionAI GmbH](https://explosion.ai/legal). The term
<add>**"you"** shall mean the person or entity identified below.
<add>
<add>If you agree to be bound by these terms, fill in the information requested
<add>below and include the filled-in version with your first pull request, under the
<add>folder [`.github/contributors/`](/.github/contributors/). The name of the file
<add>should be your GitHub username, with the extension `.md`. For example, the user
<add>example_user would create the file `.github/contributors/example_user.md`.
<add>
<add>Read this agreement carefully before signing. These terms and conditions
<add>constitute a binding legal agreement.
<add>
<add>## Contributor Agreement
<add>
<add>1. The term "contribution" or "contributed materials" means any source code,
<add>object code, patch, tool, sample, graphic, specification, manual,
<add>documentation, or any other material posted or submitted by you to the project.
<add>
<add>2. With respect to any worldwide copyrights, or copyright applications and
<add>registrations, in your contribution:
<add>
<add> * you hereby assign to us joint ownership, and to the extent that such
<add> assignment is or becomes invalid, ineffective or unenforceable, you hereby
<add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge,
<add> royalty-free, unrestricted license to exercise all rights under those
<add> copyrights. This includes, at our option, the right to sublicense these same
<add> rights to third parties through multiple levels of sublicensees or other
<add> licensing arrangements;
<add>
<add> * you agree that each of us can do all things in relation to your
<add> contribution as if each of us were the sole owners, and if one of us makes
<add> a derivative work of your contribution, the one who makes the derivative
<add> work (or has it made will be the sole owner of that derivative work;
<add>
<add> * you agree that you will not assert any moral rights in your contribution
<add> against us, our licensees or transferees;
<add>
<add> * you agree that we may register a copyright in your contribution and
<add> exercise all ownership rights associated with it; and
<add>
<add> * you agree that neither of us has any duty to consult with, obtain the
<add> consent of, pay or render an accounting to the other for any use or
<add> distribution of your contribution.
<add>
<add>3. With respect to any patents you own, or that you can license without payment
<add>to any third party, you hereby grant to us a perpetual, irrevocable,
<add>non-exclusive, worldwide, no-charge, royalty-free license to:
<add>
<add> * make, have made, use, sell, offer to sell, import, and otherwise transfer
<add> your contribution in whole or in part, alone or in combination with or
<add> included in any product, work or materials arising out of the project to
<add> which your contribution was submitted, and
<add>
<add> * at our option, to sublicense these same rights to third parties through
<add> multiple levels of sublicensees or other licensing arrangements.
<add>
<add>4. Except as set out above, you keep all right, title, and interest in your
<add>contribution. The rights that you grant to us under these terms are effective
<add>on the date you first submitted a contribution to us, even if your submission
<add>took place before the date you sign these terms.
<add>
<add>5. You covenant, represent, warrant and agree that:
<add>
<add> * Each contribution that you submit is and shall be an original work of
<add> authorship and you can legally grant the rights set out in this SCA;
<add>
<add> * to the best of your knowledge, each contribution will not violate any
<add> third party's copyrights, trademarks, patents, or other intellectual
<add> property rights; and
<add>
<add> * each contribution shall be in compliance with U.S. export control laws and
<add> other applicable export and import laws. You agree to notify us if you
<add> become aware of any circumstance which would make any of the foregoing
<add> representations inaccurate in any respect. We may publicly disclose your
<add> participation in the project, including the fact that you have signed the SCA.
<add>
<add>6. This SCA is governed by the laws of the State of California and applicable
<add>U.S. Federal law. Any choice of law rules will not apply.
<add>
<add>7. Please place an “x” on one of the applicable statement below. Please do NOT
<add>mark both statements:
<add>
<add> * [x] I am signing on behalf of myself as an individual and no other person
<add> or entity, including my employer, has or will have rights with respect to my
<add> contributions.
<add>
<add> * [ ] I am signing on behalf of my employer or a legal entity and I have the
<add> actual authority to contractually bind that entity.
<add>
<add>## Contributor Details
<add>
<add>| Field | Entry |
<add>|------------------------------- | -------------------- |
<add>| Name | Xavier Fontaine |
<add>| Company name (if applicable) | |
<add>| Title or role (if applicable) | |
<add>| Date | 2022-04-13 |
<add>| GitHub username | fonfonx |
<add>| Website (optional) | |
<ide><path>spacy/lang/fr/lex_attrs.py
<ide>
<ide> _num_words = set(
<ide> """
<del>zero un deux trois quatre cinq six sept huit neuf dix
<add>zero un une deux trois quatre cinq six sept huit neuf dix
<ide> onze douze treize quatorze quinze seize dix-sept dix-huit dix-neuf
<ide> vingt trente quarante cinquante soixante soixante-dix septante quatre-vingt huitante quatre-vingt-dix nonante
<ide> cent mille mil million milliard billion quadrillion quintillion
<ide>
<ide> _ordinal_words = set(
<ide> """
<del>premier deuxième second troisième quatrième cinquième sixième septième huitième neuvième dixième
<add>premier première deuxième second seconde troisième quatrième cinquième sixième septième huitième neuvième dixième
<ide> onzième douzième treizième quatorzième quinzième seizième dix-septième dix-huitième dix-neuvième
<ide> vingtième trentième quarantième cinquantième soixantième soixante-dixième septantième quatre-vingtième huitantième quatre-vingt-dixième nonantième
<ide> centième millième millionnième milliardième billionnième quadrillionnième quintillionnième | 2 |
Java | Java | remove some unused fields | 70d44071d361fcc99458b062709b7b4b2d9d6bf0 | <ide><path>src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableIterator.java
<ide> volatile boolean done;
<ide> Throwable error;
<ide>
<del> volatile boolean cancelled;
<del>
<ide> public BlockingFlowableIterator(int batchSize) {
<ide> this.queue = new SpscLinkedArrayQueue<T>(batchSize);
<ide> this.batchSize = batchSize;
<ide> public BlockingFlowableIterator(int batchSize) {
<ide> @Override
<ide> public boolean hasNext() {
<ide> for (;;) {
<del> if (cancelled) {
<del> return false;
<del> }
<ide> boolean d = done;
<ide> boolean empty = queue.isEmpty();
<ide> if (d) {
<ide> public boolean hasNext() {
<ide> if (empty) {
<ide> lock.lock();
<ide> try {
<del> while (!cancelled && !done && queue.isEmpty()) {
<add> while (!done && queue.isEmpty()) {
<ide> condition.await();
<ide> }
<ide> } catch (InterruptedException ex) {
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinct.java
<ide> protected void subscribeActual(Subscriber<? super T> observer) {
<ide>
<ide> final Function<? super T, K> keySelector;
<ide>
<del> Disposable d;
<del>
<del> SimpleQueue<T> queue;
<del>
<ide> DistinctSubscriber(Subscriber<? super T> actual, Function<? super T, K> keySelector, Collection<? super K> collection) {
<ide> super(actual);
<ide> this.keySelector = keySelector;
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableDistinct.java
<ide> protected void subscribeActual(Observer<? super T> observer) {
<ide>
<ide> final Function<? super T, K> keySelector;
<ide>
<del> Disposable d;
<del>
<del> SimpleQueue<T> queue;
<del>
<ide> DistinctObserver(Observer<? super T> actual, Function<? super T, K> keySelector, Collection<? super K> collection) {
<ide> super(actual);
<ide> this.keySelector = keySelector;
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableFilter.java
<ide> public void subscribeActual(Observer<? super T> s) {
<ide> static final class FilterObserver<T> extends BasicFuseableObserver<T, T> {
<ide> final Predicate<? super T> filter;
<ide>
<del> Disposable s;
<del>
<ide> FilterObserver(Observer<? super T> actual, Predicate<? super T> filter) {
<ide> super(actual);
<ide> this.filter = filter; | 4 |
Text | Text | prepare tests for recursion-protection | 090a1caa7a76bd1e35377e19a0fc0da13dbab064 | <ide><path>curriculum/challenges/english/03-front-end-development-libraries/react-and-redux/manage-state-locally-first.md
<ide> assert(
<ide> The `DisplayMessages` component should render a `div` containing an `h2` element, a `button` element, a `ul` element, and `li` elements as children.
<ide>
<ide> ```js
<del>async () => {
<add>() => {
<ide> const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages));
<del> const waitForIt = (fn) =>
<del> new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100));
<ide> const state = () => {
<ide> mockedComponent.setState({ messages: ['__TEST__MESSAGE'] });
<del> return waitForIt(() => mockedComponent);
<add> return mockedComponent;
<ide> };
<del> const updated = await state();
<add> const updated = state();
<ide> assert(
<ide> updated.find('div').length === 1 &&
<ide> updated.find('h2').length === 1 &&
<ide> assert(code.match(/this\.state\.messages\.map/g));
<ide> The `input` element should render the value of `input` in local state.
<ide>
<ide> ```js
<del>async () => {
<add>() => {
<ide> const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages));
<del> const waitForIt = (fn) =>
<del> new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100));
<ide> const causeChange = (c, v) =>
<ide> c.find('input').simulate('change', { target: { value: v } });
<ide> const testValue = '__TEST__EVENT__INPUT';
<ide> const changed = () => {
<ide> causeChange(mockedComponent, testValue);
<del> return waitForIt(() => mockedComponent);
<add> return mockedComponent;
<ide> };
<del> const updated = await changed();
<add> const updated = changed();
<ide> assert(updated.find('input').props().value === testValue);
<ide> };
<ide> ```
<ide>
<ide> Calling the method `handleChange` should update the `input` value in state to the current input.
<ide>
<ide> ```js
<del>async () => {
<add>() => {
<ide> const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages));
<del> const waitForIt = (fn) =>
<del> new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100));
<ide> const causeChange = (c, v) =>
<ide> c.find('input').simulate('change', { target: { value: v } });
<ide> const initialState = mockedComponent.state();
<ide> const testMessage = '__TEST__EVENT__MESSAGE__';
<ide> const changed = () => {
<ide> causeChange(mockedComponent, testMessage);
<del> return waitForIt(() => mockedComponent);
<add> return mockedComponent;
<ide> };
<del> const afterInput = await changed();
<add> const afterInput = changed();
<ide> assert(
<ide> initialState.input === '' &&
<ide> afterInput.state().input === '__TEST__EVENT__MESSAGE__'
<ide> async () => {
<ide> Clicking the `Add message` button should call the method `submitMessage` which should add the current `input` to the `messages` array in state.
<ide>
<ide> ```js
<del>async () => {
<add>() => {
<ide> const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages));
<del> const waitForIt = (fn) =>
<del> new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100));
<ide> const causeChange = (c, v) =>
<ide> c.find('input').simulate('change', { target: { value: v } });
<ide> const initialState = mockedComponent.state();
<ide> const testMessage_1 = '__FIRST__MESSAGE__';
<ide> const firstChange = () => {
<ide> causeChange(mockedComponent, testMessage_1);
<del> return waitForIt(() => mockedComponent);
<add> return mockedComponent;
<ide> };
<del> const firstResult = await firstChange();
<add> const firstResult = firstChange();
<ide> const firstSubmit = () => {
<ide> mockedComponent.find('button').simulate('click');
<del> return waitForIt(() => mockedComponent);
<add> return mockedComponent;
<ide> };
<del> const afterSubmit_1 = await firstSubmit();
<add> const afterSubmit_1 = firstSubmit();
<ide> const submitState_1 = afterSubmit_1.state();
<ide> const testMessage_2 = '__SECOND__MESSAGE__';
<ide> const secondChange = () => {
<ide> causeChange(mockedComponent, testMessage_2);
<del> return waitForIt(() => mockedComponent);
<add> return mockedComponent;
<ide> };
<del> const secondResult = await secondChange();
<add> const secondResult = secondChange();
<ide> const secondSubmit = () => {
<ide> mockedComponent.find('button').simulate('click');
<del> return waitForIt(() => mockedComponent);
<add> return mockedComponent;
<ide> };
<del> const afterSubmit_2 = await secondSubmit();
<add> const afterSubmit_2 = secondSubmit();
<ide> const submitState_2 = afterSubmit_2.state();
<ide> assert(
<ide> initialState.messages.length === 0 &&
<ide> async () => {
<ide> The `submitMessage` method should clear the current input.
<ide>
<ide> ```js
<del>async () => {
<add>() => {
<ide> const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages));
<del> const waitForIt = (fn) =>
<del> new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100));
<ide> const causeChange = (c, v) =>
<ide> c.find('input').simulate('change', { target: { value: v } });
<ide> const initialState = mockedComponent.state();
<ide> const testMessage = '__FIRST__MESSAGE__';
<ide> const firstChange = () => {
<ide> causeChange(mockedComponent, testMessage);
<del> return waitForIt(() => mockedComponent);
<add> return mockedComponent;
<ide> };
<del> const firstResult = await firstChange();
<add> const firstResult = firstChange();
<ide> const firstState = firstResult.state();
<ide> const firstSubmit = () => {
<ide> mockedComponent.find('button').simulate('click');
<del> return waitForIt(() => mockedComponent);
<add> return mockedComponent;
<ide> };
<del> const afterSubmit = await firstSubmit();
<add> const afterSubmit = firstSubmit();
<ide> const submitState = afterSubmit.state();
<ide> assert(firstState.input === testMessage && submitState.input === '');
<ide> };
<ide><path>curriculum/challenges/english/03-front-end-development-libraries/react/use-a-ternary-expression-for-conditional-rendering.md
<ide> Your code should not contain any `if/else` statements.
<ide> ```js
<ide> assert(
<ide> new RegExp(/(\s|;)if(\s|\()/).test(
<del> Enzyme.mount(React.createElement(CheckUserAge)).instance().render.toString()
<add> code
<ide> ) === false
<ide> );
<ide> ```
<ide><path>curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/step-139.md
<ide> while(i < 5) {
<ide> See description above for instructions.
<ide>
<ide> ```js
<del>assert(
<add>assert.include(
<ide> pick
<ide> .toString()
<del> .replace(/\s/g, '')
<del> .includes(
<del> 'while(numbers.length<10){if(_LPC++%2000===0&&Date.now()-_LP>1500){'
<del> )
<add> .replace(/\s/g, ''),
<add> 'while(numbers.length<10){'
<ide> );
<ide> ```
<ide> | 3 |
PHP | PHP | use terser assertions | c1b2ca581c7282685743d68e6a4fb0ec94e2686f | <ide><path>lib/Cake/Test/Case/View/Helper/FormHelperTest.php
<ide> public function testTagIsInvalid() {
<ide>
<ide> $this->Form->setEntity('Contact.1.email');
<ide> $result = $this->Form->tagIsInvalid();
<del> $expected = false;
<del> $this->assertSame($expected, $result);
<add> $this->assertFalse($result);
<ide>
<ide> $this->Form->setEntity('Contact.0.name');
<ide> $result = $this->Form->tagIsInvalid();
<del> $expected = false;
<del> $this->assertSame($expected, $result);
<add> $this->assertFalse($result);
<ide> }
<ide>
<ide> /** | 1 |
Java | Java | try defaulcontenttype for application/octet-stream | 8ff7cc73bcffca02117aab069017e857b17d59f3 | <ide><path>spring-web/src/main/java/org/springframework/http/converter/AbstractHttpMessageConverter.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public final void write(final T t, MediaType contentType, HttpOutputMessage outp
<ide> if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) {
<ide> contentTypeToUse = getDefaultContentType(t);
<ide> }
<add> else if (MediaType.APPLICATION_OCTET_STREAM.equals(contentType)) {
<add> MediaType type = getDefaultContentType(t);
<add> contentTypeToUse = (type != null ? type : contentTypeToUse);
<add> }
<ide> if (contentTypeToUse != null) {
<ide> headers.setContentType(contentTypeToUse);
<ide> }
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java
<ide> import org.springframework.aop.framework.ProxyFactory;
<ide> import org.springframework.aop.target.SingletonTargetSource;
<ide> import org.springframework.core.MethodParameter;
<add>import org.springframework.core.io.ClassPathResource;
<add>import org.springframework.core.io.FileSystemResource;
<add>import org.springframework.core.io.Resource;
<ide> import org.springframework.http.HttpEntity;
<ide> import org.springframework.http.HttpInputMessage;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.converter.ByteArrayHttpMessageConverter;
<ide> import org.springframework.http.converter.HttpMessageConverter;
<ide> import org.springframework.http.converter.HttpMessageNotReadableException;
<add>import org.springframework.http.converter.ResourceHttpMessageConverter;
<ide> import org.springframework.http.converter.StringHttpMessageConverter;
<ide> import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
<ide> import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
<ide> import org.springframework.web.bind.WebDataBinder;
<ide> import org.springframework.web.bind.annotation.RequestBody;
<ide> import org.springframework.web.bind.annotation.RequestMapping;
<add>import org.springframework.web.bind.annotation.RequestMethod;
<ide> import org.springframework.web.bind.annotation.ResponseBody;
<ide> import org.springframework.web.bind.annotation.RestController;
<ide> import org.springframework.web.bind.support.WebDataBinderFactory;
<ide> public void handleReturnValueStringAcceptCharset() throws Exception {
<ide> assertEquals("text/plain;charset=UTF-8", servletResponse.getHeader("Content-Type"));
<ide> }
<ide>
<add> // SPR-12894
<add>
<add> @Test
<add> public void handleReturnValueImage() throws Exception {
<add> this.servletRequest.addHeader("Accept", "*/*");
<add>
<add> Method method = getClass().getMethod("getImage");
<add> MethodParameter returnType = new MethodParameter(method, -1);
<add>
<add> List<HttpMessageConverter<?>> converters = Arrays.asList(new ResourceHttpMessageConverter());
<add> RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);
<add>
<add> ClassPathResource resource = new ClassPathResource("logo.jpg", getClass());
<add> processor.writeWithMessageConverters(resource, returnType, this.webRequest);
<add>
<add> assertEquals("image/jpeg", this.servletResponse.getHeader("Content-Type"));
<add> }
<add>
<ide> @Test
<ide> public void supportsReturnTypeResponseBodyOnType() throws Exception {
<ide> Method method = ResponseBodyController.class.getMethod("handle");
<ide> public String handle(
<ide> return null;
<ide> }
<ide>
<add> @SuppressWarnings("unused")
<add> public Resource getImage() {
<add> return null;
<add> }
<ide>
<ide> @SuppressWarnings("unused")
<ide> private static abstract class MyParameterizedController<DTO extends Identifiable> { | 2 |
PHP | PHP | update componentmakecommand.php | 22e3efcf909095828cc347f185fc29cdb8e3a947 | <ide><path>src/Illuminate/Foundation/Console/ComponentMakeCommand.php
<ide> protected function writeView($onSuccess = null)
<ide> file_put_contents(
<ide> $path,
<ide> '<div>
<del> <!-- '.Inspiring::quote().' -->
<add> <!-- '.Inspiring::quotes()->random().' -->
<ide> </div>'
<ide> );
<ide>
<ide> protected function buildClass($name)
<ide> if ($this->option('inline')) {
<ide> return str_replace(
<ide> ['DummyView', '{{ view }}'],
<del> "<<<'blade'\n<div>\n <!-- ".Inspiring::quote()." -->\n</div>\nblade",
<add> "<<<'blade'\n<div>\n <!-- ".Inspiring::quotes()->random()." -->\n</div>\nblade",
<ide> parent::buildClass($name)
<ide> );
<ide> } | 1 |
Go | Go | fix logmode enum | 6948ab4fa187e0fec2455e51073a92b932818617 | <ide><path>api/types/container/host_config.go
<ide> type LogMode string
<ide>
<ide> // Available logging modes
<ide> const (
<del> LogModeUnset = ""
<add> LogModeUnset LogMode = ""
<ide> LogModeBlocking LogMode = "blocking"
<ide> LogModeNonBlock LogMode = "non-blocking"
<ide> )
<ide><path>daemon/logger/loggerutils/cache/local_cache.go
<ide> func WithLocalCache(l logger.Logger, info logger.Info) (logger.Logger, error) {
<ide> return nil, errors.Wrap(err, "error initializing local log cache driver")
<ide> }
<ide>
<del> if info.Config["mode"] == container.LogModeUnset || container.LogMode(info.Config["mode"]) == container.LogModeNonBlock {
<add> if container.LogMode(info.Config["mode"]) == container.LogModeUnset || container.LogMode(info.Config["mode"]) == container.LogModeNonBlock {
<ide> var size int64 = -1
<ide> if s, exists := info.Config["max-buffer-size"]; exists {
<ide> size, err = units.RAMInBytes(s) | 2 |
Python | Python | add parameters to ex_create_address | 8a3de717efdd904006015b0372fdc0973001094e | <ide><path>libcloud/compute/drivers/gce.py
<ide> def ex_list_zones(self):
<ide> return list_zones
<ide>
<ide> def ex_create_address(self, name, region=None, address=None,
<del> description=None):
<add> description=None, address_type='EXTERNAL',
<add> subnetwork=None):
<ide> """
<ide> Create a static address in a region, or a global address.
<ide>
<ide> def ex_create_address(self, name, region=None, address=None,
<ide> :keyword description: Optional descriptive comment.
<ide> :type description: ``str`` or ``None``
<ide>
<add> :keyword address_type: Optional The type of address to reserve,
<add> either INTERNAL or EXTERNAL. If unspecified,
<add> defaults to EXTERNAL.
<add> :type description: ``str``
<add>
<add> :keyword subnetwork: Optional The URL of the subnetwork in which to
<add> reserve the address. If an IP address is
<add> specified, it must be within the subnetwork's
<add> IP range. This field can only be used with
<add> INTERNAL type with GCE_ENDPOINT/DNS_RESOLVER
<add> purposes.
<add> :type description: ``str``
<add>
<ide> :return: Static Address object
<ide> :rtype: :class:`GCEAddress`
<ide> """ | 1 |
Text | Text | add fansworld-claudio to collaborators | 856822efe784fba12efdf69499f1f592552a4fa4 | <ide><path>README.md
<ide> information about the governance of the Node.js project, see
<ide> * [brendanashworth](https://github.com/brendanashworth) - **Brendan Ashworth** <brendan.ashworth@me.com>
<ide> * [calvinmetcalf](https://github.com/calvinmetcalf) - **Calvin Metcalf** <calvin.metcalf@gmail.com>
<ide> * [domenic](https://github.com/domenic) - **Domenic Denicola** <d@domenic.me>
<add>* [fansworld-claudio](https://github.com/fansworld-claudio) - **Claudio Rodriguez** <cjrodr@yahoo.com>
<ide> * [geek](https://github.com/geek) - **Wyatt Preul** <wpreul@gmail.com>
<ide> * [iarna](https://github.com/iarna) - **Rebecca Turner** <me@re-becca.org>
<ide> * [isaacs](https://github.com/isaacs) - **Isaac Z. Schlueter** <i@izs.me> | 1 |
PHP | PHP | remove unneeded "use" statements | 0247146f3163ebd04c07780d8ace0e99ab3ea6ba | <ide><path>src/Console/Shell.php
<ide>
<ide> use Cake\Console\Exception\ConsoleException;
<ide> use Cake\Console\Exception\StopException;
<del>use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<ide> use Cake\Datasource\ModelAwareTrait;
<ide> use Cake\Filesystem\File;
<ide><path>src/Controller/Component/PaginatorComponent.php
<ide> use Cake\Controller\ComponentRegistry;
<ide> use Cake\Datasource\Exception\PageOutOfBoundsException;
<ide> use Cake\Datasource\Paginator;
<del>use Cake\Datasource\QueryInterface;
<ide> use Cake\Network\Exception\NotFoundException;
<ide> use InvalidArgumentException;
<ide>
<ide><path>src/Http/Client/Response.php
<ide> */
<ide> namespace Cake\Http\Client;
<ide>
<del>use Cake\Http\Cookie\Cookie;
<ide> // This alias is necessary to avoid class name conflicts
<ide> // with the deprecated class in this namespace.
<ide> use Cake\Http\Cookie\CookieCollection as CookiesCollection;
<ide><path>src/Http/Cookie/Cookie.php
<ide> use DateTimeImmutable;
<ide> use DateTimezone;
<ide> use InvalidArgumentException;
<del>use RuntimeException;
<ide>
<ide> /**
<ide> * Cookie object to build a cookie and turn it into a header value
<ide><path>src/Http/Cookie/CookieCollection.php
<ide> namespace Cake\Http\Cookie;
<ide>
<ide> use ArrayIterator;
<del>use Cake\Http\Client\Response as ClientResponse;
<ide> use Countable;
<ide> use DateTimeImmutable;
<ide> use DateTimeZone;
<ide><path>src/I18n/Translator.php
<ide> */
<ide> namespace Cake\I18n;
<ide>
<del>use Aura\Intl\FormatterInterface;
<del>use Aura\Intl\Package;
<ide> use Aura\Intl\Translator as BaseTranslator;
<ide>
<ide> /**
<ide><path>src/Routing/Middleware/RoutingMiddleware.php
<ide> use Cake\Http\MiddlewareQueue;
<ide> use Cake\Http\Runner;
<ide> use Cake\Routing\Exception\RedirectException;
<del>use Cake\Routing\RouteBuilder;
<ide> use Cake\Routing\Router;
<ide> use Psr\Http\Message\ResponseInterface;
<ide> use Psr\Http\Message\ServerRequestInterface;
<ide><path>src/Routing/Router.php
<ide> namespace Cake\Routing;
<ide>
<ide> use Cake\Core\Configure;
<del>use Cake\Http\MiddlewareQueue;
<ide> use Cake\Http\ServerRequest;
<ide> use Cake\Utility\Inflector;
<del>use InvalidArgumentException;
<ide> use Psr\Http\Message\ServerRequestInterface;
<ide>
<ide> /**
<ide><path>src/TestSuite/Constraint/EventFired.php
<ide> class_alias('PHPUnit_Framework_Constraint', 'PHPUnit\Framework\Constraint\Constr
<ide> class_alias('PHPUnit_Framework_AssertionFailedError', 'PHPUnit\Framework\AssertionFailedError');
<ide> }
<ide>
<del>use Cake\Event\EventManager;
<ide> use PHPUnit\Framework\AssertionFailedError;
<ide> use PHPUnit\Framework\Constraint\Constraint;
<ide>
<ide><path>src/TestSuite/Constraint/EventFiredWith.php
<ide> class_alias('PHPUnit_Framework_AssertionFailedError', 'PHPUnit\Framework\Asserti
<ide> }
<ide>
<ide> use Cake\Event\Event;
<del>use Cake\Event\EventManager;
<ide> use PHPUnit\Framework\AssertionFailedError;
<ide> use PHPUnit\Framework\Constraint\Constraint;
<ide>
<ide><path>src/View/Helper/FormHelper.php
<ide>
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Exception\Exception;
<del>use Cake\Form\Form;
<ide> use Cake\Routing\Router;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Inflector;
<ide><path>tests/TestCase/Cache/CacheTest.php
<ide> use Cake\Cache\CacheRegistry;
<ide> use Cake\Cache\Engine\FileEngine;
<ide> use Cake\Cache\Engine\NullEngine;
<del>use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<ide> use Cake\TestSuite\TestCase;
<ide> use InvalidArgumentException;
<ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php
<ide> use Cake\Database\Driver\Postgres;
<ide> use Cake\Database\Schema\Collection as SchemaCollection;
<ide> use Cake\Database\Schema\PostgresSchema;
<del>use Cake\Database\Schema\Table;
<ide> use Cake\Database\Schema\TableSchema;
<ide> use Cake\Datasource\ConnectionManager;
<ide> use Cake\TestSuite\TestCase;
<ide><path>tests/TestCase/Error/ErrorHandlerTest.php
<ide>
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<del>use Cake\Error;
<ide> use Cake\Error\ErrorHandler;
<ide> use Cake\Error\PHP7ErrorException;
<ide> use Cake\Http\ServerRequest;
<ide><path>tests/TestCase/Error/Middleware/ErrorHandlerMiddlewareTest.php
<ide> use Cake\TestSuite\TestCase;
<ide> use LogicException;
<ide> use Psr\Log\LoggerInterface;
<del>use Zend\Diactoros\Request;
<ide>
<ide> /**
<ide> * Test for ErrorHandlerMiddleware
<ide><path>tests/TestCase/Event/EventDispatcherTraitTest.php
<ide>
<ide> namespace Cake\Test\TestCase\Event;
<ide>
<del>use Cake\Event\EventDispatcherTrait;
<ide> use Cake\Event\EventManager;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide><path>tests/TestCase/Http/Client/CookieCollectionTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Http\Client;
<ide>
<del>use Cake\Chronos\Chronos;
<ide> use Cake\Http\Client\CookieCollection;
<ide> use Cake\Http\Client\Response;
<del>use Cake\Http\Cookie\Cookie;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide><path>tests/TestCase/Http/Client/ResponseTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Http\Client;
<ide>
<del>use Cake\Chronos\Chronos;
<ide> use Cake\Http\Client\Response;
<del>use Cake\Http\Cookie\Cookie;
<ide> use Cake\Http\Cookie\CookieCollection;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide><path>tests/TestCase/Http/Cookie/CookieCollectionTest.php
<ide> namespace Cake\Test\TestCase\Http\Cookie;
<ide>
<ide> use Cake\Http\Client\Request as ClientRequest;
<del>use Cake\Http\Client\Response as ClientResponse;
<ide> use Cake\Http\Cookie\Cookie;
<ide> use Cake\Http\Cookie\CookieCollection;
<ide> use Cake\Http\Response;
<ide><path>tests/TestCase/Http/ResponseTest.php
<ide>
<ide> include_once CORE_TEST_CASES . DS . 'Http' . DS . 'server_mocks.php';
<ide>
<del>use Cake\Chronos\Chronos;
<ide> use Cake\Http\Cookie\Cookie;
<ide> use Cake\Http\Cookie\CookieCollection;
<ide> use Cake\Http\Response;
<ide><path>tests/TestCase/Network/Session/DatabaseSessionTest.php
<ide> namespace Cake\Test\TestCase\Network\Session;
<ide>
<ide> use Cake\Datasource\ConnectionManager;
<del>use Cake\Network\Session;
<ide> use Cake\Network\Session\DatabaseSession;
<ide> use Cake\ORM\Entity;
<ide> use Cake\ORM\TableRegistry;
<ide><path>tests/TestCase/ORM/AssociationProxyTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\ORM;
<ide>
<del>use Cake\ORM\Association;
<ide> use Cake\ORM\TableRegistry;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide><path>tests/TestCase/ORM/AssociationTest.php
<ide> namespace Cake\Test\TestCase\ORM;
<ide>
<ide> use Cake\Core\Plugin;
<del>use Cake\ORM\Association;
<ide> use Cake\ORM\Table;
<ide> use Cake\ORM\TableRegistry;
<ide> use Cake\TestSuite\TestCase;
<ide><path>tests/TestCase/Routing/DispatcherTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Routing;
<ide>
<del>use Cake\Controller\Controller;
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<ide> use Cake\Http\Response;
<ide><path>tests/TestCase/Routing/RouteBuilderTest.php
<ide> use Cake\Routing\Route\RedirectRoute;
<ide> use Cake\Routing\Route\Route;
<ide> use Cake\TestSuite\TestCase;
<del>use stdClass;
<ide>
<ide> /**
<ide> * RouteBuilder test case
<ide><path>tests/TestCase/Routing/RouteCollectionTest.php
<ide> use Cake\Routing\RouteCollection;
<ide> use Cake\Routing\Route\Route;
<ide> use Cake\TestSuite\TestCase;
<del>use \stdClass;
<ide>
<ide> class RouteCollectionTest extends TestCase
<ide> {
<ide><path>tests/TestCase/Routing/RouterTest.php
<ide>
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<del>use Cake\Http\MiddlewareQueue;
<ide> use Cake\Http\ServerRequest;
<ide> use Cake\Http\ServerRequestFactory;
<ide> use Cake\Routing\RouteBuilder;
<ide><path>tests/TestCase/Shell/CacheShellTest.php
<ide> namespace Cake\Test\TestCase\Shell;
<ide>
<ide> use Cake\Cache\Cache;
<del>use Cake\Console\Exception\StopException;
<ide> use Cake\Console\Shell;
<del>use Cake\Shell\CacheShell;
<ide> use Cake\TestSuite\ConsoleIntegrationTestCase;
<ide>
<ide> /**
<ide><path>tests/TestCase/Shell/RoutesShellTest.php
<ide>
<ide> use Cake\Console\Shell;
<ide> use Cake\Routing\Router;
<del>use Cake\Shell\RoutesShell;
<ide> use Cake\TestSuite\ConsoleIntegrationTestCase;
<ide>
<ide> /** | 29 |
Python | Python | remove flaky test | 534f6b7975dcd334f6d68eef14598d75c79e7921 | <ide><path>tests/test_model_saving.py
<ide>
<ide> @keras_test
<ide> def test_sequential_model_saving():
<del> model = Sequential()
<del> model.add(Dense(2, input_dim=3))
<del> model.add(Dense(3))
<del> model.compile(loss='mse', optimizer='rmsprop', metrics=['acc'])
<del>
<del> x = np.random.random((1, 3))
<del> y = np.random.random((1, 3))
<del> model.train_on_batch(x, y)
<del>
<del> out = model.predict(x)
<del> fname = 'tmp_' + str(np.random.randint(10000)) + '.h5'
<del> save_model(model, fname)
<del>
<del> new_model = load_model(fname)
<del>
<del> out2 = new_model.predict(x)
<del> assert_allclose(out, out2, atol=1e-05)
<del>
<del> # test that new updates are the same with both models
<del> x = np.random.random((1, 3))
<del> y = np.random.random((1, 3))
<del> model.train_on_batch(x, y)
<del> new_model.train_on_batch(x, y)
<del> out = model.predict(x)
<del> out2 = new_model.predict(x)
<del> assert_allclose(out, out2, atol=1e-05)
<del>
<del> # test load_weights on model file
<del> model.load_weights(fname)
<del> os.remove(fname)
<del>
<del>
<del>@keras_test
<del>def test_sequential_model_saving_2():
<del> # test with funkier config
<ide> model = Sequential()
<ide> model.add(Dense(2, input_dim=3))
<ide> model.add(RepeatVector(3))
<ide> def test_sequential_model_saving_2():
<ide>
<ide>
<ide> @keras_test
<del>def test_sequential_model_saving_3():
<add>def test_sequential_model_saving_2():
<ide> # test with custom optimizer, loss
<ide> custom_opt = optimizers.rmsprop
<ide> custom_loss = objectives.mse | 1 |
Ruby | Ruby | find query_source_location using lazy enumerator | 0bab6310d623f9f8ed382c93ddeb9f4d1a0b8f75 | <ide><path>activerecord/lib/active_record/log_subscriber.rb
<ide> def log_query_source
<ide> end
<ide>
<ide> def extract_query_source_location(locations)
<del> backtrace_cleaner.clean(locations).first
<add> backtrace_cleaner.clean(locations.lazy).first
<ide> end
<ide> end
<ide> end
<ide><path>activesupport/lib/active_support/backtrace_cleaner.rb
<ide> def silence(backtrace)
<ide> end
<ide>
<ide> def noise(backtrace)
<del> backtrace - silence(backtrace)
<add> backtrace.select do |line|
<add> @silencers.any? do |s|
<add> s.call(line)
<add> end
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>railties/test/backtrace_cleaner_test.rb
<ide> def setup
<ide> assert_equal 1, result.length
<ide> end
<ide>
<add> test "can filter for noise" do
<add> backtrace = [ "(irb):1",
<add> "/Path/to/rails/railties/lib/rails/commands/console.rb:77:in `start'",
<add> "bin/rails:4:in `<main>'" ]
<add> result = @cleaner.clean(backtrace, :noise)
<add> assert_equal "/Path/to/rails/railties/lib/rails/commands/console.rb:77:in `start'", result[0]
<add> assert_equal "bin/rails:4:in `<main>'", result[1]
<add> assert_equal 2, result.length
<add> end
<add>
<ide> test "should omit ActionView template methods names" do
<ide> method_name = ActionView::Template.new(nil, "app/views/application/index.html.erb", nil, locals: []).send :method_name
<ide> backtrace = [ "app/views/application/index.html.erb:4:in `block in #{method_name}'"] | 3 |
Ruby | Ruby | fix rubocop offenses | ea37ccddba06466ddcde67d6c2814e401d1e2c5c | <ide><path>actionpack/lib/action_controller/metal/request_forgery_protection.rb
<ide> class InvalidCrossOriginRequest < ActionControllerError #:nodoc:
<ide> # allowed via {CORS}[https://en.wikipedia.org/wiki/Cross-origin_resource_sharing]
<ide> # will also be able to create XHR requests. Be sure to check your
<ide> # CORS whitelist before disabling forgery protection for XHR.
<del> #
<add> #
<ide> # CSRF protection is turned on with the <tt>protect_from_forgery</tt> method.
<ide> # By default <tt>protect_from_forgery</tt> protects your session with
<ide> # <tt>:null_session</tt> method, which provides an empty session
<ide><path>tasks/release.rb
<ide> current_contents = File.read(fname)
<ide>
<ide> header = "## Rails #{version} (#{Date.today.strftime('%B %d, %Y')}) ##\n\n"
<del> header += "* No changes.\n\n\n" if current_contents =~ /\A##/
<add> header += "* No changes.\n\n\n" if current_contents.start_with?("##")
<ide> contents = header + current_contents
<ide> File.write(fname, contents)
<ide> end | 2 |
Text | Text | update some i18n references in guides | fc55c34bea1a499a201b0516b8493d0596e01934 | <ide><path>guides/source/i18n.md
<ide> Internationalization is a complex problem. Natural languages differ in so many w
<ide>
<ide> As part of this solution, **every static string in the Rails framework** - e.g. Active Record validation messages, time and date formats - **has been internationalized**. _Localization_ of a Rails application means defining translated values for these strings in desired languages.
<ide>
<add>To localize store and update _content_ in your application (e.g. translate blog posts), see the [Translating model content](#translating-model-content) section.
<add>
<ide> ### The Overall Architecture of the Library
<ide>
<ide> Thus, the Ruby I18n gem is split into two parts:
<ide> This means, that in the `:en` locale, the key _hello_ will map to the _Hello wor
<ide>
<ide> The I18n library will use **English** as a **default locale**, i.e. if a different locale is not set, `:en` will be used for looking up translations.
<ide>
<del>NOTE: The i18n library takes a **pragmatic approach** to locale keys (after [some discussion](https://groups.google.com/forum/#!topic/rails-i18n/FN7eLH2-lHA)), including only the _locale_ ("language") part, like `:en`, `:pl`, not the _region_ part, like `:en-US` or `:en-GB`, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as `:cs`, `:th` or `:es` (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the `:en-US` locale you would have $ as a currency symbol, while in `:en-GB`, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a `:en-GB` dictionary. Few gems such as [Globalize3](https://github.com/globalize/globalize) may help you implement it.
<add>NOTE: The i18n library takes a **pragmatic approach** to locale keys (after [some discussion](https://groups.google.com/forum/#!topic/rails-i18n/FN7eLH2-lHA)), including only the _locale_ ("language") part, like `:en`, `:pl`, not the _region_ part, like `:en-US` or `:en-GB`, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as `:cs`, `:th` or `:es` (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the `:en-US` locale you would have $ as a currency symbol, while in `:en-GB`, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a `:en-GB` dictionary.
<ide>
<ide> The **translations load path** (`I18n.load_path`) is an array of paths to files that will be loaded automatically. Configuring this path allows for customization of translations directory structure and file naming scheme.
<ide>
<ide> Customize your I18n Setup
<ide>
<ide> For several reasons the Simple backend shipped with Active Support only does the "simplest thing that could possibly work" _for Ruby on Rails_[^3] ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but cannot dynamically store them to any format.
<ide>
<del>That does not mean you're stuck with these limitations, though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend:
<add>That does not mean you're stuck with these limitations, though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs, by passing a backend instance to the `I18n.backend=` setter.
<ide>
<del>```ruby
<del>I18n.backend = Globalize::Backend::Static.new
<del>```
<add>For example, you can replace the Simple backend with the the Chain backend to chain multiple backends together. This is useful when you want to use standard translations with a Simple backend but store custom application translations in a database or other backends.
<ide>
<del>You can also use the Chain backend to chain multiple backends together. This is useful when you want to use standard translations with a Simple backend but store custom application translations in a database or other backends. For example, you could use the Active Record backend and fall back to the (default) Simple backend:
<add>With the Chain backend, you could use the Active Record backend and fall back to the (default) Simple backend:
<ide>
<ide> ```ruby
<ide> I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend)
<ide> To do so, the helper forces `I18n#translate` to raise exceptions no matter what
<ide> I18n.t :foo, raise: true # always re-raises exceptions from the backend
<ide> ```
<ide>
<add>Translating Model Content
<add>-------------------------
<add>
<add>The I18n API described in this guide is primarily intended for translating interface strings. If you are looking to translate model content (e.g. blog posts), you will need a different solution to help with this.
<add>
<add>Several gems can help with this:
<add>
<add>* [Globalize](https://github.com/globalize/globalize): Store translations on separate translation tables, one for each translated model
<add>* [Mobility](https://github.com/shioyama/mobility): Provides support for storing translations in many formats, including translation tables, json columns (Postgres), etc.
<add>* [Traco](https://github.com/barsoom/traco): Translatable columns for Rails 3 and 4, stored in the model table itself
<add>
<ide> Conclusion
<ide> ----------
<ide>
<ide> At this point you should have a good overview about how I18n support in Ruby on Rails works and are ready to start translating your project.
<ide>
<del>If you want to discuss certain portions or have questions, please sign up to the [rails-i18n mailing list](https://groups.google.com/forum/#!forum/rails-i18n).
<del>
<ide>
<ide> Contributing to Rails I18n
<ide> -------------------------- | 1 |
PHP | PHP | remove invalid test | 7ad5e59a7130143db98d6302a9427fd7dc033062 | <ide><path>tests/View/ViewBladeCompilerTest.php
<ide> public function testDontIncludeEmptyPath()
<ide> $compiler->compile();
<ide> }
<ide>
<del> public function testDontIncludeNullPath()
<del> {
<del> $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);
<del> $files->shouldReceive('get')->once()->with(null)->andReturn('Hello World');
<del> $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true);
<del> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1(null).'.php', 'Hello World');
<del> $compiler->setPath(null);
<del> $compiler->compile();
<del> }
<del>
<ide> public function testShouldStartFromStrictTypesDeclaration()
<ide> {
<ide> $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); | 1 |
Python | Python | add dialogpt support for pytorch->tf | 90f6e73a35ee85e94b898a6867f19707b264d387 | <ide><path>transformers/modeling_tf_pytorch_utils.py
<ide> def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, a
<ide> new_key = key.replace('gamma', 'weight')
<ide> if 'beta' in key:
<ide> new_key = key.replace('beta', 'bias')
<add> # DialoGPT format
<add> if key == 'lm_head.decoder.weight':
<add> new_key = 'lm_head.weight'
<ide> if new_key:
<ide> old_keys.append(key)
<ide> new_keys.append(new_key) | 1 |
Python | Python | use imp.find_module to remove task package | 854020079e1cd4d202691276c5008072c05490b0 | <ide><path>setup.py
<ide> if sys.version_info < (2, 5):
<ide> raise Exception("Celery requires Python 2.5 or higher.")
<ide>
<add>try:
<add> import imp
<add> import celery.app
<add> _, task_path, _ = imp.find_module("task", celery.app.__path__)
<add> if "__init__.py" in task_path:
<add> print("- force upgrading previous installation")
<add> print(" - removing %r package..." % task_path)
<add> try:
<add> os.unlink(os.path.abspath(task_path))
<add> except Exception, exc:
<add> sys.stderr.write("Couldn't remove %r: %r\n" % (task_path, exc))
<add>except ImportError:
<add> print("OH NOES")
<add>
<add>
<ide> try:
<ide> from setuptools import setup, find_packages
<ide> from setuptools.command.test import test
<ide> entrypoints = {}
<ide> extra = {}
<ide>
<del>try:
<del> from celery.app import task
<del> if "__init__.py" in task.__file__:
<del> print("- force upgrading previous installation")
<del> print(" - removing celery.app.task package...")
<del> try:
<del> os.unlink(os.path.abspath(task.__file__))
<del> except Exception, exc:
<del> sys.stderr.write("Couldn't remove %r: %r\n" % (task.__file__, exc))
<del>except ImportError:
<del> pass
<del>
<ide> # -*- Classifiers -*-
<ide>
<ide> classes = """ | 1 |
PHP | PHP | add allowdynamicproperties attributes | 7c71397bdfb68863bed47ebc01f506b99f480f3b | <ide><path>src/Mailer/Mailer.php
<ide> * @method array|string getBody(?string $type = null) Get generated message body as array.
<ide> * {@see \Cake\Mailer\Message::getBody()}
<ide> */
<add>#[\AllowDynamicProperties]
<ide> class Mailer implements EventListenerInterface
<ide> {
<ide> use ModelAwareTrait;
<ide><path>src/View/Cell.php
<ide> /**
<ide> * Cell base.
<ide> */
<add>#[\AllowDynamicProperties]
<ide> abstract class Cell implements EventDispatcherInterface
<ide> {
<ide> use EventDispatcherTrait;
<ide><path>src/View/Helper.php
<ide> * - `afterRenderFile(EventInterface $event, $viewFile, $content)` - Called after any view fragment is rendered.
<ide> * If a listener returns a non-null value, the output of the rendered file will be set to that.
<ide> */
<add>#[\AllowDynamicProperties]
<ide> class Helper implements EventListenerInterface
<ide> {
<ide> use InstanceConfigTrait;
<ide><path>src/View/View.php
<ide> * @property \Cake\View\Helper\UrlHelper $Url
<ide> * @property \Cake\View\ViewBlock $Blocks
<ide> */
<add>#[\AllowDynamicProperties]
<ide> class View implements EventDispatcherInterface
<ide> {
<ide> use CellTrait { | 4 |
PHP | PHP | fix incorrect error message when using arrays | e8aef48810d5803c515f476e194092f0aa0e371b | <ide><path>src/Illuminate/Validation/Validator.php
<ide> public function __construct(TranslatorInterface $translator, array $data, array
<ide> /**
<ide> * Parse the data and hydrate the files array.
<ide> *
<del> * @param array $data
<add> * @param array $data
<add> * @param string $arrayKey
<ide> * @return array
<ide> */
<del> protected function parseData(array $data)
<add> protected function parseData(array $data, $arrayKey = null)
<ide> {
<del> $this->files = array();
<add> if (is_null($arrayKey))
<add> {
<add> $this->files = array();
<add> }
<ide>
<ide> foreach ($data as $key => $value)
<ide> {
<add> $key = ($arrayKey) ? "$arrayKey.$key" : $key;
<add>
<ide> // If this value is an instance of the HttpFoundation File class we will
<ide> // remove it from the data array and add it to the files array, which
<ide> // we use to conveniently separate out these files from other data.
<ide> protected function parseData(array $data)
<ide>
<ide> unset($data[$key]);
<ide> }
<add> elseif (is_array($value))
<add> {
<add> $this->parseData($value, $key);
<add> }
<ide> }
<ide>
<ide> return $data; | 1 |
Javascript | Javascript | add ascii fast path to getstringwidth() | ab841d5fbab1a9d2f8323d1ae3f71f37c6f636a1 | <ide><path>benchmark/misc/getstringwidth.js
<add>'use strict';
<add>
<add>const common = require('../common.js');
<add>
<add>const bench = common.createBenchmark(main, {
<add> type: ['ascii', 'mixed', 'emojiseq', 'fullwidth'],
<add> n: [10e4]
<add>}, {
<add> flags: ['--expose-internals']
<add>});
<add>
<add>function main({ n, type }) {
<add> const { getStringWidth } = require('internal/readline/utils');
<add>
<add> const str = ({
<add> ascii: 'foobar'.repeat(100),
<add> mixed: 'foo'.repeat(100) + '😀' + 'bar'.repeat(100),
<add> emojiseq: '👨👨👧👦👨👩👦👦👨👩👧👧👩👩👧👦'.repeat(10),
<add> fullwidth: '你好'.repeat(150)
<add> })[type];
<add>
<add> bench.start();
<add> for (let j = 0; j < n; j += 1)
<add> getStringWidth(str);
<add> bench.end(n);
<add>}
<ide><path>lib/internal/readline/utils.js
<ide> if (internalBinding('config').hasIntl) {
<ide> const icu = internalBinding('icu');
<ide> getStringWidth = function getStringWidth(str, options) {
<ide> options = options || {};
<del> if (!Number.isInteger(str))
<del> str = stripVTControlCharacters(String(str));
<del> return icu.getStringWidth(
<del> str,
<del> Boolean(options.ambiguousAsFullWidth),
<del> Boolean(options.expandEmojiSequence)
<del> );
<add> if (Number.isInteger(str)) {
<add> // Provide information about the character with code point 'str'.
<add> return icu.getStringWidth(
<add> str,
<add> Boolean(options.ambiguousAsFullWidth),
<add> false
<add> );
<add> }
<add> str = stripVTControlCharacters(String(str));
<add> let width = 0;
<add> for (let i = 0; i < str.length; i++) {
<add> // Try to avoid calling into C++ by first handling the ASCII portion of
<add> // the string. If it is fully ASCII, we skip the C++ part.
<add> const code = str.charCodeAt(i);
<add> if (code < 127) {
<add> width += code >= 32;
<add> continue;
<add> }
<add> width += icu.getStringWidth(
<add> str.slice(i),
<add> Boolean(options.ambiguousAsFullWidth),
<add> Boolean(options.expandEmojiSequence)
<add> );
<add> break;
<add> }
<add> return width;
<ide> };
<ide> isFullWidthCodePoint =
<ide> function isFullWidthCodePoint(code, options) {
<ide><path>test/parallel/test-icu-stringwidth.js
<ide> assert.strictEqual(
<ide>
<ide> // Control chars and combining chars are zero
<ide> assert.strictEqual(readline.getStringWidth('\u200E\n\u220A\u20D2'), 1);
<add>
<add>// Test that the fast path for ASCII characters yields results consistent
<add>// with the 'slow' path.
<add>for (const ambiguousAsFullWidth of [ false, true ]) {
<add> for (let i = 0; i < 256; i++) {
<add> const char = String.fromCharCode(i);
<add> assert.strictEqual(
<add> readline.getStringWidth(i, { ambiguousAsFullWidth }),
<add> readline.getStringWidth(char, { ambiguousAsFullWidth }));
<add> assert.strictEqual(
<add> readline.getStringWidth(char + '🎉', { ambiguousAsFullWidth }),
<add> readline.getStringWidth(char, { ambiguousAsFullWidth }) + 2);
<add>
<add> if (i < 32 || (i >= 127 && i < 160)) { // Control character
<add> assert.strictEqual(
<add> readline.getStringWidth(i, { ambiguousAsFullWidth }), 0);
<add> } else if (i < 127) { // Regular ASCII character
<add> assert.strictEqual(
<add> readline.getStringWidth(i, { ambiguousAsFullWidth }), 1);
<add> }
<add> }
<add>} | 3 |
Javascript | Javascript | remove unnecessary instantiations | 1d192327f1a032dd022e1314386adfee777caad5 | <ide><path>examples/js/controls/EditorControls.js
<ide> THREE.EditorControls = function ( object, domElement ) {
<ide>
<ide> var scope = this;
<ide> var vector = new THREE.Vector3();
<add> var delta = new THREE.Vector3();
<add> var box = new THREE.Box3();
<ide>
<ide> var STATE = { NONE: - 1, ROTATE: 0, ZOOM: 1, PAN: 2 };
<ide> var state = STATE.NONE;
<ide> THREE.EditorControls = function ( object, domElement ) {
<ide>
<ide> this.focus = function ( target ) {
<ide>
<del> var box = new THREE.Box3().setFromObject( target );
<del>
<ide> var distance;
<ide>
<add> box.setFromObject( target );
<add>
<ide> if ( box.isEmpty() === false ) {
<ide>
<ide> center.copy( box.getCenter() );
<ide> THREE.EditorControls = function ( object, domElement ) {
<ide>
<ide> }
<ide>
<del> var delta = new THREE.Vector3( 0, 0, 1 );
<add> delta.set( 0, 0, 1 );
<ide> delta.applyQuaternion( object.quaternion );
<ide> delta.multiplyScalar( distance * 4 );
<ide>
<ide> THREE.EditorControls = function ( object, domElement ) {
<ide>
<ide> if ( state === STATE.ROTATE ) {
<ide>
<del> scope.rotate( new THREE.Vector3( - movementX * scope.rotationSpeed, - movementY * scope.rotationSpeed, 0 ) );
<add> scope.rotate( delta.set( - movementX * scope.rotationSpeed, - movementY * scope.rotationSpeed, 0 ) );
<ide>
<ide> } else if ( state === STATE.ZOOM ) {
<ide>
<del> scope.zoom( new THREE.Vector3( 0, 0, movementY ) );
<add> scope.zoom( delta.set( 0, 0, movementY ) );
<ide>
<ide> } else if ( state === STATE.PAN ) {
<ide>
<del> scope.pan( new THREE.Vector3( - movementX, movementY, 0 ) );
<add> scope.pan( delta.set( - movementX, movementY, 0 ) );
<ide>
<ide> }
<ide>
<ide> THREE.EditorControls = function ( object, domElement ) {
<ide> event.preventDefault();
<ide>
<ide> // Normalize deltaY due to https://bugzilla.mozilla.org/show_bug.cgi?id=1392460
<del> scope.zoom( new THREE.Vector3( 0, 0, event.deltaY > 0 ? 1 : - 1 ) );
<add> scope.zoom( delta.set( 0, 0, event.deltaY > 0 ? 1 : - 1 ) );
<ide>
<ide> }
<ide>
<ide> THREE.EditorControls = function ( object, domElement ) {
<ide> touches[ 0 ].set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY, 0 );
<ide> touches[ 1 ].set( event.touches[ 1 ].pageX, event.touches[ 1 ].pageY, 0 );
<ide> var distance = touches[ 0 ].distanceTo( touches[ 1 ] );
<del> scope.zoom( new THREE.Vector3( 0, 0, prevDistance - distance ) );
<add> scope.zoom( delta.set( 0, 0, prevDistance - distance ) );
<ide> prevDistance = distance;
<ide>
<ide> | 1 |
Javascript | Javascript | use proper circular reference checking | 859a2285940202014a5d13c2d3897e4bc870a02b | <ide><path>lib/util.js
<ide> function formatValue(ctx, value, recurseTimes) {
<ide> }
<ide> }
<ide>
<del> ctx.seen.push(value);
<del>
<del> var output = formatter(ctx, value, recurseTimes, visibleKeys, keys);
<add> // TODO(addaleax): Make `seen` a Set to avoid linear-time lookup.
<add> if (ctx.seen.includes(value)) {
<add> return ctx.stylize('[Circular]', 'special');
<add> }
<ide>
<add> ctx.seen.push(value);
<add> const output = formatter(ctx, value, recurseTimes, visibleKeys, keys);
<ide> ctx.seen.pop();
<ide>
<ide> return reduceToSingleString(output, base, braces, ctx.breakLength);
<ide> function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
<ide> }
<ide> }
<ide> if (!str) {
<del> if (ctx.seen.indexOf(desc.value) < 0) {
<del> if (recurseTimes === null) {
<del> str = formatValue(ctx, desc.value, null);
<add> if (recurseTimes === null) {
<add> str = formatValue(ctx, desc.value, null);
<add> } else {
<add> str = formatValue(ctx, desc.value, recurseTimes - 1);
<add> }
<add> if (str.indexOf('\n') > -1) {
<add> if (array) {
<add> str = str.replace(/\n/g, '\n ');
<ide> } else {
<del> str = formatValue(ctx, desc.value, recurseTimes - 1);
<del> }
<del> if (str.indexOf('\n') > -1) {
<del> if (array) {
<del> str = str.replace(/\n/g, '\n ');
<del> } else {
<del> str = str.replace(/^|\n/g, '\n ');
<del> }
<add> str = str.replace(/^|\n/g, '\n ');
<ide> }
<del> } else {
<del> str = ctx.stylize('[Circular]', 'special');
<ide> }
<ide> }
<ide> if (name === undefined) { | 1 |
Text | Text | add hints and solution for this challenge | 64efcac19938405cf40ff0e93d4551c322530b9a | <ide><path>guide/english/certifications/front-end-libraries/react-and-redux/extract-local-state-into-redux/index.md
<ide> title: Extract Local State into Redux
<ide> ---
<ide> ## Extract Local State into Redux
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/front-end-libraries/react-and-redux/extract-local-state-into-redux/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>### Hint 1
<add>You need to change the following sections:
<add>* default state declarations: remove `messages`
<add>* `submitMessage`: use `props`
<add>* `render`: the unordered list should use `props` instead of `this.state.messages`
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>### Hint 2
<add>Replace `this.state.messages` with `this.props.messages`.
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>### Hint 3
<add>The `submitMessage` function still needs to set the state of the `input`.
<add>
<add>
<add>### Solution
<add><details>
<add> <summary>Spoiler!</summary>
<add>
<add>```jsx
<add>// Redux:
<add>const ADD = 'ADD';
<add>
<add>const addMessage = (message) => {
<add> return {
<add> type: ADD,
<add> message: message
<add> }
<add>};
<add>
<add>const messageReducer = (state = [], action) => {
<add> switch (action.type) {
<add> case ADD:
<add> return [
<add> ...state,
<add> action.message
<add> ];
<add> default:
<add> return state;
<add> }
<add>};
<add>
<add>const store = Redux.createStore(messageReducer);
<add>
<add>// React:
<add>const Provider = ReactRedux.Provider;
<add>const connect = ReactRedux.connect;
<add>
<add>// Change code below this line
<add>class Presentational extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> input: ''
<add> }
<add> this.handleChange = this.handleChange.bind(this);
<add> this.submitMessage = this.submitMessage.bind(this);
<add> }
<add> handleChange(event) {
<add> this.setState({
<add> input: event.target.value
<add> });
<add> }
<add> submitMessage() {
<add> this.props.submitNewMessage(this.state.input);
<add> this.setState({
<add> input: ''
<add> });
<add>
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h2>Type in a new Message:</h2>
<add> <input
<add> value={this.state.input}
<add> onChange={this.handleChange}/><br/>
<add> <button onClick={this.submitMessage}>Submit</button>
<add> <ul>
<add> {this.props.messages.map( (message, idx) => {
<add> return (
<add> <li key={idx}>{message}</li>
<add> )
<add> })
<add> }
<add> </ul>
<add> </div>
<add> );
<add> }
<add>};
<add>// Change code above this line
<add>
<add>const mapStateToProps = (state) => {
<add> return {messages: state}
<add>};
<add>
<add>const mapDispatchToProps = (dispatch) => {
<add> return {
<add> submitNewMessage: (message) => {
<add> dispatch(addMessage(message))
<add> }
<add> }
<add>};
<add>
<add>const Container = connect(mapStateToProps, mapDispatchToProps)(Presentational);
<add>
<add>class AppWrapper extends React.Component {
<add> render() {
<add> return (
<add> <Provider store={store}>
<add> <Container/>
<add> </Provider>
<add> );
<add> }
<add>};
<add> ```
<add>
<add></details> | 1 |
PHP | PHP | remove empty class content | 9d0487bd04b8799cb7da3898b1277d6ac32969dc | <ide><path>tests/Bus/BusDispatcherTest.php
<ide> class BusDispatcherTestSpecificQueueAndDelayCommand implements Illuminate\Contra
<ide>
<ide> class StandAloneCommand
<ide> {
<del>
<ide> }
<ide>
<ide> class StandAloneHandler | 1 |
Javascript | Javascript | fix unit determination when autoskip is enabled | f606c23f2fbea2612208ffb49511b66e37ce4335 | <ide><path>src/scales/scale.time.js
<ide> function determineUnitForAutoTicks(minUnit, min, max, capacity) {
<ide>
<ide> for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
<ide> interval = INTERVALS[UNITS[i]];
<del> factor = interval.steps ? interval.steps / 2 : MAX_INTEGER;
<add> factor = interval.steps ? interval.steps : MAX_INTEGER;
<ide>
<ide> if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
<ide> return UNITS[i];
<ide> function determineUnitForAutoTicks(minUnit, min, max, capacity) {
<ide> /**
<ide> * Figures out what unit to format a set of ticks with
<ide> */
<del>function determineUnitForFormatting(scale, ticks, minUnit, min, max) {
<add>function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
<ide> var i, unit;
<ide>
<ide> for (i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {
<ide> unit = UNITS[i];
<del> if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= ticks.length - 1) {
<add> if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
<ide> return unit;
<ide> }
<ide> }
<ide> module.exports = Scale.extend({
<ide> var min = me.min;
<ide> var max = me.max;
<ide> var options = me.options;
<add> var tickOpts = options.ticks;
<ide> var timeOpts = options.time;
<ide> var timestamps = me._timestamps;
<ide> var ticks = [];
<ide> var capacity = me.getLabelCapacity(min);
<del> var source = options.ticks.source;
<add> var source = tickOpts.source;
<ide> var distribution = options.distribution;
<ide> var i, ilen, timestamp;
<ide>
<ide> module.exports = Scale.extend({
<ide> me.max = max;
<ide>
<ide> // PRIVATE
<del> me._unit = timeOpts.unit || determineUnitForFormatting(me, ticks, timeOpts.minUnit, me.min, me.max);
<del> me._majorUnit = !options.ticks.major.enabled || me._unit === 'year' ? undefined
<add> // determineUnitForFormatting relies on the number of ticks so we don't use it when
<add> // autoSkip is enabled because we don't yet know what the final number of ticks will be
<add> me._unit = timeOpts.unit || (tickOpts.autoSkip
<add> ? determineUnitForAutoTicks(timeOpts.minUnit, me.min, me.max, capacity)
<add> : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));
<add> me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined
<ide> : determineMajorUnit(me._unit);
<ide> me._table = buildLookupTable(me._timestamps.data, min, max, distribution);
<ide> me._offsets = computeOffsets(me._table, ticks, min, max, options);
<ide>
<del> if (options.ticks.reverse) {
<add> if (tickOpts.reverse) {
<ide> ticks.reverse();
<ide> }
<ide>
<ide><path>test/specs/scale.time.tests.js
<ide> describe('Time scale tests', function() {
<ide> var ticks = getTicksLabels(scale);
<ide>
<ide> // `bounds === 'data'`: first and last ticks removed since outside the data range
<del> expect(ticks).toEqual(['Jan 2', 'Jan 3', 'Jan 4', 'Jan 5', 'Jan 6', 'Jan 7', 'Jan 8', 'Jan 9', 'Jan 10']);
<add> expect(ticks.length).toEqual(217);
<ide> });
<ide>
<ide> it('should accept labels as date objects', function() {
<ide> describe('Time scale tests', function() {
<ide> var ticks = getTicksLabels(scale);
<ide>
<ide> // `bounds === 'data'`: first and last ticks removed since outside the data range
<del> expect(ticks).toEqual(['Jan 2', 'Jan 3', 'Jan 4', 'Jan 5', 'Jan 6', 'Jan 7', 'Jan 8', 'Jan 9', 'Jan 10']);
<add> expect(ticks.length).toEqual(217);
<ide> });
<ide>
<ide> it('should accept data as xy points', function() {
<ide> describe('Time scale tests', function() {
<ide> var ticks = getTicksLabels(xScale);
<ide>
<ide> // `bounds === 'data'`: first and last ticks removed since outside the data range
<del> expect(ticks).toEqual(['Jan 2', 'Jan 3', 'Jan 4', 'Jan 5', 'Jan 6', 'Jan 7', 'Jan 8', 'Jan 9', 'Jan 10']);
<add> expect(ticks.length).toEqual(217);
<ide> });
<ide>
<ide> it('should accept data as ty points', function() {
<ide> describe('Time scale tests', function() {
<ide> var ticks = getTicksLabels(tScale);
<ide>
<ide> // `bounds === 'data'`: first and last ticks removed since outside the data range
<del> expect(ticks).toEqual(['Jan 2', 'Jan 3', 'Jan 4', 'Jan 5', 'Jan 6', 'Jan 7', 'Jan 8', 'Jan 9', 'Jan 10']);
<add> expect(ticks.length).toEqual(217);
<ide> });
<ide> });
<ide> | 2 |
PHP | PHP | accept strings as disabled value | e52f8241387afb81eda9b57306ca77cc3f8930f7 | <ide><path>src/View/Widget/MultiCheckbox.php
<ide> protected function _isDisabled($key, $disabled) {
<ide> if ($disabled === null || $disabled === false) {
<ide> return false;
<ide> }
<del> if ($disabled === true) {
<add> if ($disabled === true || is_string($disabled)) {
<ide> return true;
<ide> }
<ide> $strict = !is_numeric($key);
<ide><path>tests/TestCase/View/Widget/MultiCheckboxTest.php
<ide> public function testRenderDisabled() {
<ide> ];
<ide> $this->assertTags($result, $expected);
<ide>
<add> $data['disabled'] = 'a string';
<add> $result = $input->render($data);
<add> $this->assertTags($result, $expected);
<add>
<ide> $data['disabled'] = ['1', '1x'];
<ide> $this->assertTags($result, $expected);
<ide> | 2 |
Ruby | Ruby | return an enumerable when no block given | 1c3ece12b997206fd9cb0b2bf98c25da8332fe10 | <ide><path>Library/Homebrew/tap.rb
<ide> def ==(other)
<ide> def self.each
<ide> return unless TAP_DIRECTORY.directory?
<ide>
<add> return to_enum unless block_given?
<add>
<ide> TAP_DIRECTORY.subdirs.each do |user|
<ide> user.subdirs.each do |repo|
<ide> yield fetch(user.basename.to_s, repo.basename.to_s)
<ide><path>Library/Homebrew/test/tap_spec.rb
<ide> def setup_git_repo
<ide> subject.config["foo"] = nil
<ide> expect(subject.config["foo"]).to be nil
<ide> end
<add>
<add> describe "#each" do
<add> it "returns an enumerator if no block is passed" do
<add> expect(described_class.each).to be_an_instance_of(Enumerator)
<add> end
<add> end
<ide> end
<ide>
<ide> describe CoreTap do | 2 |
Javascript | Javascript | fix css tests on opera | 9a6967755116f14b6f27fc00b5976b58f0bc6fcd | <ide><path>test/BinderSpec.js
<ide> describe('Binder', function(){
<ide> it('BindStyle', function(){
<ide> var scope = this.compile('<div ng:style="style"/>');
<ide>
<del> scope.$eval('style={color:"red"}');
<add> scope.$eval('style={height: "10px"}');
<ide> scope.$eval();
<ide>
<del> assertEquals("red", scope.$element.css('color'));
<add> assertEquals("10px", scope.$element.css('height'));
<ide>
<ide> scope.$eval('style={}');
<ide> scope.$eval();
<ide><path>test/directivesSpec.js
<ide> describe("directive", function(){
<ide>
<ide> describe('ng:style', function(){
<ide> it('should set', function(){
<del> var scope = compile('<div ng:style="{color:\'red\'}"></div>');
<add> var scope = compile('<div ng:style="{height: \'40px\'}"></div>');
<ide> scope.$eval();
<del> expect(element.css('color')).toEqual('red');
<add> expect(element.css('height')).toEqual('40px');
<ide> });
<ide>
<ide> it('should silently ignore undefined style', function() {
<ide> describe("directive", function(){
<ide> });
<ide>
<ide> it('should preserve and remove previous style', function(){
<del> var scope = compile('<div style="color:red;" ng:style="myStyle"></div>');
<add> var scope = compile('<div style="height: 10px;" ng:style="myStyle"></div>');
<ide> scope.$eval();
<del> expect(getStyle(element)).toEqual({color:'red'});
<del> scope.myStyle = {color:'blue', width:'10px'};
<add> expect(getStyle(element)).toEqual({height: '10px'});
<add> scope.myStyle = {height: '20px', width: '10px'};
<ide> scope.$eval();
<del> expect(getStyle(element)).toEqual({color:'blue', width:'10px'});
<add> expect(getStyle(element)).toEqual({height: '20px', width: '10px'});
<ide> scope.myStyle = {};
<ide> scope.$eval();
<del> expect(getStyle(element)).toEqual({color:'red'});
<add> expect(getStyle(element)).toEqual({height: '10px'});
<ide> });
<ide> });
<ide>
<ide><path>test/scenario/dslSpec.js
<ide> describe("angular.scenario.dsl", function() {
<ide> });
<ide>
<ide> it('should get css', function() {
<del> doc.append('<div id="test" style="border: 1px solid red"></div>');
<del> $root.dsl.element('#test').css('border');
<del> expect($root.futureResult).toMatch(/red/);
<add> doc.append('<div id="test" style="height: 30px"></div>');
<add> $root.dsl.element('#test').css('height');
<add> expect($root.futureResult).toMatch(/30px/);
<ide> });
<ide>
<ide> it('should set css', function() {
<del> doc.append('<div id="test" style="border: 1px solid red"></div>');
<del> $root.dsl.element('#test').css('border', '1px solid green');
<del> expect(doc.find('#test').css('border')).toMatch(/green/);
<add> doc.append('<div id="test" style="height: 10px"></div>');
<add> $root.dsl.element('#test').css('height', '20px');
<add> expect(doc.find('#test').css('height')).toEqual('20px');
<ide> });
<ide>
<ide> it('should add all jQuery key/value methods', function() { | 3 |
Mixed | Go | add negotiation process for driver scope | 304bfd6261ee7bbac245c60bb34a8c193c86c58d | <ide><path>libnetwork/docs/remote.md
<ide> When loaded, a remote driver process receives an HTTP POST on the URL `/Plugin.A
<ide>
<ide> Other entries in the list value are allowed; `"NetworkDriver"` indicates that the plugin should be registered with LibNetwork as a driver.
<ide>
<add>### Set capability
<add>
<add>After Handshake, the remote driver will receive another POST message to the URL `/NetworkDriver.GetCapabilities` with no payload. The driver's response should have the form:
<add>
<add>{
<add> "Scope": "local"
<add>}
<add>
<add>Value of "Scope" should be either "local" or "global" which indicates the capability of remote driver, values beyond these will fail driver's registration and return an error to the caller.
<add>
<ide> ### Create network
<ide>
<ide> When the proxy is asked to create a network, the remote process shall receive a POST to the URL `/NetworkDriver.CreateNetwork` of the form
<ide><path>libnetwork/drivers/remote/api/api.go
<ide> func (r *Response) GetError() string {
<ide> return r.Err
<ide> }
<ide>
<add>// GetCapabilityResponse is the response of GetCapability request
<add>type GetCapabilityResponse struct {
<add> Response
<add> Scope string
<add>}
<add>
<ide> // CreateNetworkRequest requests a new network.
<ide> type CreateNetworkRequest struct {
<ide> // A network ID that remote plugins are expected to store for future
<ide><path>libnetwork/drivers/remote/driver.go
<ide> func newDriver(name string, client *plugins.Client) driverapi.Driver {
<ide> // plugin is activated.
<ide> func Init(dc driverapi.DriverCallback) error {
<ide> plugins.Handle(driverapi.NetworkPluginEndpointType, func(name string, client *plugins.Client) {
<del> c := driverapi.Capability{
<del> Scope: driverapi.GlobalScope,
<add> // negotiate driver capability with client
<add> d := newDriver(name, client)
<add> c, err := d.(*driver).getCapabilities()
<add> if err != nil {
<add> log.Errorf("error getting capability for %s due to %v", name, err)
<add> return
<ide> }
<del> if err := dc.RegisterDriver(name, newDriver(name, client), c); err != nil {
<add> if err = dc.RegisterDriver(name, d, *c); err != nil {
<ide> log.Errorf("error registering driver for %s due to %v", name, err)
<ide> }
<ide> })
<ide> return nil
<ide> }
<ide>
<add>// Get capability from client
<add>func (d *driver) getCapabilities() (*driverapi.Capability, error) {
<add> var capResp api.GetCapabilityResponse
<add> if err := d.call("GetCapabilities", nil, &capResp); err != nil {
<add> return nil, err
<add> }
<add>
<add> c := &driverapi.Capability{}
<add> switch capResp.Scope {
<add> case "global":
<add> c.Scope = driverapi.GlobalScope
<add> case "local":
<add> c.Scope = driverapi.LocalScope
<add> default:
<add> return nil, fmt.Errorf("invalid capability: expecting 'local' or 'global', got %s", capResp.Scope)
<add> }
<add>
<add> return c, nil
<add>}
<add>
<ide> // Config is not implemented for remote drivers, since it is assumed
<ide> // to be supplied to the remote process out-of-band (e.g., as command
<ide> // line arguments).
<ide><path>libnetwork/drivers/remote/driver_test.go
<ide> func (test *testEndpoint) AddStaticRoute(destination *net.IPNet, routeType int,
<ide> return nil
<ide> }
<ide>
<add>func TestGetEmptyCapabilities(t *testing.T) {
<add> var plugin = "test-net-driver-empty-cap"
<add>
<add> mux := http.NewServeMux()
<add> defer setupPlugin(t, plugin, mux)()
<add>
<add> handle(t, mux, "GetCapabilities", func(msg map[string]interface{}) interface{} {
<add> return map[string]interface{}{}
<add> })
<add>
<add> p, err := plugins.Get(plugin, driverapi.NetworkPluginEndpointType)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> d := newDriver(plugin, p.Client)
<add> if d.Type() != plugin {
<add> t.Fatal("Driver type does not match that given")
<add> }
<add>
<add> _, err = d.(*driver).getCapabilities()
<add> if err == nil {
<add> t.Fatal("There should be error reported when get empty capability")
<add> }
<add>}
<add>
<add>func TestGetExtraCapabilities(t *testing.T) {
<add> var plugin = "test-net-driver-extra-cap"
<add>
<add> mux := http.NewServeMux()
<add> defer setupPlugin(t, plugin, mux)()
<add>
<add> handle(t, mux, "GetCapabilities", func(msg map[string]interface{}) interface{} {
<add> return map[string]interface{}{
<add> "Scope": "local",
<add> "foo": "bar",
<add> }
<add> })
<add>
<add> p, err := plugins.Get(plugin, driverapi.NetworkPluginEndpointType)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> d := newDriver(plugin, p.Client)
<add> if d.Type() != plugin {
<add> t.Fatal("Driver type does not match that given")
<add> }
<add>
<add> c, err := d.(*driver).getCapabilities()
<add> if err != nil {
<add> t.Fatal(err)
<add> } else if c.Scope != driverapi.LocalScope {
<add> t.Fatalf("get capability '%s', expecting 'local'", c.Scope)
<add> }
<add>}
<add>
<add>func TestGetInvalidCapabilities(t *testing.T) {
<add> var plugin = "test-net-driver-invalid-cap"
<add>
<add> mux := http.NewServeMux()
<add> defer setupPlugin(t, plugin, mux)()
<add>
<add> handle(t, mux, "GetCapabilities", func(msg map[string]interface{}) interface{} {
<add> return map[string]interface{}{
<add> "Scope": "fake",
<add> }
<add> })
<add>
<add> p, err := plugins.Get(plugin, driverapi.NetworkPluginEndpointType)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> d := newDriver(plugin, p.Client)
<add> if d.Type() != plugin {
<add> t.Fatal("Driver type does not match that given")
<add> }
<add>
<add> _, err = d.(*driver).getCapabilities()
<add> if err == nil {
<add> t.Fatal("There should be error reported when get invalid capability")
<add> }
<add>}
<add>
<ide> func TestRemoteDriver(t *testing.T) {
<ide> var plugin = "test-net-driver"
<ide>
<ide> func TestRemoteDriver(t *testing.T) {
<ide>
<ide> var networkID string
<ide>
<add> handle(t, mux, "GetCapabilities", func(msg map[string]interface{}) interface{} {
<add> return map[string]interface{}{
<add> "Scope": "global",
<add> }
<add> })
<ide> handle(t, mux, "CreateNetwork", func(msg map[string]interface{}) interface{} {
<ide> nid := msg["NetworkID"]
<ide> var ok bool
<ide> func TestRemoteDriver(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> driver := newDriver(plugin, p.Client)
<del> if driver.Type() != plugin {
<add> d := newDriver(plugin, p.Client)
<add> if d.Type() != plugin {
<ide> t.Fatal("Driver type does not match that given")
<ide> }
<ide>
<add> c, err := d.(*driver).getCapabilities()
<add> if err != nil {
<add> t.Fatal(err)
<add> } else if c.Scope != driverapi.GlobalScope {
<add> t.Fatalf("get capability '%s', expecting 'global'", c.Scope)
<add> }
<add>
<ide> netID := "dummy-network"
<del> err = driver.CreateNetwork(netID, map[string]interface{}{})
<add> err = d.CreateNetwork(netID, map[string]interface{}{})
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> endID := "dummy-endpoint"
<del> err = driver.CreateEndpoint(netID, endID, ep, map[string]interface{}{})
<add> err = d.CreateEndpoint(netID, endID, ep, map[string]interface{}{})
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> joinOpts := map[string]interface{}{"foo": "fooValue"}
<del> err = driver.Join(netID, endID, "sandbox-key", ep, joinOpts)
<add> err = d.Join(netID, endID, "sandbox-key", ep, joinOpts)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if _, err = driver.EndpointOperInfo(netID, endID); err != nil {
<add> if _, err = d.EndpointOperInfo(netID, endID); err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if err = driver.Leave(netID, endID); err != nil {
<add> if err = d.Leave(netID, endID); err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if err = driver.DeleteEndpoint(netID, endID); err != nil {
<add> if err = d.DeleteEndpoint(netID, endID); err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if err = driver.DeleteNetwork(netID); err != nil {
<add> if err = d.DeleteNetwork(netID); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> } | 4 |
Text | Text | add distinct to readme | 1ee6710b54c013d31951ce22c74ac72377ebbbf6 | <ide><path>README.md
<ide> The `OR` operator works like this:
<ide> users.where(users[:name].eq('bob').or(users[:age].lt(25)))
<ide> ```
<ide>
<del>The `AND` operator behaves similarly.
<add>The `AND` operator behaves similarly. The exception is the `DISTINCT` operator, which is not chainable:
<add>
<add>```
<add>posts = Arel::Table.new(:posts)
<add>posts.project(posts[:title])
<add>posts.distinct
<add>posts.to_sql # => 'SELECT DISTINCT "posts"."title" FROM "posts"'
<add>```
<ide>
<ide> Aggregate functions `AVG`, `SUM`, `COUNT`, `MIN`, `MAX`, `HAVING`:
<ide> | 1 |
Java | Java | fix examples using markdown instead of @code | 5aef7fee1add9bd0d64a38f1f671eeac3abe0db0 | <ide><path>src/main/java/io/reactivex/Flowable.java
<ide> public final <K> Flowable<T> distinct(Function<? super T, K> keySelector,
<ide> * {@code CharSequence}s or {@code List}s where the objects will actually have the same
<ide> * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same.
<ide> * To avoid such situation, it is recommended that mutable data is converted to an immutable one,
<del> * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`.
<add> * for example using {@code map(CharSequence::toString)} or {@code map(list -> Collections.unmodifiableList(new ArrayList<>(list)))}.
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<ide> * <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s
<ide> public final Flowable<T> distinctUntilChanged() {
<ide> * {@code CharSequence}s or {@code List}s where the objects will actually have the same
<ide> * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same.
<ide> * To avoid such situation, it is recommended that mutable data is converted to an immutable one,
<del> * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`.
<add> * for example using {@code map(CharSequence::toString)} or {@code map(list -> Collections.unmodifiableList(new ArrayList<>(list)))}.
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<ide> * <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s
<ide> public final <K> Flowable<T> distinctUntilChanged(Function<? super T, K> keySele
<ide> * {@code CharSequence}s or {@code List}s where the objects will actually have the same
<ide> * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same.
<ide> * To avoid such situation, it is recommended that mutable data is converted to an immutable one,
<del> * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`.
<add> * for example using {@code map(CharSequence::toString)} or {@code map(list -> Collections.unmodifiableList(new ArrayList<>(list)))}.
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<ide> * <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s
<ide><path>src/main/java/io/reactivex/Observable.java
<ide> public final <K> Observable<T> distinct(Function<? super T, K> keySelector, Call
<ide> * {@code CharSequence}s or {@code List}s where the objects will actually have the same
<ide> * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same.
<ide> * To avoid such situation, it is recommended that mutable data is converted to an immutable one,
<del> * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`.
<add> * for example using {@code map(CharSequence::toString)} or {@code map(list -> Collections.unmodifiableList(new ArrayList<>(list)))}.
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Observable<T> distinctUntilChanged() {
<ide> * {@code CharSequence}s or {@code List}s where the objects will actually have the same
<ide> * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same.
<ide> * To avoid such situation, it is recommended that mutable data is converted to an immutable one,
<del> * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`.
<add> * for example using {@code map(CharSequence::toString)} or {@code map(list -> Collections.unmodifiableList(new ArrayList<>(list)))}.
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final <K> Observable<T> distinctUntilChanged(Function<? super T, K> keySe
<ide> * {@code CharSequence}s or {@code List}s where the objects will actually have the same
<ide> * references when they are modified and {@code distinctUntilChanged} will evaluate subsequent items as same.
<ide> * To avoid such situation, it is recommended that mutable data is converted to an immutable one,
<del> * for example using `map(CharSequence::toString)` or `map(list -> Collections.unmodifiableList(new ArrayList<>(list)))`.
<add> * for example using {@code map(CharSequence::toString)} or {@code map(list -> Collections.unmodifiableList(new ArrayList<>(list)))}.
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.</dd> | 2 |
PHP | PHP | add short-cuts for status and content | 2e8d837e72375e6c2c1b4cb91cd65bb16dd6e0af | <ide><path>src/Illuminate/Http/ResponseTrait.php
<ide>
<ide> trait ResponseTrait {
<ide>
<add> /**
<add> * Get the status code for the response.
<add> *
<add> * @return int
<add> */
<add> public function status()
<add> {
<add> return $this->getStatusCode();
<add> }
<add>
<add> /**
<add> * Get the content of the response.
<add> *
<add> * @return string
<add> */
<add> public function content()
<add> {
<add> return $this->getContent();
<add> }
<add>
<ide> /**
<ide> * Set a header on the Response.
<ide> * | 1 |
Javascript | Javascript | convert openstream to promise | 6e30fe7a7f9ae15f78827884e330104d6e2666a3 | <ide><path>lib/internal/quic/core.js
<ide> const {
<ide> Promise,
<ide> PromiseAll,
<ide> PromiseReject,
<add> PromiseResolve,
<ide> RegExp,
<ide> Set,
<ide> Symbol,
<ide> const kDestroy = Symbol('kDestroy');
<ide> const kEndpointBound = Symbol('kEndpointBound');
<ide> const kEndpointClose = Symbol('kEndpointClose');
<ide> const kHandshake = Symbol('kHandshake');
<add>const kHandshakeComplete = Symbol('kHandshakeComplete');
<ide> const kHandshakePost = Symbol('kHandshakePost');
<ide> const kHeaders = Symbol('kHeaders');
<ide> const kInternalState = Symbol('kInternalState');
<ide> const kInternalClientState = Symbol('kInternalClientState');
<ide> const kInternalServerState = Symbol('kInternalServerState');
<ide> const kListen = Symbol('kListen');
<del>const kMakeStream = Symbol('kMakeStream');
<ide> const kMaybeBind = Symbol('kMaybeBind');
<ide> const kOnFileOpened = Symbol('kOnFileOpened');
<ide> const kOnFileUnpipe = Symbol('kOnFileUnpipe');
<ide> class QuicSession extends EventEmitter {
<ide> destroyed: false,
<ide> earlyData: false,
<ide> handshakeComplete: false,
<add> handshakeCompletePromise: undefined,
<add> handshakeCompletePromiseResolve: undefined,
<add> handshakeCompletePromiseReject: undefined,
<ide> idleTimeout: false,
<ide> maxPacketLength: NGTCP2_DEFAULT_MAX_PKTLEN,
<ide> servername: undefined,
<ide> class QuicSession extends EventEmitter {
<ide> });
<ide> }
<ide>
<add> [kHandshakeComplete]() {
<add> const state = this[kInternalState];
<add> if (state.handshakeComplete)
<add> return PromiseResolve();
<add>
<add> if (state.handshakeCompletePromise !== undefined)
<add> return state.handshakeCompletePromise;
<add>
<add> state.handshakeCompletePromise = new Promise((resolve, reject) => {
<add> state.handshakeCompletePromiseResolve = resolve;
<add> state.handshakeCompletePromiseReject = reject;
<add> }).finally(() => {
<add> state.handshakeCompletePromise = undefined;
<add> state.handshakeCompletePromiseReject = undefined;
<add> state.handshakeCompletePromiseResolve = undefined;
<add> });
<add>
<add> return state.handshakeCompletePromise;
<add> }
<add>
<ide> // Sets the internal handle for the QuicSession instance. For
<ide> // server QuicSessions, this is called immediately as the
<ide> // handle is created before the QuicServerSession JS object.
<ide> class QuicSession extends EventEmitter {
<ide> state.verifyErrorReason = verifyErrorReason;
<ide> state.verifyErrorCode = verifyErrorCode;
<ide> state.earlyData = earlyData;
<del> if (!this[kHandshakePost]())
<add>
<add> if (!this[kHandshakePost]()) {
<add> if (typeof state.handshakeCompletePromiseReject === 'function') {
<add> // TODO(@jasnell): Proper error
<add> state.handshakeCompletePromiseReject(
<add> new ERR_OPERATION_FAILED('Handshake failed'));
<add> }
<ide> return;
<add> }
<add>
<add> if (typeof state.handshakeCompletePromiseResolve === 'function')
<add> state.handshakeCompletePromiseResolve();
<ide>
<ide> process.nextTick(() => {
<ide> try {
<ide> class QuicSession extends EventEmitter {
<ide> } else if (typeof state.closePromiseResolve === 'function')
<ide> state.closePromiseResolve();
<ide>
<add> if (typeof state.handshakeCompletePromiseReject === 'function') {
<add> // TODO(@jasnell): Proper error
<add> state.handshakeCompletePromiseReject(
<add> new ERR_OPERATION_FAILED('Handshake failed'));
<add> }
<add>
<ide> process.nextTick(emit.bind(this, 'close'));
<ide> }
<ide>
<ide> class QuicSession extends EventEmitter {
<ide> return this[kInternalState].statelessReset;
<ide> }
<ide>
<del> openStream(options) {
<del> const state = this[kInternalState];
<add> async openStream(options) {
<ide> if (this.destroyed) {
<ide> throw new ERR_INVALID_STATE(
<ide> `${this.constructor.name} is already destroyed`);
<ide> class QuicSession extends EventEmitter {
<ide> throw new ERR_INVALID_STATE(
<ide> `${this.constructor.name} is closing`);
<ide> }
<add>
<ide> const {
<ide> halfOpen, // Unidirectional or Bidirectional
<ide> highWaterMark,
<ide> defaultEncoding,
<ide> } = validateQuicStreamOptions(options);
<ide>
<del> const stream = new QuicStream({
<del> highWaterMark,
<del> defaultEncoding,
<del> readable: !halfOpen
<del> }, this);
<add> await this[kHandshakeComplete]();
<ide>
<del> state.pendingStreams.add(stream);
<del>
<del> // If early data is being used, we can create the internal QuicStream on the
<del> // ready event, that is immediately after the internal QuicSession handle
<del> // has been created. Otherwise, we have to wait until the secure event
<del> // signaling the completion of the TLS handshake.
<del> const makeStream = QuicSession[kMakeStream].bind(this, stream, halfOpen);
<del> let deferred = false;
<del> if (!this.handshakeComplete) {
<del> deferred = true;
<del> this.once('secure', makeStream);
<add> if (this.destroyed) {
<add> throw new ERR_INVALID_STATE(
<add> `${this.constructor.name} is already destroyed`);
<add> }
<add> if (this.closing) {
<add> throw new ERR_INVALID_STATE(
<add> `${this.constructor.name} is closing`);
<ide> }
<ide>
<del> if (!deferred)
<del> makeStream(stream, halfOpen);
<del>
<del> return stream;
<del> }
<del>
<del> static [kMakeStream](stream, halfOpen) {
<del> this[kInternalState].pendingStreams.delete(stream);
<ide> const handle =
<ide> halfOpen ?
<ide> _openUnidirectionalStream(this[kHandle]) :
<ide> _openBidirectionalStream(this[kHandle]);
<ide>
<del> if (handle === undefined) {
<del> stream.destroy(new ERR_OPERATION_FAILED('Unable to create QuicStream'));
<del> return;
<del> }
<add> if (handle === undefined)
<add> throw new ERR_OPERATION_FAILED('Unable to create QuicStream');
<add>
<add> const stream = new QuicStream({
<add> highWaterMark,
<add> defaultEncoding,
<add> readable: !halfOpen
<add> }, this);
<ide>
<ide> stream[kSetHandle](handle);
<ide> this[kAddStream](stream.id, stream);
<add>
<add> return stream;
<ide> }
<ide>
<ide> get duration() {
<ide><path>test/parallel/test-quic-client-connect-multiple-parallel.js
<ide> async function connect(server, client) {
<ide> for (let i = 0; i < kCount; i++) {
<ide> const server = createQuicSocket({ server: options });
<ide>
<del> server.on('session', common.mustCall((session) => {
<del> session.on('secure', common.mustCall(() => {
<del> const stream = session.openStream({ halfOpen: true });
<del> stream.end('Hi!');
<del> }));
<add> server.on('session', common.mustCall(async (session) => {
<add> const stream = await session.openStream({ halfOpen: true });
<add> stream.end('Hi!');
<ide> }));
<ide>
<ide> server.on('close', common.mustCall());
<ide><path>test/parallel/test-quic-client-connect-multiple-sequential.js
<ide> async function connect(server, client) {
<ide> for (let i = 0; i < kCount; i++) {
<ide> const server = createQuicSocket({ server: options });
<ide>
<del> server.on('session', common.mustCall((session) => {
<del> session.on('secure', common.mustCall(() => {
<del> const stream = session.openStream({ halfOpen: true });
<del> stream.end('Hi!');
<del> }));
<add> server.on('session', common.mustCall(async (session) => {
<add> const stream = await session.openStream({ halfOpen: true });
<add> stream.end('Hi!');
<ide> }));
<ide>
<ide> server.on('close', common.mustCall());
<ide><path>test/parallel/test-quic-client-empty-preferred-address.js
<ide> const options = { key, cert, ca, alpn: 'zzz' };
<ide> preferredAddressPolicy: 'accept',
<ide> });
<ide>
<del> const stream = clientSession.openStream();
<add> const stream = await clientSession.openStream();
<ide> stream.end('hello');
<ide>
<ide> await Promise.all([
<ide><path>test/parallel/test-quic-client-server.js
<ide> client.on('close', common.mustCall(onSocketClose.bind(client)));
<ide> });
<ide> }));
<ide>
<del> session.on('secure', common.mustCall((servername, alpn, cipher) => {
<add> session.on('secure', common.mustCall(async (servername, alpn, cipher) => {
<ide> debug('QuicServerSession TLS Handshake Complete');
<ide> debug(' Server name: %s', servername);
<ide> debug(' ALPN: %s', alpn);
<ide> client.on('close', common.mustCall(onSocketClose.bind(client)));
<ide> assert(session.authenticated);
<ide> assert.strictEqual(session.authenticationError, undefined);
<ide>
<del> const uni = session.openStream({ halfOpen: true });
<add> const uni = await session.openStream({ halfOpen: true });
<ide> assert(uni.unidirectional);
<ide> assert(!uni.bidirectional);
<ide> assert(uni.serverInitiated);
<ide> client.on('close', common.mustCall(onSocketClose.bind(client)));
<ide> name: 'Error'
<ide> };
<ide> assert.throws(() => session.ping(), err);
<del> assert.throws(() => session.openStream(), err);
<ide> assert.throws(() => session.updateKey(), err);
<add> assert.rejects(() => session.openStream(), err);
<ide> }));
<ide> }));
<ide>
<ide> client.on('close', common.mustCall(onSocketClose.bind(client)));
<ide> debug(' Params: %s', params.toString('hex'));
<ide> }, 2));
<ide>
<del> req.on('secure', common.mustCall((servername, alpn, cipher) => {
<add> req.on('secure', common.mustCall(async (servername, alpn, cipher) => {
<ide> debug('QuicClientSession TLS Handshake Complete');
<ide> debug(' Server name: %s', servername);
<ide> debug(' ALPN: %s', alpn);
<ide> client.on('close', common.mustCall(onSocketClose.bind(client)));
<ide> }
<ide>
<ide> const file = fs.createReadStream(__filename);
<del> const stream = req.openStream();
<add> const stream = await req.openStream();
<ide> file.pipe(stream);
<ide> let data = '';
<ide> stream.resume();
<ide><path>test/parallel/test-quic-errors-quicsession-openstream.js
<ide> if (!common.hasQuic)
<ide> // Test errors thrown when openStream is called incorrectly
<ide> // or is not permitted
<ide>
<add>const { once } = require('events');
<ide> const { createHook } = require('async_hooks');
<ide> const assert = require('assert');
<ide> const { createQuicSocket } = require('net');
<ide> createHook({
<ide> }
<ide> }).enable();
<ide>
<del>const Countdown = require('../common/countdown');
<ide> const { key, cert, ca } = require('../common/quic');
<ide>
<ide> const options = { key, cert, ca, alpn: 'zzz', maxStreamsUni: 0 };
<ide> const server = createQuicSocket({ server: options });
<ide> const client = createQuicSocket({ client: options });
<ide>
<del>const countdown = new Countdown(1, () => {
<del> server.close();
<del> client.close();
<del>});
<del>
<ide> server.on('close', common.mustCall());
<ide> client.on('close', common.mustCall());
<ide>
<ide> client.on('close', common.mustCall());
<ide> port: server.endpoints[0].address.port
<ide> });
<ide>
<del> ['z', 1, {}, [], null, Infinity, 1n].forEach((i) => {
<del> assert.throws(
<del> () => req.openStream({ halfOpen: i }),
<del> { code: 'ERR_INVALID_ARG_TYPE' }
<del> );
<del> });
<add> for (const halfOpen of ['z', 1, {}, [], null, Infinity, 1n]) {
<add> await assert.rejects(req.openStream({ halfOpen }), {
<add> code: 'ERR_INVALID_ARG_TYPE'
<add> });
<add> }
<ide>
<del> ['', 1n, {}, [], false, 'zebra'].forEach((defaultEncoding) => {
<del> assert.throws(() => req.openStream({ defaultEncoding }), {
<add> for (const defaultEncoding of ['', 1n, {}, [], false, 'zebra']) {
<add> await assert.rejects(req.openStream({ defaultEncoding }), {
<ide> code: 'ERR_INVALID_ARG_VALUE'
<ide> });
<del> });
<add> }
<ide>
<del> [-1, Number.MAX_SAFE_INTEGER + 1].forEach((highWaterMark) => {
<del> assert.throws(() => req.openStream({ highWaterMark }), {
<add> for (const highWaterMark of [-1, Number.MAX_SAFE_INTEGER + 1]) {
<add> await assert.rejects(req.openStream({ highWaterMark }), {
<ide> code: 'ERR_OUT_OF_RANGE'
<ide> });
<del> });
<add> }
<ide>
<del> ['a', 1n, [], {}, false].forEach((highWaterMark) => {
<del> assert.throws(() => req.openStream({ highWaterMark }), {
<add> for (const highWaterMark of ['a', 1n, [], {}, false]) {
<add> await assert.rejects(req.openStream({ highWaterMark }), {
<ide> code: 'ERR_INVALID_ARG_TYPE'
<ide> });
<del> });
<add> }
<ide>
<ide> // Unidirectional streams are not allowed. openStream will succeeed
<ide> // but the stream will be destroyed immediately. The underlying
<ide> // QuicStream C++ handle will not be created.
<del> req.openStream({
<del> halfOpen: true,
<del> highWaterMark: 10,
<del> defaultEncoding: 'utf16le'
<del> }).on('error', common.expectsError({
<del> code: 'ERR_OPERATION_FAILED'
<del> })).on('error', common.mustCall(() => countdown.dec()));
<add> await assert.rejects(
<add> req.openStream({
<add> halfOpen: true,
<add> highWaterMark: 10,
<add> defaultEncoding: 'utf16le'
<add> }), {
<add> code: 'ERR_OPERATION_FAILED'
<add> });
<add>
<add> server.close();
<add> client.close();
<add>
<add> await Promise.all([
<add> once(server, 'close'),
<add> once(client, 'close')
<add> ]);
<ide>
<ide> })().then(common.mustCall());
<ide><path>test/parallel/test-quic-http3-client-server.js
<ide> const countdown = new Countdown(1, () => {
<ide> req.on('close', common.mustCall());
<ide>
<ide> const file = fs.createReadStream(__filename);
<del> const stream = req.openStream();
<del>
<del> stream.on('ready', common.mustCall(() => {
<del> assert(stream.submitInitialHeaders({
<del> ':method': 'POST',
<del> ':scheme': 'https',
<del> ':authority': 'localhost',
<del> ':path': '/',
<del> }));
<del> file.pipe(stream);
<del> let data = '';
<del> stream.resume();
<del> stream.setEncoding('utf8');
<del>
<del> stream.on('initialHeaders', common.mustCall((headers) => {
<del> const expected = [
<del> [ ':status', '200' ]
<del> ];
<del> assert.deepStrictEqual(expected, headers);
<del> debug('Received expected response headers');
<del> }));
<del> stream.on('informationalHeaders', common.mustNotCall());
<del> stream.on('trailingHeaders', common.mustNotCall());
<del>
<del> stream.on('data', (chunk) => data += chunk);
<del> stream.on('finish', common.mustCall());
<del> stream.on('end', common.mustCall(() => {
<del> assert.strictEqual(data, filedata);
<del> debug('Client received expected data for stream %d', stream.id);
<del> }));
<del> stream.on('close', common.mustCall(() => {
<del> debug('Bidirectional, Client-initiated stream %d closed', stream.id);
<del> countdown.dec();
<del> }));
<del> debug('Bidirectional, Client-initiated stream %d opened', stream.id);
<add> const stream = await req.openStream();
<add>
<add> assert(stream.submitInitialHeaders({
<add> ':method': 'POST',
<add> ':scheme': 'https',
<add> ':authority': 'localhost',
<add> ':path': '/',
<add> }));
<add> file.pipe(stream);
<add> let data = '';
<add> stream.resume();
<add> stream.setEncoding('utf8');
<add>
<add> stream.on('initialHeaders', common.mustCall((headers) => {
<add> const expected = [
<add> [ ':status', '200' ]
<add> ];
<add> assert.deepStrictEqual(expected, headers);
<add> debug('Received expected response headers');
<add> }));
<add> stream.on('informationalHeaders', common.mustNotCall());
<add> stream.on('trailingHeaders', common.mustNotCall());
<add>
<add> stream.on('data', (chunk) => data += chunk);
<add> stream.on('finish', common.mustCall());
<add> stream.on('end', common.mustCall(() => {
<add> assert.strictEqual(data, filedata);
<add> debug('Client received expected data for stream %d', stream.id);
<add> }));
<add> stream.on('close', common.mustCall(() => {
<add> debug('Bidirectional, Client-initiated stream %d closed', stream.id);
<add> countdown.dec();
<ide> }));
<add> debug('Bidirectional, Client-initiated stream %d opened', stream.id);
<ide>
<ide> })().then(common.mustCall());
<ide><path>test/parallel/test-quic-http3-push.js
<ide> const countdown = new Countdown(2, () => {
<ide>
<ide> req.on('close', common.mustCall());
<ide>
<del> const stream = req.openStream();
<add> const stream = await req.openStream();
<ide>
<ide> stream.on('pushHeaders', common.mustCall((headers, push_id) => {
<ide> const expected = [
<ide> const countdown = new Countdown(2, () => {
<ide> countdown.dec();
<ide> }));
<ide>
<del> stream.on('ready', () => {
<del> assert(stream.submitInitialHeaders({
<del> ':method': 'POST',
<del> ':scheme': 'https',
<del> ':authority': 'localhost',
<del> ':path': '/',
<del> }));
<add> assert(stream.submitInitialHeaders({
<add> ':method': 'POST',
<add> ':scheme': 'https',
<add> ':authority': 'localhost',
<add> ':path': '/',
<add> }));
<ide>
<del> stream.end('hello world');
<del> stream.resume();
<del> stream.on('finish', common.mustCall());
<del> stream.on('end', common.mustCall());
<del> });
<add> stream.end('hello world');
<add> stream.resume();
<add> stream.on('finish', common.mustCall());
<add> stream.on('end', common.mustCall());
<ide>
<ide> })().then(common.mustCall());
<ide><path>test/parallel/test-quic-http3-trailers.js
<ide> const countdown = new Countdown(1, () => {
<ide>
<ide> req.on('close', common.mustCall());
<ide>
<del> const stream = req.openStream();
<add> const stream = await req.openStream();
<ide>
<ide> stream.on('trailingHeaders', common.mustCall((headers) => {
<ide> const expected = [ [ 'a', '1' ] ];
<ide> assert.deepStrictEqual(expected, headers);
<ide> }));
<ide>
<del> stream.on('ready', common.mustCall(() => {
<del> assert(stream.submitInitialHeaders({
<del> ':method': 'POST',
<del> ':scheme': 'https',
<del> ':authority': 'localhost',
<del> ':path': '/',
<del> }));
<del>
<del> stream.submitTrailingHeaders({ 'b': 2 });
<del> stream.end('hello world');
<del> stream.resume();
<del> stream.on('finish', common.mustCall());
<del> stream.on('end', common.mustCall());
<add> assert(stream.submitInitialHeaders({
<add> ':method': 'POST',
<add> ':scheme': 'https',
<add> ':authority': 'localhost',
<add> ':path': '/',
<ide> }));
<ide>
<add> stream.submitTrailingHeaders({ 'b': 2 });
<add> stream.end('hello world');
<add> stream.resume();
<add> stream.on('finish', common.mustCall());
<add> stream.on('end', common.mustCall());
<add>
<ide> stream.on('initialHeaders', common.mustCall((headers) => {
<ide> const expected = [
<ide> [ ':status', '200' ]
<ide><path>test/parallel/test-quic-ipv6only.js
<ide> async function ipv6() {
<ide> port: server.endpoints[0].address.port
<ide> });
<ide>
<del> const stream = session.openStream({ halfOpen: true });
<add> const stream = await session.openStream({ halfOpen: true });
<ide> stream.end('hello');
<ide>
<ide> await once(stream, 'close');
<ide> async function mismatch() {
<ide> type: 'udp6',
<ide> idleTimeout: common.platformTimeout(1),
<ide> }), {
<del> code: 'ERR_OPERATION_FAILED'
<add> code: 'ERR_QUIC_FAILED_TO_CREATE_SESSION'
<ide> });
<ide>
<ide> client.close();
<ide><path>test/parallel/test-quic-process-cleanup.js
<ide> server.on('close', common.mustNotCall());
<ide> client.on('close', common.mustNotCall());
<ide>
<ide> (async function() {
<del> server.on('session', common.mustCall((session) => {
<del> session.on('secure', common.mustCall((servername, alpn, cipher) => {
<del> const stream = session.openStream({ halfOpen: false });
<del> stream.write('Hi!');
<del> stream.on('data', common.mustNotCall());
<del> stream.on('finish', common.mustNotCall());
<del> stream.on('close', common.mustNotCall());
<del> stream.on('end', common.mustNotCall());
<del> }));
<add> server.on('session', common.mustCall(async (session) => {
<add> const stream = await session.openStream({ halfOpen: false });
<add> stream.write('Hi!');
<add> stream.on('data', common.mustNotCall());
<add> stream.on('finish', common.mustNotCall());
<add> stream.on('close', common.mustNotCall());
<add> stream.on('end', common.mustNotCall());
<ide>
<ide> session.on('close', common.mustNotCall());
<ide> }));
<ide><path>test/parallel/test-quic-qlog.js
<ide> const client = createQuicSocket({
<ide> clientSide.afterBind();
<ide>
<ide> (async function() {
<del> server.on('session', common.mustCall((session) => {
<add> server.on('session', common.mustCall(async (session) => {
<ide> gatherQlog(session, 'server');
<del> session.openStream({ halfOpen: true }).end('Hi!');
<add> (await session.openStream({ halfOpen: true })).end('Hi!');
<ide> }));
<ide>
<ide> await server.listen();
<ide><path>test/parallel/test-quic-quicsession-openstream-pending.js
<del>// Flags: --no-warnings
<del>'use strict';
<del>const common = require('../common');
<del>if (!common.hasQuic)
<del> common.skip('missing quic');
<del>
<del>// Test that opening a stream works even if the session isn’t ready yet.
<del>
<del>const assert = require('assert');
<del>const { createQuicSocket } = require('net');
<del>const { key, cert, ca } = require('../common/quic');
<del>const { once } = require('events');
<del>const options = { key, cert, ca, alpn: 'meow' };
<del>
<del>const server = createQuicSocket({ server: options });
<del>const client = createQuicSocket({ client: options });
<del>
<del>(async () => {
<del> server.on('session', common.mustCall((session) => {
<del> session.on('stream', common.mustCall(async (stream) => {
<del> let data = '';
<del> stream.setEncoding('utf8');
<del> stream.on('data', (chunk) => data += chunk);
<del> await once(stream, 'end');
<del> assert.strictEqual(data, 'Hello!');
<del> }));
<del> }));
<del>
<del> await server.listen();
<del>
<del> const req = await client.connect({
<del> address: common.localhostIPv4,
<del> port: server.endpoints[0].address.port
<del> });
<del>
<del> // In this case, the QuicStream is usable but corked
<del> // until the underlying internal QuicStream handle
<del> // has been created, which will not happen until
<del> // after the TLS handshake has been completed.
<del> const stream = req.openStream({ halfOpen: true });
<del> stream.end('Hello!');
<del> stream.on('error', common.mustNotCall());
<del> stream.resume();
<del> assert(!req.allowEarlyData);
<del> assert(!req.handshakeComplete);
<del> assert(stream.pending);
<del>
<del> await once(stream, 'ready');
<del>
<del> assert(req.handshakeComplete);
<del> assert(!stream.pending);
<del>
<del> await once(stream, 'close');
<del>
<del> server.close();
<del> client.close();
<del>
<del> await Promise.all([
<del> once(server, 'close'),
<del> once(client, 'close')
<del> ]);
<del>})().then(common.mustCall());
<ide><path>test/parallel/test-quic-quicsession-resume.js
<ide> const countdown = new Countdown(2, () => {
<ide> storedParams = params;
<ide> }, 1));
<ide>
<del> req.on('secure', () => {
<del> const stream = req.openStream({ halfOpen: true });
<del> stream.end('hello');
<del> stream.resume();
<del> stream.on('close', () => {
<del> req.close();
<del> countdown.dec();
<del> // Wait a turn then start a new session using the stored
<del> // ticket and transportParameters
<del> setImmediate(newSession, storedTicket, storedParams);
<del> });
<add> const stream = await req.openStream({ halfOpen: true });
<add> stream.end('hello');
<add> stream.resume();
<add> stream.on('close', () => {
<add> req.close();
<add> countdown.dec();
<add> // Wait a turn then start a new session using the stored
<add> // ticket and transportParameters
<add> setImmediate(newSession, storedTicket, storedParams);
<ide> });
<ide>
<ide> async function newSession(sessionTicket, remoteTransportParams) {
<ide> const countdown = new Countdown(2, () => {
<ide>
<ide> assert(req.allowEarlyData);
<ide>
<del> const stream = req.openStream({ halfOpen: true });
<add> const stream = await req.openStream({ halfOpen: true });
<ide> stream.end('hello');
<ide> stream.on('error', common.mustNotCall());
<ide> stream.on('close', common.mustCall(() => countdown.dec()));
<ide>
<del> // TODO(@jasnell): There's a slight bug in here in that
<del> // calling end() will uncork the stream, causing data to
<del> // be flushed to the C++ layer, which will trigger a
<del> // SendPendingData that will start the handshake. That
<del> // has the effect of short circuiting the intent of
<del> // manual startHandshake(), which makes it not use 0RTT
<del> // for the stream data.
<del>
<del> req.on('secure', common.mustCall(() => {
<del> // TODO(@jasnell): This will be false for now because no
<del> // early data was sent. Once we actually start making
<del> // use of early data on the client side, this should be
<del> // true when the early data was accepted.
<del> assert(!req.usingEarlyData);
<del> }));
<add> // TODO(@jasnell): This will be false for now because no
<add> // early data was sent. Once we actually start making
<add> // use of early data on the client side, this should be
<add> // true when the early data was accepted.
<add> assert(!req.usingEarlyData);
<ide> }
<ide>
<ide> })().then(common.mustCall());
<ide><path>test/parallel/test-quic-quicsession-send-fd.js
<ide> async function test({ variant, offset, length }) {
<ide> const client = createQuicSocket({ client: options });
<ide> let fd;
<ide>
<del> server.on('session', common.mustCall((session) => {
<del> session.on('secure', common.mustCall((servername, alpn, cipher) => {
<del> const stream = session.openStream({ halfOpen: true });
<add> server.on('session', common.mustCall(async (session) => {
<add> const stream = await session.openStream({ halfOpen: true });
<ide>
<del> // The data and end events won't emit because
<del> // the stream is never readable.
<del> stream.on('data', common.mustNotCall());
<del> stream.on('end', common.mustNotCall());
<add> // The data and end events won't emit because
<add> // the stream is never readable.
<add> stream.on('data', common.mustNotCall());
<add> stream.on('end', common.mustNotCall());
<ide>
<del> stream.on('finish', common.mustCall());
<del> stream.on('close', common.mustCall());
<add> stream.on('finish', common.mustCall());
<add> stream.on('close', common.mustCall());
<ide>
<del> if (variant === 'sendFD') {
<del> fd = fs.openSync(__filename, 'r');
<del> stream.sendFD(fd, { offset, length });
<del> } else if (variant === 'sendFD+fileHandle') {
<del> fs.promises.open(__filename, 'r').then(common.mustCall((handle) => {
<del> fd = handle;
<del> stream.sendFD(handle, { offset, length });
<del> }));
<del> } else {
<del> assert.strictEqual(variant, 'sendFile');
<del> stream.sendFile(__filename, { offset, length });
<del> }
<del> }));
<add> if (variant === 'sendFD') {
<add> fd = fs.openSync(__filename, 'r');
<add> stream.sendFD(fd, { offset, length });
<add> } else if (variant === 'sendFD+fileHandle') {
<add> fs.promises.open(__filename, 'r').then(common.mustCall((handle) => {
<add> fd = handle;
<add> stream.sendFD(handle, { offset, length });
<add> }));
<add> } else {
<add> assert.strictEqual(variant, 'sendFile');
<add> stream.sendFile(__filename, { offset, length });
<add> }
<ide>
<ide> session.on('close', common.mustCall());
<ide> }));
<ide><path>test/parallel/test-quic-quicsession-send-file-close-before-open.js
<ide> const server = createQuicSocket({ server: options });
<ide> const client = createQuicSocket({ client: options });
<ide>
<ide> (async function() {
<del> server.on('session', common.mustCall((session) => {
<del> session.on('secure', common.mustCall((servername, alpn, cipher) => {
<del> const stream = session.openStream({ halfOpen: false });
<add> server.on('session', common.mustCall(async (session) => {
<add> const stream = await session.openStream({ halfOpen: false });
<ide>
<del> fs.open = common.mustCall(fs.open);
<del> fs.close = common.mustCall(fs.close);
<add> fs.open = common.mustCall(fs.open);
<add> fs.close = common.mustCall(fs.close);
<ide>
<del> stream.sendFile(__filename);
<del> stream.destroy(); // Destroy the stream before opening the fd finishes.
<add> stream.sendFile(__filename);
<add> stream.destroy(); // Destroy the stream before opening the fd finishes.
<ide>
<del> session.close();
<del> }));
<add> session.close();
<ide>
<ide> session.on('close', common.mustCall());
<ide> }));
<ide><path>test/parallel/test-quic-quicsession-send-file-open-error-handled.js
<ide> const server = createQuicSocket({ server: options });
<ide> const client = createQuicSocket({ client: options });
<ide>
<ide> (async function() {
<del> server.on('session', common.mustCall((session) => {
<del> session.on('secure', common.mustCall((servername, alpn, cipher) => {
<del> const stream = session.openStream({ halfOpen: true });
<del> const nonexistentPath = path.resolve(__dirname, 'nonexistent.file');
<del> stream.sendFile(nonexistentPath, {
<del> onError: common.expectsError({
<del> code: 'ENOENT',
<del> syscall: 'open',
<del> path: nonexistentPath
<del> })
<del> });
<del> session.close();
<del> }));
<add> server.on('session', common.mustCall(async (session) => {
<add> const stream = await session.openStream({ halfOpen: true });
<add> const nonexistentPath = path.resolve(__dirname, 'nonexistent.file');
<add> stream.sendFile(nonexistentPath, {
<add> onError: common.expectsError({
<add> code: 'ENOENT',
<add> syscall: 'open',
<add> path: nonexistentPath
<add> })
<add> });
<add> session.close();
<ide>
<ide> session.on('close', common.mustCall());
<ide> }));
<ide><path>test/parallel/test-quic-quicsession-send-file-open-error.js
<ide> const server = createQuicSocket({ server: options });
<ide> const client = createQuicSocket({ client: options });
<ide>
<ide> (async function() {
<del> server.on('session', common.mustCall((session) => {
<del> session.on('secure', common.mustCall((servername, alpn, cipher) => {
<del> const stream = session.openStream({ halfOpen: false });
<del> const nonexistentPath = path.resolve(__dirname, 'nonexistent.file');
<del> stream.on('error', common.expectsError({
<del> code: 'ENOENT',
<del> syscall: 'open',
<del> path: nonexistentPath
<del> }));
<del> stream.sendFile(nonexistentPath);
<del> session.close();
<add> server.on('session', common.mustCall(async (session) => {
<add> const stream = await session.openStream({ halfOpen: false });
<add> const nonexistentPath = path.resolve(__dirname, 'nonexistent.file');
<add> stream.on('error', common.expectsError({
<add> code: 'ENOENT',
<add> syscall: 'open',
<add> path: nonexistentPath
<ide> }));
<add> stream.sendFile(nonexistentPath);
<add> session.close();
<ide>
<ide> session.on('close', common.mustCall());
<ide> }));
<ide><path>test/parallel/test-quic-quicsession-server-openstream-pending.js
<del>// Flags: --no-warnings
<del>'use strict';
<del>const common = require('../common');
<del>if (!common.hasQuic)
<del> common.skip('missing quic');
<del>
<del>// Test that opening a stream works even if the session isn’t ready yet.
<del>
<del>const assert = require('assert');
<del>const { createQuicSocket } = require('net');
<del>const { key, cert, ca } = require('../common/quic');
<del>const { once } = require('events');
<del>const options = { key, cert, ca, alpn: 'meow' };
<del>
<del>const server = createQuicSocket({ server: options });
<del>const client = createQuicSocket({ client: options });
<del>
<del>(async () => {
<del> server.on('session', common.mustCall((session) => {
<del> // The server can create a stream immediately without waiting
<del> // for the secure event... however, the data will not actually
<del> // be transmitted until the handshake is completed.
<del> const stream = session.openStream({ halfOpen: true });
<del> stream.on('close', common.mustCall());
<del> stream.on('error', console.log);
<del> stream.end('hello');
<del>
<del> session.on('stream', common.mustNotCall());
<del> }));
<del>
<del> await server.listen();
<del>
<del> const req = await client.connect({
<del> address: common.localhostIPv4,
<del> port: server.endpoints[0].address.port,
<del> });
<del>
<del> const [ stream ] = await once(req, 'stream');
<del>
<del> let data = '';
<del> stream.setEncoding('utf8');
<del> stream.on('data', (chunk) => data += chunk);
<del> stream.on('end', common.mustCall());
<del>
<del> await once(stream, 'close');
<del>
<del> assert.strictEqual(data, 'hello');
<del>
<del> server.close();
<del> client.close();
<del>
<del> await Promise.all([
<del> once(server, 'close'),
<del> once(client, 'close')
<del> ]);
<del>
<del>})().then(common.mustCall());
<ide><path>test/parallel/test-quic-quicsocket-packetloss-stream-rx.js
<ide> const countdown = new Countdown(1, () => {
<ide> port: server.endpoints[0].address.port,
<ide> });
<ide>
<del> const stream = req.openStream();
<add> const stream = await req.openStream();
<ide>
<ide> let n = 0;
<ide> // This forces multiple stream packets to be sent out
<ide><path>test/parallel/test-quic-quicsocket-packetloss-stream-tx.js
<ide> const countdown = new Countdown(1, () => {
<ide> port: server.endpoints[0].address.port,
<ide> });
<ide>
<del> const stream = req.openStream();
<add> const stream = await req.openStream();
<ide>
<ide> let n = 0;
<ide> // This forces multiple stream packets to be sent out
<ide><path>test/parallel/test-quic-quicstream-close-early.js
<ide> const countdown = new Countdown(2, () => {
<ide> });
<ide>
<ide> (async function() {
<del> server.on('session', common.mustCall((session) => {
<del> session.on('secure', common.mustCall((servername, alpn, cipher) => {
<del> const uni = session.openStream({ halfOpen: true });
<del> uni.write('hi', common.expectsError());
<del> uni.on('error', common.mustCall(() => {
<del> assert.strictEqual(uni.aborted, true);
<del> }));
<del> uni.on('data', common.mustNotCall());
<del> uni.on('close', common.mustCall());
<del> uni.close(3);
<add> server.on('session', common.mustCall(async (session) => {
<add> const uni = await session.openStream({ halfOpen: true });
<add> uni.write('hi', common.expectsError());
<add> uni.on('error', common.mustCall(() => {
<add> assert.strictEqual(uni.aborted, true);
<ide> }));
<add> uni.on('data', common.mustNotCall());
<add> uni.on('close', common.mustCall());
<add> uni.close(3);
<ide> session.on('stream', common.mustNotCall());
<ide> session.on('close', common.mustCall());
<ide> }));
<ide> const countdown = new Countdown(2, () => {
<ide> port: server.endpoints[0].address.port,
<ide> });
<ide>
<del> req.on('secure', common.mustCall((servername, alpn, cipher) => {
<del> const stream = req.openStream();
<del> stream.write('hello', common.expectsError());
<del> stream.write('there', common.expectsError());
<del> stream.on('error', common.mustCall(() => {
<del> assert.strictEqual(stream.aborted, true);
<del> }));
<del> stream.on('end', common.mustNotCall());
<del> stream.on('close', common.mustCall(() => {
<del> countdown.dec();
<del> }));
<del> stream.close(1);
<del> }));
<del>
<ide> req.on('stream', common.mustCall((stream) => {
<ide> stream.on('abort', common.mustNotCall());
<ide> stream.on('data', common.mustCall((chunk) => {
<ide> const countdown = new Countdown(2, () => {
<ide> }));
<ide> }));
<ide>
<add> const stream = await req.openStream();
<add> stream.write('hello', common.expectsError());
<add> stream.write('there', common.expectsError());
<add> stream.on('error', common.mustCall(() => {
<add> assert.strictEqual(stream.aborted, true);
<add> }));
<add> stream.on('end', common.mustNotCall());
<add> stream.on('close', common.mustCall(() => {
<add> countdown.dec();
<add> }));
<add> stream.close(1);
<add>
<ide> await Promise.all([
<ide> once(server, 'close'),
<ide> once(client, 'close')
<ide><path>test/parallel/test-quic-quicstream-destroy.js
<ide> const server = createQuicSocket({ server: options });
<ide> port: server.endpoints[0].address.port
<ide> });
<ide>
<del> const stream = req.openStream();
<add> const stream = await req.openStream();
<ide> stream.write('foo');
<ide> // Do not explicitly end the stream here.
<ide>
<ide><path>test/parallel/test-quic-quicstream-identifiers.js
<ide> const countdown = new Countdown(4, () => {
<ide> const closeHandler = common.mustCall(() => countdown.dec(), 4);
<ide>
<ide> (async function() {
<del> server.on('session', common.mustCall((session) => {
<del> session.on('secure', common.mustCall(() => {
<del> ([3, 1n, [], {}, null, 'meow']).forEach((halfOpen) => {
<del> assert.throws(() => session.openStream({ halfOpen }), {
<del> code: 'ERR_INVALID_ARG_TYPE',
<add> server.on('session', common.mustCall(async (session) => {
<add> ([3, 1n, [], {}, null, 'meow']).forEach((halfOpen) => {
<add> assert.rejects(
<add> session.openStream({ halfOpen }), {
<add> code: 'ERR_INVALID_ARG_TYPE'
<ide> });
<del> });
<add> });
<ide>
<del> const uni = session.openStream({ halfOpen: true });
<del> uni.end('test');
<add> const uni = await session.openStream({ halfOpen: true });
<add> uni.end('test');
<ide>
<del> const bidi = session.openStream();
<del> bidi.end('test');
<del> bidi.resume();
<del> bidi.on('end', common.mustCall());
<add> const bidi = await session.openStream();
<add> bidi.end('test');
<add> bidi.resume();
<add> bidi.on('end', common.mustCall());
<ide>
<del> assert.strictEqual(uni.id, 3);
<del> assert(uni.unidirectional);
<del> assert(uni.serverInitiated);
<del> assert(!uni.bidirectional);
<del> assert(!uni.clientInitiated);
<add> assert.strictEqual(uni.id, 3);
<add> assert(uni.unidirectional);
<add> assert(uni.serverInitiated);
<add> assert(!uni.bidirectional);
<add> assert(!uni.clientInitiated);
<ide>
<del> assert.strictEqual(bidi.id, 1);
<del> assert(bidi.bidirectional);
<del> assert(bidi.serverInitiated);
<del> assert(!bidi.unidirectional);
<del> assert(!bidi.clientInitiated);
<del> }));
<add> assert.strictEqual(bidi.id, 1);
<add> assert(bidi.bidirectional);
<add> assert(bidi.serverInitiated);
<add> assert(!bidi.unidirectional);
<add> assert(!bidi.clientInitiated);
<ide>
<ide> session.on('stream', common.mustCall((stream) => {
<ide> assert(stream.clientInitiated);
<ide> const closeHandler = common.mustCall(() => countdown.dec(), 4);
<ide> port: server.endpoints[0].address.port,
<ide> });
<ide>
<del> req.on('secure', common.mustCall(() => {
<del> const bidi = req.openStream();
<del> bidi.end('test');
<del> bidi.resume();
<del> bidi.on('close', closeHandler);
<del> assert.strictEqual(bidi.id, 0);
<del>
<del> assert(bidi.clientInitiated);
<del> assert(bidi.bidirectional);
<del> assert(!bidi.serverInitiated);
<del> assert(!bidi.unidirectional);
<del>
<del> const uni = req.openStream({ halfOpen: true });
<del> uni.end('test');
<del> uni.on('close', closeHandler);
<del> assert.strictEqual(uni.id, 2);
<del>
<del> assert(uni.clientInitiated);
<del> assert(!uni.bidirectional);
<del> assert(!uni.serverInitiated);
<del> assert(uni.unidirectional);
<del> }));
<add> const bidi = await req.openStream();
<add> bidi.end('test');
<add> bidi.resume();
<add> bidi.on('close', closeHandler);
<add> assert.strictEqual(bidi.id, 0);
<add>
<add> assert(bidi.clientInitiated);
<add> assert(bidi.bidirectional);
<add> assert(!bidi.serverInitiated);
<add> assert(!bidi.unidirectional);
<add>
<add> const uni = await req.openStream({ halfOpen: true });
<add> uni.end('test');
<add> uni.on('close', closeHandler);
<add> assert.strictEqual(uni.id, 2);
<add>
<add> assert(uni.clientInitiated);
<add> assert(!uni.bidirectional);
<add> assert(!uni.serverInitiated);
<add> assert(uni.unidirectional);
<ide>
<ide> req.on('stream', common.mustCall((stream) => {
<ide> assert(stream.serverInitiated);
<ide><path>test/parallel/test-quic-simple-client-migrate.js
<ide> const server = createQuicSocket({ server: options });
<ide>
<ide> (async function() {
<ide> server.on('session', common.mustCall((session) => {
<del> session.on('stream', common.mustCall((stream) => {
<add> session.on('stream', common.mustCall(async (stream) => {
<ide> pipeline(stream, stream, common.mustCall());
<del> session.openStream({ halfOpen: true }).end('Hello from the server');
<add> (await session.openStream({ halfOpen: true }))
<add> .end('Hello from the server');
<ide> }));
<ide> }));
<ide>
<ide> const server = createQuicSocket({ server: options });
<ide> server.close();
<ide> });
<ide>
<del> req.on('secure', common.mustCall(() => {
<del> let data = '';
<del> const stream = req.openStream();
<del> stream.setEncoding('utf8');
<del> stream.on('data', (chunk) => data += chunk);
<del> stream.on('end', common.mustCall(() => {
<del> assert.strictEqual(data, 'Hello from the client');
<del> }));
<del> stream.on('close', common.mustCall());
<del> // Send some data on one connection...
<del> stream.write('Hello ');
<del>
<del> // Wait just a bit, then migrate to a different
<del> // QuicSocket and continue sending.
<del> setTimeout(common.mustCall(async () => {
<del> await req.setSocket(client2);
<del> client.close();
<del> stream.end('from the client');
<del> }), common.platformTimeout(100));
<del> }));
<del>
<ide> req.on('stream', common.mustCall((stream) => {
<ide> let data = '';
<ide> stream.setEncoding('utf8');
<ide> const server = createQuicSocket({ server: options });
<ide> stream.on('close', common.mustCall());
<ide> }));
<ide>
<add> let data = '';
<add> const stream = await req.openStream();
<add> stream.setEncoding('utf8');
<add> stream.on('data', (chunk) => data += chunk);
<add> stream.on('end', common.mustCall(() => {
<add> assert.strictEqual(data, 'Hello from the client');
<add> }));
<add> stream.on('close', common.mustCall());
<add> // Send some data on one connection...
<add> stream.write('Hello ');
<add>
<add> // Wait just a bit, then migrate to a different
<add> // QuicSocket and continue sending.
<add> setTimeout(common.mustCall(async () => {
<add> await req.setSocket(client2);
<add> client.close();
<add> stream.end('from the client');
<add> }), common.platformTimeout(100));
<add>
<ide> await Promise.all([
<ide> once(server, 'close'),
<ide> once(client2, 'close')
<ide><path>test/parallel/test-quic-statelessreset.js
<ide> server.on('close', common.mustCall(() => {
<ide> port: server.endpoints[0].address.port,
<ide> });
<ide>
<del> const stream = req.openStream();
<del> stream.end('hello');
<del> stream.resume();
<del> stream.on('close', common.mustCall());
<del>
<ide> req.on('close', common.mustCall(() => {
<ide> assert.strictEqual(req.statelessReset, true);
<ide> server.close();
<ide> client.close();
<ide> }));
<add>
<add> const stream = await req.openStream();
<add> stream.end('hello');
<add> stream.resume();
<add> stream.on('close', common.mustCall());
<add>
<ide> })().then(common.mustCall());
<ide><path>test/parallel/test-quic-with-fake-udp.js
<ide> const client = createQuicSocket({
<ide> clientSide.afterBind();
<ide>
<ide> (async function() {
<del> server.on('session', common.mustCall((session) => {
<del> session.on('secure', common.mustCall(() => {
<del> const stream = session.openStream({ halfOpen: false });
<del> stream.end('Hi!');
<del> stream.on('data', common.mustNotCall());
<del> stream.on('finish', common.mustCall());
<del> stream.on('close', common.mustNotCall());
<del> stream.on('end', common.mustNotCall());
<del> }));
<add> server.on('session', common.mustCall(async (session) => {
<ide> session.on('close', common.mustNotCall());
<add> const stream = await session.openStream({ halfOpen: false });
<add> stream.end('Hi!');
<add> stream.on('data', common.mustNotCall());
<add> stream.on('finish', common.mustCall());
<add> stream.on('close', common.mustNotCall());
<add> stream.on('end', common.mustNotCall());
<ide> }));
<ide>
<ide> await server.listen(); | 27 |
Ruby | Ruby | add an options argument | 8bf28477a3da58ea5c6113d9ce3228c08c4c0ec0 | <ide><path>Library/Homebrew/utils/popen.rb
<ide> module Utils
<del> def self.popen_read(*args, &block)
<del> popen(args, "rb", &block)
<add> def self.popen_read(*args, **options, &block)
<add> popen(args, "rb", options, &block)
<ide> end
<ide>
<del> def self.popen_write(*args, &block)
<del> popen(args, "wb", &block)
<add> def self.popen_write(*args, **options, &block)
<add> popen(args, "wb", options, &block)
<ide> end
<ide>
<del> def self.popen(args, mode)
<add> def self.popen(args, mode, options = {})
<ide> IO.popen("-", mode) do |pipe|
<ide> if pipe
<ide> return pipe.read unless block_given?
<ide> yield pipe
<ide> else
<del> $stderr.reopen("/dev/null", "w")
<del> exec(*args)
<add> options[:err] ||= :close
<add> exec(*args, options)
<ide> end
<ide> end
<ide> end | 1 |
Java | Java | update copyright header | d4dd8baed569f0ce1236aafffd578b0aa69a51f3 | <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/config/MethodInvokingFactoryBean.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License. | 1 |
Javascript | Javascript | replace function with arrow function | 3c62f33d7ba0f0ec6124d5dc721811808803b8b7 | <ide><path>test/parallel/test-assert.js
<ide> const a = assert;
<ide>
<ide> function makeBlock(f) {
<ide> const args = Array.prototype.slice.call(arguments, 1);
<del> return function() {
<del> return f.apply(this, args);
<add> return () => {
<add> return f.apply(null, args);
<ide> };
<ide> }
<ide>
<ide> assert.doesNotThrow(makeBlock(a.deepEqual, a1, a2));
<ide>
<ide> // having an identical prototype property
<ide> const nbRoot = {
<del> toString: function() { return `${this.first} ${this.last}`; }
<add> toString() { return `${this.first} ${this.last}`; }
<ide> };
<ide>
<ide> function nameBuilder(first, last) {
<ide> assert.throws(makeBlock(thrower, TypeError));
<ide> 'a.doesNotThrow is not catching type matching errors');
<ide> }
<ide>
<del>assert.throws(function() { assert.ifError(new Error('test error')); },
<add>assert.throws(() => { assert.ifError(new Error('test error')); },
<ide> /^Error: test error$/);
<del>assert.doesNotThrow(function() { assert.ifError(null); });
<del>assert.doesNotThrow(function() { assert.ifError(); });
<add>assert.doesNotThrow(() => { assert.ifError(null); });
<add>assert.doesNotThrow(() => { assert.ifError(); });
<ide>
<ide> assert.throws(() => {
<ide> assert.doesNotThrow(makeBlock(thrower, Error), 'user message');
<ide> assert.throws(() => {
<ide> let threw = false;
<ide> try {
<ide> assert.throws(
<del> function() {
<add> () => {
<ide> throw ({}); // eslint-disable-line no-throw-literal
<ide> },
<ide> Array
<ide> assert.throws(() => {
<ide> a.throws(makeBlock(thrower, TypeError), /\[object Object\]/);
<ide>
<ide> // use a fn to validate error object
<del>a.throws(makeBlock(thrower, TypeError), function(err) {
<add>a.throws(makeBlock(thrower, TypeError), (err) => {
<ide> if ((err instanceof TypeError) && /\[object Object\]/.test(err)) {
<ide> return true;
<ide> }
<ide> testAssertionMessage({ a: NaN, b: Infinity, c: -Infinity },
<ide> let threw = false;
<ide> try {
<ide> // eslint-disable-next-line no-restricted-syntax
<del> assert.throws(function() {
<add> assert.throws(() => {
<ide> assert.ifError(null);
<ide> });
<ide> } catch (e) {
<ide><path>test/parallel/test-domain-top-level-error-handler-clears-stack.js
<ide> const domain = require('domain');
<ide> */
<ide> const d = domain.create();
<ide>
<del>d.on('error', common.mustCall(function() {
<del> process.nextTick(function() {
<add>d.on('error', common.mustCall(() => {
<add> process.nextTick(() => {
<ide> // Scheduling a callback with process.nextTick will enter a _new_ domain,
<ide> // and the callback will be called after the domain that handled the error
<ide> // was exited. So there should be only one domain on the domains stack if
<ide> d.on('error', common.mustCall(function() {
<ide> });
<ide> }));
<ide>
<del>d.run(function() {
<add>d.run(() => {
<ide> throw new Error('Error from domain');
<ide> });
<ide><path>test/parallel/test-querystring.js
<ide> const qsWeirdObjects = [
<ide> [{ regexp: /./g }, 'regexp=', { 'regexp': '' }],
<ide> // eslint-disable-next-line no-unescaped-regexp-dot
<ide> [{ regexp: new RegExp('.', 'g') }, 'regexp=', { 'regexp': '' }],
<del> [{ fn: function() {} }, 'fn=', { 'fn': '' }],
<add> [{ fn: () => {} }, 'fn=', { 'fn': '' }],
<ide> [{ fn: new Function('') }, 'fn=', { 'fn': '' }],
<ide> [{ math: Math }, 'math=', { 'math': '' }],
<ide> [{ e: extendedFunction }, 'e=', { 'e': '' }],
<ide> function check(actual, expected, input) {
<ide> `Expected keys: ${inspect(expectedKeys)}`;
<ide> }
<ide> assert.deepStrictEqual(actualKeys, expectedKeys, msg);
<del> expectedKeys.forEach(function(key) {
<add> expectedKeys.forEach((key) => {
<ide> if (typeof input === 'string') {
<ide> msg = `Input: ${inspect(input)}\n` +
<ide> `Key: ${inspect(key)}\n` +
<ide> function check(actual, expected, input) {
<ide> }
<ide>
<ide> // test that the canonical qs is parsed properly.
<del>qsTestCases.forEach(function(testCase) {
<add>qsTestCases.forEach((testCase) => {
<ide> check(qs.parse(testCase[0]), testCase[2], testCase[0]);
<ide> });
<ide>
<ide> // test that the colon test cases can do the same
<del>qsColonTestCases.forEach(function(testCase) {
<add>qsColonTestCases.forEach((testCase) => {
<ide> check(qs.parse(testCase[0], ';', ':'), testCase[2], testCase[0]);
<ide> });
<ide>
<ide> // test the weird objects, that they get parsed properly
<del>qsWeirdObjects.forEach(function(testCase) {
<add>qsWeirdObjects.forEach((testCase) => {
<ide> check(qs.parse(testCase[1]), testCase[2], testCase[1]);
<ide> });
<ide>
<del>qsNoMungeTestCases.forEach(function(testCase) {
<add>qsNoMungeTestCases.forEach((testCase) => {
<ide> assert.deepStrictEqual(testCase[0], qs.stringify(testCase[1], '&', '='));
<ide> });
<ide>
<ide> qsNoMungeTestCases.forEach(function(testCase) {
<ide> // now test stringifying
<ide>
<ide> // basic
<del>qsTestCases.forEach(function(testCase) {
<add>qsTestCases.forEach((testCase) => {
<ide> assert.strictEqual(testCase[1], qs.stringify(testCase[2]));
<ide> });
<ide>
<del>qsColonTestCases.forEach(function(testCase) {
<add>qsColonTestCases.forEach((testCase) => {
<ide> assert.strictEqual(testCase[1], qs.stringify(testCase[2], ';', ':'));
<ide> });
<ide>
<del>qsWeirdObjects.forEach(function(testCase) {
<add>qsWeirdObjects.forEach((testCase) => {
<ide> assert.strictEqual(testCase[1], qs.stringify(testCase[0]));
<ide> });
<ide>
<ide> assert.strictEqual('foo=', qs.stringify({ foo: Infinity }));
<ide> assert.strictEqual(f, 'a=b&q=x%3Dy%26y%3Dz');
<ide> }
<ide>
<del>assert.doesNotThrow(function() {
<add>assert.doesNotThrow(() => {
<ide> qs.parse(undefined);
<ide> });
<ide>
<ide> check(qs.parse('%\u0100=%\u0101'), { '%Ā': '%ā' });
<ide> }
<ide>
<ide> // Test QueryString.unescapeBuffer
<del>qsUnescapeTestCases.forEach(function(testCase) {
<add>qsUnescapeTestCases.forEach((testCase) => {
<ide> assert.strictEqual(qs.unescape(testCase[0]), testCase[1]);
<ide> assert.strictEqual(qs.unescapeBuffer(testCase[0]).toString(), testCase[1]);
<ide> });
<ide>
<ide> // test overriding .unescape
<ide> {
<ide> const prevUnescape = qs.unescape;
<del> qs.unescape = function(str) {
<add> qs.unescape = (str) => {
<ide> return str.replace(/o/g, '_');
<ide> };
<ide> check(
<ide><path>test/parallel/test-writeint.js
<ide> function test8(clazz) {
<ide> assert.strictEqual(0xfb, buffer[1]);
<ide>
<ide> /* Make sure we handle truncation correctly */
<del> assert.throws(function() {
<add> assert.throws(() => {
<ide> buffer.writeInt8(0xabc, 0);
<ide> }, errorOutOfBounds);
<del> assert.throws(function() {
<add> assert.throws(() => {
<ide> buffer.writeInt8(0xabc, 0);
<ide> }, errorOutOfBounds);
<ide>
<ide> function test8(clazz) {
<ide>
<ide> assert.strictEqual(0x7f, buffer[0]);
<ide> assert.strictEqual(0x80, buffer[1]);
<del> assert.throws(function() {
<add> assert.throws(() => {
<ide> buffer.writeInt8(0x7f + 1, 0);
<ide> }, errorOutOfBounds);
<del> assert.throws(function() {
<add> assert.throws(() => {
<ide> buffer.writeInt8(-0x80 - 1, 0);
<ide> }, errorOutOfBounds);
<ide> }
<ide> function test16(clazz) {
<ide> assert.strictEqual(0xff, buffer[1]);
<ide> assert.strictEqual(0x80, buffer[2]);
<ide> assert.strictEqual(0x00, buffer[3]);
<del> assert.throws(function() {
<add> assert.throws(() => {
<ide> buffer.writeInt16BE(0x7fff + 1, 0);
<ide> }, errorOutOfBounds);
<del> assert.throws(function() {
<add> assert.throws(() => {
<ide> buffer.writeInt16BE(-0x8000 - 1, 0);
<ide> }, errorOutOfBounds);
<ide>
<ide> function test16(clazz) {
<ide> assert.strictEqual(0x7f, buffer[1]);
<ide> assert.strictEqual(0x00, buffer[2]);
<ide> assert.strictEqual(0x80, buffer[3]);
<del> assert.throws(function() {
<add> assert.throws(() => {
<ide> buffer.writeInt16LE(0x7fff + 1, 0);
<ide> }, errorOutOfBounds);
<del> assert.throws(function() {
<add> assert.throws(() => {
<ide> buffer.writeInt16LE(-0x8000 - 1, 0);
<ide> }, errorOutOfBounds);
<ide> }
<ide> function test32(clazz) {
<ide> assert.strictEqual(0x00, buffer[5]);
<ide> assert.strictEqual(0x00, buffer[6]);
<ide> assert.strictEqual(0x00, buffer[7]);
<del> assert.throws(function() {
<add> assert.throws(() => {
<ide> buffer.writeInt32BE(0x7fffffff + 1, 0);
<ide> }, errorOutOfBounds);
<del> assert.throws(function() {
<add> assert.throws(() => {
<ide> buffer.writeInt32BE(-0x80000000 - 1, 0);
<ide> }, errorOutOfBounds);
<ide>
<ide> function test32(clazz) {
<ide> assert.strictEqual(0x00, buffer[5]);
<ide> assert.strictEqual(0x00, buffer[6]);
<ide> assert.strictEqual(0x80, buffer[7]);
<del> assert.throws(function() {
<add> assert.throws(() => {
<ide> buffer.writeInt32LE(0x7fffffff + 1, 0);
<ide> }, errorOutOfBounds);
<del> assert.throws(function() {
<add> assert.throws(() => {
<ide> buffer.writeInt32LE(-0x80000000 - 1, 0);
<ide> }, errorOutOfBounds);
<ide> }
<ide><path>test/parallel/test-zerolengthbufferbug.js
<ide> const common = require('../common');
<ide> const http = require('http');
<ide>
<del>const server = http.createServer(function(req, res) {
<add>const server = http.createServer((req, res) => {
<ide> const buffer = Buffer.alloc(0);
<ide> // FIXME: WTF gjslint want this?
<ide> res.writeHead(200, { 'Content-Type': 'text/html',
<ide> 'Content-Length': buffer.length });
<ide> res.end(buffer);
<ide> });
<ide>
<del>server.listen(0, common.mustCall(function() {
<del> http.get({ port: this.address().port }, common.mustCall(function(res) {
<add>server.listen(0, common.mustCall(() => {
<add> http.get({ port: server.address().port }, common.mustCall((res) => {
<ide>
<ide> res.on('data', common.mustNotCall());
<ide>
<del> res.on('end', function(d) {
<add> res.on('end', (d) => {
<ide> server.close();
<ide> });
<ide> })); | 5 |
Mixed | Python | adjust kb_id visualizer templating and docs | 6bb0324b8181b91832d19de8c00f530c26a8c16e | <ide><path>spacy/displacy/render.py
<ide>
<ide> from .templates import TPL_DEP_SVG, TPL_DEP_WORDS, TPL_DEP_WORDS_LEMMA, TPL_DEP_ARCS
<ide> from .templates import TPL_ENT, TPL_ENT_RTL, TPL_FIGURE, TPL_TITLE, TPL_PAGE
<del>from .templates import TPL_ENTS
<add>from .templates import TPL_ENTS, TPL_KB_LINK
<ide> from ..util import minify_html, escape_html, registry
<ide> from ..errors import Errors
<ide>
<ide> def render_ents(
<ide> start = span["start"]
<ide> end = span["end"]
<ide> kb_id = span.get("kb_id", "")
<del> kb_url = span.get("kb_url", "")
<del> if kb_id:
<del> kb_link = """<a style="text-decoration: none; color: black; font-weight: bold" href="{}">{}</a>""".format(kb_url, kb_id)
<del> else:
<del> kb_link = ""
<add> kb_url = span.get("kb_url", "#")
<add> kb_link = TPL_KB_LINK.format(kb_id=kb_id, kb_url=kb_url) if kb_id else ""
<ide> additional_params = span.get("params", {})
<ide> entity = escape_html(text[start:end])
<ide> fragments = text[offset:start].split("\n")
<ide> def render_ents(
<ide> markup += "</br>"
<ide> if self.ents is None or label.upper() in self.ents:
<ide> color = self.colors.get(label.upper(), self.default_color)
<del> ent_settings = {"label": label, "text": entity, "bg": color, "kb_link": kb_link}
<add> ent_settings = {
<add> "label": label,
<add> "text": entity,
<add> "bg": color,
<add> "kb_link": kb_link,
<add> }
<ide> ent_settings.update(additional_params)
<ide> markup += self.ent_template.format(**ent_settings)
<ide> else:
<ide><path>spacy/displacy/templates.py
<ide> TPL_ENT = """
<ide> <mark class="entity" style="background: {bg}; padding: 0.45em 0.6em; margin: 0 0.25em; line-height: 1; border-radius: 0.35em;">
<ide> {text}
<del> <span style="font-size: 0.8em; font-weight: bold; line-height: 1; border-radius: 0.35em; vertical-align: middle; margin-left: 0.5rem">{label}
<del> {kb_link}
<del> </span>
<add> <span style="font-size: 0.8em; font-weight: bold; line-height: 1; border-radius: 0.35em; vertical-align: middle; margin-left: 0.5rem">{label}{kb_link}</span>
<ide> </mark>
<ide> """
<ide>
<ide> TPL_ENT_RTL = """
<ide> <mark class="entity" style="background: {bg}; padding: 0.45em 0.6em; margin: 0 0.25em; line-height: 1; border-radius: 0.35em">
<ide> {text}
<del> <span style="font-size: 0.8em; font-weight: bold; line-height: 1; border-radius: 0.35em; vertical-align: middle; margin-right: 0.5rem">{label}</span>
<add> <span style="font-size: 0.8em; font-weight: bold; line-height: 1; border-radius: 0.35em; vertical-align: middle; margin-right: 0.5rem">{label}{kb_link}</span>
<ide> </mark>
<ide> """
<ide>
<add># Important: this needs to start with a space!
<add>TPL_KB_LINK = """
<add> <a style="text-decoration: none; color: inherit; font-weight: normal" href="{kb_url}">{kb_id}</a>
<add>"""
<add>
<ide>
<ide> TPL_PAGE = """
<ide> <!DOCTYPE html>
<ide><path>website/docs/usage/visualizers.md
<ide> position.
<ide> >
<ide> > ```python
<ide> > ex = [{"text": "But Google is starting from behind.",
<del>> "ents": [{"start": 4, "end": 10, "label": "ORG", "kb_id": "Q95", "kb_url": "https://www.wikidata.org/entity/Q95"}],
<add>> "ents": [{"start": 4, "end": 10, "label": "ORG"}],
<ide> > "title": None}]
<ide> > html = displacy.render(ex, style="ent", manual=True)
<ide> > ```
<ide> position.
<ide>
<ide> ```python
<ide> ### ENT input
<add>{
<add> "text": "But Google is starting from behind.",
<add> "ents": [{"start": 4, "end": 10, "label": "ORG"}],
<add> "title": None
<add>}
<add>```
<add>
<add>```python
<add>### ENT input with knowledge base links
<ide> {
<ide> "text": "But Google is starting from behind.",
<ide> "ents": [{"start": 4, "end": 10, "label": "ORG", "kb_id": "Q95", "kb_url": "https://www.wikidata.org/entity/Q95"}], | 3 |
Text | Text | add font family details | 8a2927ff9911bb833176e3f732a90a107b3954a6 | <ide><path>guide/english/certifications/responsive-web-design/basic-css/set-the-font-family-of-an-element/index.md
<ide> title: Set the Font Family of an Element
<ide> ---
<ide> ## Set the Font Family of an Element
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/responsive-web-design/basic-css/set-the-font-family-of-an-element/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>In CSS, you can define the type of font used as part of a Font Family. It's recommended to include a set of font types, mostly used for fallback mechanism such that when one Font is not available, the system will fallback to render text using the next available font, and so on.
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>As a rule of thumb, start by providing font family of your choice and end with commonly available fonts such that if the browser is not able to render text using user specified font, then it will use the generic font type as last resort.
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>A few things to keep in mind:
<add>* It is recommended to include more than one font family (mostly for fallback purposes)
<add>* If the name of the font family is more than one word, it must be in quotation marks, like: "Times New Roman"
<add>
<add>```css
<add>p {
<add> font-family: "Times New Roman", Helvetica, serif;
<add>}
<add>```
<add>
<add>This will advise the browser to render text using ```Times New Roman``` first (if available), and then ```Helvetica``` (if Times New Roman isn't available), and finally ```serif``` if none of the other fonts are available. | 1 |
Text | Text | add note clarifying pnpm args handling | 760750d8516c5627bb0bd5c2f1618552dbd0388e | <ide><path>docs/getting-started.md
<ide> If you want to start with a TypeScript project you can use the `--typescript` fl
<ide> npx create-next-app@latest --typescript
<ide> # or
<ide> yarn create next-app --typescript
<del># or
<add># or (the extra '--' is expected and tells pnpm to pass the args down)
<ide> pnpm create next-app -- --typescript
<ide> ```
<ide> | 1 |
Ruby | Ruby | clarify gnu url warning message | 21314474cdfa99e85b291bfc7480b3e253774fc8 | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_urls
<ide>
<ide> # Check GNU urls; doesn't apply to mirrors
<ide> urls.grep(%r[^(?:https?|ftp)://(?!alpha).+/gnu/]) do |u|
<del> problem "\"ftpmirror.gnu.org\" is preferred for GNU software (url is #{u})."
<add> problem "\"http://ftpmirror.gnu.org\" is preferred for GNU software (url is #{u})."
<ide> end
<ide>
<ide> # the rest of the checks apply to mirrors as well. | 1 |
Javascript | Javascript | add `eventtarget` support | a600408b284e92ed3d801d7f4e37d10b5da06b10 | <ide><path>packages/legacy-events/EventPluginUtils.js
<ide> if (__DEV__) {
<ide> */
<ide> export function executeDispatch(event, listener, inst) {
<ide> const type = event.type || 'unknown-event';
<del> event.currentTarget = getNodeFromInstance(inst);
<add> event.currentTarget =
<add> inst.tag !== undefined ? getNodeFromInstance(inst) : inst;
<ide> invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
<ide> event.currentTarget = null;
<ide> }
<ide><path>packages/legacy-events/EventSystemFlags.js
<ide> export const IS_ACTIVE = 1 << 3;
<ide> export const PASSIVE_NOT_SUPPORTED = 1 << 4;
<ide> export const IS_REPLAYED = 1 << 5;
<ide> export const IS_FIRST_ANCESTOR = 1 << 6;
<del>export const LEGACY_FB_SUPPORT = 1 << 7;
<add>export const IS_TARGET_EVENT_ONLY = 1 << 7;
<add>export const LEGACY_FB_SUPPORT = 1 << 8;
<ide><path>packages/legacy-events/ReactSyntheticEventType.js
<ide> export type ReactSyntheticEvent = {|
<ide> nativeEventTarget: EventTarget,
<ide> ) => ReactSyntheticEvent,
<ide> isPersistent: () => boolean,
<del> _dispatchInstances: null | Array<Fiber> | Fiber,
<add> _dispatchInstances: null | Array<Fiber | EventTarget> | Fiber | EventTarget,
<ide> _dispatchListeners: null | Array<Function> | Function,
<ide> _targetInst: Fiber,
<ide> type: string,
<ide><path>packages/react-dom/src/client/ReactDOMHostConfig.js
<ide> import {
<ide> IS_PASSIVE,
<ide> } from 'legacy-events/EventSystemFlags';
<ide> import {
<del> attachElementListener,
<del> detachElementListener,
<del> isDOMDocument,
<del> isDOMElement,
<add> isManagedDOMElement,
<add> isValidEventTarget,
<ide> listenToTopLevelEvent,
<add> detachListenerFromManagedDOMElement,
<add> attachListenerFromManagedDOMElement,
<add> detachTargetEventListener,
<add> attachTargetEventListener,
<ide> } from '../events/DOMModernPluginEventSystem';
<ide> import {getListenerMapForElement} from '../events/DOMEventListenerMap';
<ide>
<ide> export function registerEvent(
<ide> export function mountEventListener(listener: ReactDOMListener): void {
<ide> if (enableUseEventAPI) {
<ide> const {target} = listener;
<del> if (target === window) {
<del> // TODO (useEvent)
<del> } else if (isDOMDocument(target)) {
<del> // TODO (useEvent)
<del> } else if (isDOMElement(target)) {
<del> attachElementListener(listener);
<add> if (isManagedDOMElement(target)) {
<add> attachListenerFromManagedDOMElement(listener);
<add> } else {
<add> attachTargetEventListener(listener);
<ide> }
<ide> }
<ide> }
<ide>
<ide> export function unmountEventListener(listener: ReactDOMListener): void {
<ide> if (enableUseEventAPI) {
<ide> const {target} = listener;
<del> if (target === window) {
<del> // TODO (useEvent)
<del> } else if (isDOMDocument(target)) {
<del> // TODO (useEvent)
<del> } else if (isDOMElement(target)) {
<del> detachElementListener(listener);
<add> if (isManagedDOMElement(target)) {
<add> detachListenerFromManagedDOMElement(listener);
<add> } else {
<add> detachTargetEventListener(listener);
<ide> }
<ide> }
<ide> }
<ide> export function validateEventListenerTarget(
<ide> if (enableUseEventAPI) {
<ide> if (
<ide> target != null &&
<del> (target === window ||
<del> isDOMDocument(target) ||
<del> (isDOMElement(target) &&
<del> getClosestInstanceFromNode(((target: any): Element))))
<add> (isManagedDOMElement(target) || isValidEventTarget(target))
<ide> ) {
<ide> if (listener == null || typeof listener === 'function') {
<ide> return true;
<ide> export function validateEventListenerTarget(
<ide> }
<ide> if (__DEV__) {
<ide> console.warn(
<del> 'Event listener method setListener() from useEvent() hook requires the first argument to be either:' +
<del> '\n\n' +
<del> '1. A valid DOM node that was rendered and managed by React\n' +
<del> '2. The "window" object\n' +
<del> '3. The "document" object',
<add> 'Event listener method setListener() from useEvent() hook requires the first argument to be ' +
<add> 'a valid DOM EventTarget. If using a ref, ensure the current value is not null.',
<ide> );
<ide> }
<ide> }
<ide><path>packages/react-dom/src/events/DOMEventListenerMap.js
<ide> import type {DOMTopLevelEventType} from 'legacy-events/TopLevelEventTypes';
<ide> import {registrationNameDependencies} from 'legacy-events/EventPluginRegistry';
<ide>
<ide> const PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
<del>// prettier-ignore
<del>const elementListenerMap:
<del> // $FlowFixMe Work around Flow bug
<del> | WeakMap
<del> | Map<EventTarget, ElementListenerMap> = new PossiblyWeakMap();
<add>// $FlowFixMe: Flow cannot handle polymorphic WeakMaps
<add>const elementListenerMap: WeakMap<
<add> EventTarget,
<add> ElementListenerMap,
<add>> = new PossiblyWeakMap();
<ide>
<ide> export type ElementListenerMap = Map<
<ide> DOMTopLevelEventType | string,
<ide><path>packages/react-dom/src/events/DOMModernPluginEventSystem.js
<ide> import {registrationNameDependencies} from 'legacy-events/EventPluginRegistry';
<ide> import {batchedEventUpdates} from 'legacy-events/ReactGenericBatching';
<ide> import {executeDispatchesInOrder} from 'legacy-events/EventPluginUtils';
<ide> import {plugins} from 'legacy-events/EventPluginRegistry';
<del>import {LEGACY_FB_SUPPORT, IS_REPLAYED} from 'legacy-events/EventSystemFlags';
<add>import {
<add> LEGACY_FB_SUPPORT,
<add> IS_REPLAYED,
<add> IS_TARGET_EVENT_ONLY,
<add>} from 'legacy-events/EventSystemFlags';
<ide>
<ide> import {HostRoot, HostPortal} from 'shared/ReactWorkTags';
<ide>
<ide> import {
<ide> getListenersFromTarget,
<ide> initListenersSet,
<ide> } from '../client/ReactDOMComponentTree';
<del>import {
<del> DOCUMENT_NODE,
<del> COMMENT_NODE,
<del> ELEMENT_NODE,
<del>} from '../shared/HTMLNodeType';
<add>import {COMMENT_NODE} from '../shared/HTMLNodeType';
<ide> import {topLevelEventsToDispatchConfig} from './DOMEventProperties';
<ide>
<ide> import {enableLegacyFBSupport} from 'shared/ReactFeatureFlags';
<ide> const emptyDispatchConfigForCustomEvents: CustomDispatchConfig = {
<ide>
<ide> const isArray = Array.isArray;
<ide>
<add>// $FlowFixMe: Flow struggles with this pattern
<add>const PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
<add>// $FlowFixMe: Flow cannot handle polymorphic WeakMaps
<add>export const eventTargetEventListenerStore: WeakMap<
<add> EventTarget,
<add> Map<
<add> DOMTopLevelEventType,
<add> {bubbled: Set<ReactDOMListener>, captured: Set<ReactDOMListener>},
<add> >,
<add>> = new PossiblyWeakMap();
<add>
<ide> function dispatchEventsForPlugins(
<ide> topLevelType: DOMTopLevelEventType,
<ide> eventSystemFlags: EventSystemFlags,
<ide> export function listenToTopLevelEvent(
<ide> listenerMap: ElementListenerMap,
<ide> passive?: boolean,
<ide> priority?: EventPriority,
<add> capture?: boolean,
<ide> ): void {
<del> const listenerEntry = listenerMap.get(topLevelType);
<add> // If we explicitly define capture, then these are for EventTarget objects,
<add> // rather than React managed DOM elements. So we need to ensure we separate
<add> // capture and non-capture events. For React managed DOM nodes we only use
<add> // one or the other, never both. Which one we use is determined by the the
<add> // capturePhaseEvents Set (in this module) that defines if the event listener
<add> // should use the capture phase – otherwise we always use the bubble phase.
<add> // Finally, when we get to dispatching and accumulating event listeners, we
<add> // check if the user wanted capture/bubble and emulate the behavior at that
<add> // point (we call this accumulating two phase listeners).
<add> const typeStr = ((topLevelType: any): string);
<add> const listenerMapKey =
<add> capture === undefined
<add> ? topLevelType
<add> : `${typeStr}_${capture ? 'capture' : 'bubble'}`;
<add> const listenerEntry = listenerMap.get(listenerMapKey);
<ide> const shouldUpgrade = shouldUpgradeListener(listenerEntry, passive);
<ide> if (listenerEntry === undefined || shouldUpgrade) {
<del> const isCapturePhase = capturePhaseEvents.has(topLevelType);
<add> const isCapturePhase =
<add> capture === undefined ? capturePhaseEvents.has(topLevelType) : capture;
<ide> // If we should upgrade, then we need to remove the existing trapped
<ide> // event listener for the target container.
<ide> if (shouldUpgrade) {
<ide> export function listenToTopLevelEvent(
<ide> passive,
<ide> priority,
<ide> );
<del> listenerMap.set(topLevelType, {passive, listener});
<add> listenerMap.set(listenerMapKey, {passive, listener});
<ide> }
<ide> }
<ide>
<ide> function isMatchingRootContainer(
<ide> );
<ide> }
<ide>
<del>export function isDOMElement(target: EventTarget): boolean {
<del> const nodeType = ((target: any): Node).nodeType;
<del> return (nodeType: any) && nodeType === ELEMENT_NODE;
<add>export function isManagedDOMElement(target: EventTarget): boolean {
<add> return getClosestInstanceFromNode(((target: any): Node)) !== null;
<ide> }
<ide>
<del>export function isDOMDocument(target: EventTarget): boolean {
<del> const nodeType = ((target: any): Node).nodeType;
<del> return nodeType === DOCUMENT_NODE;
<add>export function isValidEventTarget(target: EventTarget): boolean {
<add> return typeof target.addEventListener === 'function';
<ide> }
<ide>
<ide> export function dispatchEventForPluginEventSystem(
<ide> export function dispatchEventForPluginEventSystem(
<ide> ): void {
<ide> let ancestorInst = targetInst;
<ide> if (targetContainer !== null) {
<del> const possibleTargetContainerNode = ((targetContainer: any): Node);
<del> // Given the rootContainer can be any EventTarget, if the
<del> // target is not a valid DOM element then we'll skip this part.
<del> if (
<del> possibleTargetContainerNode === window ||
<del> !isDOMElement(possibleTargetContainerNode)
<del> ) {
<del> // TODO: useEvent for document and window
<del> return;
<del> }
<del> // If we are using the legacy FB support flag, we
<del> // defer the event to the null with a one
<del> // time event listener so we can defer the event.
<del> if (
<del> enableLegacyFBSupport &&
<del> // We do not want to defer if the event system has already been
<del> // set to LEGACY_FB_SUPPORT. LEGACY_FB_SUPPORT only gets set when
<del> // we call willDeferLaterForLegacyFBSupport, thus not bailing out
<del> // will result in endless cycles like an infinite loop.
<del> (eventSystemFlags & LEGACY_FB_SUPPORT) === 0 &&
<del> // We also don't want to defer during event replaying.
<del> (eventSystemFlags & IS_REPLAYED) === 0 &&
<del> willDeferLaterForLegacyFBSupport(topLevelType, targetContainer)
<del> ) {
<del> return;
<del> }
<del> if (targetInst !== null) {
<del> // The below logic attempts to work out if we need to change
<del> // the target fiber to a different ancestor. We had similar logic
<del> // in the legacy event system, except the big difference between
<del> // systems is that the modern event system now has an event listener
<del> // attached to each React Root and React Portal Root. Together,
<del> // the DOM nodes representing these roots are the "rootContainer".
<del> // To figure out which ancestor instance we should use, we traverse
<del> // up the fiber tree from the target instance and attempt to find
<del> // root boundaries that match that of our current "rootContainer".
<del> // If we find that "rootContainer", we find the parent fiber
<del> // sub-tree for that root and make that our ancestor instance.
<del> let node = targetInst;
<add> if (eventTargetEventListenerStore.has(targetContainer)) {
<add> // For TargetEvent nodes (i.e. document, window)
<add> ancestorInst = null;
<add> eventSystemFlags |= IS_TARGET_EVENT_ONLY;
<add> } else {
<add> const targetContainerNode = ((targetContainer: any): Node);
<ide>
<del> while (true) {
<del> if (node === null) {
<del> return;
<del> }
<del> if (node.tag === HostRoot || node.tag === HostPortal) {
<del> const container = node.stateNode.containerInfo;
<del> if (isMatchingRootContainer(container, possibleTargetContainerNode)) {
<del> break;
<add> // If we are using the legacy FB support flag, we
<add> // defer the event to the null with a one
<add> // time event listener so we can defer the event.
<add> if (
<add> enableLegacyFBSupport &&
<add> // We do not want to defer if the event system has already been
<add> // set to LEGACY_FB_SUPPORT. LEGACY_FB_SUPPORT only gets set when
<add> // we call willDeferLaterForLegacyFBSupport, thus not bailing out
<add> // will result in endless cycles like an infinite loop.
<add> (eventSystemFlags & LEGACY_FB_SUPPORT) === 0 &&
<add> // We also don't want to defer during event replaying.
<add> (eventSystemFlags & IS_REPLAYED) === 0 &&
<add> willDeferLaterForLegacyFBSupport(topLevelType, targetContainer)
<add> ) {
<add> return;
<add> }
<add> if (targetInst !== null) {
<add> // The below logic attempts to work out if we need to change
<add> // the target fiber to a different ancestor. We had similar logic
<add> // in the legacy event system, except the big difference between
<add> // systems is that the modern event system now has an event listener
<add> // attached to each React Root and React Portal Root. Together,
<add> // the DOM nodes representing these roots are the "rootContainer".
<add> // To figure out which ancestor instance we should use, we traverse
<add> // up the fiber tree from the target instance and attempt to find
<add> // root boundaries that match that of our current "rootContainer".
<add> // If we find that "rootContainer", we find the parent fiber
<add> // sub-tree for that root and make that our ancestor instance.
<add> let node = targetInst;
<add>
<add> while (true) {
<add> if (node === null) {
<add> return;
<ide> }
<del> if (node.tag === HostPortal) {
<del> // The target is a portal, but it's not the rootContainer we're looking for.
<del> // Normally portals handle their own events all the way down to the root.
<del> // So we should be able to stop now. However, we don't know if this portal
<del> // was part of *our* root.
<del> let grandNode = node.return;
<del> while (grandNode !== null) {
<del> if (grandNode.tag === HostRoot || grandNode.tag === HostPortal) {
<del> const grandContainer = grandNode.stateNode.containerInfo;
<add> if (node.tag === HostRoot || node.tag === HostPortal) {
<add> const container = node.stateNode.containerInfo;
<add> if (isMatchingRootContainer(container, targetContainerNode)) {
<add> break;
<add> }
<add> if (node.tag === HostPortal) {
<add> // The target is a portal, but it's not the rootContainer we're looking for.
<add> // Normally portals handle their own events all the way down to the root.
<add> // So we should be able to stop now. However, we don't know if this portal
<add> // was part of *our* root.
<add> let grandNode = node.return;
<add> while (grandNode !== null) {
<ide> if (
<del> isMatchingRootContainer(
<del> grandContainer,
<del> possibleTargetContainerNode,
<del> )
<add> grandNode.tag === HostRoot ||
<add> grandNode.tag === HostPortal
<ide> ) {
<del> // This is the rootContainer we're looking for and we found it as
<del> // a parent of the Portal. That means we can ignore it because the
<del> // Portal will bubble through to us.
<del> return;
<add> const grandContainer = grandNode.stateNode.containerInfo;
<add> if (
<add> isMatchingRootContainer(grandContainer, targetContainerNode)
<add> ) {
<add> // This is the rootContainer we're looking for and we found it as
<add> // a parent of the Portal. That means we can ignore it because the
<add> // Portal will bubble through to us.
<add> return;
<add> }
<ide> }
<add> grandNode = grandNode.return;
<ide> }
<del> grandNode = grandNode.return;
<ide> }
<add> const parentSubtreeInst = getClosestInstanceFromNode(container);
<add> if (parentSubtreeInst === null) {
<add> return;
<add> }
<add> node = ancestorInst = parentSubtreeInst;
<add> continue;
<ide> }
<del> const parentSubtreeInst = getClosestInstanceFromNode(container);
<del> if (parentSubtreeInst === null) {
<del> return;
<del> }
<del> node = ancestorInst = parentSubtreeInst;
<del> continue;
<add> node = node.return;
<ide> }
<del> node = node.return;
<ide> }
<ide> }
<ide> }
<ide> function getNearestRootOrPortalContainer(instance: Element): Element {
<ide> return instance;
<ide> }
<ide>
<del>export function attachElementListener(listener: ReactDOMListener): void {
<add>function addEventTypeToDispatchConfig(type: DOMTopLevelEventType): void {
<add> let dispatchConfig = topLevelEventsToDispatchConfig.get(type);
<add> // If we don't have a dispatchConfig, then we're dealing with
<add> // an event type that React does not know about (i.e. a custom event).
<add> // We need to register an event config for this or the SimpleEventPlugin
<add> // will not appropriately provide a SyntheticEvent, so we use out empty
<add> // dispatch config for custom events.
<add> if (dispatchConfig === undefined) {
<add> topLevelEventsToDispatchConfig.set(
<add> type,
<add> emptyDispatchConfigForCustomEvents,
<add> );
<add> }
<add>}
<add>
<add>export function attachListenerFromManagedDOMElement(
<add> listener: ReactDOMListener,
<add>): void {
<ide> const {event, target} = listener;
<ide> const {passive, priority, type} = event;
<add> const possibleManagedTarget = ((target: any): Element);
<ide> let containerEventTarget = target;
<del> // If we the target is a managed React element, then we need to
<del> // find the nearest root/portal contained to attach the event listener
<del> // to. If it's not managed, i.e. the window, then we just attach
<del> // the listener to the target.
<del> if (isDOMElement(target)) {
<del> const possibleManagedTarget = ((target: any): Element);
<del> if (getClosestInstanceFromNode(possibleManagedTarget)) {
<del> containerEventTarget = getNearestRootOrPortalContainer(
<del> possibleManagedTarget,
<del> );
<del> }
<add> if (getClosestInstanceFromNode(possibleManagedTarget)) {
<add> containerEventTarget = getNearestRootOrPortalContainer(
<add> possibleManagedTarget,
<add> );
<ide> }
<ide> const listenerMap = getListenerMapForElement(containerEventTarget);
<ide> // Add the event listener to the target container (falling back to
<ide> export function attachElementListener(listener: ReactDOMListener): void {
<ide> // Add our listener to the listeners Set.
<ide> listeners.add(listener);
<ide> // Finally, add the event to our known event types list.
<del> let dispatchConfig = topLevelEventsToDispatchConfig.get(type);
<del> // If we don't have a dispatchConfig, then we're dealing with
<del> // an event type that React does not know about (i.e. a custom event).
<del> // We need to register an event config for this or the SimpleEventPlugin
<del> // will not appropriately provide a SyntheticEvent, so we use out empty
<del> // dispatch config for custom events.
<del> if (dispatchConfig === undefined) {
<del> topLevelEventsToDispatchConfig.set(
<del> type,
<del> emptyDispatchConfigForCustomEvents,
<del> );
<del> }
<add> addEventTypeToDispatchConfig(type);
<ide> }
<ide>
<del>export function detachElementListener(listener: ReactDOMListener): void {
<add>export function detachListenerFromManagedDOMElement(
<add> listener: ReactDOMListener,
<add>): void {
<ide> const {target} = listener;
<ide> // Get the internal listeners Set from the target instance.
<ide> const listeners = getListenersFromTarget(target);
<ide> export function detachElementListener(listener: ReactDOMListener): void {
<ide> listeners.delete(listener);
<ide> }
<ide> }
<add>
<add>export function attachTargetEventListener(listener: ReactDOMListener): void {
<add> const {event, target} = listener;
<add> const {capture, passive, priority, type} = event;
<add> const listenerMap = getListenerMapForElement(target);
<add> // Add the event listener to the TargetEvent object.
<add> listenToTopLevelEvent(type, target, listenerMap, passive, priority, capture);
<add> let eventTypeMap = eventTargetEventListenerStore.get(target);
<add> if (eventTypeMap === undefined) {
<add> eventTypeMap = new Map();
<add> eventTargetEventListenerStore.set(target, eventTypeMap);
<add> }
<add> // Get the listeners by the event type
<add> let listeners = eventTypeMap.get(type);
<add> if (listeners === undefined) {
<add> listeners = {captured: new Set(), bubbled: new Set()};
<add> eventTypeMap.set(type, listeners);
<add> }
<add> // Add our listener to the listeners Set.
<add> if (capture) {
<add> listeners.captured.add(listener);
<add> } else {
<add> listeners.bubbled.add(listener);
<add> }
<add> // Finally, add the event to our known event types list.
<add> addEventTypeToDispatchConfig(type);
<add>}
<add>
<add>export function detachTargetEventListener(listener: ReactDOMListener): void {
<add> const {event, target} = listener;
<add> const {capture, type} = event;
<add> const eventTypeMap = eventTargetEventListenerStore.get(target);
<add> if (eventTypeMap !== undefined) {
<add> const listeners = eventTypeMap.get(type);
<add> if (listeners !== undefined) {
<add> // Remove out listener from the listeners Set.
<add> if (capture) {
<add> listeners.captured.delete(listener);
<add> } else {
<add> listeners.bubbled.delete(listener);
<add> }
<add> }
<add> }
<add>}
<ide><path>packages/react-dom/src/events/SimpleEventPlugin.js
<ide> const SimpleEventPlugin: PluginModule<MouseEvent> = {
<ide> nativeEvent: MouseEvent,
<ide> nativeEventTarget: null | EventTarget,
<ide> eventSystemFlags: EventSystemFlags,
<add> targetContainer?: null | EventTarget,
<ide> ): null | ReactSyntheticEvent {
<ide> const dispatchConfig = topLevelEventsToDispatchConfig.get(topLevelType);
<ide> if (!dispatchConfig) {
<ide> const SimpleEventPlugin: PluginModule<MouseEvent> = {
<ide> nativeEvent,
<ide> nativeEventTarget,
<ide> );
<del> accumulateTwoPhaseListeners(event, true);
<add> accumulateTwoPhaseListeners(event, true, eventSystemFlags, targetContainer);
<ide> return event;
<ide> },
<ide> };
<ide><path>packages/react-dom/src/events/__tests__/DOMModernPluginEventSystem-test.internal.js
<ide> function dispatchClickEvent(element) {
<ide> dispatchEvent(element, 'click');
<ide> }
<ide>
<add>let eventListenersToClear = [];
<add>
<add>function startNativeEventListenerClearDown() {
<add> const nativeWindowEventListener = window.addEventListener;
<add> window.addEventListener = function(...params) {
<add> eventListenersToClear.push({target: window, params});
<add> return nativeWindowEventListener.apply(this, params);
<add> };
<add> const nativeDocumentEventListener = document.addEventListener;
<add> document.addEventListener = function(...params) {
<add> eventListenersToClear.push({target: document, params});
<add> return nativeDocumentEventListener.apply(this, params);
<add> };
<add>}
<add>
<add>function endNativeEventListenerClearDown() {
<add> eventListenersToClear.forEach(({target, params}) => {
<add> target.removeEventListener(...params);
<add> });
<add>}
<add>
<ide> describe('DOMModernPluginEventSystem', () => {
<ide> let container;
<ide>
<ide> describe('DOMModernPluginEventSystem', () => {
<ide> ReactDOMServer = require('react-dom/server');
<ide> container = document.createElement('div');
<ide> document.body.appendChild(container);
<add> startNativeEventListenerClearDown();
<ide> });
<ide>
<ide> afterEach(() => {
<ide> document.body.removeChild(container);
<ide> container = null;
<add> endNativeEventListenerClearDown();
<ide> });
<ide>
<ide> it('handle propagation of click events', () => {
<ide> describe('DOMModernPluginEventSystem', () => {
<ide> expect(log[0]).toEqual(['capture', buttonElement]);
<ide> expect(log[1]).toEqual(['bubble', buttonElement]);
<ide>
<add> log.length = 0;
<add> onClick.mockClear();
<add> onClickCapture.mockClear();
<add>
<ide> let divElement = divRef.current;
<ide> dispatchClickEvent(divElement);
<del> expect(onClick).toHaveBeenCalledTimes(3);
<del> expect(onClickCapture).toHaveBeenCalledTimes(3);
<del> expect(log[2]).toEqual(['capture', buttonElement]);
<del> expect(log[3]).toEqual(['capture', divElement]);
<del> expect(log[4]).toEqual(['bubble', divElement]);
<del> expect(log[5]).toEqual(['bubble', buttonElement]);
<add> expect(onClick).toHaveBeenCalledTimes(2);
<add> expect(onClickCapture).toHaveBeenCalledTimes(2);
<add> expect(log[0]).toEqual(['capture', buttonElement]);
<add> expect(log[1]).toEqual(['capture', divElement]);
<add> expect(log[2]).toEqual(['bubble', divElement]);
<add> expect(log[3]).toEqual(['bubble', buttonElement]);
<ide> });
<ide>
<ide> it('handle propagation of click events mixed with onClick events', () => {
<ide> describe('DOMModernPluginEventSystem', () => {
<ide> expect(clickEvent).toHaveBeenCalledTimes(1);
<ide> });
<ide>
<add> it('should correctly work for a basic "click" window listener', () => {
<add> const log = [];
<add> const clickEvent = jest.fn(event => {
<add> log.push({
<add> eventPhase: event.eventPhase,
<add> type: event.type,
<add> currentTarget: event.currentTarget,
<add> target: event.target,
<add> });
<add> });
<add>
<add> function Test() {
<add> const click = ReactDOM.unstable_useEvent('click');
<add>
<add> React.useEffect(() => {
<add> click.setListener(window, clickEvent);
<add> });
<add>
<add> return <button>Click anything!</button>;
<add> }
<add> ReactDOM.render(<Test />, container);
<add> Scheduler.unstable_flushAll();
<add>
<add> expect(container.innerHTML).toBe(
<add> '<button>Click anything!</button>',
<add> );
<add>
<add> // Clicking outside the button should trigger the event callback
<add> dispatchClickEvent(document.body);
<add> expect(log[0]).toEqual({
<add> eventPhase: 3,
<add> type: 'click',
<add> currentTarget: window,
<add> target: document.body,
<add> });
<add>
<add> // Unmounting the container and clicking should not work
<add> ReactDOM.render(null, container);
<add> Scheduler.unstable_flushAll();
<add>
<add> dispatchClickEvent(document.body);
<add> expect(clickEvent).toBeCalledTimes(1);
<add>
<add> // Re-rendering and clicking the body should work again
<add> ReactDOM.render(<Test />, container);
<add> Scheduler.unstable_flushAll();
<add>
<add> dispatchClickEvent(document.body);
<add> expect(clickEvent).toBeCalledTimes(2);
<add> });
<add>
<add> it('handle propagation of click events on the window', () => {
<add> const buttonRef = React.createRef();
<add> const divRef = React.createRef();
<add> const log = [];
<add> const onClick = jest.fn(e => log.push(['bubble', e.currentTarget]));
<add> const onClickCapture = jest.fn(e =>
<add> log.push(['capture', e.currentTarget]),
<add> );
<add>
<add> function Test() {
<add> const click = ReactDOM.unstable_useEvent('click');
<add> const clickCapture = ReactDOM.unstable_useEvent('click', {
<add> capture: true,
<add> });
<add>
<add> React.useEffect(() => {
<add> click.setListener(window, onClick);
<add> clickCapture.setListener(window, onClickCapture);
<add> click.setListener(buttonRef.current, onClick);
<add> clickCapture.setListener(buttonRef.current, onClickCapture);
<add> click.setListener(divRef.current, onClick);
<add> clickCapture.setListener(divRef.current, onClickCapture);
<add> });
<add>
<add> return (
<add> <button ref={buttonRef}>
<add> <div ref={divRef}>Click me!</div>
<add> </button>
<add> );
<add> }
<add>
<add> ReactDOM.render(<Test />, container);
<add> Scheduler.unstable_flushAll();
<add>
<add> let buttonElement = buttonRef.current;
<add> dispatchClickEvent(buttonElement);
<add> expect(onClick).toHaveBeenCalledTimes(2);
<add> expect(onClickCapture).toHaveBeenCalledTimes(2);
<add> expect(log[0]).toEqual(['capture', window]);
<add> expect(log[1]).toEqual(['capture', buttonElement]);
<add> expect(log[2]).toEqual(['bubble', buttonElement]);
<add> expect(log[3]).toEqual(['bubble', window]);
<add>
<add> log.length = 0;
<add> onClick.mockClear();
<add> onClickCapture.mockClear();
<add>
<add> let divElement = divRef.current;
<add> dispatchClickEvent(divElement);
<add> expect(onClick).toHaveBeenCalledTimes(3);
<add> expect(onClickCapture).toHaveBeenCalledTimes(3);
<add> expect(log[0]).toEqual(['capture', window]);
<add> expect(log[1]).toEqual(['capture', buttonElement]);
<add> expect(log[2]).toEqual(['capture', divElement]);
<add> expect(log[3]).toEqual(['bubble', divElement]);
<add> expect(log[4]).toEqual(['bubble', buttonElement]);
<add> expect(log[5]).toEqual(['bubble', window]);
<add> });
<add>
<add> it('should correctly handle stopPropagation for mixed listeners', () => {
<add> const buttonRef = React.createRef();
<add> const rootListerner1 = jest.fn(e => e.stopPropagation());
<add> const rootListerner2 = jest.fn();
<add> const targetListerner1 = jest.fn();
<add> const targetListerner2 = jest.fn();
<add>
<add> function Test() {
<add> const click1 = ReactDOM.unstable_useEvent('click', {
<add> capture: true,
<add> });
<add> const click2 = ReactDOM.unstable_useEvent('click', {
<add> capture: true,
<add> });
<add> const click3 = ReactDOM.unstable_useEvent('click');
<add> const click4 = ReactDOM.unstable_useEvent('click');
<add>
<add> React.useEffect(() => {
<add> click1.setListener(window, rootListerner1);
<add> click2.setListener(buttonRef.current, targetListerner1);
<add> click3.setListener(window, rootListerner2);
<add> click4.setListener(buttonRef.current, targetListerner2);
<add> });
<add>
<add> return <button ref={buttonRef}>Click me!</button>;
<add> }
<add>
<add> ReactDOM.render(<Test />, container);
<add> Scheduler.unstable_flushAll();
<add>
<add> let buttonElement = buttonRef.current;
<add> dispatchClickEvent(buttonElement);
<add> expect(rootListerner1).toHaveBeenCalledTimes(1);
<add> expect(targetListerner1).toHaveBeenCalledTimes(0);
<add> expect(targetListerner2).toHaveBeenCalledTimes(0);
<add> expect(rootListerner2).toHaveBeenCalledTimes(0);
<add> });
<add>
<add> it('should correctly handle stopPropagation for delegated listeners', () => {
<add> const buttonRef = React.createRef();
<add> const rootListerner1 = jest.fn(e => e.stopPropagation());
<add> const rootListerner2 = jest.fn();
<add> const rootListerner3 = jest.fn(e => e.stopPropagation());
<add> const rootListerner4 = jest.fn();
<add>
<add> function Test() {
<add> const click1 = ReactDOM.unstable_useEvent('click', {
<add> capture: true,
<add> });
<add> const click2 = ReactDOM.unstable_useEvent('click', {
<add> capture: true,
<add> });
<add> const click3 = ReactDOM.unstable_useEvent('click');
<add> const click4 = ReactDOM.unstable_useEvent('click');
<add>
<add> React.useEffect(() => {
<add> click1.setListener(window, rootListerner1);
<add> click2.setListener(window, rootListerner2);
<add> click3.setListener(window, rootListerner3);
<add> click4.setListener(window, rootListerner4);
<add> });
<add>
<add> return <button ref={buttonRef}>Click me!</button>;
<add> }
<add>
<add> ReactDOM.render(<Test />, container);
<add>
<add> Scheduler.unstable_flushAll();
<add>
<add> let buttonElement = buttonRef.current;
<add> dispatchClickEvent(buttonElement);
<add> expect(rootListerner1).toHaveBeenCalledTimes(1);
<add> expect(rootListerner2).toHaveBeenCalledTimes(1);
<add> expect(rootListerner3).toHaveBeenCalledTimes(0);
<add> expect(rootListerner4).toHaveBeenCalledTimes(0);
<add> });
<add>
<add> it('handle propagation of click events on the window and document', () => {
<add> const buttonRef = React.createRef();
<add> const divRef = React.createRef();
<add> const log = [];
<add> const onClick = jest.fn(e => log.push(['bubble', e.currentTarget]));
<add> const onClickCapture = jest.fn(e =>
<add> log.push(['capture', e.currentTarget]),
<add> );
<add>
<add> function Test() {
<add> const click = ReactDOM.unstable_useEvent('click');
<add> const clickCapture = ReactDOM.unstable_useEvent('click', {
<add> capture: true,
<add> });
<add>
<add> React.useEffect(() => {
<add> click.setListener(window, onClick);
<add> clickCapture.setListener(window, onClickCapture);
<add> click.setListener(document, onClick);
<add> clickCapture.setListener(document, onClickCapture);
<add> click.setListener(buttonRef.current, onClick);
<add> clickCapture.setListener(buttonRef.current, onClickCapture);
<add> click.setListener(divRef.current, onClick);
<add> clickCapture.setListener(divRef.current, onClickCapture);
<add> });
<add>
<add> return (
<add> <button ref={buttonRef}>
<add> <div ref={divRef}>Click me!</div>
<add> </button>
<add> );
<add> }
<add>
<add> ReactDOM.render(<Test />, container);
<add> Scheduler.unstable_flushAll();
<add>
<add> let buttonElement = buttonRef.current;
<add> dispatchClickEvent(buttonElement);
<add> expect(onClick).toHaveBeenCalledTimes(3);
<add> expect(onClickCapture).toHaveBeenCalledTimes(3);
<add> expect(log[0]).toEqual(['capture', window]);
<add> expect(log[1]).toEqual(['capture', document]);
<add> expect(log[2]).toEqual(['capture', buttonElement]);
<add> expect(log[3]).toEqual(['bubble', buttonElement]);
<add> expect(log[4]).toEqual(['bubble', document]);
<add> expect(log[5]).toEqual(['bubble', window]);
<add>
<add> log.length = 0;
<add> onClick.mockClear();
<add> onClickCapture.mockClear();
<add>
<add> let divElement = divRef.current;
<add> dispatchClickEvent(divElement);
<add> expect(onClick).toHaveBeenCalledTimes(4);
<add> expect(onClickCapture).toHaveBeenCalledTimes(4);
<add> expect(log[0]).toEqual(['capture', window]);
<add> expect(log[1]).toEqual(['capture', document]);
<add> expect(log[2]).toEqual(['capture', buttonElement]);
<add> expect(log[3]).toEqual(['capture', divElement]);
<add> expect(log[4]).toEqual(['bubble', divElement]);
<add> expect(log[5]).toEqual(['bubble', buttonElement]);
<add> expect(log[6]).toEqual(['bubble', document]);
<add> expect(log[7]).toEqual(['bubble', window]);
<add> });
<add>
<ide> it('handles propagation of custom user events', () => {
<ide> const buttonRef = React.createRef();
<ide> const divRef = React.createRef();
<ide><path>packages/react-dom/src/events/accumulateTwoPhaseListeners.js
<ide> * @flow
<ide> */
<ide>
<add>import type {DOMTopLevelEventType} from 'legacy-events/TopLevelEventTypes';
<add>import type {EventSystemFlags} from 'legacy-events/EventSystemFlags';
<ide> import type {ReactSyntheticEvent} from 'legacy-events/ReactSyntheticEventType';
<ide>
<ide> import {HostComponent} from 'shared/ReactWorkTags';
<ide> import {enableUseEventAPI} from 'shared/ReactFeatureFlags';
<ide>
<ide> import getListener from 'legacy-events/getListener';
<ide> import {getListenersFromTarget} from '../client/ReactDOMComponentTree';
<add>import {IS_TARGET_EVENT_ONLY} from 'legacy-events/EventSystemFlags';
<add>import {eventTargetEventListenerStore} from './DOMModernPluginEventSystem';
<ide>
<ide> export default function accumulateTwoPhaseListeners(
<ide> event: ReactSyntheticEvent,
<ide> accumulateUseEventListeners?: boolean,
<add> eventSystemFlags?: EventSystemFlags,
<add> targetContainer?: null | EventTarget,
<ide> ): void {
<ide> const phasedRegistrationNames = event.dispatchConfig.phasedRegistrationNames;
<ide> const dispatchListeners = [];
<ide> const dispatchInstances = [];
<del> const {bubbled, captured} = phasedRegistrationNames;
<del> let node = event._targetInst;
<ide>
<del> // Accumulate all instances and listeners via the target -> root path.
<del> while (node !== null) {
<del> // We only care for listeners that are on HostComponents (i.e. <div>)
<del> if (node.tag === HostComponent) {
<del> // For useEvent listenrs
<del> if (enableUseEventAPI && accumulateUseEventListeners) {
<del> // useEvent event listeners
<del> const instance = node.stateNode;
<del> const targetType = event.type;
<del> const listeners = getListenersFromTarget(instance);
<add> // For TargetEvent only accumulation, we do not traverse through
<add> // the React tree looking for managed React DOM elements that have
<add> // events. Instead we only check the EventTarget Store Map to see
<add> // if the container has listeners for the particular phase we're
<add> // interested in. This is because we attach the native event listener
<add> // only in the given phase.
<add> if (
<add> enableUseEventAPI &&
<add> accumulateUseEventListeners &&
<add> eventSystemFlags !== undefined &&
<add> eventSystemFlags & IS_TARGET_EVENT_ONLY &&
<add> targetContainer != null
<add> ) {
<add> const eventTypeMap = eventTargetEventListenerStore.get(targetContainer);
<add> if (eventTypeMap !== undefined) {
<add> const type = ((event.type: any): DOMTopLevelEventType);
<add> const listeners = eventTypeMap.get(type);
<add> if (listeners !== undefined) {
<add> const isCapturePhase = (event: any).eventPhase === 1;
<ide>
<del> if (listeners !== null) {
<del> const listenersArr = Array.from(listeners);
<del> for (let i = 0; i < listenersArr.length; i++) {
<del> const listener = listenersArr[i];
<del> const {
<del> callback,
<del> event: {capture, type},
<del> } = listener;
<del> if (type === targetType) {
<del> if (capture === true) {
<del> dispatchListeners.unshift(callback);
<del> dispatchInstances.unshift(node);
<del> } else {
<del> dispatchListeners.push(callback);
<del> dispatchInstances.push(node);
<add> if (isCapturePhase) {
<add> const captureListeners = Array.from(listeners.captured);
<add>
<add> for (let i = captureListeners.length - 1; i >= 0; i--) {
<add> const listener = captureListeners[i];
<add> const {callback} = listener;
<add> dispatchListeners.push(callback);
<add> dispatchInstances.push(targetContainer);
<add> }
<add> } else {
<add> const bubbleListeners = Array.from(listeners.bubbled);
<add>
<add> for (let i = 0; i < bubbleListeners.length; i++) {
<add> const listener = bubbleListeners[i];
<add> const {callback} = listener;
<add> dispatchListeners.push(callback);
<add> dispatchInstances.push(targetContainer);
<add> }
<add> }
<add> }
<add> }
<add> } else {
<add> const {bubbled, captured} = phasedRegistrationNames;
<add> // If we are not handling EventTarget only phase, then we're doing the
<add> // usual two phase accumulation using the React fiber tree to pick up
<add> // all relevant useEvent and on* prop events.
<add> let node = event._targetInst;
<add>
<add> // Accumulate all instances and listeners via the target -> root path.
<add> while (node !== null) {
<add> // We only care for listeners that are on HostComponents (i.e. <div>)
<add> if (node.tag === HostComponent) {
<add> // For useEvent listenrs
<add> if (enableUseEventAPI && accumulateUseEventListeners) {
<add> // useEvent event listeners
<add> const instance = node.stateNode;
<add> const targetType = event.type;
<add> const listeners = getListenersFromTarget(instance);
<add>
<add> if (listeners !== null) {
<add> const listenersArr = Array.from(listeners);
<add> for (let i = 0; i < listenersArr.length; i++) {
<add> const listener = listenersArr[i];
<add> const {
<add> callback,
<add> event: {capture, type},
<add> } = listener;
<add> if (type === targetType) {
<add> if (capture === true) {
<add> dispatchListeners.unshift(callback);
<add> dispatchInstances.unshift(node);
<add> } else {
<add> dispatchListeners.push(callback);
<add> dispatchInstances.push(node);
<add> }
<ide> }
<ide> }
<ide> }
<ide> }
<del> }
<del> // Standard React on* listeners, i.e. onClick prop
<del> if (captured !== null) {
<del> const captureListener = getListener(node, captured);
<del> if (captureListener != null) {
<del> // Capture listeners/instances should go at the start, so we
<del> // unshift them to the start of the array.
<del> dispatchListeners.unshift(captureListener);
<del> dispatchInstances.unshift(node);
<add> // Standard React on* listeners, i.e. onClick prop
<add> if (captured !== null) {
<add> const captureListener = getListener(node, captured);
<add> if (captureListener != null) {
<add> // Capture listeners/instances should go at the start, so we
<add> // unshift them to the start of the array.
<add> dispatchListeners.unshift(captureListener);
<add> dispatchInstances.unshift(node);
<add> }
<ide> }
<del> }
<del> if (bubbled !== null) {
<del> const bubbleListener = getListener(node, bubbled);
<del> if (bubbleListener != null) {
<del> // Bubble listeners/instances should go at the end, so we
<del> // push them to the end of the array.
<del> dispatchListeners.push(bubbleListener);
<del> dispatchInstances.push(node);
<add> if (bubbled !== null) {
<add> const bubbleListener = getListener(node, bubbled);
<add> if (bubbleListener != null) {
<add> // Bubble listeners/instances should go at the end, so we
<add> // push them to the end of the array.
<add> dispatchListeners.push(bubbleListener);
<add> dispatchInstances.push(node);
<add> }
<ide> }
<ide> }
<add> node = node.return;
<ide> }
<del> node = node.return;
<ide> }
<ide> // To prevent allocation to the event unless we actually
<ide> // have listeners we check the length of one of the arrays. | 9 |
Javascript | Javascript | add two test cases | d24da7574c42fbacb290b1f8517d39504245d699 | <ide><path>test/UglifyJsPlugin.test.js
<add>/* globals describe, it, beforeEach*/
<ide> "use strict";
<del>const should = require("should");
<add>require("should");
<ide> const sinon = require("sinon");
<ide> const UglifyJsPlugin = require("../lib/optimize/UglifyJsPlugin");
<ide> const PluginEnvironment = require("./helpers/PluginEnvironment");
<ide> describe("UglifyJsPlugin", function() {
<ide> compilation.assets["test3.js"].should.be.instanceof(SourceMapSource);
<ide> });
<ide> });
<add>
<add> describe("with warningsFilter set", function() {
<add> let compilationEventBindings, compilation;
<add>
<add> describe("and the filter returns true", function() {
<add> beforeEach(function() {
<add> const pluginEnvironment = new PluginEnvironment();
<add> const compilerEnv = pluginEnvironment.getEnvironmentStub();
<add> compilerEnv.context = "";
<add>
<add> const plugin = new UglifyJsPlugin({
<add> warningsFilter: function() {
<add> return true;
<add> },
<add> sourceMap: true,
<add> compress: {
<add> warnings: true,
<add> },
<add> mangle: false,
<add> beautify: true,
<add> comments: false
<add> });
<add> plugin.apply(compilerEnv);
<add> const eventBindings = pluginEnvironment.getEventBindings();
<add>
<add> const chunkPluginEnvironment = new PluginEnvironment();
<add> compilation = chunkPluginEnvironment.getEnvironmentStub();
<add> compilation.assets = {
<add> "test2.js": {
<add> source: function() {
<add> return "function foo(x) { if (x) { return bar(); not_called1(); } }";
<add> },
<add> map: function() {
<add> return {
<add> version: 3,
<add> sources: ["test1.js"],
<add> names: ["foo", "x", "bar", "not_called1"],
<add> mappings: "AAAA,QAASA,KAAIC,GACT,GAAIA,EAAG,CACH,MAAOC,MACPC"
<add> };
<add> }
<add> },
<add> };
<add> compilation.errors = [];
<add> compilation.warnings = [];
<add>
<add> eventBindings[0].handler(compilation);
<add> compilationEventBindings = chunkPluginEnvironment.getEventBindings();
<add> });
<add>
<add> it("should get all warnings", function() {
<add> compilationEventBindings[1].handler([{
<add> files: ["test2.js"]
<add> }], function() {
<add> compilation.warnings.length.should.be.exactly(1);
<add> compilation.warnings[0].should.be.an.Error;
<add> compilation.warnings[0].message.should.containEql("Dropping unreachable code");
<add> });
<add> });
<add> });
<add>
<add> describe("and the filter returns false", function() {
<add> beforeEach(function() {
<add> const pluginEnvironment = new PluginEnvironment();
<add> const compilerEnv = pluginEnvironment.getEnvironmentStub();
<add> compilerEnv.context = "";
<add>
<add> const plugin = new UglifyJsPlugin({
<add> warningsFilter: function() {
<add> return false;
<add> },
<add> sourceMap: true,
<add> compress: {
<add> warnings: true,
<add> },
<add> mangle: false,
<add> beautify: true,
<add> comments: false
<add> });
<add> plugin.apply(compilerEnv);
<add> const eventBindings = pluginEnvironment.getEventBindings();
<add>
<add> const chunkPluginEnvironment = new PluginEnvironment();
<add> compilation = chunkPluginEnvironment.getEnvironmentStub();
<add> compilation.assets = {
<add> "test2.js": {
<add> source: function() {
<add> return "function foo(x) { if (x) { return bar(); not_called1(); } }";
<add> },
<add> map: function() {
<add> return {
<add> version: 3,
<add> sources: ["test1.js"],
<add> names: ["foo", "x", "bar", "not_called1"],
<add> mappings: "AAAA,QAASA,KAAIC,GACT,GAAIA,EAAG,CACH,MAAOC,MACPC"
<add> };
<add> }
<add> },
<add> };
<add> compilation.errors = [];
<add> compilation.warnings = [];
<add>
<add> eventBindings[0].handler(compilation);
<add> compilationEventBindings = chunkPluginEnvironment.getEventBindings();
<add> });
<add>
<add> it("should get no warnings", function() {
<add> compilationEventBindings[1].handler([{
<add> files: ["test2.js"]
<add> }], function() {
<add> compilation.warnings.length.should.be.exactly(0);
<add> });
<add> });
<add> });
<add> });
<ide> });
<ide> });
<ide> }); | 1 |
PHP | PHP | add setters and getters for request and response | 4fdab63c96c94d86eed7dc3e7b00e7cecc876c2d | <ide><path>src/Controller/Controller.php
<ide> class Controller implements EventListenerInterface, EventDispatcherInterface
<ide> *
<ide> * @var \Cake\Http\ServerRequest
<ide> * @link https://book.cakephp.org/3.0/en/controllers/request-response.html#request
<add> * @deprecated 3.5.0 Use getRequest()/setRequest instead.
<ide> */
<ide> public $request;
<ide>
<ide> class Controller implements EventListenerInterface, EventDispatcherInterface
<ide> *
<ide> * @var \Cake\Http\Response
<ide> * @link https://book.cakephp.org/3.0/en/controllers/request-response.html#response
<add> * @deprecated 3.5.0 Use getResponse()/setResponse instead.
<ide> */
<ide> public $response;
<ide>
<ide> public function setPlugin($plugin)
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Gets the request instance.
<add> *
<add> * @return \Cake\Http\ServerRequest
<add> */
<add> public function getRequest()
<add> {
<add> return $this->request;
<add> }
<add>
<ide> /**
<ide> * Sets the request objects and configures a number of controller properties
<ide> * based on the contents of the request. Controller acts as a proxy for certain View variables
<ide> public function setPlugin($plugin)
<ide> * - View::$plugin - $this->plugin
<ide> *
<ide> * @param \Cake\Http\ServerRequest $request Request instance.
<del> * @return void
<add> * @return $this
<ide> */
<ide> public function setRequest(ServerRequest $request)
<ide> {
<ide> public function setRequest(ServerRequest $request)
<ide> if ($request->getParam('pass')) {
<ide> $this->passedArgs = $request->getParam('pass');
<ide> }
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Gets the response instance.
<add> *
<add> * @return \Cake\Http\Response
<add> */
<add> public function getResponse()
<add> {
<add> return $this->response;
<add> }
<add>
<add> /**
<add> * Sets the response instance.
<add> *
<add> * @param \Cake\Http\Response $response Response instance.
<add> * @return $this
<add> */
<add> public function setResponse(Response $response)
<add> {
<add> $this->response = $response;
<add>
<add> return $this;
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Controller/ControllerTest.php
<ide> public function testPlugin()
<ide> $this->assertEquals('Posts', $controller->getPlugin());
<ide> }
<ide>
<add> /**
<add> * Test request getter and setter.
<add> *
<add> * @return void
<add> */
<add> public function testRequest()
<add> {
<add> $controller = new PostsController();
<add> $this->assertInstanceOf(ServerRequest::class, $controller->getRequest());
<add>
<add> $request = new ServerRequest([
<add> 'params' => [
<add> 'plugin' => 'Posts',
<add> 'pass' => [
<add> 'foo',
<add> 'bar'
<add> ]
<add> ]
<add> ]);
<add> $this->assertSame($controller, $controller->setRequest($request));
<add> $this->assertSame($request, $controller->getRequest());
<add>
<add> $this->assertEquals('Posts', $controller->getPlugin());
<add> $this->assertEquals(['foo', 'bar'], $controller->passedArgs);
<add> }
<add>
<add> /**
<add> * Test response getter and setter.
<add> *
<add> * @return void
<add> */
<add> public function testResponse()
<add> {
<add> $controller = new PostsController();
<add> $this->assertInstanceOf(Response::class, $controller->getResponse());
<add>
<add> $response = new Response;
<add> $this->assertSame($controller, $controller->setResponse($response));
<add> $this->assertSame($response, $controller->getResponse());
<add> }
<add>
<ide> /**
<ide> * Tests deprecated view propertiyes work
<ide> * | 2 |
Text | Text | allow usage of gray in css | 3e797480edde91268bf680f06751a86ab5634557 | <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-basic-css-by-building-a-cafe-menu/step-081.md
<ide> assert(hasAVisited);
<ide> You should set the `color` property to `grey`.
<ide>
<ide> ```js
<del>const hasColor = new __helpers.CSSHelp(document).getCSSRules().some(x => x.style.color === 'grey');
<add>const hasColor = new __helpers.CSSHelp(document).getCSSRules().some(x => (x.style.color === 'grey' || x.style.color === 'gray'));
<ide> assert(hasColor);
<ide> ```
<ide>
<ide> Your `a:visited` should have a `color` of `grey`.
<ide>
<ide> ```js
<ide> const aVisitedColor = new __helpers.CSSHelp(document).getStyle('a:visited')?.getPropertyValue('color');
<del>assert(aVisitedColor === 'grey');
<add>assert(aVisitedColor === 'grey' || aVisitedColor === 'gray');
<ide> ```
<ide>
<ide> # --seed-- | 1 |
Java | Java | maintain cursor position when text changes | de44184e01d74e4da18f1cba9b01d4c259ef5d9c | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.java
<ide> public void maybeSetSelection(int eventCounter, int start, int end) {
<ide> }
<ide>
<ide> if (start != UNSET && end != UNSET) {
<add> // clamp selection values for safety
<add> start = clampToTextLength(start);
<add> end = clampToTextLength(end);
<add>
<ide> setSelection(start, end);
<ide> }
<ide> }
<ide>
<add> private int clampToTextLength(int value) {
<add> int textLength = getText() == null ? 0 : getText().length();
<add>
<add> return Math.max(0, Math.min(value, textLength));
<add> }
<add>
<ide> @Override
<ide> public void setSelection(int start, int end) {
<ide> if (DEBUG_MODE) {
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java
<ide> public void updateExtraData(ReactEditText view, Object extraData) {
<ide> Spannable spannable = update.getText();
<ide> TextInlineImageSpan.possiblyUpdateInlineImageSpans(spannable, view);
<ide> }
<add>
<add> // Ensure that selection is handled correctly on text update
<add> boolean isCurrentSelectionEmpty = view.getSelectionStart() == view.getSelectionEnd();
<add> int selectionStart = update.getSelectionStart();
<add> int selectionEnd = update.getSelectionEnd();
<add> if ((selectionStart == UNSET || selectionEnd == UNSET) && isCurrentSelectionEmpty) {
<add> // if selection is not set by state, shift current selection to ensure constant gap to
<add> // text end
<add> int textLength = view.getText() == null ? 0 : view.getText().length();
<add> int selectionOffset = textLength - view.getSelectionStart();
<add> selectionStart = update.getText().length() - selectionOffset;
<add> selectionEnd = selectionStart;
<add> }
<add>
<ide> view.maybeSetTextFromState(update);
<del> view.maybeSetSelection(
<del> update.getJsEventCounter(), update.getSelectionStart(), update.getSelectionEnd());
<add> view.maybeSetSelection(update.getJsEventCounter(), selectionStart, selectionEnd);
<ide> }
<ide> }
<ide> | 2 |
Javascript | Javascript | introduce a wrapper for requestanimationframe | 04d7317cdd95ba00783389f89f6e9a7e1fc418f8 | <ide><path>angularFiles.js
<ide> angularFiles = {
<ide> 'src/ng/log.js',
<ide> 'src/ng/parse.js',
<ide> 'src/ng/q.js',
<add> 'src/ng/raf.js',
<ide> 'src/ng/rootScope.js',
<ide> 'src/ng/sanitizeUri.js',
<ide> 'src/ng/sce.js',
<ide><path>src/AngularPublic.js
<ide> $SnifferProvider,
<ide> $TemplateCacheProvider,
<ide> $TimeoutProvider,
<add> $$RAFProvider,
<add> $AsyncCallbackProvider,
<ide> $WindowProvider
<ide> */
<ide>
<ide> function publishExternalAPI(angular){
<ide> $sniffer: $SnifferProvider,
<ide> $templateCache: $TemplateCacheProvider,
<ide> $timeout: $TimeoutProvider,
<del> $window: $WindowProvider
<add> $window: $WindowProvider,
<add> $$rAF: $$RAFProvider
<ide> });
<ide> }
<ide> ]);
<ide><path>src/ng/raf.js
<add>'use strict';
<add>
<add>function $$RAFProvider(){ //rAF
<add> this.$get = ['$window', function($window) {
<add> var requestAnimationFrame = $window.requestAnimationFrame ||
<add> $window.webkitRequestAnimationFrame;
<add>
<add> var cancelAnimationFrame = $window.cancelAnimationFrame ||
<add> $window.webkitCancelAnimationFrame;
<add>
<add> var raf = function(fn) {
<add> var id = requestAnimationFrame(fn);
<add> return function() {
<add> cancelAnimationFrame(id);
<add> };
<add> };
<add>
<add> raf.supported = !!requestAnimationFrame;
<add>
<add> return raf;
<add> }];
<add>}
<ide><path>src/ngMock/angular-mocks.js
<ide> angular.mock.$TimeoutDecorator = function($delegate, $browser) {
<ide> return $delegate;
<ide> };
<ide>
<add>angular.mock.$RAFDecorator = function($delegate) {
<add> var queue = [];
<add> var rafFn = function(fn) {
<add> var index = queue.length;
<add> queue.push(fn);
<add> return function() {
<add> queue.splice(index, 1);
<add> };
<add> };
<add>
<add> rafFn.supported = $delegate.supported;
<add>
<add> rafFn.flush = function() {
<add> if(queue.length === 0) {
<add> throw new Error('No rAF callbacks present');
<add> }
<add>
<add> var length = queue.length;
<add> for(var i=0;i<length;i++) {
<add> queue[i]();
<add> }
<add>
<add> queue = [];
<add> };
<add>
<add> return rafFn;
<add>};
<add>
<ide> /**
<ide> *
<ide> */
<ide> angular.module('ngMock', ['ng']).provider({
<ide> $rootElement: angular.mock.$RootElementProvider
<ide> }).config(['$provide', function($provide) {
<ide> $provide.decorator('$timeout', angular.mock.$TimeoutDecorator);
<add> $provide.decorator('$$rAF', angular.mock.$RAFDecorator);
<ide> }]);
<ide>
<ide> /**
<ide><path>test/ng/rafSpec.js
<add>'use strict';
<add>
<add>describe('$$rAF', function() {
<add> it('should queue and block animation frames', inject(function($$rAF) {
<add> if(!$$rAF.supported) return;
<add>
<add> var message;
<add> $$rAF(function() {
<add> message = 'yes';
<add> });
<add>
<add> expect(message).toBeUndefined();
<add> $$rAF.flush();
<add> expect(message).toBe('yes');
<add> }));
<add>
<add> it('should provide a cancellation method', inject(function($$rAF) {
<add> if(!$$rAF.supported) return;
<add>
<add> var present = true;
<add> var cancel = $$rAF(function() {
<add> present = false;
<add> });
<add>
<add> expect(present).toBe(true);
<add> cancel();
<add>
<add> try {
<add> $$rAF.flush();
<add> } catch(e) {};
<add> expect(present).toBe(true);
<add> }));
<add>
<add> describe('mocks', function() {
<add> it('should throw an error if no frames are present', inject(function($$rAF) {
<add> if($$rAF.supported) {
<add> var failed = false;
<add> try {
<add> $$rAF.flush();
<add> } catch(e) {
<add> failed = true;
<add> }
<add> expect(failed).toBe(true);
<add> }
<add> }));
<add> });
<add>}); | 5 |
Python | Python | add support for lr decay in all optimizers | b2e8d5ab7c476fbed088ebee27ec3373e508af47 | <ide><path>keras/optimizers.py
<ide> def __init__(self, lr=0.01, momentum=0., decay=0.,
<ide> self.lr = K.variable(lr)
<ide> self.momentum = K.variable(momentum)
<ide> self.decay = K.variable(decay)
<add> self.inital_decay = decay
<ide>
<ide> def get_updates(self, params, constraints, loss):
<ide> grads = self.get_gradients(loss, params)
<del> lr = self.lr * (1. / (1. + self.decay * self.iterations))
<del> self.updates = [K.update_add(self.iterations, 1)]
<add> self.updates = []
<add>
<add> lr = self.lr
<add> if self.inital_decay > 0:
<add> lr *= (1. / (1. + self.decay * self.iterations))
<add> self.updates .append(K.update_add(self.iterations, 1))
<ide>
<ide> # momentum
<ide> shapes = [K.get_variable_shape(p) for p in params]
<ide> class RMSprop(Optimizer):
<ide> lr: float >= 0. Learning rate.
<ide> rho: float >= 0.
<ide> epsilon: float >= 0. Fuzz factor.
<add> decay: float >= 0. Learning rate decay over each update.
<ide> '''
<del> def __init__(self, lr=0.001, rho=0.9, epsilon=1e-8, **kwargs):
<add> def __init__(self, lr=0.001, rho=0.9, epsilon=1e-8, decay=0.,
<add> **kwargs):
<ide> super(RMSprop, self).__init__(**kwargs)
<ide> self.__dict__.update(locals())
<ide> self.lr = K.variable(lr)
<ide> self.rho = K.variable(rho)
<add> self.decay = K.variable(decay)
<add> self.inital_decay = decay
<add> self.iterations = K.variable(0.)
<ide>
<ide> def get_updates(self, params, constraints, loss):
<ide> grads = self.get_gradients(loss, params)
<ide> def get_updates(self, params, constraints, loss):
<ide> self.weights = accumulators
<ide> self.updates = []
<ide>
<add> lr = self.lr
<add> if self.inital_decay > 0:
<add> lr *= (1. / (1. + self.decay * self.iterations))
<add> self.updates.append(K.update_add(self.iterations, 1))
<add>
<ide> for p, g, a in zip(params, grads, accumulators):
<ide> # update accumulator
<ide> new_a = self.rho * a + (1. - self.rho) * K.square(g)
<ide> self.updates.append(K.update(a, new_a))
<del> new_p = p - self.lr * g / (K.sqrt(new_a) + self.epsilon)
<add> new_p = p - lr * g / (K.sqrt(new_a) + self.epsilon)
<ide>
<ide> # apply constraints
<ide> if p in constraints:
<ide> class Adagrad(Optimizer):
<ide> # References
<ide> - [Adaptive Subgradient Methods for Online Learning and Stochastic Optimization](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)
<ide> '''
<del> def __init__(self, lr=0.01, epsilon=1e-8, **kwargs):
<add> def __init__(self, lr=0.01, epsilon=1e-8, decay=0., **kwargs):
<ide> super(Adagrad, self).__init__(**kwargs)
<ide> self.__dict__.update(locals())
<ide> self.lr = K.variable(lr)
<add> self.decay = K.variable(decay)
<add> self.inital_decay = decay
<add> self.iterations = K.variable(0.)
<ide>
<ide> def get_updates(self, params, constraints, loss):
<ide> grads = self.get_gradients(loss, params)
<ide> def get_updates(self, params, constraints, loss):
<ide> self.weights = accumulators
<ide> self.updates = []
<ide>
<add> lr = self.lr
<add> if self.inital_decay > 0:
<add> lr *= (1. / (1. + self.decay * self.iterations))
<add> self.updates.append(K.update_add(self.iterations, 1))
<add>
<ide> for p, g, a in zip(params, grads, accumulators):
<ide> new_a = a + K.square(g) # update accumulator
<ide> self.updates.append(K.update(a, new_a))
<del> new_p = p - self.lr * g / (K.sqrt(new_a) + self.epsilon)
<add> new_p = p - lr * g / (K.sqrt(new_a) + self.epsilon)
<ide> # apply constraints
<ide> if p in constraints:
<ide> c = constraints[p]
<ide> class Adadelta(Optimizer):
<ide> # References
<ide> - [Adadelta - an adaptive learning rate method](http://arxiv.org/abs/1212.5701)
<ide> '''
<del> def __init__(self, lr=1.0, rho=0.95, epsilon=1e-8, **kwargs):
<add> def __init__(self, lr=1.0, rho=0.95, epsilon=1e-8, decay=0.,
<add> **kwargs):
<ide> super(Adadelta, self).__init__(**kwargs)
<ide> self.__dict__.update(locals())
<ide> self.lr = K.variable(lr)
<add> self.decay = K.variable(decay)
<add> self.inital_decay = decay
<add> self.iterations = K.variable(0.)
<ide>
<ide> def get_updates(self, params, constraints, loss):
<ide> grads = self.get_gradients(loss, params)
<ide> def get_updates(self, params, constraints, loss):
<ide> self.weights = accumulators + delta_accumulators
<ide> self.updates = []
<ide>
<add> lr = self.lr
<add> if self.inital_decay > 0:
<add> lr *= (1. / (1. + self.decay * self.iterations))
<add> self.updates.append(K.update_add(self.iterations, 1))
<add>
<ide> for p, g, a, d_a in zip(params, grads, accumulators, delta_accumulators):
<ide> # update accumulator
<ide> new_a = self.rho * a + (1. - self.rho) * K.square(g)
<ide> def get_updates(self, params, constraints, loss):
<ide> # use the new accumulator and the *old* delta_accumulator
<ide> update = g * K.sqrt(d_a + self.epsilon) / K.sqrt(new_a + self.epsilon)
<ide>
<del> new_p = p - self.lr * update
<add> new_p = p - lr * update
<ide> # apply constraints
<ide> if p in constraints:
<ide> c = constraints[p]
<ide> class Adam(Optimizer):
<ide> - [Adam - A Method for Stochastic Optimization](http://arxiv.org/abs/1412.6980v8)
<ide> '''
<ide> def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999,
<del> epsilon=1e-8, **kwargs):
<add> epsilon=1e-8, decay=0., **kwargs):
<ide> super(Adam, self).__init__(**kwargs)
<ide> self.__dict__.update(locals())
<ide> self.iterations = K.variable(0)
<ide> self.lr = K.variable(lr)
<ide> self.beta_1 = K.variable(beta_1)
<ide> self.beta_2 = K.variable(beta_2)
<add> self.decay = K.variable(decay)
<add> self.inital_decay = decay
<ide>
<ide> def get_updates(self, params, constraints, loss):
<ide> grads = self.get_gradients(loss, params)
<ide> self.updates = [K.update_add(self.iterations, 1)]
<ide>
<add> lr = self.lr
<add> if self.inital_decay > 0:
<add> lr *= (1. / (1. + self.decay * self.iterations))
<add>
<ide> t = self.iterations + 1
<del> lr_t = self.lr * K.sqrt(1. - K.pow(self.beta_2, t)) / (1. - K.pow(self.beta_1, t))
<add> lr_t = lr * K.sqrt(1. - K.pow(self.beta_2, t)) / (1. - K.pow(self.beta_1, t))
<ide>
<ide> shapes = [K.get_variable_shape(p) for p in params]
<ide> ms = [K.zeros(shape) for shape in shapes]
<ide> class Adamax(Optimizer):
<ide> - [Adam - A Method for Stochastic Optimization](http://arxiv.org/abs/1412.6980v8)
<ide> '''
<ide> def __init__(self, lr=0.002, beta_1=0.9, beta_2=0.999,
<del> epsilon=1e-8, **kwargs):
<add> epsilon=1e-8, decay=0., **kwargs):
<ide> super(Adamax, self).__init__(**kwargs)
<ide> self.__dict__.update(locals())
<ide> self.iterations = K.variable(0.)
<ide> self.lr = K.variable(lr)
<ide> self.beta_1 = K.variable(beta_1)
<ide> self.beta_2 = K.variable(beta_2)
<add> self.decay = K.variable(decay)
<add> self.inital_decay = decay
<ide>
<ide> def get_updates(self, params, constraints, loss):
<ide> grads = self.get_gradients(loss, params)
<ide> self.updates = [K.update_add(self.iterations, 1)]
<ide>
<add> lr = self.lr
<add> if self.inital_decay > 0:
<add> lr *= (1. / (1. + self.decay * self.iterations))
<add>
<ide> t = self.iterations + 1
<ide> lr_t = self.lr / (1. - K.pow(self.beta_1, t))
<ide>
<ide><path>tests/keras/test_optimizers.py
<ide> def test_sgd():
<ide>
<ide> def test_rmsprop():
<ide> _test_optimizer(RMSprop())
<add> _test_optimizer(RMSprop(decay=1e-3))
<ide>
<ide>
<ide> def test_adagrad():
<ide> _test_optimizer(Adagrad())
<add> _test_optimizer(Adagrad(decay=1e-3))
<ide>
<ide>
<ide> def test_adadelta():
<ide> _test_optimizer(Adadelta())
<add> _test_optimizer(Adadelta(decay=1e-3))
<ide>
<ide>
<ide> def test_adam():
<ide> _test_optimizer(Adam())
<add> _test_optimizer(Adam(decay=1e-3))
<ide>
<ide>
<ide> def test_adamax():
<ide> _test_optimizer(Adamax())
<add> _test_optimizer(Adamax(decay=1e-3))
<ide>
<ide>
<ide> def test_nadam(): | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.