content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
PHP
PHP
fix exception in date time widget
16c157f22ffeb2cdc376b9ce2866e098a0d81acd
<ide><path>src/View/Widget/DateTime.php <ide> public function render(array $data, ContextInterface $context) { <ide> continue; <ide> } <ide> if (!is_array($data[$select])) { <del> throw \RuntimeException(sprintf( <add> throw new \RuntimeException(sprintf( <ide> 'Options for "%s" must be an array|false|null', <ide> $select <ide> ));
1
Ruby
Ruby
add loadingmodule.clear! back temporarily
6d7b0374d12de2ddeaa9c3f896234111ed6bf8e2
<ide><path>activesupport/lib/active_support/dependencies.rb <ide> def const_load!(name, file_name = nil) <ide> def const_available?(name) <ide> self.const_defined?(name) || load_paths.any? {|lp| lp.filesystem_path(path + [name])} <ide> end <add> <add> # Erase all items in this module <add> def clear! <add> constants.each do |name| <add> Object.send(:remove_const, name) if Object.const_defined?(name) && Object.const_get(name).object_id == self.const_get(name).object_id <add> self.send(:remove_const, name) <add> end <add> end <ide> end <ide> <ide> class RootLoadingModule < LoadingModule #:nodoc: <ide><path>railties/lib/dispatcher.rb <ide> def dispatch(cgi = nil, session_options = ActionController::CgiRequest::DEFAULT_ <ide> # mailers, and so forth. This allows them to be loaded again without having <ide> # to restart the server (WEBrick, FastCGI, etc.). <ide> def reset_application! <add> Controllers.clear! <ide> Dependencies.clear <ide> ActiveRecord::Base.reset_subclasses <ide> Class.remove_class(*Reloadable.reloadable_classes)
2
PHP
PHP
refactor the auth class and its comments
4c243f3a99b3e9d178e1648a6343a724413d5991
<ide><path>system/auth.php <ide> class Auth { <ide> * Typically, the user should be accessed via the "user" method. <ide> * <ide> * @var object <del> * @see user() <ide> */ <ide> public static $user; <ide> <ide> class Auth { <ide> * Determine if the current user of the application is authenticated. <ide> * <ide> * @return bool <del> * @see login <ide> */ <ide> public static function check() <ide> { <ide> public static function user() <ide> } <ide> <ide> /** <del> * Attempt to login a user. <add> * Attempt to log a user into your application. <ide> * <ide> * If the user credentials are valid. The user's ID will be stored in the session and the <ide> * user will be considered "logged in" on subsequent requests to the application. <ide> public static function user() <ide> * @param string $username <ide> * @param string $password <ide> * @return bool <del> * @see Hash::check() <ide> */ <ide> public static function login($username, $password) <ide> { <ide> public static function login($username, $password) <ide> } <ide> <ide> /** <del> * Log a user into the application without checking credentials. <add> * Log a user into your application. <ide> * <ide> * The user's ID will be stored in the session and the user will be considered <del> * "logged in" on subsequent requests to the application. <add> * "logged in" on subsequent requests to your application. <ide> * <ide> * Note: The user given to this method should be an object having an "id" property. <ide> * <ide> public static function remember($user) <ide> } <ide> <ide> /** <del> * Log the user out of the application. <add> * Log the user out of your application. <ide> * <ide> * The user ID will be removed from the session and the user will no longer <ide> * be considered logged in on subsequent requests.
1
Javascript
Javascript
upgrade occurrenceorderplugin to es6
126eb9158a0772246e461769a2ce302052fab9cb
<ide><path>lib/optimize/OccurrenceOrderPlugin.js <ide> MIT License http://www.opensource.org/licenses/mit-license.php <ide> Author Tobias Koppers @sokra <ide> */ <del>function OccurrenceOrderPlugin(preferEntry) { <del> if(preferEntry !== undefined && typeof preferEntry !== "boolean") { <del> throw new Error("Argument should be a boolean.\nFor more info on this plugin, see https://webpack.github.io/docs/list-of-plugins.html"); <del> } <del> this.preferEntry = preferEntry; <del>} <del>module.exports = OccurrenceOrderPlugin; <del>OccurrenceOrderPlugin.prototype.apply = function(compiler) { <del> var preferEntry = this.preferEntry; <del> compiler.plugin("compilation", function(compilation) { <del> compilation.plugin("optimize-module-order", function(modules) { <del> function entryChunks(m) { <del> return m.chunks.map(function(c) { <del> var sum = (c.isInitial() ? 1 : 0) + (c.entryModule === m ? 1 : 0); <del> return sum; <del> }).reduce(function(a, b) { <del> return a + b; <del> }, 0); <del> } <add>"use strict"; <ide> <del> function occursInEntry(m) { <del> if(typeof m.__OccurenceOrderPlugin_occursInEntry === "number") return m.__OccurenceOrderPlugin_occursInEntry; <del> var result = m.reasons.map(function(r) { <del> if(!r.module) return 0; <del> return entryChunks(r.module); <del> }).reduce(function(a, b) { <del> return a + b; <del> }, 0) + entryChunks(m); <del> return m.__OccurenceOrderPlugin_occursInEntry = result; <del> } <add>class OccurrenceOrderPlugin { <add> constructor(preferEntry) { <add> if(preferEntry !== undefined && typeof preferEntry !== "boolean") { <add> throw new Error("Argument should be a boolean.\nFor more info on this plugin, see https://webpack.github.io/docs/list-of-plugins.html"); <add> } <add> this.preferEntry = preferEntry; <add> } <add> apply(compiler) { <add> const preferEntry = this.preferEntry; <add> compiler.plugin("compilation", (compilation) => { <add> compilation.plugin("optimize-module-order", (modules) => { <add> function entryChunks(m) { <add> return m.chunks.map((c) => { <add> const sum = (c.isInitial() ? 1 : 0) + (c.entryModule === m ? 1 : 0); <add> return sum; <add> }).reduce((a, b) => { <add> return a + b; <add> }, 0); <add> } <ide> <del> function occurs(m) { <del> if(typeof m.__OccurenceOrderPlugin_occurs === "number") return m.__OccurenceOrderPlugin_occurs; <del> var result = m.reasons.map(function(r) { <del> if(!r.module) return 0; <del> return r.module.chunks.length; <del> }).reduce(function(a, b) { <del> return a + b; <del> }, 0) + m.chunks.length + m.chunks.filter(function(c) { <del> c.entryModule === m; <del> }).length; <del> return m.__OccurenceOrderPlugin_occurs = result; <del> } <del> modules.sort(function(a, b) { <del> if(preferEntry) { <del> var aEntryOccurs = occursInEntry(a); <del> var bEntryOccurs = occursInEntry(b); <del> if(aEntryOccurs > bEntryOccurs) return -1; <del> if(aEntryOccurs < bEntryOccurs) return 1; <add> function occursInEntry(m) { <add> if(typeof m.__OccurenceOrderPlugin_occursInEntry === "number") return m.__OccurenceOrderPlugin_occursInEntry; <add> const result = m.reasons.map((r) => { <add> if(!r.module) return 0; <add> return entryChunks(r.module); <add> }).reduce((a, b) => { <add> return a + b; <add> }, 0) + entryChunks(m); <add> return m.__OccurenceOrderPlugin_occursInEntry = result; <ide> } <del> var aOccurs = occurs(a); <del> var bOccurs = occurs(b); <del> if(aOccurs > bOccurs) return -1; <del> if(aOccurs < bOccurs) return 1; <del> if(a.identifier() > b.identifier()) return 1; <del> if(a.identifier() < b.identifier()) return -1; <del> return 0; <del> }); <del> // TODO refactor to Map <del> modules.forEach(function(m) { <del> m.__OccurenceOrderPlugin_occursInEntry = undefined; <del> m.__OccurenceOrderPlugin_occurs = undefined; <del> }); <del> }); <del> compilation.plugin("optimize-chunk-order", function(chunks) { <del> function occursInEntry(c) { <del> if(typeof c.__OccurenceOrderPlugin_occursInEntry === "number") return c.__OccurenceOrderPlugin_occursInEntry; <del> var result = c.parents.filter(function(p) { <del> return p.isInitial(); <del> }).length; <del> return c.__OccurenceOrderPlugin_occursInEntry = result; <del> } <ide> <del> function occurs(c) { <del> return c.blocks.length; <del> } <del> chunks.forEach(function(c) { <del> c.modules.sort(function(a, b) { <add> function occurs(m) { <add> if(typeof m.__OccurenceOrderPlugin_occurs === "number") return m.__OccurenceOrderPlugin_occurs; <add> const result = m.reasons.map((r) => { <add> if(!r.module) return 0; <add> return r.module.chunks.length; <add> }).reduce((a, b) => { <add> return a + b; <add> }, 0) + m.chunks.length + m.chunks.filter((c) => { <add> c.entryModule === m; <add> }).length; <add> return m.__OccurenceOrderPlugin_occurs = result; <add> } <add> modules.sort((a, b) => { <add> if(preferEntry) { <add> const aEntryOccurs = occursInEntry(a); <add> const bEntryOccurs = occursInEntry(b); <add> if(aEntryOccurs > bEntryOccurs) return -1; <add> if(aEntryOccurs < bEntryOccurs) return 1; <add> } <add> const aOccurs = occurs(a); <add> const bOccurs = occurs(b); <add> if(aOccurs > bOccurs) return -1; <add> if(aOccurs < bOccurs) return 1; <ide> if(a.identifier() > b.identifier()) return 1; <ide> if(a.identifier() < b.identifier()) return -1; <ide> return 0; <ide> }); <add> // TODO refactor to Map <add> modules.forEach((m) => { <add> m.__OccurenceOrderPlugin_occursInEntry = undefined; <add> m.__OccurenceOrderPlugin_occurs = undefined; <add> }); <ide> }); <del> chunks.sort(function(a, b) { <del> var aEntryOccurs = occursInEntry(a); <del> var bEntryOccurs = occursInEntry(b); <del> if(aEntryOccurs > bEntryOccurs) return -1; <del> if(aEntryOccurs < bEntryOccurs) return 1; <del> var aOccurs = occurs(a); <del> var bOccurs = occurs(b); <del> if(aOccurs > bOccurs) return -1; <del> if(aOccurs < bOccurs) return 1; <del> if(a.modules.length > b.modules.length) return -1; <del> if(a.modules.length < b.modules.length) return 1; <del> for(var i = 0; i < a.modules.length; i++) { <del> if(a.modules[i].identifier() > b.modules[i].identifier()) return -1; <del> if(a.modules[i].identifier() < b.modules[i].identifier()) return 1; <add> compilation.plugin("optimize-chunk-order", (chunks) => { <add> function occursInEntry(c) { <add> if(typeof c.__OccurenceOrderPlugin_occursInEntry === "number") return c.__OccurenceOrderPlugin_occursInEntry; <add> const result = c.parents.filter((p) => { <add> return p.isInitial(); <add> }).length; <add> return c.__OccurenceOrderPlugin_occursInEntry = result; <ide> } <del> return 0; <del> }); <del> // TODO refactor to Map <del> chunks.forEach(function(c) { <del> c.__OccurenceOrderPlugin_occursInEntry = undefined; <add> <add> function occurs(c) { <add> return c.blocks.length; <add> } <add> chunks.forEach((c) => { <add> c.modules.sort((a, b) => { <add> if(a.identifier() > b.identifier()) return 1; <add> if(a.identifier() < b.identifier()) return -1; <add> return 0; <add> }); <add> }); <add> chunks.sort((a, b) => { <add> const aEntryOccurs = occursInEntry(a); <add> const bEntryOccurs = occursInEntry(b); <add> if(aEntryOccurs > bEntryOccurs) return -1; <add> if(aEntryOccurs < bEntryOccurs) return 1; <add> const aOccurs = occurs(a); <add> const bOccurs = occurs(b); <add> if(aOccurs > bOccurs) return -1; <add> if(aOccurs < bOccurs) return 1; <add> if(a.modules.length > b.modules.length) return -1; <add> if(a.modules.length < b.modules.length) return 1; <add> for(let i = 0; i < a.modules.length; i++) { <add> if(a.modules[i].identifier() > b.modules[i].identifier()) return -1; <add> if(a.modules[i].identifier() < b.modules[i].identifier()) return 1; <add> } <add> return 0; <add> }); <add> // TODO refactor to Map <add> chunks.forEach((c) => { <add> c.__OccurenceOrderPlugin_occursInEntry = undefined; <add> }); <ide> }); <ide> }); <del> }); <del>}; <add> } <add>} <add> <add>module.exports = OccurrenceOrderPlugin;
1
PHP
PHP
move alias wrapping into _formataddress()
0207a61e9ba357219740cdf716a75f17419572bf
<ide><path>lib/Cake/Network/Email/CakeEmail.php <ide> protected function _formatAddress($address) { <ide> if ($email === $alias) { <ide> $return[] = $email; <ide> } else { <add> if (strpos($alias, ',') !== false) { <add> $alias = '"' . $alias . '"'; <add> } <ide> $return[] = sprintf('%s <%s>', $this->_encode($alias), $email); <ide> } <ide> } <ide> protected function _encode($text) { <ide> $restore = mb_internal_encoding(); <ide> mb_internal_encoding($this->_appCharset); <ide> } <del> if (strpos($text, ',') !== false) { <del> $text = '"' . $text . '"'; <del> } <ide> $return = mb_encode_mimeheader($text, $this->headerCharset, 'B'); <ide> if ($internalEncoding) { <ide> mb_internal_encoding($restore); <ide><path>lib/Cake/Test/Case/Network/Email/CakeEmailTest.php <ide> public function testSubject() { <ide> $this->CakeEmail->subject('You have a new message.'); <ide> $this->assertSame($this->CakeEmail->subject(), 'You have a new message.'); <ide> <add> $this->CakeEmail->subject('You have a new message, I think.'); <add> $this->assertSame($this->CakeEmail->subject(), 'You have a new message, I think.'); <ide> $this->CakeEmail->subject(1); <ide> $this->assertSame($this->CakeEmail->subject(), '1'); <ide>
2
Text
Text
add example to require ordering section
e03a7c336dc009ec62d142b85574ee8d0f24ba7b
<ide><path>CONTRIBUTING.md <ide> * Commit messages are in the present tense <ide> * Files end with a newline. <ide> * Requires should be in the following order: <del> * Node Modules <del> * Built in Atom and Atom Shell modules <del> * Local Modules (using relative links) <add> * Built in Node Modules (such as `path`) <add> * Built in Atom and Atom Shell Modules (such as `atom`, `shell`) <add> * Local Modules (using relative paths) <ide> * Class variables and methods should be in the following order: <ide> * Class methods (methods starting with a `@`) <ide> * Instance methods
1
Go
Go
fix platform type
81f862a1fe6f24fea70b1278a4292eefc4029a03
<ide><path>api/server/router/build/build_routes.go <ide> func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBui <ide> options.RemoteContext = r.FormValue("remote") <ide> if versions.GreaterThanOrEqualTo(version, "1.32") { <ide> apiPlatform := r.FormValue("platform") <del> if len(strings.TrimSpace(apiPlatform)) != 0 { <add> if apiPlatform != "" { <ide> sp, err := platforms.Parse(apiPlatform) <ide> if err != nil { <ide> return nil, err <ide> } <del> options.Platform = sp <add> options.Platform = &sp <ide> } <ide> } <ide> <ide><path>api/server/router/image/image_routes.go <ide> func (s *imageRouter) postImagesCreate(ctx context.Context, w http.ResponseWrite <ide> version := httputils.VersionFromContext(ctx) <ide> if versions.GreaterThanOrEqualTo(version, "1.32") { <ide> apiPlatform := r.FormValue("platform") <del> if len(strings.TrimSpace(apiPlatform)) != 0 { <add> if apiPlatform != "" { <ide> sp, err := platforms.Parse(apiPlatform) <ide> if err != nil { <ide> return err <ide><path>api/types/client.go <ide> type ImageBuildOptions struct { <ide> ExtraHosts []string // List of extra hosts <ide> Target string <ide> SessionID string <del> Platform specs.Platform <add> Platform *specs.Platform <ide> // Version specifies the version of the unerlying builder to use <ide> Version BuilderVersion <ide> // BuildID is an optional identifier that can be passed together with the <ide><path>builder/dockerfile/copy.go <ide> type copier struct { <ide> source builder.Source <ide> pathCache pathCache <ide> download sourceDownloader <del> platform specs.Platform <add> platform *specs.Platform <ide> // for cleanup. TODO: having copier.cleanup() is error prone and hard to <ide> // follow. Code calling performCopy should manage the lifecycle of its params. <ide> // Copier should take override source as input, not imageMount. <ide><path>client/image_build.go <ide> import ( <ide> "net/http" <ide> "net/url" <ide> "strconv" <del> "strings" <ide> <add> "github.com/containerd/containerd/platforms" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/container" <ide> ) <ide> func (cli *Client) ImageBuild(ctx context.Context, buildContext io.Reader, optio <ide> } <ide> headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf)) <ide> <del> if options.Platform != "" { <add> if options.Platform != nil { <ide> if err := cli.NewVersionError("1.32", "platform"); err != nil { <ide> return types.ImageBuildResponse{}, err <ide> } <del> query.Set("platform", options.Platform) <add> query.Set("platform", platforms.Format(*options.Platform)) <ide> } <ide> headers.Set("Content-Type", "application/x-tar") <ide> <ide> func (cli *Client) imageBuildOptionsToQuery(options types.ImageBuildOptions) (ur <ide> if options.SessionID != "" { <ide> query.Set("session", options.SessionID) <ide> } <del> if options.Platform != "" { <del> query.Set("platform", strings.ToLower(options.Platform)) <add> if options.Platform != nil { <add> query.Set("platform", platforms.Format(*options.Platform)) <ide> } <ide> if options.BuildID != "" { <ide> query.Set("buildid", options.BuildID)
5
Python
Python
allow type uint64 for eye() arguments
f9355942f6ef7c5d27691c4571096234efb67a2b
<ide><path>numpy/lib/tests/test_twodim_base.py <ide> def test_basic(self): <ide> assert_equal(eye(3) == 1, <ide> eye(3, dtype=bool)) <ide> <add> def test_uint64(self): <add> # Regression test for gh-9982 <add> assert_equal(eye(np.uint64(2), dtype=int), array([[1, 0], [0, 1]])) <add> assert_equal(eye(np.uint64(2), M=np.uint64(4), k=np.uint64(1)), <add> array([[0, 1, 0, 0], [0, 0, 1, 0]])) <add> <ide> def test_diag(self): <ide> assert_equal(eye(4, k=1), <ide> array([[0, 1, 0, 0], <ide> def test_tril_triu_dtype(): <ide> assert_equal(np.triu(arr).dtype, arr.dtype) <ide> assert_equal(np.tril(arr).dtype, arr.dtype) <ide> <del> arr = np.zeros((3,3), dtype='f4,f4') <add> arr = np.zeros((3, 3), dtype='f4,f4') <ide> assert_equal(np.triu(arr).dtype, arr.dtype) <ide> assert_equal(np.tril(arr).dtype, arr.dtype) <ide> <ide><path>numpy/lib/twodim_base.py <ide> <ide> """ <ide> import functools <add>import operator <ide> <ide> from numpy.core.numeric import ( <ide> asanyarray, arange, zeros, greater_equal, multiply, ones, <ide> def eye(N, M=None, k=0, dtype=float, order='C', *, like=None): <ide> m = zeros((N, M), dtype=dtype, order=order) <ide> if k >= M: <ide> return m <add> # Ensure M and k are integers, so we don't get any surprise casting <add> # results in the expressions `M-k` and `M+1` used below. This avoids <add> # a problem with inputs with type (for example) np.uint64. <add> M = operator.index(M) <add> k = operator.index(k) <ide> if k >= 0: <ide> i = k <ide> else: <ide> def triu(m, k=0): <ide> Upper triangle of an array. <ide> <ide> Return a copy of an array with the elements below the `k`-th diagonal <del> zeroed. For arrays with ``ndim`` exceeding 2, `triu` will apply to the final <del> two axes. <add> zeroed. For arrays with ``ndim`` exceeding 2, `triu` will apply to the <add> final two axes. <ide> <ide> Please refer to the documentation for `tril` for further details. <ide> <ide> def histogram2d(x, y, bins=10, range=None, normed=None, weights=None, <ide> >>> plt.show() <ide> """ <ide> from numpy import histogramdd <del> <add> <ide> if len(x) != len(y): <ide> raise ValueError('x and y must have the same length.') <ide>
2
Ruby
Ruby
finish custom handling [dhh]
6dea52c54e272b4592d1d157c8626003b03fcac1
<ide><path>actionpack/lib/action_controller/mime_responds.rb <ide> module InstanceMethods <ide> # and accept Rails' defaults, life will be much easier. <ide> def respond_to(*types, &block) <ide> raise ArgumentError, "respond_to takes either types or a block, never bot" unless types.any? ^ block <del> block ||= lambda { |responder| types.each { |type| responder.known(type) } } <add> block ||= lambda { |responder| types.each { |type| responder.send(type) } } <ide> responder = Responder.new(block.binding) <ide> block.call(responder) <ide> responder.respond <ide> def custom(mime_type, &block) <ide> @responses[mime_type] = eval(DEFAULT_BLOCKS[mime_type.to_sym], @block_binding) <ide> end <ide> end <del> <del> def known(mime_type_extension, &block) <del> custom(Mime.const_get(mime_type_extension.to_s.upcase), &block) <del> end <ide> <ide> def any(*args, &block) <del> args.each { |type| known(type, &block) } <add> args.each { |type| send(type, &block) } <add> end <add> <add> def method_missing(symbol, &block) <add> mime_constant = symbol.to_s.upcase <add> <add> if Mime::SET.include?(Mime.const_get(mime_constant)) <add> custom(Mime.const_get(mime_constant), &block) <add> else <add> super <add> end <ide> end <ide> <ide> def respond <ide><path>actionpack/test/controller/mime_responds_test.rb <ide> def custom_type_handling <ide> type.all { render :text => "Nothing" } <ide> end <ide> end <add> <add> def custom_constant_handling <add> Mime::Type.register("text/x-mobile", :mobile) <add> <add> respond_to do |type| <add> type.html { render :text => "HTML" } <add> type.mobile { render :text => "Mobile" } <add> end <add> <add> Mime.send :remove_const, :MOBILE <add> end <ide> <ide> def handle_any <ide> respond_to do |type| <ide> def test_xhr <ide> assert_equal '$("body").visualEffect("highlight");', @response.body <ide> end <ide> <add> def test_custom_constant <add> get :custom_constant_handling, :format => "mobile" <add> assert_equal "Mobile", @response.body <add> end <add> <ide> def test_forced_format <ide> get :html_xml_or_rss <ide> assert_equal "HTML", @response.body
2
Mixed
Go
fix rootless detection (alternative to )
3518383ed990202d93e5458782d2c975c48ececd
<ide><path>cmd/dockerd/config_common_unix.go <ide> import ( <ide> "github.com/docker/docker/daemon/config" <ide> "github.com/docker/docker/opts" <ide> "github.com/docker/docker/pkg/homedir" <del> "github.com/docker/docker/rootless" <ide> "github.com/spf13/pflag" <ide> ) <ide> <ide> func getDefaultPidFile() (string, error) { <del> if !rootless.RunningWithNonRootUsername() { <add> if !honorXDG { <ide> return "/var/run/docker.pid", nil <ide> } <ide> runtimeDir, err := homedir.GetRuntimeDir() <ide> func getDefaultPidFile() (string, error) { <ide> } <ide> <ide> func getDefaultDataRoot() (string, error) { <del> if !rootless.RunningWithNonRootUsername() { <add> if !honorXDG { <ide> return "/var/lib/docker", nil <ide> } <ide> dataHome, err := homedir.GetDataHome() <ide> func getDefaultDataRoot() (string, error) { <ide> } <ide> <ide> func getDefaultExecRoot() (string, error) { <del> if !rootless.RunningWithNonRootUsername() { <add> if !honorXDG { <ide> return "/var/run/docker", nil <ide> } <ide> runtimeDir, err := homedir.GetRuntimeDir() <ide><path>cmd/dockerd/config_unix.go <ide> package main <ide> <ide> import ( <add> "os/exec" <add> <ide> "github.com/docker/docker/daemon/config" <ide> "github.com/docker/docker/opts" <ide> "github.com/docker/docker/rootless" <ide> "github.com/docker/go-units" <add> "github.com/pkg/errors" <ide> "github.com/spf13/pflag" <ide> ) <ide> <ide> func installConfigFlags(conf *config.Config, flags *pflag.FlagSet) error { <ide> flags.BoolVar(&conf.BridgeConfig.EnableIPv6, "ipv6", false, "Enable IPv6 networking") <ide> flags.StringVar(&conf.BridgeConfig.FixedCIDRv6, "fixed-cidr-v6", "", "IPv6 subnet for fixed IPs") <ide> flags.BoolVar(&conf.BridgeConfig.EnableUserlandProxy, "userland-proxy", true, "Use userland proxy for loopback traffic") <del> flags.StringVar(&conf.BridgeConfig.UserlandProxyPath, "userland-proxy-path", "", "Path to the userland proxy binary") <add> defaultUserlandProxyPath := "" <add> if rootless.RunningWithRootlessKit() { <add> var err error <add> // use rootlesskit-docker-proxy for exposing the ports in RootlessKit netns to the initial namespace. <add> defaultUserlandProxyPath, err = exec.LookPath(rootless.RootlessKitDockerProxyBinary) <add> if err != nil { <add> return errors.Wrapf(err, "running with RootlessKit, but %s not installed", rootless.RootlessKitDockerProxyBinary) <add> } <add> } <add> flags.StringVar(&conf.BridgeConfig.UserlandProxyPath, "userland-proxy-path", defaultUserlandProxyPath, "Path to the userland proxy binary") <ide> flags.StringVar(&conf.CgroupParent, "cgroup-parent", "", "Set parent cgroup for all containers") <ide> flags.StringVar(&conf.RemappedRoot, "userns-remap", "", "User/Group setting for user namespaces") <ide> flags.BoolVar(&conf.LiveRestoreEnabled, "live-restore", false, "Enable live restore of docker when containers are still running") <ide> func installConfigFlags(conf *config.Config, flags *pflag.FlagSet) error { <ide> flags.BoolVar(&conf.NoNewPrivileges, "no-new-privileges", false, "Set no-new-privileges by default for new containers") <ide> flags.StringVar(&conf.IpcMode, "default-ipc-mode", config.DefaultIpcMode, `Default mode for containers ipc ("shareable" | "private")`) <ide> flags.Var(&conf.NetworkConfig.DefaultAddressPools, "default-address-pool", "Default address pools for node specific local networks") <del> // Mostly users don't need to set this flag explicitly. <del> flags.BoolVar(&conf.Rootless, "rootless", rootless.RunningWithNonRootUsername(), "Enable rootless mode (experimental)") <add> // rootless needs to be explicitly specified for running "rootful" dockerd in rootless dockerd (#38702) <add> // Note that defaultUserlandProxyPath and honorXDG are configured according to the value of rootless.RunningWithRootlessKit, not the value of --rootless. <add> flags.BoolVar(&conf.Rootless, "rootless", rootless.RunningWithRootlessKit(), "Enable rootless mode; typically used with RootlessKit (experimental)") <ide> return nil <ide> } <ide><path>cmd/dockerd/daemon.go <ide> func (cli *DaemonCli) start(opts *daemonOptions) (err error) { <ide> if cli.Config.IsRootless() { <ide> logrus.Warn("Running in rootless mode. Cgroups, AppArmor, and CRIU are disabled.") <ide> } <add> if rootless.RunningWithRootlessKit() { <add> logrus.Info("Running with RootlessKit integration") <add> if !cli.Config.IsRootless() { <add> return fmt.Errorf("rootless mode needs to be enabled for running with RootlessKit") <add> } <add> } <ide> } else { <ide> if cli.Config.IsRootless() { <ide> return fmt.Errorf("rootless mode is supported only when running in experimental mode") <ide> func loadListeners(cli *DaemonCli, serverConfig *apiserver.Config) ([]string, er <ide> var hosts []string <ide> for i := 0; i < len(cli.Config.Hosts); i++ { <ide> var err error <del> if cli.Config.Hosts[i], err = dopts.ParseHost(cli.Config.TLS, rootless.RunningWithNonRootUsername(), cli.Config.Hosts[i]); err != nil { <add> if cli.Config.Hosts[i], err = dopts.ParseHost(cli.Config.TLS, honorXDG, cli.Config.Hosts[i]); err != nil { <ide> return nil, errors.Wrapf(err, "error parsing -H %s", cli.Config.Hosts[i]) <ide> } <ide> <ide> func validateAuthzPlugins(requestedPlugins []string, pg plugingetter.PluginGette <ide> return nil <ide> } <ide> <del>func systemContainerdRunning(isRootless bool) (string, bool, error) { <add>func systemContainerdRunning(honorXDG bool) (string, bool, error) { <ide> addr := containerddefaults.DefaultAddress <del> if isRootless { <add> if honorXDG { <ide> runtimeDir, err := homedir.GetRuntimeDir() <ide> if err != nil { <ide> return "", false, err <ide><path>cmd/dockerd/daemon_unix.go <ide> import ( <ide> "github.com/docker/docker/daemon/config" <ide> "github.com/docker/docker/libcontainerd/supervisor" <ide> "github.com/docker/docker/pkg/homedir" <del> "github.com/docker/docker/rootless" <ide> "github.com/docker/libnetwork/portallocator" <ide> "github.com/pkg/errors" <ide> "golang.org/x/sys/unix" <ide> ) <ide> <ide> func getDefaultDaemonConfigDir() (string, error) { <del> if !rootless.RunningWithNonRootUsername() { <add> if !honorXDG { <ide> return "/etc/docker", nil <ide> } <ide> // NOTE: CLI uses ~/.docker while the daemon uses ~/.config/docker, because <ide> func newCgroupParent(config *config.Config) string { <ide> func (cli *DaemonCli) initContainerD(ctx context.Context) (func(time.Duration) error, error) { <ide> var waitForShutdown func(time.Duration) error <ide> if cli.Config.ContainerdAddr == "" { <del> systemContainerdAddr, ok, err := systemContainerdRunning(cli.Config.IsRootless()) <add> systemContainerdAddr, ok, err := systemContainerdRunning(honorXDG) <ide> if err != nil { <ide> return nil, errors.Wrap(err, "could not determine whether the system containerd is running") <ide> } <ide><path>cmd/dockerd/docker.go <ide> import ( <ide> "github.com/docker/docker/pkg/jsonmessage" <ide> "github.com/docker/docker/pkg/reexec" <ide> "github.com/docker/docker/pkg/term" <add> "github.com/docker/docker/rootless" <ide> "github.com/moby/buildkit/util/apicaps" <ide> "github.com/sirupsen/logrus" <ide> "github.com/spf13/cobra" <ide> ) <ide> <add>var ( <add> honorXDG bool <add>) <add> <ide> func newDaemonCommand() (*cobra.Command, error) { <ide> opts := newDaemonOptions(config.New()) <ide> <ide> func init() { <ide> if dockerversion.ProductName != "" { <ide> apicaps.ExportedProduct = dockerversion.ProductName <ide> } <add> // When running with RootlessKit, $XDG_RUNTIME_DIR, $XDG_DATA_HOME, and $XDG_CONFIG_HOME needs to be <add> // honored as the default dirs, because we are unlikely to have permissions to access the system-wide <add> // directories. <add> // <add> // Note that even running with --rootless, when not running with RootlessKit, honorXDG needs to be kept false, <add> // because the system-wide directories in the current mount namespace are expected to be accessible. <add> // ("rootful" dockerd in rootless dockerd, #38702) <add> honorXDG = rootless.RunningWithRootlessKit() <ide> } <ide> <ide> func main() { <ide><path>docs/rootless.md <ide> penguin:231072:65536 <ide> You need to run `dockerd-rootless.sh` instead of `dockerd`. <ide> <ide> ```console <del>$ dockerd-rootless.sh --experimental --userland-proxy --userland-proxy-path=$(which rootlesskit-docker-proxy)" <add>$ dockerd-rootless.sh --experimental <ide> ``` <ide> As Rootless mode is experimental per se, currently you always need to run `dockerd-rootless.sh` with `--experimental`. <del>Also, to expose ports, you need to set `--userland-proxy-path` to the path of `rootlesskit-docker-proxy` binary. <ide> <ide> Remarks: <ide> * The socket path is set to `$XDG_RUNTIME_DIR/docker.sock` by default. `$XDG_RUNTIME_DIR` is typically set to `/run/user/$UID`. <ide><path>opts/hosts.go <ide> func ValidateHost(val string) (string, error) { <ide> } <ide> <ide> // ParseHost and set defaults for a Daemon host string. <del>// defaultToTLS is preferred over defaultToUnixRootless. <del>func ParseHost(defaultToTLS, defaultToUnixRootless bool, val string) (string, error) { <add>// defaultToTLS is preferred over defaultToUnixXDG. <add>func ParseHost(defaultToTLS, defaultToUnixXDG bool, val string) (string, error) { <ide> host := strings.TrimSpace(val) <ide> if host == "" { <ide> if defaultToTLS { <ide> host = DefaultTLSHost <del> } else if defaultToUnixRootless { <add> } else if defaultToUnixXDG { <ide> runtimeDir, err := homedir.GetRuntimeDir() <ide> if err != nil { <ide> return "", err <ide><path>rootless/rootless.go <ide> import ( <ide> "sync" <ide> ) <ide> <add>const ( <add> // RootlessKitDockerProxyBinary is the binary name of rootlesskit-docker-proxy <add> RootlessKitDockerProxyBinary = "rootlesskit-docker-proxy" <add>) <add> <ide> var ( <del> runningWithNonRootUsername bool <del> runningWithNonRootUsernameOnce sync.Once <add> runningWithRootlessKit bool <add> runningWithRootlessKitOnce sync.Once <ide> ) <ide> <del>// RunningWithNonRootUsername returns true if we $USER is set to a non-root value, <del>// regardless to the UID/EUID value. <del>// <del>// The value of this variable is mostly used for configuring default paths. <del>// If the value is true, $HOME and $XDG_RUNTIME_DIR should be honored for setting up the default paths. <del>// If false (not only EUID==0 but also $USER==root), $HOME and $XDG_RUNTIME_DIR should be ignored <del>// even if we are in a user namespace. <del>func RunningWithNonRootUsername() bool { <del> runningWithNonRootUsernameOnce.Do(func() { <del> u := os.Getenv("USER") <del> runningWithNonRootUsername = u != "" && u != "root" <add>// RunningWithRootlessKit returns true if running under RootlessKit namespaces. <add>func RunningWithRootlessKit() bool { <add> runningWithRootlessKitOnce.Do(func() { <add> u := os.Getenv("ROOTLESSKIT_STATE_DIR") <add> runningWithRootlessKit = u != "" <ide> }) <del> return runningWithNonRootUsername <add> return runningWithRootlessKit <ide> }
8
Text
Text
remove chris dickinson from active releasers
56f4f09aa8ca1386661fe4c85c02cb2d3ca9366f
<ide><path>README.md <ide> project. <ide> <ide> Releases of Node.js and io.js will be signed with one of the following GPG keys: <ide> <del>* **Chris Dickinson** &lt;[email protected]&gt; <del>`9554F04D7259F04124DE6B476D5A82AC7E37093B` <ide> * **Colin Ihrig** &lt;[email protected]&gt; <ide> `94AE36675C464D64BAFA68DD7434390BDBE9B9C5` <ide> * **Evan Lucas** &lt;[email protected]&gt; <ide> Releases of Node.js and io.js will be signed with one of the following GPG keys: <ide> The full set of trusted release keys can be imported by running: <ide> <ide> ```shell <del>gpg --keyserver pool.sks-keyservers.net --recv-keys 9554F04D7259F04124DE6B476D5A82AC7E37093B <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 94AE36675C464D64BAFA68DD7434390BDBE9B9C5 <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys FD3A5288F042B6850C66B31F09FE44734EB7990E <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 <ide> on what to do with these keys to verify that a downloaded file is official. <ide> Previous releases of Node.js have been signed with one of the following GPG <ide> keys: <ide> <add>* **Chris Dickinson** &lt;[email protected]&gt; <add>`9554F04D7259F04124DE6B476D5A82AC7E37093B` <ide> * **Isaac Z. Schlueter** &lt;[email protected]&gt; <ide> `93C7E9E91B49E432C2F75674B0A78B0A6C481CF6` <ide> * **Julien Gilli** &lt;[email protected]&gt;
1
Mixed
Python
add header and fix command
cd40f6564e5ffb81263de6afd4a531b84ad7eeba
<ide><path>examples/adversarial/README.md <ide> export HANS_DIR=path-to-hans <ide> export MODEL_TYPE=type-of-the-model-e.g.-bert-roberta-xlnet-etc <ide> export MODEL_PATH=path-to-the-model-directory-that-is-trained-on-NLI-e.g.-by-using-run_glue.py <ide> <del>python examples/adversarial/test_hans.py \ <add>python run_hans.py \ <ide> --task_name hans \ <ide> --model_type $MODEL_TYPE \ <ide> --do_eval \ <ide><path>examples/adversarial/run_hans.py <ide> def main(): <ide> output_eval_file = os.path.join(training_args.output_dir, "hans_predictions.txt") <ide> if trainer.is_world_master(): <ide> with open(output_eval_file, "w") as writer: <add> writer.write("pairID,gold_label\n") <ide> for pid, pred in zip(pair_ids, preds): <ide> writer.write("ex" + str(pid) + "," + label_list[int(pred)] + "\n") <ide>
2
PHP
PHP
add failing test for date_format and before/after
b929969bac9354f5a77116bea518da9ea99c2a4f
<ide><path>tests/Validation/ValidationValidatorTest.php <ide> public function testBeforeAndAfterWithFormat() <ide> $v = new Validator($trans, array('start' => '31/12/2012', 'ends' => '31/12/2000'), array('start' => 'date_format:d/m/Y|before:ends', 'ends' => 'date_format:d/m/Y|after:start')); <ide> $this->assertTrue($v->fails()); <ide> <add> $v = new Validator($trans, array('start' => 'invalid', 'ends' => 'invalid'), array('start' => 'date_format:d/m/Y|before:ends', 'ends' => 'date_format:d/m/Y|after:start')); <add> $this->assertTrue($v->fails()); <add> <ide> $v = new Validator($trans, array('x' => date('d/m/Y')), array('x' => 'date_format:d/m/Y|after:yesterday|before:tomorrow')); <ide> $this->assertTrue($v->passes()); <ide>
1
Python
Python
set version to v3.0.0.dev12
67928036f2e12e886fe6f4334393d53ffedfedb2
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy" <del>__version__ = "3.0.0.dev11" <add>__version__ = "3.0.0.dev12" <ide> __release__ = True <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
1
Python
Python
fix lint errors
9980d03a4edafd92606d0ec762ee786a8c7f590d
<ide><path>libcloud/compute/drivers/openstack.py <ide> def __init__(self, *args, **kwargs): <ide> # We run the init once to get the Glance V2 API connection <ide> # and put that on the object under self.image_connection. <ide> self._ex_force_base_url = str(kwargs.pop('ex_force_image_url', <del> None)) <add> None)) <ide> kwargs['ex_force_base_url'] = self._ex_force_base_url <ide> self.connectionCls = self.image_connectionCls <ide> super(OpenStack_2_NodeDriver, self).__init__(*args, **kwargs) <ide> def __init__(self, *args, **kwargs): <ide> # We run the init once to get the Neutron V2 API connection <ide> # and put that on the object under self.image_connection. <ide> self._ex_force_base_url = str(kwargs.pop('ex_force_network_url', <del> None)) <add> None)) <ide> kwargs['ex_force_base_url'] = self._ex_force_base_url <ide> self.connectionCls = self.network_connectionCls <ide> super(OpenStack_2_NodeDriver, self).__init__(*args, **kwargs) <ide> def ex_accept_image_member(self, image_id, member_id): <ide> ) <ide> return self._to_image_member(response.object) <ide> <del> <ide> def _to_networks(self, obj): <ide> networks = obj['networks'] <ide> return [self._to_network(network) for network in networks] <ide> def ex_list_networks(self): <ide> <ide> :rtype: ``list`` of :class:`OpenStackNetwork` <ide> """ <del> response = self.network_connection.request(self._networks_url_prefix).object <add> response = self.network_connection.request( <add> self._networks_url_prefix).object <ide> return self._to_networks(response) <ide> <ide> def _to_subnets(self, obj): <ide> def ex_list_subnets(self): <ide> <ide> :rtype: ``list`` of :class:`OpenStack_2_SubNet` <ide> """ <del> response = self.network_connection.request(self._subnets_url_prefix).object <add> response = self.network_connection.request( <add> self._subnets_url_prefix).object <ide> return self._to_subnets(response) <ide> <ide> <ide> def __init__(self, id, name, cidr, driver, extra=None): <ide> def __repr__(self): <ide> return '<OpenStack_2_SubNet id="%s" name="%s" cidr="%s">' % (self.id, <ide> self.name, <del> self.cidr) <ide>\ No newline at end of file <add> self.cidr)
1
Python
Python
add cinder support libcloud-874
bd8318b53676f84e91ed775dc174545f00ac834b
<ide><path>libcloud/test/compute/test_openstack.py <ide> def _v2_1337_volumes_detail(self, method, url, body, headers): <ide> def _v2_1337_volumes(self, method, url, body, headers): <ide> if method == 'POST': <ide> body = self.fixtures.load('_v2_0__volume.json') <del> return (httplib.OK, body, self.json_content_headers, httplib.responses[httplib.OK]) <add> return (httplib.CREATED, body, self.json_content_headers, httplib.responses[httplib.OK]) <ide> <ide> def _v2_1337_volumes_cd76a3a1_c4ce_40f6_9b9f_07a61508938d(self, method, url, body, headers): <ide> if method == 'GET': <ide> def _v2_1337_snapshots_detail(self, method, url, body, headers): <ide> def _v2_1337_snapshots(self, method, url, body, headers): <ide> if method == 'POST': <ide> body = self.fixtures.load('_v2_0__snapshot.json') <del> return (httplib.OK, body, self.json_content_headers, httplib.responses[httplib.OK]) <add> return (httplib.CREATED, body, self.json_content_headers, httplib.responses[httplib.OK]) <ide> <ide> def _v2_1337_snapshots_3fbbcccf_d058_4502_8844_6feeffdf4cb5(self, method, url, body, headers): <ide> if method == 'GET':
1
PHP
PHP
fixate the sort for an association
efdcef56cad818df01c8eb291bead6a267e405f5
<ide><path>tests/TestCase/ORM/QueryTest.php <ide> public function testHasManyEagerLoadingFromSecondaryTable($strategy) <ide> $article = TableRegistry::get('articles'); <ide> $post = TableRegistry::get('posts'); <ide> <del> $author->hasMany('posts', compact('strategy')); <add> $author->hasMany('posts', [ <add> 'sort' => ['posts.id' => 'ASC'], <add> 'strategy' => $strategy <add> ]); <ide> $article->belongsTo('authors'); <ide> <ide> $query = new Query($this->connection, $article);
1
Text
Text
update changelog for 0.68.1
e331b64ea666c635c768a95bb3b310b887f86582
<ide><path>CHANGELOG.md <ide> # Changelog <ide> <add>## v0.68.1 <add> <add>### Changed <add> <add>#### Android specific <add> <add>- Bump React Native Gradle plugin to 0.0.6 ([9573d7b84d](https://github.com/facebook/react-native/commit/9573d7b84d35233fbb39a4067cfef65490aa34a7) by [@cortinico](https://github.com/cortinico)) <add>- Don't require yarn for codegen tasks ([d5da70e17e](https://github.com/facebook/react-native/commit/d5da70e17e8c8210cd79a4d7b09c6a5ded4b5607) by [@danilobuerger](https://github.com/danilobuerger)) <add> <add>### Fixed <add> <add>- Fix dynamic_cast (RTTI) by adding key function to ShadowNodeWrapper and related classes ([58a2eb7f37](https://github.com/facebook/react-native/commit/58a2eb7f37c2dc27ad3575618778ad5b23599b27) by [@kmagiera](https://github.com/kmagiera)) <add>- Pin use-subscription to < 1.6.0 ([5534634892](https://github.com/facebook/react-native/commit/5534634892f47a3890e58b661faa2260373acb25) by [@danilobuerger](https://github.com/danilobuerger)) <add> <add>#### Android specific <add> <add>- Use NDK 23 only for Windows users. ([e48a580080](https://github.com/facebook/react-native/commit/e48a580080bdae58b375f30fbcf8a83cc1915b2f) by [@cortinico](https://github.com/cortinico)) <add>- Improve support for Android users on M1 machine ([4befd2a29c](https://github.com/facebook/react-native/commit/4befd2a29cb94b026d9c048a041aa9f1817295b5) by [@cortinico](https://github.com/cortinico)) <add>- Template: Specify abiFilters if enableSeparateBuildPerCPUArchitecture is not set. ([5dff920177](https://github.com/facebook/react-native/commit/5dff920177220ae5f4e37c662c63c27ebf696c83) by [@cortinico](https://github.com/cortinico)) <add>- Fix for building new architecture sources on Windows ([5a8033df98](https://github.com/facebook/react-native/commit/5a8033df98296c941b0a57e49f2349e252339bf9) by [@mganandraj](https://github.com/mganandraj)) <add> <ide> ## v0.68.0 <ide> <ide> ### Breaking Changes
1
PHP
PHP
fix unstable test
e5c49792fec134ac22df3f670c149c5a986470a2
<ide><path>tests/TestCase/Network/Http/Adapter/StreamTest.php <ide> public function stream_open($path, $mode, $options, &$openedPath) <ide> } <ide> <ide> $this->_stream = fopen('php://memory', 'rb+'); <del> fwrite($this->_stream, str_repeat('x', 10000)); <add> fwrite($this->_stream, str_repeat('x', 20000)); <ide> rewind($this->_stream); <ide> <ide> return true; <ide> public function testSendByUsingCakephpProtocol() <ide> $responses = $stream->send($request, []); <ide> $this->assertInstanceOf('Cake\Network\Http\Response', $responses[0]); <ide> <del> $this->assertEquals(10000, strlen($responses[0]->body())); <add> $this->assertEquals(20000, strlen($responses[0]->body())); <ide> } <ide> <ide> /**
1
Javascript
Javascript
fix typographical error
5b8b92499550aa5d48254237ca3cff5642d5dcca
<ide><path>test/parallel/test-http-agent-timeout.js <ide> const http = require('http'); <ide> } <ide> <ide> { <del> // Ensure that timeouted sockets are not reused. <add> // Ensure that timed-out sockets are not reused. <ide> <ide> const agent = new http.Agent({ keepAlive: true, timeout: 50 }); <ide> <ide><path>test/sequential/test-tls-psk-client.js <ide> const cleanUp = (err) => { <ide> process.exitCode = err ? 1 : 0; <ide> }; <ide> <del>const timeout = setTimeout(() => cleanUp('Timeouted'), 5000); <add>const timeout = setTimeout(() => cleanUp('Timed out'), 5000); <ide> <ide> function waitForPort(port, cb) { <ide> const socket = net.connect(common.PORT, () => {
2
Text
Text
update one more command in crypto.md
5efbe4c1e8f9baf4251c40c52ca9452d8f7416ce
<ide><path>doc/api/crypto.md <ide> Optional `options` argument controls stream behavior. <ide> <ide> The `algorithm` is dependent on the available algorithms supported by the <ide> version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. <del>On recent releases of OpenSSL, `openssl list-message-digest-algorithms` will <add>On recent releases of OpenSSL, `openssl list -digest-algorithms` <add>(`openssl list-message-digest-algorithms` for older versions of OpenSSL) will <ide> display the available digest algorithms. <ide> <ide> The `key` is the HMAC key used to generate the cryptographic HMAC hash.
1
Mixed
Javascript
add prependlistener() and prependoncelistener()
0e7d57af3573b4dcba81217bba2f041dbdc173dc
<ide><path>doc/api/events.md <ide> console.log(util.inspect(server.listeners('connection'))); <ide> <ide> ### emitter.on(eventName, listener) <ide> <add>* `eventName` {string|Symbol} The name of the event. <add>* `listener` {Function} The callback function <add> <ide> Adds the `listener` function to the end of the listeners array for the <ide> event named `eventName`. No checks are made to see if the `listener` has <ide> already been added. Multiple calls passing the same combination of `eventName` <ide> server.on('connection', (stream) => { <ide> <ide> Returns a reference to the `EventEmitter` so calls can be chained. <ide> <add>By default, event listeners are invoked in the order they are added. The <add>`emitter.prependListener()` method can be used as an alternative to add the <add>event listener to the beginning of the listeners array. <add> <add>```js <add>const myEE = new EventEmitter(); <add>myEE.on('foo', () => console.log('a')); <add>myEE.prependListener('foo', () => console.log('b')); <add>myEE.emit('foo'); <add> // Prints: <add> // b <add> // a <add>``` <add> <ide> ### emitter.once(eventName, listener) <ide> <add>* `eventName` {string|Symbol} The name of the event. <add>* `listener` {Function} The callback function <add> <ide> Adds a **one time** `listener` function for the event named `eventName`. This <ide> listener is invoked only the next time `eventName` is triggered, after which <ide> it is removed. <ide> server.once('connection', (stream) => { <ide> <ide> Returns a reference to the `EventEmitter` so calls can be chained. <ide> <add>By default, event listeners are invoked in the order they are added. The <add>`emitter.prependOnceListener()` method can be used as an alternative to add the <add>event listener to the beginning of the listeners array. <add> <add>```js <add>const myEE = new EventEmitter(); <add>myEE.once('foo', () => console.log('a')); <add>myEE.prependOnceListener('foo', () => console.log('b')); <add>myEE.emit('foo'); <add> // Prints: <add> // b <add> // a <add>``` <add> <add>### emitter.prependListener(eventName, listener) <add> <add>* `eventName` {string|Symbol} The name of the event. <add>* `listener` {Function} The callback function <add> <add>Adds the `listener` function to the *beginning* of the listeners array for the <add>event named `eventName`. No checks are made to see if the `listener` has <add>already been added. Multiple calls passing the same combination of `eventName` <add>and `listener` will result in the `listener` being added, and called, multiple <add>times. <add> <add>```js <add>server.prependListener('connection', (stream) => { <add> console.log('someone connected!'); <add>}); <add>``` <add> <add>Returns a reference to the `EventEmitter` so calls can be chained. <add> <add>### emitter.prependOnceListener(eventName, listener) <add> <add>* `eventName` {string|Symbol} The name of the event. <add>* `listener` {Function} The callback function <add> <add>Adds a **one time** `listener` function for the event named `eventName` to the <add>*beginning* of the listeners array. This listener is invoked only the next time <add>`eventName` is triggered, after which it is removed. <add> <add>```js <add>server.prependOnceListener('connection', (stream) => { <add> console.log('Ah, we have our first user!'); <add>}); <add>``` <add> <add>Returns a reference to the `EventEmitter` so calls can be chained. <add> <ide> ### emitter.removeAllListeners([eventName]) <ide> <ide> Removes all listeners, or those of the specified `eventName`. <ide><path>lib/_stream_readable.js <ide> var StringDecoder; <ide> <ide> util.inherits(Readable, Stream); <ide> <add>const hasPrependListener = typeof EE.prototype.prependListener === 'function'; <add> <add>function prependListener(emitter, event, fn) { <add> if (hasPrependListener) <add> return emitter.prependListener(event, fn); <add> <add> // This is a brutally ugly hack to make sure that our error handler <add> // is attached before any userland ones. NEVER DO THIS. This is here <add> // only because this code needs to continue to work with older versions <add> // of Node.js that do not include the prependListener() method. The goal <add> // is to eventually remove this hack. <add> if (!emitter._events || !emitter._events[event]) <add> emitter.on(event, fn); <add> else if (Array.isArray(emitter._events[event])) <add> emitter._events[event].unshift(fn); <add> else <add> emitter._events[event] = [fn, emitter._events[event]]; <add>} <add> <ide> function ReadableState(options, stream) { <ide> options = options || {}; <ide> <ide> Readable.prototype.pipe = function(dest, pipeOpts) { <ide> if (EE.listenerCount(dest, 'error') === 0) <ide> dest.emit('error', er); <ide> } <del> // This is a brutally ugly hack to make sure that our error handler <del> // is attached before any userland ones. NEVER DO THIS. <del> if (!dest._events || !dest._events.error) <del> dest.on('error', onerror); <del> else if (Array.isArray(dest._events.error)) <del> dest._events.error.unshift(onerror); <del> else <del> dest._events.error = [onerror, dest._events.error]; <ide> <add> // Make sure our error handler is attached before userland ones. <add> prependListener(dest, 'error', onerror); <ide> <ide> // Both close and finish should trigger unpipe, but only once. <ide> function onclose() { <ide><path>lib/events.js <ide> EventEmitter.prototype.emit = function emit(type) { <ide> return true; <ide> }; <ide> <del>EventEmitter.prototype.addListener = function addListener(type, listener) { <add>function _addListener(target, type, listener, prepend) { <ide> var m; <ide> var events; <ide> var existing; <ide> <ide> if (typeof listener !== 'function') <ide> throw new TypeError('"listener" argument must be a function'); <ide> <del> events = this._events; <add> events = target._events; <ide> if (!events) { <del> events = this._events = new EventHandlers(); <del> this._eventsCount = 0; <add> events = target._events = new EventHandlers(); <add> target._eventsCount = 0; <ide> } else { <ide> // To avoid recursion in the case that type === "newListener"! Before <ide> // adding it to the listeners, first emit "newListener". <ide> if (events.newListener) { <del> this.emit('newListener', type, <del> listener.listener ? listener.listener : listener); <add> target.emit('newListener', type, <add> listener.listener ? listener.listener : listener); <ide> <ide> // Re-assign `events` because a newListener handler could have caused the <ide> // this._events to be assigned to a new object <del> events = this._events; <add> events = target._events; <ide> } <ide> existing = events[type]; <ide> } <ide> <ide> if (!existing) { <ide> // Optimize the case of one listener. Don't need the extra array object. <ide> existing = events[type] = listener; <del> ++this._eventsCount; <add> ++target._eventsCount; <ide> } else { <ide> if (typeof existing === 'function') { <ide> // Adding the second element, need to change to array. <del> existing = events[type] = [existing, listener]; <add> existing = events[type] = prepend ? [listener, existing] : <add> [existing, listener]; <ide> } else { <ide> // If we've already got an array, just append. <del> existing.push(listener); <add> if (prepend) { <add> existing.unshift(listener); <add> } else { <add> existing.push(listener); <add> } <ide> } <ide> <ide> // Check for listener leak <ide> if (!existing.warned) { <del> m = $getMaxListeners(this); <add> m = $getMaxListeners(target); <ide> if (m && m > 0 && existing.length > m) { <ide> existing.warned = true; <ide> process.emitWarning('Possible EventEmitter memory leak detected. ' + <ide> EventEmitter.prototype.addListener = function addListener(type, listener) { <ide> } <ide> } <ide> <del> return this; <add> return target; <add>} <add> <add>EventEmitter.prototype.addListener = function addListener(type, listener) { <add> return _addListener(this, type, listener, false); <ide> }; <ide> <ide> EventEmitter.prototype.on = EventEmitter.prototype.addListener; <ide> <del>EventEmitter.prototype.once = function once(type, listener) { <del> if (typeof listener !== 'function') <del> throw new TypeError('"listener" argument must be a function'); <add>EventEmitter.prototype.prependListener = <add> function prependListener(type, listener) { <add> return _addListener(this, type, listener, true); <add> }; <ide> <add>function _onceWrap(target, type, listener) { <ide> var fired = false; <del> <ide> function g() { <del> this.removeListener(type, g); <del> <add> target.removeListener(type, g); <ide> if (!fired) { <ide> fired = true; <del> listener.apply(this, arguments); <add> listener.apply(target, arguments); <ide> } <ide> } <del> <ide> g.listener = listener; <del> this.on(type, g); <add> return g; <add>} <ide> <add>EventEmitter.prototype.once = function once(type, listener) { <add> if (typeof listener !== 'function') <add> throw new TypeError('"listener" argument must be a function'); <add> this.on(type, _onceWrap(this, type, listener)); <ide> return this; <ide> }; <ide> <add>EventEmitter.prototype.prependOnceListener = <add> function prependOnceListener(type, listener) { <add> if (typeof listener !== 'function') <add> throw new TypeError('"listener" argument must be a function'); <add> this.prependListener(type, _onceWrap(this, type, listener)); <add> return this; <add> }; <add> <ide> // emits a 'removeListener' event iff the listener was removed <ide> EventEmitter.prototype.removeListener = <ide> function removeListener(type, listener) { <ide><path>test/parallel/test-event-emitter-prepend.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const EventEmitter = require('events'); <add>const assert = require('assert'); <add> <add>const myEE = new EventEmitter(); <add>var m = 0; <add>// This one comes last. <add>myEE.on('foo', common.mustCall(() => assert.equal(m, 2))); <add> <add>// This one comes second. <add>myEE.prependListener('foo', common.mustCall(() => assert.equal(m++, 1))); <add> <add>// This one comes first. <add>myEE.prependOnceListener('foo', common.mustCall(() => assert.equal(m++, 0))); <add> <add>myEE.emit('foo'); <add> <add> <add>// Test fallback if prependListener is undefined. <add>const stream = require('stream'); <add>const util = require('util'); <add> <add>delete EventEmitter.prototype.prependListener; <add> <add>function Writable() { <add> this.writable = true; <add> stream.Stream.call(this); <add>} <add>util.inherits(Writable, stream.Stream); <add> <add>function Readable() { <add> this.readable = true; <add> stream.Stream.call(this); <add>} <add>util.inherits(Readable, stream.Stream); <add> <add>const w = new Writable(); <add>const r = new Readable(); <add>r.pipe(w);
4
Ruby
Ruby
use only strings in env.x11
28c1c4ee15acb6c3a7e7c8bad855e66d9d49b585
<ide><path>Library/Homebrew/extend/ENV/std.rb <ide> def libxml2 <ide> <ide> def x11 <ide> # There are some config scripts here that should go in the PATH <del> append_path 'PATH', MacOS::X11.bin <add> append_path "PATH", MacOS::X11.bin.to_s <ide> <ide> # Append these to PKG_CONFIG_LIBDIR so they are searched <ide> # *after* our own pkgconfig directories, as we dupe some of the <ide> # libs in XQuartz. <del> append_path 'PKG_CONFIG_LIBDIR', MacOS::X11.lib/'pkgconfig' <del> append_path 'PKG_CONFIG_LIBDIR', MacOS::X11.share/'pkgconfig' <add> append_path "PKG_CONFIG_LIBDIR", "#{MacOS::X11.lib}/pkgconfig" <add> append_path "PKG_CONFIG_LIBDIR", "#{MacOS::X11.share}/pkgconfig" <ide> <del> append 'LDFLAGS', "-L#{MacOS::X11.lib}" <del> append_path 'CMAKE_PREFIX_PATH', MacOS::X11.prefix <del> append_path 'CMAKE_INCLUDE_PATH', MacOS::X11.include <del> append_path 'CMAKE_INCLUDE_PATH', MacOS::X11.include/'freetype2' <add> append "LDFLAGS", "-L#{MacOS::X11.lib}" <add> append_path "CMAKE_PREFIX_PATH", MacOS::X11.prefix.to_s <add> append_path "CMAKE_INCLUDE_PATH", MacOS::X11.include.to_s <add> append_path "CMAKE_INCLUDE_PATH", "#{MacOS::X11.include}/freetype2" <ide> <del> append 'CPPFLAGS', "-I#{MacOS::X11.include}" <del> append 'CPPFLAGS', "-I#{MacOS::X11.include}/freetype2" <add> append "CPPFLAGS", "-I#{MacOS::X11.include}" <add> append "CPPFLAGS", "-I#{MacOS::X11.include}/freetype2" <ide> <del> append_path 'ACLOCAL_PATH', MacOS::X11.share/'aclocal' <add> append_path "ACLOCAL_PATH", "#{MacOS::X11.share}/aclocal" <ide> <ide> if MacOS::XQuartz.provided_by_apple? and not MacOS::CLT.installed? <del> append_path 'CMAKE_PREFIX_PATH', MacOS.sdk_path/'usr/X11' <add> append_path "CMAKE_PREFIX_PATH", "#{MacOS.sdk_path}/usr/X11" <ide> end <ide> <del> append 'CFLAGS', "-I#{MacOS::X11.include}" unless MacOS::CLT.installed? <add> append "CFLAGS", "-I#{MacOS::X11.include}" unless MacOS::CLT.installed? <ide> end <ide> alias_method :libpng, :x11 <ide>
1
Ruby
Ruby
add subscriber to actionmailer
2a6bc1263e99060897b53a8c806916d198eab572
<ide><path>actionmailer/lib/action_mailer/base.rb <ide> def method_missing(method_symbol, *parameters) #:nodoc: <ide> # end <ide> # end <ide> def receive(raw_email) <del> logger.info "Received mail:\n #{raw_email}" unless logger.nil? <ide> mail = Mail.new(raw_email) <del> new.receive(mail) <add> ActiveSupport::Notifications.instrument("action_mailer.receive", :mail => mail) do <add> new.receive(mail) <add> end <ide> end <ide> <ide> # Deliver the given mail object directly. This can be used to deliver <ide> def process(method_name, *args) <ide> def deliver!(mail = @mail) <ide> raise "no mail object available for delivery!" unless mail <ide> <del> if logger <del> logger.info "Sent mail to #{Array(recipients).join(', ')}" <del> logger.debug "\n#{mail.encoded}" <del> end <del> <del> ActiveSupport::Notifications.instrument("action_mailer.deliver", :mail => self) do <del> begin <add> begin <add> ActiveSupport::Notifications.instrument("action_mailer.deliver", <add> :mail => @mail, :mailer => self) do <ide> self.delivery_method.perform_delivery(mail) if perform_deliveries <del> rescue Exception => e # Net::SMTP errors or sendmail pipe errors <del> raise e if raise_delivery_errors <ide> end <add> rescue Exception => e # Net::SMTP errors or sendmail pipe errors <add> raise e if raise_delivery_errors <ide> end <ide> <ide> mail <ide><path>actionmailer/lib/action_mailer/railtie.rb <ide> module ActionMailer <ide> class Railtie < Rails::Railtie <ide> plugin_name :action_mailer <ide> <add> require "action_mailer/railties/subscriber" <add> subscriber ActionMailer::Railties::Subscriber.new <add> <ide> initializer "action_mailer.set_configs" do |app| <ide> app.config.action_mailer.each do |k,v| <ide> ActionMailer::Base.send "#{k}=", v <ide><path>actionmailer/lib/action_mailer/railties/subscriber.rb <add>module ActionMailer <add> module Railties <add> class Subscriber < Rails::Subscriber <add> def deliver(event) <add> recipients = Array(event.payload[:mailer].recipients).join(', ') <add> info("Sent mail to #{recipients} (%1.fms)" % event.duration) <add> debug("\n#{event.payload[:mail].encoded}") <add> end <add> <add> def receive(event) <add> info("Received mail (%.1fms)" % event.duration) <add> debug("\n#{event.payload[:mail].encoded}") <add> end <add> <add> def logger <add> ActionMailer::Base.logger <add> end <add> end <add> end <add>end <ide>\ No newline at end of file <ide><path>actionmailer/test/mail_service_test.rb <ide> def test_performs_delivery_via_sendmail <ide> TestMailer.deliver_signed_up(@recipient) <ide> end <ide> <del> class FakeLogger <del> attr_reader :info_contents, :debug_contents <del> <del> def initialize <del> @info_contents, @debug_contents = "", "" <del> end <del> <del> def info(str = nil, &blk) <del> @info_contents << str if str <del> @info_contents << blk.call if block_given? <del> end <del> <del> def debug(str = nil, &blk) <del> @debug_contents << str if str <del> @debug_contents << blk.call if block_given? <del> end <del> end <del> <del> def test_delivery_logs_sent_mail <del> mail = TestMailer.create_signed_up(@recipient) <del> # logger = mock() <del> # logger.expects(:info).with("Sent mail to #{@recipient}") <del> # logger.expects(:debug).with("\n#{mail.encoded}") <del> TestMailer.logger = FakeLogger.new <del> TestMailer.deliver_signed_up(@recipient) <del> assert(TestMailer.logger.info_contents =~ /Sent mail to #{@recipient}/) <del> expected = TestMailer.logger.debug_contents <del> actual = "\n#{mail.encoded}" <del> expected.gsub!(/Message-ID:.*\r\n/, "Message-ID: <123@456>\r\n") <del> actual.gsub!(/Message-ID:.*\r\n/, "Message-ID: <123@456>\r\n") <del> <del> assert_equal(expected, actual) <del> end <del> <ide> def test_unquote_quoted_printable_subject <ide> msg = <<EOF <ide> From: [email protected] <ide><path>actionmailer/test/subscriber_test.rb <add>require "abstract_unit" <add>require "rails/subscriber/test_helper" <add>require "action_mailer/railties/subscriber" <add> <add>module SubscriberTest <add> Rails::Subscriber.add(:action_mailer, ActionMailer::Railties::Subscriber.new) <add> <add> class TestMailer < ActionMailer::Base <add> def basic <add> recipients "[email protected]" <add> subject "basic" <add> from "[email protected]" <add> render :text => "Hello world" <add> end <add> <add> def receive(mail) <add> # Do nothing <add> end <add> end <add> <add> def set_logger(logger) <add> ActionMailer::Base.logger = logger <add> end <add> <add> def test_deliver_is_notified <add> TestMailer.deliver_basic <add> wait <add> assert_equal 1, @logger.logged(:info).size <add> assert_match /Sent mail to [email protected]/, @logger.logged(:info).first <add> assert_equal 1, @logger.logged(:debug).size <add> assert_match /Hello world/, @logger.logged(:debug).first <add> end <add> <add> def test_receive_is_notifier <add> fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email") <add> TestMailer.receive(fixture) <add> wait <add> assert_equal 1, @logger.logged(:info).size <add> assert_match /Received mail/, @logger.logged(:info).first <add> assert_equal 1, @logger.logged(:debug).size <add> assert_match /Jamis/, @logger.logged(:debug).first <add> end <add> <add> class SyncSubscriberTest < ActionMailer::TestCase <add> include Rails::Subscriber::SyncTestHelper <add> include SubscriberTest <add> end <add> <add> class AsyncSubscriberTest < ActionMailer::TestCase <add> include Rails::Subscriber::AsyncTestHelper <add> include SubscriberTest <add> end <add>end <ide>\ No newline at end of file
5
Text
Text
add anonrig to collaborators
bda460df9403cd749ca93d11f1cb067c764dcdd0
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Anna Henningsen** <<[email protected]>> (she/her) <ide> * [aduh95](https://github.com/aduh95) - <ide> **Antoine du Hamel** <<[email protected]>> (he/him) <add>* [anonrig](https://github.com/anonrig) - <add> **Yagiz Nizipli** <<[email protected]>> (he/him) <ide> * [antsmartian](https://github.com/antsmartian) - <ide> **Anto Aravinth** <<[email protected]>> (he/him) <ide> * [apapirovski](https://github.com/apapirovski) -
1
Python
Python
return none when not masking embedding
42497d9fda537b5abc70088bfd3656fc92b5c9ab
<ide><path>keras/layers/embeddings.py <ide> def __init__(self, input_dim, output_dim, init='uniform', <ide> def get_output_mask(self, train=None): <ide> X = self.get_input(train) <ide> if not self.mask_zero: <del> return T.ones_like(X) <add> return None <ide> else: <ide> return T.ones_like(X) * (1 - T.eq(X,0)) <ide>
1
Javascript
Javascript
add tests for noop enaled and cancel methods
97a1b399b727ebb7f5c4b3ae690c4641731943df
<ide><path>src/ng/animate.js <ide> var $AnimateProvider = ['$provide', function($provide) { <ide> // only serve one instance of a promise in order to save CPU cycles <ide> if (!currentDefer) { <ide> currentDefer = $$q.defer(); <del> currentDefer.promise.cancel = noop; //ngAnimate.$animate provides this <ide> $$asyncCallback(function() { <ide> currentDefer.resolve(); <ide> currentDefer = null; <ide><path>test/ng/animateSpec.js <ide> describe("$animate", function() { <ide> expect($animate.leave(element)).toBeAPromise(); <ide> })); <ide> <add> it("should provide noop `enabled` and `cancel` methods", inject(function($animate) { <add> expect($animate.enabled).toBe(angular.noop); <add> expect($animate.enabled()).toBeUndefined(); <add> <add> expect($animate.cancel).toBe(angular.noop); <add> expect($animate.cancel()).toBeUndefined(); <add> })); <add> <ide> it("should add and remove classes on SVG elements", inject(function($animate) { <ide> if (!window.SVGElement) return; <ide> var svg = jqLite('<svg><rect></rect></svg>');
2
Python
Python
remove distutils usages for python 3.10
e4888a061f2f657a3329786a68beca9f824b2f8e
<ide><path>airflow/configuration.py <ide> # Ignored Mypy on configparser because it thinks the configparser module has no _UNSET attribute <ide> from configparser import _UNSET, ConfigParser, NoOptionError, NoSectionError # type: ignore <ide> from json.decoder import JSONDecodeError <del>from typing import Any, Dict, List, Optional, Union <add>from typing import Any, Dict, List, Optional, Tuple, Union <ide> <ide> from airflow.exceptions import AirflowConfigException <ide> from airflow.secrets import DEFAULT_SECRETS_SEARCH_PATH, BaseSecretsBackend <ide> warnings.filterwarnings(action='default', category=DeprecationWarning, module='airflow') <ide> warnings.filterwarnings(action='default', category=PendingDeprecationWarning, module='airflow') <ide> <add>_SQLITE3_VERSION_PATTERN = re.compile(r"(?P<version>^\d+(?:\.\d+)*)\D?.*$") <add> <add> <add>def _parse_sqlite_version(s: str) -> Tuple[int, ...]: <add> match = _SQLITE3_VERSION_PATTERN.match(s) <add> if match is None: <add> return () <add> return tuple(int(p) for p in match.group("version").split(".")) <add> <ide> <ide> def expand_env_var(env_var): <ide> """ <ide> def _validate_config_dependencies(self): <ide> raise AirflowConfigException(f"error: cannot use sqlite with the {self.get('core', 'executor')}") <ide> if is_sqlite: <ide> import sqlite3 <del> from distutils.version import StrictVersion <ide> <ide> from airflow.utils.docs import get_docs_url <ide> <ide> # Some of the features in storing rendered fields require sqlite version >= 3.15.0 <del> min_sqlite_version = '3.15.0' <del> if StrictVersion(sqlite3.sqlite_version) < StrictVersion(min_sqlite_version): <add> min_sqlite_version = (3, 15, 0) <add> if _parse_sqlite_version(sqlite3.sqlite_version) < min_sqlite_version: <add> min_sqlite_version_str = ".".join(str(s) for s in min_sqlite_version) <ide> raise AirflowConfigException( <del> f"error: sqlite C library version too old (< {min_sqlite_version}). " <add> f"error: sqlite C library version too old (< {min_sqlite_version_str}). " <ide> f"See {get_docs_url('howto/set-up-database.html#setting-up-a-sqlite-database')}" <ide> ) <ide> <ide><path>airflow/operators/sql.py <ide> # KIND, either express or implied. See the License for the <ide> # specific language governing permissions and limitations <ide> # under the License. <del>from distutils.util import strtobool <ide> from typing import Any, Dict, Iterable, List, Mapping, Optional, SupportsAbs, Union <ide> <ide> from airflow.compat.functools import cached_property <ide> from airflow.models import BaseOperator, SkipMixin <ide> <ide> <add>def parse_boolean(val: str) -> Union[str, bool]: <add> """Try to parse a string into boolean. <add> <add> Raises ValueError if the input is not a valid true- or false-like string value. <add> """ <add> val = val.lower() <add> if val in ('y', 'yes', 't', 'true', 'on', '1'): <add> return True <add> if val in ('n', 'no', 'f', 'false', 'off', '0'): <add> return False <add> raise ValueError(f"{val!r} is not a boolean-like string value") <add> <add> <ide> class BaseSQLOperator(BaseOperator): <ide> """ <ide> This is a base class for generic SQL Operator to get a DB Hook <ide> def execute(self, context: Dict): <ide> follow_branch = self.follow_task_ids_if_true <ide> elif isinstance(query_result, str): <ide> # return result is not Boolean, try to convert from String to Boolean <del> if bool(strtobool(query_result)): <add> if parse_boolean(query_result): <ide> follow_branch = self.follow_task_ids_if_true <ide> elif isinstance(query_result, int): <ide> if bool(query_result): <ide><path>airflow/providers/jenkins/hooks/jenkins.py <ide> # under the License. <ide> # <ide> <del>from distutils.util import strtobool <del> <ide> import jenkins <ide> <ide> from airflow.hooks.base import BaseHook <add>from airflow.utils.strings import to_boolean <ide> <ide> <ide> class JenkinsHook(BaseHook): <ide> def __init__(self, conn_id: str = default_conn_name) -> None: <ide> self.connection = connection <ide> connection_prefix = 'http' <ide> # connection.extra contains info about using https (true) or http (false) <del> if connection.extra is None or connection.extra == '': <del> connection.extra = 'false' <del> # set a default value to connection.extra <del> # to avoid rising ValueError in strtobool <del> if strtobool(connection.extra): <add> if to_boolean(connection.extra): <ide> connection_prefix = 'https' <ide> url = f'{connection_prefix}://{connection.host}:{connection.port}' <ide> self.log.info('Trying to connect to %s', url) <ide><path>airflow/providers/tableau/hooks/tableau.py <ide> # under the License. <ide> import time <ide> import warnings <del>from distutils.util import strtobool <ide> from enum import Enum <del>from typing import Any, Optional <add>from typing import Any, Optional, Union <ide> <ide> from tableauserverclient import Pager, PersonalAccessTokenAuth, Server, TableauAuth <ide> from tableauserverclient.server import Auth <ide> from airflow.hooks.base import BaseHook <ide> <ide> <add>def parse_boolean(val: str) -> Union[str, bool]: <add> """Try to parse a string into boolean. <add> <add> The string is returned as-is if it does not look like a boolean value. <add> """ <add> val = val.lower() <add> if val in ('y', 'yes', 't', 'true', 'on', '1'): <add> return True <add> if val in ('n', 'no', 'f', 'false', 'off', '0'): <add> return False <add> return val <add> <add> <ide> class TableauJobFailedException(AirflowException): <ide> """An exception that indicates that a Job failed to complete.""" <ide> <ide> def __init__(self, site_id: Optional[str] = None, tableau_conn_id: str = default <ide> self.conn = self.get_connection(self.tableau_conn_id) <ide> self.site_id = site_id or self.conn.extra_dejson.get('site_id', '') <ide> self.server = Server(self.conn.host) <del> verify = self.conn.extra_dejson.get('verify', True) <add> verify: Any = self.conn.extra_dejson.get('verify', True) <ide> if isinstance(verify, str): <del> try: <del> verify = bool(strtobool(verify)) <del> except ValueError: <del> pass <add> verify = parse_boolean(verify) <ide> self.server.add_http_options( <ide> options_dict={'verify': verify, 'cert': self.conn.extra_dejson.get('cert', None)} <ide> ) <ide><path>airflow/utils/strings.py <ide> <ide> import string <ide> from random import choice <add>from typing import Optional <ide> <ide> <ide> def get_random_string(length=8, choices=string.ascii_letters + string.digits): <ide> """Generate random string""" <ide> return ''.join(choice(choices) for _ in range(length)) <ide> <ide> <del>def to_boolean(astring): <del> """Convert a string to a boolean""" <del> return False if astring is None else astring.lower() in ['true', 't', 'y', 'yes', '1'] <add>TRUE_LIKE_VALUES = {"on", "t", "true", "y", "yes", "1"} <add> <add> <add>def to_boolean(astring: Optional[str]) -> bool: <add> """Convert a string to a boolean.""" <add> if astring is None: <add> return False <add> if astring.lower() in TRUE_LIKE_VALUES: <add> return True <add> return False <ide><path>dev/provider_packages/remove_old_releases.py <ide> """ <ide> import argparse <ide> import glob <add>import operator <ide> import os <ide> import subprocess <ide> from collections import defaultdict <del>from distutils.version import LooseVersion <ide> from typing import Dict, List, NamedTuple <ide> <add>from packaging.version import Version <add> <ide> <ide> class VersionedFile(NamedTuple): <ide> base: str <ide> version: str <ide> suffix: str <ide> type: str <del> comparable_version: LooseVersion <add> comparable_version: Version <ide> <ide> <ide> def split_version_and_suffix(file_name: str, suffix: str) -> VersionedFile: <ide> def split_version_and_suffix(file_name: str, suffix: str) -> VersionedFile: <ide> version=version, <ide> suffix=suffix, <ide> type=no_version_file + "-" + suffix, <del> comparable_version=LooseVersion(version), <add> comparable_version=Version(version), <ide> ) <ide> <ide> <ide> def process_all_files(directory: str, suffix: str, execute: bool): <ide> package_types_dicts[versioned_file.type].append(versioned_file) <ide> <ide> for package_types in package_types_dicts.values(): <del> package_types.sort(key=lambda x: x.comparable_version) <add> package_types.sort(key=operator.attrgetter("comparable_version")) <ide> <ide> for package_types in package_types_dicts.values(): <ide> if len(package_types) == 1: <ide><path>docs/exts/sphinx_script_update.py <ide> import hashlib <ide> import json <ide> import os <add>import shutil <ide> import sys <ide> import tempfile <del>from distutils.file_util import copy_file <ide> from functools import lru_cache <ide> from typing import Dict <ide> <ide> log = logging.getLogger(__name__) <ide> <ide> <add>def _copy_file(src: str, dst: str) -> None: <add> log.info("Copying %s -> %s", src, dst) <add> shutil.copy2(src, dst, follow_symlinks=False) <add> <add> <ide> def _gethash(string: str): <ide> hash_object = hashlib.sha256(string.encode()) <ide> return hash_object.hexdigest() <ide> def build_finished(app, exception): <ide> output_filename = "script.js" <ide> <ide> cache_filepath = fetch_and_cache(script_url, output_filename) <del> copy_file(cache_filepath, os.path.join(app.builder.outdir, '_static', "redoc.js")) <add> _copy_file(cache_filepath, os.path.join(app.builder.outdir, '_static', "redoc.js")) <ide> <ide> <ide> def setup(app): <ide><path>setup.py <ide> import sys <ide> import unittest <ide> from copy import deepcopy <del>from distutils import log <ide> from os.path import dirname, relpath <ide> from textwrap import wrap <ide> from typing import Dict, List <ide> from setuptools.command.develop import develop as develop_orig <ide> from setuptools.command.install import install as install_orig <ide> <add># Setuptools patches this import to point to a vendored copy instead of the <add># stdlib, which is deprecated in Python 3.10 and will be removed in 3.12. <add>from distutils import log # isort: skip <add> <ide> # Controls whether providers are installed from packages or directly from sources <ide> # It is turned on by default in case of development environments such as Breeze <ide> # And it is particularly useful when you add a new provider and there is no
8
PHP
PHP
remove the stub method for quoteidentifier()
74ed30a5630e3899340ead8781a4e14e93a24d67
<ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php <ide> public function testConstructConnectsDriver() <ide> protected function _getMockedDriver() <ide> { <ide> $driver = new \Cake\Database\Driver\Mysql(); <del> $mock = $this->getMock('FakePdo', ['quote', 'quoteIdentifier']); <add> $mock = $this->getMock('FakePdo', ['quote']); <ide> $mock->expects($this->any()) <ide> ->method('quote') <ide> ->will($this->returnCallback(function ($value) { <ide> return "'$value'"; <ide> })); <del> $mock->expects($this->any()) <del> ->method('quoteIdentifier') <del> ->will($this->returnCallback(function ($value) { <del> return '`' . $value . '`'; <del> })); <ide> $driver->connection($mock); <ide> return $driver; <ide> } <ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php <ide> public function testTruncateSql() <ide> protected function _getMockedDriver() <ide> { <ide> $driver = new \Cake\Database\Driver\Postgres(); <del> $mock = $this->getMock('FakePdo', ['quote', 'quoteIdentifier']); <add> $mock = $this->getMock('FakePdo', ['quote']); <ide> $mock->expects($this->any()) <ide> ->method('quote') <ide> ->will($this->returnCallback(function ($value) { <ide> return "'$value'"; <ide> })); <del> $mock->expects($this->any()) <del> ->method('quoteIdentifier') <del> ->will($this->returnCallback(function ($value) { <del> return "'$value'"; <del> })); <ide> $driver->connection($mock); <ide> return $driver; <ide> } <ide><path>tests/TestCase/Database/Schema/SqliteSchemaTest.php <ide> public function testTruncateSqlNoSequences() <ide> protected function _getMockedDriver() <ide> { <ide> $driver = new \Cake\Database\Driver\Sqlite(); <del> $mock = $this->getMock('FakePdo', ['quote', 'quoteIdentifier', 'prepare']); <add> $mock = $this->getMock('FakePdo', ['quote', 'prepare']); <ide> $mock->expects($this->any()) <ide> ->method('quote') <ide> ->will($this->returnCallback(function ($value) { <ide> return '"' . $value . '"'; <ide> })); <del> $mock->expects($this->any()) <del> ->method('quoteIdentifier') <del> ->will($this->returnCallback(function ($value) { <del> return '"' . $value . '"'; <del> })); <ide> $driver->connection($mock); <ide> return $driver; <ide> } <ide><path>tests/TestCase/Database/Schema/SqlserverSchemaTest.php <ide> public function testTruncateSql() <ide> protected function _getMockedDriver() <ide> { <ide> $driver = new \Cake\Database\Driver\Sqlserver(); <del> $mock = $this->getMock('FakePdo', ['quote', 'quoteIdentifier']); <add> $mock = $this->getMock('FakePdo', ['quote']); <ide> $mock->expects($this->any()) <ide> ->method('quote') <ide> ->will($this->returnCallback(function ($value) { <ide> return '[' . $value . ']'; <ide> })); <del> $mock->expects($this->any()) <del> ->method('quoteIdentifier') <del> ->will($this->returnCallback(function ($value) { <del> return '[' . $value . ']'; <del> })); <ide> $driver->connection($mock); <ide> return $driver; <ide> }
4
Java
Java
fix bug in staticlistablebeanfactory.issingleton()
7a31885ae50ec81fc97cf22da9ab51f34d7619a2
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/StaticListableBeanFactory.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 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> /** <ide> * Static {@link org.springframework.beans.factory.BeanFactory} implementation <del> * which allows to register existing singleton instances programmatically. <del> * Does not have support for prototype beans or aliases. <add> * which allows one to register existing singleton instances programmatically. <ide> * <del> * <p>Serves as example for a simple implementation of the <add> * <p>Does not have support for prototype beans or aliases. <add> * <add> * <p>Serves as an example for a simple implementation of the <ide> * {@link org.springframework.beans.factory.ListableBeanFactory} interface, <ide> * managing existing bean instances rather than creating new ones based on bean <ide> * definitions, and not implementing any extended SPI interfaces (such as <ide> * {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}). <ide> * <del> * <p>For a full-fledged factory based on bean definitions, have a look <del> * at {@link DefaultListableBeanFactory}. <add> * <p>For a full-fledged factory based on bean definitions, have a look at <add> * {@link DefaultListableBeanFactory}. <ide> * <ide> * @author Rod Johnson <ide> * @author Juergen Hoeller <add> * @author Sam Brannen <ide> * @since 06.01.2003 <ide> * @see DefaultListableBeanFactory <ide> */ <ide> public StaticListableBeanFactory() { <ide> * or {@link java.util.Collections#emptyMap()} for a dummy factory which <ide> * enforces operating against an empty set of beans. <ide> * @param beans a {@code Map} for holding this factory's beans, with the <del> * bean name String as key and the corresponding singleton object as value <add> * bean name as key and the corresponding singleton object as value <ide> * @since 4.3 <ide> */ <ide> public StaticListableBeanFactory(Map<String, Object> beans) { <ide> public StaticListableBeanFactory(Map<String, Object> beans) { <ide> <ide> /** <ide> * Add a new singleton bean. <del> * Will overwrite any existing instance for the given name. <add> * <p>Will overwrite any existing instance for the given name. <ide> * @param name the name of the bean <ide> * @param bean the bean instance <ide> */ <ide> public boolean containsBean(String name) { <ide> public boolean isSingleton(String name) throws NoSuchBeanDefinitionException { <ide> Object bean = getBean(name); <ide> // In case of FactoryBean, return singleton status of created object. <del> return (bean instanceof FactoryBean && ((FactoryBean<?>) bean).isSingleton()); <add> if (bean instanceof FactoryBean) { <add> return ((FactoryBean<?>) bean).isSingleton(); <add> } <add> return true; <ide> } <ide> <ide> @Override <ide> public String[] getBeanNamesForType(@Nullable ResolvableType type) { <ide> return getBeanNamesForType(type, true, true); <ide> } <ide> <del> <ide> @Override <ide> public String[] getBeanNamesForType(@Nullable ResolvableType type, <ide> boolean includeNonSingletons, boolean allowEagerInit) { <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 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> * @author Rod Johnson <ide> * @author Juergen Hoeller <ide> * @author Chris Beams <add> * @author Sam Brannen <ide> * @since 04.07.2003 <ide> */ <ide> public class BeanFactoryUtilsTests { <ide> public void testIntDependencies() { <ide> assertThat(Arrays.equals(new String[] { "buffer" }, deps)).isTrue(); <ide> } <ide> <add> @Test <add> public void isSingletonAndIsPrototypeWithStaticFactory() { <add> StaticListableBeanFactory lbf = new StaticListableBeanFactory(); <add> TestBean bean = new TestBean(); <add> DummyFactory fb1 = new DummyFactory(); <add> DummyFactory fb2 = new DummyFactory(); <add> fb2.setSingleton(false); <add> TestBeanSmartFactoryBean sfb1 = new TestBeanSmartFactoryBean(true, true); <add> TestBeanSmartFactoryBean sfb2 = new TestBeanSmartFactoryBean(true, false); <add> TestBeanSmartFactoryBean sfb3 = new TestBeanSmartFactoryBean(false, true); <add> TestBeanSmartFactoryBean sfb4 = new TestBeanSmartFactoryBean(false, false); <add> lbf.addBean("bean", bean); <add> lbf.addBean("fb1", fb1); <add> lbf.addBean("fb2", fb2); <add> lbf.addBean("sfb1", sfb1); <add> lbf.addBean("sfb2", sfb2); <add> lbf.addBean("sfb3", sfb3); <add> lbf.addBean("sfb4", sfb4); <add> <add> Map<String, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, ITestBean.class, true, true); <add> assertThat(beans.get("bean")).isSameAs(bean); <add> assertThat(beans.get("fb1")).isSameAs(fb1.getObject()); <add> assertThat(beans.get("fb2")).isInstanceOf(TestBean.class); <add> assertThat(beans.get("sfb1")).isInstanceOf(TestBean.class); <add> assertThat(beans.get("sfb2")).isInstanceOf(TestBean.class); <add> assertThat(beans.get("sfb3")).isInstanceOf(TestBean.class); <add> assertThat(beans.get("sfb4")).isInstanceOf(TestBean.class); <add> <add> assertThat(lbf.getBeanDefinitionCount()).isEqualTo(7); <add> assertThat(lbf.getBean("bean")).isInstanceOf(TestBean.class); <add> assertThat(lbf.getBean("&fb1")).isInstanceOf(FactoryBean.class); <add> assertThat(lbf.getBean("&fb2")).isInstanceOf(FactoryBean.class); <add> assertThat(lbf.getBean("&sfb1")).isInstanceOf(SmartFactoryBean.class); <add> assertThat(lbf.getBean("&sfb2")).isInstanceOf(SmartFactoryBean.class); <add> assertThat(lbf.getBean("&sfb3")).isInstanceOf(SmartFactoryBean.class); <add> assertThat(lbf.getBean("&sfb4")).isInstanceOf(SmartFactoryBean.class); <add> <add> assertThat(lbf.isSingleton("bean")).isTrue(); <add> assertThat(lbf.isSingleton("fb1")).isTrue(); <add> assertThat(lbf.isSingleton("fb2")).isTrue(); <add> assertThat(lbf.isSingleton("sfb1")).isTrue(); <add> assertThat(lbf.isSingleton("sfb2")).isTrue(); <add> assertThat(lbf.isSingleton("sfb3")).isTrue(); <add> assertThat(lbf.isSingleton("sfb4")).isTrue(); <add> <add> assertThat(lbf.isSingleton("&fb1")).isTrue(); <add> assertThat(lbf.isSingleton("&fb2")).isFalse(); <add> assertThat(lbf.isSingleton("&sfb1")).isTrue(); <add> assertThat(lbf.isSingleton("&sfb2")).isTrue(); <add> assertThat(lbf.isSingleton("&sfb3")).isFalse(); <add> assertThat(lbf.isSingleton("&sfb4")).isFalse(); <add> <add> assertThat(lbf.isPrototype("bean")).isFalse(); <add> assertThat(lbf.isPrototype("fb1")).isFalse(); <add> assertThat(lbf.isPrototype("fb2")).isFalse(); <add> assertThat(lbf.isPrototype("sfb1")).isFalse(); <add> assertThat(lbf.isPrototype("sfb2")).isFalse(); <add> assertThat(lbf.isPrototype("sfb3")).isFalse(); <add> assertThat(lbf.isPrototype("sfb4")).isFalse(); <add> <add> assertThat(lbf.isPrototype("&fb1")).isFalse(); <add> assertThat(lbf.isPrototype("&fb2")).isTrue(); <add> assertThat(lbf.isPrototype("&sfb1")).isTrue(); <add> assertThat(lbf.isPrototype("&sfb2")).isFalse(); <add> assertThat(lbf.isPrototype("&sfb3")).isTrue(); <add> assertThat(lbf.isPrototype("&sfb4")).isTrue(); <add> } <add> <add> <add> static class TestBeanSmartFactoryBean implements SmartFactoryBean<TestBean> { <add> <add> private final TestBean testBean = new TestBean("enigma", 42); <add> private final boolean singleton; <add> private final boolean prototype; <add> <add> TestBeanSmartFactoryBean(boolean singleton, boolean prototype) { <add> this.singleton = singleton; <add> this.prototype = prototype; <add> } <add> <add> @Override <add> public boolean isSingleton() { <add> return this.singleton; <add> } <add> <add> @Override <add> public boolean isPrototype() { <add> return this.prototype; <add> } <add> <add> @Override <add> public Class<TestBean> getObjectType() { <add> return TestBean.class; <add> } <add> <add> public TestBean getObject() throws Exception { <add> // We don't really care if the actual instance is a singleton or prototype <add> // for the tests that use this factory. <add> return this.testBean; <add> } <add> } <add> <ide> }
2
Javascript
Javascript
add type check to depthtexture
62923d60fdfed65dad7486fca25bc799d9ce8e60
<ide><path>src/renderers/webgl/WebGLTextures.js <ide> * @author mrdoob / http://mrdoob.com/ <ide> */ <ide> <del>import { LinearFilter, NearestFilter, RGBFormat, RGBAFormat, DepthFormat, DepthStencilFormat, FloatType, HalfFloatType, ClampToEdgeWrapping, NearestMipMapLinearFilter, NearestMipMapNearestFilter } from '../../constants'; <add>import { LinearFilter, NearestFilter, RGBFormat, RGBAFormat, DepthFormat, DepthStencilFormat, UnsignedShortType, UnsignedIntType, UnsignedInt248Type, FloatType, HalfFloatType, ClampToEdgeWrapping, NearestMipMapLinearFilter, NearestMipMapNearestFilter } from '../../constants'; <ide> import { _Math } from '../../math/Math'; <ide> <ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) { <ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, paramT <ide> <ide> } <ide> <add> if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) { <add> <add> // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are <add> // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT <add> // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) <add> if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) { <add> <add> console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); <add> <add> texture.type = UnsignedShortType; <add> glType = paramThreeToGL( texture.type ); <add> <add> } <add> <add> } <add> <ide> // Depth stencil textures need the DEPTH_STENCIL internal format <ide> // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) <ide> if ( texture.format === DepthStencilFormat ) { <ide> <ide> internalFormat = _gl.DEPTH_STENCIL; <ide> <add> // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are <add> // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. <add> // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) <add> if ( texture.type !== UnsignedInt248Type ) { <add> <add> console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' ); <add> <add> texture.type = UnsignedInt248Type; <add> glType = paramThreeToGL( texture.type ); <add> <add> } <add> <ide> } <ide> <ide> state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null ); <ide><path>src/textures/DepthTexture.js <ide> import { Texture } from './Texture'; <del>import { NearestFilter, UnsignedShortType, DepthFormat, DepthStencilFormat } from '../constants'; <add>import { NearestFilter, UnsignedShortType, UnsignedInt248Type, DepthFormat, DepthStencilFormat } from '../constants'; <ide> <ide> /** <ide> * @author Matt DesLauriers / @mattdesl <ide> function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, mi <ide> <ide> } <ide> <add> if ( type === undefined && format === DepthFormat ) type = UnsignedShortType; <add> if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type; <add> <ide> Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); <ide> <ide> this.image = { width: width, height: height }; <ide> <del> this.type = type !== undefined ? type : UnsignedShortType; <del> <ide> this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; <ide> this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; <ide>
2
PHP
PHP
remove middleware interface
caa166f5d6ded18f2d3f11612433e90f5a1150e9
<ide><path>app/Http/Middleware/Authenticate.php <ide> <ide> use Closure; <ide> use Illuminate\Contracts\Auth\Guard; <del>use Illuminate\Contracts\Routing\Middleware; <ide> <del>class Authenticate implements Middleware { <add>class Authenticate { <ide> <ide> /** <ide> * The Guard implementation. <ide><path>app/Http/Middleware/RedirectIfAuthenticated.php <ide> use Closure; <ide> use Illuminate\Contracts\Auth\Guard; <ide> use Illuminate\Http\RedirectResponse; <del>use Illuminate\Contracts\Routing\Middleware; <ide> <del>class RedirectIfAuthenticated implements Middleware { <add>class RedirectIfAuthenticated { <ide> <ide> /** <ide> * The Guard implementation.
2
Ruby
Ruby
remove full stop from the "skipping" comment
7542c4edb73fdfee00070d8dd6980d58141eca48
<ide><path>Library/Homebrew/utils/github.rb <ide> def create_issue_comment(body) <ide> url = "#{API_URL}/repos/#{user}/#{repo}/issues/#{pr}/comments" <ide> data = { "body" => body } <ide> if issue_comment_exists?(user, repo, pr, body) <del> ohai "Skipping: identical comment exists on #{PR_ENV}." <add> ohai "Skipping: identical comment exists on #{PR_ENV}" <ide> return true <ide> end <ide>
1
Ruby
Ruby
add audit for checksum
8717f82b9d7d3a05e7411a12434551474d4212f1
<ide><path>Library/Homebrew/resource_auditor.rb <ide> def initialize(resource, spec_name, options = {}) <ide> def audit <ide> audit_version <ide> audit_download_strategy <add> audit_checksum <ide> audit_urls <ide> self <ide> end <ide> def audit_download_strategy <ide> problem "Redundant :using value in URL" <ide> end <ide> <add> def audit_checksum <add> return if spec_name == :head <add> return unless DownloadStrategyDetector.detect(url, using) <= CurlDownloadStrategy <add> <add> problem "Checksum is missing" if checksum.blank? <add> end <add> <ide> def self.curl_openssl_and_deps <ide> @curl_openssl_and_deps ||= begin <ide> formulae_names = ["curl", "openssl"] <ide><path>Library/Homebrew/test/dev-cmd/audit_spec.rb <ide> class Foo < Formula <ide> let(:throttle_list) { { throttled_formulae: { "foo" => 10 } } } <ide> let(:versioned_head_spec_list) { { versioned_head_spec_allowlist: ["foo"] } } <ide> <add> it "doesn't allow to miss a checksum" do <add> fa = formula_auditor "foo", <<~RUBY <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tgz" <add> end <add> RUBY <add> <add> fa.audit_specs <add> expect(fa.problems.first[:message]).to match "Checksum is missing" <add> end <add> <add> it "allows to miss a checksum for git strategy" do <add> fa = formula_auditor "foo", <<~RUBY <add> class Foo < Formula <add> url "https://brew.sh/foo.git", tag: "1.0", revision: "f5e00e485e7aa4c5baa20355b27e3b84a6912790" <add> end <add> RUBY <add> <add> fa.audit_specs <add> expect(fa.problems).to be_empty <add> end <add> <add> it "allows to miss a checksum for HEAD" do <add> fa = formula_auditor "foo", <<~RUBY <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tgz" <add> sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" <add> head "https://brew.sh/foo.tgz" <add> end <add> RUBY <add> <add> fa.audit_specs <add> expect(fa.problems).to be_empty <add> end <add> <ide> it "allows versions with no throttle rate" do <ide> fa = formula_auditor "bar", <<~RUBY, core_tap: true, tap_audit_exceptions: throttle_list <ide> class Bar < Formula <ide> url "https://brew.sh/foo-1.0.1.tgz" <add> sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" <ide> end <ide> RUBY <ide> <ide> class Bar < Formula <ide> fa = formula_auditor "foo", <<~RUBY, core_tap: true, tap_audit_exceptions: throttle_list <ide> class Foo < Formula <ide> url "https://brew.sh/foo-1.0.0.tgz" <add> sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" <ide> end <ide> RUBY <ide> <ide> class Foo < Formula <ide> fa = formula_auditor "foo", <<~RUBY, core_tap: true, tap_audit_exceptions: throttle_list <ide> class Foo < Formula <ide> url "https://brew.sh/foo-1.0.10.tgz" <add> sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" <ide> end <ide> RUBY <ide> <ide> class Foo < Formula <ide> fa = formula_auditor "foo", <<~RUBY, core_tap: true, tap_audit_exceptions: throttle_list <ide> class Foo < Formula <ide> url "https://brew.sh/foo-1.0.1.tgz" <add> sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" <ide> end <ide> RUBY <ide> <ide> class Foo < Formula <ide> fa = formula_auditor "bar", <<~RUBY, core_tap: true, tap_audit_exceptions: versioned_head_spec_list <ide> class Bar < Formula <ide> url "https://brew.sh/foo-1.0.tgz" <del> head "https://brew.sh/foo-1.0.tgz" <add> sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" <add> head "https://brew.sh/foo.git" <ide> end <ide> RUBY <ide> <ide> class Bar < Formula <ide> fa = formula_auditor "bar@1", <<~RUBY, core_tap: true, tap_audit_exceptions: versioned_head_spec_list <ide> class BarAT1 < Formula <ide> url "https://brew.sh/foo-1.0.tgz" <del> head "https://brew.sh/foo-1.0.tgz" <add> sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" <add> head "https://brew.sh/foo.git" <ide> end <ide> RUBY <ide> <ide> fa.audit_specs <ide> expect(fa.problems.first[:message]).to match "Versioned formulae should not have a `HEAD` spec" <ide> end <ide> <del> it "allows ersioned formulae on the allowlist to have a `HEAD` spec" do <add> it "allows versioned formulae on the allowlist to have a `HEAD` spec" do <ide> fa = formula_auditor "foo", <<~RUBY, core_tap: true, tap_audit_exceptions: versioned_head_spec_list <ide> class Foo < Formula <ide> url "https://brew.sh/foo-1.0.tgz" <del> head "https://brew.sh/foo-1.0.tgz" <add> sha256 "31cccfc6630528db1c8e3a06f6decf2a370060b982841cfab2b8677400a5092e" <add> head "https://brew.sh/foo.git" <ide> end <ide> RUBY <ide>
2
Ruby
Ruby
make testqueuetest work with marshalling queue
b44104ae1357f0177056e833d7cd1e0abaa5c759
<ide><path>railties/test/queueing/test_queue_test.rb <ide> require 'rails/queueing' <ide> <ide> class TestQueueTest < ActiveSupport::TestCase <del> class Job <del> def initialize(&block) <del> @block = block <del> end <add> def setup <add> @queue = Rails::Queueing::TestQueue.new <add> end <ide> <add> class ExceptionRaisingJob <ide> def run <del> @block.call if @block <add> raise <ide> end <ide> end <ide> <del> def setup <del> @queue = Rails::Queueing::TestQueue.new <del> end <del> <ide> def test_drain_raises <del> @queue.push Job.new { raise } <add> @queue.push ExceptionRaisingJob.new <ide> assert_raises(RuntimeError) { @queue.drain } <ide> end <ide> <ide> def test_jobs <ide> assert_equal [1,2], @queue.jobs <ide> end <ide> <add> class EquivalentJob <add> def initialize <add> @initial_id = self.object_id <add> end <add> <add> def run <add> end <add> <add> def ==(other) <add> other.same_initial_id?(@initial_id) <add> end <add> <add> def same_initial_id?(other_id) <add> other_id == @initial_id <add> end <add> end <add> <ide> def test_contents <ide> assert @queue.empty? <del> job = Job.new <add> job = EquivalentJob.new <ide> @queue.push job <ide> refute @queue.empty? <ide> assert_equal job, @queue.pop <ide> end <ide> <del> def test_order <del> processed = [] <add> class ProcessingJob <add> def self.clear_processed <add> @processed = [] <add> end <add> <add> def self.processed <add> @processed <add> end <add> <add> def initialize(object) <add> @object = object <add> end <add> <add> def run <add> self.class.processed << @object <add> end <add> end <ide> <del> job1 = Job.new { processed << 1 } <del> job2 = Job.new { processed << 2 } <add> def test_order <add> ProcessingJob.clear_processed <add> job1 = ProcessingJob.new(1) <add> job2 = ProcessingJob.new(2) <ide> <ide> @queue.push job1 <ide> @queue.push job2 <ide> @queue.drain <ide> <del> assert_equal [1,2], processed <add> assert_equal [1,2], ProcessingJob.processed <ide> end <ide> <del> def test_drain <del> t = nil <del> ran = false <add> class ThreadTrackingJob <add> attr_reader :thread_id <ide> <del> job = Job.new do <del> ran = true <del> t = Thread.current <add> def run <add> @thread_id = Thread.current.object_id <ide> end <ide> <del> @queue.push job <add> def ran? <add> @thread_id <add> end <add> end <add> <add> def test_drain <add> @queue.push ThreadTrackingJob.new <add> job = @queue.jobs.last <ide> @queue.drain <ide> <ide> assert @queue.empty? <del> assert ran, "The job runs synchronously when the queue is drained" <del> assert_not_equal t, Thread.current <add> assert job.ran?, "The job runs synchronously when the queue is drained" <add> assert_not_equal job.thread_id, Thread.current.object_id <ide> end <ide> end
1
Javascript
Javascript
create cdn archives in the build script
47f56f1612b907ec9eaa7111c7af66d335279fa2
<ide><path>build/release.js <ide> var fs = require("fs"), <ide> <ide> var releaseVersion, <ide> nextVersion, <del> CDNFiles, <ide> isBeta, <ide> pkg, <ide> branch, <ide> var releaseVersion, <ide> // "jquery-latest.js": devFile, <ide> // "jquery-latest.min.js": minFile, <ide> // "jquery-latest.min.map": mapFile <del> }; <add> }, <add> <add> jQueryFilesCDN = [], <add> <add> googleFilesCDN = [ <add> "jquery.js", "jquery.min.js", "jquery.min.map" <add> ], <add> <add> msFilesCDN = [ <add> "jquery-VER.js", "jquery-VER.min.js", "jquery-VER.min.map" <add> ]; <add> <ide> <ide> steps( <ide> initialize, <ide> steps( <ide> gruntBuild, <ide> makeReleaseCopies, <ide> setNextVersion, <del> uploadToCDN, <add> copyTojQueryCDN, <add> buildGoogleCDN, <add> buildMicrosoftCDN, <ide> pushToGithub, <ide> exit <ide> ); <ide> function gruntBuild( next ) { <ide> } <ide> <ide> function makeReleaseCopies( next ) { <del> CDNFiles = {}; <ide> Object.keys( releaseFiles ).forEach(function( key ) { <ide> var text, <ide> builtFile = releaseFiles[ key ], <ide> function makeReleaseCopies( next ) { <ide> copy( builtFile, releaseFile ); <ide> } <ide> <del> CDNFiles[ releaseFile ] = builtFile; <add> jQueryFilesCDN.push( releaseFile ); <ide> } <ide> }); <ide> next(); <ide> function setNextVersion( next ) { <ide> git( [ "commit", "-a", "-m", "Updating the source version to " + nextVersion + "✓™" ], next, debug ); <ide> } <ide> <del>function uploadToCDN( next ) { <add>function copyTojQueryCDN( next ) { <ide> var cmds = []; <ide> <del> Object.keys( CDNFiles ).forEach(function( name ) { <add> jQueryFilesCDN.forEach(function( name ) { <ide> cmds.push(function( nxt ){ <ide> exec( "scp", [ name, scpURL ], nxt, debug || skipRemote ); <ide> }); <ide> function uploadToCDN( next ) { <ide> steps.apply( this, cmds ); <ide> } <ide> <add>function buildGoogleCDN( next ) { <add> makeArchive( "googlecdn", googleFilesCDN, next ); <add>} <add> <add>function buildMicrosoftCDN( next ) { <add> makeArchive( "mscdn", msFilesCDN, next ); <add>} <add> <ide> function pushToGithub( next ) { <ide> git( [ "push", "--tags", repoURL, branch ], next, debug || skipRemote ); <ide> } <ide> function updatePackageVersion( ver ) { <ide> } <ide> } <ide> <add>function makeArchive( cdn, files, fn ) { <add> <add> if ( isBeta ) { <add> console.log( "Skipping archive creation for " + cdn + "; " + releaseVersion + " is beta" ); <add> process.nextTick( fn ); <add> return <add> } <add> console.log("Creating production archive for " + cdn ); <add> files = files.map(function( item ) { <add> return "dist/" + item.replace( /VER/g, releaseVersion ); <add> }); <add> var md5file = "dist/" + cdn + "-md5.txt"; <add> exec( "md5sum", files, function( err, stdout, stderr ) { <add> fs.writeFileSync( md5file, stdout ); <add> files.push( md5file ); <add> exec( "tar", [ "-czvf", "dist/" + cdn + "-jquery-" + releaseVersion + ".tar.gz" ].concat( files ), fn, false ); <add> }, false ); <add>} <add> <ide> function copy( oldFile, newFile ) { <ide> console.log( "Copying " + oldFile + " to " + newFile ); <ide> if ( !debug ) {
1
Ruby
Ruby
handle broken encoding in `#write_query?`
b629a5bc42396fe81fdc0aa02dbfba04fb61d62d
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb <ide> def self.type_cast_config_to_boolean(config) <ide> def self.build_read_query_regexp(*parts) # :nodoc: <ide> parts += DEFAULT_READ_QUERY <ide> parts = parts.map { |part| /#{part}/i } <del> /\A(?:[(\s]|#{COMMENT_REGEX})*#{Regexp.union(*parts)}/ <add> /\A(?:[(\s]|#{COMMENT_REGEX})*#{Regexp.union(*parts)}/n <ide> end <ide> <ide> def self.quoted_column_names # :nodoc: <ide><path>activerecord/lib/active_record/connection_adapters/mysql/database_statements.rb <ide> def query(sql, name = nil) # :nodoc: <ide> <ide> def write_query?(sql) # :nodoc: <ide> !READ_QUERY.match?(sql) <add> rescue ArgumentError # Invalid encoding <add> !READ_QUERY.match?(sql.b) <ide> end <ide> <ide> def explain(arel, binds = []) <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb <ide> def query(sql, name = nil) # :nodoc: <ide> <ide> def write_query?(sql) # :nodoc: <ide> !READ_QUERY.match?(sql) <add> rescue ArgumentError # Invalid encoding <add> !READ_QUERY.match?(sql.b) <ide> end <ide> <ide> # Executes an SQL statement, returning a PG::Result object on success <ide><path>activerecord/lib/active_record/connection_adapters/sqlite3/database_statements.rb <ide> module DatabaseStatements <ide> <ide> def write_query?(sql) # :nodoc: <ide> !READ_QUERY.match?(sql) <add> rescue ArgumentError # Invalid encoding <add> !READ_QUERY.match?(sql.b) <ide> end <ide> <ide> def explain(arel, binds = []) <ide><path>activerecord/test/cases/adapter_prevent_writes_test.rb <ide> def test_errors_when_a_delete_query_is_called_while_preventing_writes <ide> end <ide> end <ide> <add> if current_adapter?(:PostgreSQLAdapter) <add> def test_doesnt_error_when_a_select_query_has_encoding_errors <add> ActiveRecord::Base.while_preventing_writes do <add> # Contrary to other adapters, Postgres will eagerly fail on encoding errors. <add> # But at least we can assert it fails in the client and not before when trying to <add> # match the query. <add> assert_raises ActiveRecord::StatementInvalid do <add> @connection.select_all("SELECT '\xC8'") <add> end <add> end <add> end <add> else <add> def test_doesnt_error_when_a_select_query_has_encoding_errors <add> ActiveRecord::Base.while_preventing_writes do <add> @connection.select_all("SELECT '\xC8'") <add> end <add> end <add> end <add> <ide> def test_doesnt_error_when_a_select_query_is_called_while_preventing_writes <ide> @connection.insert("INSERT INTO subscribers(nick) VALUES ('138853948594')") <ide>
5
Go
Go
add hostname to the container environment
05219d6b52d8448fdad72f89b192d61480483aff
<ide><path>container.go <ide> func (container *Container) Start(hostConfig *HostConfig) error { <ide> "-e", "HOME=/", <ide> "-e", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", <ide> "-e", "container=lxc", <add> "-e", "HOSTNAME="+container.Config.Hostname, <ide> ) <ide> <ide> for _, elem := range container.Config.Env {
1
Go
Go
use gorp.get() instead of gorp.select()
07b6bc3fc738ab3a27e9760b0efc57c78d7f98af
<ide><path>fs/store.go <ide> func (store *Store) List(pth string) ([]*Image, error) { <ide> } <ide> <ide> func (store *Store) Get(id string) (*Image, error) { <del> images, err := store.orm.Select(Image{}, "select * from images where Id=?", id) <del> if err != nil { <del> return nil, err <del> } <del> if len(images) < 1 { <del> return nil, os.ErrNotExist <del> } <del> return images[0].(*Image), nil <add> img, err := store.orm.Get(Image{}, id) <add> return img.(*Image), err <ide> } <ide> <ide> func (store *Store) Create(layer Archive, parent *Image, pth, comment string) (*Image, error) {
1
Python
Python
modernize tokenizer tests for emoticons
ee6b49b293279d14466744debc3392081f6da4ec
<ide><path>spacy/tests/tokenizer/test_emoticons.py <ide> from __future__ import unicode_literals <add> <ide> import pytest <ide> <ide> <del>def test_tweebo_challenge(en_tokenizer): <add>def test_tokenizer_handles_emoticons(en_tokenizer): <add> # Tweebo challenge (CMU) <ide> text = u""":o :/ :'( >:o (: :) >.< XD -__- o.O ;D :-) @_@ :P 8D :1 >:( :D =| ") :> ....""" <ide> tokens = en_tokenizer(text) <ide> assert tokens[0].orth_ == ":o" <ide> def test_tweebo_challenge(en_tokenizer): <ide> assert tokens[21].orth_ == '....' <ide> <ide> <del>def test_false_positive(en_tokenizer): <del> text = "example:)" <add>@pytest.mark.parametrize('text,length', [("example:)", 3), ("108)", 2), ("XDN", 1)]) <add>def test_tokenizer_excludes_false_pos_emoticons(en_tokenizer, text, length): <ide> tokens = en_tokenizer(text) <del> assert len(tokens) == 3 <add> assert len(tokens) == length
1
Java
Java
register custom before default codecs
49388315751160b1801a5063d665b5b1381f8555
<ide><path>spring-web/src/main/java/org/springframework/http/codec/support/BaseCodecConfigurer.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> public CustomCodecs customCodecs() { <ide> public List<HttpMessageReader<?>> getReaders() { <ide> List<HttpMessageReader<?>> result = new ArrayList<>(); <ide> <del> result.addAll(this.defaultCodecs.getTypedReaders()); <ide> result.addAll(this.customCodecs.getTypedReaders()); <add> result.addAll(this.defaultCodecs.getTypedReaders()); <ide> <del> result.addAll(this.defaultCodecs.getObjectReaders()); <ide> result.addAll(this.customCodecs.getObjectReaders()); <add> result.addAll(this.defaultCodecs.getObjectReaders()); <ide> <ide> result.addAll(this.defaultCodecs.getCatchAllReaders()); <ide> return result; <ide> public List<HttpMessageWriter<?>> getWriters() { <ide> protected List<HttpMessageWriter<?>> getWritersInternal(boolean forMultipart) { <ide> List<HttpMessageWriter<?>> result = new ArrayList<>(); <ide> <del> result.addAll(this.defaultCodecs.getTypedWriters(forMultipart)); <ide> result.addAll(this.customCodecs.getTypedWriters()); <add> result.addAll(this.defaultCodecs.getTypedWriters(forMultipart)); <ide> <del> result.addAll(this.defaultCodecs.getObjectWriters(forMultipart)); <ide> result.addAll(this.customCodecs.getObjectWriters()); <add> result.addAll(this.defaultCodecs.getObjectWriters(forMultipart)); <ide> <ide> result.addAll(this.defaultCodecs.getCatchAllWriters()); <ide> return result; <ide><path>spring-web/src/test/java/org/springframework/http/codec/support/CodecConfigurerTests.java <ide> public void defaultAndCustomReaders() { <ide> List<HttpMessageReader<?>> readers = this.configurer.getReaders(); <ide> <ide> assertEquals(15, readers.size()); <add> assertSame(customDecoder1, getNextDecoder(readers)); <add> assertSame(customReader1, readers.get(this.index.getAndIncrement())); <ide> assertEquals(ByteArrayDecoder.class, getNextDecoder(readers).getClass()); <ide> assertEquals(ByteBufferDecoder.class, getNextDecoder(readers).getClass()); <ide> assertEquals(DataBufferDecoder.class, getNextDecoder(readers).getClass()); <ide> assertEquals(ResourceHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass()); <ide> assertEquals(StringDecoder.class, getNextDecoder(readers).getClass()); <ide> assertEquals(ProtobufDecoder.class, getNextDecoder(readers).getClass()); <ide> assertEquals(FormHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass()); <del> assertSame(customDecoder1, getNextDecoder(readers)); <del> assertSame(customReader1, readers.get(this.index.getAndIncrement())); <add> assertSame(customDecoder2, getNextDecoder(readers)); <add> assertSame(customReader2, readers.get(this.index.getAndIncrement())); <ide> assertEquals(Jackson2JsonDecoder.class, getNextDecoder(readers).getClass()); <ide> assertEquals(Jackson2SmileDecoder.class, getNextDecoder(readers).getClass()); <ide> assertEquals(Jaxb2XmlDecoder.class, getNextDecoder(readers).getClass()); <del> assertSame(customDecoder2, getNextDecoder(readers)); <del> assertSame(customReader2, readers.get(this.index.getAndIncrement())); <ide> assertEquals(StringDecoder.class, getNextDecoder(readers).getClass()); <ide> } <ide> <ide> public void defaultAndCustomWriters() { <ide> List<HttpMessageWriter<?>> writers = this.configurer.getWriters(); <ide> <ide> assertEquals(14, writers.size()); <add> assertSame(customEncoder1, getNextEncoder(writers)); <add> assertSame(customWriter1, writers.get(this.index.getAndIncrement())); <ide> assertEquals(ByteArrayEncoder.class, getNextEncoder(writers).getClass()); <ide> assertEquals(ByteBufferEncoder.class, getNextEncoder(writers).getClass()); <ide> assertEquals(DataBufferEncoder.class, getNextEncoder(writers).getClass()); <ide> assertEquals(ResourceHttpMessageWriter.class, writers.get(index.getAndIncrement()).getClass()); <ide> assertEquals(CharSequenceEncoder.class, getNextEncoder(writers).getClass()); <ide> assertEquals(ProtobufHttpMessageWriter.class, writers.get(index.getAndIncrement()).getClass()); <del> assertSame(customEncoder1, getNextEncoder(writers)); <del> assertSame(customWriter1, writers.get(this.index.getAndIncrement())); <add> assertSame(customEncoder2, getNextEncoder(writers)); <add> assertSame(customWriter2, writers.get(this.index.getAndIncrement())); <ide> assertEquals(Jackson2JsonEncoder.class, getNextEncoder(writers).getClass()); <ide> assertEquals(Jackson2SmileEncoder.class, getNextEncoder(writers).getClass()); <ide> assertEquals(Jaxb2XmlEncoder.class, getNextEncoder(writers).getClass()); <del> assertSame(customEncoder2, getNextEncoder(writers)); <del> assertSame(customWriter2, writers.get(this.index.getAndIncrement())); <ide> assertEquals(CharSequenceEncoder.class, getNextEncoder(writers).getClass()); <ide> } <ide>
2
PHP
PHP
remove unneeded code
893c21613eaa9e7836daddca5b2bc044a0281710
<ide><path>src/Core/Configure.php <ide> public static function dump($key, $config = 'default', $keys = []) <ide> if (!$engine) { <ide> throw new Exception(sprintf('There is no "%s" config engine.', $config)); <ide> } <del> if (!method_exists($engine, 'dump')) { <del> throw new Exception(sprintf('The "%s" config engine, does not have a dump() method.', $config)); <del> } <ide> $values = static::$_values; <ide> if (!empty($keys) && is_array($keys)) { <ide> $values = array_intersect_key($values, array_flip($keys));
1
Text
Text
update layouts and rendering in rails [ci skip]
a52e2bed8634531272018a4ae7ba389e1feebdf5
<ide><path>guides/source/layouts_and_rendering.md <ide> If we want to display the properties of all the books in our view, we can do so <ide> <h1>Listing Books</h1> <ide> <ide> <table> <del> <tr> <del> <th>Title</th> <del> <th>Summary</th> <del> <th></th> <del> <th></th> <del> <th></th> <del> </tr> <del> <del><% @books.each do |book| %> <del> <tr> <del> <td><%= book.title %></td> <del> <td><%= book.content %></td> <del> <td><%= link_to "Show", book %></td> <del> <td><%= link_to "Edit", edit_book_path(book) %></td> <del> <td><%= link_to "Remove", book, method: :delete, data: { confirm: "Are you sure?" } %></td> <del> </tr> <del><% end %> <add> <thead> <add> <tr> <add> <th>Title</th> <add> <th>Content</th> <add> <th colspan="3"></th> <add> </tr> <add> </thead> <add> <add> <tbody> <add> <% @books.each do |book| %> <add> <tr> <add> <td><%= book.title %></td> <add> <td><%= book.content %></td> <add> <td><%= link_to "Show", book %></td> <add> <td><%= link_to "Edit", edit_book_path(book) %></td> <add> <td><%= link_to "Destroy", book, method: :delete, data: { confirm: "Are you sure?" } %></td> <add> </tr> <add> <% end %> <add> </tbody> <ide> </table> <ide> <ide> <br>
1
Ruby
Ruby
reduce dependency expansion computations
96670cedb2e84f4f741c514d0b1c3e15ef3106eb
<ide><path>Library/Homebrew/formula_installer.rb <ide> def check_conflicts <ide> # Compute and collect the dependencies needed by the formula currently <ide> # being installed. <ide> def compute_dependencies <del> req_map, req_deps = expand_requirements <del> check_requirements(req_map) <del> expand_dependencies(req_deps + formula.deps) <add> @compute_dependencies ||= begin <add> req_map, req_deps = expand_requirements <add> check_requirements(req_map) <add> expand_dependencies(req_deps + formula.deps) <add> end <ide> end <ide> <ide> def unbottled_dependencies(deps) <ide> def forbidden_license_check <ide> end <ide> <ide> return if forbidden_licenses.blank? <add> return if ignore_deps? <ide> <ide> compute_dependencies.each do |dep, _| <del> next if @ignore_deps <del> <ide> dep_f = dep.to_formula <ide> next unless SPDX.licenses_forbid_installation? dep_f.license, forbidden_licenses <ide> <ide> def forbidden_license_check <ide> #{SPDX.license_expression_to_string dep_f.license}. <ide> EOS <ide> end <del> return if @only_deps <add> <add> return if only_deps? <ide> <ide> return unless SPDX.licenses_forbid_installation? formula.license, forbidden_licenses <ide>
1
Ruby
Ruby
add standard meson args
f8536d0b5bffaafa0f317c1e3526cb01d6112b10
<ide><path>Library/Homebrew/formula.rb <ide> def std_cabal_v2_args <ide> ["--jobs=#{ENV.make_jobs}", "--max-backjumps=100000", "--install-method=copy", "--installdir=#{bin}"] <ide> end <ide> <add> # Standard parameters for meson builds. <add> def std_meson_args <add> ["--prefix=#{prefix}", "--libdir=#{lib}"] <add> end <add> <ide> # an array of all core {Formula} names <ide> # @private <ide> def self.core_names <ide><path>Library/Homebrew/formula_creator.rb <ide> def install <ide> system "go", "build", *std_go_args <ide> <% elsif mode == :meson %> <ide> mkdir "build" do <del> system "meson", "--prefix=\#{prefix}", ".." <add> system "meson", *std_meson_args, ".." <ide> system "ninja", "-v" <ide> system "ninja", "install", "-v" <ide> end
2
PHP
PHP
remove dead catch blocks
ab8eac7bc2853b443c3986e19fdbe9701613d212
<ide><path>src/Error/ErrorHandler.php <ide> protected function _displayException($exception) <ide> $this->_sendResponse($response); <ide> } catch (Throwable $exception) { <ide> $this->_logInternalError($exception); <del> } catch (Exception $exception) { <del> $this->_logInternalError($exception); <ide> } <ide> } <ide> <ide><path>src/Error/Middleware/ErrorHandlerMiddleware.php <ide> public function __invoke($request, $response, $next) <ide> return $next($request, $response); <ide> } catch (Throwable $exception) { <ide> return $this->handleException($exception, $request, $response); <del> } catch (Exception $exception) { <del> return $this->handleException($exception, $request, $response); <ide> } <ide> } <ide> <ide> public function handleException($exception, $request, $response) <ide> } catch (Throwable $exception) { <ide> $this->logException($request, $exception); <ide> $response = $this->handleInternalError($response); <del> } catch (Exception $exception) { <del> $this->logException($request, $exception); <del> $response = $this->handleInternalError($response); <ide> } <ide> <ide> return $response;
2
Go
Go
move layer mount refcounts to mountedlayer
65d79e3e5e537039b244afd7eda29e721a93d84f
<ide><path>daemon/commit.go <ide> func (daemon *Daemon) exportContainerRw(container *container.Container) (archive <ide> <ide> archive, err := container.RWLayer.TarStream() <ide> if err != nil { <add> daemon.Unmount(container) // logging is already handled in the `Unmount` function <ide> return nil, err <ide> } <ide> return ioutils.NewReadCloserWrapper(archive, func() error { <ide><path>daemon/graphdriver/aufs/aufs.go <ide> import ( <ide> "os" <ide> "os/exec" <ide> "path" <add> "path/filepath" <ide> "strings" <ide> "sync" <ide> "syscall" <ide> func init() { <ide> graphdriver.Register("aufs", Init) <ide> } <ide> <del>type data struct { <del> referenceCount int <del> path string <del>} <del> <ide> // Driver contains information about the filesystem mounted. <del>// root of the filesystem <del>// sync.Mutex to protect against concurrent modifications <del>// active maps mount id to the count <ide> type Driver struct { <del> root string <del> uidMaps []idtools.IDMap <del> gidMaps []idtools.IDMap <del> sync.Mutex // Protects concurrent modification to active <del> active map[string]*data <add> root string <add> uidMaps []idtools.IDMap <add> gidMaps []idtools.IDMap <add> pathCacheLock sync.Mutex <add> pathCache map[string]string <ide> } <ide> <ide> // Init returns a new AUFS driver. <ide> func Init(root string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap <ide> } <ide> <ide> a := &Driver{ <del> root: root, <del> active: make(map[string]*data), <del> uidMaps: uidMaps, <del> gidMaps: gidMaps, <add> root: root, <add> uidMaps: uidMaps, <add> gidMaps: gidMaps, <add> pathCache: make(map[string]string), <ide> } <ide> <ide> rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps) <ide> func (a *Driver) Create(id, parent, mountLabel string) error { <ide> } <ide> } <ide> } <del> a.Lock() <del> a.active[id] = &data{} <del> a.Unlock() <add> <ide> return nil <ide> } <ide> <ide> func (a *Driver) createDirsFor(id string) error { <ide> <ide> // Remove will unmount and remove the given id. <ide> func (a *Driver) Remove(id string) error { <del> // Protect the a.active from concurrent access <del> a.Lock() <del> defer a.Unlock() <del> <del> m := a.active[id] <del> if m != nil { <del> if m.referenceCount > 0 { <del> return nil <del> } <del> // Make sure the dir is umounted first <del> if err := a.unmount(m); err != nil { <del> return err <del> } <add> a.pathCacheLock.Lock() <add> mountpoint, exists := a.pathCache[id] <add> a.pathCacheLock.Unlock() <add> if !exists { <add> mountpoint = a.getMountpoint(id) <ide> } <del> tmpDirs := []string{ <del> "mnt", <del> "diff", <add> if err := a.unmount(mountpoint); err != nil { <add> // no need to return here, we can still try to remove since the `Rename` will fail below if still mounted <add> logrus.Debugf("aufs: error while unmounting %s: %v", mountpoint, err) <ide> } <ide> <ide> // Atomically remove each directory in turn by first moving it out of the <ide> // way (so that docker doesn't find it anymore) before doing removal of <ide> // the whole tree. <del> for _, p := range tmpDirs { <del> realPath := path.Join(a.rootPath(), p, id) <del> tmpPath := path.Join(a.rootPath(), p, fmt.Sprintf("%s-removing", id)) <del> if err := os.Rename(realPath, tmpPath); err != nil && !os.IsNotExist(err) { <del> return err <del> } <del> defer os.RemoveAll(tmpPath) <add> tmpMntPath := path.Join(a.mntPath(), fmt.Sprintf("%s-removing", id)) <add> if err := os.Rename(mountpoint, tmpMntPath); err != nil && !os.IsNotExist(err) { <add> return err <add> } <add> defer os.RemoveAll(tmpMntPath) <add> <add> tmpDiffpath := path.Join(a.diffPath(), fmt.Sprintf("%s-removing", id)) <add> if err := os.Rename(a.getDiffPath(id), tmpDiffpath); err != nil && !os.IsNotExist(err) { <add> return err <ide> } <add> defer os.RemoveAll(tmpDiffpath) <add> <ide> // Remove the layers file for the id <ide> if err := os.Remove(path.Join(a.rootPath(), "layers", id)); err != nil && !os.IsNotExist(err) { <ide> return err <ide> } <del> if m != nil { <del> delete(a.active, id) <del> } <add> <add> a.pathCacheLock.Lock() <add> delete(a.pathCache, id) <add> a.pathCacheLock.Unlock() <ide> return nil <ide> } <ide> <ide> // Get returns the rootfs path for the id. <ide> // This will mount the dir at it's given path <ide> func (a *Driver) Get(id, mountLabel string) (string, error) { <del> // Protect the a.active from concurrent access <del> a.Lock() <del> defer a.Unlock() <del> <del> m := a.active[id] <del> if m == nil { <del> m = &data{} <del> a.active[id] = m <del> } <del> <ide> parents, err := a.getParentLayerPaths(id) <ide> if err != nil && !os.IsNotExist(err) { <ide> return "", err <ide> } <ide> <add> a.pathCacheLock.Lock() <add> m, exists := a.pathCache[id] <add> a.pathCacheLock.Unlock() <add> <add> if !exists { <add> m = a.getDiffPath(id) <add> if len(parents) > 0 { <add> m = a.getMountpoint(id) <add> } <add> } <add> <ide> // If a dir does not have a parent ( no layers )do not try to mount <ide> // just return the diff path to the data <del> m.path = path.Join(a.rootPath(), "diff", id) <ide> if len(parents) > 0 { <del> m.path = path.Join(a.rootPath(), "mnt", id) <del> if m.referenceCount == 0 { <del> if err := a.mount(id, m, mountLabel, parents); err != nil { <del> return "", err <del> } <add> if err := a.mount(id, m, mountLabel, parents); err != nil { <add> return "", err <ide> } <ide> } <del> m.referenceCount++ <del> return m.path, nil <add> <add> a.pathCacheLock.Lock() <add> a.pathCache[id] = m <add> a.pathCacheLock.Unlock() <add> return m, nil <ide> } <ide> <ide> // Put unmounts and updates list of active mounts. <ide> func (a *Driver) Put(id string) error { <del> // Protect the a.active from concurrent access <del> a.Lock() <del> defer a.Unlock() <del> <del> m := a.active[id] <del> if m == nil { <del> // but it might be still here <del> if a.Exists(id) { <del> path := path.Join(a.rootPath(), "mnt", id) <del> err := Unmount(path) <del> if err != nil { <del> logrus.Debugf("Failed to unmount %s aufs: %v", id, err) <del> } <del> } <del> return nil <add> a.pathCacheLock.Lock() <add> m, exists := a.pathCache[id] <add> if !exists { <add> m = a.getMountpoint(id) <add> a.pathCache[id] = m <ide> } <del> if count := m.referenceCount; count > 1 { <del> m.referenceCount = count - 1 <del> } else { <del> ids, _ := getParentIds(a.rootPath(), id) <del> // We only mounted if there are any parents <del> if ids != nil && len(ids) > 0 { <del> a.unmount(m) <del> } <del> delete(a.active, id) <add> a.pathCacheLock.Unlock() <add> <add> err := a.unmount(m) <add> if err != nil { <add> logrus.Debugf("Failed to unmount %s aufs: %v", id, err) <ide> } <del> return nil <add> return err <ide> } <ide> <ide> // Diff produces an archive of the changes between the specified <ide> func (a *Driver) getParentLayerPaths(id string) ([]string, error) { <ide> return layers, nil <ide> } <ide> <del>func (a *Driver) mount(id string, m *data, mountLabel string, layers []string) error { <add>func (a *Driver) mount(id string, target string, mountLabel string, layers []string) error { <ide> // If the id is mounted or we get an error return <del> if mounted, err := a.mounted(m); err != nil || mounted { <add> if mounted, err := a.mounted(target); err != nil || mounted { <ide> return err <ide> } <ide> <del> var ( <del> target = m.path <del> rw = path.Join(a.rootPath(), "diff", id) <del> ) <add> rw := a.getDiffPath(id) <ide> <ide> if err := a.aufsMount(layers, rw, target, mountLabel); err != nil { <ide> return fmt.Errorf("error creating aufs mount to %s: %v", target, err) <ide> } <ide> return nil <ide> } <ide> <del>func (a *Driver) unmount(m *data) error { <del> if mounted, err := a.mounted(m); err != nil || !mounted { <add>func (a *Driver) unmount(mountPath string) error { <add> if mounted, err := a.mounted(mountPath); err != nil || !mounted { <add> return err <add> } <add> if err := Unmount(mountPath); err != nil { <ide> return err <ide> } <del> return Unmount(m.path) <add> return nil <ide> } <ide> <del>func (a *Driver) mounted(m *data) (bool, error) { <del> var buf syscall.Statfs_t <del> if err := syscall.Statfs(m.path, &buf); err != nil { <del> return false, nil <del> } <del> return graphdriver.FsMagic(buf.Type) == graphdriver.FsMagicAufs, nil <add>func (a *Driver) mounted(mountpoint string) (bool, error) { <add> return graphdriver.Mounted(graphdriver.FsMagicAufs, mountpoint) <ide> } <ide> <ide> // Cleanup aufs and unmount all mountpoints <ide> func (a *Driver) Cleanup() error { <del> for id, m := range a.active { <add> var dirs []string <add> if err := filepath.Walk(a.mntPath(), func(path string, info os.FileInfo, err error) error { <add> if err != nil { <add> return err <add> } <add> if !info.IsDir() { <add> return nil <add> } <add> dirs = append(dirs, path) <add> return nil <add> }); err != nil { <add> return err <add> } <add> <add> for _, m := range dirs { <ide> if err := a.unmount(m); err != nil { <del> logrus.Errorf("Unmounting %s: %s", stringid.TruncateID(id), err) <add> logrus.Debugf("aufs error unmounting %s: %s", stringid.TruncateID(m), err) <ide> } <ide> } <ide> return mountpk.Unmount(a.root) <ide><path>daemon/graphdriver/aufs/aufs_test.go <ide> func TestMountedFalseResponse(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> response, err := d.mounted(d.active["1"]) <add> response, err := d.mounted(d.getDiffPath("1")) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestMountedTrueReponse(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> response, err := d.mounted(d.active["2"]) <add> response, err := d.mounted(d.pathCache["2"]) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestRemoveMountedDir(t *testing.T) { <ide> t.Fatal("mntPath should not be empty string") <ide> } <ide> <del> mounted, err := d.mounted(d.active["2"]) <add> mounted, err := d.mounted(d.pathCache["2"]) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide><path>daemon/graphdriver/aufs/dirs.go <ide> func getParentIds(root, id string) ([]string, error) { <ide> } <ide> return out, s.Err() <ide> } <add> <add>func (a *Driver) getMountpoint(id string) string { <add> return path.Join(a.mntPath(), id) <add>} <add> <add>func (a *Driver) mntPath() string { <add> return path.Join(a.rootPath(), "mnt") <add>} <add> <add>func (a *Driver) getDiffPath(id string) string { <add> return path.Join(a.diffPath(), id) <add>} <add> <add>func (a *Driver) diffPath() string { <add> return path.Join(a.rootPath(), "diff") <add>} <ide><path>daemon/graphdriver/devmapper/deviceset.go <ide> type devInfo struct { <ide> Deleted bool `json:"deleted"` <ide> devices *DeviceSet <ide> <del> mountCount int <del> mountPath string <del> <ide> // The global DeviceSet lock guarantees that we serialize all <ide> // the calls to libdevmapper (which is not threadsafe), but we <ide> // sometimes release that lock while sleeping. In that case <ide> func (devices *DeviceSet) DeleteDevice(hash string, syncDelete bool) error { <ide> devices.Lock() <ide> defer devices.Unlock() <ide> <del> // If mountcount is not zero, that means devices is still in use <del> // or has not been Put() properly. Fail device deletion. <del> <del> if info.mountCount != 0 { <del> return fmt.Errorf("devmapper: Can't delete device %v as it is still mounted. mntCount=%v", info.Hash, info.mountCount) <del> } <del> <ide> return devices.deleteDevice(info, syncDelete) <ide> } <ide> <ide> func (devices *DeviceSet) cancelDeferredRemoval(info *devInfo) error { <ide> } <ide> <ide> // Shutdown shuts down the device by unmounting the root. <del>func (devices *DeviceSet) Shutdown() error { <add>func (devices *DeviceSet) Shutdown(home string) error { <ide> logrus.Debugf("devmapper: [deviceset %s] Shutdown()", devices.devicePrefix) <ide> logrus.Debugf("devmapper: Shutting down DeviceSet: %s", devices.root) <ide> defer logrus.Debugf("devmapper: [deviceset %s] Shutdown() END", devices.devicePrefix) <ide> <del> var devs []*devInfo <del> <ide> // Stop deletion worker. This should start delivering new events to <ide> // ticker channel. That means no new instance of cleanupDeletedDevice() <ide> // will run after this call. If one instance is already running at <ide> func (devices *DeviceSet) Shutdown() error { <ide> // metadata. Hence save this early before trying to deactivate devices. <ide> devices.saveDeviceSetMetaData() <ide> <del> for _, info := range devices.Devices { <del> devs = append(devs, info) <add> // ignore the error since it's just a best effort to not try to unmount something that's mounted <add> mounts, _ := mount.GetMounts() <add> mounted := make(map[string]bool, len(mounts)) <add> for _, mnt := range mounts { <add> mounted[mnt.Mountpoint] = true <ide> } <del> devices.Unlock() <ide> <del> for _, info := range devs { <del> info.lock.Lock() <del> if info.mountCount > 0 { <add> if err := filepath.Walk(path.Join(home, "mnt"), func(p string, info os.FileInfo, err error) error { <add> if err != nil { <add> return err <add> } <add> if !info.IsDir() { <add> return nil <add> } <add> <add> if mounted[p] { <ide> // We use MNT_DETACH here in case it is still busy in some running <ide> // container. This means it'll go away from the global scope directly, <ide> // and the device will be released when that container dies. <del> if err := syscall.Unmount(info.mountPath, syscall.MNT_DETACH); err != nil { <del> logrus.Debugf("devmapper: Shutdown unmounting %s, error: %s", info.mountPath, err) <add> if err := syscall.Unmount(p, syscall.MNT_DETACH); err != nil { <add> logrus.Debugf("devmapper: Shutdown unmounting %s, error: %s", p, err) <ide> } <add> } <ide> <del> devices.Lock() <del> if err := devices.deactivateDevice(info); err != nil { <del> logrus.Debugf("devmapper: Shutdown deactivate %s , error: %s", info.Hash, err) <add> if devInfo, err := devices.lookupDevice(path.Base(p)); err != nil { <add> logrus.Debugf("devmapper: Shutdown lookup device %s, error: %s", path.Base(p), err) <add> } else { <add> if err := devices.deactivateDevice(devInfo); err != nil { <add> logrus.Debugf("devmapper: Shutdown deactivate %s , error: %s", devInfo.Hash, err) <ide> } <del> devices.Unlock() <ide> } <del> info.lock.Unlock() <add> <add> return nil <add> }); err != nil && !os.IsNotExist(err) { <add> devices.Unlock() <add> return err <ide> } <ide> <add> devices.Unlock() <add> <ide> info, _ := devices.lookupDeviceWithLock("") <ide> if info != nil { <ide> info.lock.Lock() <ide> func (devices *DeviceSet) MountDevice(hash, path, mountLabel string) error { <ide> devices.Lock() <ide> defer devices.Unlock() <ide> <del> if info.mountCount > 0 { <del> if path != info.mountPath { <del> return fmt.Errorf("devmapper: Trying to mount devmapper device in multiple places (%s, %s)", info.mountPath, path) <del> } <del> <del> info.mountCount++ <del> return nil <del> } <del> <ide> if err := devices.activateDeviceIfNeeded(info, false); err != nil { <ide> return fmt.Errorf("devmapper: Error activating devmapper device for '%s': %s", hash, err) <ide> } <ide> func (devices *DeviceSet) MountDevice(hash, path, mountLabel string) error { <ide> return fmt.Errorf("devmapper: Error mounting '%s' on '%s': %s", info.DevName(), path, err) <ide> } <ide> <del> info.mountCount = 1 <del> info.mountPath = path <del> <ide> return nil <ide> } <ide> <ide> func (devices *DeviceSet) UnmountDevice(hash, mountPath string) error { <ide> devices.Lock() <ide> defer devices.Unlock() <ide> <del> // If there are running containers when daemon crashes, during daemon <del> // restarting, it will kill running containers and will finally call <del> // Put() without calling Get(). So info.MountCount may become negative. <del> // if info.mountCount goes negative, we do the unmount and assign <del> // it to 0. <del> <del> info.mountCount-- <del> if info.mountCount > 0 { <del> return nil <del> } else if info.mountCount < 0 { <del> logrus.Warnf("devmapper: Mount count of device went negative. Put() called without matching Get(). Resetting count to 0") <del> info.mountCount = 0 <del> } <del> <ide> logrus.Debugf("devmapper: Unmount(%s)", mountPath) <ide> if err := syscall.Unmount(mountPath, syscall.MNT_DETACH); err != nil { <ide> return err <ide> func (devices *DeviceSet) UnmountDevice(hash, mountPath string) error { <ide> return err <ide> } <ide> <del> info.mountPath = "" <del> <ide> return nil <ide> } <ide> <ide><path>daemon/graphdriver/devmapper/driver.go <ide> func (d *Driver) GetMetadata(id string) (map[string]string, error) { <ide> <ide> // Cleanup unmounts a device. <ide> func (d *Driver) Cleanup() error { <del> err := d.DeviceSet.Shutdown() <add> err := d.DeviceSet.Shutdown(d.home) <ide> <ide> if err2 := mount.Unmount(d.home); err == nil { <ide> err = err2 <ide><path>daemon/graphdriver/driver_freebsd.go <ide> package graphdriver <ide> <add>import "syscall" <add> <ide> var ( <ide> // Slice of drivers that should be used in an order <ide> priority = []string{ <ide> "zfs", <ide> } <ide> ) <add> <add>// Mounted checks if the given path is mounted as the fs type <add>func Mounted(fsType FsMagic, mountPath string) (bool, error) { <add> var buf syscall.Statfs_t <add> if err := syscall.Statfs(mountPath, &buf); err != nil { <add> return false, err <add> } <add> return FsMagic(buf.Type) == fsType, nil <add>} <ide><path>daemon/graphdriver/driver_linux.go <ide> const ( <ide> FsMagicXfs = FsMagic(0x58465342) <ide> // FsMagicZfs filesystem id for Zfs <ide> FsMagicZfs = FsMagic(0x2fc12fc1) <add> // FsMagicOverlay filesystem id for overlay <add> FsMagicOverlay = FsMagic(0x794C7630) <ide> ) <ide> <ide> var ( <ide> func GetFSMagic(rootpath string) (FsMagic, error) { <ide> } <ide> return FsMagic(buf.Type), nil <ide> } <add> <add>// Mounted checks if the given path is mounted as the fs type <add>func Mounted(fsType FsMagic, mountPath string) (bool, error) { <add> var buf syscall.Statfs_t <add> if err := syscall.Statfs(mountPath, &buf); err != nil { <add> return false, err <add> } <add> return FsMagic(buf.Type) == fsType, nil <add>} <ide><path>daemon/graphdriver/overlay/overlay.go <ide> func (d *naiveDiffDriverWithApply) ApplyDiff(id, parent string, diff archive.Rea <ide> // of that. This means all child images share file (but not directory) <ide> // data with the parent. <ide> <del>// ActiveMount contains information about the count, path and whether is mounted or not. <del>// This information is part of the Driver, that contains list of active mounts that are part of this overlay. <del>type ActiveMount struct { <del> count int <del> path string <del> mounted bool <del>} <del> <ide> // Driver contains information about the home directory and the list of active mounts that are created using this driver. <ide> type Driver struct { <del> home string <del> sync.Mutex // Protects concurrent modification to active <del> active map[string]*ActiveMount <del> uidMaps []idtools.IDMap <del> gidMaps []idtools.IDMap <add> home string <add> pathCacheLock sync.Mutex <add> pathCache map[string]string <add> uidMaps []idtools.IDMap <add> gidMaps []idtools.IDMap <ide> } <ide> <ide> var backingFs = "<unknown>" <ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap <ide> } <ide> <ide> d := &Driver{ <del> home: home, <del> active: make(map[string]*ActiveMount), <del> uidMaps: uidMaps, <del> gidMaps: gidMaps, <add> home: home, <add> pathCache: make(map[string]string), <add> uidMaps: uidMaps, <add> gidMaps: gidMaps, <ide> } <ide> <ide> return NaiveDiffDriverWithApply(d, uidMaps, gidMaps), nil <ide> func (d *Driver) Remove(id string) error { <ide> if err := os.RemoveAll(d.dir(id)); err != nil && !os.IsNotExist(err) { <ide> return err <ide> } <add> d.pathCacheLock.Lock() <add> delete(d.pathCache, id) <add> d.pathCacheLock.Unlock() <ide> return nil <ide> } <ide> <ide> // Get creates and mounts the required file system for the given id and returns the mount path. <ide> func (d *Driver) Get(id string, mountLabel string) (string, error) { <del> // Protect the d.active from concurrent access <del> d.Lock() <del> defer d.Unlock() <del> <del> mount := d.active[id] <del> if mount != nil { <del> mount.count++ <del> return mount.path, nil <del> } <del> <del> mount = &ActiveMount{count: 1} <del> <ide> dir := d.dir(id) <ide> if _, err := os.Stat(dir); err != nil { <ide> return "", err <ide> func (d *Driver) Get(id string, mountLabel string) (string, error) { <ide> // If id has a root, just return it <ide> rootDir := path.Join(dir, "root") <ide> if _, err := os.Stat(rootDir); err == nil { <del> mount.path = rootDir <del> d.active[id] = mount <del> return mount.path, nil <add> d.pathCacheLock.Lock() <add> d.pathCache[id] = rootDir <add> d.pathCacheLock.Unlock() <add> return rootDir, nil <ide> } <ide> <ide> lowerID, err := ioutil.ReadFile(path.Join(dir, "lower-id")) <ide> func (d *Driver) Get(id string, mountLabel string) (string, error) { <ide> if err := os.Chown(path.Join(workDir, "work"), rootUID, rootGID); err != nil { <ide> return "", err <ide> } <del> mount.path = mergedDir <del> mount.mounted = true <del> d.active[id] = mount <ide> <del> return mount.path, nil <add> d.pathCacheLock.Lock() <add> d.pathCache[id] = mergedDir <add> d.pathCacheLock.Unlock() <add> <add> return mergedDir, nil <add>} <add> <add>func (d *Driver) mounted(dir string) (bool, error) { <add> return graphdriver.Mounted(graphdriver.FsMagicOverlay, dir) <ide> } <ide> <ide> // Put unmounts the mount path created for the give id. <ide> func (d *Driver) Put(id string) error { <del> // Protect the d.active from concurrent access <del> d.Lock() <del> defer d.Unlock() <add> d.pathCacheLock.Lock() <add> mountpoint, exists := d.pathCache[id] <add> d.pathCacheLock.Unlock() <ide> <del> mount := d.active[id] <del> if mount == nil { <add> if !exists { <ide> logrus.Debugf("Put on a non-mounted device %s", id) <ide> // but it might be still here <ide> if d.Exists(id) { <del> mergedDir := path.Join(d.dir(id), "merged") <del> err := syscall.Unmount(mergedDir, 0) <del> if err != nil { <del> logrus.Debugf("Failed to unmount %s overlay: %v", id, err) <del> } <add> mountpoint = path.Join(d.dir(id), "merged") <ide> } <del> return nil <del> } <ide> <del> mount.count-- <del> if mount.count > 0 { <del> return nil <add> d.pathCacheLock.Lock() <add> d.pathCache[id] = mountpoint <add> d.pathCacheLock.Unlock() <ide> } <ide> <del> defer delete(d.active, id) <del> if mount.mounted { <del> err := syscall.Unmount(mount.path, 0) <del> if err != nil { <add> if mounted, err := d.mounted(mountpoint); mounted || err != nil { <add> if err = syscall.Unmount(mountpoint, 0); err != nil { <ide> logrus.Debugf("Failed to unmount %s overlay: %v", id, err) <ide> } <ide> return err <ide><path>daemon/graphdriver/windows/windows.go <ide> import ( <ide> "path" <ide> "path/filepath" <ide> "strings" <del> "sync" <ide> "syscall" <ide> "time" <ide> <ide> const ( <ide> type Driver struct { <ide> // info stores the shim driver information <ide> info hcsshim.DriverInfo <del> // Mutex protects concurrent modification to active <del> sync.Mutex <del> // active stores references to the activated layers <del> active map[string]int <ide> } <ide> <ide> var _ graphdriver.DiffGetterDriver = &Driver{} <ide> func InitFilter(home string, options []string, uidMaps, gidMaps []idtools.IDMap) <ide> HomeDir: home, <ide> Flavour: filterDriver, <ide> }, <del> active: make(map[string]int), <ide> } <ide> return d, nil <ide> } <ide> func InitDiff(home string, options []string, uidMaps, gidMaps []idtools.IDMap) ( <ide> HomeDir: home, <ide> Flavour: diffDriver, <ide> }, <del> active: make(map[string]int), <ide> } <ide> return d, nil <ide> } <ide> func (d *Driver) Get(id, mountLabel string) (string, error) { <ide> logrus.Debugf("WindowsGraphDriver Get() id %s mountLabel %s", id, mountLabel) <ide> var dir string <ide> <del> d.Lock() <del> defer d.Unlock() <del> <ide> rID, err := d.resolveID(id) <ide> if err != nil { <ide> return "", err <ide> func (d *Driver) Get(id, mountLabel string) (string, error) { <ide> return "", err <ide> } <ide> <del> if d.active[rID] == 0 { <del> if err := hcsshim.ActivateLayer(d.info, rID); err != nil { <del> return "", err <del> } <del> if err := hcsshim.PrepareLayer(d.info, rID, layerChain); err != nil { <del> if err2 := hcsshim.DeactivateLayer(d.info, rID); err2 != nil { <del> logrus.Warnf("Failed to Deactivate %s: %s", id, err) <del> } <del> return "", err <add> if err := hcsshim.ActivateLayer(d.info, rID); err != nil { <add> return "", err <add> } <add> if err := hcsshim.PrepareLayer(d.info, rID, layerChain); err != nil { <add> if err2 := hcsshim.DeactivateLayer(d.info, rID); err2 != nil { <add> logrus.Warnf("Failed to Deactivate %s: %s", id, err) <ide> } <add> return "", err <ide> } <ide> <ide> mountPath, err := hcsshim.GetLayerMountPath(d.info, rID) <ide> func (d *Driver) Get(id, mountLabel string) (string, error) { <ide> return "", err <ide> } <ide> <del> d.active[rID]++ <del> <ide> // If the layer has a mount path, use that. Otherwise, use the <ide> // folder path. <ide> if mountPath != "" { <ide> func (d *Driver) Put(id string) error { <ide> return err <ide> } <ide> <del> d.Lock() <del> defer d.Unlock() <del> <del> if d.active[rID] > 1 { <del> d.active[rID]-- <del> } else if d.active[rID] == 1 { <del> if err := hcsshim.UnprepareLayer(d.info, rID); err != nil { <del> return err <del> } <del> if err := hcsshim.DeactivateLayer(d.info, rID); err != nil { <del> return err <del> } <del> delete(d.active, rID) <add> if err := hcsshim.UnprepareLayer(d.info, rID); err != nil { <add> return err <ide> } <del> <del> return nil <add> return hcsshim.DeactivateLayer(d.info, rID) <ide> } <ide> <ide> // Cleanup ensures the information the driver stores is properly removed. <ide> func (d *Driver) Cleanup() error { <ide> <ide> // Diff produces an archive of the changes between the specified <ide> // layer and its parent layer which may be "". <add>// The layer should be mounted when calling this function <ide> func (d *Driver) Diff(id, parent string) (_ archive.Archive, err error) { <ide> rID, err := d.resolveID(id) <ide> if err != nil { <ide> return <ide> } <ide> <del> // Getting the layer paths must be done outside of the lock. <ide> layerChain, err := d.getLayerChain(rID) <ide> if err != nil { <ide> return <ide> } <ide> <del> var undo func() <del> <del> d.Lock() <del> <del> // To support export, a layer must be activated but not prepared. <del> if d.info.Flavour == filterDriver { <del> if d.active[rID] == 0 { <del> if err = hcsshim.ActivateLayer(d.info, rID); err != nil { <del> d.Unlock() <del> return <del> } <del> undo = func() { <del> if err := hcsshim.DeactivateLayer(d.info, rID); err != nil { <del> logrus.Warnf("Failed to Deactivate %s: %s", rID, err) <del> } <del> } <del> } else { <del> if err = hcsshim.UnprepareLayer(d.info, rID); err != nil { <del> d.Unlock() <del> return <del> } <del> undo = func() { <del> if err := hcsshim.PrepareLayer(d.info, rID, layerChain); err != nil { <del> logrus.Warnf("Failed to re-PrepareLayer %s: %s", rID, err) <del> } <del> } <del> } <add> // this is assuming that the layer is unmounted <add> if err := hcsshim.UnprepareLayer(d.info, rID); err != nil { <add> return nil, err <ide> } <del> <del> d.Unlock() <add> defer func() { <add> if err := hcsshim.PrepareLayer(d.info, rID, layerChain); err != nil { <add> logrus.Warnf("Failed to Deactivate %s: %s", rID, err) <add> } <add> }() <ide> <ide> arch, err := d.exportLayer(rID, layerChain) <ide> if err != nil { <del> undo() <ide> return <ide> } <ide> return ioutils.NewReadCloserWrapper(arch, func() error { <del> defer undo() <ide> return arch.Close() <ide> }), nil <ide> } <ide> <ide> // Changes produces a list of changes between the specified layer <ide> // and its parent layer. If parent is "", then all changes will be ADD changes. <add>// The layer should be mounted when calling this function <ide> func (d *Driver) Changes(id, parent string) ([]archive.Change, error) { <ide> rID, err := d.resolveID(id) <ide> if err != nil { <ide> func (d *Driver) Changes(id, parent string) ([]archive.Change, error) { <ide> return nil, err <ide> } <ide> <del> d.Lock() <del> if d.info.Flavour == filterDriver { <del> if d.active[rID] == 0 { <del> if err = hcsshim.ActivateLayer(d.info, rID); err != nil { <del> d.Unlock() <del> return nil, err <del> } <del> defer func() { <del> if err := hcsshim.DeactivateLayer(d.info, rID); err != nil { <del> logrus.Warnf("Failed to Deactivate %s: %s", rID, err) <del> } <del> }() <del> } else { <del> if err = hcsshim.UnprepareLayer(d.info, rID); err != nil { <del> d.Unlock() <del> return nil, err <del> } <del> defer func() { <del> if err := hcsshim.PrepareLayer(d.info, rID, parentChain); err != nil { <del> logrus.Warnf("Failed to re-PrepareLayer %s: %s", rID, err) <del> } <del> }() <del> } <add> // this is assuming that the layer is unmounted <add> if err := hcsshim.UnprepareLayer(d.info, rID); err != nil { <add> return nil, err <ide> } <del> d.Unlock() <add> defer func() { <add> if err := hcsshim.PrepareLayer(d.info, rID, parentChain); err != nil { <add> logrus.Warnf("Failed to Deactivate %s: %s", rID, err) <add> } <add> }() <ide> <ide> r, err := hcsshim.NewLayerReader(d.info, id, parentChain) <ide> if err != nil { <ide> func (d *Driver) Changes(id, parent string) ([]archive.Change, error) { <ide> // ApplyDiff extracts the changeset from the given diff into the <ide> // layer with the specified id and parent, returning the size of the <ide> // new layer in bytes. <add>// The layer should not be mounted when calling this function <ide> func (d *Driver) ApplyDiff(id, parent string, diff archive.Reader) (size int64, err error) { <ide> rPId, err := d.resolveID(parent) <ide> if err != nil { <ide><path>daemon/graphdriver/zfs/zfs.go <ide> import ( <ide> "github.com/opencontainers/runc/libcontainer/label" <ide> ) <ide> <del>type activeMount struct { <del> count int <del> path string <del> mounted bool <del>} <del> <ide> type zfsOptions struct { <ide> fsName string <ide> mountPath string <ide> func Init(base string, opt []string, uidMaps, gidMaps []idtools.IDMap) (graphdri <ide> dataset: rootDataset, <ide> options: options, <ide> filesystemsCache: filesystemsCache, <del> active: make(map[string]*activeMount), <ide> uidMaps: uidMaps, <ide> gidMaps: gidMaps, <ide> } <ide> type Driver struct { <ide> options zfsOptions <ide> sync.Mutex // protects filesystem cache against concurrent access <ide> filesystemsCache map[string]bool <del> active map[string]*activeMount <ide> uidMaps []idtools.IDMap <ide> gidMaps []idtools.IDMap <ide> } <ide> func (d *Driver) Remove(id string) error { <ide> <ide> // Get returns the mountpoint for the given id after creating the target directories if necessary. <ide> func (d *Driver) Get(id, mountLabel string) (string, error) { <del> d.Lock() <del> defer d.Unlock() <del> <del> mnt := d.active[id] <del> if mnt != nil { <del> mnt.count++ <del> return mnt.path, nil <del> } <del> <del> mnt = &activeMount{count: 1} <del> <ide> mountpoint := d.mountPath(id) <ide> filesystem := d.zfsPath(id) <ide> options := label.FormatMountLabel("", mountLabel) <ide> func (d *Driver) Get(id, mountLabel string) (string, error) { <ide> if err := os.Chown(mountpoint, rootUID, rootGID); err != nil { <ide> return "", fmt.Errorf("error modifying zfs mountpoint (%s) directory ownership: %v", mountpoint, err) <ide> } <del> mnt.path = mountpoint <del> mnt.mounted = true <del> d.active[id] = mnt <ide> <ide> return mountpoint, nil <ide> } <ide> <ide> // Put removes the existing mountpoint for the given id if it exists. <ide> func (d *Driver) Put(id string) error { <del> d.Lock() <del> defer d.Unlock() <del> <del> mnt := d.active[id] <del> if mnt == nil { <del> logrus.Debugf("[zfs] Put on a non-mounted device %s", id) <del> // but it might be still here <del> if d.Exists(id) { <del> err := mount.Unmount(d.mountPath(id)) <del> if err != nil { <del> logrus.Debugf("[zfs] Failed to unmount %s zfs fs: %v", id, err) <del> } <del> } <del> return nil <del> } <del> <del> mnt.count-- <del> if mnt.count > 0 { <del> return nil <add> mountpoint := d.mountPath(id) <add> mounted, err := graphdriver.Mounted(graphdriver.FsMagicZfs, mountpoint) <add> if err != nil || !mounted { <add> return err <ide> } <ide> <del> defer delete(d.active, id) <del> if mnt.mounted { <del> logrus.Debugf(`[zfs] unmount("%s")`, mnt.path) <add> logrus.Debugf(`[zfs] unmount("%s")`, mountpoint) <ide> <del> if err := mount.Unmount(mnt.path); err != nil { <del> return fmt.Errorf("error unmounting to %s: %v", mnt.path, err) <del> } <add> if err := mount.Unmount(mountpoint); err != nil { <add> return fmt.Errorf("error unmounting to %s: %v", mountpoint, err) <ide> } <ide> return nil <ide> } <ide> <ide> // Exists checks to see if the cache entry exists for the given id. <ide> func (d *Driver) Exists(id string) bool { <add> d.Lock() <add> defer d.Unlock() <ide> return d.filesystemsCache[d.zfsPath(id)] == true <ide> } <ide><path>integration-cli/benchmark_test.go <add>package main <add> <add>import ( <add> "fmt" <add> "io/ioutil" <add> "os" <add> "runtime" <add> "strings" <add> "sync" <add> <add> "github.com/docker/docker/pkg/integration/checker" <add> "github.com/go-check/check" <add>) <add> <add>func (s *DockerSuite) BenchmarkConcurrentContainerActions(c *check.C) { <add> maxConcurrency := runtime.GOMAXPROCS(0) <add> numIterations := c.N <add> outerGroup := &sync.WaitGroup{} <add> outerGroup.Add(maxConcurrency) <add> chErr := make(chan error, numIterations*2*maxConcurrency) <add> <add> for i := 0; i < maxConcurrency; i++ { <add> go func() { <add> defer outerGroup.Done() <add> innerGroup := &sync.WaitGroup{} <add> innerGroup.Add(2) <add> <add> go func() { <add> defer innerGroup.Done() <add> for i := 0; i < numIterations; i++ { <add> args := []string{"run", "-d", defaultSleepImage} <add> args = append(args, defaultSleepCommand...) <add> out, _, err := dockerCmdWithError(args...) <add> if err != nil { <add> chErr <- fmt.Errorf(out) <add> return <add> } <add> <add> id := strings.TrimSpace(out) <add> tmpDir, err := ioutil.TempDir("", "docker-concurrent-test-"+id) <add> if err != nil { <add> chErr <- err <add> return <add> } <add> defer os.RemoveAll(tmpDir) <add> out, _, err = dockerCmdWithError("cp", id+":/tmp", tmpDir) <add> if err != nil { <add> chErr <- fmt.Errorf(out) <add> return <add> } <add> <add> out, _, err = dockerCmdWithError("kill", id) <add> if err != nil { <add> chErr <- fmt.Errorf(out) <add> } <add> <add> out, _, err = dockerCmdWithError("start", id) <add> if err != nil { <add> chErr <- fmt.Errorf(out) <add> } <add> <add> out, _, err = dockerCmdWithError("kill", id) <add> if err != nil { <add> chErr <- fmt.Errorf(out) <add> } <add> <add> // don't do an rm -f here since it can potentially ignore errors from the graphdriver <add> out, _, err = dockerCmdWithError("rm", id) <add> if err != nil { <add> chErr <- fmt.Errorf(out) <add> } <add> } <add> }() <add> <add> go func() { <add> defer innerGroup.Done() <add> for i := 0; i < numIterations; i++ { <add> out, _, err := dockerCmdWithError("ps") <add> if err != nil { <add> chErr <- fmt.Errorf(out) <add> } <add> } <add> }() <add> <add> innerGroup.Wait() <add> }() <add> } <add> <add> outerGroup.Wait() <add> close(chErr) <add> <add> for err := range chErr { <add> c.Assert(err, checker.IsNil) <add> } <add>} <ide><path>layer/layer.go <ide> var ( <ide> // to be created which would result in a layer depth <ide> // greater than the 125 max. <ide> ErrMaxDepthExceeded = errors.New("max depth exceeded") <add> <add> // ErrNotSupported is used when the action is not supppoted <add> // on the current platform <add> ErrNotSupported = errors.New("not support on this platform") <ide> ) <ide> <ide> // ChainID is the content-addressable ID of a layer. <ide><path>layer/mounted_layer.go <ide> type mountedLayer struct { <ide> mountID string <ide> initID string <ide> parent *roLayer <add> path string <ide> layerStore *layerStore <ide> <ide> references map[RWLayer]*referencedRWLayer <ide> func (rl *referencedRWLayer) Mount(mountLabel string) (string, error) { <ide> return "", ErrLayerNotRetained <ide> } <ide> <del> rl.activityCount++ <del> return rl.mountedLayer.Mount(mountLabel) <add> if rl.activityCount > 0 { <add> rl.activityCount++ <add> return rl.path, nil <add> } <add> <add> m, err := rl.mountedLayer.Mount(mountLabel) <add> if err == nil { <add> rl.activityCount++ <add> rl.path = m <add> } <add> return m, err <ide> } <ide> <add>// Unmount decrements the activity count and unmounts the underlying layer <add>// Callers should only call `Unmount` once per call to `Mount`, even on error. <ide> func (rl *referencedRWLayer) Unmount() error { <ide> rl.activityL.Lock() <ide> defer rl.activityL.Unlock() <ide> func (rl *referencedRWLayer) Unmount() error { <ide> if rl.activityCount == -1 { <ide> return ErrLayerNotRetained <ide> } <add> <ide> rl.activityCount-- <add> if rl.activityCount > 0 { <add> return nil <add> } <ide> <ide> return rl.mountedLayer.Unmount() <ide> }
14
Javascript
Javascript
remove extra space
60033b7db1eb7bf542a46df420f26ebadd920204
<ide><path>spec/config-file-spec.js <ide> describe('ConfigFile', () => { <ide> }) <ide> }) <ide> <del> describe('when the file is updated with invalid CSON', () => { <add> describe('when the file is updated with invalid CSON', () => { <ide> it('notifies onDidError observers', async () => { <ide> configFile = new ConfigFile(filePath) <ide> subscription = await configFile.watch()
1
Javascript
Javascript
change the format of textcontent to be an array
668c2867d473ff95e3f7124215e57ade489eec2d
<ide><path>src/evaluator.js <ide> var PartialEvaluator = (function PartialEvaluatorClosure() { <ide> <ide> getTextContent: function partialEvaluatorGetIRQueue(stream, resources, state) { <ide> if (!state) { <del> state = { <del> text: '', <del> mapping: [] <del> }; <add> state = []; <ide> } <ide> <ide> var self = this; <ide> var PartialEvaluator = (function PartialEvaluatorClosure() { <ide> var res = resources; <ide> var args = [], obj; <ide> <del> var text = state.text; <ide> var chunk = ''; <del> var commandOffset = state.mapping; <ide> var font = null; <ide> while (!isEOF(obj = parser.getObj())) { <ide> if (isCmd(obj)) { <ide> var PartialEvaluator = (function PartialEvaluatorClosure() { <ide> <ide> // Add some spacing between the text here and the text of the <ide> // xForm. <del> text = text + ' '; <ide> <del> state.text = text; <ide> state = this.getTextContent( <ide> xobj, <ide> xobj.dict.get('Resources') || resources, <ide> state <ide> ); <del> text = state.text; <ide> break; <ide> } // switch <ide> if (chunk !== '') { <del> commandOffset.push(text.length); <del> text += chunk; <add> state.push(chunk); <ide> chunk = ''; <ide> } <ide> <ide> var PartialEvaluator = (function PartialEvaluatorClosure() { <ide> } <ide> } <ide> <del> return { <del> text: text, <del> mapping: commandOffset <del> }; <add> return state; <ide> }, <ide> <ide> extractDataStructures: function <ide><path>web/viewer.js <ide> var PDFView = { <ide> function extractPageText(pageIndex) { <ide> self.pages[pageIndex].pdfPage.getTextContent().then( <ide> function textContentResolved(textContent) { <del> self.pageText[pageIndex] = textContent.text; <add> self.pageText[pageIndex] = textContent.join(''); <ide> self.search(); <ide> if ((pageIndex + 1) < self.pages.length) <ide> extractPageText(pageIndex + 1);
2
Text
Text
add details for july 2022 security releases
15bb82b268584ad206606ffd46cc78c929c93fca
<ide><path>doc/changelogs/CHANGELOG_V18.md <ide> <ide> This is a security release. <ide> <del>### Notable Changes <add>### Notable changes <ide> <del>* \[[`3f0c3e142d`](https://github.com/nodejs/node/commit/3f0c3e142d)] - **(SEMVER-MAJOR)** **src,deps,build,test**: add OpenSSL config appname (Daniel Bevenius) [#43124](https://github.com/nodejs/node/pull/43124) <del>* \[[`9578158ff8`](https://github.com/nodejs/node/commit/9578158ff8)] - **(SEMVER-MAJOR)** **src,doc,test**: add --openssl-shared-config option (Daniel Bevenius) [#43124](https://github.com/nodejs/node/pull/43124) <del> * Node.js now reads `nodejs_conf` section in the `openssl` config <del>* \[[`dc7af13486`](https://github.com/nodejs/node/commit/dc7af13486)] - **deps**: update archs files for quictls/openssl-3.0.5+quic (RafaelGSS) [#43693](https://github.com/nodejs/node/pull/43693) <del>* \[[`fa72c534eb`](https://github.com/nodejs/node/commit/fa72c534eb)] - **deps**: upgrade openssl sources to quictls/openssl-3.0.5+quic (RafaelGSS) [#43693](https://github.com/nodejs/node/pull/43693) <add>The following CVEs are fixed in this release: <add> <add>* **[CVE-2022-2097](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-2097)**: OpenSSL - AES OCB fails to encrypt some bytes (Medium) <add>* **[CVE-2022-32212](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-32212)**: DNS rebinding in --inspect via invalid IP addresses (High) <add>* **[CVE-2022-32213](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-32213)**: HTTP Request Smuggling - Flawed Parsing of Transfer-Encoding (Medium) <add>* **[CVE-2022-32214](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-32214)**: HTTP Request Smuggling - Improper Delimiting of Header Fields (Medium) <add>* **[CVE-2022-32215](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-32215)**: HTTP Request Smuggling - Incorrect Parsing of Multi-line Transfer-Encoding (Medium) <add>* **[CVE-2022-32222](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-32222)**: Attempt to read openssl.cnf from /home/iojs/build/ upon startup (Medium) <add>* **[CVE-2022-32223](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-32223)**: DLL Hijacking on Windows (High) <add> <add>More detailed information on each of the vulnerabilities can be found in [July 7th 2022 Security Releases](https://nodejs.org/en/blog/vulnerability/july-2022-security-releases/) blog post. <add> <add>#### llhttp updated to 6.0.7 <add> <add>`llhttp` is updated to 6.0.7 which includes fixes for the following vulnerabilities. <add> <add>* **HTTP Request Smuggling - Flawed Parsing of Transfer-Encoding (Medium)([CVE-2022-32213](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-32214) )**: The `llhttp` parser in the `http` module does not correctly parse and validate Transfer-Encoding headers. This can lead to HTTP Request Smuggling (HRS). <add>* **HTTP Request Smuggling - Improper Delimiting of Header Fields (Medium)([CVE-2022-32214](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-32214))**: The `llhttp` parser in the `http` module does not strictly use the CRLF sequence to delimit HTTP requests. This can lead to HTTP Request Smuggling. <add> * **Note**: This can be considered a breaking change due to disabling LF header delimiting. To enable LF header delimiting you can specify the `--insecure-http-parser` command-line flag, but note that this will additionally enable other insecure behaviours. <add>* **HTTP Request Smuggling - Incorrect Parsing of Multi-line Transfer-Encoding (Medium)([CVE-2022-32215](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-32215))**: The `llhttp` parser in the `http` module does not correctly handle multi-line Transfer-Encoding headers. This can lead to HTTP Request Smuggling (HRS). <add> <add>Some of these fixes required breaking changes, so you may be impacted by this update. <add> <add>#### Default OpenSSL Configuration <add> <add>To resolve **[CVE-2022-32223](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-32223)**: DLL Hijacking on Windows (High), changes were made to how Node.js loads OpenSSL configuration by default. <add> <add>**[CVE-2022-32223](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-32223)** could be exploited if the victim has the following dependencies on Windows machine: <add> <add>* OpenSSL has been installed and `C:\Program Files\Common Files\SSL\openssl.cnf` exists. <add> <add>Whenever the above conditions are present, `node.exe` will search for `providers.dll` in the current user directory. After that, `node.exe` will try to search for `providers.dll` by the DLL Search Order in Windows. An attacker can place the malicious file `providers.dll` under a variety of paths to exploit this vulnerability. <add> <add>Node.js can use an OpenSSL configuration file by specifying the environment variable `OPENSSL_CONF`, or using the command-line option `--openssl-conf`, and if none of those are specified will default to reading the default OpenSSL configuration file `openssl.cnf`. <add> <add>From this release, Node.js will only read a section that is, by default, named `nodejs_conf`. If you were previously relying on the configuration specified in the shared section of the `openssl.cnf` file, you may be affected by this change. You can fall back to the previous behavior to read the default section by: <add> <add>* Specifying the `--openssl-shared-config` command-line flag; or <add>* Creating a new `nodejs_conf` section in that file and copying the contents of the default section into the new `nodejs_conf` section. <add> <add>Note that when specifying `--openssl-shared-config` or defining `nodejs_conf` in your `openssl.cnf`, you should be cautious and review your configuration as it could lead to you being vulnerable to similar DLL exploit attacks. <ide> <ide> ### Commits <ide> <ide> * \[[`dc7af13486`](https://github.com/nodejs/node/commit/dc7af13486)] - **deps**: update archs files for quictls/openssl-3.0.5+quic (RafaelGSS) [#43693](https://github.com/nodejs/node/pull/43693) <ide> * \[[`fa72c534eb`](https://github.com/nodejs/node/commit/fa72c534eb)] - **deps**: upgrade openssl sources to quictls/openssl-3.0.5+quic (RafaelGSS) [#43693](https://github.com/nodejs/node/pull/43693) <ide> * \[[`a5fc2deb43`](https://github.com/nodejs/node/commit/a5fc2deb43)] - **deps**: update default openssl.cnf directory (Michael Dawson) [nodejs-private/node-private#335](https://github.com/nodejs-private/node-private/pull/335) <del>* \[[`f2407748e3`](https://github.com/nodejs/node/commit/f2407748e3)] - **http**: stricter Transfer-Encoding and header separator parsing (Paolo Insogna) [nodejs-private/node-private#315](https://github.com/nodejs-private/node-private/pull/315) <add>* \[[`f2407748e3`](https://github.com/nodejs/node/commit/f2407748e3)] - **(SEMVER-MAJOR)** **http**: stricter Transfer-Encoding and header separator parsing (Paolo Insogna) [nodejs-private/node-private#315](https://github.com/nodejs-private/node-private/pull/315) <ide> * \[[`e4af5eba95`](https://github.com/nodejs/node/commit/e4af5eba95)] - **src**: fix IPv4 validation in inspector\_socket (Tobias Nießen) [nodejs-private/node-private#320](https://github.com/nodejs-private/node-private/pull/320) <ide> * \[[`3f0c3e142d`](https://github.com/nodejs/node/commit/3f0c3e142d)] - **(SEMVER-MAJOR)** **src,deps,build,test**: add OpenSSL config appname (Daniel Bevenius) [#43124](https://github.com/nodejs/node/pull/43124) <del>* \[[`9578158ff8`](https://github.com/nodejs/node/commit/9578158ff8)] - **(SEMVER-MAJOR)** **src,doc,test**: add --openssl-shared-config option (Daniel Bevenius) [#43124](https://github.com/nodejs/node/pull/43124) <add>* \[[`9578158ff8`](https://github.com/nodejs/node/commit/9578158ff8)] - **(SEMVER-MINOR)** **src,doc,test**: add --openssl-shared-config option (Daniel Bevenius) [#43124](https://github.com/nodejs/node/pull/43124) <ide> <ide> <a id="18.4.0"></a> <ide>
1
PHP
PHP
set the timezone if it is set for mysql
1a59fa9d411387f92254411dd97eb512aa8f7063
<ide><path>src/Illuminate/Database/Connectors/MySqlConnector.php <ide> public function connect(array $config) <ide> <ide> $connection->prepare($names)->execute(); <ide> <add> // Next, we will check to see if a timezone has been specified in this config <add> // and if it has we will issue a statement to modify the timezone with the <add> // database. Setting this DB timezone is an optional configuration item. <add> if (isset($config['timezone'])) <add> { <add> $connection->prepare( <add> 'set time_zone="'.$config['timezone'].'"' <add> )->execute(); <add> } <add> <ide> // If the "strict" option has been configured for the connection we'll enable <ide> // strict mode on all of these tables. This enforces some extra rules when <ide> // using the MySQL database system and is a quicker way to enforce them.
1
Python
Python
fix failing empty serializer test
cba972911a90bdc0050bc48397bc70e1a062040d
<ide><path>rest_framework/tests/test_serializer.py <ide> def test_empty(self): <ide> 'email': '', <ide> 'content': '', <ide> 'created': None, <add> 'sub_comment': '' <ide> } <ide> self.assertEqual(serializer.data, expected) <ide>
1
Ruby
Ruby
fix return conditions
b4adf2a42e48e6e92de45b9536373998bf8426c0
<ide><path>Library/Homebrew/livecheck/strategy/page_match.rb <ide> def self.versions_from_content(content, regex, &block) <ide> } <ide> def self.find_versions(url:, regex:, provided_content: nil, **_unused, &block) <ide> match_data = { matches: {}, regex: regex, url: url } <del> return match_data if url.blank? || regex.blank? <add> return match_data if url.blank? || (regex.blank? && block.blank?) <ide> <ide> content = if provided_content.is_a?(String) <ide> match_data[:cached] = true
1
Python
Python
add tqdm to the process of eval
77944d1b313ad532d7f60cd8e7355af04617e4b5
<ide><path>examples/run_swag.py <ide> def main(): <ide> model.eval() <ide> eval_loss, eval_accuracy = 0, 0 <ide> nb_eval_steps, nb_eval_examples = 0, 0 <del> for input_ids, input_mask, segment_ids, label_ids in eval_dataloader: <add> for input_ids, input_mask, segment_ids, label_ids in tqdm(eval_dataloader, desc="Evaluating"): <ide> input_ids = input_ids.to(device) <ide> input_mask = input_mask.to(device) <ide> segment_ids = segment_ids.to(device)
1
Ruby
Ruby
prefer autoloaded html scanner
426a86ab1e4fc2488215a9adab4511a59646a413
<ide><path>actionpack/lib/action_controller.rb <ide> end <ide> end <ide> <del>$:.unshift "#{File.dirname(__FILE__)}/action_controller/vendor/html-scanner" <del> <ide> module ActionController <ide> # TODO: Review explicit to see if they will automatically be handled by <ide> # the initilizer if they are really needed. <ide> class Session <ide> end <ide> <ide> autoload :Mime, 'action_controller/mime_type' <add> <add>autoload :HTML, 'action_controller/vendor/html-scanner' <ide> autoload :Rack, 'action_controller/vendor/rack' <ide> <ide> ActionController.load_all! <ide><path>actionpack/lib/action_controller/assertions/selector_assertions.rb <ide> # Under MIT and/or CC By license. <ide> #++ <ide> <del>require 'action_controller/vendor/html-scanner' <del> <ide> module ActionController <ide> module Assertions <ide> unless const_defined?(:NO_STRIP) <ide><path>actionpack/lib/action_view/helpers/sanitize_helper.rb <ide> require 'action_view/helpers/tag_helper' <del>require 'action_controller/vendor/html-scanner' <ide> <ide> module ActionView <ide> module Helpers #:nodoc:
3
Python
Python
remove tf.roll wherever not needed
0d2bffad31e88fe72ec12eb20f5dc8996cbc6497
<ide><path>src/transformers/generation_tf_utils.py <ide> def tf_top_k_top_p_filtering(logits, top_k=0, top_p=1.0, filter_value=-float("In <ide> ) <ide> <ide> # Shift the indices to the right to keep also the first token above the threshold <del> sorted_indices_to_remove = tf.roll(sorted_indices_to_remove, 1, axis=-1) <ide> sorted_indices_to_remove = tf.concat( <del> [tf.zeros_like(sorted_indices_to_remove[:, :1]), sorted_indices_to_remove[:, 1:]], <add> [tf.zeros_like(sorted_indices_to_remove[:, :1]), sorted_indices_to_remove[:, :-1]], <ide> -1, <ide> ) <ide> # scatter sorted tensors to original indexing <ide><path>src/transformers/models/bart/modeling_tf_bart.py <ide> <ide> <ide> def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int): <del> shifted_input_ids = tf.roll(input_ids, 1, axis=-1) <del> start_tokens = tf.fill((shape_list(shifted_input_ids)[0], 1), decoder_start_token_id) <del> shifted_input_ids = tf.concat([start_tokens, shifted_input_ids[:, 1:]], -1) <add> start_tokens = tf.fill((shape_list(input_ids)[0], 1), decoder_start_token_id) <add> shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1) <ide> # replace possible -100 values in labels by `pad_token_id` <ide> shifted_input_ids = tf.where( <ide> shifted_input_ids == -100, tf.fill(shape_list(shifted_input_ids), pad_token_id), shifted_input_ids <ide><path>src/transformers/models/blenderbot/modeling_tf_blenderbot.py <ide> <ide> # Copied from transformers.models.bart.modeling_tf_bart.shift_tokens_right <ide> def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int): <del> shifted_input_ids = tf.roll(input_ids, 1, axis=-1) <del> start_tokens = tf.fill((shape_list(shifted_input_ids)[0], 1), decoder_start_token_id) <del> shifted_input_ids = tf.concat([start_tokens, shifted_input_ids[:, 1:]], -1) <add> start_tokens = tf.fill((shape_list(input_ids)[0], 1), decoder_start_token_id) <add> shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1) <ide> # replace possible -100 values in labels by `pad_token_id` <ide> shifted_input_ids = tf.where( <ide> shifted_input_ids == -100, tf.fill(shape_list(shifted_input_ids), pad_token_id), shifted_input_ids <ide><path>src/transformers/models/blenderbot_small/modeling_tf_blenderbot_small.py <ide> <ide> # Copied from transformers.models.bart.modeling_tf_bart.shift_tokens_right <ide> def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int): <del> shifted_input_ids = tf.roll(input_ids, 1, axis=-1) <del> start_tokens = tf.fill((shape_list(shifted_input_ids)[0], 1), decoder_start_token_id) <del> shifted_input_ids = tf.concat([start_tokens, shifted_input_ids[:, 1:]], -1) <add> start_tokens = tf.fill((shape_list(input_ids)[0], 1), decoder_start_token_id) <add> shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1) <ide> # replace possible -100 values in labels by `pad_token_id` <ide> shifted_input_ids = tf.where( <ide> shifted_input_ids == -100, tf.fill(shape_list(shifted_input_ids), pad_token_id), shifted_input_ids <ide><path>src/transformers/models/led/modeling_tf_led.py <ide> <ide> <ide> def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int): <del> shifted_input_ids = tf.roll(input_ids, 1, axis=-1) <del> start_tokens = tf.fill((shape_list(shifted_input_ids)[0], 1), decoder_start_token_id) <del> shifted_input_ids = tf.concat([start_tokens, shifted_input_ids[:, 1:]], -1) <add> start_tokens = tf.fill((shape_list(input_ids)[0], 1), decoder_start_token_id) <add> shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1) <ide> # replace possible -100 values in labels by `pad_token_id` <ide> shifted_input_ids = tf.where( <ide> shifted_input_ids == -100, tf.fill(shape_list(shifted_input_ids), pad_token_id), shifted_input_ids <ide><path>src/transformers/models/marian/modeling_tf_marian.py <ide> <ide> # Copied from transformers.models.bart.modeling_tf_bart.shift_tokens_right <ide> def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int): <del> shifted_input_ids = tf.roll(input_ids, 1, axis=-1) <del> start_tokens = tf.fill((shape_list(shifted_input_ids)[0], 1), decoder_start_token_id) <del> shifted_input_ids = tf.concat([start_tokens, shifted_input_ids[:, 1:]], -1) <add> start_tokens = tf.fill((shape_list(input_ids)[0], 1), decoder_start_token_id) <add> shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1) <ide> # replace possible -100 values in labels by `pad_token_id` <ide> shifted_input_ids = tf.where( <ide> shifted_input_ids == -100, tf.fill(shape_list(shifted_input_ids), pad_token_id), shifted_input_ids <ide><path>src/transformers/models/pegasus/modeling_tf_pegasus.py <ide> <ide> # Copied from transformers.models.bart.modeling_tf_bart.shift_tokens_right <ide> def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int): <del> shifted_input_ids = tf.roll(input_ids, 1, axis=-1) <del> start_tokens = tf.fill((shape_list(shifted_input_ids)[0], 1), decoder_start_token_id) <del> shifted_input_ids = tf.concat([start_tokens, shifted_input_ids[:, 1:]], -1) <add> start_tokens = tf.fill((shape_list(input_ids)[0], 1), decoder_start_token_id) <add> shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1) <ide> # replace possible -100 values in labels by `pad_token_id` <ide> shifted_input_ids = tf.where( <ide> shifted_input_ids == -100, tf.fill(shape_list(shifted_input_ids), pad_token_id), shifted_input_ids <ide><path>src/transformers/models/rag/modeling_tf_rag.py <ide> def shift_tokens_right(self, input_ids, start_token_id=None): <ide> assert pad_token_id is not None, "self.model.config.pad_token_id has to be defined." <ide> <ide> shifted_input_ids = tf.cast(input_ids, tf.int32) <del> shifted_input_ids = tf.roll(shifted_input_ids, 1, axis=-1) <ide> start_tokens = tf.fill((shape_list(shifted_input_ids)[0], 1), start_token_id) <del> shifted_input_ids = tf.concat([start_tokens, shifted_input_ids[:, 1:]], -1) <add> shifted_input_ids = tf.concat([start_tokens, shifted_input_ids[:, :-1]], -1) <ide> <ide> # replace possible -100 values in labels by `pad_token_id` <ide> shifted_input_ids = tf.where( <ide><path>src/transformers/models/t5/modeling_tf_t5.py <ide> def _shift_right(self, input_ids): <ide> decoder_start_token_id is not None <ide> ), "self.model.config.decoder_start_token_id has to be defined. In TF T5 it is usually set to the pad_token_id. See T5 docs for more information" <ide> <del> shifted_input_ids = tf.roll(input_ids, 1, axis=-1) <del> start_tokens = tf.fill((shape_list(shifted_input_ids)[0], 1), decoder_start_token_id) <del> shifted_input_ids = tf.concat([start_tokens, shifted_input_ids[:, 1:]], -1) <add> start_tokens = tf.fill((shape_list(input_ids)[0], 1), decoder_start_token_id) <add> shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1) <ide> <ide> assert pad_token_id is not None, "self.model.config.pad_token_id has to be defined." <ide> # replace possible -100 values in labels by `pad_token_id` <ide><path>templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py <ide> def serving_output(self, output: TFQuestionAnsweringModelOutput) -> TFQuestionAn <ide> <ide> <ide> def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int): <del> shifted_input_ids = tf.roll(input_ids, 1, axis=-1) <del> start_tokens = tf.fill((shape_list(shifted_input_ids)[0], 1), decoder_start_token_id) <del> shifted_input_ids = tf.concat([start_tokens, shifted_input_ids[:, 1:]], -1) <add> start_tokens = tf.fill((shape_list(input_ids)[0], 1), decoder_start_token_id) <add> shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1) <ide> # replace possible -100 values in labels by `pad_token_id` <ide> shifted_input_ids = tf.where( <ide> shifted_input_ids == -100, tf.fill(shape_list(shifted_input_ids), pad_token_id), shifted_input_ids
10
Ruby
Ruby
remove old method and comment
ccf5f2c4a20a9a275dd86f251fa026eee7f344c5
<ide><path>activerecord/lib/active_record/associations.rb <ide> def remove_duplicate_results!(base, records, associations) <ide> end <ide> end <ide> <del> def joins_for_table_name(table_name) <del> join = join_for_table_name(table_name) <del> result = nil <del> if join && join.is_a?(JoinAssociation) <del> result = [join] <del> if join.parent && join.parent.is_a?(JoinAssociation) <del> result = joins_for_table_name(join.parent.aliased_table_name) + <del> result <del> end <del> end <del> result <del> end <del> <ide> protected <ide> def build(associations, parent = nil) <ide> parent ||= @joins.last <ide> def build(associations, parent = nil) <ide> end <ide> end <ide> <del> # overridden in InnerJoinDependency subclass <ide> def build_join_association(reflection, parent) <ide> JoinAssociation.new(reflection, self, parent) <ide> end
1
Javascript
Javascript
add translation for bahasa melayu
5be0376374cd28d8280723143f35c4ab92f98922
<ide><path>lang/ms-my.js <add>// moment.js language configuration <add>// language : Bahasa Malaysia (ms-MY) <add>// author : Weldan Jamili : https://github.com/weldan <add> <add>require('../moment').lang('ms', { <add> months : "Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember".split("_"), <add> monthsShort : "Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis".split("_"), <add> weekdays : "Minggu_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu".split("_"), <add> weekdaysShort : "Min_Isn_Sel_Rab_Kam_Jum_Sab".split("_"), <add> weekdaysMin : "Mg_Is_Sl_Rb_Km_Jm_Sb".split("_"), <add> longDateFormat : { <add> LT : "HH.mm", <add> L : "DD/MM/YYYY", <add> LL : "D MMMM YYYY", <add> LLL : "D MMMM YYYY [pukul] LT", <add> LLLL : "dddd, D MMMM YYYY [pukul] LT" <add> }, <add> meridiem : function (hours, minutes, isLower) { <add> if (hours < 11) { <add> return 'pagi'; <add> } else if (hours < 15) { <add> return 'tengahari'; <add> } else if (hours < 19) { <add> return 'petang'; <add> } else { <add> return 'malam'; <add> } <add> }, <add> calendar : { <add> sameDay : '[Hari ini pukul] LT', <add> nextDay : '[Esok pukul] LT', <add> nextWeek : 'dddd [pukul] LT', <add> lastDay : '[Kelmarin pukul] LT', <add> lastWeek : 'dddd [lepas pukul] LT', <add> sameElse : 'L' <add> }, <add> relativeTime : { <add> future : "dalam %s", <add> past : "%s yang lalu", <add> s : "beberapa saat", <add> m : "seminit", <add> mm : "%d minit", <add> h : "sejam", <add> hh : "%d jam", <add> d : "sehari", <add> dd : "%d hari", <add> M : "sebulan", <add> MM : "%d bulan", <add> y : "setahun", <add> yy : "%d tahun" <add> }, <add> week : { <add> dow : 1, // Monday is the first day of the week. <add> doy : 7 // The week that contains Jan 1st is the first week of the year. <add> } <add>});
1
Python
Python
add on_kill method to dataprocsubmitjoboperator
68cc7273bf0c0f562748b5f663da5c12d2cba6a7
<ide><path>airflow/providers/google/cloud/operators/dataproc.py <ide> class DataprocSubmitJobOperator(BaseOperator): <ide> This is useful for submitting long running jobs and <ide> waiting on them asynchronously using the DataprocJobSensor <ide> :type asynchronous: bool <add> :param cancel_on_kill: Flag which indicates whether cancel the hook's job or not, when on_kill is called <add> :type cancel_on_kill: bool <ide> """ <ide> <ide> template_fields = ('project_id', 'location', 'job', 'impersonation_chain') <ide> def __init__( <ide> gcp_conn_id: str = "google_cloud_default", <ide> impersonation_chain: Optional[Union[str, Sequence[str]]] = None, <ide> asynchronous: bool = False, <add> cancel_on_kill: bool = True, <ide> **kwargs, <ide> ) -> None: <ide> super().__init__(**kwargs) <ide> def __init__( <ide> self.gcp_conn_id = gcp_conn_id <ide> self.impersonation_chain = impersonation_chain <ide> self.asynchronous = asynchronous <add> self.cancel_on_kill = cancel_on_kill <add> self.hook: Optional[DataprocHook] = None <add> self.job_id: Optional[str] = None <ide> <ide> def execute(self, context: Dict): <ide> self.log.info("Submitting job") <del> hook = DataprocHook(gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain) <del> job_object = hook.submit_job( <add> self.hook = DataprocHook(gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain) <add> job_object = self.hook.submit_job( <ide> project_id=self.project_id, <ide> location=self.location, <ide> job=self.job, <ide> def execute(self, context: Dict): <ide> <ide> if not self.asynchronous: <ide> self.log.info('Waiting for job %s to complete', job_id) <del> hook.wait_for_job(job_id=job_id, location=self.location, project_id=self.project_id) <add> self.hook.wait_for_job(job_id=job_id, location=self.location, project_id=self.project_id) <ide> self.log.info('Job %s completed successfully.', job_id) <ide> <del> return job_id <add> self.job_id = job_id <add> return self.job_id <add> <add> def on_kill(self): <add> if self.job_id and self.cancel_on_kill: <add> self.hook.cancel_job(job_id=self.job_id, project_id=self.project_id, location=self.location) <ide> <ide> <ide> class DataprocUpdateClusterOperator(BaseOperator): <ide><path>tests/providers/google/cloud/operators/test_dataproc.py <ide> def test_execute_async(self, mock_hook): <ide> ) <ide> mock_hook.return_value.wait_for_job.assert_not_called() <ide> <add> @mock.patch(DATAPROC_PATH.format("DataprocHook")) <add> def test_on_kill(self, mock_hook): <add> job = {} <add> job_id = "job_id" <add> mock_hook.return_value.wait_for_job.return_value = None <add> mock_hook.return_value.submit_job.return_value.reference.job_id = job_id <add> <add> op = DataprocSubmitJobOperator( <add> task_id=TASK_ID, <add> location=GCP_LOCATION, <add> project_id=GCP_PROJECT, <add> job=job, <add> gcp_conn_id=GCP_CONN_ID, <add> retry=RETRY, <add> timeout=TIMEOUT, <add> metadata=METADATA, <add> request_id=REQUEST_ID, <add> impersonation_chain=IMPERSONATION_CHAIN, <add> cancel_on_kill=False, <add> ) <add> op.execute(context={}) <add> <add> op.on_kill() <add> mock_hook.return_value.cancel_job.assert_not_called() <add> <add> op.cancel_on_kill = True <add> op.on_kill() <add> mock_hook.return_value.cancel_job.assert_called_once_with( <add> project_id=GCP_PROJECT, location=GCP_LOCATION, job_id=job_id <add> ) <add> <ide> <ide> class TestDataprocUpdateClusterOperator(unittest.TestCase): <ide> @mock.patch(DATAPROC_PATH.format("DataprocHook"))
2
Ruby
Ruby
return argv from each method
4e0694c603099a2f76de8ad0f65c4f446a44dc4f
<ide><path>railties/lib/rails/generators/rails/app/app_generator.rb <ide> def initialize(argv = ARGV) <ide> <ide> def prepare! <ide> handle_version_request!(@argv.first) <del> unless handle_invalid_command!(@argv.first, @argv) <add> handle_invalid_command!(@argv.first, @argv) do <ide> @argv.shift <ide> handle_rails_rc!(@argv) <ide> end <del> @argv <ide> end <ide> <ide> def self.default_rc_file <ide> def handle_version_request!(argument) <ide> end <ide> <ide> def handle_invalid_command!(argument, argv) <del> if argument != "new" <del> argv[0] = "--help" <add> if argument == "new" <add> yield <add> else <add> ['--help'] + argv.drop(1) <ide> end <ide> end <ide> <ide> def handle_rails_rc!(argv) <ide> unless argv.delete("--no-rc") <ide> insert_railsrc_into_argv!(argv, railsrc(argv)) <ide> end <add> argv <ide> end <ide> <ide> def railsrc(argv)
1
Java
Java
add generic parameters to messagehandler impls
3f9da6f4809431a323a627c719cc28987fb6945e
<ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/PubSubChannelRegistry.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public interface PubSubChannelRegistry<M extends Message<?>, H extends MessageHandler<M>> { <add>@SuppressWarnings("rawtypes") <add>public interface PubSubChannelRegistry<M extends Message, H extends MessageHandler<M>> { <ide> <ide> SubscribableChannel<M, H> getClientInputChannel(); <ide> <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/service/AbstractPubSubMessageHandler.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public abstract class AbstractPubSubMessageHandler implements MessageHandler<Message<?>> { <add>@SuppressWarnings("rawtypes") <add>public abstract class AbstractPubSubMessageHandler<M extends Message> implements MessageHandler<M> { <ide> <ide> protected final Log logger = LogFactory.getLog(getClass()); <ide> <ide> public void setDisallowedDestinations(String... patterns) { <ide> protected abstract Collection<MessageType> getSupportedMessageTypes(); <ide> <ide> <del> protected boolean canHandle(Message<?> message, MessageType messageType) { <add> protected boolean canHandle(M message, MessageType messageType) { <ide> <ide> if (!CollectionUtils.isEmpty(getSupportedMessageTypes())) { <ide> if (!getSupportedMessageTypes().contains(messageType)) { <ide> protected boolean canHandle(Message<?> message, MessageType messageType) { <ide> return isDestinationAllowed(message); <ide> } <ide> <del> protected boolean isDestinationAllowed(Message<?> message) { <add> protected boolean isDestinationAllowed(M message) { <ide> <ide> PubSubHeaders headers = PubSubHeaders.fromMessageHeaders(message.getHeaders()); <ide> String destination = headers.getDestination(); <ide> protected boolean isDestinationAllowed(Message<?> message) { <ide> } <ide> <ide> @Override <del> public final void handleMessage(Message<?> message) throws MessagingException { <add> public final void handleMessage(M message) throws MessagingException { <ide> <ide> PubSubHeaders headers = PubSubHeaders.fromMessageHeaders(message.getHeaders()); <ide> MessageType messageType = headers.getMessageType(); <ide> else if (MessageType.DISCONNECT.equals(messageType)) { <ide> } <ide> } <ide> <del> protected void handleConnect(Message<?> message) { <add> protected void handleConnect(M message) { <ide> } <ide> <del> protected void handlePublish(Message<?> message) { <add> protected void handlePublish(M message) { <ide> } <ide> <del> protected void handleSubscribe(Message<?> message) { <add> protected void handleSubscribe(M message) { <ide> } <ide> <del> protected void handleUnsubscribe(Message<?> message) { <add> protected void handleUnsubscribe(M message) { <ide> } <ide> <del> protected void handleDisconnect(Message<?> message) { <add> protected void handleDisconnect(M message) { <ide> } <ide> <del> protected void handleOther(Message<?> message) { <add> protected void handleOther(M message) { <ide> } <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/service/ReactorPubSubMessageHandler.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class ReactorPubSubMessageHandler extends AbstractPubSubMessageHandler { <add>@SuppressWarnings("rawtypes") <add>public class ReactorPubSubMessageHandler<M extends Message> extends AbstractPubSubMessageHandler<M> { <ide> <del> private MessageChannel<Message<?>> clientChannel; <add> private MessageChannel<M> clientChannel; <ide> <ide> private final Reactor reactor; <ide> <ide> public class ReactorPubSubMessageHandler extends AbstractPubSubMessageHandler { <ide> private Map<String, List<Registration<?>>> subscriptionsBySession = new ConcurrentHashMap<String, List<Registration<?>>>(); <ide> <ide> <del> public ReactorPubSubMessageHandler(PubSubChannelRegistry registry, Reactor reactor) { <add> public ReactorPubSubMessageHandler(PubSubChannelRegistry<M, ?> registry, Reactor reactor) { <ide> Assert.notNull(reactor, "reactor is required"); <ide> this.clientChannel = registry.getClientOutputChannel(); <ide> this.reactor = reactor; <ide> protected Collection<MessageType> getSupportedMessageTypes() { <ide> } <ide> <ide> @Override <del> public void handleSubscribe(Message<?> message) { <add> public void handleSubscribe(M message) { <ide> <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("Subscribe " + message); <ide> private String getPublishKey(String destination) { <ide> } <ide> <ide> @Override <del> public void handlePublish(Message<?> message) { <add> public void handlePublish(M message) { <ide> <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("Message received: " + message); <ide> public void handlePublish(Message<?> message) { <ide> // Convert to byte[] payload before the fan-out <ide> PubSubHeaders headers = PubSubHeaders.fromMessageHeaders(message.getHeaders()); <ide> byte[] payload = payloadConverter.convertToPayload(message.getPayload(), headers.getContentType()); <del> message = MessageBuilder.fromPayloadAndHeaders(payload, message.getHeaders()).build(); <add> @SuppressWarnings("unchecked") <add> M m = (M) MessageBuilder.fromPayloadAndHeaders(payload, message.getHeaders()).build(); <ide> <del> this.reactor.notify(getPublishKey(headers.getDestination()), Event.wrap(message)); <add> this.reactor.notify(getPublishKey(headers.getDestination()), Event.wrap(m)); <ide> } <ide> catch (Exception ex) { <ide> logger.error("Failed to publish " + message, ex); <ide> } <ide> } <ide> <ide> @Override <del> public void handleDisconnect(Message<?> message) { <add> public void handleDisconnect(M message) { <ide> PubSubHeaders headers = PubSubHeaders.fromMessageHeaders(message.getHeaders()); <ide> removeSubscriptions(headers.getSessionId()); <ide> } <ide> <del>/* @Override <del> public void handleClientConnectionClosed(String sessionId) { <del> removeSubscriptions(sessionId); <del> } <del>*/ <del> <ide> private void removeSubscriptions(String sessionId) { <ide> List<Registration<?>> registrations = this.subscriptionsBySession.remove(sessionId); <ide> if (logger.isTraceEnabled()) { <ide> public void accept(Event<Message<?>> event) { <ide> PubSubHeaders clientHeaders = PubSubHeaders.fromMessageHeaders(sentMessage.getHeaders()); <ide> clientHeaders.setSubscriptionId(this.subscriptionId); <ide> <del> Message<?> clientMessage = MessageBuilder.fromPayloadAndHeaders(sentMessage.getPayload(), <add> @SuppressWarnings("unchecked") <add> M clientMessage = (M) MessageBuilder.fromPayloadAndHeaders(sentMessage.getPayload(), <ide> clientHeaders.toMessageHeaders()).build(); <ide> <ide> clientChannel.send(clientMessage); <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/service/method/AnnotationPubSubMessageHandler.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class AnnotationPubSubMessageHandler extends AbstractPubSubMessageHandler <add>@SuppressWarnings("rawtypes") <add>public class AnnotationPubSubMessageHandler<M extends Message> extends AbstractPubSubMessageHandler<M> <ide> implements ApplicationContextAware, InitializingBean { <ide> <del> private PubSubChannelRegistry registry; <add> private PubSubChannelRegistry<M, ?> registry; <ide> <ide> private List<MessageConverter> messageConverters; <ide> <ide> public class AnnotationPubSubMessageHandler extends AbstractPubSubMessageHandler <ide> <ide> private Map<MappingInfo, HandlerMethod> unsubscribeMethods = new HashMap<MappingInfo, HandlerMethod>(); <ide> <del> private ArgumentResolverComposite argumentResolvers = new ArgumentResolverComposite(); <add> private ArgumentResolverComposite<M> argumentResolvers = new ArgumentResolverComposite<M>(); <ide> <del> private ReturnValueHandlerComposite returnValueHandlers = new ReturnValueHandlerComposite(); <add> private ReturnValueHandlerComposite<M> returnValueHandlers = new ReturnValueHandlerComposite<M>(); <ide> <ide> <del> public AnnotationPubSubMessageHandler(PubSubChannelRegistry registry) { <add> public AnnotationPubSubMessageHandler(PubSubChannelRegistry<M, ?> registry) { <ide> Assert.notNull(registry, "registry is required"); <ide> this.registry = registry; <ide> } <ide> public void afterPropertiesSet() { <ide> <ide> initHandlerMethods(); <ide> <del> this.argumentResolvers.addResolver(new MessageChannelArgumentResolver(this.registry.getMessageBrokerChannel())); <del> this.argumentResolvers.addResolver(new MessageBodyArgumentResolver(this.messageConverters)); <add> this.argumentResolvers.addResolver(new MessageChannelArgumentResolver<M>(this.registry.getMessageBrokerChannel())); <add> this.argumentResolvers.addResolver(new MessageBodyArgumentResolver<M>(this.messageConverters)); <ide> <del> this.returnValueHandlers.addHandler(new MessageReturnValueHandler(this.registry.getClientOutputChannel())); <add> this.returnValueHandlers.addHandler(new MessageReturnValueHandler<M>(this.registry.getClientOutputChannel())); <ide> } <ide> <ide> protected void initHandlerMethods() { <ide> protected HandlerMethod createHandlerMethod(Object handler, Method method) { <ide> } <ide> <ide> @Override <del> public void handlePublish(Message<?> message) { <add> public void handlePublish(M message) { <ide> handleMessageInternal(message, this.messageMethods); <ide> } <ide> <ide> @Override <del> public void handleSubscribe(Message<?> message) { <add> public void handleSubscribe(M message) { <ide> handleMessageInternal(message, this.subscribeMethods); <ide> } <ide> <ide> @Override <del> public void handleUnsubscribe(Message<?> message) { <add> public void handleUnsubscribe(M message) { <ide> handleMessageInternal(message, this.unsubscribeMethods); <ide> } <ide> <del> private void handleMessageInternal(final Message<?> message, Map<MappingInfo, HandlerMethod> handlerMethods) { <add> private void handleMessageInternal(final M message, Map<MappingInfo, HandlerMethod> handlerMethods) { <ide> <ide> PubSubHeaders headers = PubSubHeaders.fromMessageHeaders(message.getHeaders()); <ide> String destination = headers.getDestination(); <ide> private void handleMessageInternal(final Message<?> message, Map<MappingInfo, Ha <ide> HandlerMethod handlerMethod = match.createWithResolvedBean(); <ide> <ide> // TODO: <del> InvocableMessageHandlerMethod invocableHandlerMethod = new InvocableMessageHandlerMethod(handlerMethod); <add> InvocableMessageHandlerMethod<M> invocableHandlerMethod = new InvocableMessageHandlerMethod<M>(handlerMethod); <ide> invocableHandlerMethod.setMessageMethodArgumentResolvers(this.argumentResolvers); <ide> <ide> try { <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/service/method/ArgumentResolver.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public interface ArgumentResolver { <add>@SuppressWarnings("rawtypes") <add>public interface ArgumentResolver<M extends Message> { <ide> <ide> /** <ide> * Whether the given {@linkplain MethodParameter method parameter} is <ide> public interface ArgumentResolver { <ide> * <ide> * @throws Exception in case of errors with the preparation of argument values <ide> */ <del> Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception; <add> Object resolveArgument(MethodParameter parameter, M message) throws Exception; <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/service/method/ArgumentResolverComposite.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class ArgumentResolverComposite implements ArgumentResolver { <add>@SuppressWarnings("rawtypes") <add>public class ArgumentResolverComposite<M extends Message> implements ArgumentResolver<M> { <ide> <ide> protected final Log logger = LogFactory.getLog(getClass()); <ide> <del> private final List<ArgumentResolver> argumentResolvers = <del> new LinkedList<ArgumentResolver>(); <add> private final List<ArgumentResolver<M>> argumentResolvers = new LinkedList<ArgumentResolver<M>>(); <ide> <del> private final Map<MethodParameter, ArgumentResolver> argumentResolverCache = <del> new ConcurrentHashMap<MethodParameter, ArgumentResolver>(256); <add> private final Map<MethodParameter, ArgumentResolver<M>> argumentResolverCache = <add> new ConcurrentHashMap<MethodParameter, ArgumentResolver<M>>(256); <ide> <ide> <ide> /** <ide> * Return a read-only list with the contained resolvers, or an empty list. <ide> */ <del> public List<ArgumentResolver> getResolvers() { <add> public List<ArgumentResolver<M>> getResolvers() { <ide> return Collections.unmodifiableList(this.argumentResolvers); <ide> } <ide> <ide> public boolean supportsParameter(MethodParameter parameter) { <ide> * @exception IllegalStateException if no suitable {@link ArgumentResolver} is found. <ide> */ <ide> @Override <del> public Object resolveArgument(MethodParameter parameter, Message message) throws Exception { <add> public Object resolveArgument(MethodParameter parameter, M message) throws Exception { <ide> <del> ArgumentResolver resolver = getArgumentResolver(parameter); <add> ArgumentResolver<M> resolver = getArgumentResolver(parameter); <ide> Assert.notNull(resolver, "Unknown parameter type [" + parameter.getParameterType().getName() + "]"); <ide> return resolver.resolveArgument(parameter, message); <ide> } <ide> <ide> /** <ide> * Find a registered {@link ArgumentResolver} that supports the given method parameter. <ide> */ <del> private ArgumentResolver getArgumentResolver(MethodParameter parameter) { <del> ArgumentResolver result = this.argumentResolverCache.get(parameter); <add> private ArgumentResolver<M> getArgumentResolver(MethodParameter parameter) { <add> ArgumentResolver<M> result = this.argumentResolverCache.get(parameter); <ide> if (result == null) { <del> for (ArgumentResolver resolver : this.argumentResolvers) { <add> for (ArgumentResolver<M> resolver : this.argumentResolvers) { <ide> if (resolver.supportsParameter(parameter)) { <ide> result = resolver; <ide> this.argumentResolverCache.put(parameter, result); <ide> private ArgumentResolver getArgumentResolver(MethodParameter parameter) { <ide> /** <ide> * Add the given {@link ArgumentResolver}. <ide> */ <del> public ArgumentResolverComposite addResolver(ArgumentResolver argumentResolver) { <add> public ArgumentResolverComposite<M> addResolver(ArgumentResolver<M> argumentResolver) { <ide> this.argumentResolvers.add(argumentResolver); <ide> return this; <ide> } <ide> <ide> /** <ide> * Add the given {@link ArgumentResolver}s. <ide> */ <del> public ArgumentResolverComposite addResolvers(List<? extends ArgumentResolver> argumentResolvers) { <add> public ArgumentResolverComposite<M> addResolvers(List<? extends ArgumentResolver<M>> argumentResolvers) { <ide> if (argumentResolvers != null) { <del> for (ArgumentResolver resolver : argumentResolvers) { <add> for (ArgumentResolver<M> resolver : argumentResolvers) { <ide> this.argumentResolvers.add(resolver); <ide> } <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/service/method/InvocableMessageHandlerMethod.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class InvocableMessageHandlerMethod extends HandlerMethod { <add>@SuppressWarnings("rawtypes") <add>public class InvocableMessageHandlerMethod<M extends Message> extends HandlerMethod { <ide> <del> private ArgumentResolverComposite argumentResolvers = new ArgumentResolverComposite(); <add> private ArgumentResolverComposite<M> argumentResolvers = new ArgumentResolverComposite<M>(); <ide> <ide> private ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer(); <ide> <ide> public InvocableMessageHandlerMethod( <ide> * Set {@link ArgumentResolver}s to use to use for resolving method <ide> * argument values. <ide> */ <del> public void setMessageMethodArgumentResolvers(ArgumentResolverComposite argumentResolvers) { <add> public void setMessageMethodArgumentResolvers(ArgumentResolverComposite<M> argumentResolvers) { <ide> this.argumentResolvers = argumentResolvers; <ide> } <ide> <ide> public void setParameterNameDiscoverer(ParameterNameDiscoverer parameterNameDisc <ide> * @exception Exception raised if no suitable argument resolver can be found, or the <ide> * method raised an exception <ide> */ <del> public final Object invoke(Message<?> message) throws Exception { <add> public final Object invoke(M message) throws Exception { <ide> <ide> Object[] args = getMethodArgumentValues(message); <ide> <ide> public final Object invoke(Message<?> message) throws Exception { <ide> /** <ide> * Get the method argument values for the current request. <ide> */ <del> private Object[] getMethodArgumentValues(Message<?> message) throws Exception { <add> private Object[] getMethodArgumentValues(M message) throws Exception { <ide> <ide> MethodParameter[] parameters = getMethodParameters(); <ide> Object[] args = new Object[parameters.length]; <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/service/method/MessageBodyArgumentResolver.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class MessageBodyArgumentResolver implements ArgumentResolver { <add>@SuppressWarnings("rawtypes") <add>public class MessageBodyArgumentResolver<M extends Message> implements ArgumentResolver<M> { <ide> <ide> private final MessageConverter converter; <ide> <ide> public boolean supportsParameter(MethodParameter parameter) { <ide> } <ide> <ide> @Override <del> public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { <add> public Object resolveArgument(MethodParameter parameter, M message) throws Exception { <ide> <ide> Object arg = null; <ide> <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/service/method/MessageChannelArgumentResolver.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class MessageChannelArgumentResolver implements ArgumentResolver { <add>@SuppressWarnings("rawtypes") <add>public class MessageChannelArgumentResolver<M extends Message> implements ArgumentResolver<M> { <ide> <del> private MessageChannel<Message<?>> messageBrokerChannel; <add> private MessageChannel<M> messageBrokerChannel; <ide> <ide> <del> public MessageChannelArgumentResolver(MessageChannel<Message<?>> messageBrokerChannel) { <add> public MessageChannelArgumentResolver(MessageChannel<M> messageBrokerChannel) { <ide> Assert.notNull(messageBrokerChannel, "messageBrokerChannel is required"); <ide> this.messageBrokerChannel = messageBrokerChannel; <ide> } <ide> public boolean supportsParameter(MethodParameter parameter) { <ide> } <ide> <ide> @Override <del> public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { <add> public Object resolveArgument(MethodParameter parameter, M message) throws Exception { <ide> Assert.notNull(this.messageBrokerChannel, "messageBrokerChannel is required"); <ide> final String sessionId = PubSubHeaders.fromMessageHeaders(message.getHeaders()).getSessionId(); <del> return new SessionMessageChannel(this.messageBrokerChannel, sessionId); <add> return new SessionMessageChannel<M>(this.messageBrokerChannel, sessionId); <ide> } <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/service/method/MessageReturnValueHandler.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class MessageReturnValueHandler implements ReturnValueHandler { <add>@SuppressWarnings("rawtypes") <add>public class MessageReturnValueHandler<M extends Message> implements ReturnValueHandler<M> { <ide> <del> private MessageChannel<Message<?>> clientChannel; <add> private MessageChannel<M> clientChannel; <ide> <ide> <del> public MessageReturnValueHandler(MessageChannel<Message<?>> clientChannel) { <add> public MessageReturnValueHandler(MessageChannel<M> clientChannel) { <ide> Assert.notNull(clientChannel, "clientChannel is required"); <ide> this.clientChannel = clientChannel; <ide> } <ide> public boolean supportsReturnType(MethodParameter returnType) { <ide> // return Message.class.isAssignableFrom(paramType); <ide> } <ide> <del> @SuppressWarnings("unchecked") <ide> @Override <del> public void handleReturnValue(Object returnValue, MethodParameter returnType, Message<?> message) <add> public void handleReturnValue(Object returnValue, MethodParameter returnType, M message) <ide> throws Exception { <ide> <ide> Assert.notNull(this.clientChannel, "No clientChannel to send messages to"); <ide> <del> Message<?> returnMessage = (Message<?>) returnValue; <add> @SuppressWarnings("unchecked") <add> M returnMessage = (M) returnValue; <ide> if (returnMessage == null) { <ide> return; <ide> } <ide> public void handleReturnValue(Object returnValue, MethodParameter returnType, Me <ide> this.clientChannel.send(returnMessage); <ide> } <ide> <del> protected Message<?> updateReturnMessage(Message<?> returnMessage, Message<?> message) { <add> protected M updateReturnMessage(M returnMessage, M message) { <ide> <ide> PubSubHeaders headers = PubSubHeaders.fromMessageHeaders(message.getHeaders()); <ide> String sessionId = headers.getSessionId(); <ide> protected Message<?> updateReturnMessage(Message<?> returnMessage, Message<?> me <ide> } <ide> <ide> Object payload = returnMessage.getPayload(); <del> return MessageBuilder.fromPayloadAndHeaders(payload, returnHeaders.toMessageHeaders()).build(); <add> return createMessage(returnHeaders, payload); <add> } <add> <add> @SuppressWarnings("unchecked") <add> private M createMessage(PubSubHeaders returnHeaders, Object payload) { <add> return (M) MessageBuilder.fromPayloadAndHeaders(payload, returnHeaders.toMessageHeaders()).build(); <ide> } <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/service/method/ReturnValueHandler.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public interface ReturnValueHandler { <add>@SuppressWarnings("rawtypes") <add>public interface ReturnValueHandler<M extends Message> { <ide> <ide> /** <ide> * Whether the given {@linkplain MethodParameter method return type} is <ide> public interface ReturnValueHandler { <ide> * @param message the message that caused this method to be called <ide> * @throws Exception if the return value handling results in an error <ide> */ <del> void handleReturnValue(Object returnValue, MethodParameter returnType, Message<?> message) throws Exception; <add> void handleReturnValue(Object returnValue, MethodParameter returnType, M message) throws Exception; <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/service/method/ReturnValueHandlerComposite.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class ReturnValueHandlerComposite implements ReturnValueHandler { <add>@SuppressWarnings("rawtypes") <add>public class ReturnValueHandlerComposite<M extends Message> implements ReturnValueHandler<M> { <ide> <del> private final List<ReturnValueHandler> returnValueHandlers = <del> new ArrayList<ReturnValueHandler>(); <add> private final List<ReturnValueHandler<M>> returnValueHandlers = new ArrayList<ReturnValueHandler<M>>(); <ide> <ide> <ide> /** <ide> * Add the given {@link ReturnValueHandler}. <ide> */ <del> public ReturnValueHandlerComposite addHandler(ReturnValueHandler returnValuehandler) { <add> public ReturnValueHandlerComposite<M> addHandler(ReturnValueHandler<M> returnValuehandler) { <ide> this.returnValueHandlers.add(returnValuehandler); <ide> return this; <ide> } <ide> <ide> /** <ide> * Add the given {@link ReturnValueHandler}s. <ide> */ <del> public ReturnValueHandlerComposite addHandlers(List<? extends ReturnValueHandler> handlers) { <add> public ReturnValueHandlerComposite<M> addHandlers(List<? extends ReturnValueHandler<M>> handlers) { <ide> if (handlers != null) { <del> for (ReturnValueHandler handler : handlers) { <add> for (ReturnValueHandler<M> handler : handlers) { <ide> this.returnValueHandlers.add(handler); <ide> } <ide> } <ide> public boolean supportsReturnType(MethodParameter returnType) { <ide> return getReturnValueHandler(returnType) != null; <ide> } <ide> <del> private ReturnValueHandler getReturnValueHandler(MethodParameter returnType) { <del> for (ReturnValueHandler handler : this.returnValueHandlers) { <add> private ReturnValueHandler<M> getReturnValueHandler(MethodParameter returnType) { <add> for (ReturnValueHandler<M> handler : this.returnValueHandlers) { <ide> if (handler.supportsReturnType(returnType)) { <ide> return handler; <ide> } <ide> private ReturnValueHandler getReturnValueHandler(MethodParameter returnType) { <ide> } <ide> <ide> @Override <del> public void handleReturnValue(Object returnValue, MethodParameter returnType, Message<?> message) <add> public void handleReturnValue(Object returnValue, MethodParameter returnType, M message) <ide> throws Exception { <ide> <del> ReturnValueHandler handler = getReturnValueHandler(returnType); <add> ReturnValueHandler<M> handler = getReturnValueHandler(returnType); <ide> Assert.notNull(handler, "Unknown return value type [" + returnType.getParameterType().getName() + "]"); <ide> handler.handleReturnValue(returnValue, returnType, message); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompMessageConverter.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class StompMessageConverter { <add>@SuppressWarnings("rawtypes") <add>public class StompMessageConverter<M extends Message> { <ide> <ide> private static final Charset STOMP_CHARSET = Charset.forName("UTF-8"); <ide> <ide> public class StompMessageConverter { <ide> /** <ide> * @param stompContent a complete STOMP message (without the trailing 0x00) as byte[] or String. <ide> */ <del> public Message<byte[]> toMessage(Object stompContent, String sessionId) { <add> public M toMessage(Object stompContent, String sessionId) { <ide> <ide> byte[] byteContent = null; <ide> if (stompContent instanceof String) { <ide> else if (stompContent instanceof byte[]){ <ide> byte[] payload = new byte[totalLength - payloadIndex]; <ide> System.arraycopy(byteContent, payloadIndex, payload, 0, totalLength - payloadIndex); <ide> <del> return MessageBuilder.fromPayloadAndHeaders(payload, stompHeaders.toMessageHeaders()).build(); <add> return createMessage(stompHeaders, payload); <add> } <add> <add> @SuppressWarnings("unchecked") <add> private M createMessage(StompHeaders stompHeaders, byte[] payload) { <add> return (M) MessageBuilder.fromPayloadAndHeaders(payload, stompHeaders.toMessageHeaders()).build(); <ide> } <ide> <ide> private int findIndexOfPayload(byte[] bytes) { <ide> private int findIndexOfPayload(byte[] bytes) { <ide> return index; <ide> } <ide> <del> public byte[] fromMessage(Message<byte[]> message) { <add> public byte[] fromMessage(M message) { <add> <add> byte[] payload; <add> if (message.getPayload() instanceof byte[]) { <add> payload = (byte[]) message.getPayload(); <add> } <add> else { <add> throw new IllegalArgumentException( <add> "stompContent is not byte[]: " + message.getPayload().getClass()); <add> } <add> <ide> ByteArrayOutputStream out = new ByteArrayOutputStream(); <ide> MessageHeaders messageHeaders = message.getHeaders(); <ide> StompHeaders stompHeaders = StompHeaders.fromMessageHeaders(messageHeaders); <add> <ide> try { <ide> out.write(stompHeaders.getStompCommand().toString().getBytes("UTF-8")); <ide> out.write(LF); <ide> public byte[] fromMessage(Message<byte[]> message) { <ide> } <ide> } <ide> out.write(LF); <del> out.write(message.getPayload()); <add> out.write(payload); <ide> out.write(0); <ide> return out.toByteArray(); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class StompRelayPubSubMessageHandler extends AbstractPubSubMessageHandler { <add>@SuppressWarnings("rawtypes") <add>public class StompRelayPubSubMessageHandler<M extends Message> extends AbstractPubSubMessageHandler<M> { <ide> <del> private MessageChannel<Message<?>> clientChannel; <add> private MessageChannel<M> clientChannel; <ide> <del> private final StompMessageConverter stompMessageConverter = new StompMessageConverter(); <add> private final StompMessageConverter<M> stompMessageConverter = new StompMessageConverter<M>(); <ide> <ide> private MessageConverter payloadConverter; <ide> <ide> public class StompRelayPubSubMessageHandler extends AbstractPubSubMessageHandler <ide> * @param clientChannel a channel for sending messages from the remote message broker <ide> * back to clients <ide> */ <del> public StompRelayPubSubMessageHandler(PubSubChannelRegistry registry) { <add> public StompRelayPubSubMessageHandler(PubSubChannelRegistry<M, ?> registry) { <ide> <ide> Assert.notNull(registry, "registry is required"); <ide> this.clientChannel = registry.getClientOutputChannel(); <ide> protected Collection<MessageType> getSupportedMessageTypes() { <ide> } <ide> <ide> @Override <del> public void handleConnect(Message<?> message) { <add> public void handleConnect(M message) { <ide> StompHeaders stompHeaders = StompHeaders.fromMessageHeaders(message.getHeaders()); <ide> String sessionId = stompHeaders.getSessionId(); <ide> if (sessionId == null) { <ide> public void handleConnect(Message<?> message) { <ide> } <ide> <ide> @Override <del> public void handlePublish(Message<?> message) { <add> public void handlePublish(M message) { <ide> forwardMessage(message, StompCommand.SEND); <ide> } <ide> <ide> @Override <del> public void handleSubscribe(Message<?> message) { <add> public void handleSubscribe(M message) { <ide> forwardMessage(message, StompCommand.SUBSCRIBE); <ide> } <ide> <ide> @Override <del> public void handleUnsubscribe(Message<?> message) { <add> public void handleUnsubscribe(M message) { <ide> forwardMessage(message, StompCommand.UNSUBSCRIBE); <ide> } <ide> <ide> @Override <del> public void handleDisconnect(Message<?> message) { <add> public void handleDisconnect(M message) { <ide> StompHeaders stompHeaders = StompHeaders.fromMessageHeaders(message.getHeaders()); <ide> if (stompHeaders.getStompCommand() != null) { <ide> forwardMessage(message, StompCommand.DISCONNECT); <ide> public void handleDisconnect(Message<?> message) { <ide> } <ide> <ide> @Override <del> public void handleOther(Message<?> message) { <add> public void handleOther(M message) { <ide> StompCommand command = (StompCommand) message.getHeaders().get(PubSubHeaders.PROTOCOL_MESSAGE_TYPE); <ide> Assert.notNull(command, "Expected STOMP command: " + message.getHeaders()); <ide> forwardMessage(message, command); <ide> } <ide> <del> private void forwardMessage(Message<?> message, StompCommand command) { <add> private void forwardMessage(M message, StompCommand command) { <ide> <ide> StompHeaders headers = StompHeaders.fromMessageHeaders(message.getHeaders()); <ide> headers.setStompCommandIfNotSet(command); <ide> private final class RelaySession { <ide> <ide> private final AtomicBoolean isConnected = new AtomicBoolean(false); <ide> <del> private final BlockingQueue<Message<?>> messageQueue = new LinkedBlockingQueue<Message<?>>(50); <add> private final BlockingQueue<M> messageQueue = new LinkedBlockingQueue<M>(50); <ide> <ide> <del> public RelaySession(final Message<?> message, final StompHeaders stompHeaders) { <add> public RelaySession(final M message, final StompHeaders stompHeaders) { <ide> <ide> Assert.notNull(message, "message is required"); <ide> Assert.notNull(stompHeaders, "stompHeaders is required"); <ide> private void readStompFrame(String stompFrame) { <ide> return; <ide> } <ide> <del> Message<byte[]> message = stompMessageConverter.toMessage(stompFrame, this.sessionId); <add> M message = stompMessageConverter.toMessage(stompFrame, this.sessionId); <ide> if (logger.isTraceEnabled()) { <ide> logger.trace("Reading message " + message); <ide> } <ide> private void sendError(String sessionId, String errorText) { <ide> StompHeaders stompHeaders = StompHeaders.create(StompCommand.ERROR); <ide> stompHeaders.setSessionId(sessionId); <ide> stompHeaders.setMessage(errorText); <del> Message<byte[]> errorMessage = MessageBuilder.fromPayloadAndHeaders( <del> new byte[0], stompHeaders.toMessageHeaders()).build(); <add> @SuppressWarnings("unchecked") <add> M errorMessage = (M) MessageBuilder.fromPayloadAndHeaders(new byte[0], stompHeaders.toMessageHeaders()).build(); <ide> clientChannel.send(errorMessage); <ide> } <ide> <del> public void forward(Message<?> message, StompHeaders headers) { <add> public void forward(M message, StompHeaders headers) { <ide> <ide> if (!this.isConnected.get()) { <del> message = MessageBuilder.fromPayloadAndHeaders(message.getPayload(), headers.toMessageHeaders()).build(); <add> @SuppressWarnings("unchecked") <add> M m = (M) MessageBuilder.fromPayloadAndHeaders(message.getPayload(), headers.toMessageHeaders()).build(); <ide> if (logger.isTraceEnabled()) { <del> logger.trace("Adding to queue message " + message + ", queue size=" + this.messageQueue.size()); <add> logger.trace("Adding to queue message " + m + ", queue size=" + this.messageQueue.size()); <ide> } <del> this.messageQueue.add(message); <add> this.messageQueue.add(m); <ide> return; <ide> } <ide> <ide> public void forward(Message<?> message, StompHeaders headers) { <ide> } <ide> <ide> private void flushMessages(TcpConnection<String, String> connection) { <del> List<Message<?>> messages = new ArrayList<Message<?>>(); <add> List<M> messages = new ArrayList<M>(); <ide> this.messageQueue.drainTo(messages); <ide> for (Message<?> message : messages) { <ide> StompHeaders headers = StompHeaders.fromMessageHeaders(message.getHeaders()); <ide> private boolean forwardInternal(Message<?> message, StompHeaders headers, TcpCon <ide> <ide> MediaType contentType = headers.getContentType(); <ide> byte[] payload = payloadConverter.convertToPayload(message.getPayload(), contentType); <del> Message<byte[]> byteMessage = MessageBuilder.fromPayloadAndHeaders(payload, headers.toMessageHeaders()).build(); <add> @SuppressWarnings("unchecked") <add> M byteMessage = (M) MessageBuilder.fromPayloadAndHeaders(payload, headers.toMessageHeaders()).build(); <ide> <ide> if (logger.isTraceEnabled()) { <ide> logger.trace("Forwarding message " + byteMessage); <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompWebSocketHandler.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class StompWebSocketHandler extends TextWebSocketHandlerAdapter implements MessageHandler<Message<?>> { <add>@SuppressWarnings("rawtypes") <add>public class StompWebSocketHandler<M extends Message> extends TextWebSocketHandlerAdapter <add> implements MessageHandler<M> { <ide> <ide> private static final byte[] EMPTY_PAYLOAD = new byte[0]; <ide> <ide> private static Log logger = LogFactory.getLog(StompWebSocketHandler.class); <ide> <del> private MessageChannel outputChannel; <add> private MessageChannel<M> outputChannel; <ide> <del> private final StompMessageConverter stompMessageConverter = new StompMessageConverter(); <add> private final StompMessageConverter<M> stompMessageConverter = new StompMessageConverter<M>(); <ide> <ide> private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<String, WebSocketSession>(); <ide> <ide> private MessageConverter payloadConverter = new CompositeMessageConverter(null); <ide> <ide> <del> public StompWebSocketHandler(PubSubChannelRegistry registry) { <add> public StompWebSocketHandler(PubSubChannelRegistry<M, ?> registry) { <ide> Assert.notNull(registry, "registry is required"); <ide> this.outputChannel = registry.getClientInputChannel(); <ide> } <ide> public void setMessageConverters(List<MessageConverter> converters) { <ide> this.payloadConverter = new CompositeMessageConverter(converters); <ide> } <ide> <del> public StompMessageConverter getStompMessageConverter() { <add> public StompMessageConverter<M> getStompMessageConverter() { <ide> return this.stompMessageConverter; <ide> } <ide> <ide> public void afterConnectionEstablished(WebSocketSession session) throws Exceptio <ide> /** <ide> * Handle incoming WebSocket messages from clients. <ide> */ <del> @SuppressWarnings("unchecked") <ide> @Override <ide> protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) { <ide> try { <ide> String payload = textMessage.getPayload(); <del> Message<byte[]> message = this.stompMessageConverter.toMessage(payload, session.getId()); <add> M message = this.stompMessageConverter.toMessage(payload, session.getId()); <ide> <ide> // TODO: validate size limits <ide> // http://stomp.github.io/stomp-specification-1.2.html#Size_Limits <ide> else if (MessageType.DISCONNECT.equals(messageType)) { <ide> } <ide> } <ide> <del> protected void handleConnect(final WebSocketSession session, Message<byte[]> message) throws IOException { <add> protected void handleConnect(final WebSocketSession session, M message) throws IOException { <ide> <ide> StompHeaders connectHeaders = StompHeaders.fromMessageHeaders(message.getHeaders()); <ide> StompHeaders connectedHeaders = StompHeaders.create(StompCommand.CONNECTED); <ide> else if (acceptVersions.isEmpty()) { <ide> <ide> // TODO: security <ide> <del> Message<byte[]> connectedMessage = MessageBuilder.fromPayloadAndHeaders(EMPTY_PAYLOAD, <add> @SuppressWarnings("unchecked") <add> M connectedMessage = (M) MessageBuilder.fromPayloadAndHeaders(EMPTY_PAYLOAD, <ide> connectedHeaders.toMessageHeaders()).build(); <ide> byte[] bytes = getStompMessageConverter().fromMessage(connectedMessage); <ide> session.sendMessage(new TextMessage(new String(bytes, Charset.forName("UTF-8")))); <ide> } <ide> <del> protected void handlePublish(Message<byte[]> stompMessage) { <add> protected void handlePublish(M stompMessage) { <ide> } <ide> <del> protected void handleSubscribe(Message<byte[]> message) { <add> protected void handleSubscribe(M message) { <ide> // TODO: need a way to communicate back if subscription was successfully created or <ide> // not in which case an ERROR should be sent back and close the connection <ide> // http://stomp.github.io/stomp-specification-1.2.html#SUBSCRIBE <ide> } <ide> <del> protected void handleUnsubscribe(Message<byte[]> message) { <add> protected void handleUnsubscribe(M message) { <ide> } <ide> <del> protected void handleDisconnect(Message<byte[]> stompMessage) { <add> protected void handleDisconnect(M stompMessage) { <ide> } <ide> <ide> protected void sendErrorMessage(WebSocketSession session, Throwable error) { <ide> <ide> StompHeaders headers = StompHeaders.create(StompCommand.ERROR); <ide> headers.setMessage(error.getMessage()); <ide> <del> Message<byte[]> message = MessageBuilder.fromPayloadAndHeaders(EMPTY_PAYLOAD, <del> headers.toMessageHeaders()).build(); <add> @SuppressWarnings("unchecked") <add> M message = (M) MessageBuilder.fromPayloadAndHeaders(EMPTY_PAYLOAD, headers.toMessageHeaders()).build(); <ide> byte[] bytes = this.stompMessageConverter.fromMessage(message); <ide> <ide> try { <ide> protected void sendErrorMessage(WebSocketSession session, Throwable error) { <ide> } <ide> } <ide> <del> @SuppressWarnings("unchecked") <ide> @Override <ide> public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { <ide> this.sessions.remove(session.getId()); <ide> PubSubHeaders headers = PubSubHeaders.create(MessageType.DISCONNECT); <ide> headers.setSessionId(session.getId()); <del> Message<?> message = MessageBuilder.fromPayloadAndHeaders(new byte[0], headers.toMessageHeaders()).build(); <add> @SuppressWarnings("unchecked") <add> M message = (M) MessageBuilder.fromPayloadAndHeaders(new byte[0], headers.toMessageHeaders()).build(); <ide> this.outputChannel.send(message); <ide> } <ide> <ide> /** <ide> * Handle STOMP messages going back out to WebSocket clients. <ide> */ <ide> @Override <del> public void handleMessage(Message<?> message) { <add> public void handleMessage(M message) { <ide> <ide> StompHeaders headers = StompHeaders.fromMessageHeaders(message.getHeaders()); <ide> headers.setStompCommandIfNotSet(StompCommand.MESSAGE); <ide> public void handleMessage(Message<?> message) { <ide> } <ide> <ide> try { <del> Message<byte[]> byteMessage = MessageBuilder.fromPayloadAndHeaders(payload, <del> headers.toMessageHeaders()).build(); <add> @SuppressWarnings("unchecked") <add> M byteMessage = (M) MessageBuilder.fromPayloadAndHeaders(payload, headers.toMessageHeaders()).build(); <ide> byte[] bytes = getStompMessageConverter().fromMessage(byteMessage); <ide> session.sendMessage(new TextMessage(new String(bytes, Charset.forName("UTF-8")))); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/support/AbstractPubSubChannelRegistry.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class AbstractPubSubChannelRegistry<M extends Message<?>, H extends MessageHandler<M>> implements PubSubChannelRegistry<M, H>, InitializingBean { <add>@SuppressWarnings("rawtypes") <add>public class AbstractPubSubChannelRegistry<M extends Message, H extends MessageHandler<M>> <add> implements PubSubChannelRegistry<M, H>, InitializingBean { <ide> <ide> private SubscribableChannel<M, H> clientInputChannel; <ide> <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/support/ReactorMessageChannel.java <ide> public class ReactorMessageChannel implements SubscribableChannel<Message<?>, Me <ide> private String name = toString(); // TODO <ide> <ide> <del> private final Map<MessageHandler, Registration<?>> registrations = <del> new HashMap<MessageHandler, Registration<?>>(); <add> private final Map<MessageHandler<Message<?>>, Registration<?>> registrations = <add> new HashMap<MessageHandler<Message<?>>, Registration<?>>(); <ide> <ide> <ide> public ReactorMessageChannel(Reactor reactor) { <ide> public boolean send(Message<?> message, long timeout) { <ide> } <ide> <ide> @Override <del> public boolean subscribe(final MessageHandler handler) { <add> public boolean subscribe(final MessageHandler<Message<?>> handler) { <ide> <ide> if (this.registrations.containsKey(handler)) { <ide> logger.warn("Channel " + getName() + ", handler already subscribed " + handler); <ide> public boolean subscribe(final MessageHandler handler) { <ide> } <ide> <ide> @Override <del> public boolean unsubscribe(MessageHandler handler) { <add> public boolean unsubscribe(MessageHandler<Message<?>> handler) { <ide> <ide> if (logger.isTraceEnabled()) { <ide> logger.trace("Channel " + getName() + ", removing subscription for handler " + handler); <ide> public boolean unsubscribe(MessageHandler handler) { <ide> <ide> private static final class MessageHandlerConsumer implements Consumer<Event<Message<?>>> { <ide> <del> private final MessageHandler handler; <add> private final MessageHandler<Message<?>> handler; <ide> <del> private MessageHandlerConsumer(MessageHandler handler) { <add> private MessageHandlerConsumer(MessageHandler<Message<?>> handler) { <ide> this.handler = handler; <ide> } <ide> <del> @SuppressWarnings("unchecked") <ide> @Override <ide> public void accept(Event<Message<?>> event) { <ide> Message<?> message = event.getData(); <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/support/SessionMessageChannel.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class SessionMessageChannel implements MessageChannel<Message<?>> { <add>@SuppressWarnings("rawtypes") <add>public class SessionMessageChannel<M extends Message> implements MessageChannel<M> { <ide> <del> private MessageChannel<Message<?>> delegate; <add> private MessageChannel<M> delegate; <ide> <ide> private final String sessionId; <ide> <ide> <del> public SessionMessageChannel(MessageChannel<Message<?>> delegate, String sessionId) { <add> public SessionMessageChannel(MessageChannel<M> delegate, String sessionId) { <ide> Assert.notNull(delegate, "delegate is required"); <ide> Assert.notNull(sessionId, "sessionId is required"); <ide> this.sessionId = sessionId; <ide> this.delegate = delegate; <ide> } <ide> <ide> @Override <del> public boolean send(Message<?> message) { <add> public boolean send(M message) { <ide> return send(message, -1); <ide> } <ide> <ide> @Override <del> public boolean send(Message<?> message, long timeout) { <add> public boolean send(M message, long timeout) { <ide> PubSubHeaders headers = PubSubHeaders.fromMessageHeaders(message.getHeaders()); <ide> headers.setSessionId(this.sessionId); <del> MessageBuilder<?> messageToSend = MessageBuilder.fromPayloadAndHeaders( <del> message.getPayload(), headers.toMessageHeaders()); <del> this.delegate.send(messageToSend.build()); <add> @SuppressWarnings("unchecked") <add> M messageToSend = (M) MessageBuilder.fromPayloadAndHeaders(message.getPayload(), headers.toMessageHeaders()).build(); <add> this.delegate.send(messageToSend); <ide> return true; <ide> } <ide> }
18
Javascript
Javascript
update imports in ember-glimmer package tests
dd28ca046a299497aacda9e674229be99f02db52
<ide><path>packages/ember-application/lib/index.js <ide> export { default as ApplicationInstance } from './system/application-instance'; <ide> export { default as Resolver } from './system/resolver'; <ide> export { default as Engine } from './system/engine'; <ide> export { default as EngineInstance } from './system/engine-instance'; <add>export { getEngineParent, setEngineParent } from './system/engine-parent'; <ide> <ide> // add domTemplates initializer (only does something if `ember-template-compiler` <ide> // is loaded already) <ide><path>packages/ember-glimmer/tests/integration/application/engine-test.js <ide> import { moduleFor, ApplicationTest } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { compile } from '../../utils/helpers'; <del>import Controller from 'ember-runtime/controllers/controller'; <del>import Engine from 'ember-application/system/engine'; <del>import Route from 'ember-routing/system/route'; <add>import { Controller } from 'ember-runtime'; <add>import { Engine } from 'ember-application'; <add>import { Route } from 'ember-routing'; <ide> <ide> moduleFor('Application test: engine rendering', class extends ApplicationTest { <ide> setupAppAndRoutableEngine(hooks = []) { <ide><path>packages/ember-glimmer/tests/integration/application/rendering-test.js <del>import Controller from 'ember-runtime/controllers/controller'; <add>import { Controller } from 'ember-runtime'; <ide> import { moduleFor, ApplicationTest } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <del>import Route from 'ember-routing/system/route'; <add>import { Route } from 'ember-routing'; <ide> <ide> moduleFor('Application test: rendering', class extends ApplicationTest { <ide> <ide><path>packages/ember-glimmer/tests/integration/binding_integration_test.js <ide> import { RenderingTest, moduleFor } from '../utils/test-case'; <ide> import { Component } from '../utils/helpers'; <del>import { set } from 'ember-metal/property_set'; <del>import { Binding } from 'ember-metal/binding'; <add>import { set, Binding } from 'ember-metal'; <ide> <ide> moduleFor('Binding integration tests', class extends RenderingTest { <ide> ['@test should accept bindings as a string or an Ember.binding']() { <ide><path>packages/ember-glimmer/tests/integration/components/append-test.js <del>import { set } from 'ember-metal/property_set'; <del>import jQuery from 'ember-views/system/jquery'; <add>import { set } from 'ember-metal'; <add>import { jQuery } from 'ember-views'; <ide> import { moduleFor, RenderingTest } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <ide> <ide><path>packages/ember-glimmer/tests/integration/components/attribute-bindings-test.js <ide> import { moduleFor, RenderingTest } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <ide> import { strip } from '../../utils/abstract-test-case'; <del>import { set } from 'ember-metal/property_set'; <add>import { set } from 'ember-metal'; <ide> <ide> moduleFor('Attribute bindings integration', class extends RenderingTest { <ide> ['@test it can have attribute bindings']() { <ide><path>packages/ember-glimmer/tests/integration/components/attrs-lookup-test.js <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <del>import { set } from 'ember-metal/property_set'; <del>import { computed } from 'ember-metal/computed'; <add>import { set, computed } from 'ember-metal'; <ide> import { styles } from '../../utils/test-helpers'; <ide> <ide> moduleFor('Components test: attrs lookup', class extends RenderingTest { <ide><path>packages/ember-glimmer/tests/integration/components/class-bindings-test.js <ide> import { moduleFor, RenderingTest } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <ide> import { classes } from '../../utils/test-helpers'; <del>import { set } from 'ember-metal/property_set'; <add>import { set, computed } from 'ember-metal'; <ide> import { strip } from '../../utils/abstract-test-case'; <del>import computed from 'ember-metal/computed'; <ide> <ide> moduleFor('ClassNameBindings integration', class extends RenderingTest { <ide> <ide><path>packages/ember-glimmer/tests/integration/components/closure-components-test.js <ide> import { Component } from '../../utils/helpers'; <ide> import { applyMixins, strip } from '../../utils/abstract-test-case'; <ide> import { moduleFor, RenderingTest } from '../../utils/test-case'; <del>import assign from 'ember-metal/assign'; <del>import isEmpty from 'ember-metal/is_empty'; <add>import { assign, isEmpty } from 'ember-metal'; <ide> <ide> moduleFor('Components test: closure components', class extends RenderingTest { <ide> ['@test renders with component helper']() { <ide><path>packages/ember-glimmer/tests/integration/components/curly-components-test.js <ide> /* globals EmberDev */ <del>import isEnabled from 'ember-metal/features'; <del>import { set } from 'ember-metal/property_set'; <del>import { get } from 'ember-metal/property_get'; <del>import { observer } from 'ember-metal/mixin'; <del>import { on } from 'ember-metal/events'; <del>import EmberObject from 'ember-runtime/system/object'; <add>import { <add> isFeatureEnabled, <add> set, <add> get, <add> observer, <add> on, <add> computed, <add> run <add>} from 'ember-metal'; <add>import { <add> Object as EmberObject, <add> A as emberA, <add> inject, <add> Service <add>} from 'ember-runtime'; <ide> import { Component, compile, htmlSafe } from '../../utils/helpers'; <del>import { A as emberA } from 'ember-runtime/system/native_array'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { moduleFor, RenderingTest } from '../../utils/test-case'; <del>import { classes, equalTokens, equalsElement, styles } from '../../utils/test-helpers'; <del>import { computed } from 'ember-metal/computed'; <del>import run from 'ember-metal/run_loop'; <del>import inject from 'ember-runtime/inject'; <del>import Service from 'ember-runtime/system/service'; <add>import { <add> classes, <add> equalTokens, <add> equalsElement, <add> styles <add>} from '../../utils/test-helpers'; <ide> <ide> moduleFor('Components test: curly components', class extends RenderingTest { <ide> <ide> moduleFor('Components test: curly components', class extends RenderingTest { <ide> } <ide> <ide> ['@test when a property is changed during children\'s rendering'](assert) { <del> if (isEnabled('ember-glimmer-allow-backtracking-rerender')) { <add> if (isFeatureEnabled('ember-glimmer-allow-backtracking-rerender')) { <ide> expectDeprecation(/modified value twice in a single render/); <ide> } <ide> <ide> moduleFor('Components test: curly components', class extends RenderingTest { <ide> assert.equal(this.$('#inner-value').text(), '1', 'initial render of inner'); <ide> assert.equal(this.$('#middle-value').text(), '', 'initial render of middle (observers do not run during init)'); <ide> <del> if (!isEnabled('ember-glimmer-allow-backtracking-rerender')) { <add> if (!isFeatureEnabled('ember-glimmer-allow-backtracking-rerender')) { <ide> expectAssertion(() => { <ide> this.runTask(() => outer.set('value', 2)); <ide> }, /modified value twice in a single render/); <ide> moduleFor('Components test: curly components', class extends RenderingTest { <ide> } <ide> <ide> ['@test when a shared dependency is changed during children\'s rendering'](assert) { <del> if (isEnabled('ember-glimmer-allow-backtracking-rerender')) { <add> if (isFeatureEnabled('ember-glimmer-allow-backtracking-rerender')) { <ide> expectDeprecation(/modified wrapper.content twice in a single render/); <ide> } <ide> <ide> moduleFor('Components test: curly components', class extends RenderingTest { <ide> template: '<div id="inner-value">{{wrapper.content}}</div>' <ide> }); <ide> <del> if (!isEnabled('ember-glimmer-allow-backtracking-rerender')) { <add> if (!isFeatureEnabled('ember-glimmer-allow-backtracking-rerender')) { <ide> expectAssertion(() => { <ide> this.render('{{x-outer}}'); <ide> }, /modified wrapper.content twice in a single render/); <ide> moduleFor('Components test: curly components', class extends RenderingTest { <ide> <ide> this.assertText('initial value - initial value'); <ide> <del> if (isEnabled('mandatory-setter')) { <add> if (isFeatureEnabled('mandatory-setter')) { <ide> expectAssertion(() => { <ide> component.bar = 'foo-bar'; <ide> }, /You must use Ember\.set\(\) to set the `bar` property \(of .+\) to `foo-bar`\./); <ide><path>packages/ember-glimmer/tests/integration/components/dynamic-components-test.js <del>import { set } from 'ember-metal/property_set'; <add>import { set, computed } from 'ember-metal'; <ide> import { Component } from '../../utils/helpers'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { moduleFor, RenderingTest } from '../../utils/test-case'; <del>import computed from 'ember-metal/computed'; <ide> <ide> moduleFor('Components test: dynamic components', class extends RenderingTest { <ide> <ide><path>packages/ember-glimmer/tests/integration/components/fragment-components-test.js <ide> import { moduleFor, RenderingTest } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { Component } from '../../utils/helpers'; <del>import { set } from 'ember-metal/property_set'; <add>import { set } from 'ember-metal'; <ide> <ide> moduleFor('Components test: fragment components', class extends RenderingTest { <ide> getCustomDispatcherEvents() { <ide><path>packages/ember-glimmer/tests/integration/components/instrumentation-test.js <ide> import { moduleFor, RenderingTest } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <del>import { subscribe, reset } from 'ember-metal/instrumentation'; <del>import { set } from 'ember-metal/property_set'; <add>import { <add> instrumentationSubscribe, <add> instrumentationReset, <add> set <add>} from 'ember-metal'; <ide> <ide> moduleFor('Components instrumentation', class extends RenderingTest { <ide> constructor() { <ide> super(); <ide> <ide> this.resetEvents(); <ide> <del> subscribe('render.component', { <add> instrumentationSubscribe('render.component', { <ide> before: (name, timestamp, payload) => { <ide> if (payload.view !== this.component) { <ide> this.actual.before.push(payload); <ide> moduleFor('Components instrumentation', class extends RenderingTest { <ide> this.assert.deepEqual(this.actual.before, [], 'No unexpected events (before)'); <ide> this.assert.deepEqual(this.actual.after, [], 'No unexpected events (after)'); <ide> super.teardown(); <del> reset(); <add> instrumentationReset(); <ide> } <ide> <ide> ['@test zomg'](assert) { assert.ok(true); } <ide><path>packages/ember-glimmer/tests/integration/components/life-cycle-test.js <del>import { set } from 'ember-metal/property_set'; <add>import { set, run } from 'ember-metal'; <ide> import { Component } from '../../utils/helpers'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { moduleFor, RenderingTest } from '../../utils/test-case'; <del>import { getViewId } from 'ember-views/system/utils'; <del>import run from 'ember-metal/run_loop'; <add>import { getViewId } from 'ember-views'; <ide> <ide> class LifeCycleHooksTest extends RenderingTest { <ide> constructor() { <ide><path>packages/ember-glimmer/tests/integration/components/link-to-test.js <ide> import { moduleFor, ApplicationTest } from '../../utils/test-case'; <del>import Controller from 'ember-runtime/controllers/controller'; <del>import Route from 'ember-routing/system/route'; <del>import { set } from 'ember-metal/property_set'; <add>import { Controller } from 'ember-runtime'; <add>import { Route } from 'ember-routing'; <add>import { set, isFeatureEnabled } from 'ember-metal'; <ide> import { LinkComponent } from '../../utils/helpers'; <ide> import { classes as classMatcher } from '../../utils/test-helpers'; <del>import isEnabled from 'ember-metal/features'; <ide> <ide> moduleFor('Link-to component', class extends ApplicationTest { <ide> visitWithDeprecation(path, deprecation) { <ide> moduleFor('Link-to component with query-params', class extends ApplicationTest { <ide> constructor() { <ide> super(...arguments); <ide> <del> if (isEnabled('ember-routing-route-configured-query-params')) { <add> if (isFeatureEnabled('ember-routing-route-configured-query-params')) { <ide> this.registerRoute('index', Route.extend({ <ide> queryParams: { <ide> foo: { <ide><path>packages/ember-glimmer/tests/integration/components/target-action-test.js <del>import { moduleFor, RenderingTest, ApplicationTest } from '../../utils/test-case'; <del>import { set } from 'ember-metal/property_set'; <add>import { <add> moduleFor, <add> RenderingTest, <add> ApplicationTest <add>} from '../../utils/test-case'; <add>import { set, assign, Mixin } from 'ember-metal'; <ide> import { Component } from '../../utils/helpers'; <del>import assign from 'ember-metal/assign'; <del>import Controller from 'ember-runtime/controllers/controller'; <del>import { Mixin } from 'ember-metal/mixin'; <del>import Route from 'ember-routing/system/route'; <del>import EmberObject from 'ember-runtime/system/object'; <add>import { Controller, Object as EmberObject } from 'ember-runtime'; <add>import { Route } from 'ember-routing'; <ide> <ide> moduleFor('Components test: sendAction', class extends RenderingTest { <ide> <ide><path>packages/ember-glimmer/tests/integration/components/utils-test.js <del>import Controller from 'ember-runtime/controllers/controller'; <del>import $ from 'ember-views/system/jquery'; <del>import { moduleFor, ApplicationTest, RenderingTest } from '../../utils/test-case'; <del>import { Component } from '../../utils/helpers'; <add>import { Controller } from 'ember-runtime'; <ide> import { <add> jQuery as $, <ide> getRootViews, <ide> getChildViews, <ide> getViewBounds, <ide> getViewClientRects, <ide> getViewBoundingClientRect <del>} from 'ember-views/system/utils'; <add>} from 'ember-views'; <add>import { <add> moduleFor, <add> ApplicationTest, <add> RenderingTest <add>} from '../../utils/test-case'; <add>import { Component } from '../../utils/helpers'; <ide> <ide> moduleFor('View tree tests', class extends ApplicationTest { <ide> <ide><path>packages/ember-glimmer/tests/integration/components/web-component-fallback-test.js <ide> import { moduleFor, RenderingTest } from '../../utils/test-case'; <del>import { set } from 'ember-metal/property_set'; <add>import { set } from 'ember-metal'; <ide> <ide> moduleFor('Components test: web component fallback', class extends RenderingTest { <ide> ['@test custom elements are rendered']() { <ide><path>packages/ember-glimmer/tests/integration/components/will-destroy-element-hook-test.js <del>import { set } from 'ember-metal/property_set'; <add>import { set } from 'ember-metal'; <ide> import { Component } from '../../utils/helpers'; <ide> import { moduleFor, RenderingTest } from '../../utils/test-case'; <ide> <ide><path>packages/ember-glimmer/tests/integration/content-test.js <ide> /* globals EmberDev */ <ide> import { RenderingTest, moduleFor } from '../utils/test-case'; <ide> import { applyMixins } from '../utils/abstract-test-case'; <del>import { set } from 'ember-metal/property_set'; <del>import { computed } from 'ember-metal/computed'; <del>import EmberObject from 'ember-runtime/system/object'; <del>import ObjectProxy from 'ember-runtime/system/object_proxy'; <add>import { <add> set, <add> computed, <add> getDebugFunction, <add> setDebugFunction <add>} from 'ember-metal'; <add>import { Object as EmberObject, ObjectProxy } from 'ember-runtime'; <ide> import { classes } from '../utils/test-helpers'; <del>import { getDebugFunction, setDebugFunction } from 'ember-metal/debug'; <del>import { STYLE_WARNING } from 'ember-views/system/utils'; <add>import { STYLE_WARNING } from 'ember-views'; <ide> import { Component, SafeString } from '../utils/helpers'; <ide> <ide> moduleFor('Static content tests', class extends RenderingTest { <ide><path>packages/ember-glimmer/tests/integration/event-dispatcher-test.js <ide> import { RenderingTest, moduleFor } from '../utils/test-case'; <ide> import { Component } from '../utils/helpers'; <del>import isEnabled from 'ember-metal/features'; <del>import { subscribe, reset } from 'ember-metal/instrumentation'; <del>import run from 'ember-metal/run_loop'; <add>import { <add> isFeatureEnabled, <add> instrumentationSubscribe, <add> instrumentationReset, <add> run <add>} from 'ember-metal'; <ide> <ide> let canDataTransfer = !!document.createEvent('HTMLEvents').dataTransfer; <ide> <ide> moduleFor('EventDispatcher#setup', class extends RenderingTest { <ide> } <ide> }); <ide> <del>if (isEnabled('ember-improved-instrumentation')) { <add>if (isFeatureEnabled('ember-improved-instrumentation')) { <ide> moduleFor('EventDispatcher - Instrumentation', class extends RenderingTest { <ide> teardown() { <ide> super.teardown(); <del> reset(); <add> instrumentationReset(); <ide> } <ide> <ide> ['@test instruments triggered events'](assert) { <ide> if (isEnabled('ember-improved-instrumentation')) { <ide> assert.equal(clicked, 1, 'precond - the click handler was invoked'); <ide> <ide> let clickInstrumented = 0; <del> subscribe('interaction.click', { <add> instrumentationSubscribe('interaction.click', { <ide> before() { <ide> clickInstrumented++; <ide> assert.equal(clicked, 1, 'invoked before event is handled'); <ide> if (isEnabled('ember-improved-instrumentation')) { <ide> }); <ide> <ide> let keypressInstrumented = 0; <del> subscribe('interaction.keypress', { <add> instrumentationSubscribe('interaction.keypress', { <ide> before() { <ide> keypressInstrumented++; <ide> }, <ide><path>packages/ember-glimmer/tests/integration/helpers/-class-test.js <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <ide> import { classes } from '../../utils/test-helpers'; <del>import { set } from 'ember-metal/property_set'; <add>import { set } from 'ember-metal'; <ide> <ide> moduleFor('Helpers test: {{-class}}', class extends RenderingTest { <ide> <ide><path>packages/ember-glimmer/tests/integration/helpers/closure-action-test.js <del>import run from 'ember-metal/run_loop'; <del>import { computed } from 'ember-metal/computed'; <del>import isEnabled from 'ember-metal/features'; <del>import { subscribe, unsubscribe } from 'ember-metal/instrumentation'; <add>import { <add> run, <add> computed, <add> isFeatureEnabled, <add> instrumentationSubscribe, <add> instrumentationUnsubscribe <add>} from 'ember-metal'; <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <ide> import { Component, INVOKE } from '../../utils/helpers'; <ide> <del>if (isEnabled('ember-improved-instrumentation')) { <add>if (isFeatureEnabled('ember-improved-instrumentation')) { <ide> moduleFor('Helpers test: closure {{action}} improved instrumentation', class extends RenderingTest { <ide> <ide> subscribe(eventName, options) { <del> this.subscriber = subscribe(eventName, options); <add> this.subscriber = instrumentationSubscribe(eventName, options); <ide> } <ide> <ide> teardown() { <ide> if (this.subscriber) { <del> unsubscribe(this.subscriber); <add> instrumentationUnsubscribe(this.subscriber); <ide> } <ide> <ide> super.teardown(); <ide><path>packages/ember-glimmer/tests/integration/helpers/concat-test.js <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <del>import { set } from 'ember-metal/property_set'; <add>import { set } from 'ember-metal'; <ide> <ide> moduleFor('Helpers test: {{concat}}', class extends RenderingTest { <ide> <ide><path>packages/ember-glimmer/tests/integration/helpers/custom-helper-test.js <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <ide> import { makeBoundHelper } from '../../utils/helpers'; <del>import { runDestroy } from 'ember-runtime/tests/utils'; <del>import { set } from 'ember-metal/property_set'; <add>import { runDestroy } from 'internal-test-helpers'; <add>import { set } from 'ember-metal'; <ide> <ide> let assert = QUnit.assert; <ide> <ide><path>packages/ember-glimmer/tests/integration/helpers/element-action-test.js <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { Component } from '../../utils/helpers'; <del>import { set } from 'ember-metal/property_set'; <add>import { <add> set, <add> isFeatureEnabled, <add> instrumentationSubscribe, <add> instrumentationReset <add>} from 'ember-metal'; <ide> <del>import EmberObject from 'ember-runtime/system/object'; <del>import { A as emberA } from 'ember-runtime/system/native_array'; <add>import { Object as EmberObject, A as emberA } from 'ember-runtime'; <ide> <del>import ActionManager from 'ember-views/system/action_manager'; <del>import jQuery from 'ember-views/system/jquery'; <del>import isEnabled from 'ember-metal/features'; <del>import { subscribe, reset } from 'ember-metal/instrumentation'; <add>import { ActionManager, jQuery } from 'ember-views'; <ide> <ide> function getActionAttributes(element) { <ide> let attributes = element.attributes; <ide> function getActionIds(element) { <ide> return getActionAttributes(element).map(attribute => attribute.slice('data-ember-action-'.length)); <ide> } <ide> <del>if (isEnabled('ember-improved-instrumentation')) { <add>if (isFeatureEnabled('ember-improved-instrumentation')) { <ide> moduleFor('Helpers test: element action instrumentation', class extends RenderingTest { <ide> teardown() { <ide> super.teardown(); <del> reset(); <add> instrumentationReset(); <ide> } <ide> <ide> ['@test action should fire interaction event with proper params']() { <ide> if (isEnabled('ember-improved-instrumentation')) { <ide> template: '<button {{action "foo" "bar"}}>Click me</button>' <ide> }); <ide> <del> subscribe('interaction.ember-action', { <add> instrumentationSubscribe('interaction.ember-action', { <ide> before() { <ide> subscriberCallCount++; <ide> }, <ide><path>packages/ember-glimmer/tests/integration/helpers/get-test.js <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <del>import { set } from 'ember-metal/property_set'; <del>import { get } from 'ember-metal/property_get'; <add>import { set, get } from 'ember-metal'; <ide> <ide> moduleFor('Helpers test: {{get}}', class extends RenderingTest { <ide> <ide><path>packages/ember-glimmer/tests/integration/helpers/hash-test.js <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <del>import { set } from 'ember-metal/property_set'; <add>import { set } from 'ember-metal'; <ide> <ide> moduleFor('Helpers test: {{hash}}', class extends RenderingTest { <ide> <ide><path>packages/ember-glimmer/tests/integration/helpers/input-test.js <del>import { set } from 'ember-metal/property_set'; <add>import { set, assign } from 'ember-metal'; <ide> import { TextField, Checkbox, Component } from '../../utils/helpers'; <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <del>import { runDestroy } from 'ember-runtime/tests/utils'; <del>import assign from 'ember-metal/assign'; <add>import { runDestroy } from 'internal-test-helpers'; <ide> <ide> class InputRenderingTest extends RenderingTest { <ide> constructor() { <ide><path>packages/ember-glimmer/tests/integration/helpers/loc-test.js <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <del>import { set } from 'ember-metal/property_set'; <del>import Ember from 'ember-metal/core'; // Ember.STRINGS <add>import { set } from 'ember-metal'; <add>import Ember from 'ember'; <ide> <ide> moduleFor('Helpers test: {{loc}}', class extends RenderingTest { <ide> <ide><path>packages/ember-glimmer/tests/integration/helpers/mut-test.js <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <del>import { set } from 'ember-metal/property_set'; <del>import { get } from 'ember-metal/property_get'; <del>import { computed } from 'ember-metal/computed'; <add>import { set, get, computed } from 'ember-metal'; <ide> import { styles } from '../../utils/test-helpers'; <ide> <ide> moduleFor('Helpers test: {{mut}}', class extends RenderingTest { <ide><path>packages/ember-glimmer/tests/integration/helpers/partial-test.js <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <del>import { set } from 'ember-metal/property_set'; <add>import { set } from 'ember-metal'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> <ide> <ide><path>packages/ember-glimmer/tests/integration/helpers/readonly-test.js <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <del>import { set } from 'ember-metal/property_set'; <del>import { get } from 'ember-metal/property_get'; <add>import { set, get } from 'ember-metal'; <ide> <ide> moduleFor('Helpers test: {{readonly}}', class extends RenderingTest { <ide> <ide><path>packages/ember-glimmer/tests/integration/helpers/render-test.js <del>import { observer } from 'ember-metal/mixin'; <del>import Controller from 'ember-runtime/controllers/controller'; <add>import { observer, set } from 'ember-metal'; <add>import { Controller } from 'ember-runtime'; <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <del>import { set } from 'ember-metal/property_set'; <ide> <ide> moduleFor('Helpers test: {{render}}', class extends RenderingTest { <ide> ['@test should render given template']() { <ide><path>packages/ember-glimmer/tests/integration/helpers/text-area-test.js <del>import { set } from 'ember-metal/property_set'; <add>import { set, assign } from 'ember-metal'; <ide> import { TextArea } from '../../utils/helpers'; <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <del>import assign from 'ember-metal/assign'; <ide> import { classes } from '../../utils/test-helpers'; <ide> import { applyMixins } from '../../utils/abstract-test-case'; <ide> <ide><path>packages/ember-glimmer/tests/integration/helpers/unbound-test.js <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <del>import { set } from 'ember-metal/property_set'; <del>import { get } from 'ember-metal/property_get'; <del>import setProperties from 'ember-metal/set_properties'; <add>import { set, get, setProperties } from 'ember-metal'; <ide> import { Component } from '../../utils/helpers'; <del>import { A as emberA } from 'ember-runtime/system/native_array'; <add>import { A as emberA } from 'ember-runtime'; <ide> <ide> moduleFor('Helpers test: {{unbound}}', class extends RenderingTest { <ide> <ide><path>packages/ember-glimmer/tests/integration/helpers/yield-test.js <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <del>import { set } from 'ember-metal/property_set'; <add>import { set } from 'ember-metal'; <ide> import { Component } from '../../utils/helpers'; <ide> <ide> moduleFor('Helpers test: {{yield}} helper', class extends RenderingTest { <ide><path>packages/ember-glimmer/tests/integration/input-test.js <ide> import { RenderingTest, moduleFor } from '../utils/test-case'; <del>import { set } from 'ember-metal/property_set'; <add>import { set } from 'ember-metal'; <ide> <ide> moduleFor('Input element tests', class extends RenderingTest { <ide> runAttributeTest(attributeName, values) { <ide><path>packages/ember-glimmer/tests/integration/mount-test.js <del>import { moduleFor, ApplicationTest, RenderingTest } from '../utils/test-case'; <add>import { <add> moduleFor, <add> ApplicationTest, <add> RenderingTest <add>} from '../utils/test-case'; <ide> import { compile } from '../utils/helpers'; <del>import Controller from 'ember-runtime/controllers/controller'; <del>import { set } from 'ember-metal/property_set'; <del>import Engine from 'ember-application/system/engine'; <del>import { getEngineParent } from 'ember-application/system/engine-parent'; <add>import { Controller } from 'ember-runtime'; <add>import { set } from 'ember-metal'; <add>import { Engine, getEngineParent } from 'ember-application'; <ide> import { getOwner } from 'container'; <ide> <ide> moduleFor('{{mount}} assertions', class extends RenderingTest { <ide><path>packages/ember-glimmer/tests/integration/outlet-test.js <ide> import { RenderingTest, moduleFor } from '../utils/test-case'; <del>import { runAppend } from 'ember-runtime/tests/utils'; <del>import { set } from 'ember-metal/property_set'; <add>import { runAppend } from 'internal-test-helpers'; <add>import { set } from 'ember-metal'; <ide> <ide> moduleFor('outlet view', class extends RenderingTest { <ide> constructor() { <ide><path>packages/ember-glimmer/tests/integration/svg-test.js <ide> import { RenderingTest, moduleFor } from '../utils/test-case'; <del>import { set } from 'ember-metal/property_set'; <add>import { set } from 'ember-metal'; <ide> import { strip } from '../utils/abstract-test-case'; <ide> <ide> moduleFor('SVG element tests', class extends RenderingTest { <ide><path>packages/ember-glimmer/tests/integration/syntax/each-in-test.js <del>import { set } from 'ember-metal/property_set'; <del>import { get } from 'ember-metal/property_get'; <add>import { set, get } from 'ember-metal'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { applyMixins } from '../../utils/abstract-test-case'; <ide> import { moduleFor } from '../../utils/test-case'; <del>import ObjectProxy from 'ember-runtime/system/object_proxy'; <del>import EmberObject from 'ember-runtime/system/object'; <add>import { ObjectProxy, Object as EmberObject } from 'ember-runtime'; <ide> <ide> import { <ide> TogglingSyntaxConditionalsTest, <ide><path>packages/ember-glimmer/tests/integration/syntax/each-test.js <del>import { get } from 'ember-metal/property_get'; <del>import { set } from 'ember-metal/property_set'; <add>import { get, set, propertyDidChange } from 'ember-metal'; <ide> import { applyMixins, strip } from '../../utils/abstract-test-case'; <ide> import { moduleFor, RenderingTest } from '../../utils/test-case'; <del>import { A as emberA } from 'ember-runtime/system/native_array'; <del>import ArrayProxy from 'ember-runtime/system/array_proxy'; <del>import { propertyDidChange } from 'ember-metal/property_events'; <add>import { A as emberA, ArrayProxy } from 'ember-runtime'; <ide> <ide> import { <ide> TogglingSyntaxConditionalsTest, <ide><path>packages/ember-glimmer/tests/integration/syntax/if-unless-test.js <ide> import { Component } from '../../utils/helpers'; <del>import { A as emberA } from 'ember-runtime/system/native_array'; <del>import { set } from 'ember-metal/property_set'; <add>import { A as emberA } from 'ember-runtime'; <add>import { set } from 'ember-metal'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> <ide> import { RenderingTest, moduleFor } from '../../utils/test-case'; <ide><path>packages/ember-glimmer/tests/integration/syntax/with-test.js <del>import { get } from 'ember-metal/property_get'; <del>import { set } from 'ember-metal/property_set'; <del>import { A as emberA } from 'ember-runtime/system/native_array'; <add>import { get, set } from 'ember-metal'; <add>import { A as emberA, ObjectProxy, removeAt } from 'ember-runtime'; <ide> import { moduleFor, RenderingTest } from '../../utils/test-case'; <ide> import { IfUnlessWithSyntaxTest } from '../../utils/shared-conditional-tests'; <ide> import { strip } from '../../utils/abstract-test-case'; <del>import ObjectProxy from 'ember-runtime/system/object_proxy'; <del>import { removeAt } from 'ember-runtime/mixins/mutable_array'; <ide> <ide> moduleFor('Syntax test: {{#with}}', class extends IfUnlessWithSyntaxTest { <ide> <ide><path>packages/ember-glimmer/tests/unit/layout-cache-test.js <ide> import { RenderingTest, moduleFor } from '../utils/test-case'; <del>import EmptyObject from 'ember-metal/empty_object'; <add>import { EmptyObject } from 'ember-metal'; <ide> import { CompiledBlock } from 'glimmer-runtime'; <ide> <ide> class Counter { <ide><path>packages/ember-glimmer/tests/unit/template-factory-test.js <ide> import { precompile, compile } from 'ember-template-compiler'; <del>import { template } from 'ember-glimmer'; <add>import { template } from '../../index'; <ide> import { RenderingTest, moduleFor } from '../utils/test-case'; <ide> import { Component } from '../utils/helpers'; <ide> <ide><path>packages/ember-glimmer/tests/utils/abstract-test-case.js <ide> import { compile, helper, Helper, Component } from './helpers'; <del>import { equalsElement, equalTokens, regex, classes, equalInnerHTML } from './test-helpers'; <del>import run from 'ember-metal/run_loop'; <del>import { runAppend, runDestroy } from 'ember-runtime/tests/utils'; <del>import jQuery from 'ember-views/system/jquery'; <del>import assign from 'ember-metal/assign'; <del>import Application from 'ember-application/system/application'; <del>import Router from 'ember-routing/system/router'; <del>import EventDispatcher from 'ember-views/system/event_dispatcher'; <add>import { <add> equalsElement, <add> equalTokens, <add> regex, <add> classes, <add> equalInnerHTML <add>} from './test-helpers'; <add>import { run, assign } from 'ember-metal'; <add>import { runAppend, runDestroy } from 'internal-test-helpers'; <add>import { jQuery, EventDispatcher } from 'ember-views'; <add>import { Application } from 'ember-application'; <add>import { Router } from 'ember-routing'; <ide> import { buildOwner } from './helpers'; <ide> <ide> function isGenerator(mixin) { <ide><path>packages/ember-glimmer/tests/utils/shared-conditional-tests.js <ide> import { applyMixins } from './abstract-test-case'; <ide> import { RenderingTest } from './test-case'; <del>import { get } from 'ember-metal/property_get'; <del>import { set } from 'ember-metal/property_set'; <del>import assign from 'ember-metal/assign'; <del>import EmberObject from 'ember-runtime/system/object'; <del>import ObjectProxy from 'ember-runtime/system/object_proxy'; <del>import { A as emberA } from 'ember-runtime/system/native_array'; <del>import ArrayProxy from 'ember-runtime/system/array_proxy'; <del>import { removeAt } from 'ember-runtime/mixins/mutable_array'; <add>import { get, set, assign } from 'ember-metal'; <add>import { <add> Object as EmberObject, <add> ObjectProxy, <add> A as emberA, <add> ArrayProxy, <add> removeAt <add>} from 'ember-runtime'; <ide> import { Component } from './helpers'; <ide> <ide> class AbstractConditionalsTest extends RenderingTest { <ide><path>packages/ember-glimmer/tests/utils/string-test.js <ide> import { SafeString, htmlSafe, isHTMLSafe } from './helpers'; <del>import isEnabled from 'ember-metal/features'; <add>import { isFeatureEnabled } from 'ember-metal'; <ide> import { TestCase } from './abstract-test-case'; <ide> import { moduleFor } from './test-case'; <ide> <ide> moduleFor('SafeString', class extends TestCase { <ide> } <ide> }); <ide> <del>if (isEnabled('ember-string-ishtmlsafe')) { <add>if (isFeatureEnabled('ember-string-ishtmlsafe')) { <ide> moduleFor('SafeString isHTMLSafe', class extends TestCase { <ide> ['@test isHTMLSafe should detect SafeString']() { <ide> let safeString = htmlSafe('<em>Emphasize</em> the important things.'); <ide><path>packages/ember-glimmer/tests/utils/test-case.js <ide> import { <ide> AbstractApplicationTest, <ide> AbstractRenderingTest <ide> } from './abstract-test-case'; <del>import ComponentLookup from 'ember-views/component_lookup'; <add>import { ComponentLookup } from 'ember-views'; <ide> <ide> export class ApplicationTest extends AbstractApplicationTest { <ide> } <ide><path>packages/ember-routing/tests/system/route_test.js <del>import { runDestroy } from 'ember-runtime/tests/utils'; <add>import { runDestroy } from 'internal-test-helpers'; <ide> import Service from 'ember-runtime/system/service'; <ide> import EmberObject from 'ember-runtime/system/object'; <ide> import EmberRoute from 'ember-routing/system/route'; <ide><path>packages/ember-routing/tests/system/router_test.js <ide> import HistoryLocation from 'ember-routing/location/history_location'; <ide> import AutoLocation from 'ember-routing/location/auto_location'; <ide> import NoneLocation from 'ember-routing/location/none_location'; <ide> import Router, { triggerEvent } from 'ember-routing/system/router'; <del>import { runDestroy } from 'ember-runtime/tests/utils'; <del>import { buildOwner } from 'internal-test-helpers'; <add>import { runDestroy, buildOwner } from 'internal-test-helpers'; <ide> import { setOwner } from 'container'; <ide> <ide> let owner; <ide><path>packages/ember-runtime/lib/index.js <ide> export { <ide> } from './system/lazy_load'; <ide> export { default as Observable } from './mixins/observable'; <ide> export { default as MutableEnumerable } from './mixins/mutable_enumerable'; <del>export { default as MutableArray } from './mixins/mutable_array'; <add>export { <add> default as MutableArray, <add> removeAt <add>} from './mixins/mutable_array'; <ide> export { default as TargetActionSupport } from './mixins/target_action_support'; <ide> export { default as Evented } from './mixins/evented'; <ide> export { default as PromiseProxyMixin } from './mixins/promise_proxy'; <ide><path>packages/ember-runtime/tests/utils.js <del>import { run } from 'ember-metal'; <del> <del>function runAppend(view) { <del> run(view, 'appendTo', '#qunit-fixture'); <del>} <del> <del>function runDestroy(destroyed) { <del> if (destroyed) { <del> run(destroyed, 'destroy'); <del> } <del>} <del> <del>export { <del> runAppend, <del> runDestroy <del>}; <ide><path>packages/ember-template-compiler/tests/system/bootstrap-test.js <ide> import run from 'ember-metal/run_loop'; <ide> import jQuery from 'ember-views/system/jquery'; <ide> import { Component, getTemplate, setTemplates } from 'ember-glimmer'; <del>import { runAppend, runDestroy } from 'ember-runtime/tests/utils'; <ide> import bootstrap from 'ember-template-compiler/system/bootstrap'; <del>import { buildOwner } from 'internal-test-helpers'; <add>import { <add> runAppend, <add> runDestroy, <add> buildOwner <add>} from 'internal-test-helpers'; <ide> <ide> import { <ide> hasTemplate, <ide><path>packages/internal-test-helpers/lib/index.js <ide> import { ENV } from 'ember-environment'; <ide> import { <ide> get as getFromEmberMetal, <ide> getWithDefault as getWithDefaultFromEmberMetal, <del> set as setFromEmberMetal <add> set as setFromEmberMetal, <add> run <ide> } from 'ember-metal'; <ide> <ide> import require from 'require'; <ide> export function testWithDefault(testname, callback) { <ide> } <ide> }); <ide> } <add> <add>export function runAppend(view) { <add> run(view, 'appendTo', '#qunit-fixture'); <add>} <add> <add>export function runDestroy(toDestroy) { <add> if (toDestroy) { <add> run(toDestroy, 'destroy'); <add> } <add>}
57
Javascript
Javascript
allow option view for ember.select overwritable
6c6b6445aa38c58ba7a10133e2d30a3b4dd65ed3
<ide><path>packages/ember-handlebars/lib/controls/select.js <ide> var set = Ember.set, <ide> isArray = Ember.isArray, <ide> precompileTemplate = Ember.Handlebars.compile; <ide> <add>Ember.SelectOption = Ember.View.extend({ <add> tagName: 'option', <add> attributeBindings: ['value', 'selected'], <add> <add> defaultTemplate: function(context, options) { <add> options = { data: options.data, hash: {} }; <add> Ember.Handlebars.helpers.bind.call(context, "view.label", options); <add> }, <add> <add> init: function() { <add> this.labelPathDidChange(); <add> this.valuePathDidChange(); <add> <add> this._super(); <add> }, <add> <add> selected: Ember.computed(function() { <add> var content = get(this, 'content'), <add> selection = get(this, 'parentView.selection'); <add> if (get(this, 'parentView.multiple')) { <add> return selection && indexOf(selection, content.valueOf()) > -1; <add> } else { <add> // Primitives get passed through bindings as objects... since <add> // `new Number(4) !== 4`, we use `==` below <add> return content == selection; <add> } <add> }).property('content', 'parentView.selection'), <add> <add> labelPathDidChange: Ember.observer(function() { <add> var labelPath = get(this, 'parentView.optionLabelPath'); <add> <add> if (!labelPath) { return; } <add> <add> Ember.defineProperty(this, 'label', Ember.computed(function() { <add> return get(this, labelPath); <add> }).property(labelPath)); <add> }, 'parentView.optionLabelPath'), <add> <add> valuePathDidChange: Ember.observer(function() { <add> var valuePath = get(this, 'parentView.optionValuePath'); <add> <add> if (!valuePath) { return; } <add> <add> Ember.defineProperty(this, 'value', Ember.computed(function() { <add> return get(this, valuePath); <add> }).property(valuePath)); <add> }, 'parentView.optionValuePath') <add>}); <add> <ide> /** <ide> The `Ember.Select` view class renders a <ide> [select](https://developer.mozilla.org/en/HTML/Element/select) HTML element, <ide> Ember.Select = Ember.View.extend( <ide> <ide> tagName: 'select', <ide> classNames: ['ember-select'], <del> defaultTemplate: precompileTemplate('{{#if view.prompt}}<option value="">{{view.prompt}}</option>{{/if}}{{#each view.content}}{{view Ember.SelectOption contentBinding="this"}}{{/each}}'), <add> defaultTemplate: precompileTemplate('{{#if view.prompt}}<option value="">{{view.prompt}}</option>{{/if}}{{#each view.content}}{{view view.optionView contentBinding="this"}}{{/each}}'), <ide> attributeBindings: ['multiple', 'disabled', 'tabindex', 'name'], <ide> <ide> /** <ide> Ember.Select = Ember.View.extend( <ide> */ <ide> optionValuePath: 'content', <ide> <add> /** <add> The view class for option. <add> <add> @property optionView <add> @type Ember.View <add> @default Ember.SelectOption <add> */ <add> optionView: Ember.SelectOption, <add> <ide> _change: function() { <ide> if (get(this, 'multiple')) { <ide> this._changeMultiple(); <ide> Ember.Select = Ember.View.extend( <ide> this.on("change", this, this._change); <ide> } <ide> }); <del> <del>Ember.SelectOption = Ember.View.extend({ <del> tagName: 'option', <del> attributeBindings: ['value', 'selected'], <del> <del> defaultTemplate: function(context, options) { <del> options = { data: options.data, hash: {} }; <del> Ember.Handlebars.helpers.bind.call(context, "view.label", options); <del> }, <del> <del> init: function() { <del> this.labelPathDidChange(); <del> this.valuePathDidChange(); <del> <del> this._super(); <del> }, <del> <del> selected: Ember.computed(function() { <del> var content = get(this, 'content'), <del> selection = get(this, 'parentView.selection'); <del> if (get(this, 'parentView.multiple')) { <del> return selection && indexOf(selection, content.valueOf()) > -1; <del> } else { <del> // Primitives get passed through bindings as objects... since <del> // `new Number(4) !== 4`, we use `==` below <del> return content == selection; <del> } <del> }).property('content', 'parentView.selection'), <del> <del> labelPathDidChange: Ember.observer(function() { <del> var labelPath = get(this, 'parentView.optionLabelPath'); <del> <del> if (!labelPath) { return; } <del> <del> Ember.defineProperty(this, 'label', Ember.computed(function() { <del> return get(this, labelPath); <del> }).property(labelPath)); <del> }, 'parentView.optionLabelPath'), <del> <del> valuePathDidChange: Ember.observer(function() { <del> var valuePath = get(this, 'parentView.optionValuePath'); <del> <del> if (!valuePath) { return; } <del> <del> Ember.defineProperty(this, 'value', Ember.computed(function() { <del> return get(this, valuePath); <del> }).property(valuePath)); <del> }, 'parentView.optionValuePath') <del>});
1
Mixed
Ruby
implement content disposition in direct upload
9940c65a78c913c6f67b3fc0f1595311865128e9
<ide><path>activestorage/CHANGELOG.md <add>* Set content disposition in direct upload using `filename` and `disposition` parameters to `ActiveStorage::Service#headers_for_direct_upload`. <add> <add> *Peter Zhu* <add> <ide> * Allow record to be optionally passed to blob finders to make sharding <ide> easier. <ide> <ide><path>activestorage/lib/active_storage/service/azure_storage_service.rb <ide> def url_for_direct_upload(key, expires_in:, content_type:, content_length:, chec <ide> end <ide> end <ide> <del> def headers_for_direct_upload(key, content_type:, checksum:, **) <del> { "Content-Type" => content_type, "Content-MD5" => checksum, "x-ms-blob-type" => "BlockBlob" } <add> def headers_for_direct_upload(key, content_type:, checksum:, filename: nil, disposition: nil, **) <add> content_disposition = content_disposition_with(type: disposition, filename: filename) if filename <add> <add> { "Content-Type" => content_type, "Content-MD5" => checksum, "x-ms-blob-content-disposition" => content_disposition, "x-ms-blob-type" => "BlockBlob" } <ide> end <ide> <ide> private <ide><path>activestorage/lib/active_storage/service/gcs_service.rb <ide> def url_for_direct_upload(key, expires_in:, checksum:, **) <ide> end <ide> end <ide> <del> def headers_for_direct_upload(key, checksum:, **) <del> { "Content-MD5" => checksum } <add> def headers_for_direct_upload(key, checksum:, filename: nil, disposition: nil, **) <add> content_disposition = content_disposition_with(type: disposition, filename: filename) if filename <add> <add> { "Content-MD5" => checksum, "Content-Disposition" => content_disposition } <ide> end <ide> <ide> private <ide><path>activestorage/lib/active_storage/service/s3_service.rb <ide> def url_for_direct_upload(key, expires_in:, content_type:, content_length:, chec <ide> end <ide> end <ide> <del> def headers_for_direct_upload(key, content_type:, checksum:, **) <del> { "Content-Type" => content_type, "Content-MD5" => checksum } <add> def headers_for_direct_upload(key, content_type:, checksum:, filename: nil, disposition: nil, **) <add> content_disposition = content_disposition_with(type: disposition, filename: filename) if filename <add> <add> { "Content-Type" => content_type, "Content-MD5" => checksum, "Content-Disposition" => content_disposition } <ide> end <ide> <ide> private <ide><path>activestorage/test/controllers/direct_uploads_controller_test.rb <ide> class ActiveStorage::S3DirectUploadsControllerTest < ActionDispatch::Integration <ide> assert_equal "text/plain", details["content_type"] <ide> assert_match SERVICE_CONFIGURATIONS[:s3][:bucket], details["direct_upload"]["url"] <ide> assert_match(/s3(-[-a-z0-9]+)?\.(\S+)?amazonaws\.com/, details["direct_upload"]["url"]) <del> assert_equal({ "Content-Type" => "text/plain", "Content-MD5" => checksum }, details["direct_upload"]["headers"]) <add> assert_equal({ "Content-Type" => "text/plain", "Content-MD5" => checksum, "Content-Disposition" => "inline; filename=\"hello.txt\"; filename*=UTF-8''hello.txt" }, details["direct_upload"]["headers"]) <ide> end <ide> end <ide> end <ide> class ActiveStorage::GCSDirectUploadsControllerTest < ActionDispatch::Integratio <ide> assert_equal checksum, details["checksum"] <ide> assert_equal "text/plain", details["content_type"] <ide> assert_match %r{storage\.googleapis\.com/#{@config[:bucket]}}, details["direct_upload"]["url"] <del> assert_equal({ "Content-MD5" => checksum }, details["direct_upload"]["headers"]) <add> assert_equal({ "Content-MD5" => checksum, "Content-Disposition" => "inline; filename=\"hello.txt\"; filename*=UTF-8''hello.txt" }, details["direct_upload"]["headers"]) <ide> end <ide> end <ide> end <ide> class ActiveStorage::AzureStorageDirectUploadsControllerTest < ActionDispatch::I <ide> assert_equal checksum, details["checksum"] <ide> assert_equal "text/plain", details["content_type"] <ide> assert_match %r{#{@config[:storage_account_name]}\.blob\.core\.windows\.net/#{@config[:container]}}, details["direct_upload"]["url"] <del> assert_equal({ "Content-Type" => "text/plain", "Content-MD5" => checksum, "x-ms-blob-type" => "BlockBlob" }, details["direct_upload"]["headers"]) <add> assert_equal({ "Content-Type" => "text/plain", "Content-MD5" => checksum, "x-ms-blob-content-disposition" => "inline; filename=\"hello.txt\"; filename*=UTF-8''hello.txt", "x-ms-blob-type" => "BlockBlob" }, details["direct_upload"]["headers"]) <ide> end <ide> end <ide> end <ide><path>activestorage/test/service/azure_storage_service_test.rb <ide> class ActiveStorage::Service::AzureStorageServiceTest < ActiveSupport::TestCase <ide> @service.delete key <ide> end <ide> <add> test "direct upload with content disposition" do <add> key = SecureRandom.base58(24) <add> data = "Something else entirely!" <add> checksum = Digest::MD5.base64digest(data) <add> url = @service.url_for_direct_upload(key, expires_in: 5.minutes, content_type: "text/plain", content_length: data.size, checksum: checksum) <add> <add> uri = URI.parse url <add> request = Net::HTTP::Put.new uri.request_uri <add> request.body = data <add> @service.headers_for_direct_upload(key, checksum: checksum, content_type: "text/plain", filename: ActiveStorage::Filename.new("test.txt"), disposition: :attachment).each do |k, v| <add> request.add_field k, v <add> end <add> Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| <add> http.request request <add> end <add> <add> assert_equal("attachment; filename=\"test.txt\"; filename*=UTF-8''test.txt", @service.client.get_blob_properties(@service.container, key).properties[:content_disposition]) <add> ensure <add> @service.delete key <add> end <add> <ide> test "upload with content_type" do <ide> key = SecureRandom.base58(24) <ide> data = "Foobar" <ide><path>activestorage/test/service/gcs_service_test.rb <ide> class ActiveStorage::Service::GCSServiceTest < ActiveSupport::TestCase <ide> @service.delete key <ide> end <ide> <add> test "direct upload with content disposition" do <add> key = SecureRandom.base58(24) <add> data = "Something else entirely!" <add> checksum = Digest::MD5.base64digest(data) <add> url = @service.url_for_direct_upload(key, expires_in: 5.minutes, content_type: "text/plain", content_length: data.size, checksum: checksum) <add> <add> uri = URI.parse url <add> request = Net::HTTP::Put.new uri.request_uri <add> request.body = data <add> @service.headers_for_direct_upload(key, checksum: checksum, filename: ActiveStorage::Filename.new("test.txt"), disposition: :attachment).each do |k, v| <add> request.add_field k, v <add> end <add> request.add_field "Content-Type", "" <add> Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| <add> http.request request <add> end <add> <add> url = @service.url(key, expires_in: 2.minutes, disposition: :inline, content_type: "text/html", filename: ActiveStorage::Filename.new("test.html")) <add> response = Net::HTTP.get_response(URI(url)) <add> assert_equal("attachment; filename=\"test.txt\"; filename*=UTF-8''test.txt", response["Content-Disposition"]) <add> ensure <add> @service.delete key <add> end <add> <ide> test "upload with content_type and content_disposition" do <ide> key = SecureRandom.base58(24) <ide> data = "Something else entirely!" <ide><path>activestorage/test/service/s3_service_test.rb <ide> class ActiveStorage::Service::S3ServiceTest < ActiveSupport::TestCase <ide> @service.delete key <ide> end <ide> <add> test "direct upload with content disposition" do <add> key = SecureRandom.base58(24) <add> data = "Something else entirely!" <add> checksum = Digest::MD5.base64digest(data) <add> url = @service.url_for_direct_upload(key, expires_in: 5.minutes, content_type: "text/plain", content_length: data.size, checksum: checksum) <add> <add> uri = URI.parse url <add> request = Net::HTTP::Put.new uri.request_uri <add> request.body = data <add> @service.headers_for_direct_upload(key, checksum: checksum, content_type: "text/plain", filename: ActiveStorage::Filename.new("test.txt"), disposition: :attachment).each do |k, v| <add> request.add_field k, v <add> end <add> Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| <add> http.request request <add> end <add> <add> assert_equal("attachment; filename=\"test.txt\"; filename*=UTF-8''test.txt", @service.bucket.object(key).content_disposition) <add> ensure <add> @service.delete key <add> end <add> <ide> test "upload a zero byte file" do <ide> blob = directly_upload_file_blob filename: "empty_file.txt", content_type: nil <ide> user = User.create! name: "DHH", avatar: blob
8
Java
Java
remove unnecessary assertion
1e003a1c90fe7f5aa91f99a34fa5be53a43ad6d8
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandler.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 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> protected void handleMessageInternal(Message<?> message) { <ide> return; <ide> } <ide> <del> SimpMessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class); <del> if (accessor == null) { <del> throw new IllegalStateException( <del> "No header accessor (not using the SimpMessagingTemplate?): " + message); <del> } <del> <ide> if (SimpMessageType.MESSAGE.equals(messageType)) { <ide> logMessage(message); <ide> sendMessageToSubscribers(destination, message);
1
Python
Python
replace tab with spaces
f90bb0842577786ffc9383b305d36ad8b79eb58e
<ide><path>airflow/example_dags/example_branch_python_dop_operator_3.py <ide> <ide> from airflow.operators import BranchPythonOperator, DummyOperator <ide> from airflow.models import DAG <del>import airflow.utils <ide> from datetime import datetime, timedelta <ide> <ide> two_days_ago = datetime.combine(datetime.today() - timedelta(2), <ide> def should_run(ds, **kwargs): <ide> <ide> print("------------- exec dttm = {} and minute = {}".format(kwargs['execution_date'], kwargs['execution_date'].minute)) <ide> if kwargs['execution_date'].minute % 2 == 0: <del> return "oper_1" <add> return "oper_1" <ide> else: <ide> return "oper_2" <ide>
1
PHP
PHP
allow input type=number to also be magic
9a9ac6f3a7fd112e4d685f3cf507d528ed9cf102
<ide><path>lib/Cake/View/Helper/FormHelper.php <ide> public function input($fieldName, $options = array()) { <ide> <ide> if ( <ide> (!isset($options['options']) && in_array($options['type'], $types)) || <del> (isset($magicType) && $options['type'] == 'text') <add> (isset($magicType) && in_array($options['type'], array('text', 'number'))) <ide> ) { <ide> $varName = Inflector::variable( <ide> Inflector::pluralize(preg_replace('/_id$/', '', $fieldKey))
1
Python
Python
remove obsolete code
d0689a3243b77b8b65e9c49eb8376a9dd190b698
<ide><path>numpy/distutils/ccompiler.py <ide> def CCompiler_spawn(self, cmd, display=None): <ide> else: <ide> msg = '' <ide> raise DistutilsExecError('Command "%s" failed with exit status %d%s' % (cmd, s, msg)) <del> if hasattr(self, 'config_output'): <del> self.config_output += o <ide> <ide> replace_method(CCompiler, 'spawn', CCompiler_spawn) <ide> <ide><path>numpy/distutils/command/autodist.py <ide> def check_gcc_variable_attribute(cmd, attribute): <ide> } <ide> """ % (attribute, ) <ide> return cmd.try_compile(body, None, None) != 0 <del> <del>def check_compile_without_warning(cmd, body): <del> cmd._check_compiler() <del> ret, output = cmd.try_output_compile(body, None, None) <del> if not ret or len(output) > 0: <del> return False <del> return True <ide><path>numpy/distutils/command/config.py <ide> from numpy.distutils.command.autodist import (check_gcc_function_attribute, <ide> check_gcc_variable_attribute, <ide> check_inline, <del> check_compiler_gcc4, <del> check_compile_without_warning) <add> check_compiler_gcc4) <ide> from numpy.distutils.compat import get_exception <ide> <ide> LANG_EXT['f77'] = '.f' <ide> def try_run(self, body, headers=None, include_dirs=None, <ide> return old_config.try_run(self, body, headers, include_dirs, libraries, <ide> library_dirs, lang) <ide> <del> def try_output_compile(self, body, headers=None, include_dirs=None, lang="c"): <del> """Try to compile a source file built from 'body' and 'headers'. <del> Return true on success, false otherwise. <del> """ <del> # XXX: this is fairly ugly. Passing the output of executed command <del> # would require heroic efforts so instead we use a dynamically created <del> # instance variable on the compiler class to pass output between <del> # compiler and the config command. <del> self.compiler.config_output = "" <del> self._check_compiler() <del> try: <del> self._compile(body, headers, include_dirs, lang) <del> status = True <del> except CompileError: <del> status = False <del> <del> log.info(status and "success!" or "failure.") <del> self._clean() <del> return status, self.compiler.config_output <del> <ide> def _check_compiler (self): <ide> old_config._check_compiler(self) <ide> from numpy.distutils.fcompiler import FCompiler, new_fcompiler <ide> def check_gcc_function_attribute(self, attribute, name): <ide> def check_gcc_variable_attribute(self, attribute): <ide> return check_gcc_variable_attribute(self, attribute) <ide> <del> def check_compile_without_warning(self, code): <del> """Returns True if the given code may be compiled without warning.""" <del> return check_compile_without_warning(self, code) <del> <ide> def get_output(self, body, headers=None, include_dirs=None, <ide> libraries=None, library_dirs=None, <ide> lang="c", use_tee=None):
3
Ruby
Ruby
replace depends_on with uses_from_macos
86feb5a9deeffbf0b41850098c0fd3505d8a1673
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit_deps <ide> dep_f.keg_only_reason.valid? && <ide> !%w[apr apr-util openblas openssl [email protected]].include?(dep.name) <ide> new_formula_problem( <del> "Dependency '#{dep.name}' may be unnecessary as it is provided " \ <del> "by macOS; try to build this formula without it.", <add> "Dependency '#{dep.name}' is provided by macOS; " \ <add> "please replace 'depends_on' with 'uses_from_macos'.", <ide> ) <ide> end <ide> <ide><path>Library/Homebrew/test/dev-cmd/audit_spec.rb <ide> class Foo < Formula <ide> fa.audit_deps <ide> end <ide> <del> its(:new_formula_problems) { are_expected.to match([/unnecessary/]) } <add> its(:new_formula_problems) { are_expected.to match([/is provided by macOS/]) } <ide> end <ide> end <ide> end
2
Go
Go
fix error reporting in `copyfilewithtar`
57e12037ac8f8eb48cc05979c3030853d011dfea
<ide><path>pkg/archive/archive.go <ide> func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { <ide> return nil <ide> }) <ide> defer func() { <del> if er := <-errC; err != nil { <add> if er := <-errC; err == nil && er != nil { <ide> err = er <ide> } <ide> }()
1
Java
Java
remove trailing whitespace in java source code
7018747ceccb0f715093af2a12312e42d52d9579
<ide><path>spring-core/src/main/java/org/springframework/util/concurrent/CompletableToListenableFutureAdapter.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del> <add> <ide> package org.springframework.util.concurrent; <del> <add> <ide> import java.util.concurrent.CompletableFuture; <ide> import java.util.concurrent.ExecutionException; <ide> import java.util.concurrent.TimeUnit; <ide> */ <ide> @UsesJava8 <ide> public class CompletableToListenableFutureAdapter<T> implements ListenableFuture<T> { <del> <add> <ide> private final CompletableFuture<T> completableFuture; <del> <add> <ide> private final ListenableFutureCallbackRegistry<T> callbacks = new ListenableFutureCallbackRegistry<T>(); <del> <add> <ide> public CompletableToListenableFutureAdapter(CompletableFuture<T> completableFuture) { <ide> this.completableFuture = completableFuture; <ide> this.completableFuture.handle(new BiFunction<T, Throwable, Object>() { <ide> public Object apply(T result, Throwable ex) { <ide> } <ide> }); <ide> } <del> <add> <ide> @Override <ide> public void addCallback(ListenableFutureCallback<? super T> callback) { <ide> this.callbacks.addCallback(callback); <ide> } <del> <add> <ide> @Override <ide> public void addCallback(SuccessCallback<? super T> successCallback, FailureCallback failureCallback) { <ide> this.callbacks.addSuccessCallback(successCallback); <ide> this.callbacks.addFailureCallback(failureCallback); <ide> } <del> <add> <ide> @Override <ide> public boolean cancel(boolean mayInterruptIfRunning) { <ide> return this.completableFuture.cancel(mayInterruptIfRunning); <ide> } <del> <add> <ide> @Override <ide> public boolean isCancelled() { <ide> return this.completableFuture.isCancelled(); <ide> } <del> <add> <ide> @Override <ide> public boolean isDone() { <ide> return this.completableFuture.isDone(); <ide> } <del> <add> <ide> @Override <ide> public T get() throws InterruptedException, ExecutionException { <ide> return this.completableFuture.get(); <ide> } <del> <add> <ide> @Override <ide> public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { <ide> return this.completableFuture.get(timeout, unit); <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/CodeFlow.java <ide> public static void insertUnboxNumberInsns(MethodVisitor mv, char targetDescripto <ide> mv.visitTypeInsn(CHECKCAST, "java/lang/Number"); <ide> } <ide> mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "doubleValue", "()D", false); <del> break; <add> break; <ide> case 'F': <ide> if (stackDescriptor.equals("Ljava/lang/Object")) { <ide> mv.visitTypeInsn(CHECKCAST, "java/lang/Number"); <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ExpressionState.java <ide> public class ExpressionState { <ide> // When entering a new scope there is a new base object which should be used <ide> // for '#this' references (or to act as a target for unqualified references). <ide> // This stack captures those objects at each nested scope level. <del> // For example: <add> // For example: <ide> // #list1.?[#list2.contains(#this)] <ide> // On entering the selection we enter a new scope, and #this is now the <ide> // element from list1 <ide> public void enterScope(Map<String, Object> argMap) { <ide> this.variableScopes.push(new VariableScope(argMap)); <ide> this.scopeRootObjects.push(getActiveContextObject()); <ide> } <del> <add> <ide> public void enterScope() { <ide> ensureVariableScopesInitialized(); <ide> this.variableScopes.push(new VariableScope(Collections.<String,Object>emptyMap())); <del> this.scopeRootObjects.push(getActiveContextObject()); <add> this.scopeRootObjects.push(getActiveContextObject()); <ide> } <ide> <ide> public void enterScope(String name, Object value) { <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java <ide> else if (peekToken(TokenKind.COMMA, true)) { // multi item list <ide> while (peekToken(TokenKind.COMMA,true)); <ide> closingCurly = eatToken(TokenKind.RCURLY); <ide> expr = new InlineList(toPos(t.startPos,closingCurly.endPos),listElements.toArray(new SpelNodeImpl[listElements.size()])); <del> <add> <ide> } <ide> else if (peekToken(TokenKind.COLON, true)) { // map! <ide> List<SpelNodeImpl> mapElements = new ArrayList<SpelNodeImpl>(); <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectiveMethodExecutor.java <ide> private Class<?> discoverPublicClass(Method method, Class<?> clazz) { <ide> clazz.getDeclaredMethod(method.getName(), method.getParameterTypes()); <ide> return clazz; <ide> } catch (NoSuchMethodException nsme) { <del> <add> <ide> } <ide> } <ide> Class<?>[] intfaces = clazz.getInterfaces(); <ide><path>spring-expression/src/test/java/org/springframework/expression/spel/MapTests.java <ide> public void testMapKeysThatAreAlsoSpELKeywords() { <ide> expression = (SpelExpression) parser.parseExpression("foo['abc.def']"); <ide> o = expression.getValue(new MapHolder()); <ide> assertEquals("value", o); <del> <add> <ide> expression = (SpelExpression)parser.parseExpression("foo[foo[NEW]]"); <ide> o = expression.getValue(new MapHolder()); <ide> assertEquals("37",o); <ide> <ide> expression = (SpelExpression)parser.parseExpression("foo[foo[new]]"); <ide> o = expression.getValue(new MapHolder()); <ide> assertEquals("38",o); <del> <add> <ide> expression = (SpelExpression)parser.parseExpression("foo[foo[foo[T]]]"); <ide> o = expression.getValue(new MapHolder()); <ide> assertEquals("value",o); <ide><path>spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java <ide> public void failsWhenSettingContextForExpression_SPR12326() { <ide> context.setVariable("it", person); <ide> expression.setEvaluationContext(context); <ide> assertTrue(expression.getValue(Boolean.class)); <del> assertTrue(expression.getValue(Boolean.class)); <add> assertTrue(expression.getValue(Boolean.class)); <ide> assertCanCompile(expression); <ide> assertTrue(expression.getValue(Boolean.class)); <ide> } <ide> public void indexer() throws Exception { <ide> float[] fs = new float[]{6.0f,7.0f,8.0f}; <ide> byte[] bs = new byte[]{(byte)2,(byte)3,(byte)4}; <ide> char[] cs = new char[]{'a','b','c'}; <del> <add> <ide> // Access String (reference type) array <ide> expression = parser.parseExpression("[0]"); <ide> assertEquals("a",expression.getValue(sss)); <ide> public void fourteen(String a, String[]... vargs) { <ide> for (String[] varg: vargs) { <ide> s+="{"; <ide> for (String v: varg) { <del> s+=v; <add> s+=v; <ide> } <ide> s+="}"; <ide> } <ide> public void fifteen(String a, int[]... vargs) { <ide> for (int[] varg: vargs) { <ide> s+="{"; <ide> for (int v: varg) { <del> s+=Integer.toString(v); <add> s+=Integer.toString(v); <ide> } <ide> s+="}"; <ide> } <ide> public Obj3(int... params) { <ide> } <ide> output = b.toString(); <ide> } <del> <add> <ide> public Obj3(String s, Float f, int... ints) { <ide> StringBuilder b = new StringBuilder(); <ide> b.append(s); <ide> public Obj3(String s, Float f, int... ints) { <ide> output = b.toString(); <ide> } <ide> } <del> <add> <ide> public static class Obj4 { <del> <add> <ide> public final String output; <ide> <ide> public Obj4(int[] params) { <ide><path>spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java <ide> public void SPR12808() throws Exception { <ide> sec.setVariable("no", "1.0"); <ide> assertTrue(expression.getValue(sec).toString().startsWith("Object")); <ide> } <del> <add> <ide> @Test <ide> @SuppressWarnings("rawtypes") <ide> public void SPR13055() throws Exception { <ide> public void SPR12035() { <ide> assertTrue(expression2.getValue(new BeanClass(new ListOf(1.1), new ListOf(-2.2)), <ide> Boolean.class)); <ide> } <del> <add> <ide> static class CCC { <ide> public boolean method(Object o) { <ide> System.out.println(o); <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/user/DefaultUserDestinationResolverTests.java <ide> public void handleMessage() { <ide> } <ide> <ide> // SPR-12444 <del> <add> <ide> @Test <ide> public void handleMessageToOtherUser() { <del> <add> <ide> TestSimpUser otherSimpUser = new TestSimpUser("anna"); <ide> otherSimpUser.addSessions(new TestSimpSession("456")); <ide> when(this.registry.getUser("anna")).thenReturn(otherSimpUser); <ide><path>spring-web/src/main/java/org/springframework/web/cors/CorsConfiguration.java <ide> private List<String> combine(List<String> source, List<String> other) { <ide> List<String> combined = new ArrayList<String>(source); <ide> combined.addAll(other); <ide> return combined; <del> } <add> } <ide> <ide> /** <ide> * Configure origins to allow, e.g. "http://domain1.com". The special value <ide><path>spring-web/src/test/java/org/springframework/http/client/OkHttpAsyncClientHttpRequestFactoryTests.java <ide> * @author Luciano Leggieri <ide> */ <ide> public class OkHttpAsyncClientHttpRequestFactoryTests extends AbstractAsyncHttpRequestFactoryTestCase { <del> <add> <ide> @Override <ide> protected AsyncClientHttpRequestFactory createRequestFactory() { <ide> return new OkHttpClientHttpRequestFactory(); <ide><path>spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilderTests.java <ide> public void modulesToInstallByInstance() { <ide> @Test <ide> public void defaultModules() throws JsonProcessingException, UnsupportedEncodingException { <ide> ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build(); <del> <add> <ide> Long timestamp = 1322903730000L; <ide> DateTime dateTime = new DateTime(timestamp, DateTimeZone.UTC); <ide> assertEquals(timestamp.toString(), new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")); <del> <add> <ide> Optional<String> optional = Optional.of("test"); <ide> assertEquals("\"test\"", new String(objectMapper.writeValueAsBytes(optional), "UTF-8")); <ide> } <ide><path>spring-web/src/test/java/org/springframework/web/cors/CorsConfigurationTests.java <ide> public class CorsConfigurationTests { <ide> public void setup() { <ide> config = new CorsConfiguration(); <ide> } <del> <add> <ide> @Test <ide> public void setNullValues() { <ide> config.setAllowedOrigins(null); <ide> public void setNullValues() { <ide> config.setMaxAge(null); <ide> assertNull(config.getMaxAge()); <ide> } <del> <add> <ide> @Test <ide> public void setValues() { <ide> config.addAllowedOrigin("*"); <ide> public void setValues() { <ide> config.setMaxAge(123L); <ide> assertEquals(new Long(123), config.getMaxAge()); <ide> } <del> <add> <ide> @Test(expected = IllegalArgumentException.class) <ide> public void asteriskWildCardOnAddExposedHeader() { <ide> config.addExposedHeader("*"); <ide> } <del> <add> <ide> @Test(expected = IllegalArgumentException.class) <ide> public void asteriskWildCardOnSetExposedHeaders() { <ide> config.setExposedHeaders(Arrays.asList("*")); <ide> } <del> <add> <ide> @Test <ide> public void combineWithNull() { <ide> config.setAllowedOrigins(Arrays.asList("*")); <ide> config.combine(null); <ide> assertEquals(Arrays.asList("*"), config.getAllowedOrigins()); <ide> } <del> <add> <ide> @Test <ide> public void combineWithNullProperties() { <ide> config.addAllowedOrigin("*"); <ide> public void combineWithNullProperties() { <ide> assertEquals(new Long(123), config.getMaxAge()); <ide> assertTrue(config.getAllowCredentials()); <ide> } <del> <add> <ide> @Test <ide> public void combineWithAsteriskWildCard() { <ide> config.addAllowedOrigin("*"); <ide> public void combineWithAsteriskWildCard() { <ide> assertEquals(Arrays.asList("header2"), config.getExposedHeaders()); <ide> assertEquals(Arrays.asList(HttpMethod.PUT.name()), config.getAllowedMethods()); <ide> } <del> <add> <ide> @Test <ide> public void combine() { <ide> config.addAllowedOrigin("http://domain1.com"); <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/CorsConfigurer.java <ide> /** <ide> * Assist with the registration of {@link CorsConfiguration} mapped to one or more path patterns. <ide> * @author Sebastien Deleuze <del> * <add> * <ide> * @since 4.2 <ide> * @see CorsRegistration <ide> */ <ide> public class CorsConfigurer { <del> <add> <ide> private final List<CorsRegistration> registrations = new ArrayList<CorsRegistration>(); <ide> <ide> <ide> /** <ide> * Enable cross origin requests on the specified path patterns. If no path pattern is specified, <ide> * cross-origin request handling is mapped on "/**" . <del> * <add> * <ide> * <p>By default, all origins, all headers and credentials are allowed. Max age is set to 30 minutes.</p> <ide> */ <ide> public CorsRegistration enableCors(String... pathPatterns) { <ide> CorsRegistration registration = new CorsRegistration(pathPatterns); <ide> this.registrations.add(registration); <ide> return registration; <ide> } <del> <add> <ide> protected Map<String, CorsConfiguration> getCorsConfigurations() { <ide> Map<String, CorsConfiguration> configs = new LinkedHashMap<String, CorsConfiguration>(this.registrations.size()); <ide> for (CorsRegistration registration : this.registrations) { <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/CorsRegistration.java <ide> /** <ide> * Assists with the creation of a {@link CorsConfiguration} mapped to one or more path patterns. <ide> * If no path pattern is specified, cross-origin request handling is mapped on "/**" . <del> * <add> * <ide> * <p>By default, all origins, all headers, credentials and GET, HEAD, POST methods are allowed. <ide> * Max age is set to 30 minutes.</p> <del> * <add> * <ide> * @author Sebastien Deleuze <ide> * @since 4.2 <ide> */ <ide> public class CorsRegistration { <del> <add> <ide> private final String[] pathPatterns; <del> <add> <ide> private final CorsConfiguration config; <del> <add> <ide> public CorsRegistration(String... pathPatterns) { <ide> this.pathPatterns = (pathPatterns.length == 0 ? new String[]{ "/**" } : pathPatterns); <ide> // Same default values than @CrossOrigin annotation + allows simple methods <ide> public CorsRegistration(String... pathPatterns) { <ide> this.config.setAllowCredentials(true); <ide> this.config.setMaxAge(1800L); <ide> } <del> <add> <ide> public CorsRegistration allowedOrigins(String... origins) { <ide> this.config.setAllowedOrigins(new ArrayList<String>(Arrays.asList(origins))); <ide> return this; <ide> } <del> <add> <ide> public CorsRegistration allowedMethods(String... methods) { <ide> this.config.setAllowedMethods(new ArrayList<String>(Arrays.asList(methods))); <ide> return this; <ide> } <del> <add> <ide> public CorsRegistration allowedHeaders(String... headers) { <ide> this.config.setAllowedHeaders(new ArrayList<String>(Arrays.asList(headers))); <ide> return this; <ide> } <del> <add> <ide> public CorsRegistration exposedHeaders(String... headers) { <ide> this.config.setExposedHeaders(new ArrayList<String>(Arrays.asList(headers))); <ide> return this; <ide> } <del> <add> <ide> public CorsRegistration maxAge(long maxAge) { <ide> this.config.setMaxAge(maxAge); <ide> return this; <ide> } <del> <add> <ide> public CorsRegistration allowCredentials(boolean allowCredentials) { <ide> this.config.setAllowCredentials(allowCredentials); <ide> return this; <ide> } <del> <add> <ide> protected String[] getPathPatterns() { <ide> return this.pathPatterns; <ide> } <del> <add> <ide> protected CorsConfiguration getCorsConfiguration() { <ide> return this.config; <ide> } <del> <add> <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.java <ide> protected void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> <ide> protected void configureCors(CorsConfigurer configurer) { <ide> this.configurers.configureCors(configurer); <ide> } <del> <add> <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java <ide> public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv <ide> private ContentNegotiationManager contentNegotiationManager; <ide> <ide> private List<HttpMessageConverter<?>> messageConverters; <del> <add> <ide> private Map<String, CorsConfiguration> corsConfigurations; <ide> <ide> <ide> protected final Map<String, CorsConfiguration> getCorsConfigurations() { <ide> } <ide> return this.corsConfigurations; <ide> } <del> <add> <ide> /** <ide> * Override this method to configure cross-origin requests handling. <ide> * @since 4.2 <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.java <ide> public void configureDefaultServletHandling(DefaultServletHandlerConfigurer conf <ide> @Override <ide> public void configureCors(CorsConfigurer configurer) { <ide> } <del> <add> <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java <ide> public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport <ide> private final List<HandlerInterceptor> adaptedInterceptors = new ArrayList<HandlerInterceptor>(); <ide> <ide> private CorsProcessor corsProcessor = new DefaultCorsProcessor(); <del> <add> <ide> private final Map<String, CorsConfiguration> corsConfiguration = <ide> new LinkedHashMap<String, CorsConfiguration>(); <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java <ide> public UriComponentsBuilder withMethod(Class<?> controllerType, Method method, O <ide> ControllerMethodInvocationInterceptor(Class<?> controllerType) { <ide> this.controllerType = controllerType; <ide> } <del> <add> <ide> @Override <ide> public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) { <ide> if (getControllerMethod.equals(method)) { <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/CorsConfigurerTests.java <ide> <ide> /** <ide> * Test fixture with a {@link CorsConfigurer}. <del> * <add> * <ide> * @author Sebastien Deleuze <ide> */ <ide> public class CorsConfigurerTests { <del> <add> <ide> private CorsConfigurer configurer; <del> <add> <ide> @Before <ide> public void setUp() { <ide> this.configurer = new CorsConfigurer(); <ide> } <del> <add> <ide> @Test <ide> public void noCorsConfigured() { <ide> assertTrue(this.configurer.getCorsConfigurations().isEmpty()); <ide> } <del> <add> <ide> @Test <ide> public void multipleCorsConfigured() { <ide> this.configurer.enableCors("/foo"); <ide> this.configurer.enableCors("/bar"); <ide> assertEquals(2, this.configurer.getCorsConfigurations().size()); <ide> } <del> <add> <ide> @Test <ide> public void defaultCorsRegistration() { <ide> this.configurer.enableCors(); <ide> public void defaultCorsRegistration() { <ide> assertEquals(true, config.getAllowCredentials()); <ide> assertEquals(Long.valueOf(1800), config.getMaxAge()); <ide> } <del> <add> <ide> @Test <ide> public void customizedCorsRegistration() { <ide> this.configurer.enableCors("/foo").allowedOrigins("http://domain2.com", "http://domain2.com") <ide> public void customizedCorsRegistration() { <ide> assertEquals(false, config.getAllowCredentials()); <ide> assertEquals(Long.valueOf(3600), config.getMaxAge()); <ide> } <del> <add> <ide> } <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportExtensionTests.java <ide> public void viewResolvers() throws Exception { <ide> assertEquals("/", accessor.getPropertyValue("prefix")); <ide> assertEquals(".jsp", accessor.getPropertyValue("suffix")); <ide> } <del> <add> <ide> @Test <ide> public void crossOrigin() { <ide> Map<String, CorsConfiguration> configs = this.config.getCorsConfigurations(); <ide> public void configureDefaultServletHandling(DefaultServletHandlerConfigurer conf <ide> public void configureCors(CorsConfigurer registry) { <ide> registry.enableCors("/resources/**"); <ide> } <del> <add> <ide> } <ide> <ide> private class TestPathHelper extends UrlPathHelper {} <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/handler/CorsAbstractHandlerMappingTests.java <ide> public void preflightRequestWithCorsConfigurationProvider() throws Exception { <ide> assertNotNull(config); <ide> assertArrayEquals(config.getAllowedOrigins().toArray(), new String[]{"*"}); <ide> } <del> <add> <ide> @Test <ide> public void actualRequestWithMappedCorsConfiguration() throws Exception { <ide> CorsConfiguration config = new CorsConfiguration(); <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilderTests.java <ide> public void testFromMethodCallOnSubclass() { <ide> assertThat(uriComponents.toUriString(), startsWith("http://localhost")); <ide> assertThat(uriComponents.toUriString(), endsWith("/extended/else")); <ide> } <del> <add> <ide> @Test <ide> public void testFromMethodCallWithTypeLevelUriVars() { <ide> UriComponents uriComponents = fromMethodCall(on( <ide> HttpEntity<Void> methodWithMultiValueRequestParams(@PathVariable String id, <ide> static class ExtendedController extends ControllerWithMethods { <ide> <ide> } <del> <add> <ide> @RequestMapping("/user/{userId}/contacts") <ide> static class UserContactController { <ide>
24
Ruby
Ruby
use cli/args and tweak freeze behaviour
ae63381bd979cccaf0f8f4234c6278a6b3b18634
<ide><path>Library/Homebrew/cli/parser.rb <add>require "cli/args" <ide> require "optparse" <del>require "ostruct" <ide> require "set" <ide> <ide> COMMAND_DESC_WIDTH = 80 <ide> def self.global_options <ide> <ide> def initialize(&block) <ide> @parser = OptionParser.new <del> Homebrew.args = OpenStruct.new <del> # undefine tap to allow --tap argument <del> Homebrew.args.instance_eval { undef tap } <add> @args = Homebrew::CLI::Args.new(argv: ARGV_WITHOUT_MONKEY_PATCHING) <ide> @constraints = [] <ide> @conflicts = [] <ide> @switch_sources = {} <ide> def comma_array(name, description: nil) <ide> description = option_to_description(name) if description.nil? <ide> process_option(name, description) <ide> @parser.on(name, OptionParser::REQUIRED_ARGUMENT, Array, *wrap_option_desc(description)) do |list| <del> Homebrew.args[option_to_name(name)] = list <add> @args[option_to_name(name)] = list <ide> end <ide> end <ide> <ide> def flag(*names, description: nil, required_for: nil, depends_on: nil) <ide> process_option(*names, description) <ide> @parser.on(*names, *wrap_option_desc(description), required) do |option_value| <ide> names.each do |name| <del> Homebrew.args[option_to_name(name)] = option_value <add> @args[option_to_name(name)] = option_value <ide> end <ide> end <ide> <ide> def summary <ide> end <ide> <ide> def parse(cmdline_args = ARGV) <add> raise "Arguments were already parsed!" if @args_parsed <add> <ide> begin <ide> remaining_args = @parser.parse(cmdline_args) <ide> rescue OptionParser::InvalidOption => e <ide> $stderr.puts generate_help_text <ide> raise e <ide> end <ide> check_constraint_violations <del> Homebrew.args[:remaining] = remaining_args <del> Homebrew.args.freeze <add> @args[:remaining] = remaining_args <add> @args_parsed = true <add> Homebrew.args = @args <ide> cmdline_args.freeze <ide> @parser <ide> end <ide> def hide_from_man_page! <ide> def enable_switch(*names, from:) <ide> names.each do |name| <ide> @switch_sources[option_to_name(name)] = from <del> Homebrew.args["#{option_to_name(name)}?"] = true <add> @args["#{option_to_name(name)}?"] = true <ide> end <ide> end <ide> <ide> def disable_switch(*names) <ide> names.each do |name| <del> Homebrew.args.delete_field("#{option_to_name(name)}?") <add> @args.delete_field("#{option_to_name(name)}?") <ide> end <ide> end <ide> <ide> def common_switch(name) <ide> end <ide> <ide> def option_passed?(name) <del> Homebrew.args.respond_to?(name) || Homebrew.args.respond_to?("#{name}?") <add> @args.respond_to?(name) || @args.respond_to?("#{name}?") <ide> end <ide> <ide> def wrap_option_desc(desc) <ide><path>Library/Homebrew/test/cli/parser_spec.rb <ide> <ide> it "raises exception upon Homebrew.args mutation" do <ide> parser.parse(["--switch-a"]) <del> expect { parser.parse(["--switch-b"]) }.to raise_error(RuntimeError, /can't modify frozen OpenStruct/) <add> expect { parser.parse(["--switch-b"]) }.to raise_error(RuntimeError, /Arguments were already parsed!/) <ide> end <ide> end <ide> end
2
Text
Text
add note about purpose of github issues
ca0b7cb5e893618b62f8708080fd3e490bfe3865
<ide><path>CONTRIBUTING.md <ide> # Contributing <ide> <add>**Important:** these GitHub issues are for *bug reports and feature requests only*. Please use [StackOverflow](http://stackoverflow.com/questions/tagged/d3.js) or the [d3-js Google group](https://groups.google.com/d/forum/d3-js) for general help. <add> <ide> If you’re looking for ways to contribute, please [peruse open issues](https://github.com/mbostock/d3/issues?milestone=&page=1&state=open). The icebox is a good place to find ideas that are not currently in development. If you already have an idea, please check past issues to see whether your idea or a similar one was previously discussed. <ide> <del>Before submitting a pull request, consider implementing a live example first, say using [bl.ocks.org](http://bl.ocks.org). Real-world use cases go a long way to demonstrating the usefulness of a proposed feature. The more complex a feature’s implementation, the more usefulness it should provide. Share your demo using the #d3js tag on Twitter or by sending it to the d3-js Google group. <add>Before submitting a pull request, consider implementing a live example first, say using [bl.ocks.org](http://bl.ocks.org). Real-world use cases go a long way to demonstrating the usefulness of a proposed feature. The more complex a feature’s implementation, the more usefulness it should provide. Share your demo using the #d3js tag on Twitter or by sending it to the [d3-js Google group](https://groups.google.com/d/forum/d3-js). <ide> <ide> If your proposed feature does not involve changing core functionality, consider submitting it instead as a [D3 plugin](https://github.com/d3/d3-plugins). New core features should be for general use, whereas plugins are suitable for more specialized use cases. When in doubt, it’s easier to start with a plugin before “graduating” to core. <ide>
1
Go
Go
add tests for issecure
75e3b35bf15dd01363f8b422d6b8a4a62b1054c6
<ide><path>registry/registry_test.go <ide> func TestAddRequiredHeadersToRedirectedRequests(t *testing.T) { <ide> } <ide> } <ide> } <add> <add>func TestIsSecure(t *testing.T) { <add> tests := []struct { <add> addr string <add> insecureRegistries []string <add> expected bool <add> }{ <add> {"example.com", []string{}, true}, <add> {"example.com", []string{"example.com"}, false}, <add> {"localhost", []string{"localhost:5000"}, true}, <add> {"localhost:5000", []string{"localhost:5000"}, false}, <add> {"localhost", []string{"example.com"}, true}, <add> {"127.0.0.1:5000", []string{"127.0.0.1:5000"}, false}, <add> } <add> for _, tt := range tests { <add> if sec := IsSecure(tt.addr, tt.insecureRegistries); sec != tt.expected { <add> t.Errorf("IsSecure failed for %q %v, expected %v got %v", tt.addr, tt.insecureRegistries, tt.expected, sec) <add> } <add> } <add>}
1
Javascript
Javascript
fix stitching function
baab676b00c4999440864738742bc27dfff12d64
<ide><path>src/function.js <ide> var PDFFunction = (function PDFFunctionClosure() { <ide> <ide> constructStiched: function pdfFunctionConstructStiched(fn, dict, xref) { <ide> var domain = dict.get('Domain'); <del> var range = dict.get('Range'); <ide> <ide> if (!domain) <ide> error('No domain'); <ide> var PDFFunction = (function PDFFunctionClosure() { <ide> if (inputSize != 1) <ide> error('Bad domain for stiched function'); <ide> <del> var fnRefs = dict.get('Functions'); <add> var fnRefs = xref.fetchIfRef(dict.get('Functions')); <ide> var fns = []; <ide> for (var i = 0, ii = fnRefs.length; i < ii; ++i) <ide> fns.push(PDFFunction.getIR(xref, xref.fetchIfRef(fnRefs[i]))); <ide> <del> var bounds = dict.get('Bounds'); <del> var encode = dict.get('Encode'); <add> var bounds = xref.fetchIfRef(dict.get('Bounds')); <add> var encode = xref.fetchIfRef(dict.get('Encode')); <ide> <ide> return [CONSTRUCT_STICHED, domain, bounds, encode, fns]; <ide> },
1
Mixed
Python
update example and sign contributor agreement
8c0586fd9c178afdb0f1c955acfc96715905cf53
<ide><path>.github/contributors/askhogan.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 | Patrick Hogan | <add>| Company name (if applicable) | | <add>| Title or role (if applicable) | | <add>| Date | 7/7/2019 | <add>| GitHub username | [email protected] | <add>| Website (optional) | | <ide><path>examples/information_extraction/entity_relations.py <ide> def filter_spans(spans): <ide> <ide> def extract_currency_relations(doc): <ide> # Merge entities and noun chunks into one token <del> seen_tokens = set() <ide> spans = list(doc.ents) + list(doc.noun_chunks) <ide> spans = filter_spans(spans) <ide> with doc.retokenize() as retokenizer:
2
Text
Text
add route to timestamp api in tests
d2e1a385e793c69abcc5c455131f670d21fa4de9
<ide><path>curriculum/challenges/english/05-apis-and-microservices/apis-and-microservices-projects/url-shortener-microservice.md <ide> forumTopicId: 301509 <ide> --- <ide> <ide> ## Description <add> <ide> <section id='description'> <ide> Build a full stack JavaScript app that is functionally similar to this: <a href='https://url-shortener-microservice.freecodecamp.rocks/' target='_blank'>https://url-shortener-microservice.freecodecamp.rocks/</a>. <ide> Working on this project will involve you writing your code on Repl.it on our starter project. After completing this project you can copy your public Repl.it URL (to the homepage of your app) into this screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing. <ide> Start this project on Repl.it using <a href='https://repl.it/github/freeCodeCamp/boilerplate-project-urlshortener' target='_blank'>this link</a> or clone <a href='https://github.com/freeCodeCamp/boilerplate-project-urlshortener/'>this repository</a> on GitHub! If you use Repl.it, remember to save the link to your project somewhere safe! <ide> </section> <ide> <ide> ## Instructions <add> <ide> <section id='instructions'> <ide> <ide> </section> <ide> <ide> ## Tests <add> <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <ide> const res = await fetch(url + '/api/shorturl/new/', { <ide> method: 'POST', <ide> headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, <del> body: `url=https://timestamp-microservice.freecodecamp.rocks/${urlVariable}` <add> body: `url=https://timestamp-microservice.freecodecamp.rocks/api/timestamp/${urlVariable}` <ide> }); <ide> <ide> if (res.ok) { <ide> const { short_url, original_url } = await res.json(); <ide> assert.isNotNull(short_url); <del> assert.match(original_url, new RegExp(`https://timestamp-microservice.freecodecamp.rocks/${urlVariable}`)); <add> assert.match(original_url, new RegExp(`https://timestamp-microservice.freecodecamp.rocks/api/timestamp/${urlVariable}`)); <ide> } else { <ide> throw new Error(`${res.status} ${res.statusText}`); <ide> } <ide> tests: <ide> const postResponse = await fetch(url + '/api/shorturl/new/', { <ide> method: 'POST', <ide> headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, <del> body: `url=https://timestamp-microservice.freecodecamp.rocks/${urlVariable}` <add> body: `url=https://timestamp-microservice.freecodecamp.rocks/api/timestamp/${urlVariable}` <ide> }); <ide> <ide> if (postResponse.ok) { <ide> tests: <ide> const { redirected, url } = getResponse; <ide> <ide> assert.isTrue(redirected); <del> assert.strictEqual(url, `https://timestamp-microservice.freecodecamp.rocks/${urlVariable}`); <add> assert.strictEqual(url, `https://timestamp-microservice.freecodecamp.rocks/api/timestamp/${urlVariable}`); <ide> } else { <ide> throw new Error(`${getResponse.status} ${getResponse.statusText}`); <ide> } <ide> tests: <ide> if (res.ok) { <ide> const { error } = await res.json(); <ide> assert.isNotNull(error); <del> assert.strictEqual(error.toLowerCase(), 'invalid url'); <add> assert.strictEqual(error.toLowerCase(), 'invalid url'); <ide> } else { <ide> throw new Error(`${res.status} ${res.statusText}`); <ide> } <ide> tests: <ide> </section> <ide> <ide> ## Challenge Seed <add> <ide> <section id='challengeSeed'> <ide> <ide> </section> <ide> <ide> ## Solution <add> <ide> <section id='solution'> <ide> <ide> ```js
1
Javascript
Javascript
use isip consistently
b9299884dc1a15c2b08429d3adba1d9bba5b3af4
<ide><path>lib/dns.js <ide> 'use strict'; <ide> <del>const net = require('net'); <ide> const util = require('util'); <ide> <ide> const cares = process.binding('cares_wrap'); <ide> const GetAddrInfoReqWrap = cares.GetAddrInfoReqWrap; <ide> const GetNameInfoReqWrap = cares.GetNameInfoReqWrap; <ide> const QueryReqWrap = cares.QueryReqWrap; <ide> <del>const isIp = net.isIP; <add>const isIP = cares.isIP; <ide> const isLegalPort = internalNet.isLegalPort; <ide> <ide> <ide> exports.lookup = function lookup(hostname, options, callback) { <ide> return {}; <ide> } <ide> <del> var matchedFamily = net.isIP(hostname); <add> var matchedFamily = isIP(hostname); <ide> if (matchedFamily) { <ide> if (all) { <ide> callback(null, [{address: hostname, family: matchedFamily}]); <ide> exports.lookupService = function(host, port, callback) { <ide> if (arguments.length !== 3) <ide> throw new Error('Invalid arguments'); <ide> <del> if (cares.isIP(host) === 0) <add> if (isIP(host) === 0) <ide> throw new TypeError('"host" argument needs to be a valid IP address'); <ide> <ide> if (port == null || !isLegalPort(port)) <ide> exports.setServers = function(servers) { <ide> var newSet = []; <ide> <ide> servers.forEach(function(serv) { <del> var ver = isIp(serv); <add> var ver = isIP(serv); <ide> <ide> if (ver) <ide> return newSet.push([ver, serv]); <ide> exports.setServers = function(servers) { <ide> <ide> // we have an IPv6 in brackets <ide> if (match) { <del> ver = isIp(match[1]); <add> ver = isIP(match[1]); <ide> if (ver) <ide> return newSet.push([ver, match[1]]); <ide> } <ide> <ide> var s = serv.split(/:\d+$/)[0]; <del> ver = isIp(s); <add> ver = isIP(s); <ide> <ide> if (ver) <ide> return newSet.push([ver, s]);
1
Mixed
Javascript
add order option to `.inspect()`
b95b0d87c3582eee82600d076874c9d4afeb4b72
<ide><path>doc/api/util.md <ide> stream.write('With ES6'); <ide> <!-- YAML <ide> added: v0.3.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/22788 <add> description: The `sorted` option is supported now. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/22756 <ide> description: The inspection output is now limited to about 128 MB. Data <ide> changes: <ide> objects the same as arrays. Note that no text will be reduced below 16 <ide> characters, no matter the `breakLength` size. For more information, see the <ide> example below. **Default:** `true`. <add> * `sorted` {boolean|Function} If set to `true` or a function, all properties <add> of an object and Set and Map entries will be sorted in the returned string. <add> If set to `true` the [default sort][] is going to be used. If set to a <add> function, it is used as a [compare function][]. <ide> * Returns: {string} The representation of passed object <ide> <ide> The `util.inspect()` method returns a string representation of `object` that is <ide> console.log(inspect(weakSet, { showHidden: true })); <ide> // WeakSet { { a: 1 }, { b: 2 } } <ide> ``` <ide> <add>The `sorted` option makes sure the output is identical, no matter of the <add>properties insertion order: <add> <add>```js <add>const { inspect } = require('util'); <add>const assert = require('assert'); <add> <add>const o1 = { <add> b: [2, 3, 1], <add> a: '`a` comes before `b`', <add> c: new Set([2, 3, 1]) <add>}; <add>console.log(inspect(o1, { sorted: true })); <add>// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set { 1, 2, 3 } } <add>console.log(inspect(o1, { sorted: (a, b) => a < b })); <add>// { c: Set { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } <add> <add>const o2 = { <add> c: new Set([2, 1, 3]), <add> a: '`a` comes before `b`', <add> b: [2, 3, 1] <add>}; <add>assert.strict.equal( <add> inspect(o1, { sorted: true }), <add> inspect(o2, { sorted: true }) <add>); <add>``` <add> <ide> Please note that `util.inspect()` is a synchronous method that is mainly <ide> intended as a debugging tool. Its maximum output length is limited to <ide> approximately 128 MB and input values that result in output bigger than that <ide> Deprecated predecessor of `console.log`. <ide> [WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/ <ide> [Common System Errors]: errors.html#errors_common_system_errors <ide> [async function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function <add>[compare function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters <ide> [constructor]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor <add>[default sort]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort <ide> [global symbol registry]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for <ide> [list of deprecated APIS]: deprecations.html#deprecations_list_of_deprecated_apis <ide> [semantically incompatible]: https://github.com/nodejs/node/issues/4179 <ide><path>lib/util.js <ide> const inspectDefaultOptions = Object.seal({ <ide> showProxy: false, <ide> maxArrayLength: 100, <ide> breakLength: 60, <del> compact: true <add> compact: true, <add> sorted: false <ide> }); <ide> <ide> const kObjectType = 0; <ide> function debuglog(set) { <ide> function inspect(value, opts) { <ide> // Default options <ide> const ctx = { <add> budget: {}, <add> indentationLvl: 0, <ide> seen: [], <ide> stylize: stylizeNoColor, <ide> showHidden: inspectDefaultOptions.showHidden, <ide> function inspect(value, opts) { <ide> // `maxEntries`. <ide> maxArrayLength: inspectDefaultOptions.maxArrayLength, <ide> breakLength: inspectDefaultOptions.breakLength, <del> indentationLvl: 0, <ide> compact: inspectDefaultOptions.compact, <del> budget: {} <add> sorted: inspectDefaultOptions.sorted <ide> }; <ide> if (arguments.length > 1) { <ide> // Legacy... <ide> function formatRaw(ctx, value, recurseTimes) { <ide> } <ide> ctx.seen.pop(); <ide> <add> if (ctx.sorted) { <add> const comparator = ctx.sorted === true ? undefined : ctx.sorted; <add> if (extrasType === kObjectType) { <add> output = output.sort(comparator); <add> } else if (keys.length > 1) { <add> const sorted = output.slice(output.length - keys.length).sort(comparator); <add> output.splice(output.length - keys.length, keys.length, ...sorted); <add> } <add> } <add> <ide> const res = reduceToSingleString(ctx, output, base, braces); <ide> const budget = ctx.budget[ctx.indentationLvl] || 0; <ide> const newLength = budget + res.length; <ide><path>test/parallel/test-util-inspect.js <ide> assert.strictEqual(inspect(new BigUint64Array([0n])), 'BigUint64Array [ 0n ]'); <ide> ); <ide> rejection.catch(() => {}); <ide> } <add> <add>assert.strictEqual( <add> inspect([1, 3, 2], { sorted: true }), <add> inspect([1, 3, 2]) <add>); <add>assert.strictEqual( <add> inspect({ c: 3, a: 1, b: 2 }, { sorted: true }), <add> '{ a: 1, b: 2, c: 3 }' <add>); <add>assert.strictEqual( <add> inspect( <add> { a200: 4, a100: 1, a102: 3, a101: 2 }, <add> { sorted(a, b) { return a < b; } } <add> ), <add> '{ a200: 4, a102: 3, a101: 2, a100: 1 }' <add>); <add> <add>// Non-indices array properties are sorted as well. <add>{ <add> const arr = [3, 2, 1]; <add> arr.b = 2; <add> arr.c = 3; <add> arr.a = 1; <add> arr[Symbol('b')] = true; <add> arr[Symbol('a')] = false; <add> assert.strictEqual( <add> inspect(arr, { sorted: true }), <add> '[ 3, 2, 1, [Symbol(a)]: false, [Symbol(b)]: true, a: 1, b: 2, c: 3 ]' <add> ); <add>}
3
Ruby
Ruby
add plist test
776a73da7c4b92c73dea3e5065ea4b2d9873f029
<ide><path>Library/Homebrew/test/test_cmd_audit.rb <ide> class Foo < Formula <ide> fa.problems <ide> end <ide> <add> def test_audit_file_strict_plist_placement <add> fa = formula_auditor "foo", <<-EOS.undent, :strict => true <add> class Foo < Formula <add> url "https://example.com/foo-1.0.tgz" <add> <add> test do <add> assert_match "Dogs are terrific", shell_output("./dogs") <add> end <add> <add> def plist <add> end <add> end <add> EOS <add> fa.audit_file <add> assert_equal ["`plist block` (line 8) should be put before `test block` (line 4)"], <add> fa.problems <add> end <add> <ide> def test_audit_file_strict_url_outside_of_stable_block <ide> fa = formula_auditor "foo", <<-EOS.undent, :strict => true <ide> class Foo < Formula
1
Text
Text
apply suggestions from code review
7c6cd247ee8f1eae426ba61c7bfa9ea3b4c91a33
<ide><path>docs/Formula-Cookbook.md <ide> Try to summarise from the [`homepage`](https://rubydoc.brew.sh/Formula#homepage% <ide> <ide> ### Fill in the `license` <ide> <del>**We don’t accept formulae without a [`license`](https://rubydoc.brew.sh/Formula#license-class_method)!** <add>**We don’t accept new formulae into Homebrew/homebrew-core without a [`license`](https://rubydoc.brew.sh/Formula#license-class_method)!** <ide> <del>Find the license identifier from the [SPDX License List](https://spdx.org/licenses/). We only accept licenses from this list. <add>Find the license identifier from the [SPDX License List](https://spdx.org/licenses/). We only accept licenses from this list that are a [Debian Free Software Guidelines license](https://wiki.debian.org/DFSGLicenses). <ide> <del>If the formula gives the user the option to choose which license to use, you should list them all in an array: <add>If the software is available under multiple licenses, you should list them all in an array: <ide> <ide> ```ruby <ide> license ["MIT", "GPL-2.0"]
1
Javascript
Javascript
remove an export i missed
320664a35939aeafa71c25b12925e9b687bbdca9
<ide><path>src/path-watcher.js <ide> const ACTION_MAP = new Map([ <ide> ]) <ide> <ide> // Private: Possible states of a {NativeWatcher}. <del>export const WATCHER_STATE = { <add>const WATCHER_STATE = { <ide> STOPPED: Symbol('stopped'), <ide> STARTING: Symbol('starting'), <ide> RUNNING: Symbol('running'),
1
Javascript
Javascript
use performancenow() instead of performance.now()
103ca4b406a3c008cca99a17b33bdf83344e7ffe
<ide><path>src/isomorphic/ReactDebugTool.js <ide> var ReactDebugTool = { <ide> currentFlushMeasurements.push({ <ide> timerType, <ide> instanceID: debugID, <del> duration: performance.now() - currentTimerStartTime, <add> duration: performanceNow() - currentTimerStartTime, <ide> }); <ide> currentTimerStartTime = null; <ide> currentTimerDebugID = null;
1
PHP
PHP
add test case and add case _jsonoption = false
875035b1f8cb09d8f3d048e3e02e747bfa9eb990
<ide><path>Cake/Test/TestCase/View/JsonViewTest.php <ide> public static function renderWithoutViewProvider() { <ide> array( <ide> array('data' => array('user' => 'fake', 'list' => array('item1', 'item2'))), <ide> 'data', <add> null, <ide> json_encode(array('user' => 'fake', 'list' => array('item1', 'item2'))) <ide> ), <ide> <ide> // Test render with a string with an invalid key in _serialize. <ide> array( <ide> array('data' => array('user' => 'fake', 'list' => array('item1', 'item2'))), <ide> 'no_key', <add> null, <ide> json_encode(null) <ide> ), <ide> <ide> // Test render with a valid array in _serialize. <ide> array( <ide> array('no' => 'nope', 'user' => 'fake', 'list' => array('item1', 'item2')), <ide> array('no', 'user'), <add> null, <ide> json_encode(array('no' => 'nope', 'user' => 'fake')) <ide> ), <ide> <ide> // Test render with an empty array in _serialize. <ide> array( <ide> array('no' => 'nope', 'user' => 'fake', 'list' => array('item1', 'item2')), <ide> array(), <add> null, <ide> json_encode(null) <ide> ), <ide> <ide> // Test render with a valid array with an invalid key in _serialize. <ide> array( <ide> array('no' => 'nope', 'user' => 'fake', 'list' => array('item1', 'item2')), <ide> array('no', 'user', 'no_key'), <add> null, <ide> json_encode(array('no' => 'nope', 'user' => 'fake')) <ide> ), <ide> <ide> // Test render with a valid array with only an invalid key in _serialize. <ide> array( <ide> array('no' => 'nope', 'user' => 'fake', 'list' => array('item1', 'item2')), <ide> array('no_key'), <add> null, <ide> json_encode(null) <ide> ), <ide> <ide> // Test render with Null in _serialize (unset). <ide> array( <ide> array('no' => 'nope', 'user' => 'fake', 'list' => array('item1', 'item2')), <ide> null, <add> null, <ide> null <ide> ), <ide> <ide> // Test render with False in _serialize. <ide> array( <ide> array('no' => 'nope', 'user' => 'fake', 'list' => array('item1', 'item2')), <ide> false, <add> null, <ide> json_encode(null) <ide> ), <ide> <ide> // Test render with True in _serialize. <ide> array( <ide> array('no' => 'nope', 'user' => 'fake', 'list' => array('item1', 'item2')), <ide> true, <add> null, <ide> json_encode(null) <ide> ), <ide> <ide> // Test render with empty string in _serialize. <ide> array( <ide> array('no' => 'nope', 'user' => 'fake', 'list' => array('item1', 'item2')), <ide> '', <add> null, <ide> json_encode(null) <ide> ), <ide> <ide> // Test render with a valid array in _serialize and alias. <ide> array( <ide> array('original_name' => 'my epic name', 'user' => 'fake', 'list' => array('item1', 'item2')), <ide> array('new_name' => 'original_name', 'user'), <add> null, <ide> json_encode(array('new_name' => 'my epic name', 'user' => 'fake')) <ide> ), <ide> <ide> // Test render with an a valid array in _serialize and alias of a null value. <ide> array( <ide> array('null' => null), <ide> array('null'), <add> null, <ide> json_encode(array('null' => null)) <ide> ), <ide> <ide> // Test render with a False value to be serialized. <ide> array( <ide> array('false' => false), <ide> 'false', <add> null, <ide> json_encode(false) <ide> ), <ide> <ide> // Test render with a True value to be serialized. <ide> array( <ide> array('true' => true), <ide> 'true', <add> null, <ide> json_encode(true) <ide> ), <ide> <ide> // Test render with an empty string value to be serialized. <ide> array( <ide> array('empty' => ''), <ide> 'empty', <add> null, <ide> json_encode('') <ide> ), <ide> <ide> // Test render with a zero value to be serialized. <ide> array( <ide> array('zero' => 0), <ide> 'zero', <add> null, <ide> json_encode(0) <ide> ), <add> <add> // Test render with encode <, >, ', &, and " for RFC4627-compliant to be serialized. <add> array( <add> array('rfc4627_escape' => '<tag> \'quote\' "double-quote" &'), <add> 'rfc4627_escape', <add> null, <add> json_encode('<tag> \'quote\' "double-quote" &', JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) <add> ), <add> <add> // Test render with _jsonOptions null to be serialized. <add> array( <add> array('noescape' => '<tag> \'quote\' "double-quote" &'), <add> 'noescape', <add> false, <add> json_encode('<tag> \'quote\' "double-quote" &') <add> ), <add> <add> // Test render with setting _jsonOptions to be serialized. <add> array( <add> array('rfc4627_escape' => '<tag> \'quote\' "double-quote" &'), <add> 'rfc4627_escape', <add> JSON_HEX_TAG | JSON_HEX_APOS, <add> json_encode('<tag> \'quote\' "double-quote" &', JSON_HEX_TAG | JSON_HEX_APOS) <add> ), <ide> ); <ide> } <ide> <ide> public static function renderWithoutViewProvider() { <ide> * @dataProvider renderWithoutViewProvider <ide> * @return void <ide> */ <del> public function testRenderWithoutView($data, $serialize, $expected) { <add> public function testRenderWithoutView($data, $serialize, $jsonOptions, $expected) { <ide> $Request = new Request(); <ide> $Response = new Response(); <ide> $Controller = new Controller($Request, $Response); <ide> <ide> $Controller->set($data); <ide> $Controller->set('_serialize', $serialize); <add> $Controller->set('_jsonOptions', $jsonOptions); <ide> $View = new JsonView($Controller); <ide> $output = $View->render(false); <ide> <ide><path>Cake/View/JsonView.php <ide> protected function _serialize($serialize) { <ide> <ide> $jsonOptions = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT; <ide> if (isset($this->viewVars['_jsonOptions'])) { <del> $jsonOptions = $this->viewVars['_jsonOptions']; <add> if ($this->viewVars['_jsonOptions'] === false) { <add> $jsonOptions = 0; <add> } else { <add> $jsonOptions = $this->viewVars['_jsonOptions']; <add> } <ide> } <ide> <ide> if (Configure::read('debug')) {
2
Javascript
Javascript
fix a typo
7e760ac7d3ecb21a5f69b488235ad6558b175c1c
<ide><path>src/Dispatcher.js <ide> import { Component, PropTypes } from 'react'; <ide> <del>export default function dispatch(store, atom, action) { <add>function dispatch(store, atom, action) { <ide> return store(atom, action); <ide> } <ide>
1
Javascript
Javascript
fix race in test-net-server-pause-on-connect
e22cc6c2eb728c08ec284b6c306d969d8fb8fbce
<ide><path>test/parallel/test-net-server-pause-on-connect.js <ide> 'use strict'; <del>var common = require('../common'); <del>var assert = require('assert'); <del>var net = require('net'); <del>var msg = 'test'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const net = require('net'); <add>const msg = 'test'; <ide> var stopped = true; <del>var server1 = net.createServer({pauseOnConnect: true}, function(socket) { <add>var server1Sock; <add> <add> <add>const server1ConnHandler = function(socket) { <ide> socket.on('data', function(data) { <ide> if (stopped) { <del> assert(false, 'data event should not have happened yet'); <add> common.fail('data event should not have happened yet'); <ide> } <ide> <ide> assert.equal(data.toString(), msg, 'invalid data received'); <ide> socket.end(); <ide> server1.close(); <ide> }); <ide> <del> setTimeout(function() { <del> // After 50(ish) ms, the other socket should have already read the data. <del> assert.equal(read, true); <del> assert.equal(socket.bytesRead, 0, 'no data should have been read yet'); <add> server1Sock = socket; <add>}; <ide> <del> socket.resume(); <del> stopped = false; <del> }, common.platformTimeout(50)); <del>}); <add>const server1 = net.createServer({pauseOnConnect: true}, server1ConnHandler); <ide> <del>// read is a timing check, as server1's timer should fire after server2's <del>// connection receives the data. Note that this could be race-y. <del>var read = false; <del>var server2 = net.createServer({pauseOnConnect: false}, function(socket) { <add>const server2ConnHandler = function(socket) { <ide> socket.on('data', function(data) { <del> read = true; <del> <ide> assert.equal(data.toString(), msg, 'invalid data received'); <ide> socket.end(); <ide> server2.close(); <add> <add> assert.equal(server1Sock.bytesRead, 0, 'no data should have been read yet'); <add> server1Sock.resume(); <add> stopped = false; <ide> }); <del>}); <add>}; <ide> <del>server1.listen(common.PORT, function() { <del> net.createConnection({port: common.PORT}).write(msg); <del>}); <add>const server2 = net.createServer({pauseOnConnect: false}, server2ConnHandler); <ide> <del>server2.listen(common.PORT + 1, function() { <del> net.createConnection({port: common.PORT + 1}).write(msg); <add>server1.listen(common.PORT, function() { <add> const clientHandler = common.mustCall(function() { <add> server2.listen(common.PORT + 1, function() { <add> net.createConnection({port: common.PORT + 1}).write(msg); <add> }); <add> }); <add> net.createConnection({port: common.PORT}).write(msg, clientHandler); <ide> }); <ide> <ide> process.on('exit', function() { <ide> assert.equal(stopped, false); <del> assert.equal(read, true); <ide> });
1
PHP
PHP
fix variable casing
063e45ebf0e40a571a26242444c3b358115120a6
<ide><path>src/Illuminate/Foundation/Application.php <ide> class Application extends Container implements HttpKernelInterface, ResponsePrep <ide> * <ide> * @var array <ide> */ <del> protected $finishCallBacks = array(); <add> protected $finishCallbacks = array(); <ide> <ide> /** <ide> * The array of shutdown callbacks.
1
Text
Text
fix typo and cleanup docs for installation
9746021f1a36222111dff1ef95904ba39cc81db5
<ide><path>docs/installation/mac.md <ide> You install Docker using Docker Toolbox. Docker Toolbox includes the following D <ide> * Docker Compose for running the `docker-compose` binary <ide> * Kitematic, the Docker GUI <ide> * a shell preconfigured for a Docker command-line environment <del>* Oracle VM VirtualBox <add>* Oracle VM VirtualBox <ide> <ide> Because the Docker daemon uses Linux-specific kernel features, you can't run <ide> Docker natively in OS X. Instead, you must use `docker-machine` to create and <ide> practice, work through the exercises on this page. <ide> ### Installation <ide> <ide> If you have VirtualBox running, you must shut it down before running the <del>installer. <add>installer. <ide> <ide> 1. Go to the [Docker Toolbox](https://www.docker.com/toolbox) page. <ide> <ide> installer. <ide> and choosing "Open" from the pop-up menu. <ide> <ide> The installer launches the "Install Docker Toolbox" dialog. <del> <add> <ide> ![Install Docker Toolbox](/installation/images/mac-welcome-page.png) <ide> <ide> 4. Press "Continue" to install the toolbox. <ide> <ide> The installer presents you with options to customize the standard <del> installation. <del> <add> installation. <add> <ide> ![Standard install](/installation/images/mac-page-two.png) <del> <add> <ide> By default, the standard Docker Toolbox installation: <del> <del> * installs binaries for the Docker tools in `/usr/local/bin` <del> * makes these binaries available to all users <add> <add> * installs binaries for the Docker tools in `/usr/local/bin` <add> * makes these binaries available to all users <ide> * installs VirtualBox; or updates any existing installation <del> <add> <ide> Change these defaults by pressing "Customize" or "Change <del> Install Location." <add> Install Location." <ide> <ide> 5. Press "Install" to perform the standard installation. <ide> <ide> The system prompts you for your password. <del> <add> <ide> ![Password prompt](/installation/images/mac-password-prompt.png) <del> <add> <ide> 6. Provide your password to continue with the installation. <ide> <ide> When it completes, the installer provides you with some information you can <ide> use to complete some common tasks. <del> <add> <ide> ![All finished](/installation/images/mac-page-finished.png) <del> <add> <ide> 7. Press "Close" to exit. <ide> <ide> <ide> ## Running a Docker Container <ide> <ide> To run a Docker container, you: <ide> <del>* create a new (or start an existing) Docker virtual machine <add>* create a new (or start an existing) Docker virtual machine <ide> * switch your environment to your new VM <ide> * use the `docker` client to create, load, and manage containers <ide> <ide> There are two ways to use the installed tools, from the Docker Quickstart Termin <ide> * points the terminal environment to this VM <ide> <ide> Once the launch completes, the Docker Quickstart Terminal reports: <del> <add> <ide> ![All finished](/installation/images/mac-success.png) <del> <del> Now, you can run `docker` commands. <add> <add> Now, you can run `docker` commands. <ide> <ide> 3. Verify your setup succeeded by running the `hello-world` container. <ide> <ide> different shell such as C Shell but the commands are the same. <ide> To see how to connect Docker to this machine, run: docker-machine env default <ide> <ide> This creates a new `default` VM in VirtualBox. <del> <add> <ide> ![default](/installation/images/default.png) <ide> <ide> The command also creates a machine configuration in the <ide> `~/.docker/machine/machines/default` directory. You only need to run the <ide> `create` command once. Then, you can use `docker-machine` to start, stop, <ide> query, and otherwise manage the VM from the command line. <del> <add> <ide> 2. List your available machines. <ide> <ide> $ docker-machine ls <ide> NAME ACTIVE DRIVER STATE URL SWARM <del> default * virtualbox Running tcp://192.168.99.101:2376 <del> <add> default * virtualbox Running tcp://192.168.99.101:2376 <add> <ide> If you have previously installed the deprecated Boot2Docker application or <ide> run the Docker Quickstart Terminal, you may have a `dev` VM as well. When you <ide> created `default` VM, the `docker-machine` command provided instructions <ide> different shell such as C Shell but the commands are the same. <ide> export DOCKER_HOST="tcp://192.168.99.101:2376" <ide> export DOCKER_CERT_PATH="/Users/mary/.docker/machine/machines/default" <ide> export DOCKER_MACHINE_NAME="default" <del> # Run this command to configure your shell: <add> # Run this command to configure your shell: <ide> # eval "$(docker-machine env default)" <del> <add> <ide> 4. Connect your shell to the `default` machine. <ide> <ide> $ eval "$(docker-machine env default)" <ide> this older VM, you can migrate it. <ide> 2. Type the following command. <ide> <ide> $ docker-machine create -d virtualbox --virtualbox-import-boot2docker-vm boot2docker-vm docker-vm <del> <del>3. Use the `docker-machine` command to interact with the migrated VM. <del> <add> <add>3. Use the `docker-machine` command to interact with the migrated VM. <add> <ide> The `docker-machine` subcommands are slightly different than the `boot2docker` <ide> subcommands. The table below lists the equivalent `docker-machine` subcommand <ide> and what it does: <ide> To verify this, run the following commands: <ide> <ide> $ docker-machine ls <ide> NAME ACTIVE DRIVER STATE URL SWARM <del> default * virtualbox Running tcp://192.168.99.100:2376 <add> default * virtualbox Running tcp://192.168.99.100:2376 <ide> <ide> The `ACTIVE` machine, in this case `default`, is the one your environment is pointing to. <ide> <ide> The `ACTIVE` machine, in this case `default`, is the one your environment is poi <ide> 2. Display your running container with `docker ps` command <ide> <ide> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES <del> 5fb65ff765e9 nginx:latest "nginx -g 'daemon of 3 minutes ago Up 3 minutes 0.0.0.0:49156->443/tcp, 0.0.0.0:49157->80/tcp web <add> 5fb65ff765e9 nginx:latest "nginx -g 'daemon of 3 minutes ago Up 3 minutes 0.0.0.0:49156->443/tcp, 0.0.0.0:49157->80/tcp web <ide> <ide> At this point, you can see `nginx` is running as a daemon. <ide> <ide> To upgrade Docker Toolbox, download an re-run [the Docker Toolbox <ide> installer](https://docker.com/toolbox/). <ide> <ide> <del>## Uninstall Docker Toolbox <add>## Uninstall Docker Toolbox <ide> <ide> To uninstall, do the following: <ide> <ide> 1. List your machines. <ide> <ide> $ docker-machine ls <ide> NAME ACTIVE DRIVER STATE URL SWARM <del> dev * virtualbox Running tcp://192.168.99.100:2376 <del> my-docker-machine virtualbox Stopped <del> default virtualbox Stopped <add> dev * virtualbox Running tcp://192.168.99.100:2376 <add> my-docker-machine virtualbox Stopped <add> default virtualbox Stopped <ide> <ide> 2. Remove each machine. <ide> <ide> $ docker-machine rm dev <ide> Successfully removed dev <del> <add> <ide> Removing a machine deletes its VM from VirtualBox and from the <ide> `~/.docker/machine/machines` directory. <ide> <ide> To uninstall, do the following: <ide> 4. Remove the `docker`, `docker-compose`, and `docker-machine` commands from the `/usr/local/bin` folder. <ide> <ide> $ rm /usr/local/bin/docker <del> <add> <ide> 5. Delete the `~/.docker` folder from your system. <ide> <ide> <del>## Learning more <add>## Learning more <ide> <ide> Use `docker-machine help` to list the full command line reference for Docker Machine. For more <ide> information about using SSH or SCP to access a VM, see [the Docker Machine <ide> documentation](https://docs.docker.com/machine/). <ide> <ide> You can continue with the [Docker User Guide](/userguide). If you are <del>interested in using the Kitematic GUI, see the [Kitermatic user <add>interested in using the Kitematic GUI, see the [Kitematic user <ide> guide](/kitematic/userguide/). <ide><path>docs/installation/windows.md <ide> You install Docker using Docker Toolbox. Docker Toolbox includes the following D <ide> * Docker Engine for running the `docker` binary <ide> * Kitematic, the Docker GUI <ide> * a shell preconfigured for a Docker command-line environment <del>* Oracle VM VirtualBox <add>* Oracle VM VirtualBox <ide> <ide> Because the Docker daemon uses Linux-specific kernel features, you can't run <ide> Docker natively in Windows. Instead, you must use `docker-machine` to create and attach to a Docker VM on your machine. This VM hosts Docker for you on your Windows system. <ide> Your machine must be running Windows 7, 8/8.1 or newer to run Docker. Windows 10 <ide> 1. Right click the Windows Start Menu and choose **System**. <ide> <ide> ![Which version](/installation/images/win_ver.png) <del> <add> <ide> If you are using an unsupported version of Windows, you should consider <ide> upgrading your operating system in order to try out Docker. <ide> <del>2. Make sure your CPU supports [virtualization technology](https://en.wikipedia.org/wiki/X86_virtualization) <add>2. Make sure your CPU supports [virtualization technology](https://en.wikipedia.org/wiki/X86_virtualization) <ide> and virtualization support is enabled in BIOS and recognized by Windows. <ide> <ide> #### For Windows 8 or 8.1 <ide> <del> Choose **Start > Task Manager** and navigate to the **Performance** tab. <add> Choose **Start > Task Manager** and navigate to the **Performance** tab. <ide> Under **CPU** you should see the following: <ide> <ide> ![Release page](/installation/images/virtualization.png) <del> <add> <ide> If virtualization is not enabled on your system, follow the manufacturer's instructions for enabling it. <del> <add> <ide> #### For Windows 7 <del> <add> <ide> Run the <a <ide> href="http://www.microsoft.com/en-us/download/details.aspx?id=592" <ide> target="_blank"> Microsoft® Hardware-Assisted Virtualization Detection <ide> Docker container using standard localhost addressing such as `localhost:8000` or <ide> <ide> In an Windows installation, the `docker` daemon is running inside a Linux virtual <ide> machine. You use the Windows Docker client to talk to the Docker host VM. Your <del>Docker containers run inside this host. <add>Docker containers run inside this host. <ide> <ide> ![Windows Architecture Diagram](/installation/images/win_docker_host.svg) <ide> <ide> practice, work through the exercises on this page. <ide> ### Installation <ide> <ide> If you have VirtualBox running, you must shut it down before running the <del>installer. <add>installer. <ide> <ide> 1. Go to the [Docker Toolbox](https://www.docker.com/toolbox) page. <ide> <ide> installer. <ide> 3. Install Docker Toolbox by double-clicking the installer. <ide> <ide> The installer launches the "Setup - Docker Toolbox" dialog. <del> <add> <ide> ![Install Docker Toolbox](/installation/images/win-welcome.png) <ide> <ide> 4. Press "Next" to install the toolbox. <ide> <ide> The installer presents you with options to customize the standard <ide> installation. By default, the standard Docker Toolbox installation: <del> <del> * installs executables for the Docker tools in `C:\Program Files\Docker Toolbox` <add> <add> * installs executables for the Docker tools in `C:\Program Files\Docker Toolbox` <ide> * install VirtualBox; or updates any existing installation <ide> * adds a Docker Inc. folder to your program shortcuts <ide> * updates your `PATH` environment variable <ide> installer. <ide> 5. Press "Next" until you reach the "Ready to Install" page. <ide> <ide> The system prompts you for your password. <del> <add> <ide> ![Install](/installation/images/win-page-6.png) <del> <add> <ide> 6. Press "Install" to continue with the installation. <ide> <ide> When it completes, the installer provides you with some information you can <ide> use to complete some common tasks. <del> <add> <ide> ![All finished](/installation/images/windows-finish.png) <del> <add> <ide> 7. Press "Finish" to exit. <ide> <ide> ## Running a Docker Container <ide> <ide> To run a Docker container, you: <ide> <del>* create a new (or start an existing) Docker virtual machine <add>* create a new (or start an existing) Docker virtual machine <ide> * switch your environment to your new VM <ide> * use the `docker` client to create, load, and manage containers <ide> <ide> There are several ways to use the installed tools, from the Docker Quickstart Te <ide> * creates a `default` VM if it doesn't exist, and starts the VM after <ide> * points the terminal environment to this VM <ide> <del> Once the launch completes, you can run `docker` commands. <add> Once the launch completes, you can run `docker` commands. <ide> <ide> 3. Verify your setup succeeded by running the `hello-world` container. <ide> <ide> There are several ways to use the installed tools, from the Docker Quickstart Te <ide> 1. Launch a Windows Command Prompt (cmd.exe). <ide> <ide> The `docker-machine` command requires `ssh.exe` in your `PATH` environment <del> variable. This `.exe` is in the MsysGit `bin` folder. <add> variable. This `.exe` is in the MsysGit `bin` folder. <ide> <ide> 2. Add this to the `%PATH%` environment variable by running: <ide> <ide> set PATH=%PATH%;"c:\Program Files (x86)\Git\bin" <del> <add> <ide> 3. Create a new Docker VM. <ide> <ide> docker-machine create --driver virtualbox my-default <ide> There are several ways to use the installed tools, from the Docker Quickstart Te <ide> `C:\USERS\USERNAME\.docker\machine\machines` directory. You only need to run the `create` <ide> command once. Then, you can use `docker-machine` to start, stop, query, and <ide> otherwise manage the VM from the command line. <del> <add> <ide> 4. List your available machines. <ide> <ide> C:\Users\mary> docker-machine ls <ide> NAME ACTIVE DRIVER STATE URL SWARM <del> my-default * virtualbox Running tcp://192.168.99.101:2376 <del> <add> my-default * virtualbox Running tcp://192.168.99.101:2376 <add> <ide> If you have previously installed the deprecated Boot2Docker application or <del> run the Docker Quickstart Terminal, you may have a `dev` VM as well. <add> run the Docker Quickstart Terminal, you may have a `dev` VM as well. <ide> <ide> 5. Get the environment commands for your new VM. <ide> <ide> C:\Users\mary> docker-machine env --shell cmd my-default <del> <add> <ide> 6. Connect your shell to the `my-default` machine. <ide> <ide> C:\Users\mary> eval "$(docker-machine env my-default)" <ide> There are several ways to use the installed tools, from the Docker Quickstart Te <ide> 2. Add `ssh.exe` to your PATH: <ide> <ide> PS C:\Users\mary> $Env:Path = "${Env:Path};c:\Program Files (x86)\Git\bin" <del> <add> <ide> 3. Create a new Docker VM. <ide> <ide> PS C:\Users\mary> docker-machine create --driver virtualbox my-default <del> <add> <ide> 4. List your available machines. <ide> <ide> C:\Users\mary> docker-machine ls <ide> NAME ACTIVE DRIVER STATE URL SWARM <del> my-default * virtualbox Running tcp://192.168.99.101:2376 <del> <add> my-default * virtualbox Running tcp://192.168.99.101:2376 <add> <ide> 5. Get the environment commands for your new VM. <ide> <ide> C:\Users\mary> docker-machine env --shell powershell my-default <del> <add> <ide> 6. Connect your shell to the `my-default` machine. <ide> <ide> C:\Users\mary> eval "$(docker-machine env my-default)" <ide> this older VM, you can migrate it. <ide> 2. Type the following command. <ide> <ide> $ docker-machine create -d virtualbox --virtualbox-import-boot2docker-vm boot2docker-vm docker-vm <del> <del>3. Use the `docker-machine` command to interact with the migrated VM. <del> <add> <add>3. Use the `docker-machine` command to interact with the migrated VM. <add> <ide> The `docker-machine` subcommands are slightly different than the `boot2docker` <ide> subcommands. The table below lists the equivalent `docker-machine` subcommand <ide> and what it does: <ide> uses. You can do this with <ide> [puttygen](http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html): <ide> <ide> 1. Open `puttygen.exe` and load ("File"->"Load" menu) the private key from <del> <add> <ide> %USERPROFILE%\.docker\machine\machines\<name_of_your_machine> <ide> <ide> 2. Click "Save Private Key". <ide> delete that file yourself. <ide> ## Learn more <ide> <ide> You can continue with the [Docker User Guide](/userguide). If you are <del>interested in using the Kitematic GUI, see the [Kitermatic user <add>interested in using the Kitematic GUI, see the [Kitematic user <ide> guide](/kitematic/userguide/).
2
PHP
PHP
apply fixes from styleci
15db4cb8da2c4ab594c86fec7c6bd0e689a22e8e
<ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php <ide> use Illuminate\Queue\Console\FailedTableCommand; <ide> use Illuminate\Foundation\Console\AppNameCommand; <ide> use Illuminate\Foundation\Console\JobMakeCommand; <add>use Illuminate\Database\Console\Seeds\SeedCommand; <ide> use Illuminate\Foundation\Console\MailMakeCommand; <ide> use Illuminate\Foundation\Console\OptimizeCommand; <ide> use Illuminate\Foundation\Console\TestMakeCommand; <del>use Illuminate\Database\Console\Seeds\SeedCommand; <ide> use Illuminate\Foundation\Console\EventMakeCommand; <ide> use Illuminate\Foundation\Console\ModelMakeCommand; <ide> use Illuminate\Foundation\Console\RouteListCommand; <ide> protected function registerCacheForgetCommand() <ide> }); <ide> } <ide> <del> <ide> /** <ide> * Register the command. <ide> *
1
Javascript
Javascript
update revision constant
d9f39de84a1581a619554cfc57cf625ea6c9201b
<ide><path>src/constants.js <del>export const REVISION = '129'; <add>export const REVISION = '130dev'; <ide> export const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; <ide> export const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; <ide> export const CullFaceNone = 0;
1
Text
Text
add helpful links
22f64fbce6f46c8a39006fcb35b20aad978e0611
<ide><path>guide/english/mathematics/pythagorean-theorem/index.md <ide> And then, we will square root both sides to get the value of b: <ide> b = &radic;(c<sup>2</sup> - a<sup>2</sup>) <ide> <ide> #### More Information: <del><!-- Please add any articles you think might be helpful to read before writing the article --> <add> <add>- <a href = "https://www.khanacademy.org/math/basic-geo/basic-geometry-pythagorean-theorem">Khan Academy Pythagorean Theorem</a> <add>- <a href = "https://en.wikipedia.org/wiki/Pythagorean_theorem">Wikipedia Pythagorean Theorem</a>
1
Text
Text
describe node_options interop w/cmd line opts
5eaef7b9151037c727806a8a40c8f6d5bdb26386
<ide><path>doc/api/cli.md <ide> When set to `1`, process warnings are silenced. <ide> added: v8.0.0 <ide> --> <ide> <del>A space-separated list of command line options. `options...` are interpreted as <del>if they had been specified on the command line before the actual command line <del>(so they can be overridden). Node.js will exit with an error if an option <del>that is not allowed in the environment is used, such as `-p` or a script file. <add>A space-separated list of command line options. `options...` are interpreted <add>before command line options, so command line options will override or <add>compound after anything in `options...`. Node.js will exit with an error if <add>an option that is not allowed in the environment is used, such as `-p` or a <add>script file. <ide> <del>In case an option value happens to contain a space (for example a path listed in <del>`--require`), it must be escaped using double quotes. For example: <add>In case an option value happens to contain a space (for example a path listed <add>in `--require`), it must be escaped using double quotes. For example: <ide> <ide> ```bash <del>--require "./my path/file.js" <add>NODE_OPTIONS='--require "./my path/file.js"' <add>``` <add> <add>A singleton flag passed as a command line option will override the same flag <add>passed into `NODE_OPTIONS`: <add> <add>```bash <add># The inspector will be available on port 5555 <add>NODE_OPTIONS='--inspect=localhost:4444' node --inspect=localhost:5555 <add>``` <add> <add>A flag that can be passed multiple times will be treated as if its <add>`NODE_OPTIONS` instances were passed first, and then its command line <add>instances afterwards: <add> <add>```bash <add>NODE_OPTIONS='--require "./a.js"' node --require "./b.js" <add># is equivalent to: <add>node --require "./a.js" --require "./b.js" <ide> ``` <ide> <ide> Node.js options that are allowed are:
1
PHP
PHP
apply fixes from styleci
be94e7bf403c044446f060b940c8d641d28a9a1f
<ide><path>tests/Cache/CacheRateLimiterTest.php <ide> public function testAttemptsCallbackReturnsTrue() <ide> <ide> $rateLimiter = new RateLimiter($cache); <ide> <del> $this->assertTrue($rateLimiter->attempt('key', 1, function() use (&$executed) { <add> $this->assertTrue($rateLimiter->attempt('key', 1, function () use (&$executed) { <ide> $executed = true; <ide> }, 1)); <ide> $this->assertTrue($executed); <ide> public function testAttemptsCallbackReturnsCallbackReturn() <ide> <ide> $rateLimiter = new RateLimiter($cache); <ide> <del> $this->assertEquals('foo', $rateLimiter->attempt('key', 1, function() { <add> $this->assertEquals('foo', $rateLimiter->attempt('key', 1, function () { <ide> return 'foo'; <ide> }, 1)); <ide> } <ide> public function testAttemptsCallbackReturnsFalse() <ide> <ide> $rateLimiter = new RateLimiter($cache); <ide> <del> $this->assertFalse($rateLimiter->attempt('key', 1, function() use (&$executed) { <add> $this->assertFalse($rateLimiter->attempt('key', 1, function () use (&$executed) { <ide> $executed = true; <ide> }, 1)); <ide> $this->assertFalse($executed);
1
Ruby
Ruby
make the tapping already there step actually work
21bddc7972c4c7936bc02ee45378600f180bdbaa
<ide><path>Library/Homebrew/cmd/tap.rb <ide> def link_tap_formula formulae <ide> to = HOMEBREW_LIBRARY.join("Formula/#{formula.basename}") <ide> <ide> # Unexpected, but possible, lets proceed as if nothing happened <del> formula.delete if to.symlink? and to.realpath == from <add> to.delete if to.symlink? and to.realpath == from <ide> <ide> # using the system ln is the only way to get relative symlinks <ide> system "ln -s ../Taps/#{formula} 2>/dev/null"
1
Ruby
Ruby
remove redundant `to_s` in interpolation
797a7a7c833f456987335d02696cc8531df992d3
<ide><path>activejob/lib/active_job/logging.rb <ide> def perform_start(event) <ide> def perform(event) <ide> info do <ide> job = event.payload[:job] <del> "Performed #{job.class.name} from #{queue_name(event)} in #{event.duration.round(2).to_s}ms" <add> "Performed #{job.class.name} from #{queue_name(event)} in #{event.duration.round(2)}ms" <ide> end <ide> end <ide>
1
Ruby
Ruby
fix rubocop warnings
a0c29eb1af9abe25a29616bdcdd6aa19348e7eb3
<ide><path>Library/Homebrew/cmd/tap-info.rb <ide> def print_tap_info(taps) <ide> puts info <ide> else <ide> taps.each_with_index do |tap, i| <del> puts unless i == 0 <add> puts unless i.zero? <ide> info = "#{tap}: " <ide> if tap.installed? <ide> info += tap.pinned? ? "pinned" : "unpinned" <ide> def print_tap_info(taps) <ide> if (command_count = tap.command_files.size) > 0 <ide> info += ", #{command_count} command#{plural(command_count)}" <ide> end <del> info += ", no formulae/commands" if formula_count + command_count == 0 <add> info += ", no formulae/commands" if (formula_count + command_count).zero? <ide> info += "\n#{tap.path} (#{tap.path.abv})" <ide> info += "\nFrom: #{tap.remote.nil? ? "N/A" : tap.remote}" <ide> else
1
Ruby
Ruby
require hardware where it is needed
41af4592059530e1df14fcb8b846f6b286847ae2
<ide><path>Library/Homebrew/extend/ENV.rb <add>require 'hardware' <add> <ide> module HomebrewEnvExtension <ide> # -w: keep signal to noise high <ide> SAFE_CFLAGS_FLAGS = "-w -pipe" <ide><path>Library/Homebrew/macos.rb <ide> require 'os/mac/version' <add>require 'hardware' <ide> <ide> module MacOS extend self <ide> <ide><path>Library/Homebrew/test/test_ENV.rb <ide> require 'testing_env' <del>require 'hardware' <ide> <ide> class EnvironmentTests < Test::Unit::TestCase <ide> def test_ENV_options <ide><path>Library/Homebrew/test/test_download_strategies.rb <ide> require 'testing_env' <ide> require 'download_strategy' <ide> require 'bottles' # XXX: hoist these regexps into constants in Pathname? <del>require 'hardware' # XXX: wat. fix this require mess! <ide> <ide> class SoftwareSpecDouble <ide> attr_reader :url, :specs <ide><path>Library/Homebrew/test/test_language_module_dependency.rb <ide> require 'testing_env' <ide> require 'requirements/language_module_dependency' <ide> <del># XXX: Figure out what env file needs to require hardware <del>require 'hardware' <del> <ide> class LanguageModuleDependencyTests < Test::Unit::TestCase <ide> def assert_deps_fail(spec) <ide> l = LanguageModuleDependency.new(*spec.shift.reverse) <ide><path>Library/Homebrew/test/test_software_spec.rb <ide> require 'testing_env' <ide> require 'formula_support' <del> <del># XXX: grrrrr <del>require 'hardware' <ide> require 'bottles' <ide> <ide> class SoftwareSpecTests < Test::Unit::TestCase <ide><path>Library/Homebrew/test/test_version_subclasses.rb <ide> require 'testing_env' <ide> require 'version' <ide> require 'os/mac/version' <del>require 'hardware' <ide> <ide> class MacOSVersionTests < Test::Unit::TestCase <ide> def setup
7
Javascript
Javascript
move all user fetching to learn
f48952c3e62438bd825a72a1ecacdf6fd93b121d
<ide><path>client/src/components/layouts/Learn.js <ide> import React, { Fragment } from 'react'; <ide> import PropTypes from 'prop-types'; <add>import { createSelector } from 'reselect'; <add>import { connect } from 'react-redux'; <ide> <add>import { Loader } from '../../components/helpers'; <add>import { <add> userSelector, <add> userFetchStateSelector, <add> isSignedInSelector <add>} from '../../redux'; <add>import createRedirect from '../../components/createRedirect'; <ide> import DonateModal from '../Donation'; <ide> <ide> import 'prismjs/themes/prism.css'; <ide> import './prism-night.css'; <ide> import 'react-reflex/styles.css'; <ide> import './learn.css'; <ide> <del>function LearnLayout({ children }) { <add>const mapStateToProps = createSelector( <add> userFetchStateSelector, <add> isSignedInSelector, <add> userSelector, <add> (fetchState, isSignedIn, user) => ({ <add> fetchState, <add> isSignedIn, <add> user <add> }) <add>); <add> <add>const RedirectAcceptPrivacyTerm = createRedirect('/accept-privacy-terms'); <add> <add>function LearnLayout({ <add> fetchState: { pending, complete }, <add> isSignedIn, <add> user: { acceptedPrivacyTerms }, <add> children <add>}) { <add> if (pending && !complete) { <add> return <Loader fullScreen={true} />; <add> } <add> <add> if (isSignedIn && !acceptedPrivacyTerms) { <add> return <RedirectAcceptPrivacyTerm />; <add> } <add> <ide> return ( <ide> <Fragment> <ide> <main id='learn-app-wrapper'>{children}</main> <ide> function LearnLayout({ children }) { <ide> } <ide> <ide> LearnLayout.displayName = 'LearnLayout'; <del>LearnLayout.propTypes = { children: PropTypes.any }; <add>LearnLayout.propTypes = { <add> children: PropTypes.any, <add> fetchState: PropTypes.shape({ <add> pending: PropTypes.bool, <add> complete: PropTypes.bool, <add> errored: PropTypes.bool <add> }), <add> isSignedIn: PropTypes.bool, <add> user: PropTypes.shape({ <add> acceptedPrivacyTerms: PropTypes.bool <add> }) <add>}; <ide> <del>export default LearnLayout; <add>export default connect(mapStateToProps)(LearnLayout); <ide><path>client/src/components/welcome/Welcome.test.js <ide> describe('<Welcome />', () => { <ide> const shallow = new ShallowRenderer(); <ide> shallow.render(<LearnPage {...loggedInProps} />); <ide> const result = shallow.getRenderOutput(); <del> expect(result.type.displayName === 'LearnLayout').toBeTruthy(); <add> expect( <add> result.type.WrappedComponent.displayName === 'LearnLayout' <add> ).toBeTruthy(); <ide> }); <ide> <ide> it('has a header', () => { <ide><path>client/src/components/welcome/index.js <ide> function Welcome({ name }) { <ide> </blockquote> <ide> </Col> <ide> </Row> <del> <Row> <del> <Col sm={10} smOffset={1} xs={12}> <del> <Spacer /> <del> <h2 className='text-center medium-heading'> <del> What would you like to do today? <del> </h2> <del> </Col> <del> </Row> <ide> </Fragment> <ide> ); <ide> } <ide><path>client/src/pages/accept-privacy-terms.js <ide> import PropTypes from 'prop-types'; <ide> import { bindActionCreators } from 'redux'; <ide> import { connect } from 'react-redux'; <ide> import { <del> Grid, <ide> Row, <ide> Col, <ide> Button, <ide> class AcceptPrivacyTerms extends Component { <ide> <Helmet> <ide> <title>Privacy Policy and Terms of Service | freeCodeCamp.org</title> <ide> </Helmet> <del> <Grid> <del> <Row> <del> <Col xs={12}> <del> <div className='text-center'> <del> <Spacer size={2} /> <del> <h3> <del> Please review our updated privacy policy and the terms of <del> service. <del> </h3> <add> <Spacer size={2} /> <add> <Row className='text-center'> <add> <Col sm={8} smOffset={2} xs={12}> <add> <h1> <add> Please review our updated privacy policy and the terms of service. <add> </h1> <add> </Col> <add> </Row> <add> <Spacer size={2} /> <add> <Row> <add> <Col sm={8} smOffset={2} xs={12}> <add> <form onSubmit={this.handleSubmit}> <add> <FormGroup> <add> <ControlLabel htmlFor='terms-of-service'> <add> Terms of Service <add> </ControlLabel> <ide> <Spacer /> <del> </div> <del> </Col> <del> </Row> <del> <Row> <del> <Col sm={6} smOffset={3}> <del> <form onSubmit={this.handleSubmit}> <del> <FormGroup> <del> <ControlLabel htmlFor='terms-of-service'> <del> Terms of Service <del> </ControlLabel> <del> <Spacer /> <del> <Checkbox <del> checked={termsOfService} <del> id='terms-of-service' <del> inline={true} <del> onChange={this.createHandleChange('termsOfService')} <del> > <del> I accept the{' '} <del> <Link external={true} to='/news/terms-of-service'> <del> terms of service <del> </Link>{' '} <del> (required) <del> </Checkbox> <del> </FormGroup> <del> <FormGroup> <del> <ControlLabel htmlFor='privacy-policy'> <del> Privacy Policy <del> </ControlLabel> <del> <Spacer /> <del> <Checkbox <del> checked={privacyPolicy} <del> id='privacy-policy' <del> inline={true} <del> onChange={this.createHandleChange('privacyPolicy')} <del> > <del> I accept the{' '} <del> <Link external={true} to='/news/privacy-policy'> <del> privacy policy <del> </Link>{' '} <del> (required) <del> </Checkbox> <del> </FormGroup> <del> <FormGroup> <del> <ControlLabel htmlFor='quincy-email'> <del> Quincy's Emails <del> </ControlLabel> <del> <Spacer /> <del> <Checkbox <del> checked={quincyEmail} <del> id='quincy-email' <del> inline={true} <del> onChange={this.createHandleChange('quincyEmail')} <del> > <del> I want weekly emails from Quincy, freeCodeCamp.org's <del> founder. <del> </Checkbox> <del> </FormGroup> <del> <ButtonSpacer /> <del> <Button <del> block={true} <del> bsStyle='primary' <del> className='big-cta-btn' <del> disabled={!privacyPolicy || !termsOfService} <del> type='submit' <add> <Checkbox <add> checked={termsOfService} <add> id='terms-of-service' <add> inline={true} <add> onChange={this.createHandleChange('termsOfService')} <ide> > <del> Continue to freeCodeCamp <del> </Button> <del> </form> <del> </Col> <del> </Row> <del> </Grid> <add> I accept the{' '} <add> <Link external={true} to='/news/terms-of-service'> <add> terms of service <add> </Link>{' '} <add> (required) <add> </Checkbox> <add> </FormGroup> <add> <Spacer /> <add> <FormGroup> <add> <ControlLabel htmlFor='privacy-policy'> <add> Privacy Policy <add> </ControlLabel> <add> <Spacer /> <add> <Checkbox <add> checked={privacyPolicy} <add> id='privacy-policy' <add> inline={true} <add> onChange={this.createHandleChange('privacyPolicy')} <add> > <add> I accept the{' '} <add> <Link external={true} to='/news/privacy-policy'> <add> privacy policy <add> </Link>{' '} <add> (required) <add> </Checkbox> <add> </FormGroup> <add> <Spacer /> <add> <FormGroup> <add> <ControlLabel htmlFor='quincy-email'> <add> Quincy's Emails <add> </ControlLabel> <add> <Spacer /> <add> <Checkbox <add> checked={quincyEmail} <add> id='quincy-email' <add> inline={true} <add> onChange={this.createHandleChange('quincyEmail')} <add> > <add> I want weekly emails from Quincy, freeCodeCamp.org's founder. <add> </Checkbox> <add> </FormGroup> <add> <ButtonSpacer /> <add> <Button <add> block={true} <add> bsStyle='primary' <add> className='big-cta-btn' <add> disabled={!privacyPolicy || !termsOfService} <add> type='submit' <add> > <add> Continue to freeCodeCamp.org <add> </Button> <add> <Spacer size={2} /> <add> </form> <add> </Col> <add> </Row> <ide> </Fragment> <ide> ); <ide> } <ide><path>client/src/pages/index.js <ide> import React from 'react'; <del>import { createSelector } from 'reselect'; <del>import { connect } from 'react-redux'; <ide> import PropTypes from 'prop-types'; <ide> import { graphql } from 'gatsby'; <ide> <del>import { Loader } from '../components/helpers'; <ide> import Landing from '../components/landing'; <del>import { <del> userSelector, <del> userFetchStateSelector, <del> isSignedInSelector <del>} from '../redux'; <del>import createRedirect from '../components/createRedirect'; <ide> import { AllChallengeNode } from '../redux/propTypes'; <ide> <del>const mapStateToProps = createSelector( <del> userFetchStateSelector, <del> isSignedInSelector, <del> userSelector, <del> (fetchState, isSignedIn, user) => ({ <del> fetchState, <del> isSignedIn, <del> user <del> }) <del>); <del> <del>const RedirectAcceptPrivacyTerm = createRedirect('/accept-privacy-terms'); <del>const RedirectLearn = createRedirect('/learn'); <del> <ide> export const IndexPage = ({ <del> fetchState: { pending, complete }, <del> isSignedIn, <del> user: { acceptedPrivacyTerms }, <ide> data: { <ide> allChallengeNode: { edges } <ide> } <ide> }) => { <del> if (pending && !complete) { <del> return <Loader fullScreen={true} />; <del> } <del> <del> if (isSignedIn && !acceptedPrivacyTerms) { <del> return <RedirectAcceptPrivacyTerm />; <del> } <del> <del> if (isSignedIn) { <del> return <RedirectLearn />; <del> } <del> <ide> return <Landing edges={edges} />; <ide> }; <ide> <ide> const propTypes = { <ide> data: PropTypes.shape({ <ide> allChallengeNode: AllChallengeNode <del> }), <del> fetchState: PropTypes.shape({ <del> pending: PropTypes.bool, <del> complete: PropTypes.bool, <del> errored: PropTypes.bool <del> }), <del> isSignedIn: PropTypes.bool, <del> user: PropTypes.shape({ <del> acceptedPrivacyTerms: PropTypes.bool <ide> }) <ide> }; <ide> <ide> IndexPage.propTypes = propTypes; <ide> IndexPage.displayName = 'IndexPage'; <ide> <del>export default connect(mapStateToProps)(IndexPage); <add>export default IndexPage; <ide> <ide> export const query = graphql` <ide> query challNodes { <ide><path>client/src/pages/learn.js <ide> import { <ide> <ide> import LearnLayout from '../components/layouts/Learn'; <ide> import Login from '../components/Header/components/Login'; <del>import { Link, Spacer, Loader } from '../components/helpers'; <add>import { Link, Spacer } from '../components/helpers'; <ide> import Map from '../components/Map'; <ide> import Welcome from '../components/welcome'; <ide> import { dasherize } from '../../../utils/slugs'; <ide> const hashValueSelector = (state, hash) => { <ide> }; <ide> <ide> export const LearnPage = ({ <del> fetchState: { pending, complete }, <ide> location: { hash = '', state = '' }, <ide> isSignedIn, <ide> user: { name = '' }, <ide> export const LearnPage = ({ <ide> allMarkdownRemark: { edges: mdEdges } <ide> } <ide> }) => { <del> if (pending && !complete) { <del> return <Loader fullScreen={true} />; <del> } <del> <ide> const hashValue = hashValueSelector(state, hash); <del> <ide> return ( <ide> <LearnLayout> <ide> <Helmet title='Learn | freeCodeCamp.org' />
6
Javascript
Javascript
add keyboardevent.code to synthetic event
f625fce8578cc77113d9da8ffd02032a60477e6a
<ide><path>packages/react-dom/src/events/SyntheticKeyboardEvent.js <ide> import getEventModifierState from './getEventModifierState'; <ide> */ <ide> const SyntheticKeyboardEvent = SyntheticUIEvent.extend({ <ide> key: getEventKey, <add> code: null, <ide> location: null, <ide> ctrlKey: null, <ide> shiftKey: null, <ide><path>packages/react-dom/src/events/__tests__/SyntheticKeyboardEvent-test.js <ide> describe('SyntheticKeyboardEvent', () => { <ide> }); <ide> }); <ide> }); <add> <add> describe('code', () => { <add> it('returns code on `keydown`, `keyup` and `keypress`', () => { <add> let codeDown = null; <add> let codeUp = null; <add> let codePress = null; <add> const node = ReactDOM.render( <add> <input <add> onKeyDown={e => { <add> codeDown = e.code; <add> }} <add> onKeyUp={e => { <add> codeUp = e.code; <add> }} <add> onKeyPress={e => { <add> codePress = e.code; <add> }} <add> />, <add> container, <add> ); <add> node.dispatchEvent( <add> new KeyboardEvent('keydown', { <add> code: 'KeyQ', <add> bubbles: true, <add> cancelable: true, <add> }), <add> ); <add> node.dispatchEvent( <add> new KeyboardEvent('keyup', { <add> code: 'KeyQ', <add> bubbles: true, <add> cancelable: true, <add> }), <add> ); <add> node.dispatchEvent( <add> new KeyboardEvent('keypress', { <add> code: 'KeyQ', <add> charCode: 113, <add> bubbles: true, <add> cancelable: true, <add> }), <add> ); <add> expect(codeDown).toBe('KeyQ'); <add> expect(codeUp).toBe('KeyQ'); <add> expect(codePress).toBe('KeyQ'); <add> }); <add> }); <ide> }); <ide> <ide> describe('EventInterface', () => {
2
Javascript
Javascript
improve fchmod{sync} validation
1ae184a85c05164b40933a5efc678cd9f008d2c4
<ide><path>lib/fs.js <ide> fs.unlinkSync = function(path) { <ide> }; <ide> <ide> fs.fchmod = function(fd, mode, callback) { <del> validateUint32(fd, 'fd'); <add> validateInt32(fd, 'fd', 0); <ide> mode = validateAndMaskMode(mode, 'mode'); <ide> callback = makeCallback(callback); <ide> <ide> fs.fchmod = function(fd, mode, callback) { <ide> }; <ide> <ide> fs.fchmodSync = function(fd, mode) { <del> validateUint32(fd, 'fd'); <add> validateInt32(fd, 'fd', 0); <ide> mode = validateAndMaskMode(mode, 'mode'); <ide> const ctx = {}; <ide> binding.fchmod(fd, mode, undefined, ctx); <ide><path>test/parallel/test-fs-fchmod.js <ide> const fs = require('fs'); <ide> const errObj = { <ide> code: 'ERR_OUT_OF_RANGE', <ide> name: 'RangeError [ERR_OUT_OF_RANGE]', <del> message: 'The value of "fd" is out of range. It must be >= 0 && < ' + <del> `${2 ** 32}. Received ${input}` <add> message: 'The value of "fd" is out of range. It must be >= 0 && <= ' + <add> `2147483647. Received ${input}` <ide> }; <ide> assert.throws(() => fs.fchmod(input), errObj); <ide> assert.throws(() => fs.fchmodSync(input), errObj); <del> errObj.message = errObj.message.replace('fd', 'mode'); <add>}); <add> <add>[-1, 2 ** 32].forEach((input) => { <add> const errObj = { <add> code: 'ERR_OUT_OF_RANGE', <add> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> message: 'The value of "mode" is out of range. It must be >= 0 && < ' + <add> `4294967296. Received ${input}` <add> }; <add> <ide> assert.throws(() => fs.fchmod(1, input), errObj); <ide> assert.throws(() => fs.fchmodSync(1, input), errObj); <ide> });
2