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
relocate config options merge
c4a2eaafa4764951c07f89aa8ffaf7b520832802
<ide><path>src/ORM/TableRegistry.php <ide> public static function get($alias, array $options = []) <ide> list(, $classAlias) = pluginSplit($alias); <ide> $options = ['alias' => $classAlias] + $options; <ide> <add> if (isset(static::$_config[$alias])) { <add> $options += static::$_config[$alias]; <add> } <add> <ide> if (empty($options['className'])) { <ide> $options['className'] = Inflector::camelize($alias); <ide> } <ide> public static function get($alias, array $options = []) <ide> $options['className'] = 'Cake\ORM\Table'; <ide> } <ide> <del> if (isset(static::$_config[$alias])) { <del> $options = static::$_config[$alias] + $options; <del> } <ide> if (empty($options['connection'])) { <ide> $connectionName = $options['className']::defaultConnectionName(); <ide> $options['connection'] = ConnectionManager::get($connectionName);
1
PHP
PHP
add tests for testresponse
0745d9dccc8788680be7039470309ff03d844af2
<ide><path>tests/Foundation/FoundationTestResponseTest.php <add><?php <add> <add>namespace Illuminate\Tests\Foundation; <add> <add>use JsonSerializable; <add>use PHPUnit\Framework\TestCase; <add>use Illuminate\Foundation\Testing\TestResponse; <add> <add>class FoundationTestResponseTest extends TestCase <add>{ <add> public function testAssertJsonWithArray() <add> { <add> $response = new TestResponse(new JsonSerializableSingleResourceStub); <add> <add> $resource = new JsonSerializableSingleResourceStub; <add> <add> $response->assertJson($resource->jsonSerialize()); <add> } <add> <add> public function testAssertJsonWithMixed() <add> { <add> $response = new TestResponse(new JsonSerializableMixedResourcesStub); <add> <add> $resource = new JsonSerializableMixedResourcesStub; <add> <add> $response->assertJson($resource->jsonSerialize()); <add> } <add> <add> public function testAssertJsonStructure() <add> { <add> $response = new TestResponse(new JsonSerializableMixedResourcesStub); <add> <add> // At root <add> $response->assertJsonStructure(['foo']); <add> <add> // Nested <add> $response->assertJsonStructure(['foobar' => ['foobar_foo', 'foobar_bar']]); <add> <add> // Wildcard (repeating structure) <add> $response->assertJsonStructure(['bars' => ['*' => ['bar', 'foo']]]); <add> <add> // Nested after wildcard <add> $response->assertJsonStructure(['baz' => ['*' => ['foo', 'bar' => ['foo', 'bar']]]]); <add> <add> // Wildcard (repeating structure) at root <add> $response = new TestResponse(new JsonSerializableSingleResourceStub); <add> $response->assertJsonStructure(['*' => ['foo', 'bar', 'foobar']]); <add> } <add>} <add> <add>class JsonSerializableMixedResourcesStub implements JsonSerializable <add>{ <add> public function jsonSerialize() <add> { <add> return [ <add> 'foo' => 'bar', <add> 'foobar' => [ <add> 'foobar_foo' => 'foo', <add> 'foobar_bar' => 'bar', <add> ], <add> 'bars' => [ <add> ['bar' => 'foo 0', 'foo' => 'bar 0'], <add> ['bar' => 'foo 1', 'foo' => 'bar 1'], <add> ['bar' => 'foo 2', 'foo' => 'bar 2'], <add> ], <add> 'baz' => [ <add> ['foo' => 'bar 0', 'bar' => ['foo' => 'bar 0', 'bar' => 'foo 0']], <add> ['foo' => 'bar 1', 'bar' => ['foo' => 'bar 1', 'bar' => 'foo 1']], <add> ], <add> ]; <add> } <add>} <add> <add>class JsonSerializableSingleResourceStub implements JsonSerializable <add>{ <add> public function jsonSerialize() <add> { <add> return [ <add> ['foo' => 'foo 0', 'bar' => 'bar 0', 'foobar' => 'foobar 0'], <add> ['foo' => 'foo 1', 'bar' => 'bar 1', 'foobar' => 'foobar 1'], <add> ['foo' => 'foo 2', 'bar' => 'bar 2', 'foobar' => 'foobar 2'], <add> ['foo' => 'foo 3', 'bar' => 'bar 3', 'foobar' => 'foobar 3'], <add> ]; <add> } <add>}
1
Ruby
Ruby
address syntax warnings in homebrew core
8091b33f85c96a93d14de80ce3bfd9c32f8bb58c
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_text <ide> problem "\"Formula.factory(name)\" is deprecated in favor of \"Formula[name]\"" <ide> end <ide> <del> if text =~ /system "npm", "install"/ && text !~ %r[opt_libexec}/npm/bin] <add> if text =~ /system "npm", "install"/ && text !~ %r[opt_libexec\}/npm/bin] <ide> need_npm = "\#{Formula[\"node\"].opt_libexec\}/npm/bin" <ide> problem <<-EOS.undent <ide> Please add ENV.prepend_path \"PATH\", \"#{need_npm}"\ to def install <ide><path>Library/Homebrew/test/test_formula.rb <ide> def test_any_version_installed? <ide> refute_predicate f, :any_version_installed? <ide> prefix = HOMEBREW_CELLAR+f.name+"0.1" <ide> prefix.mkpath <del> FileUtils.touch (prefix+Tab::FILENAME) <add> FileUtils.touch prefix+Tab::FILENAME <ide> assert_predicate f, :any_version_installed? <ide> ensure <ide> f.rack.rmtree <ide><path>Library/Homebrew/test/test_migrator.rb <ide> def test_migrate <ide> <ide> assert_predicate @new_keg_record, :exist? <ide> assert_predicate @old_keg_record.parent, :symlink? <del> refute_predicate (HOMEBREW_LIBRARY/"LinkedKegs/oldname"), :exist? <add> refute_predicate HOMEBREW_LIBRARY/"LinkedKegs/oldname", :exist? <ide> assert_equal @new_keg_record.realpath, (HOMEBREW_LIBRARY/"LinkedKegs/newname").realpath <ide> assert_equal @new_keg_record.realpath, @old_keg_record.realpath <ide> assert_equal @new_keg_record.realpath, (HOMEBREW_PREFIX/"opt/oldname").realpath <ide><path>Library/Homebrew/test/test_pathname.rb <ide> def test_install_symlink <ide> assert_predicate @dst+"bin", :directory? <ide> assert_predicate @dst+"bin/a.txt", :exist? <ide> assert_predicate @dst+"bin/b.txt", :exist? <del> assert_predicate (@dst+"bin").readlink, :relative? <add> assert_predicate((@dst+"bin").readlink, :relative?) <ide> end <ide> <ide> def test_install_relative_symlink
4
Python
Python
add tests for regularizers
56e09ad7365ed09caded620f65e44160d6aa02b6
<ide><path>keras/layers/core.py <ide> class ActivityRegularization(Layer): <ide> Layer that passes through its input unchanged, but applies an update <ide> to the cost function based on the activity. <ide> ''' <del> def __init__(self, activity_regularizer): <add> def __init__(self, activity_regularizer = None): <ide> super(ActivityRegularization, self).__init__() <del> self.cost_update = activity_regularizer(self) <add> if activity_regularizer is not None: <add> self.cost_update = activity_regularizer(self) <ide> <ide> def get_output(self, train): <ide> return self.get_input(train) <ide><path>tests/auto/test_regularizers.py <add>import unittest <add>import numpy as np <add>from keras.models import Sequential <add>from keras.layers.core import Merge, Dense, Activation, Flatten, ActivityRegularization <add>from keras.layers.embeddings import Embedding <add>from keras.datasets import mnist <add>from keras.utils import np_utils <add>from keras import regularizers <add> <add>nb_classes = 10 <add>batch_size = 128 <add>nb_epoch = 5 <add>weighted_class = 9 <add>standard_weight = 1 <add>high_weight = 5 <add>max_train_samples = 5000 <add>max_test_samples = 1000 <add> <add>np.random.seed(1337) # for reproducibility <add> <add># the data, shuffled and split between tran and test sets <add>(X_train, y_train), (X_test, y_test) = mnist.load_data() <add>X_train = X_train.reshape(60000, 784)[:max_train_samples] <add>X_test = X_test.reshape(10000, 784)[:max_test_samples] <add>X_train = X_train.astype("float32") / 255 <add>X_test = X_test.astype("float32") / 255 <add> <add># convert class vectors to binary class matrices <add>y_train = y_train[:max_train_samples] <add>y_test = y_test[:max_test_samples] <add>Y_train = np_utils.to_categorical(y_train, nb_classes) <add>Y_test = np_utils.to_categorical(y_test, nb_classes) <add>test_ids = np.where(y_test == np.array(weighted_class))[0] <add> <add>def create_model(weight_reg=None, activity_reg=None): <add> model = Sequential() <add> model.add(Dense(784, 50)) <add> model.add(Activation('relu')) <add> model.add(ActivityRegularization(activity_reg)) <add> model.add(Dense(50, 10, W_regularizer=weight_reg)) <add> model.add(Activation('softmax')) <add> return model <add> <add> <add>class TestRegularizers(unittest.TestCase): <add> def test_W_reg(self): <add> for reg in [regularizers.identity, regularizers.l1(), regularizers.l2(), regularizers.l1l2()]: <add> model = create_model(weight_reg=reg) <add> model.compile(loss='categorical_crossentropy', optimizer='rmsprop') <add> model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0) <add> model.evaluate(X_test[test_ids, :], Y_test[test_ids, :], verbose=0) <add> <add> def test_A_reg(self): <add> for reg in [regularizers.activity_l1(), regularizers.activity_l2()]: <add> model = create_model(activity_reg=reg) <add> model.compile(loss='categorical_crossentropy', optimizer='rmsprop') <add> model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0) <add> model.evaluate(X_test[test_ids, :], Y_test[test_ids, :], verbose=0) <ide>\ No newline at end of file
2
Javascript
Javascript
ignore setgstate no-ops
9674abc542603a0c6b38420e98b11c35ae2ba0f2
<ide><path>src/core/evaluator.js <ide> var PartialEvaluator = (function PartialEvaluatorClosure() { <ide> <ide> break; <ide> // Only generate info log messages for the following since <del> // they are unlikey to have a big impact on the rendering. <add> // they are unlikely to have a big impact on the rendering. <ide> case 'OP': <ide> case 'op': <ide> case 'OPM': <ide> var PartialEvaluator = (function PartialEvaluatorClosure() { <ide> setGStateForKey(gStateObj, key, value); <ide> } <ide> return promise.then(function () { <del> operatorList.addOp(OPS.setGState, [gStateObj]); <add> if (gStateObj.length >= 0) { <add> operatorList.addOp(OPS.setGState, [gStateObj]); <add> } <ide> }); <ide> }, <ide>
1
Text
Text
mitigate `marked` bug
536b1fbd3ff38df3d5e8eb0b011820fd94f68b9d
<ide><path>doc/api/net.md <ide> Possible signatures: <ide> * [`server.listen(options[, callback])`][`server.listen(options)`] <ide> * [`server.listen(path[, backlog][, callback])`][`server.listen(path)`] <ide> for [IPC][] servers <del>* [`server.listen([port[, host[, backlog]]][, callback])`][`server.listen(port, host)`] <add>* <a href="#net_server_listen_port_host_backlog_callback"> <add> <code>server.listen([port[, host[, backlog]]][, callback])</code></a> <ide> for TCP servers <ide> <ide> This function is asynchronous. When the server starts listening, the <ide> added: v0.11.14 <ide> * Returns: {net.Server} <ide> <ide> If `port` is specified, it behaves the same as <del>[`server.listen([port[, host[, backlog]]][, callback])`][`server.listen(port, host)`]. <add><a href="#net_server_listen_port_host_backlog_callback"> <add><code>server.listen([port[, host[, backlog]]][, callback])</code></a>. <ide> Otherwise, if `path` is specified, it behaves the same as <ide> [`server.listen(path[, backlog][, callback])`][`server.listen(path)`]. <ide> If none of them is specified, an error will be thrown. <ide> Returns `true` if input is a version 6 IP address, otherwise returns `false`. <ide> [`server.listen(handle)`]: #net_server_listen_handle_backlog_callback <ide> [`server.listen(options)`]: #net_server_listen_options_callback <ide> [`server.listen(path)`]: #net_server_listen_path_backlog_callback <del>[`server.listen(port, host)`]: #net_server_listen_port_host_backlog_callback <ide> [`socket.connect()`]: #net_socket_connect <ide> [`socket.connect(options)`]: #net_socket_connect_options_connectlistener <ide> [`socket.connect(path)`]: #net_socket_connect_path_connectlistener
1
Text
Text
fix preposition capitalization
f27175d166470e69a13ec96af6ac0d5f908dae57
<ide><path>docs/docs/07.1-more-about-refs.md <ide> Consider the case when you wish to tell an `<input />` element (that exists with <ide> return ( <ide> <div> <ide> <div onClick={this.clearAndFocusInput}> <del> Click To Focus and Reset <add> Click to Focus and Reset <ide> </div> <ide> <input <ide> value={this.state.userInput} <ide> It's as simple as: <ide> return ( <ide> <div> <ide> <div onClick={this.clearAndFocusInput}> <del> Click To Focus and Reset <add> Click to Focus and Reset <ide> </div> <ide> <input <ide> ref="theInput"
1
Javascript
Javascript
revert local file
df5dced258776058f8b45c2c85d1974c075567a0
<ide><path>locale/es.js <ide> }(this, function (moment) { 'use strict'; <ide> <ide> <del> var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'), <del> monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); <add> var monthsShortDot = 'Ene._Feb._Mar._Abr._May._Jun._Jul._Ago._Sep._Oct._Nov._Dic.'.split('_'), <add> monthsShort = 'Ene_Feb_Mar_Abr_May_Jun_Jul_Ago_Sep_Oct_Nov_Dic'.split('_'); <ide> <ide> var es = moment.defineLocale('es', { <del> months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), <add> months : 'Enero_Febrero_Marzo_Abril_Mayo_Junio_Julio_Agosto_Septiembre_Octubre_Noviembre_Diciembre'.split('_'), <ide> monthsShort : function (m, format) { <ide> if (/-MMM-/.test(format)) { <ide> return monthsShort[m.month()]; <ide> } else { <ide> return monthsShortDot[m.month()]; <ide> } <ide> }, <del> weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), <del> weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), <del> weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'), <add> weekdays : 'Domingo_Lunes_Martes_Miércoles_Jueves_Viernes_Sábado'.split('_'), <add> weekdaysShort : 'Dom._Lun._Mar._Mié._Jue._Vie._Sáb.'.split('_'), <add> weekdaysMin : 'Do_Lu_Ma_Mi_Ju_Vi_Sá'.split('_'), <ide> longDateFormat : { <ide> LT : 'H:mm', <ide> LTS : 'H:mm:ss',
1
Java
Java
fix typo in beandefinitionparserdelegate
072961b91ae03c998dc4aa27a87590e5d897fd12
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.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> public class BeanDefinitionParserDelegate { <ide> <ide> /** <ide> * Value of a T/F attribute that represents true. <del> * Anything else represents false. Case seNsItive. <add> * Anything else represents false. Case sensitive. <ide> */ <ide> public static final String TRUE_VALUE = "true"; <ide>
1
PHP
PHP
use less inflection on aliasing
4b6806379c45436a051a1fb65eea8be8c143f132
<ide><path>src/ORM/Locator/TableLocator.php <ide> public function getConfig(?string $alias = null): array <ide> * key in the registry. This means that if two plugins, or a plugin and app provide <ide> * the same alias, the registry will only store the first instance. <ide> * <del> * @param string $alias The alias name you want to get. <add> * @param string $alias The alias name you want to get. Must be in CamelCase format. <ide> * @param array $options The options you want to build the table with. <ide> * If a table has already been loaded the options will be ignored. <ide> * @return \Cake\ORM\Table <ide> public function get(string $alias, array $options = []): Table <ide> $options['className'] = $className; <ide> } else { <ide> if (empty($options['className'])) { <del> $options['className'] = Inflector::camelize($alias); <add> $options['className'] = $alias; <ide> } <ide> if (!isset($options['table']) && strpos($options['className'], '\\') === false) { <ide> [, $table] = pluginSplit($options['className']); <ide> public function get(string $alias, array $options = []): Table <ide> /** <ide> * Gets the table class name. <ide> * <del> * @param string $alias The alias name you want to get. <add> * @param string $alias The alias name you want to get. Must be in CamelCase format. <ide> * @param array $options Table options array. <ide> * @return string|null <ide> */ <ide> protected function _getClassName(string $alias, array $options = []): ?string <ide> { <ide> if (empty($options['className'])) { <del> $options['className'] = Inflector::camelize($alias); <add> $options['className'] = $alias; <ide> } <ide> <ide> if (strpos($options['className'], '\\') !== false && class_exists($options['className'])) {
1
Ruby
Ruby
remove preset env vars for encryption keys
5cec2eced604cd18482c9c664dcabb903ac19a21
<ide><path>activerecord/lib/active_record/railtie.rb <ide> class Railtie < Rails::Railtie # :nodoc: <ide> initializer "active_record_encryption.configuration" do |app| <ide> config.before_initialize do <ide> ActiveRecord::Encryption.configure \ <del> master_key: app.credentials.dig(:active_record_encryption, :master_key) || ENV["ACTIVE_RECORD_ENCRYPTION_MASTER_KEY"], <del> deterministic_key: app.credentials.dig(:active_record_encryption, :deterministic_key) || ENV["ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY"], <del> key_derivation_salt: app.credentials.dig(:active_record_encryption, :key_derivation_salt) || ENV["ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT"], <add> master_key: app.credentials.dig(:active_record_encryption, :master_key), <add> deterministic_key: app.credentials.dig(:active_record_encryption, :deterministic_key), <add> key_derivation_salt: app.credentials.dig(:active_record_encryption, :key_derivation_salt), <ide> **config.active_record.encryption <ide> <ide> # Encrypt active record fixtures
1
Java
Java
fix bug in sockjs jsonptransporthandler
82ec06ad349426acf663f8edc22dd7716c4ff2cd
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/JsonpTransportHandler.java <ide> public void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse <ide> <ide> @Override <ide> protected String[] readMessages(ServerHttpRequest request) throws IOException { <del> if (MediaType.APPLICATION_FORM_URLENCODED.equals(request.getHeaders().getContentType())) { <add> MediaType contentType = request.getHeaders().getContentType(); <add> if ((contentType != null) && MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType)) { <ide> MultiValueMap<String, String> map = this.formConverter.read(null, request); <ide> String d = map.getFirst("d"); <ide> return (StringUtils.hasText(d)) ? getObjectMapper().readValue(d, String[].class) : null; <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/transport/HttpReceivingTransportHandlerTests.java <ide> public void readMessagesJsonpFormEncoded() throws Exception { <ide> assertEquals("ok", this.servletResponse.getContentAsString()); <ide> } <ide> <add> // SPR-10621 <add> <add> @Test <add> public void readMessagesJsonpFormEncodedWithEncoding() throws Exception { <add> this.servletRequest.setContent("d=[\"x\"]".getBytes("UTF-8")); <add> this.servletRequest.setContentType("application/x-www-form-urlencoded;charset=UTF-8"); <add> handleRequest(new JsonpTransportHandler()); <add> <add> assertEquals(200, this.servletResponse.getStatus()); <add> assertEquals("ok", this.servletResponse.getContentAsString()); <add> } <add> <ide> @Test <ide> public void readMessagesBadContent() throws Exception { <ide> this.servletRequest.setContent("".getBytes("UTF-8"));
2
Ruby
Ruby
fix shebang on created files
e0a4d8be93b1bfa17cbf1fb87947d7b12049ddc7
<ide><path>railties/lib/generator/generators/app.rb <ide> def app_secret <ide> ActiveSupport::SecureRandom.hex(64) <ide> end <ide> <del> def freeze <del> options[:freeze] <del> end <del> <ide> def shebang <del> options[:ruby] || "#!/usr/bin/env ruby" <add> "#!#{options[:ruby] || "/usr/bin/env ruby"}" <ide> end <ide> <ide> def mysql_socket <ide><path>railties/lib/generator/templates/app/config/environment.rb <ide> # Be sure to restart your server when you modify this file <ide> <ide> # Specifies gem version of Rails to use when vendor/rails is not present <del><%= '# ' if freeze %>RAILS_GEM_VERSION = '<%= Rails::VERSION::STRING %>' unless defined? RAILS_GEM_VERSION <add><%= '# ' if options[:freeze] %>RAILS_GEM_VERSION = '<%= Rails::VERSION::STRING %>' unless defined? RAILS_GEM_VERSION <ide> <ide> # Bootstrap the Rails environment, frameworks, and default configuration <ide> require File.join(File.dirname(__FILE__), 'boot')
2
Mixed
Javascript
fix various spelling mistakes
360a4780339b7f412b75ad8a06dca7f39616f654
<ide><path>build/release/dist.js <ide> module.exports = function( Release, complete ) { <ide> shell = require( "shelljs" ), <ide> pkg = require( Release.dir.repo + "/package.json" ), <ide> distRemote = Release.remote.replace( "jquery.git", "jquery-dist.git" ), <del> // These files are included with the distrubtion <add> // These files are included with the distribution <ide> files = [ <ide> "src", <ide> "LICENSE.txt", <ide><path>test/data/support/csp.php <ide> <?php <del> # This test page checkes CSP only for browsers with "Content-Security-Policy" header support <add> # This test page checks CSP only for browsers with "Content-Security-Policy" header support <ide> # i.e. no old WebKit or old Firefox <ide> header("Content-Security-Policy: default-src 'self'; report-uri csp-log.php"); <ide> ?> <ide><path>test/unit/css.js <ide> test("css(String|Hash)", function() { <ide> <ide> equal( div2.find("input").css("height"), "20px", "Height on hidden input." ); <ide> equal( div2.find("textarea").css("height"), "20px", "Height on hidden textarea." ); <del> equal( div2.find("div").css("height"), "20px", "Height on hidden textarea." ); <add> equal( div2.find("div").css("height"), "20px", "Height on hidden div." ); <ide> <ide> div2.remove(); <ide> <ide><path>test/unit/event.js <ide> test( "Donor event interference", function( assert ) { <ide> jQuery( "#donor-input" )[ 0 ].click(); <ide> } ); <ide> <del>test( "originalEvent property for Chrome, Safari and FF of simualted event", function( assert ) { <add>test( "originalEvent property for Chrome, Safari and FF of simulated event", function( assert ) { <ide> var userAgent = window.navigator.userAgent; <ide> <ide> if ( !(/chrome/i.test( userAgent ) || <ide><path>test/unit/manipulation.js <ide> test( "html(String) tag-hyphenated elements (Bug #1987)", function() { <ide> var j = jQuery("<tr-multiple-hyphens><td-with-hyphen>text</td-with-hyphen></tr-multiple-hyphens>"); <ide> ok( jQuery.nodeName(j[0], "TR-MULTIPLE-HYPHENS"), "Tags with multiple hypens" ); <ide> ok( jQuery.nodeName(j.children()[0], "TD-WITH-HYPHEN"), "Tags with multiple hypens" ); <del> equal( j.children().text(), "text", "Tags with multple hypens behave normally" ); <add> equal( j.children().text(), "text", "Tags with multiple hypens behave normally" ); <ide> }); <ide> <ide> test( "IE8 serialization bug", function() { <ide><path>test/unit/tween.js <ide> test( "jQuery.Tween - custom propHooks - advanced values", function() { <ide> <ide> // Some day this NaN assumption might change - perhaps add a "calc" helper to the hooks? <ide> ok( isNaN( tween.now ), "Used return value from propHook.get" ); <del> equal( tween.pos, 0.5, "But the eased percent is still avaliable" ); <add> equal( tween.pos, 0.5, "But the eased percent is still available" ); <ide> ok( propHook.set.calledWith( tween ), "Called propHook.set function with correct parameters" ); <ide> <ide> delete jQuery.Tween.propHooks.testHooked;
6
Javascript
Javascript
add invert to mercator, albers and azimuthal
872c9ff13be83a20601c2989b4fc276c1aebaaff
<ide><path>d3.geo.js <ide> d3.geo.azimuthal = function() { <ide> sx1 = Math.sin(x1), <ide> cy1 = Math.cos(y1), <ide> sy1 = Math.sin(y1), <del> k = mode == "stereographic" ? 1 / (1 + sy0 * sy1 + cy0 * cy1 * cx1) : 1, <add> k = mode === "stereographic" ? 1 / (1 + sy0 * sy1 + cy0 * cy1 * cx1) : 1, <ide> x = k * cy1 * sx1, <ide> y = k * (sy0 * cy1 * cx1 - cy0 * sy1); <ide> return [ <ide> d3.geo.azimuthal = function() { <ide> ]; <ide> } <ide> <add> azimuthal.invert = function(xy) { <add> var x = (xy[0] - translate[0]) / scale, <add> y = -(xy[1] - translate[1]) / scale, <add> p = Math.sqrt(x * x + y * y), <add> c = mode === "stereographic" ? 2 * Math.atan(p) : Math.asin(p), <add> sc = Math.sin(c), <add> cc = Math.cos(c); <add> return [ <add> (x0 + Math.atan2(x * sc, p * cy0 * cc - y * sy0 * sc)) / d3_radians, <add> Math.asin(cc * sy0 + (y * sc * cy0) / p) / d3_radians <add> ]; <add> }; <add> <ide> azimuthal.mode = function(x) { <ide> if (!arguments.length) return mode; <ide> mode = x; <ide> d3.geo.albers = function() { <ide> ]; <ide> } <ide> <add> albers.invert = function(xy) { <add> var x = (xy[0] - translate[0]) / scale, <add> y = -(xy[1] - translate[1]) / scale, <add> p0y = p0 - y, <add> t = Math.atan2(x, p0y), <add> p = Math.sqrt(x * x + p0y * p0y); <add> return [ <add> (lng0 + t / n) / d3_radians, <add> Math.asin((C - p * p * n * n) / (2 * n)) / d3_radians <add> ]; <add> }; <add> <ide> function reload() { <ide> var phi1 = d3_radians * parallels[0], <ide> phi2 = d3_radians * parallels[1], <ide> d3.geo.mercator = function() { <ide> translate = [480, 250]; <ide> <ide> function mercator(coordinates) { <del> var x = (coordinates[0]) / 360, <del> y = (-180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + coordinates[1] * Math.PI / 360))) / 360; <add> var x = coordinates[0] / 360, <add> y = -(Math.log(Math.tan(Math.PI / 4 + coordinates[1] * d3_radians / 2)) / d3_radians) / 360; <ide> return [ <ide> scale * x + translate[0], <ide> scale * Math.max(-.5, Math.min(.5, y)) + translate[1] <ide> ]; <ide> } <ide> <add> mercator.invert = function(xy) { <add> var lon = 360 * (xy[0] - translate[0]) / scale, <add> lat = -360 * (xy[1] - translate[1]) / scale; <add> return [ <add> lon, <add> 2 * Math.atan(Math.exp(lat * d3_radians)) / d3_radians - 90 <add> ]; <add> }; <add> <ide> mercator.scale = function(x) { <ide> if (!arguments.length) return scale; <ide> scale = +x; <ide><path>d3.geo.min.js <del>(function(){function m(a,b){for(var c=a.coordinates[0],d=0,e=c.length;d<e;d++)b.apply(null,c[d])}function l(a,b){b.apply(null,a.coordinates)}function k(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)for(var f=c[d][0],g=0,h=f.length;g<h;g++)b.apply(null,f[g])}function j(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)for(var f=c[d],g=0,h=f.length;g<h;g++)b.apply(null,f[g])}function i(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)b.apply(null,c[d])}function h(a,b){for(var c=a.features,d=0,f=c.length;d<f;d++)e(c[d].geometry,b)}function g(a,b){e(a.geometry,b)}function e(a,b){a.type in f&&f[a.type](a,b)}function d(a,b){return b&&b.type in a?a[b.type](b):""}function c(){return 0}function b(a){return"m0,"+a+"a"+a+","+a+" 0 1,1 0,"+ -2*a+"a"+a+","+a+" 0 1,1 0,"+2*a+"z"}d3.geo={},d3.geo.azimuthal=function(){function j(c){var g=c[0]*a-f,j=c[1]*a,k=Math.cos(g),l=Math.sin(g),m=Math.cos(j),n=Math.sin(j),o=b=="stereographic"?1/(1+i*n+h*m*k):1,p=o*m*l,q=o*(i*m*k-h*n);return[d*p+e[0],d*q+e[1]]}var b="orthographic",c,d=200,e=[480,250],f,g,h,i;j.mode=function(a){if(!arguments.length)return b;b=a;return j},j.origin=function(b){if(!arguments.length)return c;c=b,f=c[0]*a,g=c[1]*a,h=Math.cos(g),i=Math.sin(g);return j},j.scale=function(a){if(!arguments.length)return d;d=+a;return j},j.translate=function(a){if(!arguments.length)return e;e=[+a[0],+a[1]];return j};return j.origin([0,0])},d3.geo.albers=function(){function k(){var d=a*c[0],e=a*c[1],k=a*b[1],l=Math.sin(d),m=Math.cos(d);f=a*b[0],g=.5*(l+Math.sin(e)),h=m*m+2*g*l,i=Math.sqrt(h-2*g*Math.sin(k))/g;return j}function j(b){var c=g*(a*b[0]-f),j=Math.sqrt(h-2*g*Math.sin(a*b[1]))/g;return[d*j*Math.sin(c)+e[0],d*(j*Math.cos(c)-i)+e[1]]}var b=[-98,38],c=[29.5,45.5],d=1e3,e=[480,250],f,g,h,i;j.origin=function(a){if(!arguments.length)return b;b=[+a[0],+a[1]];return k()},j.parallels=function(a){if(!arguments.length)return c;c=[+a[0],+a[1]];return k()},j.scale=function(a){if(!arguments.length)return d;d=+a;return j},j.translate=function(a){if(!arguments.length)return e;e=[+a[0],+a[1]];return j};return k()},d3.geo.albersUsa=function(){function e(e){var f=e[0],g=e[1];return(g>50?b:f<-140?c:g<21?d:a)(e)}var a=d3.geo.albers(),b=d3.geo.albers().origin([-160,60]).parallels([55,65]),c=d3.geo.albers().origin([-160,20]).parallels([8,18]),d=d3.geo.albers().origin([-60,10]).parallels([8,18]);e.scale=function(f){if(!arguments.length)return a.scale();a.scale(f),b.scale(f*.6),c.scale(f),d.scale(f*1.5);return e.translate(a.translate())},e.translate=function(f){if(!arguments.length)return a.translate();var g=a.scale()/1e3,h=f[0],i=f[1];a.translate(f),b.translate([h-400*g,i+170*g]),c.translate([h-190*g,i+200*g]),d.translate([h+580*g,i+430*g]);return e};return e.scale(a.scale())};var a=Math.PI/180;d3.geo.mercator=function(){function c(c){var d=c[0]/360,e=-180/Math.PI*Math.log(Math.tan(Math.PI/4+c[1]*Math.PI/360))/360;return[a*d+b[0],a*Math.max(-0.5,Math.min(.5,e))+b[1]]}var a=500,b=[480,250];c.scale=function(b){if(!arguments.length)return a;a=+b;return c},c.translate=function(a){if(!arguments.length)return b;b=[+a[0],+a[1]];return c};return c},d3.geo.path=function(){function n(a){return Math.abs(d3.geom.polygon(a.map(f)).area())}function l(a){var b=d3.geom.polygon(a[0].map(f)),c=b.centroid(1),d=c[0],e=c[1],g=Math.abs(b.area()),h=0,i=a.length;while(++h<i)b=d3.geom.polygon(a[h].map(f)),c=b.centroid(1),d-=c[0],e-=c[1],g-=Math.abs(b.area());return[d,e,6*g]}function k(a){var b=n(a[0]),c=0,d=a.length;while(++c<d)b-=n(a[c]);return b}function h(a){return f(a).join(",")}function g(c,f){typeof a=="function"&&(e=b(a.apply(this,arguments)));return d(i,c)}var a=4.5,e=b(a),f=d3.geo.albersUsa(),i={FeatureCollection:function(a){var b=[],c=a.features,e=-1,f=c.length;while(++e<f)b.push(d(i,c[e].geometry));return b.join("")},Feature:function(a){return d(i,a.geometry)},Point:function(a){return"M"+h(a.coordinates)+e},MultiPoint:function(a){var b=[],c=a.coordinates,d=-1,f=c.length;while(++d<f)b.push("M",h(c[d]),e);return b.join("")},LineString:function(a){var b=["M"],c=a.coordinates,d=-1,e=c.length;while(++d<e)b.push(h(c[d]),"L");b.pop();return b.join("")},MultiLineString:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i;while(++d<e){f=c[d],g=-1,i=f.length,b.push("M");while(++g<i)b.push(h(f[g]),"L");b.pop()}return b.join("")},Polygon:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i;while(++d<e){f=c[d],g=-1,i=f.length,b.push("M");while(++g<i)b.push(h(f[g]),"L");b[b.length-1]="Z"}return b.join("")},MultiPolygon:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i,j,k,l;while(++d<e){f=c[d],g=-1,i=f.length;while(++g<i){j=f[g],k=-1,l=j.length-1,b.push("M");while(++k<l)b.push(h(j[k]),"L");b[b.length-1]="Z"}}return b.join("")},GeometryCollection:function(a){var b=[],c=a.geometries,e=-1,f=c.length;while(++e<f)b.push(d(i,c[e]));return b.join("")}},j={FeatureCollection:function(a){var b=0,c=a.features,e=-1,f=c.length;while(++e<f)b+=d(j,c[e]);return b},Feature:function(a){return d(j,a.geometry)},Point:c,MultiPoint:c,LineString:c,MultiLineString:c,Polygon:function(a){return k(a.coordinates)},MultiPolygon:function(a){var b=0,c=a.coordinates,d=-1,e=c.length;while(++d<e)b+=k(c[d]);return b},GeometryCollection:function(a){var b=0,c=a.geometries,e=-1,f=c.length;while(++e<f)b+=d(j,c[e]);return b}},m={Feature:function(a){return d(m,a.geometry)},Polygon:function(a){var b=l(a.coordinates);return[b[0]/b[2],b[1]/b[2]]},MultiPolygon:function(a){var b=0,c=a.coordinates,d,e=0,f=0,g=0,h=-1,i=c.length;while(++h<i)d=l(c[h]),e+=d[0],f+=d[1],g+=d[2];return[e/g,f/g]}};g.projection=function(a){f=a;return g},g.area=function(a){return d(j,a)},g.centroid=function(a){return d(m,a)},g.pointRadius=function(c){typeof c=="function"?a=c:(a=+c,e=b(a));return g};return g},d3.geo.bounds=function(a){var b=Infinity,c=Infinity,d=-Infinity,f=-Infinity;e(a,function(a,e){a<b&&(b=a),a>d&&(d=a),e<c&&(c=e),e>f&&(f=e)});return[[b,c],[d,f]]};var f={Feature:g,FeatureCollection:h,LineString:i,MultiLineString:j,MultiPoint:i,MultiPolygon:k,Point:l,Polygon:m}})() <ide>\ No newline at end of file <add>(function(){function m(a,b){for(var c=a.coordinates[0],d=0,e=c.length;d<e;d++)b.apply(null,c[d])}function l(a,b){b.apply(null,a.coordinates)}function k(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)for(var f=c[d][0],g=0,h=f.length;g<h;g++)b.apply(null,f[g])}function j(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)for(var f=c[d],g=0,h=f.length;g<h;g++)b.apply(null,f[g])}function i(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)b.apply(null,c[d])}function h(a,b){for(var c=a.features,d=0,f=c.length;d<f;d++)e(c[d].geometry,b)}function g(a,b){e(a.geometry,b)}function e(a,b){a.type in f&&f[a.type](a,b)}function d(a,b){return b&&b.type in a?a[b.type](b):""}function c(){return 0}function b(a){return"m0,"+a+"a"+a+","+a+" 0 1,1 0,"+ -2*a+"a"+a+","+a+" 0 1,1 0,"+2*a+"z"}d3.geo={},d3.geo.azimuthal=function(){function j(c){var g=c[0]*a-f,j=c[1]*a,k=Math.cos(g),l=Math.sin(g),m=Math.cos(j),n=Math.sin(j),o=b==="stereographic"?1/(1+i*n+h*m*k):1,p=o*m*l,q=o*(i*m*k-h*n);return[d*p+e[0],d*q+e[1]]}var b="orthographic",c,d=200,e=[480,250],f,g,h,i;j.invert=function(c){var g=(c[0]-e[0])/d,j=-(c[1]-e[1])/d,k=Math.sqrt(g*g+j*j),l=b==="stereographic"?2*Math.atan(k):Math.asin(k),m=Math.sin(l),n=Math.cos(l);return[(f+Math.atan2(g*m,k*h*n-j*i*m))/a,Math.asin(n*i+j*m*h/k)/a]},j.mode=function(a){if(!arguments.length)return b;b=a;return j},j.origin=function(b){if(!arguments.length)return c;c=b,f=c[0]*a,g=c[1]*a,h=Math.cos(g),i=Math.sin(g);return j},j.scale=function(a){if(!arguments.length)return d;d=+a;return j},j.translate=function(a){if(!arguments.length)return e;e=[+a[0],+a[1]];return j};return j.origin([0,0])},d3.geo.albers=function(){function k(){var d=a*c[0],e=a*c[1],k=a*b[1],l=Math.sin(d),m=Math.cos(d);f=a*b[0],g=.5*(l+Math.sin(e)),h=m*m+2*g*l,i=Math.sqrt(h-2*g*Math.sin(k))/g;return j}function j(b){var c=g*(a*b[0]-f),j=Math.sqrt(h-2*g*Math.sin(a*b[1]))/g;return[d*j*Math.sin(c)+e[0],d*(j*Math.cos(c)-i)+e[1]]}var b=[-98,38],c=[29.5,45.5],d=1e3,e=[480,250],f,g,h,i;j.invert=function(b){var c=(b[0]-e[0])/d,j=-(b[1]-e[1])/d,k=i-j,l=Math.atan2(c,k),m=Math.sqrt(c*c+k*k);return[(f+l/g)/a,Math.asin((h-m*m*g*g)/(2*g))/a]},j.origin=function(a){if(!arguments.length)return b;b=[+a[0],+a[1]];return k()},j.parallels=function(a){if(!arguments.length)return c;c=[+a[0],+a[1]];return k()},j.scale=function(a){if(!arguments.length)return d;d=+a;return j},j.translate=function(a){if(!arguments.length)return e;e=[+a[0],+a[1]];return j};return k()},d3.geo.albersUsa=function(){function e(e){var f=e[0],g=e[1];return(g>50?b:f<-140?c:g<21?d:a)(e)}var a=d3.geo.albers(),b=d3.geo.albers().origin([-160,60]).parallels([55,65]),c=d3.geo.albers().origin([-160,20]).parallels([8,18]),d=d3.geo.albers().origin([-60,10]).parallels([8,18]);e.scale=function(f){if(!arguments.length)return a.scale();a.scale(f),b.scale(f*.6),c.scale(f),d.scale(f*1.5);return e.translate(a.translate())},e.translate=function(f){if(!arguments.length)return a.translate();var g=a.scale()/1e3,h=f[0],i=f[1];a.translate(f),b.translate([h-400*g,i+170*g]),c.translate([h-190*g,i+200*g]),d.translate([h+580*g,i+430*g]);return e};return e.scale(a.scale())};var a=Math.PI/180;d3.geo.mercator=function(){function d(d){var e=d[0]/360,f=-(Math.log(Math.tan(Math.PI/4+d[1]*a/2))/a)/360;return[b*e+c[0],b*Math.max(-0.5,Math.min(.5,f))+c[1]]}var b=500,c=[480,250];d.invert=function(d){var e=360*(d[0]-c[0])/b,f=-360*(d[1]-c[1])/b;return[e,2*Math.atan(Math.exp(f*a))/a-90]},d.scale=function(a){if(!arguments.length)return b;b=+a;return d},d.translate=function(a){if(!arguments.length)return c;c=[+a[0],+a[1]];return d};return d},d3.geo.path=function(){function n(a){return Math.abs(d3.geom.polygon(a.map(f)).area())}function l(a){var b=d3.geom.polygon(a[0].map(f)),c=b.centroid(1),d=c[0],e=c[1],g=Math.abs(b.area()),h=0,i=a.length;while(++h<i)b=d3.geom.polygon(a[h].map(f)),c=b.centroid(1),d-=c[0],e-=c[1],g-=Math.abs(b.area());return[d,e,6*g]}function k(a){var b=n(a[0]),c=0,d=a.length;while(++c<d)b-=n(a[c]);return b}function h(a){return f(a).join(",")}function g(c,f){typeof a=="function"&&(e=b(a.apply(this,arguments)));return d(i,c)}var a=4.5,e=b(a),f=d3.geo.albersUsa(),i={FeatureCollection:function(a){var b=[],c=a.features,e=-1,f=c.length;while(++e<f)b.push(d(i,c[e].geometry));return b.join("")},Feature:function(a){return d(i,a.geometry)},Point:function(a){return"M"+h(a.coordinates)+e},MultiPoint:function(a){var b=[],c=a.coordinates,d=-1,f=c.length;while(++d<f)b.push("M",h(c[d]),e);return b.join("")},LineString:function(a){var b=["M"],c=a.coordinates,d=-1,e=c.length;while(++d<e)b.push(h(c[d]),"L");b.pop();return b.join("")},MultiLineString:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i;while(++d<e){f=c[d],g=-1,i=f.length,b.push("M");while(++g<i)b.push(h(f[g]),"L");b.pop()}return b.join("")},Polygon:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i;while(++d<e){f=c[d],g=-1,i=f.length,b.push("M");while(++g<i)b.push(h(f[g]),"L");b[b.length-1]="Z"}return b.join("")},MultiPolygon:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i,j,k,l;while(++d<e){f=c[d],g=-1,i=f.length;while(++g<i){j=f[g],k=-1,l=j.length-1,b.push("M");while(++k<l)b.push(h(j[k]),"L");b[b.length-1]="Z"}}return b.join("")},GeometryCollection:function(a){var b=[],c=a.geometries,e=-1,f=c.length;while(++e<f)b.push(d(i,c[e]));return b.join("")}},j={FeatureCollection:function(a){var b=0,c=a.features,e=-1,f=c.length;while(++e<f)b+=d(j,c[e]);return b},Feature:function(a){return d(j,a.geometry)},Point:c,MultiPoint:c,LineString:c,MultiLineString:c,Polygon:function(a){return k(a.coordinates)},MultiPolygon:function(a){var b=0,c=a.coordinates,d=-1,e=c.length;while(++d<e)b+=k(c[d]);return b},GeometryCollection:function(a){var b=0,c=a.geometries,e=-1,f=c.length;while(++e<f)b+=d(j,c[e]);return b}},m={Feature:function(a){return d(m,a.geometry)},Polygon:function(a){var b=l(a.coordinates);return[b[0]/b[2],b[1]/b[2]]},MultiPolygon:function(a){var b=0,c=a.coordinates,d,e=0,f=0,g=0,h=-1,i=c.length;while(++h<i)d=l(c[h]),e+=d[0],f+=d[1],g+=d[2];return[e/g,f/g]}};g.projection=function(a){f=a;return g},g.area=function(a){return d(j,a)},g.centroid=function(a){return d(m,a)},g.pointRadius=function(c){typeof c=="function"?a=c:(a=+c,e=b(a));return g};return g},d3.geo.bounds=function(a){var b=Infinity,c=Infinity,d=-Infinity,f=-Infinity;e(a,function(a,e){a<b&&(b=a),a>d&&(d=a),e<c&&(c=e),e>f&&(f=e)});return[[b,c],[d,f]]};var f={Feature:g,FeatureCollection:h,LineString:i,MultiLineString:j,MultiPoint:i,MultiPolygon:k,Point:l,Polygon:m}})() <ide>\ No newline at end of file <ide><path>src/geo/albers.js <ide> d3.geo.albers = function() { <ide> ]; <ide> } <ide> <add> albers.invert = function(xy) { <add> var x = (xy[0] - translate[0]) / scale, <add> y = -(xy[1] - translate[1]) / scale, <add> p0y = p0 - y, <add> t = Math.atan2(x, p0y), <add> p = Math.sqrt(x * x + p0y * p0y); <add> return [ <add> (lng0 + t / n) / d3_radians, <add> Math.asin((C - p * p * n * n) / (2 * n)) / d3_radians <add> ]; <add> }; <add> <ide> function reload() { <ide> var phi1 = d3_radians * parallels[0], <ide> phi2 = d3_radians * parallels[1], <ide><path>src/geo/azimuthal.js <ide> d3.geo.azimuthal = function() { <ide> sx1 = Math.sin(x1), <ide> cy1 = Math.cos(y1), <ide> sy1 = Math.sin(y1), <del> k = mode == "stereographic" ? 1 / (1 + sy0 * sy1 + cy0 * cy1 * cx1) : 1, <add> k = mode === "stereographic" ? 1 / (1 + sy0 * sy1 + cy0 * cy1 * cx1) : 1, <ide> x = k * cy1 * sx1, <ide> y = k * (sy0 * cy1 * cx1 - cy0 * sy1); <ide> return [ <ide> d3.geo.azimuthal = function() { <ide> ]; <ide> } <ide> <add> azimuthal.invert = function(xy) { <add> var x = (xy[0] - translate[0]) / scale, <add> y = -(xy[1] - translate[1]) / scale, <add> p = Math.sqrt(x * x + y * y), <add> c = mode === "stereographic" ? 2 * Math.atan(p) : Math.asin(p), <add> sc = Math.sin(c), <add> cc = Math.cos(c); <add> return [ <add> (x0 + Math.atan2(x * sc, p * cy0 * cc - y * sy0 * sc)) / d3_radians, <add> Math.asin(cc * sy0 + (y * sc * cy0) / p) / d3_radians <add> ]; <add> }; <add> <ide> azimuthal.mode = function(x) { <ide> if (!arguments.length) return mode; <ide> mode = x; <ide><path>src/geo/mercator.js <ide> d3.geo.mercator = function() { <ide> translate = [480, 250]; <ide> <ide> function mercator(coordinates) { <del> var x = (coordinates[0]) / 360, <del> y = (-180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + coordinates[1] * Math.PI / 360))) / 360; <add> var x = coordinates[0] / 360, <add> y = -(Math.log(Math.tan(Math.PI / 4 + coordinates[1] * d3_radians / 2)) / d3_radians) / 360; <ide> return [ <ide> scale * x + translate[0], <ide> scale * Math.max(-.5, Math.min(.5, y)) + translate[1] <ide> ]; <ide> } <ide> <add> mercator.invert = function(xy) { <add> var lon = 360 * (xy[0] - translate[0]) / scale, <add> lat = -360 * (xy[1] - translate[1]) / scale; <add> return [ <add> lon, <add> 2 * Math.atan(Math.exp(lat * d3_radians)) / d3_radians - 90 <add> ]; <add> }; <add> <ide> mercator.scale = function(x) { <ide> if (!arguments.length) return scale; <ide> scale = +x; <ide><path>test/geo/albers-test.js <add>require("../env"); <add>require("../../d3"); <add>require("../../d3.geo"); <add> <add>var vows = require("vows"), <add> assert = require("assert"); <add> <add>var suite = vows.describe("d3.geo.albers"); <add> <add>suite.addBatch({ <add> "albers": { <add> topic: function() { <add> return d3.geo.albers(); <add> }, <add> "Arctic": function(albers) { <add> var coords = albers([0, 85]); <add> assert.inDelta(coords[0], 1031.393796, 1e-6); <add> assert.inDelta(coords[1], -714.160436, 1e-6); <add> var lonlat = albers.invert(coords); <add> assert.inDelta(lonlat[0], 0, 1e-6); <add> assert.inDelta(lonlat[1], 85, 1e-6); <add> }, <add> "Antarctic": function(albers) { <add> var coords = albers([0, -85]); <add> assert.inDelta(coords[0], 2753.458335, 1e-6); <add> assert.inDelta(coords[1], 317.371122, 1e-6); <add> var lonlat = albers.invert(coords); <add> assert.inDelta(lonlat[0], 0, 1e-6); <add> assert.inDelta(lonlat[1], -85, 1e-6); <add> }, <add> "Hawaii": function(albers) { <add> var coords = albers([-180, 0]); <add> assert.inDelta(coords[0], -984.779405, 1e-6); <add> assert.inDelta(coords[1], 209.571197, 1e-6); <add> var lonlat = albers.invert(coords); <add> assert.inDelta(lonlat[0], -180, 1e-6); <add> assert.inDelta(lonlat[1], 0, 1e-6); <add> }, <add> "Phillipines": function(albers) { <add> var coords = albers([180, 0]); <add> assert.inDelta(coords[0], 894.435228, 1e-6); <add> assert.inDelta(coords[1], -2927.636630, 1e-6); <add> var lonlat = albers.invert(coords); <add> assert.inDelta(lonlat[0], 180, 1e-6); <add> assert.inDelta(lonlat[1], 0, 1e-6); <add> }, <add> "Inversion works for non-zero translation": function() { <add> var albers = d3.geo.albers().translate([123, 99]).scale(100), <add> coords = albers([0, 85]), <add> lonlat = albers.invert(coords); <add> assert.inDelta(lonlat[0], 0, 1e-6); <add> assert.inDelta(lonlat[1], 85, 1e-6); <add> } <add> } <add>}); <add> <add>suite.export(module); <ide><path>test/geo/azimuthal-test.js <add>require("../env"); <add>require("../../d3"); <add>require("../../d3.geo"); <add> <add>var vows = require("vows"), <add> assert = require("assert"); <add> <add>var suite = vows.describe("d3.geo.azimuthal"); <add> <add>suite.addBatch({ <add> "azimuthal.stereographic": { <add> topic: function() { <add> return d3.geo.azimuthal().mode("stereographic").translate([0, 0]).scale(100); <add> }, <add> "Arctic": function(azimuthal) { <add> var coords = azimuthal([0, 85]); <add> assert.inDelta(coords[0], 0, 1e-6); <add> assert.inDelta(coords[1], -91.633117, 1e-6); <add> var lonlat = azimuthal.invert(coords); <add> assert.inDelta(lonlat[0], 0, 1e-6); <add> assert.inDelta(lonlat[1], 85, 1e-6); <add> }, <add> "Antarctic": function(azimuthal) { <add> var coords = azimuthal([0, -85]); <add> assert.inDelta(coords[0], 0, 1e-6); <add> assert.inDelta(coords[1], 91.633117, 1e-6); <add> var lonlat = azimuthal.invert(coords); <add> assert.inDelta(lonlat[0], 0, 1e-6); <add> assert.inDelta(lonlat[1], -85, 1e-6); <add> }, <add> "Hawaii": function(azimuthal) { <add> var coords = azimuthal([-180, 0]); <add> assert.equal(coords[0], -Infinity); <add> assert.isTrue(isNaN(coords[1])); <add> }, <add> "Phillipines": function(azimuthal) { <add> var coords = azimuthal([180, 0]); <add> assert.equal(coords[0], Infinity); <add> assert.isTrue(isNaN(coords[1])); <add> }, <add> "Inversion works for non-zero translation": function() { <add> var azimuthal = d3.geo.azimuthal().mode("stereographic").translate([123, 99]).scale(100), <add> coords = azimuthal([0, 85]), <add> lonlat = azimuthal.invert(coords); <add> assert.inDelta(lonlat[0], 0, 1e-6); <add> assert.inDelta(lonlat[1], 85, 1e-6); <add> } <add> }, <add> "azimuthal.orthographic": { <add> topic: function() { <add> return d3.geo.azimuthal().mode("orthographic").translate([0, 0]).scale(100); <add> }, <add> "Arctic": function(azimuthal) { <add> var coords = azimuthal([0, 85]); <add> assert.inDelta(coords[0], 0, 1e-6); <add> assert.inDelta(coords[1], -99.619469, 1e-6); <add> var lonlat = azimuthal.invert(coords); <add> assert.inDelta(lonlat[0], 0, 1e-6); <add> assert.inDelta(lonlat[1], 85, 1e-6); <add> }, <add> "Antarctic": function(azimuthal) { <add> var coords = azimuthal([0, -85]); <add> assert.inDelta(coords[0], 0, 1e-6); <add> assert.inDelta(coords[1], 99.619469, 1e-6); <add> var lonlat = azimuthal.invert(coords); <add> assert.inDelta(lonlat[0], 0, 1e-6); <add> assert.inDelta(lonlat[1], -85, 1e-6); <add> }, <add> "Hawaii": function(azimuthal) { <add> var coords = azimuthal([-180, 0]); <add> assert.inDelta(coords[0], 0, 1e-6); <add> assert.inDelta(coords[1], 0, 1e-6); <add> }, <add> "Phillipines": function(azimuthal) { <add> var coords = azimuthal([180, 0]); <add> assert.inDelta(coords[0], 0, 1e-6); <add> assert.inDelta(coords[1], 0, 1e-6); <add> }, <add> "Inversion works for non-zero translation": function() { <add> var azimuthal = d3.geo.azimuthal().mode("orthographic").translate([123, 99]).scale(100), <add> coords = azimuthal([0, 85]), <add> lonlat = azimuthal.invert(coords); <add> assert.inDelta(lonlat[0], 0, 1e-6); <add> assert.inDelta(lonlat[1], 85, 1e-6); <add> } <add> } <add>}); <add> <add>suite.export(module); <ide><path>test/geo/mercator-test.js <add>require("../env"); <add>require("../../d3"); <add>require("../../d3.geo"); <add> <add>var vows = require("vows"), <add> assert = require("assert"); <add> <add>var suite = vows.describe("d3.geo.mercator"); <add> <add>suite.addBatch({ <add> "mercator": { <add> topic: function() { <add> return d3.geo.mercator().translate([0, 0]).scale(100); <add> }, <add> "Arctic": function(mercator) { <add> var coords = mercator([0, 85]); <add> assert.inDelta(coords[0], 0, 1e-6); <add> assert.inDelta(coords[1], -49.8362085, 1e-6); <add> var lonlat = mercator.invert(coords); <add> assert.inDelta(lonlat[0], 0, 1e-6); <add> assert.inDelta(lonlat[1], 85, 1e-6); <add> }, <add> "Antarctic": function(mercator) { <add> var coords = mercator([0, -85]); <add> assert.inDelta(coords[0], 0, 1e-6); <add> assert.inDelta(coords[1], 49.8362085, 1e-6); <add> var lonlat = mercator.invert(coords); <add> assert.inDelta(lonlat[0], 0, 1e-6); <add> assert.inDelta(lonlat[1], -85, 1e-6); <add> }, <add> "Hawaii": function(mercator) { <add> var coords = mercator([-180, 0]); <add> assert.inDelta(coords[0], -50, 1e-6); <add> assert.inDelta(coords[1], 0, 1e-6); <add> var lonlat = mercator.invert(coords); <add> assert.inDelta(lonlat[0], -180, 1e-6); <add> assert.inDelta(lonlat[1], 0, 1e-6); <add> }, <add> "Phillipines": function(mercator) { <add> var coords = mercator([180, 0]); <add> assert.inDelta(coords[0], 50, 1e-6); <add> assert.inDelta(coords[1], 0, 1e-6); <add> var lonlat = mercator.invert(coords); <add> assert.inDelta(lonlat[0], 180, 1e-6); <add> assert.inDelta(lonlat[1], 0, 1e-6); <add> }, <add> "Inversion works for non-zero translation": function() { <add> var mercator = d3.geo.mercator().translate([123, 99]).scale(100), <add> coords = mercator([0, 85]), <add> lonlat = mercator.invert(coords); <add> assert.inDelta(lonlat[0], 0, 1e-6); <add> assert.inDelta(lonlat[1], 85, 1e-6); <add> } <add> } <add>}); <add> <add>suite.export(module);
8
Javascript
Javascript
fix minimum values for writeint*() functions
3b852d7faba82d5ec2367939ecc98c3ab03cb2e6
<ide><path>lib/buffer.js <ide> Buffer.prototype.writeInt8 = function(value, offset, noAssert) { <ide> assert.ok(offset < buffer.length, <ide> 'Trying to write beyond buffer length'); <ide> <del> verifsint(value, 0x7f, -0xf0); <add> verifsint(value, 0x7f, -0x80); <ide> } <ide> <ide> if (value >= 0) { <ide> function writeInt16(buffer, value, offset, isBigEndian, noAssert) { <ide> assert.ok(offset + 1 < buffer.length, <ide> 'Trying to write beyond buffer length'); <ide> <del> verifsint(value, 0x7fff, -0xf000); <add> verifsint(value, 0x7fff, -0x8000); <ide> } <ide> <ide> if (value >= 0) { <ide> function writeInt32(buffer, value, offset, isBigEndian, noAssert) { <ide> assert.ok(offset + 3 < buffer.length, <ide> 'Trying to write beyond buffer length'); <ide> <del> verifsint(value, 0x7fffffff, -0xf0000000); <add> verifsint(value, 0x7fffffff, -0x80000000); <ide> } <ide> <ide> if (value >= 0) { <ide><path>test/simple/test-writeint.js <ide> function test8() { <ide> ASSERT.throws(function() { <ide> buffer.writeInt8(0xabc, 0); <ide> }); <add> <add> /* Make sure we handle min/max correctly */ <add> buffer.writeInt8(0x7f, 0); <add> buffer.writeInt8(-0x80, 1); <add> <add> ASSERT.equal(0x7f, buffer[0]); <add> ASSERT.equal(0x80, buffer[1]); <add> ASSERT.throws(function() { <add> buffer.writeInt8(0x7f + 1, 0); <add> }); <add> ASSERT.throws(function() { <add> buffer.writeInt8(-0x80 - 1, 0); <add> }); <ide> } <ide> <ide> <ide> function test16() { <ide> ASSERT.equal(0x71, buffer[2]); <ide> ASSERT.equal(0x71, buffer[3]); <ide> ASSERT.equal(0xf9, buffer[4]); <add> <add> /* Make sure we handle min/max correctly */ <add> buffer.writeInt16BE(0x7fff, 0); <add> buffer.writeInt16BE(-0x8000, 2); <add> ASSERT.equal(0x7f, buffer[0]); <add> ASSERT.equal(0xff, buffer[1]); <add> ASSERT.equal(0x80, buffer[2]); <add> ASSERT.equal(0x00, buffer[3]); <add> ASSERT.throws(function() { <add> buffer.writeInt16BE(0x7fff + 1, 0); <add> }); <add> ASSERT.throws(function() { <add> buffer.writeInt16BE(-0x8000 - 1, 0); <add> }); <add> <add> buffer.writeInt16LE(0x7fff, 0); <add> buffer.writeInt16LE(-0x8000, 2); <add> ASSERT.equal(0xff, buffer[0]); <add> ASSERT.equal(0x7f, buffer[1]); <add> ASSERT.equal(0x00, buffer[2]); <add> ASSERT.equal(0x80, buffer[3]); <add> ASSERT.throws(function() { <add> buffer.writeInt16LE(0x7fff + 1, 0); <add> }); <add> ASSERT.throws(function() { <add> buffer.writeInt16LE(-0x8000 - 1, 0); <add> }); <ide> } <ide> <ide> <ide> function test32() { <ide> ASSERT.equal(0xfe, buffer[5]); <ide> ASSERT.equal(0xff, buffer[6]); <ide> ASSERT.equal(0xcf, buffer[7]); <add> <add> /* Make sure we handle min/max correctly */ <add> buffer.writeInt32BE(0x7fffffff, 0); <add> buffer.writeInt32BE(-0x80000000, 4); <add> ASSERT.equal(0x7f, buffer[0]); <add> ASSERT.equal(0xff, buffer[1]); <add> ASSERT.equal(0xff, buffer[2]); <add> ASSERT.equal(0xff, buffer[3]); <add> ASSERT.equal(0x80, buffer[4]); <add> ASSERT.equal(0x00, buffer[5]); <add> ASSERT.equal(0x00, buffer[6]); <add> ASSERT.equal(0x00, buffer[7]); <add> ASSERT.throws(function() { <add> buffer.writeInt32BE(0x7fffffff + 1, 0); <add> }); <add> ASSERT.throws(function() { <add> buffer.writeInt32BE(-0x80000000 - 1, 0); <add> }); <add> <add> buffer.writeInt32LE(0x7fffffff, 0); <add> buffer.writeInt32LE(-0x80000000, 4); <add> ASSERT.equal(0xff, buffer[0]); <add> ASSERT.equal(0xff, buffer[1]); <add> ASSERT.equal(0xff, buffer[2]); <add> ASSERT.equal(0x7f, buffer[3]); <add> ASSERT.equal(0x00, buffer[4]); <add> ASSERT.equal(0x00, buffer[5]); <add> ASSERT.equal(0x00, buffer[6]); <add> ASSERT.equal(0x80, buffer[7]); <add> ASSERT.throws(function() { <add> buffer.writeInt32LE(0x7fffffff + 1, 0); <add> }); <add> ASSERT.throws(function() { <add> buffer.writeInt32LE(-0x80000000 - 1, 0); <add> }); <ide> } <ide> <ide>
2
Javascript
Javascript
handle any element in triggermouseevent in tests
8b110fdc513141e99848ae236860741e48cc31ff
<ide><path>test/specs/controller.polarArea.tests.js <ide> describe('Chart.controllers.polarArea', function() { <ide> var chart = this.chart; <ide> var arc = chart.getDatasetMeta(0).data[0]; <ide> <del> jasmine.triggerMouseEvent(chart, 'mousemove', {_model: arc.getCenterPoint()}); <add> jasmine.triggerMouseEvent(chart, 'mousemove', arc); <ide> expect(arc._model.backgroundColor).toBe('rgb(49, 135, 221)'); <ide> expect(arc._model.borderColor).toBe('rgb(22, 89, 156)'); <ide> expect(arc._model.borderWidth).toBe(2); <ide> <del> jasmine.triggerMouseEvent(chart, 'mouseout', {_model: arc.getCenterPoint()}); <add> jasmine.triggerMouseEvent(chart, 'mouseout', arc); <ide> expect(arc._model.backgroundColor).toBe('rgb(100, 150, 200)'); <ide> expect(arc._model.borderColor).toBe('rgb(50, 100, 150)'); <ide> expect(arc._model.borderWidth).toBe(2); <ide> describe('Chart.controllers.polarArea', function() { <ide> <ide> chart.update(); <ide> <del> jasmine.triggerMouseEvent(chart, 'mousemove', {_model: arc.getCenterPoint()}); <add> jasmine.triggerMouseEvent(chart, 'mousemove', arc); <ide> expect(arc._model.backgroundColor).toBe('rgb(200, 100, 150)'); <ide> expect(arc._model.borderColor).toBe('rgb(150, 50, 100)'); <ide> expect(arc._model.borderWidth).toBe(8.4); <ide> <del> jasmine.triggerMouseEvent(chart, 'mouseout', {_model: arc.getCenterPoint()}); <add> jasmine.triggerMouseEvent(chart, 'mouseout', arc); <ide> expect(arc._model.backgroundColor).toBe('rgb(100, 150, 200)'); <ide> expect(arc._model.borderColor).toBe('rgb(50, 100, 150)'); <ide> expect(arc._model.borderWidth).toBe(2); <ide> describe('Chart.controllers.polarArea', function() { <ide> <ide> chart.update(); <ide> <del> jasmine.triggerMouseEvent(chart, 'mousemove', {_model: arc.getCenterPoint()}); <add> jasmine.triggerMouseEvent(chart, 'mousemove', arc); <ide> expect(arc._model.backgroundColor).toBe('rgb(200, 100, 150)'); <ide> expect(arc._model.borderColor).toBe('rgb(150, 50, 100)'); <ide> expect(arc._model.borderWidth).toBe(8.4); <ide> <del> jasmine.triggerMouseEvent(chart, 'mouseout', {_model: arc.getCenterPoint()}); <add> jasmine.triggerMouseEvent(chart, 'mouseout', arc); <ide> expect(arc._model.backgroundColor).toBe('rgb(100, 150, 200)'); <ide> expect(arc._model.borderColor).toBe('rgb(50, 100, 150)'); <ide> expect(arc._model.borderWidth).toBe(2); <ide> describe('Chart.controllers.polarArea', function() { <ide> <ide> chart.update(); <ide> <del> jasmine.triggerMouseEvent(chart, 'mousemove', {_model: arc.getCenterPoint()}); <add> jasmine.triggerMouseEvent(chart, 'mousemove', arc); <ide> expect(arc._model.backgroundColor).toBe('rgb(200, 100, 150)'); <ide> expect(arc._model.borderColor).toBe('rgb(150, 50, 100)'); <ide> expect(arc._model.borderWidth).toBe(8.4); <ide> <del> jasmine.triggerMouseEvent(chart, 'mouseout', {_model: arc.getCenterPoint()}); <add> jasmine.triggerMouseEvent(chart, 'mouseout', arc); <ide> expect(arc._model.backgroundColor).toBe('rgb(100, 150, 200)'); <ide> expect(arc._model.borderColor).toBe('rgb(50, 100, 150)'); <ide> expect(arc._model.borderWidth).toBe(2); <ide><path>test/utils.js <ide> function waitForResize(chart, callback) { <ide> }; <ide> } <ide> <add>function _resolveElementPoint(el) { <add> var point = {x: 0, y: 0}; <add> if (el) { <add> if (typeof el.getCenterPoint === 'function') { <add> point = el.getCenterPoint(); <add> } else if (el.x !== undefined && el.y !== undefined) { <add> point = el; <add> } else if (el._model && el._model.x !== undefined && el._model.y !== undefined) { <add> point = el._model; <add> } <add> } <add> return point; <add>} <add> <ide> function triggerMouseEvent(chart, type, el) { <ide> var node = chart.canvas; <ide> var rect = node.getBoundingClientRect(); <add> var point = _resolveElementPoint(el); <ide> var event = new MouseEvent(type, { <del> clientX: rect.left + el._model.x, <del> clientY: rect.top + el._model.y, <add> clientX: rect.left + point.x, <add> clientY: rect.top + point.y, <ide> cancelable: true, <ide> bubbles: true, <ide> view: window
2
Python
Python
move ma/matrix regressions out of numpy.core tests
1c321def2841860d97cd335a6a34fc8abed4a548
<ide><path>numpy/core/tests/test_regression.py <ide> def test_pickle_transposed(self,level=rlevel): <ide> f.close() <ide> assert_array_equal(a,b) <ide> <del> def test_masked_array_create(self,level=rlevel): <del> """Ticket #17""" <del> x = np.ma.masked_array([0,1,2,3,0,4,5,6],mask=[0,0,0,1,1,1,0,0]) <del> assert_array_equal(np.ma.nonzero(x),[[1,2,6,7]]) <del> <ide> def test_poly1d(self,level=rlevel): <ide> """Ticket #28""" <ide> assert_equal(np.poly1d([1]) - np.poly1d([1,0]), <ide> def test_bool(self,level=rlevel): <ide> """Ticket #60""" <ide> x = np.bool_(1) <ide> <del> def test_masked_array(self,level=rlevel): <del> """Ticket #61""" <del> x = np.ma.array(1,mask=[1]) <del> <del> def test_mem_masked_where(self,level=rlevel): <del> """Ticket #62""" <del> from numpy.ma import masked_where, MaskType <del> a = np.zeros((1,1)) <del> b = np.zeros(a.shape, MaskType) <del> c = masked_where(b,a) <del> a-c <del> <ide> def test_indexing1(self,level=rlevel): <ide> """Ticket #64""" <ide> descr = [('x', [('y', [('z', 'c16', (2,)),]),]),] <ide> def test_round(self,level=rlevel): <ide> x = np.array([1+2j]) <ide> assert_almost_equal(x**(-1), [1/(1+2j)]) <ide> <del> def test_kron_matrix(self,level=rlevel): <del> """Ticket #71""" <del> x = np.matrix('[1 0; 1 0]') <del> assert_equal(type(np.kron(x,x)),type(x)) <del> <ide> def test_scalar_compare(self,level=rlevel): <ide> """Ticket #72""" <ide> a = np.array(['test', 'auto']) <ide> def test_pickle_dtype(self,level=rlevel): <ide> import pickle <ide> pickle.dumps(np.float) <ide> <del> def test_masked_array_multiply(self,level=rlevel): <del> """Ticket #254""" <del> a = np.ma.zeros((4,1)) <del> a[2,0] = np.ma.masked <del> b = np.zeros((4,2)) <del> a*b <del> b*a <del> <ide> def test_swap_real(self, level=rlevel): <ide> """Ticket #265""" <ide> assert_equal(np.arange(4,dtype='>c8').imag.max(),0.0) <ide> def test_object_array_from_list(self, level=rlevel): <ide> """Ticket #270""" <ide> a = np.array([1,'A',None]) <ide> <del> def test_masked_array_repeat(self, level=rlevel): <del> """Ticket #271""" <del> np.ma.array([1],mask=False).repeat(10) <del> <ide> def test_multiple_assign(self, level=rlevel): <ide> """Ticket #273""" <ide> a = np.zeros((3,1),int) <ide><path>numpy/ma/tests/test_regression.py <add>from numpy.testing import * <add>import numpy as np <add> <add>rlevel = 1 <add> <add>class TestRegression(TestCase): <add> def test_masked_array_create(self,level=rlevel): <add> """Ticket #17""" <add> x = np.ma.masked_array([0,1,2,3,0,4,5,6],mask=[0,0,0,1,1,1,0,0]) <add> assert_array_equal(np.ma.nonzero(x),[[1,2,6,7]]) <add> <add> def test_masked_array(self,level=rlevel): <add> """Ticket #61""" <add> x = np.ma.array(1,mask=[1]) <add> <add> def test_mem_masked_where(self,level=rlevel): <add> """Ticket #62""" <add> from numpy.ma import masked_where, MaskType <add> a = np.zeros((1,1)) <add> b = np.zeros(a.shape, MaskType) <add> c = masked_where(b,a) <add> a-c <add> <add> def test_masked_array_multiply(self,level=rlevel): <add> """Ticket #254""" <add> a = np.ma.zeros((4,1)) <add> a[2,0] = np.ma.masked <add> b = np.zeros((4,2)) <add> a*b <add> b*a <add> <add> def test_masked_array_repeat(self, level=rlevel): <add> """Ticket #271""" <add> np.ma.array([1],mask=False).repeat(10) <add> <ide><path>numpy/matrx/tests/test_regression.py <add>from numpy.testing import * <add>import numpy as np <add> <add>rlevel = 1 <add> <add>class TestRegression(TestCase): <add> def test_kron_matrix(self,level=rlevel): <add> """Ticket #71""" <add> x = np.matrix('[1 0; 1 0]') <add> assert_equal(type(np.kron(x,x)),type(x))
3
Java
Java
behaviorsubject subscription timegap fix
4bb777c63a38d9e962766a0d7b612e6d8f73e980
<ide><path>rxjava-core/src/main/java/rx/subjects/BehaviorSubject.java <ide> */ <ide> package rx.subjects; <ide> <add>import java.util.ArrayList; <ide> import java.util.Collection; <add>import java.util.List; <ide> import java.util.concurrent.atomic.AtomicReference; <ide> <ide> import rx.Notification; <ide> import rx.Observer; <add>import rx.Subscriber; <ide> import rx.functions.Action0; <ide> import rx.functions.Action1; <ide> import rx.subjects.SubjectSubscriptionManager.SubjectObserver; <ide> * @param <T> <ide> */ <ide> public final class BehaviorSubject<T> extends Subject<T, T> { <del> <add> /** <add> * Create a {@link BehaviorSubject} without a default value. <add> * @param <T> the value type <add> * @return the constructed {@link BehaviorSubject} <add> */ <add> public static <T> BehaviorSubject<T> create() { <add> return create(null, false); <add> } <ide> /** <ide> * Creates a {@link BehaviorSubject} which publishes the last and all subsequent events to each {@link Observer} that subscribes to it. <ide> * <add> * @param <T> the value type <ide> * @param defaultValue <ide> * the value which will be published to any {@link Observer} as long as the {@link BehaviorSubject} has not yet received any events <ide> * @return the constructed {@link BehaviorSubject} <ide> */ <ide> public static <T> BehaviorSubject<T> create(T defaultValue) { <add> return create(defaultValue, true); <add> } <add> private static <T> BehaviorSubject<T> create(T defaultValue, boolean hasDefault) { <ide> final SubjectSubscriptionManager<T> subscriptionManager = new SubjectSubscriptionManager<T>(); <ide> // set a default value so subscriptions will immediately receive this until a new notification is received <del> final AtomicReference<Notification<T>> lastNotification = new AtomicReference<Notification<T>>(Notification.createOnNext(defaultValue)); <add> final State<T> state = new State<T>(); <add> if (hasDefault) { <add> state.lastNotification.set(Notification.createOnNext(defaultValue)); <add> } <ide> <del> OnSubscribe<T> onSubscribe = subscriptionManager.getOnSubscribeFunc( <add> final OnSubscribe<T> onSubscribeBase = subscriptionManager.getOnSubscribeFunc( <ide> /** <ide> * This function executes at beginning of subscription. <ide> * <ide> * This will always run, even if Subject is in terminal state. <ide> */ <ide> new Action1<SubjectObserver<? super T>>() { <del> <ide> @Override <ide> public void call(SubjectObserver<? super T> o) { <ide> /* <ide> * When we subscribe we always emit the latest value to the observer. <ide> * <ide> * Here we only emit if it's an onNext as terminal states are handled in the next function. <ide> */ <del> Notification<T> n = lastNotification.get(); <del> if (n.isOnNext()) { <del> n.accept(o); <del> } <add> state.addPending(o); <ide> } <ide> }, <ide> /** <ide> * This function executes if the Subject is terminated before subscription occurs. <ide> */ <ide> new Action1<SubjectObserver<? super T>>() { <del> <ide> @Override <ide> public void call(SubjectObserver<? super T> o) { <ide> /* <ide> * If we are already terminated, or termination happens while trying to subscribe <ide> * this will be invoked and we emit whatever the last terminal value was. <ide> */ <del> lastNotification.get().accept(o); <add> state.removePending(o); <ide> } <del> }, null); <add> }, new Action1<SubjectObserver<? super T>>() { <add> @Override <add> public void call(SubjectObserver<? super T> o) { <add> state.removePending(o); <add> } <add> <add> }); <add> OnSubscribe<T> onSubscribe = new OnSubscribe<T>() { <ide> <del> return new BehaviorSubject<T>(onSubscribe, subscriptionManager, lastNotification); <add> @Override <add> public void call(Subscriber<? super T> t1) { <add> onSubscribeBase.call(t1); <add> state.removePendingSubscriber(t1); <add> } <add> }; <add> return new BehaviorSubject<T>(onSubscribe, subscriptionManager, state); <ide> } <ide> <add> static final class State<T> { <add> final AtomicReference<Notification<T>> lastNotification; <add> /** Guarded by this. */ <add> List<Object> pendingSubscriptions; <add> public State() { <add> this.lastNotification = new AtomicReference<Notification<T>>(); <add> } <add> public void addPending(SubjectObserver<? super T> subscriber) { <add> synchronized (this) { <add> if (pendingSubscriptions == null) { <add> pendingSubscriptions = new ArrayList<Object>(4); <add> } <add> pendingSubscriptions.add(subscriber); <add> List<Notification<T>> list = new ArrayList<Notification<T>>(4); <add> list.add(lastNotification.get()); <add> pendingSubscriptions.add(list); <add> } <add> } <add> public void bufferValue(Notification<T> value) { <add> synchronized (this) { <add> if (pendingSubscriptions == null) { <add> return; <add> } <add> for (int i = 1; i < pendingSubscriptions.size(); i += 2) { <add> @SuppressWarnings("unchecked") <add> List<Notification<T>> list = (List<Notification<T>>)pendingSubscriptions.get(i); <add> list.add(value); <add> } <add> } <add> } <add> public void removePending(SubjectObserver<? super T> subscriber) { <add> List<Notification<T>> toCatchUp = null; <add> synchronized (this) { <add> if (pendingSubscriptions == null) { <add> return; <add> } <add> int idx = pendingSubscriptions.indexOf(subscriber); <add> if (idx >= 0) { <add> pendingSubscriptions.remove(idx); <add> @SuppressWarnings("unchecked") <add> List<Notification<T>> list = (List<Notification<T>>)pendingSubscriptions.remove(idx); <add> toCatchUp = list; <add> subscriber.caughtUp = true; <add> if (pendingSubscriptions.isEmpty()) { <add> pendingSubscriptions = null; <add> } <add> } <add> } <add> if (toCatchUp != null) { <add> for (Notification<T> n : toCatchUp) { <add> if (n != null) { <add> n.accept(subscriber); <add> } <add> } <add> } <add> } <add> public void removePendingSubscriber(Subscriber<? super T> subscriber) { <add> List<Notification<T>> toCatchUp = null; <add> synchronized (this) { <add> if (pendingSubscriptions == null) { <add> return; <add> } <add> for (int i = 0; i < pendingSubscriptions.size(); i += 2) { <add> @SuppressWarnings("unchecked") <add> SubjectObserver<? super T> so = (SubjectObserver<? super T>)pendingSubscriptions.get(i); <add> if (so.getActual() == subscriber && !so.caughtUp) { <add> @SuppressWarnings("unchecked") <add> List<Notification<T>> list = (List<Notification<T>>)pendingSubscriptions.get(i + 1); <add> toCatchUp = list; <add> so.caughtUp = true; <add> pendingSubscriptions.remove(i); <add> pendingSubscriptions.remove(i); <add> if (pendingSubscriptions.isEmpty()) { <add> pendingSubscriptions = null; <add> } <add> break; <add> } <add> } <add> } <add> if (toCatchUp != null) { <add> for (Notification<T> n : toCatchUp) { <add> if (n != null) { <add> n.accept(subscriber); <add> } <add> } <add> } <add> } <add> public void replayAllPending() { <add> List<Object> localPending; <add> synchronized (this) { <add> localPending = pendingSubscriptions; <add> pendingSubscriptions = null; <add> } <add> if (localPending != null) { <add> for (int i = 0; i < localPending.size(); i += 2) { <add> @SuppressWarnings("unchecked") <add> SubjectObserver<? super T> so = (SubjectObserver<? super T>)localPending.get(i); <add> if (!so.caughtUp) { <add> @SuppressWarnings("unchecked") <add> List<Notification<T>> list = (List<Notification<T>>)localPending.get(i + 1); <add> for (Notification<T> v : list) { <add> if (v != null) { <add> v.accept(so); <add> } <add> } <add> so.caughtUp = true; <add> } <add> } <add> } <add> } <add> } <add> <add> private final State<T> state; <ide> private final SubjectSubscriptionManager<T> subscriptionManager; <del> final AtomicReference<Notification<T>> lastNotification; <ide> <del> protected BehaviorSubject(OnSubscribe<T> onSubscribe, SubjectSubscriptionManager<T> subscriptionManager, AtomicReference<Notification<T>> lastNotification) { <add> protected BehaviorSubject(OnSubscribe<T> onSubscribe, SubjectSubscriptionManager<T> subscriptionManager, <add> State<T> state) { <ide> super(onSubscribe); <ide> this.subscriptionManager = subscriptionManager; <del> this.lastNotification = lastNotification; <add> this.state = state; <ide> } <ide> <ide> @Override <ide> public void onCompleted() { <ide> <ide> @Override <ide> public void call() { <del> lastNotification.set(Notification.<T> createOnCompleted()); <add> final Notification<T> ne = Notification.<T>createOnCompleted(); <add> state.bufferValue(ne); <add> state.lastNotification.set(ne); <ide> } <ide> }); <ide> if (observers != null) { <add> state.replayAllPending(); <ide> for (Observer<? super T> o : observers) { <ide> o.onCompleted(); <ide> } <ide> public void onError(final Throwable e) { <ide> <ide> @Override <ide> public void call() { <del> lastNotification.set(Notification.<T> createOnError(e)); <add> final Notification<T> ne = Notification.<T>createOnError(e); <add> state.bufferValue(ne); <add> state.lastNotification.set(ne); <ide> } <ide> }); <ide> if (observers != null) { <add> state.replayAllPending(); <ide> for (Observer<? super T> o : observers) { <ide> o.onError(e); <ide> } <ide> public void call() { <ide> public void onNext(T v) { <ide> // do not overwrite a terminal notification <ide> // so new subscribers can get them <del> if (lastNotification.get().isOnNext()) { <del> lastNotification.set(Notification.createOnNext(v)); <del> for (Observer<? super T> o : subscriptionManager.rawSnapshot()) { <del> o.onNext(v); <add> Notification<T> last = state.lastNotification.get(); <add> if (last == null || last.isOnNext()) { <add> Notification<T> n = Notification.createOnNext(v); <add> state.bufferValue(n); <add> state.lastNotification.set(n); <add> <add> for (SubjectObserver<? super T> o : subscriptionManager.rawSnapshot()) { <add> if (o.caughtUp) { <add> o.onNext(v); <add> } else { <add> state.removePending(o); <add> } <ide> } <ide> } <ide> } <del> <ide> } <ide><path>rxjava-core/src/main/java/rx/subjects/SubjectSubscriptionManager.java <ide> public void onError(Throwable e) { <ide> public void onNext(T v) { <ide> this.actual.onNext(v); <ide> } <del> <add> Observer<? super T> getActual() { <add> return actual; <add> } <ide> } <ide> <ide> } <ide>\ No newline at end of file <ide><path>rxjava-core/src/test/java/rx/subjects/BehaviorSubjectTest.java <ide> public void onCompleted() { <ide> verify(o, never()).onError(any(Throwable.class)); <ide> } <ide> } <add> @Test <add> public void testStartEmpty() { <add> BehaviorSubject<Integer> source = BehaviorSubject.create(); <add> @SuppressWarnings("unchecked") <add> final Observer<Object> o = mock(Observer.class); <add> InOrder inOrder = inOrder(o); <add> <add> source.subscribe(o); <add> <add> inOrder.verify(o, never()).onNext(any()); <add> inOrder.verify(o, never()).onCompleted(); <add> <add> source.onNext(1); <add> <add> source.onCompleted(); <add> <add> source.onNext(2); <add> <add> inOrder.verify(o).onNext(1); <add> inOrder.verify(o).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> <add> verify(o, never()).onError(any(Throwable.class)); <add> <add> } <add> @Test <add> public void testStartEmptyThenAddOne() { <add> BehaviorSubject<Integer> source = BehaviorSubject.create(); <add> @SuppressWarnings("unchecked") <add> final Observer<Object> o = mock(Observer.class); <add> InOrder inOrder = inOrder(o); <add> <add> source.onNext(1); <add> <add> source.subscribe(o); <add> <add> inOrder.verify(o).onNext(1); <add> <add> source.onCompleted(); <add> <add> source.onNext(2); <add> <add> inOrder.verify(o).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> <add> verify(o, never()).onError(any(Throwable.class)); <add> <add> } <add> @Test <add> public void testStartEmptyCompleteWithOne() { <add> BehaviorSubject<Integer> source = BehaviorSubject.create(); <add> @SuppressWarnings("unchecked") <add> final Observer<Object> o = mock(Observer.class); <add> <add> source.onNext(1); <add> source.onCompleted(); <add> <add> source.onNext(2); <add> <add> source.subscribe(o); <add> <add> verify(o).onCompleted(); <add> verify(o, never()).onError(any(Throwable.class)); <add> verify(o, never()).onNext(any()); <add> } <ide> }
3
PHP
PHP
add doc for _basename()
902e05e75f81131bab03d246eb89b3599955be13
<ide><path>src/Filesystem/File.php <ide> public function name() <ide> /** <ide> * Returns the file basename. simulate the php basename(). <ide> * <add> * @param string $path Path to file <add> * @param string|null $ext The name of the extension <ide> * @return string the file basename. <ide> */ <del> protected function _basename($name, $ext = null) <add> protected function _basename($path, $ext = null) <ide> { <del> $splInfo = new SplFileInfo($name); <add> $splInfo = new SplFileInfo($path); <ide> $name = ltrim($splInfo->getFilename(), DS); <ide> if ($ext === null || rtrim($name, $ext) === '') { <ide> return $name;
1
PHP
PHP
add templatevars support to widgets
146d7c81e9ed650265befed0b68f7dfe2719e68c
<ide><path>src/View/Widget/ButtonWidget.php <ide> public function render(array $data, ContextInterface $context) <ide> 'text' => '', <ide> 'type' => 'submit', <ide> 'escape' => false, <add> 'templateVars' => [] <ide> ]; <ide> return $this->_templates->format('button', [ <ide> 'text' => $data['escape'] ? h($data['text']) : $data['text'], <add> 'templateVars' => $data['templateVars'], <ide> 'attrs' => $this->_templates->formatAttributes($data, ['text']), <ide> ]); <ide> } <ide><path>src/View/Widget/CheckboxWidget.php <ide> public function render(array $data, ContextInterface $context) <ide> 'value' => 1, <ide> 'val' => null, <ide> 'disabled' => false, <add> 'templateVars' => [] <ide> ]; <ide> if ($this->_isChecked($data)) { <ide> $data['checked'] = true; <ide> public function render(array $data, ContextInterface $context) <ide> return $this->_templates->format('checkbox', [ <ide> 'name' => $data['name'], <ide> 'value' => $data['value'], <add> 'templateVars' => $data['templateVars'], <ide> 'attrs' => $attrs <ide> ]); <ide> } <ide><path>src/View/Widget/DateTimeWidget.php <ide> public function render(array $data, ContextInterface $context) <ide> <ide> $selected = $this->_deconstructDate($data['val'], $data); <ide> <del> $templateOptions = []; <add> $templateOptions = ['templateVars' => $data['templateVars']]; <ide> foreach ($this->_selects as $select) { <ide> if ($data[$select] === false || $data[$select] === null) { <ide> $templateOptions[$select] = ''; <ide> protected function _normalizeData($data) <ide> 'minute' => [], <ide> 'second' => [], <ide> 'meridian' => null, <add> 'templateVars' => [], <ide> ]; <ide> <ide> $timeFormat = isset($data['hour']['format']) ? $data['hour']['format'] : null; <ide><path>src/View/Widget/FileWidget.php <ide> public function render(array $data, ContextInterface $context) <ide> $data += [ <ide> 'name' => '', <ide> 'escape' => true, <add> 'templateVars' => [], <ide> ]; <ide> unset($data['val']); <ide> <ide> return $this->_templates->format('file', [ <ide> 'name' => $data['name'], <add> 'templateVars' => $data['templateVars'], <ide> 'attrs' => $this->_templates->formatAttributes( <ide> $data, <ide> ['name', 'val'] <ide><path>src/View/Widget/MultiCheckboxWidget.php <ide> public function render(array $data, ContextInterface $context) <ide> 'options' => [], <ide> 'disabled' => null, <ide> 'val' => null, <del> 'idPrefix' => null <add> 'idPrefix' => null, <add> 'templateVars' => [] <ide> ]; <ide> $out = []; <ide> $this->_idPrefix = $data['idPrefix']; <ide> public function render(array $data, ContextInterface $context) <ide> $checkbox = [ <ide> 'value' => $key, <ide> 'text' => $val, <add> 'templateVars' => $data['templateVars'] <ide> ]; <ide> if (is_array($val) && isset($val['text'], $val['value'])) { <ide> $checkbox = $val; <ide><path>src/View/Widget/RadioWidget.php <ide> public function render(array $data, ContextInterface $context) <ide> 'escape' => true, <ide> 'label' => true, <ide> 'empty' => false, <del> 'idPrefix' => null <add> 'idPrefix' => null, <add> 'templateVars' => [], <ide> ]; <ide> if ($data['options'] instanceof Traversable) { <ide> $options = iterator_to_array($data['options']); <ide> protected function _renderInput($val, $text, $data, $context) <ide> $input = $this->_templates->format('radio', [ <ide> 'name' => $radio['name'], <ide> 'value' => $escape ? h($radio['value']) : $radio['value'], <add> 'templateVars' => $data['templateVars'], <ide> 'attrs' => $this->_templates->formatAttributes($radio, ['name', 'value', 'text']), <ide> ]); <ide> <ide> protected function _renderInput($val, $text, $data, $context) <ide> return $this->_templates->format('radioWrapper', [ <ide> 'input' => $input, <ide> 'label' => $label, <add> 'templateVars' => $data['templateVars'], <ide> ]); <ide> } <ide> <ide><path>src/View/Widget/SelectBoxWidget.php <ide> public function render(array $data, ContextInterface $context) <ide> 'options' => [], <ide> 'disabled' => null, <ide> 'val' => null, <add> 'templateVars' => [] <ide> ]; <ide> <ide> $options = $this->_renderContent($data); <ide> public function render(array $data, ContextInterface $context) <ide> $attrs = $this->_templates->formatAttributes($data); <ide> return $this->_templates->format($template, [ <ide> 'name' => $name, <add> 'templateVars' => $data['templateVars'], <ide> 'attrs' => $attrs, <ide> 'content' => implode('', $options), <ide> ]); <ide><path>src/View/Widget/TextareaWidget.php <ide> public function render(array $data, ContextInterface $context) <ide> 'val' => '', <ide> 'name' => '', <ide> 'escape' => true, <del> 'rows' => 5 <add> 'rows' => 5, <add> 'templateVars' => [] <ide> ]; <ide> return $this->_templates->format('textarea', [ <ide> 'name' => $data['name'], <ide> 'value' => $data['escape'] ? h($data['val']) : $data['val'], <add> 'templateVars' => $data['templateVars'], <ide> 'attrs' => $this->_templates->formatAttributes( <ide> $data, <ide> ['name', 'val']
8
Text
Text
add note about getconfig
cfe748d4b5c1ec7ef9ec4adc4bec534a9616aed8
<ide><path>readme.md <ide> module.exports = { <ide> ```js <ide> // pages/index.js <ide> import getConfig from 'next/config' <del>const {serverRuntimeConfig, publicRuntimeConfig} = getConfig() <add>const {serverRuntimeConfig, publicRuntimeConfig} = getConfig() // Only holds serverRuntimeConfig and publicRuntimeConfig from next.config.js nothing else. <ide> <ide> console.log(serverRuntimeConfig.mySecret) // Will only be available on the server side <ide> console.log(publicRuntimeConfig.staticFolder) // Will be available on both server and client
1
Ruby
Ruby
move default pub_date value
e7d3b2cb3116cdd5354c443b0534e50b26ce6113
<ide><path>Library/Homebrew/livecheck/strategy/sparkle.rb <ide> def self.item_from_content(content) <ide> version ||= (item > "version").first&.text&.strip <ide> <ide> title = (item > "title").first&.text&.strip <del> pub_date = (item > "pubDate").first&.text&.strip&.yield_self { |d| Time.parse(d) } || Time.new(0) <add> pub_date = (item > "pubDate").first&.text&.strip&.yield_self { |d| Time.parse(d) } <ide> <ide> if (match = title&.match(/(\d+(?:\.\d+)*)\s*(\([^)]+\))?\Z/)) <ide> short_version ||= match[1] <ide> def self.item_from_content(content) <ide> <ide> data = { <ide> title: title, <del> pub_date: pub_date, <add> pub_date: pub_date || Time.new(0), <ide> url: url, <ide> bundle_version: bundle_version, <ide> }.compact
1
Text
Text
add readme for explosion-bot
29afbdb91e5fecf513125a85f1ac1d165f40bc93
<ide><path>extra/DEVELOPER_DOCS/ExplosionBot.md <add># Explosion-bot <add> <add>Explosion-bot is a robot that can be invoked to help with running particular test commands. <add> <add>## Permissions <add> <add>Only maintainers have permissions to summon explosion-bot. Each of the open source repos that use explosion-bot has its own team(s) of maintainers, and only github users who are members of those teams can successfully run bot commands. <add> <add>## Running robot commands <add> <add>To summon the robot, write a github comment on the issue/PR you wish to test. The comment must be in the following format: <add> <add>``` <add>@explosion-bot please test_gpu <add>``` <add> <add>Some things to note: <add> <add>* The `@explosion-bot please` must be the beginning of the command - you cannot add anything in front of this or else the robot won't know how to parse it. Adding anything at the end aside from the test name will also confuse the robot, so keep it simple! <add>* The command name (such as `test_gpu`) must be one of the tests that the bot knows how to run. The available commands are documented in the bot's [workflow config](https://github.com/explosion/spaCy/blob/master/.github/workflows/explosionbot.yml#L26) and must match exactly one of the commands listed there. <add>* The robot can't do multiple things at once, so if you want it to run multiple tests, you'll have to summon it with one comment per test. <add>* For the `test_gpu` command, you can specify an optional thinc branch (from the spaCy repo) or a spaCy branch (from the thinc repo) with either the `--thinc-branch` or `--spacy-branch` flags. By default, the bot will pull in the PR branch from the repo where the command was issued, and the main branch of the other repository. However, if you need to run against another branch, you can say (for example): <add> <add>``` <add>@explosion-bot please test_gpu --thinc-branch develop <add>``` <add> <add>## Troubleshooting <add> <add>If the robot isn't responding to commands as expected, you can check its logs in the [Github Action](https://github.com/explosion/spaCy/actions/workflows/explosionbot.yml). <add> <add>For each command sent to the bot, there should be a run of the `explosion-bot` workflow. In the `Install and run explosion-bot` step, towards the ends of the logs you should see info about the configuration that the bot was run with, as well as any errors that the bot encountered. <ide>\ No newline at end of file
1
Javascript
Javascript
fix jshint error in ember-debug/main
12bca9f7fcdc7701e61f1f84af50919c0065e7af
<ide><path>packages/ember-debug/lib/main.js <del>/*global __fail__*/ <del> <ide> import Ember from 'ember-metal/core'; <ide> import { registerDebugFunction } from 'ember-metal/assert'; <ide> import isEnabled, { FEATURES } from 'ember-metal/features';
1
Python
Python
improve speed to run `airflow` by 6x
1a8a897120762692ca98ac5ce4da881678c073aa
<ide><path>airflow/exceptions.py <ide> import warnings <ide> from typing import Any, Dict, List, NamedTuple, Optional, Sized <ide> <del>from airflow.api_connexion.exceptions import NotFound as ApiConnexionNotFound <del>from airflow.utils.code_utils import prepare_code_snippet <del>from airflow.utils.platform import is_tty <del> <ide> <ide> class AirflowException(Exception): <ide> """ <ide> class AirflowBadRequest(AirflowException): <ide> status_code = 400 <ide> <ide> <del>class AirflowNotFoundException(AirflowException, ApiConnexionNotFound): <add>class AirflowNotFoundException(AirflowException): <ide> """Raise when the requested object/resource is not available in the system.""" <ide> <ide> status_code = 404 <ide> def __init__(self, msg: str, file_path: str, parse_errors: List[FileSyntaxError] <ide> self.parse_errors = parse_errors <ide> <ide> def __str__(self): <add> from airflow.utils.code_utils import prepare_code_snippet <add> from airflow.utils.platform import is_tty <add> <ide> result = f"{self.msg}\nFilename: {self.file_path}\n\n" <ide> <ide> for error_no, parse_error in enumerate(self.parse_errors, 1): <ide><path>airflow/executors/executor_loader.py <ide> import logging <ide> from contextlib import suppress <ide> from enum import Enum, unique <del>from typing import Optional, Tuple, Type <add>from typing import TYPE_CHECKING, Optional, Tuple, Type <ide> <ide> from airflow.exceptions import AirflowConfigException <del>from airflow.executors.base_executor import BaseExecutor <ide> from airflow.executors.executor_constants import ( <ide> CELERY_EXECUTOR, <ide> CELERY_KUBERNETES_EXECUTOR, <ide> <ide> log = logging.getLogger(__name__) <ide> <add>if TYPE_CHECKING: <add> from airflow.executors.base_executor import BaseExecutor <add> <ide> <ide> @unique <ide> class ConnectorSource(Enum): <ide> class ConnectorSource(Enum): <ide> class ExecutorLoader: <ide> """Keeps constants for all the currently available executors.""" <ide> <del> _default_executor: Optional[BaseExecutor] = None <add> _default_executor: Optional["BaseExecutor"] = None <ide> executors = { <ide> LOCAL_EXECUTOR: 'airflow.executors.local_executor.LocalExecutor', <ide> SEQUENTIAL_EXECUTOR: 'airflow.executors.sequential_executor.SequentialExecutor', <ide> class ExecutorLoader: <ide> } <ide> <ide> @classmethod <del> def get_default_executor(cls) -> BaseExecutor: <add> def get_default_executor(cls) -> "BaseExecutor": <ide> """Creates a new instance of the configured executor if none exists and returns it""" <ide> if cls._default_executor is not None: <ide> return cls._default_executor <ide> def get_default_executor(cls) -> BaseExecutor: <ide> return cls._default_executor <ide> <ide> @classmethod <del> def load_executor(cls, executor_name: str) -> BaseExecutor: <add> def load_executor(cls, executor_name: str) -> "BaseExecutor": <ide> """ <ide> Loads the executor. <ide> <ide> def load_executor(cls, executor_name: str) -> BaseExecutor: <ide> return executor_cls() <ide> <ide> @classmethod <del> def import_executor_cls(cls, executor_name: str) -> Tuple[Type[BaseExecutor], ConnectorSource]: <add> def import_executor_cls(cls, executor_name: str) -> Tuple[Type["BaseExecutor"], ConnectorSource]: <ide> """ <ide> Imports the executor class. <ide> <ide> def import_executor_cls(cls, executor_name: str) -> Tuple[Type[BaseExecutor], Co <ide> return import_string(executor_name), ConnectorSource.CUSTOM_PATH <ide> <ide> @classmethod <del> def __load_celery_kubernetes_executor(cls) -> BaseExecutor: <add> def __load_celery_kubernetes_executor(cls) -> "BaseExecutor": <ide> """:return: an instance of CeleryKubernetesExecutor""" <ide> celery_executor = import_string(cls.executors[CELERY_EXECUTOR])() <ide> kubernetes_executor = import_string(cls.executors[KUBERNETES_EXECUTOR])() <ide><path>airflow/models/param.py <ide> import warnings <ide> from typing import Any, Dict, ItemsView, MutableMapping, Optional, ValuesView <ide> <del>import jsonschema <del>from jsonschema import FormatChecker <del>from jsonschema.exceptions import ValidationError <del> <ide> from airflow.exceptions import AirflowException, ParamValidationError <ide> from airflow.utils.context import Context <ide> from airflow.utils.types import NOTSET, ArgNotSet <ide> def resolve(self, value: Any = NOTSET, suppress_exception: bool = False) -> Any: <ide> :param suppress_exception: To raise an exception or not when the validations fails. <ide> If true and validations fails, the return value would be None. <ide> """ <add> import jsonschema <add> from jsonschema import FormatChecker <add> from jsonschema.exceptions import ValidationError <add> <ide> try: <ide> json.dumps(value) <ide> except Exception: <ide><path>airflow/models/taskinstance.py <ide> from airflow.utils.state import DagRunState, State, TaskInstanceState <ide> from airflow.utils.timeout import timeout <ide> <del>try: <del> from kubernetes.client.api_client import ApiClient <del> <del> from airflow.kubernetes.kube_config import KubeConfig <del> from airflow.kubernetes.pod_generator import PodGenerator <del>except ImportError: <del> ApiClient = None <del> <ide> TR = TaskReschedule <ide> <ide> _CURRENT_CONTEXT: List[Context] = [] <ide> def render_templates(self, context: Optional[Context] = None) -> None: <ide> <ide> def render_k8s_pod_yaml(self) -> Optional[dict]: <ide> """Render k8s pod yaml""" <add> from kubernetes.client.api_client import ApiClient <add> <add> from airflow.kubernetes.kube_config import KubeConfig <ide> from airflow.kubernetes.kubernetes_helper_functions import create_pod_id # Circular import <add> from airflow.kubernetes.pod_generator import PodGenerator <ide> <ide> kube_config = KubeConfig() <ide> pod = PodGenerator.construct_pod( <ide><path>airflow/serialization/serialized_objects.py <ide> from airflow.utils.module_loading import as_importable_string, import_string <ide> from airflow.utils.task_group import MappedTaskGroup, TaskGroup <ide> <del>try: <del> # isort: off <del> from kubernetes.client import models as k8s <del> from airflow.kubernetes.pod_generator import PodGenerator <del> <del> # isort: on <del> HAS_KUBERNETES = True <del>except ImportError: <del> HAS_KUBERNETES = False <del> <ide> if TYPE_CHECKING: <ide> from airflow.ti_deps.deps.base_ti_dep import BaseTIDep <ide> <add> HAS_KUBERNETES: bool <add> try: <add> from kubernetes.client import models as k8s <add> <add> from airflow.kubernetes.pod_generator import PodGenerator <add> except ImportError: <add> pass <add> <ide> log = logging.getLogger(__name__) <ide> <ide> _OPERATOR_EXTRA_LINKS: Set[str] = { <ide> def _serialize(cls, var: Any) -> Any: # Unfortunately there is no support for r <ide> return cls._encode({str(k): cls._serialize(v) for k, v in var.items()}, type_=DAT.DICT) <ide> elif isinstance(var, list): <ide> return [cls._serialize(v) for v in var] <del> elif HAS_KUBERNETES and isinstance(var, k8s.V1Pod): <add> elif _has_kubernetes() and isinstance(var, k8s.V1Pod): <ide> json_pod = PodGenerator.serialize_pod(var) <ide> return cls._encode(json_pod, type_=DAT.POD) <ide> elif isinstance(var, DAG): <ide> def _deserialize(cls, encoded_var: Any) -> Any: <ide> elif type_ == DAT.DATETIME: <ide> return pendulum.from_timestamp(var) <ide> elif type_ == DAT.POD: <del> if not HAS_KUBERNETES: <add> if not _has_kubernetes(): <ide> raise RuntimeError("Cannot deserialize POD objects without kubernetes libraries installed!") <ide> pod = PodGenerator.deserialize_model_dict(var) <ide> return pod <ide> class DagDependency: <ide> def node_id(self): <ide> """Node ID for graph rendering""" <ide> return f"{self.dependency_type}:{self.source}:{self.target}:{self.dependency_id}" <add> <add> <add>def _has_kubernetes() -> bool: <add> global HAS_KUBERNETES <add> if "HAS_KUBERNETES" in globals(): <add> return HAS_KUBERNETES <add> <add> # Loading kube modules is expensive, so delay it until the last moment <add> <add> try: <add> from kubernetes.client import models as k8s <add> <add> from airflow.kubernetes.pod_generator import PodGenerator <add> <add> globals()['k8s'] = k8s <add> globals()['PodGenerator'] = PodGenerator <add> <add> # isort: on <add> HAS_KUBERNETES = True <add> except ImportError: <add> HAS_KUBERNETES = False <add> return HAS_KUBERNETES <ide><path>airflow/utils/cli.py <ide> from airflow import settings <ide> from airflow.exceptions import AirflowException <ide> from airflow.utils import cli_action_loggers <del>from airflow.utils.db import check_and_run_migrations, synchronize_log_template <ide> from airflow.utils.log.non_caching_file_handler import NonCachingFileHandler <ide> from airflow.utils.platform import getuser, is_terminal_support_colors <ide> from airflow.utils.session import provide_session <ide> def wrapper(*args, **kwargs): <ide> try: <ide> # Check and run migrations if necessary <ide> if check_db: <add> from airflow.utils.db import check_and_run_migrations, synchronize_log_template <add> <ide> check_and_run_migrations() <ide> synchronize_log_template() <ide> return f(*args, **kwargs) <ide><path>airflow/utils/helpers.py <ide> ) <ide> from urllib import parse <ide> <del>import flask <del>import jinja2 <del>import jinja2.nativetypes <del> <ide> from airflow.configuration import conf <ide> from airflow.exceptions import AirflowException <ide> from airflow.utils.module_loading import import_string <ide> <ide> if TYPE_CHECKING: <add> import jinja2 <add> <ide> from airflow.models import TaskInstance <ide> <ide> KEY_REGEX = re.compile(r'^[\w.-]+$') <ide> def as_flattened_list(iterable: Iterable[Iterable[T]]) -> List[T]: <ide> return [e for i in iterable for e in i] <ide> <ide> <del>def parse_template_string(template_string: str) -> Tuple[Optional[str], Optional[jinja2.Template]]: <add>def parse_template_string(template_string: str) -> Tuple[Optional[str], Optional["jinja2.Template"]]: <ide> """Parses Jinja template string.""" <add> import jinja2 <add> <ide> if "{{" in template_string: # jinja mode <ide> return None, jinja2.Template(template_string) <ide> else: <ide> def build_airflow_url_with_query(query: Dict[str, Any]) -> str: <ide> For example: <ide> 'http://0.0.0.0:8000/base/graph?dag_id=my-task&root=&execution_date=2020-10-27T10%3A59%3A25.615587 <ide> """ <add> import flask <add> <ide> view = conf.get('webserver', 'dag_default_view').lower() <ide> url = flask.url_for(f"Airflow.{view}") <ide> return f"{url}?{parse.urlencode(query)}" <ide> def render_template(template: Any, context: MutableMapping[str, Any], *, native: <ide> except Exception: <ide> env.handle_exception() # Rewrite traceback to point to the template. <ide> if native: <add> import jinja2.nativetypes <add> <ide> return jinja2.nativetypes.native_concat(nodes) <ide> return "".join(nodes) <ide> <ide> <del>def render_template_to_string(template: jinja2.Template, context: MutableMapping[str, Any]) -> str: <add>def render_template_to_string(template: "jinja2.Template", context: MutableMapping[str, Any]) -> str: <ide> """Shorthand to ``render_template(native=False)`` with better typing support.""" <ide> return render_template(template, context, native=False) <ide> <ide> <del>def render_template_as_native(template: jinja2.Template, context: MutableMapping[str, Any]) -> Any: <add>def render_template_as_native(template: "jinja2.Template", context: MutableMapping[str, Any]) -> Any: <ide> """Shorthand to ``render_template(native=True)`` with better typing support.""" <ide> return render_template(template, context, native=True) <ide> <ide><path>airflow/utils/log/file_task_handler.py <ide> from pathlib import Path <ide> from typing import TYPE_CHECKING, Optional <ide> <del>import httpx <ide> from itsdangerous import TimedJSONWebSignatureSerializer <ide> <ide> from airflow.configuration import AirflowConfigException, conf <ide> def _read(self, ti, try_number, metadata=None): <ide> except Exception as f: <ide> log += f'*** Unable to fetch logs from worker pod {ti.hostname} ***\n{str(f)}\n\n' <ide> else: <add> import httpx <add> <ide> url = os.path.join("http://{ti.hostname}:{worker_log_server_port}/log", log_relative_path).format( <ide> ti=ti, worker_log_server_port=conf.get('logging', 'WORKER_LOG_SERVER_PORT') <ide> )
8
Ruby
Ruby
improve relocatability check
c5bd5c4aa7f0595c91431407ff5bda4b1938afc3
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> def bottle_formula(f) <ide> relocatable = false if keg_contain?(cellar, keg, ignores) <ide> if prefix != prefix_check <ide> relocatable = false if keg_contain_absolute_symlink_starting_with?(prefix, keg) <add> relocatable = false if keg_contain?("#{prefix}/etc", keg, ignores) <add> relocatable = false if keg_contain?("#{prefix}/var", keg, ignores) <ide> end <ide> skip_relocation = relocatable && !keg.require_relocation? <ide> end
1
Javascript
Javascript
remove unused code and broken unittests
1ff28f8961155f32eb95b0c4de1f766fc5703fe7
<ide><path>lib/removeAndDo.js <del>/* <del> MIT License http://www.opensource.org/licenses/mit-license.php <del> Author Tobias Koppers @sokra <del>*/ <del>"use strict"; <del> <del>// TODO can this be deleted? <del>module.exports = (collection, thing, action) => { <del> const idx = this[collection].indexOf(thing); <del> const hasThingInCollection = idx >= 0; <del> if(hasThingInCollection) { <del> this[collection].splice(idx, 1); <del> thing[action](this); <del> } <del> return hasThingInCollection; <del>}; <ide><path>test/JsonpHotUpdateChunkTemplatePlugin.unittest.js <del>"use strict"; <del> <del>const should = require("should"); <del>const sinon = require("sinon"); <del>const ConcatSource = require("webpack-sources").ConcatSource; <del>const JsonpHotUpdateChunkTemplatePlugin = require("../lib/JsonpHotUpdateChunkTemplatePlugin"); <del>const applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); <del> <del>describe("JsonpHotUpdateChunkTemplatePlugin", () => { <del> let handlerContext; <del> <del> beforeEach(() => <del> handlerContext = { <del> outputOptions: { <del> hotUpdateFunction: "Foo", <del> library: "Bar" <del> } <del> }); <del> <del> it("has apply function", () => (new JsonpHotUpdateChunkTemplatePlugin()).apply.should.be.a.Function()); <del> <del> describe("when applied", () => { <del> let eventBindings, eventBinding; <del> <del> beforeEach(() => eventBindings = applyPluginWithOptions(JsonpHotUpdateChunkTemplatePlugin)); <del> <del> it("binds two event handlers", () => eventBindings.length.should.be.exactly(2)); <del> <del> describe("render handler", () => { <del> beforeEach(() => eventBinding = eventBindings[0]); <del> <del> it("binds to render event", () => eventBinding.name.should.be.exactly("render")); <del> <del> it("creates source wrapper with export", () => { <del> const source = eventBinding.handler.call(handlerContext, "moduleSource()", [], [], {}, 100); <del> source.should.be.instanceof(ConcatSource); <del> source.source().should.be.exactly("Foo(100,moduleSource())"); <del> }); <del> }); <del> <del> describe("hash handler", () => { <del> let hashMock; <del> <del> beforeEach(() => { <del> eventBinding = eventBindings[1]; <del> hashMock = { <del> update: sinon.spy() <del> }; <del> }); <del> <del> it("binds to hash event", () => eventBinding.name.should.be.exactly("hash")); <del> <del> it("updates hash object", () => { <del> eventBinding.handler.call(handlerContext, hashMock); <del> hashMock.update.callCount.should.be.exactly(4); <del> sinon.assert.calledWith(hashMock.update, "JsonpHotUpdateChunkTemplatePlugin"); <del> sinon.assert.calledWith(hashMock.update, "3"); <del> sinon.assert.calledWith(hashMock.update, "Foo"); <del> sinon.assert.calledWith(hashMock.update, "Bar"); <del> }); <del> }); <del> }); <del>}); <ide><path>test/NodeHotUpdateChunkTemplatePlugin.unittest.js <del>"use strict"; <del> <del>const should = require("should"); <del>const sinon = require("sinon"); <del>const ConcatSource = require("webpack-sources").ConcatSource; <del>const NodeHotUpdateChunkTemplatePlugin = require("../lib/node/NodeHotUpdateChunkTemplatePlugin"); <del>const applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); <del> <del>describe("NodeHotUpdateChunkTemplatePlugin", () => { <del> let handlerContext; <del> <del> beforeEach(() => { <del> handlerContext = { <del> outputOptions: { <del> hotUpdateFunction: "Foo", <del> library: "Bar" <del> } <del> }; <del> }); <del> <del> it("has apply function", () => (new NodeHotUpdateChunkTemplatePlugin()).apply.should.be.a.Function()); <del> <del> describe("when applied", () => { <del> let eventBindings, eventBinding; <del> <del> beforeEach(() => eventBindings = applyPluginWithOptions(NodeHotUpdateChunkTemplatePlugin)); <del> <del> it("binds two event handlers", () => eventBindings.length.should.be.exactly(2)); <del> <del> describe("render handler", () => { <del> beforeEach(() => eventBinding = eventBindings[0]); <del> <del> it("binds to render event", () => eventBinding.name.should.be.exactly("render")); <del> <del> it("creates source wrapper with export", () => { <del> const source = eventBinding.handler.call(handlerContext, "moduleSource()", [], [], {}, 100); <del> source.should.be.instanceof(ConcatSource); <del> source.source().should.be.exactly("exports.id = 100;\nexports.modules = moduleSource();"); <del> }); <del> }); <del> <del> describe("hash handler", () => { <del> let hashMock; <del> <del> beforeEach(() => { <del> eventBinding = eventBindings[1]; <del> hashMock = { <del> update: sinon.spy() <del> }; <del> }); <del> <del> it("binds to hash event", () => eventBinding.name.should.be.exactly("hash")); <del> <del> it("updates hash object", () => { <del> eventBinding.handler.call(handlerContext, hashMock); <del> hashMock.update.callCount.should.be.exactly(4); <del> sinon.assert.calledWith(hashMock.update, "NodeHotUpdateChunkTemplatePlugin"); <del> sinon.assert.calledWith(hashMock.update, "3"); <del> sinon.assert.calledWith(hashMock.update, "Foo"); <del> sinon.assert.calledWith(hashMock.update, "Bar"); <del> }); <del> }); <del> }); <del>}); <ide><path>test/WebWorkerChunkTemplatePlugin.unittest.js <del>"use strict"; <del> <del>const should = require("should"); <del>const sinon = require("sinon"); <del>const ConcatSource = require("webpack-sources").ConcatSource; <del>const WebWorkerChunkTemplatePlugin = require("../lib/webworker/WebWorkerChunkTemplatePlugin"); <del>const applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); <del> <del>describe("WebWorkerChunkTemplatePlugin", () => { <del> let handlerContext; <del> <del> beforeEach(() => { <del> handlerContext = { <del> outputOptions: { <del> chunkCallbackName: "Foo", <del> library: "Bar" <del> } <del> }; <del> }); <del> <del> it("has apply function", () => { <del> (new WebWorkerChunkTemplatePlugin()).apply.should.be.a.Function(); <del> }); <del> <del> describe("when applied", () => { <del> let eventBindings, eventBinding; <del> <del> beforeEach(() => { <del> eventBindings = applyPluginWithOptions(WebWorkerChunkTemplatePlugin); <del> }); <del> <del> it("binds two event handlers", () => { <del> eventBindings.length.should.be.exactly(2); <del> }); <del> <del> describe("render handler", () => { <del> beforeEach(() => { <del> eventBinding = eventBindings[0]; <del> }); <del> <del> it("binds to render event", () => { <del> eventBinding.name.should.be.exactly("render"); <del> }); <del> <del> describe("with chunk call back name set", () => { <del> it("creates source wrapper with function name", () => { <del> const source = eventBinding.handler.call(handlerContext, "modules()", { <del> ids: 100, <del> }); <del> source.should.be.instanceof(ConcatSource); <del> source.source().should.be.exactly("Foo(100,modules())"); <del> }); <del> }); <del> <del> describe("without chunk call back name set", () => { <del> it("creates source wrapper with library name", () => { <del> delete handlerContext.outputOptions.chunkCallbackName; <del> const source = eventBinding.handler.call(handlerContext, "modules()", { <del> ids: 100, <del> }); <del> source.should.be.instanceof(ConcatSource); <del> source.source().should.be.exactly("webpackChunkBar(100,modules())"); <del> }); <del> }); <del> }); <del> <del> describe("hash handler", () => { <del> var hashMock; <del> <del> beforeEach(() => { <del> eventBinding = eventBindings[1]; <del> hashMock = { <del> update: sinon.spy() <del> }; <del> }); <del> <del> it("binds to hash event", () => { <del> eventBinding.name.should.be.exactly("hash"); <del> }); <del> <del> it("updates hash object", () => { <del> eventBinding.handler.call(handlerContext, hashMock); <del> hashMock.update.callCount.should.be.exactly(4); <del> sinon.assert.calledWith(hashMock.update, "webworker"); <del> sinon.assert.calledWith(hashMock.update, "3"); <del> sinon.assert.calledWith(hashMock.update, "Foo"); <del> sinon.assert.calledWith(hashMock.update, "Bar"); <del> }); <del> }); <del> }); <del>}); <ide><path>test/WebWorkerHotUpdateChunkTemplatePlugin.unittest.js <del>"use strict"; <del> <del>const should = require("should"); <del>const sinon = require("sinon"); <del>const ConcatSource = require("webpack-sources").ConcatSource; <del>const WebWorkerHotUpdateChunkTemplatePlugin = require("../lib/webworker/WebWorkerHotUpdateChunkTemplatePlugin"); <del>const applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); <del> <del>describe("WebWorkerHotUpdateChunkTemplatePlugin", () => { <del> let handlerContext; <del> <del> beforeEach(() => { <del> handlerContext = { <del> outputOptions: { <del> hotUpdateFunction: "Foo", <del> library: "Bar" <del> } <del> }; <del> }); <del> <del> it("has apply function", () => (new WebWorkerHotUpdateChunkTemplatePlugin()).apply.should.be.a.Function()); <del> <del> describe("when applied", () => { <del> let eventBindings, eventBinding; <del> <del> beforeEach(() => eventBindings = applyPluginWithOptions(WebWorkerHotUpdateChunkTemplatePlugin)); <del> <del> it("binds two event handlers", () => eventBindings.length.should.be.exactly(2)); <del> <del> describe("render handler", () => { <del> beforeEach(() => eventBinding = eventBindings[0]); <del> <del> it("binds to render event", () => eventBinding.name.should.be.exactly("render")); <del> <del> describe("with hot update function name set", () => { <del> it("creates source wrapper with function name", () => { <del> const source = eventBinding.handler.call(handlerContext, "moduleSource()", [], [], {}, 100); <del> source.should.be.instanceof(ConcatSource); <del> source.source().should.be.exactly("Foo(100,moduleSource())"); <del> }); <del> }); <del> <del> describe("without hot update function name set", () => { <del> it("creates source wrapper with library name", () => { <del> delete handlerContext.outputOptions.hotUpdateFunction; <del> const source = eventBinding.handler.call(handlerContext, "moduleSource()", [], [], {}, 100); <del> source.should.be.instanceof(ConcatSource); <del> source.source().should.be.exactly("webpackHotUpdateBar(100,moduleSource())"); <del> }); <del> }); <del> }); <del> <del> describe("hash handler", () => { <del> let hashMock; <del> <del> beforeEach(() => { <del> eventBinding = eventBindings[1]; <del> hashMock = { <del> update: sinon.spy() <del> }; <del> }); <del> <del> it("binds to hash event", () => { <del> eventBinding.name.should.be.exactly("hash"); <del> }); <del> <del> it("updates hash object", () => { <del> eventBinding.handler.call(handlerContext, hashMock); <del> hashMock.update.callCount.should.be.exactly(4); <del> sinon.assert.calledWith(hashMock.update, "WebWorkerHotUpdateChunkTemplatePlugin"); <del> sinon.assert.calledWith(hashMock.update, "3"); <del> sinon.assert.calledWith(hashMock.update, "Foo"); <del> sinon.assert.calledWith(hashMock.update, "Bar"); <del> }); <del> }); <del> }); <del>}); <ide><path>test/WebWorkerMainTemplatePlugin.unittest.js <del>/* globals describe, beforeEach, it */ <del>"use strict"; <del> <del>require("should"); <del>const sinon = require("sinon"); <del>const WebWorkerMainTemplatePlugin = require("../lib/webworker/WebWorkerMainTemplatePlugin"); <del>const applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); <del> <del>const createMockChunk = (ids, chunks) => { <del> return { <del> ids: ids, <del> _chunks: new Set(chunks), <del> getChunks() { <del> return Array.from(this._chunks); <del> }, <del> getNumberOfChunks() { <del> return this._chunks.size; <del> } <del> }; <del>}; <del> <del>describe("WebWorkerMainTemplatePlugin", function() { <del> let env; <del> <del> beforeEach(() => { <del> env = {}; <del> }); <del> <del> it("has apply function", function() { <del> (new WebWorkerMainTemplatePlugin()).apply.should.be.a.Function(); <del> }); <del> <del> describe("when applied", function() { <del> beforeEach(function() { <del> env.eventBindings = applyPluginWithOptions(WebWorkerMainTemplatePlugin); <del> env.handlerContext = { <del> requireFn: "requireFn", <del> indent: (value) => typeof value === "string" ? value : value.join("\n"), <del> asString: (values) => values.join("\n"), <del> renderCurrentHashCode: (value) => value, <del> outputOptions: { <del> chunkFilename: "chunkFilename" <del> }, <del> applyPluginsWaterfall: (moduleName, fileName, data) => { <del> return `"${moduleName}${data.hash}${data.hashWithLength()}${data.chunk && data.chunk.id || ""}"`; <del> }, <del> renderAddModule: () => "renderAddModuleSource();", <del> }; <del> }); <del> <del> it("binds five event handlers", function() { <del> env.eventBindings.length.should.be.exactly(5); <del> }); <del> <del> describe("local-vars handler", function() { <del> beforeEach(() => { <del> env.eventBinding = env.eventBindings[0]; <del> }); <del> <del> it("binds to local-vars event", () => { <del> env.eventBinding.name.should.be.exactly("local-vars"); <del> }); <del> <del> describe("when no chunks are provided", () => { <del> beforeEach(() => { <del> const chunk = createMockChunk(); <del> env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk); <del> }); <del> <del> it("returns the original source", () => { <del> env.source.should.be.exactly("moduleSource()"); <del> }); <del> }); <del> <del> describe("when chunks are provided", () => { <del> beforeEach(() => { <del> const chunk = createMockChunk([1, 2, 3], [ <del> "foo", <del> "bar", <del> "baz" <del> ]); <del> env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, "abc123"); <del> }); <del> <del> it("returns the original source with installed mapping", () => { <del> env.source.should.be.exactly(` <del>moduleSource() <del> <del>// object to store loaded chunks <del>// "1" means "already loaded" <del>var installedChunks = { <del>1: 1, <del>2: 1, <del>3: 1 <del>}; <del>`.trim()); <del> }); <del> }); <del> }); <del> <del> describe("require-ensure handler", () => { <del> beforeEach(() => { <del> env.eventBinding = env.eventBindings[1]; <del> }); <del> <del> it("binds to require-ensure event", () => { <del> env.eventBinding.name.should.be.exactly("require-ensure"); <del> }); <del> <del> describe("when called", () => { <del> beforeEach(() => { <del> const chunk = createMockChunk(); <del> env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, "abc123"); <del> }); <del> <del> it("creates import scripts call and promise resolve", () => { <del> env.source.should.be.exactly(` <del>return new Promise(function(resolve) { <del>// "1" is the signal for "already loaded" <del>if(!installedChunks[chunkId]) { <del>importScripts("asset-path" + abc123 + "" + abc123 + "" + chunkId + ""); <del>} <del>resolve(); <del>}); <del>`.trim()); <del> }); <del> }); <del> }); <del> <del> describe("bootstrap handler", () => { <del> beforeEach(() => { <del> env.eventBinding = env.eventBindings[2]; <del> }); <del> <del> it("binds to bootstrap event", () => { <del> env.eventBinding.name.should.be.exactly("bootstrap"); <del> }); <del> <del> describe("when no chunks are provided", () => { <del> beforeEach(() => { <del> const chunk = createMockChunk(); <del> env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk); <del> }); <del> <del> it("returns the original source", () => { <del> env.source.should.be.exactly("moduleSource()"); <del> }); <del> }); <del> <del> describe("when chunks are provided", () => { <del> beforeEach(() => { <del> const chunk = createMockChunk([1, 2, 3], [ <del> "foo", <del> "bar", <del> "baz" <del> ]); <del> env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk); <del> }); <del> <del> it("returns the original source with chunk callback", () => { <del> env.source.should.be.exactly(` <del>moduleSource() <del>this["webpackChunk"] = function webpackChunkCallback(chunkIds, moreModules) { <del>for(var moduleId in moreModules) { <del>renderAddModuleSource(); <del>} <del>while(chunkIds.length) <del>installedChunks[chunkIds.pop()] = 1; <del>}; <del>`.trim()); <del> }); <del> }); <del> }); <del> <del> describe("hot-bootstrap handler", () => { <del> beforeEach(() => { <del> env.eventBinding = env.eventBindings[3]; <del> }); <del> <del> it("binds to hot-bootstrap event", () => { <del> env.eventBinding.name.should.be.exactly("hot-bootstrap"); <del> }); <del> <del> describe("when called", () => { <del> beforeEach(() => { <del> const chunk = createMockChunk(); <del> env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, "abc123"); <del> }); <del> <del> it("returns the original source with hot update callback", () => { <del> env.source.should.be.exactly(` <del>moduleSource() <del>var parentHotUpdateCallback = this["webpackHotUpdate"]; <del>this["webpackHotUpdate"] = function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars <del> hotAddUpdateChunk(chunkId, moreModules); <del> if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); <del>} ; <del> <del>function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars <del> importScripts(requireFn.p + "asset-path" + abc123 + "" + abc123 + "" + chunkId + ""); <del>} <del> <del>function hotDownloadManifest(requestTimeout) { // eslint-disable-line no-unused-vars <del> requestTimeout = requestTimeout || 10000; <del> return new Promise(function(resolve, reject) { <del> if(typeof XMLHttpRequest === "undefined") <del> return reject(new Error("No browser support")); <del> try { <del> var request = new XMLHttpRequest(); <del> var requestPath = requireFn.p + "asset-path" + abc123 + "" + abc123 + ""; <del> request.open("GET", requestPath, true); <del> request.timeout = requestTimeout; <del> request.send(null); <del> } catch(err) { <del> return reject(err); <del> } <del> request.onreadystatechange = function() { <del> if(request.readyState !== 4) return; <del> if(request.status === 0) { <del> // timeout <del> reject(new Error("Manifest request to " + requestPath + " timed out.")); <del> } else if(request.status === 404) { <del> // no update available <del> resolve(); <del> } else if(request.status !== 200 && request.status !== 304) { <del> // other failure <del> reject(new Error("Manifest request to " + requestPath + " failed.")); <del> } else { <del> // success <del> try { <del> var update = JSON.parse(request.responseText); <del> } catch(e) { <del> reject(e); <del> return; <del> } <del> resolve(update); <del> } <del> }; <del> }); <del>} <del> <del>function hotDisposeChunk(chunkId) { //eslint-disable-line no-unused-vars <del> delete installedChunks[chunkId]; <del>} <del>`.trim()); <del> }); <del> }); <del> }); <del> <del> describe("hash handler", () => { <del> beforeEach(() => { <del> env.eventBinding = env.eventBindings[4]; <del> env.handlerContext = { <del> outputOptions: { <del> publicPath: "Alpha", <del> filename: "Bravo", <del> chunkFilename: "Charlie", <del> chunkCallbackName: "Delta", <del> library: "Echo" <del> } <del> }; <del> env.hashMock = { <del> update: sinon.spy() <del> }; <del> env.eventBinding.handler.call(env.handlerContext, env.hashMock); <del> }); <del> <del> it("binds to hash event", () => { <del> env.eventBinding.name.should.be.exactly("hash"); <del> }); <del> <del> it("updates hash object", () => { <del> env.hashMock.update.callCount.should.be.exactly(7); <del> sinon.assert.calledWith(env.hashMock.update, "webworker"); <del> sinon.assert.calledWith(env.hashMock.update, "3"); <del> sinon.assert.calledWith(env.hashMock.update, "Alpha"); <del> sinon.assert.calledWith(env.hashMock.update, "Bravo"); <del> sinon.assert.calledWith(env.hashMock.update, "Charlie"); <del> sinon.assert.calledWith(env.hashMock.update, "Delta"); <del> sinon.assert.calledWith(env.hashMock.update, "Echo"); <del> }); <del> }); <del> }); <del>}); <ide><path>test/removeAndDo.unittest.js <del>/* globals describe, it, beforeEach */ <del>"use strict"; <del> <del>const should = require("should"); <del>const sinon = require("sinon"); <del>const removeAndDo = require("../lib/removeAndDo"); <del> <del>describe("removeAndDo", () => { <del> let actionSpy; <del> let thingsMock; <del> let contextMock; <del> let anotherThingsMock; <del> <del> beforeEach(() => { <del> actionSpy = sinon.spy(); <del> thingsMock = { <del> action: actionSpy <del> }; <del> anotherThingsMock = { <del> action: actionSpy <del> }; <del> contextMock = { <del> context: [thingsMock] <del> }; <del> }); <del> <del> it("should return true", () => { <del> should(removeAndDo.bind(contextMock)('context', thingsMock, 'action')).be.eql(true); <del> actionSpy.callCount.should.be.exactly(1); <del> }); <del> <del> it("should return false", () => { <del> should(removeAndDo.bind(contextMock)('context', anotherThingsMock, 'anotherAction')).be.eql(false); <del> actionSpy.callCount.should.be.exactly(0); <del> }); <del>});
7
Text
Text
fix wrong feature description in changelog
b4a89489ae0ba3b399aeb05e599bb8072a462c6e
<ide><path>CHANGELOG.md <ide> ### Bug fixes <ide> <ide> - Add missing 'Names' field to /containers/json API output <del>- Make `docker rmi --dangling` safe when pulling <add>- Make `docker rmi` of dangling images safe while pulling <ide> - Devicemapper: Change default basesize to 100G <ide> - Go Scheduler issue with sync.Mutex and gcc <ide> - Fix issue where Search API endpoint would panic due to empty AuthConfig
1
Javascript
Javascript
improve string (de)serialization
227c16b9a8a406173c626b5f562a838417bc20b9
<ide><path>lib/serialization/BinaryMiddleware.js <ide> BooleansSection -> TrueHeaderByte | FalseHeaderByte | BooleansSectionHeaderByte <ide> F64NumbersSection -> F64NumbersSectionHeaderByte f64* <ide> I32NumbersSection -> I32NumbersSectionHeaderByte i32* <ide> I8NumbersSection -> I8NumbersSectionHeaderByte i8* <del>ShortStringSection -> ShortStringSectionHeaderByte utf8-byte* <add>ShortStringSection -> ShortStringSectionHeaderByte ascii-byte* <ide> StringSection -> StringSectionHeaderByte i32:length utf8-byte* <ide> BufferSection -> BufferSectionHeaderByte i32:length byte* <ide> NopSection --> NopSectionHeaderByte <ide> class BinaryMiddleware extends SerializerMiddleware { <ide> } <ide> case "string": { <ide> const len = Buffer.byteLength(thing); <del> if (len >= 128) { <add> if (len >= 128 || len !== thing.length) { <ide> allocate(len + HEADER_SIZE + I32_SIZE); <ide> writeU8(STRING_HEADER); <ide> writeU32(len); <add> currentBuffer.write(thing, currentPosition); <ide> } else { <ide> allocate(len + HEADER_SIZE); <ide> writeU8(SHORT_STRING_HEADER | len); <add> currentBuffer.write(thing, currentPosition, "latin1"); <ide> } <del> currentBuffer.write(thing, currentPosition); <ide> currentPosition += len; <ide> break; <ide> } <ide> class BinaryMiddleware extends SerializerMiddleware { <ide> } <ide> case STRING_HEADER: { <ide> const len = readU32(); <del> const buf = read(len); <del> result.push(buf.toString()); <add> if (isInCurrentBuffer(len)) { <add> result.push( <add> currentBuffer.toString( <add> undefined, <add> currentPosition, <add> currentPosition + len <add> ) <add> ); <add> currentPosition += len; <add> checkOverflow(); <add> } else { <add> const buf = read(len); <add> result.push(buf.toString()); <add> } <ide> break; <ide> } <ide> default: <ide> class BinaryMiddleware extends SerializerMiddleware { <ide> const len = header & SHORT_STRING_LENGTH_MASK; <ide> if (len === 0) { <ide> result.push(""); <add> } else if (isInCurrentBuffer(len)) { <add> result.push( <add> currentBuffer.toString( <add> "latin1", <add> currentPosition, <add> currentPosition + len <add> ) <add> ); <add> currentPosition += len; <add> checkOverflow(); <ide> } else { <ide> const buf = read(len); <del> result.push(buf.toString()); <add> result.push(buf.toString("latin1")); <ide> } <ide> } else if ((header & NUMBERS_HEADER_MASK) === F64_HEADER) { <ide> const len = (header & NUMBERS_COUNT_MASK) + 1; <ide><path>test/BinaryMiddleware.unittest.js <ide> const cont = (base, count) => { <ide> }; <ide> <ide> describe("BinaryMiddleware", () => { <add> const items = [ <add> undefined, <add> true, <add> false, <add> null, <add> "", <add> "hi", <add> "hi".repeat(200), <add> "😀", <add> "😀".repeat(200), <add> Buffer.from("hello"), <add> 1, <add> 11, <add> 0x100, <add> -1, <add> -11, <add> -0x100, <add> -1.25 <add> ]; <add> <ide> const cases = [ <del> [true], <del> [false], <del> [null], <del> [""], <del> ["hi"], <del> [Buffer.from("hello")], <del> [1], <del> [11], <del> [0x100], <del> [-1], <del> [-11], <del> [-0x100], <del> [-1.25], <add> ...items.map(item => [item]), <ide> [true, true], <ide> [false, true], <ide> [true, false], <ide> describe("BinaryMiddleware", () => { <ide> cont([false, true, false, true], 133), <ide> cont([false, true, false, true], 134), <ide> cont([false, true, false, true], 135), <del> cont([true], 135) <del> ]; <del> <del> const items = [ <del> undefined, <del> true, <del> false, <del> null, <del> "", <del> "hi", <del> Buffer.from("hello"), <del> 1, <del> 11, <del> 0x100, <del> -1, <del> -11, <del> -0x100, <del> -1.25 <add> cont([true], 135), <add> [null], <add> [null, null], <add> [null, null, null], <add> cont([null], 4), <add> cont([null], 100), <add> cont([null], 300), <add> cont([-20], 20), <add> cont([400], 20), <add> cont([5.5], 20) <ide> ]; <ide> <ide> for (const caseData of cases) { <ide> describe("BinaryMiddleware", () => { <ide> const data = [prepend, ...caseData, append].filter( <ide> x => x !== undefined <ide> ); <add> if (data.length === 0) continue; <ide> const key = JSON.stringify(data); <ide> it(`should serialize ${key} (${data.length}) correctly`, () => { <ide> const mw = new BinaryMiddleware();
2
Go
Go
add unit test for expose cache
7b89af2a08b65fac064603cb3b5eb8e091e2c076
<ide><path>integration/buildfile_test.go <ide> import ( <ide> "github.com/dotcloud/docker/archive" <ide> "github.com/dotcloud/docker/engine" <ide> "github.com/dotcloud/docker/image" <add> "github.com/dotcloud/docker/nat" <ide> "github.com/dotcloud/docker/utils" <ide> "io/ioutil" <ide> "net" <ide> func TestBuildExpose(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> if img.Config.PortSpecs[0] != "4243" { <add> if _, exists := img.Config.ExposedPorts[nat.NewPort("tcp", "4243")]; !exists { <ide> t.Fail() <ide> } <ide> } <ide> func TestBuildImageWithCache(t *testing.T) { <ide> checkCacheBehavior(t, template, true) <ide> } <ide> <add>func TestBuildExposeWithCache(t *testing.T) { <add> template := testContextTemplate{` <add> from {IMAGE} <add> maintainer dockerio <add> expose 80 <add> run echo hello <add> `, <add> nil, nil} <add> checkCacheBehavior(t, template, true) <add>} <add> <ide> func TestBuildImageWithoutCache(t *testing.T) { <ide> template := testContextTemplate{` <ide> from {IMAGE} <ide> func TestBuildInheritance(t *testing.T) { <ide> } <ide> <ide> // from parent <del> if img.Config.PortSpecs[0] != "4243" { <add> if _, exists := img.Config.ExposedPorts[nat.NewPort("tcp", "4243")]; !exists { <ide> t.Fail() <ide> } <ide> }
1
PHP
PHP
use blade comments
88ecd387f62bd8a083ec1998d39d9b5d881e2b35
<ide><path>src/Illuminate/Notifications/resources/views/email.blade.php <ide> <ide> @endforeach <ide> <del><!-- Salutation --> <add>{{-- Salutation --}} <ide> @if (! empty($salutation)) <ide> {{ $salutation }} <ide> @else <ide> Regards,<br>{{ config('app.name') }} <ide> @endif <ide> <del><!-- Subcopy --> <add>{{-- Subcopy --}} <ide> @isset($actionText) <ide> @component('mail::subcopy') <ide> If you’re having trouble clicking the "{{ $actionText }}" button, copy and paste the URL below
1
Ruby
Ruby
resolve bug in nested formbuilder#field_id
3b34cb9e395eea361c996c428b69c568903dc2ae
<ide><path>actionview/lib/action_view/helpers/form_helper.rb <ide> def id <ide> # element, sharing a common <tt>id</tt> root (<tt>post_title</tt>, in this <ide> # case). <ide> def field_id(method, *suffixes, index: @index) <del> @template.field_id(@object || @object_name, method, *suffixes, index: @index) <add> @template.field_id(@object_name, method, *suffixes, index: index) <ide> end <ide> <ide> ## <ide><path>actionview/test/template/form_helper_test.rb <ide> def test_nested_fields_for <ide> assert_dom_equal expected, output_buffer <ide> end <ide> <add> def test_nested_fields_for_field_id <add> form_for(@post) do |form| <add> concat form.fields_for(:comment_attributes, @comment) { |c| <add> concat c.field_id(:body) <add> } <add> end <add> <add> expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do <add> "post_comment_attributes_body" <add> end <add> <add> assert_dom_equal expected, output_buffer <add> end <add> <add> def test_nested_fields_for_field_id_with_index_override <add> form_for(@post) do |form| <add> concat form.fields_for(:comment_attributes, @comment, index: 1) { |c| <add> concat c.field_id(:body) <add> } <add> end <add> <add> expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do <add> "post_comment_attributes_1_body" <add> end <add> <add> assert_dom_equal expected, output_buffer <add> end <add> <ide> def test_deep_nested_fields_for <ide> @comment.save <ide> form_for(:posts) do |f| <ide> def test_fields_for <ide> assert_dom_equal expected, output_buffer <ide> end <ide> <add> def test_fields_for_field_id <add> fields_for(:post, @post) do |fields| <add> assert_equal "post_title", fields.field_id(:title) <add> end <add> end <add> <ide> def test_fields_for_with_index <ide> output_buffer = fields_for("post[]", @post) do |f| <ide> concat f.text_field(:title) <ide> def test_fields_for_with_index <ide> assert_dom_equal expected, output_buffer <ide> end <ide> <add> def test_fields_for_field_id_with_index_option <add> fields_for(:post, @post) do |fields| <add> assert_equal "post_5_title", fields.field_id(:title, index: 5) <add> end <add> end <add> <ide> def test_fields_for_with_nil_index_option_override <ide> output_buffer = fields_for("post[]", @post, index: nil) do |f| <ide> concat f.text_field(:title) <ide> def test_fields_for_with_nil_index_option_override <ide> assert_dom_equal expected, output_buffer <ide> end <ide> <add> def test_fields_for_with_index_option_override_field_id <add> fields_for(:post, @post, index: 1) do |fields| <add> assert_equal "post_1_title", fields.field_id(:title) <add> end <add> end <add> <ide> def test_fields_for_with_index_option_override <ide> output_buffer = fields_for("post[]", @post, index: "abc") do |f| <ide> concat f.text_field(:title)
2
Javascript
Javascript
simplify date inspection tests
666c67e078bddc32f25409f4a929c1e9b5f47373
<ide><path>test/parallel/test-util-inspect.js <ide> assert.strictEqual(util.inspect('"\'${a}'), "'\"\\'${a}'"); <ide> [RegExp, ['foobar', 'g'], '/foobar/g'], <ide> [WeakSet, [[{}]], '{ <items unknown> }'], <ide> [WeakMap, [[[{}, {}]]], '{ <items unknown> }'], <del> [BigInt64Array, [10], '[ 0n, 0n, 0n, 0n, 0n, 0n, 0n, 0n, 0n, 0n ]'] <add> [BigInt64Array, [10], '[ 0n, 0n, 0n, 0n, 0n, 0n, 0n, 0n, 0n, 0n ]'], <add> [Date, ['Sun, 14 Feb 2010 11:48:40 GMT'], '2010-02-14T11:48:40.000Z'], <add> [Date, ['invalid_date'], 'Invalid Date'] <ide> ].forEach(([base, input, rawExpected]) => { <ide> class Foo extends base {} <ide> const value = new Foo(...input); <ide> assert.strictEqual(util.inspect('"\'${a}'), "'\"\\'${a}'"); <ide> assert(/\[Symbol\(foo\)]: 'yeah'/.test(res), res); <ide> }); <ide> <del>// Date null prototype checks <del>{ <del> class CustomDate extends Date { <del> } <del> <del> const date = new CustomDate('Sun, 14 Feb 2010 11:48:40 GMT'); <del> assert.strictEqual(util.inspect(date), 'CustomDate 2010-02-14T11:48:40.000Z'); <del> <del> // add properties <del> date.foo = 'bar'; <del> assert.strictEqual(util.inspect(date), <del> '{ CustomDate 2010-02-14T11:48:40.000Z foo: \'bar\' }'); <del> <del> // Check for null prototype <del> Object.setPrototypeOf(date, null); <del> assert.strictEqual(util.inspect(date), <del> '{ [Date: null prototype] 2010-02-14T11:48:40.000Z' + <del> ' foo: \'bar\' }'); <del> <del> const anotherDate = new CustomDate('Sun, 14 Feb 2010 11:48:40 GMT'); <del> Object.setPrototypeOf(anotherDate, null); <del> assert.strictEqual(util.inspect(anotherDate), <del> '[Date: null prototype] 2010-02-14T11:48:40.000Z'); <del>} <del> <del>// Check for invalid dates and null prototype <del>{ <del> class CustomDate extends Date { <del> } <del> <del> const date = new CustomDate('invalid_date'); <del> assert.strictEqual(util.inspect(date), 'CustomDate Invalid Date'); <del> <del> // add properties <del> date.foo = 'bar'; <del> assert.strictEqual(util.inspect(date), <del> '{ CustomDate Invalid Date foo: \'bar\' }'); <del> <del> // Check for null prototype <del> Object.setPrototypeOf(date, null); <del> assert.strictEqual(util.inspect(date), <del> '{ [Date: null prototype] Invalid Date foo: \'bar\' }'); <del>} <del> <ide> assert.strictEqual(inspect(1n), '1n'); <ide> assert.strictEqual(inspect(Object(-1n)), '[BigInt: -1n]'); <ide> assert.strictEqual(inspect(Object(13n)), '[BigInt: 13n]');
1
Text
Text
add v4.0.0-beta.3 to changelog
70e95eaa305640d4ca2c08754b2c34c120b2c3cc
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v4.0.0-beta.3 (August 30, 2021) <add> <add>- [#19708](https://github.com/emberjs/ember.js/pull/19708) [CLEANUP] Remove class-binding-and-class-name-bindings-in-templates <add> <ide> ### v4.0.0-beta.2 (August 23, 2021) <ide> <ide> - [#19680](https://github.com/emberjs/ember.js/pull/19680) [DEPRECATION] Deprecate owner.inject per [RFC #680](https://github.com/emberjs/rfcs/blob/sn/owner-inject-deprecation/text/0680-implicit-injection-deprecation.md#1-deprecate-implicit-injection-on-target-object) and cleanup related deprecations that are `until: 4.0.0`.
1
Javascript
Javascript
fix image link
0472f0fa819a4974a9624542603fd8a3c2639e73
<ide><path>examples/cms-sanity/components/cover-image.js <ide> export default function CoverImage({ title, slug, image: source }) { <ide> return ( <ide> <div className="sm:mx-0"> <ide> {slug ? ( <del> <Link href={slug}> <add> <Link href={`/posts/${slug}`}> <ide> <a aria-label={title}>{image}</a> <ide> </Link> <ide> ) : (
1
Text
Text
move timothy to tsc emeritus
aea81fc9ff64b3111b67386a0f21ad194c144698
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Michaël Zasso** &lt;[email protected]&gt; (he/him) <ide> * [thefourtheye](https://github.com/thefourtheye) - <ide> **Sakthipriyan Vairamani** &lt;[email protected]&gt; (he/him) <del>* [TimothyGu](https://github.com/TimothyGu) - <del>**Tiancheng "Timothy" Gu** &lt;[email protected]&gt; (he/him) <ide> * [Trott](https://github.com/Trott) - <ide> **Rich Trott** &lt;[email protected]&gt; (he/him) <ide> <ide> For information about the governance of the Node.js project, see <ide> **Bert Belder** &lt;[email protected]&gt; <ide> * [shigeki](https://github.com/shigeki) - <ide> **Shigeki Ohtsu** &lt;[email protected]&gt; (he/him) <add>* [TimothyGu](https://github.com/TimothyGu) - <add>**Tiancheng "Timothy" Gu** &lt;[email protected]&gt; (he/him) <ide> * [trevnorris](https://github.com/trevnorris) - <ide> **Trevor Norris** &lt;[email protected]&gt; <ide>
1
Mixed
Javascript
fix some misspellings
064c1be2ba8a98a7c49b3ec54cbcff70bf7c03e6
<ide><path>docs/guides/options.md <ide> The source URL to a video source to embed. <ide> <ide> > Type: `string|number` <ide> <del>Sets the display height of the video player in pixels. <add>Sets the display width of the video player in pixels. <ide> <ide> ## Video.js-specific Options <ide> <ide> Using `<source>` elements will have the same effect: <ide> <ide> > Type: `boolean` <ide> <del>Gives the possibility to techs to override the player's poster <add>Gives the possibility to techs to override the player's poster <ide> and integrate into the player's poster life-cycle. <ide> This can be useful when multiple techs are used and each has to set their own poster <ide> any time a new source is played. <ide><path>src/js/control-bar/progress-control/seek-bar.js <ide> class SeekBar extends Slider { <ide> } <ide> <ide> /** <del> * This function updates the play progress bar and accessiblity <add> * This function updates the play progress bar and accessibility <ide> * attributes to whatever is passed in. <ide> * <ide> * @param {number} currentTime <del> * The currentTime value that should be used for accessiblity <add> * The currentTime value that should be used for accessibility <ide> * <ide> * @param {number} percent <ide> * The percentage as a decimal that the bar should be filled from 0-1. <ide><path>src/js/control-bar/text-track-controls/text-track-button.js <ide> class TextTrackButton extends TrackButton { <ide> */ <ide> createItems(items = [], TrackMenuItem = TextTrackMenuItem) { <ide> <del> // Label is an overide for the [track] off label <add> // Label is an override for the [track] off label <ide> // USed to localise captions/subtitles <ide> let label; <ide> <ide><path>src/js/mixins/evented.js <ide> const listen = (target, method, type, listener) => { <ide> }; <ide> <ide> /** <del> * Contains methods that provide event capabilites to an object which is passed <add> * Contains methods that provide event capabilities to an object which is passed <ide> * to {@link module:evented|evented}. <ide> * <ide> * @mixin EventedMixin <ide><path>src/js/player.js <ide> class Player extends Component { <ide> * dragging it along the progress bar. <ide> * <ide> * @param {boolean} [isScrubbing] <del> * wether the user is or is not scrubbing <add> * whether the user is or is not scrubbing <ide> * <ide> * @return {boolean} <ide> * The value of scrubbing when getting <ide> class Player extends Component { <ide> <ide> seconds = parseFloat(seconds); <ide> <del> // Standardize on Inifity for signaling video is live <add> // Standardize on Infinity for signaling video is live <ide> if (seconds < 0) { <ide> seconds = Infinity; <ide> } <ide> class Player extends Component { <ide> * <ide> * @return {number} <ide> * A decimal between 0 and 1 representing the percent <del> * that is bufferred 0 being 0% and 1 being 100% <add> * that is buffered 0 being 0% and 1 being 100% <ide> */ <ide> bufferedPercent() { <ide> return bufferedPercent(this.buffered(), this.duration()); <ide> class Player extends Component { <ide> <ide> /** <ide> * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted <del> * indicates the state of muted on intial playback. <add> * indicates the state of muted on initial playback. <ide> * <ide> * ```js <ide> * var myPlayer = videojs('some-player-id'); <ide> class Player extends Component { <ide> } <ide> <ide> /** <del> * Set the source object on the tech, returns a boolean that indicates wether <add> * Set the source object on the tech, returns a boolean that indicates whether <ide> * there is a tech that can play the source or not <ide> * <ide> * @param {Tech~SourceObject} source <ide> class Player extends Component { <ide> <ide> /** <ide> * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4 <del> * Can be used in conjuction with `currentType` to assist in rebuilding the current source object. <add> * Can be used in conjunction with `currentType` to assist in rebuilding the current source object. <ide> * <ide> * @return {string} <ide> * The current source <ide> class Player extends Component { <ide> * <ide> * @param {boolean} [value] <ide> * - true means that we should preload <del> * - false maens that we should not preload <add> * - false means that we should not preload <ide> * <ide> * @return {string} <ide> * The preload attribute value when getting <ide> class Player extends Component { <ide> /** <ide> * Gets or sets the current default playback rate. A default playback rate of <ide> * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance. <del> * defaultPlaybackRate will only represent what the intial playbackRate of a video was, not <add> * defaultPlaybackRate will only represent what the initial playbackRate of a video was, not <ide> * not the current playbackRate. <ide> * <ide> * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate <ide> class Player extends Component { <ide> /** <ide> * The player's language code <ide> * NOTE: The language should be set in the player options if you want the <del> * the controls to be built with a specific language. Changing the lanugage <add> * the controls to be built with a specific language. Changing the language <ide> * later will not update controls text. <ide> * <ide> * @param {string} [code] <ide> class Player extends Component { <ide> } <ide> <ide> /** <del> * Determine wether or not flexbox is supported <add> * Determine whether or not flexbox is supported <ide> * <ide> * @return {boolean} <ide> * - true if flexbox is supported <ide><path>src/js/tech/html5.js <ide> import setupSourceset from './setup-sourceset'; <ide> /** <ide> * HTML5 Media Controller - Wrapper for HTML5 Media API <ide> * <del> * @mixes Tech~SouceHandlerAdditions <add> * @mixes Tech~SourceHandlerAdditions <ide> * @extends Tech <ide> */ <ide> class Html5 extends Tech { <ide> class Html5 extends Tech { <ide> * Get the current height of the HTML5 media element. <ide> * <ide> * @return {number} <del> * The heigth of the HTML5 media element. <add> * The height of the HTML5 media element. <ide> */ <ide> height() { <ide> return this.el_.offsetHeight; <ide> class Html5 extends Tech { <ide> * on the value of `featuresNativeTextTracks` <ide> * <ide> * @param {Object} options <del> * The object should contain the options to intialize the TextTrack with. <add> * The object should contain the options to initialize the TextTrack with. <ide> * <ide> * @param {string} [options.kind] <ide> * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata). <ide> * <del> * @param {string} [options.label]. <add> * @param {string} [options.label] <ide> * Label to identify the text track <ide> * <ide> * @param {string} [options.language] <ide> Html5.canControlPlaybackRate = function() { <ide> * Object.defineProperty. <ide> * <ide> * @return {boolean} <del> * - True if builtin attributes can be overriden <add> * - True if builtin attributes can be overridden <ide> * - False otherwise <ide> */ <ide> Html5.canOverrideAttributes = function() { <ide> Html5.prototype.featuresVolumeControl = Html5.canControlVolume(); <ide> Html5.prototype.featuresPlaybackRate = Html5.canControlPlaybackRate(); <ide> <ide> /** <del> * Boolean indicating wether the `Tech` supports the `sourceset` event. <add> * Boolean indicating whether the `Tech` supports the `sourceset` event. <ide> * <ide> * @type {boolean} <ide> * @default <ide> Html5.prototype.featuresFullscreenResize = true; <ide> <ide> /** <ide> * Boolean indicating whether the `HTML5` tech currently supports the progress event. <del> * If this is false, manual `progress` events will be triggred instead. <add> * If this is false, manual `progress` events will be triggered instead. <ide> * <ide> * @type {boolean} <ide> * @default <ide> Html5.prototype.featuresProgressEvents = true; <ide> <ide> /** <ide> * Boolean indicating whether the `HTML5` tech currently supports the timeupdate event. <del> * If this is false, manual `timeupdate` events will be triggred instead. <add> * If this is false, manual `timeupdate` events will be triggered instead. <ide> * <ide> * @default <ide> */ <ide> Html5.resetMediaElement = function(el) { <ide> <ide> /** <ide> * Get the value of the `error` from the media element. `error` indicates any <del> * MediaError that may have occured during playback. If error returns null there is no <add> * MediaError that may have occurred during playback. If error returns null there is no <ide> * current error. <ide> * <ide> * @method Html5#error <ide> Html5.resetMediaElement = function(el) { <ide> * @return {boolean} <ide> * - The value of `seeking` from the media element. <ide> * - True indicates that the media is currently seeking to a new position. <del> * - Flase indicates that the media is not seeking to a new position at this time. <add> * - False indicates that the media is not seeking to a new position at this time. <ide> * <ide> * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking} <ide> */ <ide> Html5.resetMediaElement = function(el) { <ide> * Get the value of `networkState` from the media element. `networkState` indicates <ide> * the current network state. It returns an enumeration from the following list: <ide> * - 0: NETWORK_EMPTY <del> * - 1: NEWORK_IDLE <add> * - 1: NETWORK_IDLE <ide> * - 2: NETWORK_LOADING <ide> * - 3: NETWORK_NO_SOURCE <ide> * <ide> Html5.resetMediaElement = function(el) { <ide> 'videoWidth', <ide> <ide> /** <del> * Get the value of `videoHeight` from the video element. `videoHeigth` indicates <add> * Get the value of `videoHeight` from the video element. `videoHeight` indicates <ide> * the current height of the video in css pixels. <ide> * <ide> * @method Html5#videoHeight <ide> Html5.resetMediaElement = function(el) { <ide> <ide> // wrap native functions with a function <ide> // The list is as follows: <del>// pause, load play <add>// pause, load, play <ide> [ <ide> /** <ide> * A wrapper around the media elements `pause` function. This will call the `HTML5` <ide> Tech.withSourceHandlers(Html5); <ide> /** <ide> * Native source handler for Html5, simply passes the source to the media element. <ide> * <del> * @proprety {Tech~SourceObject} source <add> * @property {Tech~SourceObject} source <ide> * The source object <ide> * <del> * @proprety {Html5} tech <add> * @property {Html5} tech <ide> * The instance of the HTML5 tech. <ide> */ <ide> Html5.nativeSourceHandler = {}; <ide><path>src/js/tech/setup-sourceset.js <ide> const getSrcDescriptor = (el) => { <ide> }; <ide> <ide> /** <del> * Patches browser internal functions so that we can tell syncronously <add> * Patches browser internal functions so that we can tell synchronously <ide> * if a `<source>` was appended to the media element. For some reason this <ide> * causes a `sourceset` if the the media element is ready and has no source. <ide> * This happens when:
7
PHP
PHP
remove unneeded variable
b35d4c7bce7d88c10dfecfdde87589fa952a0d93
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> protected function performUpdate(Builder $query) <ide> $dirty = $this->getDirty(); <ide> <ide> if (count($dirty) > 0) { <del> $numRows = $this->setKeysForSaveQuery($query)->update($dirty); <del> <add> $this->setKeysForSaveQuery($query)->update($dirty); <ide> $this->fireModelEvent('updated', false); <ide> } <ide>
1
Python
Python
improve docs for multi_gpu_model
a04284341c26761d4b1a92f3245a535b2b2eaad4
<ide><path>keras/utils/training_utils.py <ide> def multi_gpu_model(model, gpus): <ide> width = 224 <ide> num_classes = 1000 <ide> <del> # Instantiate the base model <del> # (here, we do it on CPU, which is optional). <add> # Instantiate the base model (or "template" model). <add> # We recommend doing this with under a CPU device scope, <add> # so that the model's weights are hosted on CPU memory. <add> # Otherwise they may end up hosted on a GPU, which would <add> # complicate weight sharing. <ide> with tf.device('/cpu:0'): <ide> model = Xception(weights=None, <ide> input_shape=(height, width, 3), <ide> def multi_gpu_model(model, gpus): <ide> # This `fit` call will be distributed on 8 GPUs. <ide> # Since the batch size is 256, each GPU will process 32 samples. <ide> parallel_model.fit(x, y, epochs=20, batch_size=256) <add> <add> # Save model via the template model (which shares the same weights): <add> model.save('my_model.h5') <ide> ``` <add> <add> # On model saving <add> <add> To save the multi-gpu model, use `.save(fname)` or `.save_weights(fname)` <add> with the template model (the argument you passed to `multi_gpu_model), <add> rather than the model returned by `multi_gpu_model`. <ide> """ <ide> if K.backend() != 'tensorflow': <ide> raise ValueError('`multi_gpu_model` is only available '
1
Javascript
Javascript
add map aside to challenges
cc1c2e6aa157c9121b96b0e880587e5bb5885e94
<ide><path>server/boot/challenge.js <ide> function getRenderData$(user, challenge$, origChallengeName, solution) { <ide> }); <ide> } <ide> <add>function getCompletedChallengeIds(user = {}) { <add> // if user <add> // get the id's of all the users completed challenges <add> return !user.completedChallenges ? <add> [] : <add> _.uniq(user.completedChallenges) <add> .map(({ id, _id }) => id || _id); <add>} <add> <ide> // create a stream of an array of all the challenge blocks <ide> function getSuperBlocks$(challenge$, completedChallenges) { <ide> return challenge$ <ide> module.exports = function(app) { <ide> <ide> function showChallenge(req, res, next) { <ide> const solution = req.query.solution; <del> getRenderData$(req.user, challenge$, req.params.challengeName, solution) <add> const completedChallenges = getCompletedChallengeIds(req.user); <add> <add> Observable.combineLatest( <add> getRenderData$(req.user, challenge$, req.params.challengeName, solution), <add> getSuperBlocks$(challenge$, completedChallenges), <add> ({ data, ...rest }, superBlocks) => ({ <add> ...rest, <add> data: { <add> ...data, <add> superBlocks <add> } <add> }) <add> ) <ide> .subscribe( <ide> ({ type, redirectUrl, message, data }) => { <ide> if (message) { <ide> module.exports = function(app) { <ide> ); <ide> } <ide> <del> function showMap({ user = {} }, res, next) { <del> // if user <del> // get the id's of all the users completed challenges <del> const completedChallenges = !user.completedChallenges ? <del> [] : <del> _.uniq(user.completedChallenges).map(({ id, _id }) => id || _id); <add> function showMap({ user }, res, next) { <ide> <del> getSuperBlocks$(challenge$, completedChallenges) <add> getSuperBlocks$(challenge$, getCompletedChallengeIds(user)) <ide> .subscribe( <ide> superBlocks => { <ide> res.render('map/show', {
1
Ruby
Ruby
use homebrew_path for external commands
12e0a5ee7dc730c163655def44ae9e6dc316a44a
<ide><path>Library/Homebrew/brew.rb <ide> def require?(path) <ide> end <ide> <ide> path = PATH.new(ENV["PATH"]) <add> homebrew_path = PATH.new(ENV["HOMEBREW_PATH"]) <ide> <ide> # Add contributed commands to PATH before checking. <del> path.append(Pathname.glob(Tap::TAP_DIRECTORY/"*/*/cmd")) <add> tap_cmds = Pathname.glob(Tap::TAP_DIRECTORY/"*/*/cmd") <add> path.append(tap_cmds) <add> homebrew_path.append(tap_cmds) <ide> <ide> # Add SCM wrappers. <ide> path.append(HOMEBREW_SHIMS_PATH/"scm") <add> homebrew_path.append(HOMEBREW_SHIMS_PATH/"scm") <ide> <ide> ENV["PATH"] = path <ide> <ide> def require?(path) <ide> system(HOMEBREW_BREW_FILE, "uninstall", "--force", "brew-cask") <ide> end <ide> <add> # External commands expect a normal PATH <add> ENV["PATH"] = homebrew_path unless internal_cmd <add> <ide> if internal_cmd <ide> Homebrew.send cmd.to_s.tr("-", "_").downcase <ide> elsif which "brew-#{cmd}"
1
PHP
PHP
remove unnecessary space
6f6f6ff7711671252be2d09abefc75e69b15b500
<ide><path>src/Illuminate/Routing/UrlGenerator.php <ide> public function hasValidSignature(Request $request, $absolute = true) <ide> <ide> $signature = hash_hmac('sha256', $original, call_user_func($this->keyResolver)); <ide> <del> return hash_equals($signature, (string) $request->query('signature', '')) && <add> return hash_equals($signature, (string) $request->query('signature', '')) && <ide> ! ($expires && Carbon::now()->getTimestamp() > $expires); <ide> } <ide>
1
Ruby
Ruby
reduce duplication somewhat
ea55d86eb110842347351c2b15b4103ed62172fb
<ide><path>activerecord/lib/active_record/fixtures.rb <ide> def primary_key_name <ide> @primary_key_name ||= model_class && model_class.primary_key <ide> end <ide> <add> def join_rows(targets, row, lhs_key, rhs_key) <add> targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/) <add> targets.map { |target| <add> { lhs_key => row[primary_key_name], <add> rhs_key => ActiveRecord::FixtureSet.identify(target) } <add> } <add> end <add> <ide> def handle_hmt(rows, row, association) <ide> # This is the case when the join table has no fixtures file <ide> if (targets = row.delete(association.name.to_s)) <del> targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/) <ide> table_name = association.join_table <del> lhs_key = association.through_reflection.foreign_key <del> rhs_key = association.foreign_key <add> lhs_key = association.through_reflection.foreign_key <add> rhs_key = association.foreign_key <ide> <del> rows[table_name].concat targets.map { |target| <del> { lhs_key => row[primary_key_name], <del> rhs_key => ActiveRecord::FixtureSet.identify(target) } <del> } <add> rows[table_name].concat join_rows(targets, row, lhs_key, rhs_key) <ide> end <ide> end <ide> <ide> def handle_habtm(rows, row, association) <ide> # This is the case when the join table has no fixtures file <ide> if (targets = row.delete(association.name.to_s)) <del> targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/) <ide> table_name = association.join_table <del> lhs_key = association.foreign_key <del> rhs_key = association.association_foreign_key <add> lhs_key = association.foreign_key <add> rhs_key = association.association_foreign_key <ide> <del> rows[table_name].concat targets.map { |target| <del> { lhs_key => row[primary_key_name], <del> rhs_key => ActiveRecord::FixtureSet.identify(target) } <del> } <add> rows[table_name].concat join_rows(targets, row, lhs_key, rhs_key) <ide> end <ide> end <ide>
1
Java
Java
register annotation based on its type
059b66bf26c2aa8b96847938a2eb00e7645c69e1
<ide><path>spring-context/src/main/java/org/springframework/context/aot/ReflectiveProcessorBeanRegistrationAotProcessor.java <ide> import java.util.function.Consumer; <ide> <ide> import org.springframework.aot.generate.GenerationContext; <del>import org.springframework.aot.hint.MemberCategory; <ide> import org.springframework.aot.hint.ReflectionHints; <ide> import org.springframework.aot.hint.RuntimeHints; <del>import org.springframework.aot.hint.TypeHint.Builder; <ide> import org.springframework.aot.hint.annotation.Reflective; <ide> import org.springframework.aot.hint.annotation.ReflectiveProcessor; <ide> import org.springframework.aot.hint.support.RuntimeHintsUtils; <ide> private record Entry(AnnotatedElement element, ReflectiveProcessor processor) {} <ide> <ide> private static class ReflectiveProcessorBeanRegistrationAotContribution implements BeanRegistrationAotContribution { <ide> <del> private static final Consumer<Builder> ANNOTATION_CUSTOMIZATIONS = hint -> hint.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS); <del> <ide> private final Iterable<Entry> entries; <ide> <ide> public ReflectiveProcessorBeanRegistrationAotContribution(Iterable<Entry> entries) { <ide> public ReflectiveProcessorBeanRegistrationAotContribution(Iterable<Entry> entrie <ide> @Override <ide> public void applyTo(GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode) { <ide> RuntimeHints runtimeHints = generationContext.getRuntimeHints(); <del> runtimeHints.reflection().registerType(Reflective.class, ANNOTATION_CUSTOMIZATIONS); <add> RuntimeHintsUtils.registerAnnotation(runtimeHints, Reflective.class); <ide> this.entries.forEach(entry -> { <ide> AnnotatedElement element = entry.element(); <ide> entry.processor().registerReflectionHints(runtimeHints.reflection(), element); <ide> public void applyTo(GenerationContext generationContext, BeanRegistrationCode be <ide> private void registerAnnotationIfNecessary(RuntimeHints hints, AnnotatedElement element) { <ide> MergedAnnotation<Reflective> reflectiveAnnotation = MergedAnnotations.from(element).get(Reflective.class); <ide> if (reflectiveAnnotation.getDistance() > 0) { <del> RuntimeHintsUtils.registerAnnotation(hints, reflectiveAnnotation.getRoot()); <add> RuntimeHintsUtils.registerAnnotation(hints, reflectiveAnnotation.getRoot().getType()); <ide> } <ide> } <ide> <ide><path>spring-context/src/test/java/org/springframework/context/aot/ReflectiveProcessorBeanRegistrationAotProcessorTests.java <ide> void shouldRegisterAnnotation() { <ide> process(SampleMethodMetaAnnotatedBean.class); <ide> RuntimeHints runtimeHints = this.generationContext.getRuntimeHints(); <ide> assertThat(runtimeHints.reflection().getTypeHint(SampleInvoker.class)).satisfies(typeHint -> <del> assertThat(typeHint.getMemberCategories()).containsOnly(MemberCategory.INVOKE_PUBLIC_METHODS)); <add> assertThat(typeHint.getMemberCategories()).containsOnly(MemberCategory.INVOKE_DECLARED_METHODS)); <ide> assertThat(runtimeHints.proxies().jdkProxies()).isEmpty(); <ide> } <ide> <ide> void shouldRegisterAnnotationAndProxyWithAliasFor() { <ide> process(SampleMethodMetaAnnotatedBeanWithAlias.class); <ide> RuntimeHints runtimeHints = this.generationContext.getRuntimeHints(); <ide> assertThat(runtimeHints.reflection().getTypeHint(RetryInvoker.class)).satisfies(typeHint -> <del> assertThat(typeHint.getMemberCategories()).containsOnly(MemberCategory.INVOKE_PUBLIC_METHODS)); <add> assertThat(typeHint.getMemberCategories()).containsOnly(MemberCategory.INVOKE_DECLARED_METHODS)); <ide> assertThat(runtimeHints.proxies().jdkProxies()).anySatisfy(jdkProxyHint -> <ide> assertThat(jdkProxyHint.getProxiedInterfaces()).containsExactly( <ide> TypeReference.of(RetryInvoker.class), TypeReference.of(SynthesizedAnnotation.class))); <ide><path>spring-core/src/main/java/org/springframework/aot/hint/support/RuntimeHintsUtils.java <ide> <ide> package org.springframework.aot.hint.support; <ide> <add>import java.lang.annotation.Annotation; <add>import java.lang.reflect.Method; <add>import java.util.LinkedHashSet; <add>import java.util.Set; <ide> import java.util.function.Consumer; <ide> <ide> import org.springframework.aot.hint.MemberCategory; <ide> import org.springframework.aot.hint.RuntimeHints; <ide> import org.springframework.aot.hint.TypeHint; <ide> import org.springframework.aot.hint.TypeHint.Builder; <del>import org.springframework.core.annotation.MergedAnnotation; <add>import org.springframework.core.annotation.AliasFor; <add>import org.springframework.core.annotation.MergedAnnotations; <ide> import org.springframework.core.annotation.SynthesizedAnnotation; <ide> <ide> /** <ide> public abstract class RuntimeHintsUtils { <ide> * that its attributes are visible. <ide> */ <ide> public static final Consumer<Builder> ANNOTATION_HINT = hint -> <del> hint.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS); <add> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS); <ide> <ide> /** <ide> * Register the necessary hints so that the specified annotation is visible <del> * at runtime. <add> * at runtime. If an annotation attributes aliases an attribute of another <add> * annotation, it is registered as well and a JDK proxy hints is defined <add> * so that the synthesized annotation can be resolved. <ide> * @param hints the {@link RuntimeHints} instance ot use <del> * @param annotation the annotation <add> * @param annotationType the annotation type <ide> * @see SynthesizedAnnotation <ide> */ <del> public static void registerAnnotation(RuntimeHints hints, MergedAnnotation<?> annotation) { <del> hints.reflection().registerType(annotation.getType(), ANNOTATION_HINT); <del> MergedAnnotation<?> parentSource = annotation.getMetaSource(); <del> while (parentSource != null) { <del> hints.reflection().registerType(parentSource.getType(), ANNOTATION_HINT); <del> parentSource = parentSource.getMetaSource(); <add> public static void registerAnnotation(RuntimeHints hints, Class<?> annotationType) { <add> Set<Class<?>> allAnnotations = new LinkedHashSet<>(); <add> allAnnotations.add(annotationType); <add> collectAliasedAnnotations(allAnnotations, annotationType); <add> allAnnotations.forEach(annotation -> hints.reflection().registerType(annotation, ANNOTATION_HINT)); <add> if (allAnnotations.size() > 1) { <add> hints.proxies().registerJdkProxy(annotationType, SynthesizedAnnotation.class); <ide> } <del> if (annotation.synthesize() instanceof SynthesizedAnnotation) { <del> hints.proxies().registerJdkProxy(annotation.getType(), SynthesizedAnnotation.class); <add> } <add> <add> private static void collectAliasedAnnotations(Set<Class<?>> types, Class<?> annotationType) { <add> for (Method method : annotationType.getDeclaredMethods()) { <add> MergedAnnotations methodAnnotations = MergedAnnotations.from(method); <add> if (methodAnnotations.isPresent(AliasFor.class)) { <add> Class<?> aliasedAnnotation = methodAnnotations.get(AliasFor.class).getClass("annotation"); <add> boolean process = (aliasedAnnotation != Annotation.class && !types.contains(aliasedAnnotation)); <add> if (process) { <add> types.add(aliasedAnnotation); <add> collectAliasedAnnotations(types, aliasedAnnotation); <add> } <add> } <ide> } <ide> } <ide> <ide><path>spring-core/src/main/java/org/springframework/core/annotation/CoreAnnotationsRuntimeHintsRegistrar.java <ide> <ide> package org.springframework.core.annotation; <ide> <add>import java.util.stream.Stream; <add> <ide> import org.springframework.aot.hint.RuntimeHints; <ide> import org.springframework.aot.hint.RuntimeHintsRegistrar; <ide> import org.springframework.aot.hint.support.RuntimeHintsUtils; <add>import org.springframework.lang.Nullable; <ide> <ide> /** <ide> * {@link RuntimeHintsRegistrar} for core annotations. <ide> class CoreAnnotationsRuntimeHintsRegistrar implements RuntimeHintsRegistrar { <ide> <ide> @Override <del> public void registerHints(RuntimeHints hints, ClassLoader classLoader) { <del> hints.reflection().registerType(AliasFor.class, RuntimeHintsUtils.ANNOTATION_HINT) <del> .registerType(Order.class, RuntimeHintsUtils.ANNOTATION_HINT); <add> public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { <add> Stream.of(AliasFor.class, Order.class).forEach(annotationType -> <add> RuntimeHintsUtils.registerAnnotation(hints, annotationType)); <ide> } <ide> <ide> } <ide><path>spring-core/src/test/java/org/springframework/aot/hint/support/RuntimeHintsUtilsTests.java <ide> import org.springframework.aot.hint.TypeHint; <ide> import org.springframework.aot.hint.TypeReference; <ide> import org.springframework.core.annotation.AliasFor; <del>import org.springframework.core.annotation.MergedAnnotations; <ide> import org.springframework.core.annotation.SynthesizedAnnotation; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> class RuntimeHintsUtilsTests { <ide> private final RuntimeHints hints = new RuntimeHints(); <ide> <ide> @Test <del> void registerAnnotation() { <del> RuntimeHintsUtils.registerAnnotation(this.hints, MergedAnnotations <del> .from(SampleInvokerClass.class).get(SampleInvoker.class)); <add> void registerAnnotationType() { <add> RuntimeHintsUtils.registerAnnotation(this.hints, SampleInvoker.class); <ide> assertThat(this.hints.reflection().typeHints()).singleElement() <ide> .satisfies(annotationHint(SampleInvoker.class)); <ide> assertThat(this.hints.proxies().jdkProxies()).isEmpty(); <ide> } <ide> <ide> @Test <del> void registerAnnotationProxyRegistersJdkProxy() { <del> RuntimeHintsUtils.registerAnnotation(this.hints, MergedAnnotations <del> .from(RetryInvokerClass.class).get(RetryInvoker.class)); <del> assertThat(this.hints.reflection().typeHints()).singleElement() <del> .satisfies(annotationHint(RetryInvoker.class)); <add> void registerAnnotationTypeProxyRegistersJdkProxy() { <add> RuntimeHintsUtils.registerAnnotation(this.hints, RetryInvoker.class); <add> assertThat(this.hints.reflection().typeHints()) <add> .anySatisfy(annotationHint(RetryInvoker.class)) <add> .anySatisfy(annotationHint(SampleInvoker.class)); <ide> assertThat(this.hints.proxies().jdkProxies()).singleElement() <ide> .satisfies(annotationProxy(RetryInvoker.class)); <ide> } <ide> <ide> @Test <del> void registerAnnotationWhereUsedAsAMetaAnnotationRegistersHierarchy() { <del> RuntimeHintsUtils.registerAnnotation(this.hints, MergedAnnotations <del> .from(RetryWithEnabledFlagInvokerClass.class).get(SampleInvoker.class)); <add> void registerAnnotationTypeWhereUsedAsAMetaAnnotationRegistersHierarchy() { <add> RuntimeHintsUtils.registerAnnotation(this.hints, RetryWithEnabledFlagInvoker.class); <ide> ReflectionHints reflection = this.hints.reflection(); <ide> assertThat(reflection.typeHints()) <del> .anySatisfy(annotationHint(SampleInvoker.class)) <del> .anySatisfy(annotationHint(RetryInvoker.class)) <ide> .anySatisfy(annotationHint(RetryWithEnabledFlagInvoker.class)) <add> .anySatisfy(annotationHint(RetryInvoker.class)) <add> .anySatisfy(annotationHint(SampleInvoker.class)) <ide> .hasSize(3); <ide> assertThat(this.hints.proxies().jdkProxies()).singleElement() <del> .satisfies(annotationProxy(SampleInvoker.class)); <add> .satisfies(annotationProxy(RetryWithEnabledFlagInvoker.class)); <ide> } <ide> <ide> private Consumer<TypeHint> annotationHint(Class<?> type) { <ide> private Consumer<TypeHint> annotationHint(Class<?> type) { <ide> assertThat(typeHint.constructors()).isEmpty(); <ide> assertThat(typeHint.fields()).isEmpty(); <ide> assertThat(typeHint.methods()).isEmpty(); <del> assertThat(typeHint.getMemberCategories()).containsOnly(MemberCategory.INVOKE_PUBLIC_METHODS); <add> assertThat(typeHint.getMemberCategories()).containsOnly(MemberCategory.INVOKE_DECLARED_METHODS); <ide> }; <ide> } <ide> <ide><path>spring-core/src/test/java/org/springframework/core/annotation/CoreAnnotationsRuntimeHintsRegistrarTests.java <ide> void setup() { <ide> void aliasForHasHints() { <ide> assertThat(this.hints.reflection().getTypeHint(TypeReference.of(AliasFor.class))) <ide> .satisfies(hint -> assertThat(hint.getMemberCategories()) <del> .containsExactly(MemberCategory.INVOKE_PUBLIC_METHODS)); <add> .containsExactly(MemberCategory.INVOKE_DECLARED_METHODS)); <ide> } <ide> <ide> @Test <ide> void orderAnnotationHasHints() { <ide> assertThat(this.hints.reflection().getTypeHint(TypeReference.of(Order.class))) <ide> .satisfies(hint -> assertThat(hint.getMemberCategories()) <del> .containsExactly(MemberCategory.INVOKE_PUBLIC_METHODS)); <add> .containsExactly(MemberCategory.INVOKE_DECLARED_METHODS)); <ide> } <ide> <ide> }
6
Java
Java
add reactrootview perf markers
f1fbfebccbe0e4fc48d305b51efc373f69bf93f7
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java <ide> private void init() { <ide> @Override <ide> protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { <ide> Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactRootView.onMeasure"); <add> ReactMarker.logMarker(ReactMarkerConstants.ROOT_VIEW_ON_MEASURE_START); <ide> try { <ide> boolean measureSpecsUpdated = <ide> widthMeasureSpec != mWidthMeasureSpec || heightMeasureSpec != mHeightMeasureSpec; <ide> protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { <ide> mLastHeight = height; <ide> <ide> } finally { <add> ReactMarker.logMarker(ReactMarkerConstants.ROOT_VIEW_ON_MEASURE_END); <ide> Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <ide> } <ide> public static Point getViewportOffset(View v) { <ide> */ <ide> private void updateRootLayoutSpecs( <ide> boolean measureSpecsChanged, final int widthMeasureSpec, final int heightMeasureSpec) { <add> ReactMarker.logMarker(ReactMarkerConstants.ROOT_VIEW_UPDATE_LAYOUT_SPECS_START); <ide> if (mReactInstanceManager == null) { <add> ReactMarker.logMarker(ReactMarkerConstants.ROOT_VIEW_UPDATE_LAYOUT_SPECS_END); <ide> FLog.w(TAG, "Unable to update root layout specs for uninitialized ReactInstanceManager"); <ide> return; <ide> } <ide> private void updateRootLayoutSpecs( <ide> mLastOffsetY = offsetY; <ide> } <ide> } <add> <add> ReactMarker.logMarker(ReactMarkerConstants.ROOT_VIEW_UPDATE_LAYOUT_SPECS_END); <ide> } <ide> <ide> /** <ide> private CustomGlobalLayoutListener getCustomGlobalLayoutListener() { <ide> <ide> private void attachToReactInstanceManager() { <ide> Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "attachToReactInstanceManager"); <del> <del> if (mIsAttachedToInstance) { <del> return; <del> } <add> ReactMarker.logMarker(ReactMarkerConstants.ROOT_VIEW_ATTACH_TO_REACT_INSTANCE_MANAGER_START); <ide> <ide> try { <add> if (mIsAttachedToInstance) { <add> return; <add> } <add> <ide> mIsAttachedToInstance = true; <ide> Assertions.assertNotNull(mReactInstanceManager).attachRootView(this); <ide> getViewTreeObserver().addOnGlobalLayoutListener(getCustomGlobalLayoutListener()); <ide> } finally { <add> ReactMarker.logMarker(ReactMarkerConstants.ROOT_VIEW_ATTACH_TO_REACT_INSTANCE_MANAGER_END); <ide> Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMarkerConstants.java <ide> public enum ReactMarkerConstants { <ide> JAVASCRIPT_EXECUTOR_FACTORY_INJECT_END, <ide> LOAD_REACT_NATIVE_SO_FILE_START, <ide> LOAD_REACT_NATIVE_SO_FILE_END, <add> ROOT_VIEW_ON_MEASURE_START, <add> ROOT_VIEW_ON_MEASURE_END, <add> ROOT_VIEW_ATTACH_TO_REACT_INSTANCE_MANAGER_START, <add> ROOT_VIEW_ATTACH_TO_REACT_INSTANCE_MANAGER_END, <add> ROOT_VIEW_UPDATE_LAYOUT_SPECS_START, <add> ROOT_VIEW_UPDATE_LAYOUT_SPECS_END, <ide> // Fabric-specific constants below this line <ide> LOAD_REACT_NATIVE_FABRIC_SO_FILE_START, <ide> LOAD_REACT_NATIVE_FABRIC_SO_FILE_END,
2
Text
Text
clarify one commit per formula
14981e6265f27a1439778bb894be283a9e741066
<ide><path>share/doc/homebrew/How-To-Open-a-Homebrew-Pull-Request-(and-get-it-merged).md <ide> To make changes based on feedback: <ide> <ide> 1. Checkout your branch again with `git checkout YOUR_BRANCH_NAME` <ide> 2. Make any requested changes and commit them with `git add` and `git commit` <del>3. Squash new commits into one change per formula with `git rebase --interactive origin/master` <add>3. Squash new commits into one commit per formula with `git rebase --interactive origin/master` <ide> 4. Push to the fork's remote branch and the pull request with `git push --force` <ide> <ide> Once all feedback has been addressed and if it's a change we want to include (we include most changes) then we'll add your commit to Homebrew. Note it will not show up as "Merged" because of the way we include contributions.
1
Text
Text
simplify sentences that use "considered"
c6bee70eec91debb6dafeb62b5dafce17a04fddb
<ide><path>doc/api/child_process.md <ide> process.send({ foo: 'bar', baz: NaN }); <ide> Child Node.js processes will have a [`process.send()`][] method of their own that <ide> allows the child to send messages back to the parent. <ide> <del>There is a special case when sending a `{cmd: 'NODE_foo'}` message. All messages <del>containing a `NODE_` prefix in its `cmd` property are considered to be reserved <del>for use within Node.js core and will not be emitted in the child's <del>[`process.on('message')`][] event. Rather, such messages are emitted using the <add>There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages <add>containing a `NODE_` prefix in the `cmd` property are reserved for use within <add>Node.js core and will not be emitted in the child's [`process.on('message')`][] <add>event. Rather, such messages are emitted using the <ide> `process.on('internalMessage')` event and are consumed internally by Node.js. <ide> Applications should avoid using such messages or listening for <ide> `'internalMessage'` events as it is subject to change without notice. <ide><path>doc/api/http.md <ide> Once a socket is assigned to this request and is connected <ide> added: v0.5.9 <ide> --> <ide> <del>* `timeout` {number} Milliseconds before a request is considered to be timed out. <add>* `timeout` {number} Milliseconds before a request times out. <ide> * `callback` {Function} Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. <ide> <ide> Once a socket is assigned to this request and is connected <ide><path>doc/api/readline.md <ide> The `'close'` event is emitted when one of the following occur: <ide> <ide> The listener function is called without passing any arguments. <ide> <del>The `readline.Interface` instance should be considered to be "finished" once <del>the `'close'` event is emitted. <add>The `readline.Interface` instance is finished once the `'close'` event is <add>emitted. <ide> <ide> ### Event: 'line' <ide> <!-- YAML <ide><path>doc/guides/maintaining-V8.md <ide> For example, at the time of this writing: <ide> released as part of the Chromium **canary** builds. This branch will be <ide> promoted to beta next when V8 5.5 ships as stable. <ide> <del>All older branches are considered **abandoned**, and are not maintained by the <del>V8 team. <add>All older branches are abandoned and are not maintained by the V8 team. <ide> <ide> ### V8 merge process overview <ide>
4
Ruby
Ruby
fix spelling for permssions
bcea01ca0a6c9b37d2f147cfc577b93ebd7678f8
<ide><path>Library/Homebrew/extend/pathname.rb <ide> def make_relative_symlink src <ide> unless rv and $? == 0 <ide> raise <<-EOS.undent <ide> Could not create symlink #{to_s}. <del> Check that you have permssions on #{self.dirname} <add> Check that you have permissions on #{self.dirname} <ide> EOS <ide> end <ide> end
1
Javascript
Javascript
use an es6 class in listview docs
700574fe76ee32f1fb6f892319ff7640fbf8ce7a
<ide><path>Libraries/CustomComponents/ListView/ListView.js <ide> var DEFAULT_SCROLL_CALLBACK_THROTTLE = 50; <ide> * Minimal example: <ide> * <ide> * ``` <del> * getInitialState: function() { <del> * var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); <del> * return { <del> * dataSource: ds.cloneWithRows(['row 1', 'row 2']), <del> * }; <del> * }, <add> * class MyComponent extends Component { <add> * constructor() { <add> * super(); <add> * const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); <add> * this.state = { <add> * dataSource: ds.cloneWithRows(['row 1', 'row 2']), <add> * }; <add> * } <ide> * <del> * render: function() { <del> * return ( <del> * <ListView <del> * dataSource={this.state.dataSource} <del> * renderRow={(rowData) => <Text>{rowData}</Text>} <del> * /> <del> * ); <del> * }, <add> * render() { <add> * return ( <add> * <ListView <add> * dataSource={this.state.dataSource} <add> * renderRow={(rowData) => <Text>{rowData}</Text>} <add> * /> <add> * ); <add> * } <add> * } <ide> * ``` <ide> * <ide> * ListView also supports more advanced features, including sections with sticky
1
Python
Python
fix gradient checkpoint test in encoder-decoder
c6c9db3d0cc36c5fe57d508b669c305ac7894145
<ide><path>tests/models/encoder_decoder/test_modeling_encoder_decoder.py <ide> def test_training_gradient_checkpointing(self): <ide> ) <ide> <ide> model = EncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) <del> model.train() <add> model.to(torch_device) <ide> model.gradient_checkpointing_enable() <add> model.train() <add> <ide> model.config.decoder_start_token_id = 0 <ide> model.config.pad_token_id = 0 <ide> <ide> def test_training_gradient_checkpointing(self): <ide> "labels": inputs_dict["labels"], <ide> "decoder_input_ids": inputs_dict["decoder_input_ids"], <ide> } <add> model_inputs = {k: v.to(torch_device) for k, v in model_inputs.items()} <add> <ide> loss = model(**model_inputs).loss <ide> loss.backward() <ide>
1
Text
Text
fix grammatical errors
50298e608076374ec72bae18ba4be8e3a7802aaf
<ide><path>threejs/lessons/fr/threejs-primitives.md <ide> Title: Primitives de Three.js <del>Description: Un tour des primitives de three.js <add>Description: Un tour des primitives de Three.js <ide> TOC: Primitives <ide> <del>Cet article fait partie d'une série consacrée à three.js. <del>Le premier article est [Principes de base](threejs-fundamentals.html). <add>Cet article fait partie d'une série consacrée à Three.js. <add>Le premier article s'intitule [Principes de base](threejs-fundamentals.html). <ide> Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là. <ide> <ide> Three.js a un grand nombre de primitives. Les primitives <ide> applications 3D, il est courant de demander à un artiste de faire des modèles <ide> dans un programme de modélisation 3D comme [Blender](https://blender.org), <ide> [Maya](https://www.autodesk.com/products/maya/) ou [Cinema 4D](https://www.maxon.net/en-us/products/cinema-4d/). <ide> Plus tard dans cette série, <del>nous aborderons la conception et le chargement de données de <add>nous aborderons la conception et le chargement de données provenant de <ide> plusieurs programme de modélisation 3D. Pour l'instant, passons <ide> en revue certaines primitives disponibles. <ide> <ide> La plupart des primitives ci-dessous ont des valeurs par défaut <del>pour certains ou tous leurs paramètres. Vous pouvez donc les <add>pour certain ou tous leurs paramètres. Vous pouvez donc les <ide> utiliser en fonction de vos besoins. <ide> <ide> <div id="Diagram-BoxGeometry" data-primitive="BoxGeometry">Une Boîte</div> <ide> utiliser en fonction de vos besoins. <ide> <div id="Diagram-DodecahedronGeometry" data-primitive="DodecahedronGeometry">Un Dodécaèdre (12 côtés)</div> <ide> <div id="Diagram-ExtrudeGeometry" data-primitive="ExtrudeGeometry">Une forme 2D extrudée avec un biseautage optionnel. Ici, nous extrudons une forme de cœur. Notez qu'il s'agit du principe de fonctionnement pour les <code>TextGeometry</code> et les <code>TextGeometry</code>.</div> <ide> <div id="Diagram-IcosahedronGeometry" data-primitive="IcosahedronGeometry">Un Icosaèdre (20 côtés)</div> <del><div id="Diagram-LatheGeometry" data-primitive="LatheGeometry">Une forme généré par la rotation d'une ligne pour, par exemple, dessiner une lampe, une quille, bougies, bougeoirs, verres à vin, verres à boire, etc. Vous fournissez une silhouette en deux dimensions comme une série de points et vous indiquez ensuite à three.js combien de subdivisions sont nécessaires en faisant tourner la silhouette autour d'un axe.</div> <add><div id="Diagram-LatheGeometry" data-primitive="LatheGeometry">Une forme généré par la rotation d'une ligne pour, par exemple, dessiner une lampe, une quille, une bougie, un bougeoir, un verre à vin, etc. Vous fournissez une silhouette en deux dimensions comme une série de points et vous indiquez ensuite à Three.js combien de subdivisions sont nécessaires en faisant tourner la silhouette autour d'un axe.</div> <ide> <div id="Diagram-OctahedronGeometry" data-primitive="OctahedronGeometry">Un Octaèdre (8 côtés)</div> <ide> <div id="Diagram-ParametricGeometry" data-primitive="ParametricGeometry">Une surface générée en fournissant à la fonction un point 2D d'une grille et retourne le point 3D correspondant.</div> <ide> <div id="Diagram-PlaneGeometry" data-primitive="PlaneGeometry">Un plan 2D</div>
1
Text
Text
remove last remaining danger
ca473de52f5f2245326a1c28907c88f062aa38ee
<ide><path>docs/how-to-translate-files.md <ide> These files will most likely be maintained by your language lead but you are wel <ide> <ide> ### On Crowdin <ide> <del>> [!DANGER] <add>> [!ATTENTION] <ide> > Do not edit the following files through a GitHub PR. <ide> <ide> The `intro.json` and `translations.json` files are both translated on Crowdin, in the Learn User Interface project. Translating these can be a bit tricky, as each individual JSON value appears as its own string and sometimes the context is missing.
1
Javascript
Javascript
allow autocompletion for scoped packages
e248f7f9e7410c6c40cddc63f4b4f33547788895
<ide><path>lib/repl.js <ide> ArrayStream.prototype.writable = true; <ide> ArrayStream.prototype.resume = function() {}; <ide> ArrayStream.prototype.write = function() {}; <ide> <del>const requireRE = /\brequire\s*\(['"](([\w./-]+\/)?([\w./-]*))/; <add>const requireRE = /\brequire\s*\(['"](([\w@./-]+\/)?([\w@./-]*))/; <ide> const simpleExpressionRE = <ide> /(([a-zA-Z_$](?:\w|\$)*)\.)*([a-zA-Z_$](?:\w|\$)*)\.?$/; <ide> <ide><path>test/fixtures/node_modules/@nodejsscope/index.js <add>// Not used <ide><path>test/parallel/test-repl-tab-complete.js <ide> 'use strict'; <ide> <del>var common = require('../common'); <del>var assert = require('assert'); <del>var repl = require('repl'); <add>const common = require('../common'); <add>const assert = require('assert'); <add> <add>// We have to change the directory to ../fixtures before requiring repl <add>// in order to make the tests for completion of node_modules work properly <add>// since repl modifies module.paths. <add>process.chdir(common.fixturesDir); <add> <add>const repl = require('repl'); <ide> <ide> function getNoResultsFunction() { <ide> return common.mustCall((err, data) => { <ide> testMe.complete('require(\'n', common.mustCall(function(error, data) { <ide> }); <ide> })); <ide> <add>{ <add> const expected = ['@nodejsscope', '@nodejsscope/']; <add> putIn.run(['.clear']); <add> testMe.complete('require(\'@nodejs', common.mustCall((err, data) => { <add> assert.strictEqual(err, null); <add> assert.deepStrictEqual(data, [expected, '@nodejs']); <add> })); <add>} <add> <ide> // Make sure tab completion works on context properties <ide> putIn.run(['.clear']); <ide>
3
Go
Go
fix random bug in cli events test
e15c3e36cc5559c3ec17179d8740b2841709daf5
<ide><path>integration-cli/docker_cli_events_test.go <ide> func TestEventsFilterContainerID(t *testing.T) { <ide> container2 := stripTrailingCharacters(out) <ide> <ide> for _, s := range []string{container1, container2, container1[:12], container2[:12]} { <add> if err := waitInspect(s, "{{.State.Running}}", "false", 5); err != nil { <add> t.Fatalf("Failed to get container %s state, error: %s", s, err) <add> } <add> <ide> eventsCmd := exec.Command(dockerBinary, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(t).Unix()), "--filter", fmt.Sprintf("container=%s", s)) <ide> out, _, err := runCommandWithOutput(eventsCmd) <ide> if err != nil { <ide> func TestEventsFilterContainerName(t *testing.T) { <ide> } <ide> <ide> for _, s := range []string{"container_1", "container_2"} { <add> if err := waitInspect(s, "{{.State.Running}}", "false", 5); err != nil { <add> t.Fatalf("Failed to get container %s state, error: %s", s, err) <add> } <add> <ide> eventsCmd := exec.Command(dockerBinary, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(t).Unix()), "--filter", fmt.Sprintf("container=%s", s)) <ide> out, _, err := runCommandWithOutput(eventsCmd) <ide> if err != nil {
1
Javascript
Javascript
enable fourth italian cert
dcf31599125e04c8209a398e993e0ef618d59e32
<ide><path>config/i18n/all-langs.js <ide> const auditedCerts = { <ide> italian: [ <ide> 'responsive-web-design', <ide> 'javascript-algorithms-and-data-structures', <del> 'front-end-libraries' <add> 'front-end-libraries', <add> 'data-visualization' <ide> ], <ide> portuguese: ['responsive-web-design'] <ide> };
1
Python
Python
replace // operator with / operator + long()
33929448a1af579cf1d2ef76d1da8f26e1b50de1
<ide><path>src/transformers/generation_utils.py <ide> def beam_search( <ide> next_token_scores, 2 * num_beams, dim=1, largest=True, sorted=True <ide> ) <ide> <del> next_indices = next_tokens // vocab_size <add> next_indices = (next_tokens / vocab_size).long() <ide> next_tokens = next_tokens % vocab_size <ide> <ide> # stateless
1
Java
Java
convert testcontext to interface & default impl
88fe2e9b00b68b05c35f2204dbc5783ff04d9bcc
<ide><path>spring-test/src/main/java/org/springframework/test/context/DefaultTestContext.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.test.context; <add> <add>import java.lang.reflect.Method; <add> <add>import org.apache.commons.logging.Log; <add>import org.apache.commons.logging.LogFactory; <add> <add>import org.springframework.context.ApplicationContext; <add>import org.springframework.core.AttributeAccessorSupport; <add>import org.springframework.core.style.ToStringCreator; <add>import org.springframework.test.annotation.DirtiesContext.HierarchyMode; <add>import org.springframework.util.Assert; <add> <add>/** <add> * Default implementation of the {@link TestContext} interface. <add> * <add> * <p>Although {@code DefaultTestContext} was first introduced in Spring Framework <add> * 4.0, the initial implementation of this class was extracted from the existing <add> * code base for {@code TestContext} when {@code TestContext} was converted into <add> * an interface. <add> * <add> * @author Sam Brannen <add> * @author Juergen Hoeller <add> * @since 4.0 <add> */ <add>class DefaultTestContext extends AttributeAccessorSupport implements TestContext { <add> <add> private static final long serialVersionUID = -5827157174866681233L; <add> <add> private static final Log logger = LogFactory.getLog(DefaultTestContext.class); <add> <add> private final ContextCache contextCache; <add> <add> private final CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate; <add> <add> private final MergedContextConfiguration mergedContextConfiguration; <add> <add> private final Class<?> testClass; <add> <add> private Object testInstance; <add> <add> private Method testMethod; <add> <add> private Throwable testException; <add> <add> <add> /** <add> * Delegates to {@link #DefaultTestContext(Class, ContextCache, String)} with a <add> * value of {@code null} for the default {@code ContextLoader} class name. <add> */ <add> DefaultTestContext(Class<?> testClass, ContextCache contextCache) { <add> this(testClass, contextCache, null); <add> } <add> <add> /** <add> * Construct a new test context for the supplied {@linkplain Class test class} <add> * and {@linkplain ContextCache context cache} and parse the corresponding <add> * {@link ContextConfiguration &#064;ContextConfiguration} or <add> * {@link ContextHierarchy &#064;ContextHierarchy} annotation, if present. <add> * <p>If the supplied class name for the default {@code ContextLoader} <add> * is {@code null} or <em>empty</em> and no concrete {@code ContextLoader} <add> * class is explicitly supplied via {@code @ContextConfiguration}, a <add> * {@link org.springframework.test.context.support.DelegatingSmartContextLoader <add> * DelegatingSmartContextLoader} or <add> * {@link org.springframework.test.context.web.WebDelegatingSmartContextLoader <add> * WebDelegatingSmartContextLoader} will be used instead. <add> * @param testClass the test class for which the test context should be <add> * constructed (must not be {@code null}) <add> * @param contextCache the context cache from which the constructed test <add> * context should retrieve application contexts (must not be <add> * {@code null}) <add> * @param defaultContextLoaderClassName the name of the default <add> * {@code ContextLoader} class to use (may be {@code null}) <add> */ <add> DefaultTestContext(Class<?> testClass, ContextCache contextCache, String defaultContextLoaderClassName) { <add> Assert.notNull(testClass, "Test class must not be null"); <add> Assert.notNull(contextCache, "ContextCache must not be null"); <add> <add> this.testClass = testClass; <add> this.contextCache = contextCache; <add> this.cacheAwareContextLoaderDelegate = new CacheAwareContextLoaderDelegate(contextCache); <add> <add> MergedContextConfiguration mergedContextConfiguration; <add> <add> if (testClass.isAnnotationPresent(ContextConfiguration.class) <add> || testClass.isAnnotationPresent(ContextHierarchy.class)) { <add> mergedContextConfiguration = ContextLoaderUtils.buildMergedContextConfiguration(testClass, <add> defaultContextLoaderClassName, cacheAwareContextLoaderDelegate); <add> } <add> else { <add> if (logger.isInfoEnabled()) { <add> logger.info(String.format( <add> "Neither @ContextConfiguration nor @ContextHierarchy found for test class [%s]", <add> testClass.getName())); <add> } <add> mergedContextConfiguration = new MergedContextConfiguration(testClass, null, null, null, null); <add> } <add> <add> this.mergedContextConfiguration = mergedContextConfiguration; <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> public ApplicationContext getApplicationContext() { <add> return cacheAwareContextLoaderDelegate.loadContext(mergedContextConfiguration); <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> public final Class<?> getTestClass() { <add> return testClass; <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> public final Object getTestInstance() { <add> return testInstance; <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> public final Method getTestMethod() { <add> return testMethod; <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> public final Throwable getTestException() { <add> return testException; <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> public void markApplicationContextDirty(HierarchyMode hierarchyMode) { <add> contextCache.remove(mergedContextConfiguration, hierarchyMode); <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> public void updateState(Object testInstance, Method testMethod, Throwable testException) { <add> this.testInstance = testInstance; <add> this.testMethod = testMethod; <add> this.testException = testException; <add> } <add> <add> /** <add> * Provide a String representation of this test context's state. <add> */ <add> @Override <add> public String toString() { <add> return new ToStringCreator(this)// <add> .append("testClass", testClass)// <add> .append("testInstance", testInstance)// <add> .append("testMethod", testMethod)// <add> .append("testException", testException)// <add> .append("mergedContextConfiguration", mergedContextConfiguration)// <add> .toString(); <add> } <add> <add>} <ide><path>spring-test/src/main/java/org/springframework/test/context/TestContext.java <ide> <ide> package org.springframework.test.context; <ide> <add>import java.io.Serializable; <ide> import java.lang.reflect.Method; <ide> <del>import org.apache.commons.logging.Log; <del>import org.apache.commons.logging.LogFactory; <del> <ide> import org.springframework.context.ApplicationContext; <del>import org.springframework.core.AttributeAccessorSupport; <del>import org.springframework.core.style.ToStringCreator; <add>import org.springframework.core.AttributeAccessor; <ide> import org.springframework.test.annotation.DirtiesContext.HierarchyMode; <del>import org.springframework.util.Assert; <ide> <ide> /** <ide> * {@code TestContext} encapsulates the context in which a test is executed, <ide> * agnostic of the actual testing framework in use. <ide> * <ide> * @author Sam Brannen <del> * @author Juergen Hoeller <ide> * @since 2.5 <ide> */ <del>public class TestContext extends AttributeAccessorSupport { <del> <del> private static final long serialVersionUID = -5827157174866681233L; <del> <del> private static final Log logger = LogFactory.getLog(TestContext.class); <del> <del> private final ContextCache contextCache; <del> <del> private final CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate; <del> <del> private final MergedContextConfiguration mergedContextConfiguration; <del> <del> private final Class<?> testClass; <del> <del> private Object testInstance; <del> <del> private Method testMethod; <del> <del> private Throwable testException; <del> <del> <del> /** <del> * Delegates to {@link #TestContext(Class, ContextCache, String)} with a <del> * value of {@code null} for the default {@code ContextLoader} class name. <del> */ <del> TestContext(Class<?> testClass, ContextCache contextCache) { <del> this(testClass, contextCache, null); <del> } <del> <del> /** <del> * Construct a new test context for the supplied {@linkplain Class test class} <del> * and {@linkplain ContextCache context cache} and parse the corresponding <del> * {@link ContextConfiguration &#064;ContextConfiguration} or <del> * {@link ContextHierarchy &#064;ContextHierarchy} annotation, if present. <del> * <p>If the supplied class name for the default {@code ContextLoader} <del> * is {@code null} or <em>empty</em> and no concrete {@code ContextLoader} <del> * class is explicitly supplied via {@code @ContextConfiguration}, a <del> * {@link org.springframework.test.context.support.DelegatingSmartContextLoader <del> * DelegatingSmartContextLoader} or <del> * {@link org.springframework.test.context.web.WebDelegatingSmartContextLoader <del> * WebDelegatingSmartContextLoader} will be used instead. <del> * @param testClass the test class for which the test context should be <del> * constructed (must not be {@code null}) <del> * @param contextCache the context cache from which the constructed test <del> * context should retrieve application contexts (must not be <del> * {@code null}) <del> * @param defaultContextLoaderClassName the name of the default <del> * {@code ContextLoader} class to use (may be {@code null}) <del> */ <del> TestContext(Class<?> testClass, ContextCache contextCache, String defaultContextLoaderClassName) { <del> Assert.notNull(testClass, "Test class must not be null"); <del> Assert.notNull(contextCache, "ContextCache must not be null"); <del> <del> this.testClass = testClass; <del> this.contextCache = contextCache; <del> this.cacheAwareContextLoaderDelegate = new CacheAwareContextLoaderDelegate(contextCache); <del> <del> MergedContextConfiguration mergedContextConfiguration; <del> <del> if (testClass.isAnnotationPresent(ContextConfiguration.class) <del> || testClass.isAnnotationPresent(ContextHierarchy.class)) { <del> mergedContextConfiguration = ContextLoaderUtils.buildMergedContextConfiguration(testClass, <del> defaultContextLoaderClassName, cacheAwareContextLoaderDelegate); <del> } <del> else { <del> if (logger.isInfoEnabled()) { <del> logger.info(String.format( <del> "Neither @ContextConfiguration nor @ContextHierarchy found for test class [%s]", <del> testClass.getName())); <del> } <del> mergedContextConfiguration = new MergedContextConfiguration(testClass, null, null, null, null); <del> } <del> <del> this.mergedContextConfiguration = mergedContextConfiguration; <del> } <add>public interface TestContext extends AttributeAccessor, Serializable { <ide> <ide> /** <ide> * Get the {@link ApplicationContext application context} for this test <ide> * context, possibly cached. <add> * <add> * <p>Implementations of this method are responsible for loading the <add> * application context if the corresponding context has not already been <add> * loaded, potentially caching the context as well. <ide> * @return the application context <ide> * @throws IllegalStateException if an error occurs while retrieving the <ide> * application context <ide> */ <del> public ApplicationContext getApplicationContext() { <del> return cacheAwareContextLoaderDelegate.loadContext(mergedContextConfiguration); <del> } <add> ApplicationContext getApplicationContext(); <ide> <ide> /** <ide> * Get the {@link Class test class} for this test context. <ide> * @return the test class (never {@code null}) <ide> */ <del> public final Class<?> getTestClass() { <del> return testClass; <del> } <add> Class<?> getTestClass(); <ide> <ide> /** <ide> * Get the current {@link Object test instance} for this test context. <ide> * <p>Note: this is a mutable property. <ide> * @return the current test instance (may be {@code null}) <ide> * @see #updateState(Object, Method, Throwable) <ide> */ <del> public final Object getTestInstance() { <del> return testInstance; <del> } <add> Object getTestInstance(); <ide> <ide> /** <ide> * Get the current {@link Method test method} for this test context. <ide> * <p>Note: this is a mutable property. <ide> * @return the current test method (may be {@code null}) <ide> * @see #updateState(Object, Method, Throwable) <ide> */ <del> public final Method getTestMethod() { <del> return testMethod; <del> } <add> Method getTestMethod(); <ide> <ide> /** <ide> * Get the {@link Throwable exception} that was thrown during execution of <ide> public final Method getTestMethod() { <ide> * exception was thrown <ide> * @see #updateState(Object, Method, Throwable) <ide> */ <del> public final Throwable getTestException() { <del> return testException; <del> } <del> <del> /** <del> * Call this method to signal that the {@linkplain ApplicationContext application <del> * context} associated with this test context is <em>dirty</em> and should be <del> * discarded. Do this if a test has modified the context &mdash; for example, <del> * by replacing a bean definition or modifying the state of a singleton bean. <del> * @deprecated as of Spring 3.2.2; use <del> * {@link #markApplicationContextDirty(DirtiesContext.HierarchyMode)} instead. <del> */ <del> @Deprecated <del> public void markApplicationContextDirty() { <del> markApplicationContextDirty((HierarchyMode) null); <del> } <add> Throwable getTestException(); <ide> <ide> /** <ide> * Call this method to signal that the {@linkplain ApplicationContext application <ide> public void markApplicationContextDirty() { <ide> * @param hierarchyMode the context cache clearing mode to be applied if the <ide> * context is part of a hierarchy (may be {@code null}) <ide> */ <del> public void markApplicationContextDirty(HierarchyMode hierarchyMode) { <del> contextCache.remove(mergedContextConfiguration, hierarchyMode); <del> } <add> void markApplicationContextDirty(HierarchyMode hierarchyMode); <ide> <ide> /** <ide> * Update this test context to reflect the state of the currently executing <ide> * test. <add> * <p>Caution: concurrent invocations of this method might not be thread-safe, <add> * depending on the underlying implementation. <ide> * @param testInstance the current test instance (may be {@code null}) <ide> * @param testMethod the current test method (may be {@code null}) <ide> * @param testException the exception that was thrown in the test method, or <ide> * {@code null} if no exception was thrown <ide> */ <del> void updateState(Object testInstance, Method testMethod, Throwable testException) { <del> this.testInstance = testInstance; <del> this.testMethod = testMethod; <del> this.testException = testException; <del> } <del> <del> /** <del> * Provide a String representation of this test context's state. <del> */ <del> @Override <del> public String toString() { <del> return new ToStringCreator(this)// <del> .append("testClass", testClass)// <del> .append("testInstance", testInstance)// <del> .append("testMethod", testMethod)// <del> .append("testException", testException)// <del> .append("mergedContextConfiguration", mergedContextConfiguration)// <del> .toString(); <del> } <add> void updateState(Object testInstance, Method testMethod, Throwable testException); <ide> <ide> } <ide><path>spring-test/src/main/java/org/springframework/test/context/TestContextManager.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 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> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <del> <ide> import org.springframework.beans.BeanUtils; <ide> import org.springframework.context.ApplicationContext; <ide> import org.springframework.core.annotation.AnnotationUtils; <ide> public TestContextManager(Class<?> testClass) { <ide> * @see #registerTestExecutionListeners(TestExecutionListener...) <ide> */ <ide> public TestContextManager(Class<?> testClass, String defaultContextLoaderClassName) { <del> this.testContext = new TestContext(testClass, contextCache, defaultContextLoaderClassName); <add> this.testContext = new DefaultTestContext(testClass, contextCache, defaultContextLoaderClassName); <ide> registerTestExecutionListeners(retrieveTestExecutionListeners(testClass)); <ide> } <ide> <ide> private TestExecutionListener[] retrieveTestExecutionListeners(Class<?> clazz) { <ide> } <ide> classesList.addAll(getDefaultTestExecutionListenerClasses()); <ide> defaultListeners = true; <del> } else { <add> } <add> else { <ide> // Traverse the class hierarchy... <ide> while (declaringClass != null) { <ide> TestExecutionListeners testExecutionListeners = declaringClass.getAnnotation(annotationType); <ide> private TestExecutionListener[] retrieveTestExecutionListeners(Class<?> clazz) { <ide> ObjectUtils.nullSafeToString(listenerClasses)); <ide> logger.error(msg); <ide> throw new IllegalStateException(msg); <del> } else if (!ObjectUtils.isEmpty(valueListenerClasses)) { <add> } <add> else if (!ObjectUtils.isEmpty(valueListenerClasses)) { <ide> listenerClasses = valueListenerClasses; <ide> } <ide> <ide> private TestExecutionListener[] retrieveTestExecutionListeners(Class<?> clazz) { <ide> for (Class<? extends TestExecutionListener> listenerClass : classesList) { <ide> try { <ide> listeners.add(BeanUtils.instantiateClass(listenerClass)); <del> } catch (NoClassDefFoundError err) { <add> } <add> catch (NoClassDefFoundError err) { <ide> if (defaultListeners) { <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("Could not instantiate default TestExecutionListener class [" <ide> + listenerClass.getName() <ide> + "]. Specify custom listener classes or make the default listener classes available."); <ide> } <del> } else { <add> } <add> else { <ide> throw err; <ide> } <ide> } <ide> protected Set<Class<? extends TestExecutionListener>> getDefaultTestExecutionLis <ide> try { <ide> defaultListenerClasses.add((Class<? extends TestExecutionListener>) getClass().getClassLoader().loadClass( <ide> className)); <del> } catch (Throwable t) { <add> } <add> catch (Throwable t) { <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("Could not load default TestExecutionListener class [" + className <ide> + "]. Specify custom listener classes or make the default listener classes available.", t); <ide> public void beforeTestClass() throws Exception { <ide> for (TestExecutionListener testExecutionListener : getTestExecutionListeners()) { <ide> try { <ide> testExecutionListener.beforeTestClass(getTestContext()); <del> } catch (Exception ex) { <add> } <add> catch (Exception ex) { <ide> logger.warn("Caught exception while allowing TestExecutionListener [" + testExecutionListener <ide> + "] to process 'before class' callback for test class [" + testClass + "]", ex); <ide> throw ex; <ide> public void prepareTestInstance(Object testInstance) throws Exception { <ide> for (TestExecutionListener testExecutionListener : getTestExecutionListeners()) { <ide> try { <ide> testExecutionListener.prepareTestInstance(getTestContext()); <del> } catch (Exception ex) { <add> } <add> catch (Exception ex) { <ide> logger.error("Caught exception while allowing TestExecutionListener [" + testExecutionListener <ide> + "] to prepare test instance [" + testInstance + "]", ex); <ide> throw ex; <ide> public void beforeTestMethod(Object testInstance, Method testMethod) throws Exce <ide> for (TestExecutionListener testExecutionListener : getTestExecutionListeners()) { <ide> try { <ide> testExecutionListener.beforeTestMethod(getTestContext()); <del> } catch (Exception ex) { <add> } <add> catch (Exception ex) { <ide> logger.warn("Caught exception while allowing TestExecutionListener [" + testExecutionListener <ide> + "] to process 'before' execution of test method [" + testMethod + "] for test instance [" <ide> + testInstance + "]", ex); <ide> public void afterTestMethod(Object testInstance, Method testMethod, Throwable ex <ide> for (TestExecutionListener testExecutionListener : getReversedTestExecutionListeners()) { <ide> try { <ide> testExecutionListener.afterTestMethod(getTestContext()); <del> } catch (Exception ex) { <add> } <add> catch (Exception ex) { <ide> logger.warn("Caught exception while allowing TestExecutionListener [" + testExecutionListener <ide> + "] to process 'after' execution for test: method [" + testMethod + "], instance [" <ide> + testInstance + "], exception [" + exception + "]", ex); <ide> public void afterTestClass() throws Exception { <ide> for (TestExecutionListener testExecutionListener : getReversedTestExecutionListeners()) { <ide> try { <ide> testExecutionListener.afterTestClass(getTestContext()); <del> } catch (Exception ex) { <add> } <add> catch (Exception ex) { <ide> logger.warn("Caught exception while allowing TestExecutionListener [" + testExecutionListener <ide> + "] to process 'after class' callback for test class [" + testClass + "]", ex); <ide> if (afterTestClassException == null) { <ide><path>spring-test/src/main/java/org/springframework/test/context/support/DirtiesContextTestExecutionListener.java <ide> public class DirtiesContextTestExecutionListener extends AbstractTestExecutionLi <ide> private static final Log logger = LogFactory.getLog(DirtiesContextTestExecutionListener.class); <ide> <ide> <del> /** <del> * Marks the {@linkplain ApplicationContext application context} of the supplied <del> * {@linkplain TestContext test context} as <del> * {@linkplain TestContext#markApplicationContextDirty() dirty}, and sets the <del> * {@link DependencyInjectionTestExecutionListener#REINJECT_DEPENDENCIES_ATTRIBUTE} <del> * in the test context to {@code true}. <del> * @param testContext the test context whose application context should <del> * marked as dirty <del> * @deprecated as of Spring 3.2.2, use {@link #dirtyContext(TestContext, HierarchyMode)} instead. <del> */ <del> @Deprecated <del> protected void dirtyContext(TestContext testContext) { <del> testContext.markApplicationContextDirty(); <del> testContext.setAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE, Boolean.TRUE); <del> } <del> <ide> /** <ide> * Marks the {@linkplain ApplicationContext application context} of the supplied <ide> * {@linkplain TestContext test context} as <ide><path>spring-test/src/test/java/org/springframework/test/context/ContextCacheTests.java <ide> private MergedContextConfiguration getMergedContextConfiguration(TestContext tes <ide> } <ide> <ide> private ApplicationContext loadContext(Class<?> testClass) { <del> TestContext testContext = new TestContext(testClass, contextCache); <add> TestContext testContext = new DefaultTestContext(testClass, contextCache); <ide> return testContext.getApplicationContext(); <ide> } <ide> <ide> public void verifyCacheBehaviorForContextHierarchies() { <ide> public void removeContextHierarchyCacheLevel1() { <ide> <ide> // Load Level 3-A <del> TestContext testContext3a = new TestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache); <add> TestContext testContext3a = new DefaultTestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, <add> contextCache); <ide> testContext3a.getApplicationContext(); <ide> assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3); <ide> assertParentContextCount(2); <ide> <ide> // Load Level 3-B <del> TestContext testContext3b = new TestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache); <add> TestContext testContext3b = new DefaultTestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, <add> contextCache); <ide> testContext3b.getApplicationContext(); <ide> assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4); <ide> assertParentContextCount(2); <ide> public void removeContextHierarchyCacheLevel1() { <ide> public void removeContextHierarchyCacheLevel1WithExhaustiveMode() { <ide> <ide> // Load Level 3-A <del> TestContext testContext3a = new TestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache); <add> TestContext testContext3a = new DefaultTestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, <add> contextCache); <ide> testContext3a.getApplicationContext(); <ide> assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3); <ide> assertParentContextCount(2); <ide> <ide> // Load Level 3-B <del> TestContext testContext3b = new TestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache); <add> TestContext testContext3b = new DefaultTestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, <add> contextCache); <ide> testContext3b.getApplicationContext(); <ide> assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4); <ide> assertParentContextCount(2); <ide> public void removeContextHierarchyCacheLevel1WithExhaustiveMode() { <ide> public void removeContextHierarchyCacheLevel2() { <ide> <ide> // Load Level 3-A <del> TestContext testContext3a = new TestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache); <add> TestContext testContext3a = new DefaultTestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, <add> contextCache); <ide> testContext3a.getApplicationContext(); <ide> assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3); <ide> assertParentContextCount(2); <ide> <ide> // Load Level 3-B <del> TestContext testContext3b = new TestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache); <add> TestContext testContext3b = new DefaultTestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, <add> contextCache); <ide> testContext3b.getApplicationContext(); <ide> assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4); <ide> assertParentContextCount(2); <ide> public void removeContextHierarchyCacheLevel2() { <ide> public void removeContextHierarchyCacheLevel2WithExhaustiveMode() { <ide> <ide> // Load Level 3-A <del> TestContext testContext3a = new TestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache); <add> TestContext testContext3a = new DefaultTestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, <add> contextCache); <ide> testContext3a.getApplicationContext(); <ide> assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3); <ide> assertParentContextCount(2); <ide> <ide> // Load Level 3-B <del> TestContext testContext3b = new TestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache); <add> TestContext testContext3b = new DefaultTestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, <add> contextCache); <ide> testContext3b.getApplicationContext(); <ide> assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4); <ide> assertParentContextCount(2); <ide> public void removeContextHierarchyCacheLevel2WithExhaustiveMode() { <ide> public void removeContextHierarchyCacheLevel3Then2() { <ide> <ide> // Load Level 3-A <del> TestContext testContext3a = new TestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache); <add> TestContext testContext3a = new DefaultTestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, <add> contextCache); <ide> testContext3a.getApplicationContext(); <ide> assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3); <ide> assertParentContextCount(2); <ide> <ide> // Load Level 3-B <del> TestContext testContext3b = new TestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache); <add> TestContext testContext3b = new DefaultTestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, <add> contextCache); <ide> testContext3b.getApplicationContext(); <ide> assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4); <ide> assertParentContextCount(2); <ide> public void removeContextHierarchyCacheLevel3Then2() { <ide> public void removeContextHierarchyCacheLevel3Then2WithExhaustiveMode() { <ide> <ide> // Load Level 3-A <del> TestContext testContext3a = new TestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache); <add> TestContext testContext3a = new DefaultTestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, <add> contextCache); <ide> testContext3a.getApplicationContext(); <ide> assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3); <ide> assertParentContextCount(2); <ide> <ide> // Load Level 3-B <del> TestContext testContext3b = new TestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache); <add> TestContext testContext3b = new DefaultTestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, <add> contextCache); <ide> testContext3b.getApplicationContext(); <ide> assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4); <ide> assertParentContextCount(2);
5
Ruby
Ruby
use formulary.factory to find formula in taps
3b15b58d007c38f56315a4a09908b6efaa46ee8e
<ide><path>Library/Homebrew/cmd/search.rb <ide> def search <ide> exec_browser "https://admin.fedoraproject.org/pkgdb/acls/list/*#{ARGV.next}*" <ide> elsif ARGV.include? '--ubuntu' <ide> exec_browser "http://packages.ubuntu.com/search?keywords=#{ARGV.next}&searchon=names&suite=all&section=all" <del> elsif (query = ARGV.first).nil? <add> elsif ARGV.empty? <ide> puts_columns Formula.names <ide> elsif ARGV.first =~ HOMEBREW_TAP_FORMULA_REGEX <del> # So look for user/repo/query or list all formulae by the tap <del> # we downcase to avoid case-insensitive filesystem issues. <del> user, repo, query = $1.downcase, $2.downcase, $3 <del> tap_dir = HOMEBREW_LIBRARY/"Taps/#{user}/homebrew-#{repo}" <del> # If, instead of `user/repo/query` the user wrote `user/repo query`: <del> query = ARGV[1] if query.nil? <del> if tap_dir.directory? <del> result = "" <del> if query <del> tap_dir.find_formula do |file| <del> basename = file.basename(".rb").to_s <del> result = basename if basename == query <del> end <del> end <del> else <del> # Search online: <del> query = '' if query.nil? <del> result = search_tap(user, repo, query_regexp(query)) <add> query = ARGV.first <add> user, repo, name = query.split("/", 3) <add> <add> begin <add> result = Formulary.factory(query).name <add> rescue FormulaUnavailableError <add> result = search_tap(user, repo, name) <ide> end <del> puts_columns result <add> <add> puts_columns Array(result) <ide> else <add> query = ARGV.first <ide> rx = query_regexp(query) <ide> local_results = search_formulae(rx) <ide> puts_columns(local_results)
1
Javascript
Javascript
fix bug in retry logic
568fb403bfb5b4b92ec912812b00095047d18850
<ide><path>packager/src/lib/GlobalTransformCache.js <ide> class URIBasedGlobalTransformCache { <ide> return ( <ide> error instanceof FetchError && error.type === 'request-timeout' || ( <ide> error instanceof FetchFailedError && <del> error.details.type === 'wrong_http_status' && <add> error.details.type === 'unhandled_http_status' && <ide> (error.details.statusCode === 503 || error.details.statusCode === 502) <ide> ) <ide> );
1
PHP
PHP
add a locations method for moving test/case
e9f94d2132f5593aea9d6b92bff8f58114aae6d2
<ide><path>lib/Cake/Console/Command/UpgradeShell.php <ide> class UpgradeShell extends Shell { <ide> */ <ide> public function startup() { <ide> parent::startup(); <del> if ($this->params['dry-run']) { <add> if ($this->params['dryRun']) { <ide> $this->out(__d('cake_console', '<warning>Dry-run mode enabled!</warning>'), 1, Shell::QUIET); <ide> } <ide> } <ide> public function all() { <ide> } <ide> } <ide> <add>/** <add> * Move files and folders to their new homes <add> * <add> * @return void <add> */ <add> public function locations() { <add> $path = isset($this->args[0]) ? $this->args[0] : APP; <add> <add> if (!empty($this->params['plugin'])) { <add> $path = App::pluginPath($this->params['plugin']); <add> } <add> $path = rtrim($path, DS); <add> <add> $moves = array( <add> 'Test' . DS . 'Case' => 'Test' . DS . 'TestCase' <add> ); <add> $dry = $this->params['dryRun']; <add> <add> foreach ($moves as $old => $new) { <add> $old = $path . DS . $old; <add> $new = $path . DS . $new; <add> if (!is_dir($old)) { <add> continue; <add> } <add> $this->out(__d('cake_console', '<info>Moving %s to %s</info>', $old, $new)); <add> if ($dry) { <add> continue; <add> } <add> if ($this->params['git']) { <add> exec('git mv -f ' . escapeshellarg($old) . ' ' . escapeshellarg($old . '__')); <add> exec('git mv -f ' . escapeshellarg($old . '__') . ' ' . escapeshellarg($new)); <add> } else { <add> $Folder = new Folder($old); <add> $Folder->move($new); <add> } <add> } <add> } <add> <ide> /** <ide> * Convert App::uses() to normal use statements. <ide> * <ide> public function namespaces() { <ide> $this->_findFiles('php', ['index.php', 'test.php', 'cake.php']); <ide> <ide> foreach ($this->_files as $filePath) { <del> $this->_addNamespace($path, $filePath, $ns, $this->params['dry-run']); <add> $this->_addNamespace($path, $filePath, $ns, $this->params['dryRun']); <ide> } <ide> $this->out(__d('cake_console', '<success>Namespaces added successfully</success>')); <ide> } <ide> protected function _updateFile($file, $patterns) { <ide> } <ide> <ide> $this->out(__d('cake_console', 'Done updating %s', $file), 1); <del> if (!$this->params['dry-run']) { <add> if (!$this->params['dryRun']) { <ide> file_put_contents($file, $contents); <ide> } <ide> } <ide> protected function _updateFile($file, $patterns) { <ide> * @return ConsoleOptionParser <ide> */ <ide> public function getOptionParser() { <del> $subcommandParser = array( <del> 'options' => array( <del> 'plugin' => array( <del> 'short' => 'p', <del> 'help' => __d('cake_console', 'The plugin to update. Only the specified plugin will be updated.') <del> ), <del> 'ext' => array( <del> 'short' => 'e', <del> 'help' => __d('cake_console', 'The extension(s) to search. A pipe delimited list, or a preg_match compatible subpattern'), <del> 'default' => 'php|ctp' <del> ), <del> 'dry-run' => array( <del> 'short' => 'd', <del> 'help' => __d('cake_console', 'Dry run the update, no files will actually be modified.'), <del> 'boolean' => true <del> ) <del> ) <del> ); <del> <del> $namespaceParser = $subcommandParser; <del> $namespaceParser['options']['namespace'] = [ <add> $plugin = [ <add> 'short' => 'p', <add> 'help' => __d('cake_console', 'The plugin to update. Only the specified plugin will be updated.') <add> ]; <add> $dryRun = [ <add> 'short' => 'd', <add> 'help' => __d('cake_console', 'Dry run the update, no files will actually be modified.'), <add> 'boolean' => true <add> ]; <add> $git = [ <add> 'help' => __d('cake_console', 'Perform git operations. eg. git mv instead of just moving files.'), <add> 'boolean' => true <add> ]; <add> $namespace = [ <ide> 'help' => __d('cake_console', 'Set the base namespace you want to use. Defaults to App or the plugin name.'), <ide> 'default' => 'App', <ide> ]; <del> $namespaceParser['options']['exclude'] = [ <add> $exclude = [ <ide> 'help' => __d('cake_console', 'Comma separated list of top level diretories to exclude.'), <ide> 'default' => '', <ide> ]; <ide> <ide> return parent::getOptionParser() <del> ->description(__d('cake_console', "A shell to help automate upgrading from CakePHP 1.3 to 2.0. \n" . <add> ->description(__d('cake_console', "A shell to help automate upgrading from CakePHP 3.0 to 2.x. \n" . <ide> "Be sure to have a backup of your application before running these commands.")) <ide> ->addSubcommand('all', array( <ide> 'help' => __d('cake_console', 'Run all upgrade commands.'), <del> 'parser' => $subcommandParser <add> 'parser' => ['options' => compact('plugin', 'dryRun')] <ide> )) <del> ->addSubcommand('app_uses', array( <del> 'help' => __d('cake_console', 'Replace App::uses() with use statements'), <del> 'parser' => $subcommandParser <add> ->addSubcommand('locations', array( <add> 'help' => __d('cake_console', 'Move files/directories around. Run this *before* adding namespaces with the namespaces command.'), <add> 'parser' => ['options' => compact('plugin', 'dryRun', 'git')] <ide> )) <ide> ->addSubcommand('namespaces', array( <del> 'help' => __d('cake_console', 'Add namespaces to files based on their file path.'), <del> 'parser' => $namespaceParser <add> 'help' => __d('cake_console', 'Add namespaces to files based on their file path. Only run this *after* you have moved files.'), <add> 'parser' => ['options' => compact('plugin', 'dryRun', 'namespace', 'exclude')] <add> )) <add> ->addSubcommand('app_uses', array( <add> 'help' => __d('cake_console', 'Replace App::uses() with use statements'), <add> 'parser' => ['options' => compact('plugin', 'dryRun')] <ide> )) <ide> ->addSubcommand('cache', array( <ide> 'help' => __d('cake_console', "Replace Cache::config() with Configure."), <del> 'parser' => $subcommandParser <add> 'parser' => ['options' => compact('plugin', 'dryRun')] <ide> )) <ide> ->addSubcommand('log', array( <ide> 'help' => __d('cake_console', "Replace CakeLog::config() with Configure."), <del> 'parser' => $subcommandParser <add> 'parser' => ['options' => compact('plugin', 'dryRun')] <ide> )); <ide> } <ide>
1
Ruby
Ruby
extract simplified_type into the abstract class
4fcd847c8d9fb2b22e1c2e3c840c8d1c590b56b4
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> module ActiveRecord <ide> module ConnectionAdapters <ide> class AbstractMysqlAdapter < AbstractAdapter <del> class Column < ConnectionAdapters::Column <add> class Column < ConnectionAdapters::Column # :nodoc: <ide> def extract_default(default) <ide> if sql_type =~ /blob/i || type == :text <ide> if default.blank? <ide> def has_default? <ide> super <ide> end <ide> <add> # Must return the relevant concrete adapter <add> def adapter <add> raise NotImplementedError <add> end <add> <ide> private <ide> <add> def simplified_type(field_type) <add> return :boolean if adapter.emulate_booleans && field_type.downcase.index("tinyint(1)") <add> <add> case field_type <add> when /enum/i, /set/i then :string <add> when /year/i then :integer <add> when /bit/i then :binary <add> else <add> super <add> end <add> end <add> <ide> def extract_limit(sql_type) <ide> case sql_type <ide> when /blob|text/i <ide><path>activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb <ide> def self.mysql2_connection(config) <ide> <ide> module ConnectionAdapters <ide> class Mysql2Adapter < AbstractMysqlAdapter <del> class Column < AbstractMysqlAdapter::Column # :nodoc: <del> BOOL = "tinyint(1)" <del> <del> private <del> <del> # FIXME: Combine with the mysql version and move to abstract adapter <del> def simplified_type(field_type) <del> return :boolean if Mysql2Adapter.emulate_booleans && field_type.downcase.index(BOOL) <ide> <del> case field_type <del> when /enum/i, /set/i then :string <del> when /year/i then :integer <del> when /bit/i then :binary <del> else <del> super <del> end <add> class Column < AbstractMysqlAdapter::Column # :nodoc: <add> def adapter <add> Mysql2Adapter <ide> end <ide> end <ide> <ide><path>activerecord/lib/active_record/connection_adapters/mysql_adapter.rb <ide> module ConnectionAdapters <ide> # * <tt>:sslcipher</tt> - Necessary to use MySQL with an SSL connection. <ide> # <ide> class MysqlAdapter < AbstractMysqlAdapter <add> <ide> class Column < AbstractMysqlAdapter::Column #:nodoc: <ide> def self.string_to_time(value) <ide> return super unless Mysql::Time === value <ide> def self.string_to_date(v) <ide> new_date(v.year, v.month, v.day) <ide> end <ide> <del> private <del> <del> # FIXME: Combine with the mysql2 version and move to abstract adapter <del> def simplified_type(field_type) <del> return :boolean if MysqlAdapter.emulate_booleans && field_type.downcase.index("tinyint(1)") <del> return :string if field_type =~ /enum/i <del> super <add> def adapter <add> MysqlAdapter <ide> end <ide> end <ide>
3
Javascript
Javascript
remove old validation scripts
184c1f5b9d6067f4369bd092216ea70be710a294
<ide><path>tools/scripts/ci/ensure-challenge-formatting.js <del>const readdirp = require('readdirp-walk'); <del>const { has, isEmpty, isNumber } = require('lodash'); <del>const ora = require('ora'); <del> <del>const { parseMarkdown } = require('../../challenge-parser'); <del>const { challengeRoot, checkFrontmatter } = require('./md-testing-utils'); <del> <del>const scrimbaUrlRE = /^https:\/\/scrimba\.com\//; <del>const requiredProps = ['title', 'id', 'challengeType']; <del> <del>const spinner = ora('Checking challenge markdown formatting').start(); <del> <del>readdirp({ root: challengeRoot, directoryFilter: '!_meta' }) <del> .on('data', file => <del> Promise.all([ <del> isChallengeParseable(file), <del> checkFrontmatter(file, { <del> validator: challengeFrontmatterValidator(file) <del> }) <del> ]).catch(err => { <del> console.info(` <del> the following error occurred when testing <del> <del> ${file.fullPath} <del> <del> `); <del> console.error(err); <del> // eslint-disable-next-line no-process-exit <del> process.exit(1); <del> }) <del> ) <del> .on('end', () => spinner.stop()); <del> <del>const challengeFrontmatterValidator = file => frontmatter => { <del> const { fullPath } = file; <del> <del> const hasRequiredProperties = requiredProps <del> .map( <del> prop => <del> has(frontmatter, prop) && <del> (!isEmpty(frontmatter[prop]) || isNumber(frontmatter[prop])) <del> ) <del> .every(bool => bool); <del> <del> if (!hasRequiredProperties) { <del> console.log(`${fullPath} is missing required frontmatter <del> <del> ${JSON.stringify(frontmatter, null, 2)} <del> <del> Required properties are: ${JSON.stringify(requiredProps, null, 2)} <del> <del> `); <del> } <del> <del> const { videoUrl } = frontmatter; <del> let validVideoUrl = false; <del> if (!isEmpty(videoUrl) && !scrimbaUrlRE.test(videoUrl)) { <del> validVideoUrl = true; <del> console.log(` <del> ${fullPath} contains an invalid videoUrl <del> `); <del> } <del> <del> const { forumTopicId } = frontmatter; <del> let validForumTopicId = false; <del> if (!isEmpty(forumTopicId) && !isNumber(forumTopicId)) { <del> validForumTopicId = true; <del> console.log(` <del> ${fullPath} contains an invalid forumTopicId <del> `); <del> } <del> <del> return hasRequiredProperties && validVideoUrl && validForumTopicId; <del>}; <del> <del>function isChallengeParseable(file) { <del> const { stat, fullPath } = file; <del> if (!stat.isFile() || /_meta/.test(fullPath)) { <del> return Promise.resolve(true); <del> } <del> return parseMarkdown(fullPath); <del>} <ide><path>tools/scripts/ci/ensure-guide-formatting.js <del>const readdirp = require('readdirp-walk'); <del>const { has } = require('lodash'); <del>const ora = require('ora'); <del> <del>const { <del> guideRoot, <del> checkGuideFile, <del> checkFrontmatter, <del> extractLangFromFileName <del>} = require('./md-testing-utils'); <del> <del>const spinner = ora('Checking guide markdown formatting').start(); <del> <del>const guideFrontmatterValidator = file => frontmatter => { <del> const hasLocale = <del> extractLangFromFileName(file) === 'english' <del> ? true <del> : has(frontmatter, 'localeTitle'); <del> const hasTitle = has(frontmatter, 'title'); <del> return hasLocale && hasTitle; <del>}; <del> <del>readdirp({ root: guideRoot }) <del> .on('data', file => <del> Promise.all([ <del> checkGuideFile(file), <del> checkFrontmatter(file, { validator: guideFrontmatterValidator(file) }) <del> ]).catch(err => { <del> console.error(err); <del> // eslint-disable-next-line no-process-exit <del> process.exit(1); <del> }) <del> ) <del> .on('end', () => spinner.stop()); <ide><path>tools/scripts/ci/md-testing-utils.js <del>const path = require('path'); <del>const fs = require('fs'); <del>const matter = require('gray-matter'); <del>const { dasherize } = require('../../../utils/slugs'); <del> <del>const pass = true; <del> <del>const guideRoot = path.resolve(__dirname, '../../../guide'); <del>const challengeRoot = path.resolve(__dirname, '../../../curriculum/challenges'); <del>exports.guideRoot = guideRoot; <del>exports.challengeRoot = challengeRoot; <del> <del>const allowedLangDirNames = [ <del> 'arabic', <del> 'chinese', <del> 'english', <del> 'portuguese', <del> 'russian', <del> 'spanish' <del>]; <del> <del>exports.checkGuideFile = function checkGuideFile(file) { <del> const { stat, depth, name, fullPath } = file; <del> if (depth === 1) { <del> if (stat.isFile()) { <del> throw new Error(`${name} is not valid in the ${guideRoot} directory`); <del> } <del> if (!allowedLangDirNames.includes(name)) { <del> throw new Error(`${name} should not be in the ${guideRoot} directory`); <del> } <del> } <del> if (stat.isDirectory()) { <del> return checkDirName(name, fullPath); <del> } <del> return checkGuideFileName(name, fullPath); <del>}; <del> <del>function checkDirName(dirName, fullPath) { <del> return new Promise((resolve, reject) => { <del> if (dasherize(dirName) !== dirName) { <del> return reject( <del> new Error(` <del>Invalid or upper case character found in '${dirName}', please use '-' for spaces <del>and all folder names must be lower case. Valid characters are [a-z0-9\\-.]. <del> <del> Found in: <del> ${fullPath} <del>`) <del> ); <del> } <del> return resolve(pass); <del> }); <del>} <del> <del>function checkGuideFileName(fileName, fullPath) { <del> return new Promise((resolve, reject) => { <del> if (fileName !== 'index.md') { <del> return reject( <del> new Error( <del> `${fileName} is not a valid file name, please use 'index.md' <del> <del> Found in: <del> ${fullPath} <del> ` <del> ) <del> ); <del> } <del> return resolve(pass); <del> }); <del>} <del> <del>exports.checkFrontmatter = function checkFrontmatter( <del> { fullPath, stat }, <del> options = { <del> validator() { <del> return true; <del> } <del> } <del>) { <del> if (!stat.isFile()) { <del> return Promise.resolve(pass); <del> } <del> return new Promise((resolve, reject) => <del> fs.readFile(fullPath, 'utf8', (err, content) => { <del> if (err) { <del> return reject(new Error(err)); <del> } <del> try { <del> const { data: frontmatter } = matter(content); <del> const { validator } = options; <del> if (!validator(frontmatter)) { <del> return reject( <del> new Error( <del> `The article at: ${fullPath} failed frontmatter validation.` <del> ) <del> ); <del> } <del> return resolve(pass); <del> } catch (e) { <del> console.log(` <del> <del> The below occurred in: <del> <del> ${fullPath} <del> <del> `); <del> throw e; <del> } <del> }) <del> ); <del>}; <del> <del>function extractLangFromFileName({ path: relativePath }) { <del> return relativePath.split(path.sep)[0]; <del>} <del> <del>exports.extractLangFromFileName = extractLangFromFileName;
3
Go
Go
add client.withapiversionnegotiation() option
b26aa97914dab997d6f8ebf1cb9c019f97e3c254
<ide><path>client/client.go <ide> type Client struct { <ide> customHTTPHeaders map[string]string <ide> // manualOverride is set to true when the version was set by users. <ide> manualOverride bool <add> <add> // negotiateVersion indicates if the client should automatically negotiate <add> // the API version to use when making requests. API version negotiation is <add> // performed on the first request, after which negotiated is set to "true" <add> // so that subsequent requests do not re-negotiate. <add> negotiateVersion bool <add> <add> // negotiated indicates that API version negotiation took place <add> negotiated bool <ide> } <ide> <ide> // CheckRedirect specifies the policy for dealing with redirect responses: <ide> func (cli *Client) Close() error { <ide> <ide> // getAPIPath returns the versioned request path to call the api. <ide> // It appends the query parameters to the path if they are not empty. <del>func (cli *Client) getAPIPath(p string, query url.Values) string { <add>func (cli *Client) getAPIPath(ctx context.Context, p string, query url.Values) string { <ide> var apiPath string <add> if cli.negotiateVersion && !cli.negotiated { <add> cli.NegotiateAPIVersion(ctx) <add> } <ide> if cli.version != "" { <ide> v := strings.TrimPrefix(cli.version, "v") <ide> apiPath = path.Join(cli.basePath, "/v"+v, p) <ide> func (cli *Client) ClientVersion() string { <ide> } <ide> <ide> // NegotiateAPIVersion queries the API and updates the version to match the <del>// API version. Any errors are silently ignored. <add>// API version. Any errors are silently ignored. If a manual override is in place, <add>// either through the `DOCKER_API_VERSION` environment variable, or if the client <add>// was initialized with a fixed version (`opts.WithVersion(xx)`), no negotiation <add>// will be performed. <ide> func (cli *Client) NegotiateAPIVersion(ctx context.Context) { <del> ping, _ := cli.Ping(ctx) <del> cli.NegotiateAPIVersionPing(ping) <add> if !cli.manualOverride { <add> ping, _ := cli.Ping(ctx) <add> cli.negotiateAPIVersionPing(ping) <add> } <ide> } <ide> <ide> // NegotiateAPIVersionPing updates the client version to match the Ping.APIVersion <del>// if the ping version is less than the default version. <add>// if the ping version is less than the default version. If a manual override is <add>// in place, either through the `DOCKER_API_VERSION` environment variable, or if <add>// the client was initialized with a fixed version (`opts.WithVersion(xx)`), no <add>// negotiation is performed. <ide> func (cli *Client) NegotiateAPIVersionPing(p types.Ping) { <del> if cli.manualOverride { <del> return <add> if !cli.manualOverride { <add> cli.negotiateAPIVersionPing(p) <ide> } <add>} <ide> <add>// negotiateAPIVersionPing queries the API and updates the version to match the <add>// API version. Any errors are silently ignored. <add>func (cli *Client) negotiateAPIVersionPing(p types.Ping) { <ide> // try the latest version before versioning headers existed <ide> if p.APIVersion == "" { <ide> p.APIVersion = "1.24" <ide> func (cli *Client) NegotiateAPIVersionPing(p types.Ping) { <ide> if versions.LessThan(p.APIVersion, cli.version) { <ide> cli.version = p.APIVersion <ide> } <add> <add> // Store the results, so that automatic API version negotiation (if enabled) <add> // won't be performed on the next request. <add> if cli.negotiateVersion { <add> cli.negotiated = true <add> } <ide> } <ide> <ide> // DaemonHost returns the host address used by the client <ide><path>client/client_test.go <ide> package client // import "github.com/docker/docker/client" <ide> <ide> import ( <ide> "bytes" <add> "context" <add> "io/ioutil" <ide> "net/http" <ide> "net/url" <ide> "os" <ide> "runtime" <add> "strings" <ide> "testing" <ide> <ide> "github.com/docker/docker/api" <ide> func TestGetAPIPath(t *testing.T) { <ide> {"v1.22", "/networks/kiwl$%^", nil, "/v1.22/networks/kiwl$%25%5E"}, <ide> } <ide> <add> ctx := context.TODO() <ide> for _, testcase := range testcases { <ide> c := Client{version: testcase.version, basePath: "/"} <del> actual := c.getAPIPath(testcase.path, testcase.query) <add> actual := c.getAPIPath(ctx, testcase.path, testcase.query) <ide> assert.Check(t, is.Equal(actual, testcase.expected)) <ide> } <ide> } <ide> func TestNegotiateAPVersionOverride(t *testing.T) { <ide> assert.Check(t, is.Equal(expected, client.version)) <ide> } <ide> <add>func TestNegotiateAPIVersionAutomatic(t *testing.T) { <add> var pingVersion string <add> httpClient := newMockClient(func(req *http.Request) (*http.Response, error) { <add> resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}} <add> resp.Header.Set("API-Version", pingVersion) <add> resp.Body = ioutil.NopCloser(strings.NewReader("OK")) <add> return resp, nil <add> }) <add> <add> client, err := NewClientWithOpts( <add> WithHTTPClient(httpClient), <add> WithAPIVersionNegotiation(), <add> ) <add> assert.NilError(t, err) <add> <add> ctx := context.Background() <add> assert.Equal(t, client.ClientVersion(), api.DefaultVersion) <add> <add> // First request should trigger negotiation <add> pingVersion = "1.35" <add> _, _ = client.Info(ctx) <add> assert.Equal(t, client.ClientVersion(), "1.35") <add> <add> // Once successfully negotiated, subsequent requests should not re-negotiate <add> pingVersion = "1.25" <add> _, _ = client.Info(ctx) <add> assert.Equal(t, client.ClientVersion(), "1.35") <add>} <add> <ide> // TestNegotiateAPIVersionWithEmptyVersion asserts that initializing a client <ide> // with an empty version string does still allow API-version negotiation <ide> func TestNegotiateAPIVersionWithEmptyVersion(t *testing.T) { <ide><path>client/hijack.go <ide> func (cli *Client) postHijacked(ctx context.Context, path string, query url.Valu <ide> return types.HijackedResponse{}, err <ide> } <ide> <del> apiPath := cli.getAPIPath(path, query) <add> apiPath := cli.getAPIPath(ctx, path, query) <ide> req, err := http.NewRequest("POST", apiPath, bodyEncoded) <ide> if err != nil { <ide> return types.HijackedResponse{}, err <ide><path>client/options.go <ide> func WithVersion(version string) Opt { <ide> return nil <ide> } <ide> } <add> <add>// WithAPIVersionNegotiation enables automatic API version negotiation for the client. <add>// With this option enabled, the client automatically negotiates the API version <add>// to use when making requests. API version negotiation is performed on the first <add>// request; subsequent requests will not re-negotiate. <add>func WithAPIVersionNegotiation() Opt { <add> return func(c *Client) error { <add> c.negotiateVersion = true <add> return nil <add> } <add>} <ide><path>client/request.go <ide> func (cli *Client) buildRequest(method, path string, body io.Reader, headers hea <ide> } <ide> <ide> func (cli *Client) sendRequest(ctx context.Context, method, path string, query url.Values, body io.Reader, headers headers) (serverResponse, error) { <del> req, err := cli.buildRequest(method, cli.getAPIPath(path, query), body, headers) <add> req, err := cli.buildRequest(method, cli.getAPIPath(ctx, path, query), body, headers) <ide> if err != nil { <ide> return serverResponse{}, err <ide> }
5
Ruby
Ruby
fix artifact list
5d38cd7296dabb5cf1a0f0065c82697b12f70229
<ide><path>Library/Homebrew/cask/cmd/list.rb <ide> # frozen_string_literal: true <ide> <add>require "cask/artifact/relocated" <add> <ide> module Cask <ide> class Cmd <ide> class List < AbstractCommand <ide> def self.list_casks(*casks, json: false, one: false, full_name: false, versions: <ide> elsif versions <ide> puts output.map(&method(:format_versioned)) <ide> elsif !output.empty? && casks.any? <del> puts output.map(&method(:list_artifacts)) <add> output.map(&method(:list_artifacts)) <ide> elsif !output.empty? <ide> puts Formatter.columns(output.map(&:to_s)) <ide> end <ide> end <ide> <ide> def self.list_artifacts(cask) <del> cask.artifacts.group_by(&:class).each do |klass, artifacts| <del> next unless klass.respond_to?(:english_description) <add> cask.artifacts.group_by(&:class).sort_by { |klass, _| klass.english_name }.each do |klass, artifacts| <add> next if [Artifact::Uninstall, Artifact::Zap].include? klass <add> <add> ohai klass.english_name <add> artifacts.each do |artifact| <add> puts artifact.summarize_installed if artifact.respond_to?(:summarize_installed) <add> next if artifact.respond_to?(:summarize_installed) <ide> <del> return "==> #{klass.english_description}", artifacts.map(&:summarize_installed) <add> puts artifact <add> end <ide> end <ide> end <ide> <ide><path>Library/Homebrew/test/cask/cmd/list_spec.rb <ide> expect { <ide> described_class.run("local-transmission", "local-caffeine") <ide> }.to output(<<~EOS).to_stdout <del> ==> Apps <add> ==> App <ide> #{transmission.config.appdir.join("Transmission.app")} (#{transmission.config.appdir.join("Transmission.app").abv}) <del> ==> Apps <add> ==> App <ide> Missing App: #{caffeine.config.appdir.join("Caffeine.app")} <ide> EOS <ide> end
2
Ruby
Ruby
require open-uri where opening uri
95a8be46eaf0c9fe5eab4af0952d8e3ecb8fe2c8
<ide><path>activesupport/test/multibyte_test_helpers.rb <ide> # frozen_string_literal: true <ide> <ide> require "fileutils" <add>require "open-uri" <ide> require "tmpdir" <ide> <ide> module MultibyteTestHelpers
1
PHP
PHP
add a test for check 0 before natural number
f96a68f60343694abc19f0a842b7599140bf8792
<ide><path>tests/TestCase/Validation/ValidationTest.php <ide> public function testIsInteger() <ide> $this->assertTrue(Validation::isInteger(-10)); <ide> $this->assertTrue(Validation::isInteger(0)); <ide> $this->assertTrue(Validation::isInteger(10)); <add> $this->assertTrue(Validation::isInteger(012)); <add> $this->assertTrue(Validation::isInteger(-012)); <ide> $this->assertTrue(Validation::isInteger('-10')); <ide> $this->assertTrue(Validation::isInteger('0')); <ide> $this->assertTrue(Validation::isInteger('10')); <add> $this->assertTrue(Validation::isInteger('012')); <add> $this->assertTrue(Validation::isInteger('-012')); <ide> <ide> $this->assertFalse(Validation::isInteger('2.5')); <ide> $this->assertFalse(Validation::isInteger([]));
1
Text
Text
add missing space before hyphen
4e18f472c7c33fa82c1dc1db86d1b1dfe78f3104
<ide><path>README.md <ide> releases on a rotation basis as outlined in the <ide> * [mcollina](https://github.com/mcollina) - <ide> **Matteo Collina** <<[email protected]>> (he/him) <ide> * Red Hat and IBM <del> * [joesepi](https://github.com/joesepi)- <add> * [joesepi](https://github.com/joesepi) - <ide> **Joe Sepi** <<[email protected]>> (he/him) <ide> * [mhdawson](https://github.com/mhdawson) - <ide> **Michael Dawson** <<[email protected]>> (he/him)
1
Javascript
Javascript
add missing semicolon
29a674b9736be9384ec8e077edeba475f3a892e3
<ide><path>d3.v2.js <ide> d3.interpolateObject = function(a, b) { <ide> for (k in i) c[k] = i[k](t); <ide> return c; <ide> }; <del>} <add>}; <ide> <ide> var d3_interpolate_number = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g; <ide> <ide><path>src/core/interpolate.js <ide> d3.interpolateObject = function(a, b) { <ide> for (k in i) c[k] = i[k](t); <ide> return c; <ide> }; <del>} <add>}; <ide> <ide> var d3_interpolate_number = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g; <ide>
2
Javascript
Javascript
use err_debugger_error in debugger client
c22eec85b477f73e95235caadbcaa2bb433e5f49
<ide><path>lib/internal/inspector/inspect_client.js <del>// TODO(aduh95): use errors exported by the internal/errors module <del>/* eslint-disable no-restricted-syntax */ <del> <ide> 'use strict'; <ide> <ide> const { <ide> ArrayPrototypePush, <del> Error, <ide> ErrorCaptureStackTrace, <ide> FunctionPrototypeBind, <ide> JSONParse, <ide> const { <ide> } = primordials; <ide> <ide> const Buffer = require('buffer').Buffer; <add>const { ERR_DEBUGGER_ERROR } = require('internal/errors').codes; <ide> const { EventEmitter } = require('events'); <ide> const http = require('http'); <ide> const URL = require('url'); <ide> const kEightBytePayloadLengthField = 127; <ide> const kMaskingKeyWidthInBytes = 4; <ide> <ide> function unpackError({ code, message, data }) { <del> const err = new Error(`${message} - ${data}`); <add> const err = new ERR_DEBUGGER_ERROR(`${message} - ${data}`); <ide> err.code = code; <ide> ErrorCaptureStackTrace(err, unpackError); <ide> return err; <ide> function decodeFrameHybi17(data) { <ide> const masked = (secondByte & kMaskBit) !== 0; <ide> const compressed = reserved1; <ide> if (compressed) { <del> throw new Error('Compressed frames not supported'); <add> throw new ERR_DEBUGGER_ERROR('Compressed frames not supported'); <ide> } <ide> if (!final || reserved2 || reserved3) { <del> throw new Error('Only compression extension is supported'); <add> throw new ERR_DEBUGGER_ERROR('Only compression extension is supported'); <ide> } <ide> <ide> if (masked) { <del> throw new Error('Masked server frame - not supported'); <add> throw new ERR_DEBUGGER_ERROR('Masked server frame - not supported'); <ide> } <ide> <ide> let closed = false; <ide> function decodeFrameHybi17(data) { <ide> case kOpCodeText: <ide> break; <ide> default: <del> throw new Error(`Unsupported op code ${opCode}`); <add> throw new ERR_DEBUGGER_ERROR(`Unsupported op code ${opCode}`); <ide> } <ide> <ide> let payloadLength = secondByte & kPayloadLengthMask; <ide> class Client extends EventEmitter { <ide> debuglog('< %s', payloadStr); <ide> const lastChar = payloadStr[payloadStr.length - 1]; <ide> if (payloadStr[0] !== '{' || lastChar !== '}') { <del> throw new Error(`Payload does not look like JSON: ${payloadStr}`); <add> throw new ERR_DEBUGGER_ERROR(`Payload does not look like JSON: ${payloadStr}`); <ide> } <ide> let payload; <ide> try { <ide> class Client extends EventEmitter { <ide> this.emit('debugEvent', method, params); <ide> this.emit(method, params); <ide> } else { <del> throw new Error(`Unsupported response: ${payloadStr}`); <add> throw new ERR_DEBUGGER_ERROR(`Unsupported response: ${payloadStr}`); <ide> } <ide> } <ide> } <ide> class Client extends EventEmitter { <ide> callMethod(method, params) { <ide> return new Promise((resolve, reject) => { <ide> if (!this._socket) { <del> reject(new Error('Use `run` to start the app again.')); <add> reject(new ERR_DEBUGGER_ERROR('Use `run` to start the app again.')); <ide> return; <ide> } <ide> const data = { id: ++this._lastId, method, params }; <ide> class Client extends EventEmitter { <ide> function parseChunks() { <ide> const resBody = Buffer.concat(chunks).toString(); <ide> if (httpRes.statusCode !== 200) { <del> reject(new Error(`Unexpected ${httpRes.statusCode}: ${resBody}`)); <add> reject(new ERR_DEBUGGER_ERROR(`Unexpected ${httpRes.statusCode}: ${resBody}`)); <ide> return; <ide> } <ide> try { <ide> resolve(JSONParse(resBody)); <ide> } catch { <del> reject(new Error(`Response didn't contain JSON: ${resBody}`)); <add> reject(new ERR_DEBUGGER_ERROR(`Response didn't contain JSON: ${resBody}`)); <ide> <ide> } <ide> }
1
Ruby
Ruby
add a new constructor for allocating test requests
78a5124bf09d0cd285d4d1a6242bd67badb2f621
<ide><path>actionpack/lib/action_controller/test_case.rb <ide> def self.new_session <ide> TestSession.new <ide> end <ide> <add> # Create a new test request with default `env` values <add> def self.create <add> env = {} <add> env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application <add> new(default_env.merge(env), new_session) <add> end <add> <add> def self.default_env <add> DEFAULT_ENV <add> end <add> private_class_method :default_env <add> <ide> def initialize(env, session) <ide> super(env) <ide> <ide> def recycle! <ide> @fullpath = @ip = @remote_ip = @protocol = nil <ide> @env['action_dispatch.request.query_parameters'] = {} <ide> end <del> <del> private <del> <del> def default_env <del> DEFAULT_ENV <del> end <ide> end <ide> <ide> class TestResponse < ActionDispatch::TestResponse <ide> def setup_controller_request_and_response <ide> end <ide> end <ide> <del> @request = build_request({}, TestRequest.new_session) <add> @request = TestRequest.create <ide> @request.env["rack.request.cookie_hash"] = {}.with_indifferent_access <ide> @response = build_response @response_klass <ide> @response.request = @request <ide> def setup_controller_request_and_response <ide> end <ide> end <ide> <del> def build_request(env, session) <del> TestRequest.new(env, session) <del> end <del> <ide> def build_response(klass) <ide> klass.new <ide> end <ide><path>actionpack/lib/action_dispatch/testing/assertions/routing.rb <ide> def recognized_request_for(path, extras = {}, msg) <ide> end <ide> <ide> # Assume given controller <del> request = build_request({}, ActionController::TestRequest.new_session) <add> request = ActionController::TestRequest.create <ide> <ide> if path =~ %r{://} <ide> fail_on(URI::InvalidURIError, msg) do <ide><path>actionpack/lib/action_dispatch/testing/test_request.rb <ide> class TestRequest < Request <ide> "rack.request.cookie_hash" => {}.with_indifferent_access <ide> ) <ide> <del> def initialize(env) <add> # Create a new test request with default `env` values <add> def self.create(env = {}) <ide> env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application <del> super(default_env.merge(env)) <add> new(default_env.merge(env)) <ide> end <ide> <add> def self.default_env <add> DEFAULT_ENV <add> end <add> private_class_method :default_env <add> <ide> def request_method=(method) <ide> @env['REQUEST_METHOD'] = method.to_s.upcase <ide> end <ide> def accept=(mime_types) <ide> @env.delete('action_dispatch.request.accepts') <ide> @env['HTTP_ACCEPT'] = Array(mime_types).collect(&:to_s).join(",") <ide> end <del> <del> private <del> <del> def default_env <del> DEFAULT_ENV <del> end <ide> end <ide> end <ide><path>actionpack/test/dispatch/test_request_test.rb <ide> <ide> class TestRequestTest < ActiveSupport::TestCase <ide> test "sane defaults" do <del> env = ActionDispatch::TestRequest.new({}).env <add> env = ActionDispatch::TestRequest.create.env <ide> <ide> assert_equal "GET", env.delete("REQUEST_METHOD") <ide> assert_equal "off", env.delete("HTTPS") <ide> class TestRequestTest < ActiveSupport::TestCase <ide> end <ide> <ide> test "cookie jar" do <del> req = ActionDispatch::TestRequest.new({}) <add> req = ActionDispatch::TestRequest.create({}) <ide> <ide> assert_equal({}, req.cookies) <ide> assert_equal nil, req.env["HTTP_COOKIE"] <ide> class TestRequestTest < ActiveSupport::TestCase <ide> <ide> test "does not complain when Rails.application is nil" do <ide> Rails.stubs(:application).returns(nil) <del> req = ActionDispatch::TestRequest.new({}) <add> req = ActionDispatch::TestRequest.create({}) <ide> <ide> assert_equal false, req.env.empty? <ide> end <ide> <ide> test "default remote address is 0.0.0.0" do <del> req = ActionDispatch::TestRequest.new({}) <add> req = ActionDispatch::TestRequest.create({}) <ide> assert_equal '0.0.0.0', req.remote_addr <ide> end <ide> <ide> test "allows remote address to be overridden" do <del> req = ActionDispatch::TestRequest.new('REMOTE_ADDR' => '127.0.0.1') <add> req = ActionDispatch::TestRequest.create('REMOTE_ADDR' => '127.0.0.1') <ide> assert_equal '127.0.0.1', req.remote_addr <ide> end <ide> <ide> test "default host is test.host" do <del> req = ActionDispatch::TestRequest.new({}) <add> req = ActionDispatch::TestRequest.create({}) <ide> assert_equal 'test.host', req.host <ide> end <ide> <ide> test "allows host to be overridden" do <del> req = ActionDispatch::TestRequest.new('HTTP_HOST' => 'www.example.com') <add> req = ActionDispatch::TestRequest.create('HTTP_HOST' => 'www.example.com') <ide> assert_equal 'www.example.com', req.host <ide> end <ide> <ide> test "default user agent is 'Rails Testing'" do <del> req = ActionDispatch::TestRequest.new({}) <add> req = ActionDispatch::TestRequest.create({}) <ide> assert_equal 'Rails Testing', req.user_agent <ide> end <ide> <ide> test "allows user agent to be overridden" do <del> req = ActionDispatch::TestRequest.new('HTTP_USER_AGENT' => 'GoogleBot') <add> req = ActionDispatch::TestRequest.create('HTTP_USER_AGENT' => 'GoogleBot') <ide> assert_equal 'GoogleBot', req.user_agent <ide> end <ide>
4
Javascript
Javascript
reduce diff noise
02c44a48943302d07a3b9575402a8992e57dada8
<ide><path>lib/internal/assert.js <ide> function createErrDiff(actual, expected, operator) { <ide> res += `\n${green}+${white} ${actualLines[i]}`; <ide> printedLines++; <ide> // Lines diverge <del> } else if (actualLines[i] !== expectedLines[i]) { <del> if (cur > 1 && i > 2) { <del> if (cur > 4) { <del> res += `\n${blue}...${white}`; <del> skipped = true; <del> } else if (cur > 3) { <del> res += `\n ${actualLines[i - 2]}`; <add> } else { <add> const expectedLine = expectedLines[i]; <add> let actualLine = actualLines[i]; <add> let divergingLines = actualLine !== expectedLine && <add> (!actualLine.endsWith(',') || <add> actualLine.slice(0, -1) !== expectedLine); <add> if (divergingLines && <add> expectedLine.endsWith(',') && <add> expectedLine.slice(0, -1) === actualLine) { <add> divergingLines = false; <add> actualLine += ','; <add> } <add> if (divergingLines) { <add> if (cur > 1 && i > 2) { <add> if (cur > 4) { <add> res += `\n${blue}...${white}`; <add> skipped = true; <add> } else if (cur > 3) { <add> res += `\n ${actualLines[i - 2]}`; <add> printedLines++; <add> } <add> res += `\n ${actualLines[i - 1]}`; <add> printedLines++; <add> } <add> lastPos = i; <add> res += `\n${green}+${white} ${actualLine}`; <add> other += `\n${red}-${white} ${expectedLine}`; <add> printedLines += 2; <add> // Lines are identical <add> } else { <add> res += other; <add> other = ''; <add> if (cur === 1 || i === 0) { <add> res += `\n ${actualLine}`; <ide> printedLines++; <ide> } <del> res += `\n ${actualLines[i - 1]}`; <del> printedLines++; <del> } <del> lastPos = i; <del> res += `\n${green}+${white} ${actualLines[i]}`; <del> other += `\n${red}-${white} ${expectedLines[i]}`; <del> printedLines += 2; <del> // Lines are identical <del> } else { <del> res += other; <del> other = ''; <del> if (cur === 1 || i === 0) { <del> res += `\n ${actualLines[i]}`; <del> printedLines++; <ide> } <ide> } <ide> // Inspected object to big (Show ~20 rows max) <ide><path>test/parallel/test-assert-deep.js <ide> assert.deepEqual(arr, buf); <ide> () => assert.deepStrictEqual(buf2, buf), <ide> { <ide> code: 'ERR_ASSERTION', <del> message: `${defaultMsgStartFull}\n\n` + <del> ' Buffer [Uint8Array] [\n 120,\n 121,\n 122,\n' + <del> '+ 10,\n+ prop: 1\n- 10\n ]' <add> message: `${defaultMsgStartFull} ... Lines skipped\n\n` + <add> ' Buffer [Uint8Array] [\n' + <add> ' 120,\n' + <add> '...\n' + <add> ' 10,\n' + <add> '+ prop: 1\n' + <add> ' ]' <ide> } <ide> ); <ide> assert.deepEqual(buf2, buf); <ide> assert.deepEqual(arr, buf); <ide> () => assert.deepStrictEqual(arr, arr2), <ide> { <ide> code: 'ERR_ASSERTION', <del> message: `${defaultMsgStartFull}\n\n` + <del> ' Uint8Array [\n 120,\n 121,\n 122,\n' + <del> '+ 10\n- 10,\n- prop: 5\n ]' <add> message: `${defaultMsgStartFull} ... Lines skipped\n\n` + <add> ' Uint8Array [\n' + <add> ' 120,\n' + <add> '...\n' + <add> ' 10,\n' + <add> '- prop: 5\n' + <add> ' ]' <ide> } <ide> ); <ide> assert.deepEqual(arr, arr2); <ide> assert.throws( <ide> code: 'ERR_ASSERTION', <ide> name: 'AssertionError [ERR_ASSERTION]', <ide> message: `${defaultMsgStartFull}\n\n ` + <del> '{\n+ a: 4\n- a: 4,\n- b: true\n }' <add> '{\n a: 4,\n- b: true\n }' <ide> }); <ide> assert.throws( <ide> () => assert.deepStrictEqual(['a'], { 0: 'a' }), <ide> assert.deepStrictEqual(obj1, obj2); <ide> assert.throws( <ide> () => assert.deepStrictEqual(arrProxy, [1, 2, 3]), <ide> { message: `${defaultMsgStartFull}\n\n` + <del> ' [\n 1,\n+ 2\n- 2,\n- 3\n ]' } <add> ' [\n 1,\n 2,\n- 3\n ]' } <ide> ); <ide> util.inspect.defaultOptions = tmp; <ide>
2
Java
Java
improve asobservable() javadoc description
0cc4ff2f8f7bea2a9b5d274a73770f078d0641bc
<ide><path>src/main/java/rx/Observable.java <ide> public final Observable<T> ambWith(Observable<? extends T> t1) { <ide> } <ide> <ide> /** <del> * Disguises a object of an Observable subclass as a simple Observable object. Useful for instance when you <del> * have an implementation of a subclass of Observable but you want to hide the properties and methods of <del> * this subclass from whomever you are passing the Observable to. <add> * Portrays a object of an Observable subclass as a simple Observable object. This is useful, for instance, <add> * when you have an implementation of a subclass of Observable but you want to hide the properties and <add> * methods of this subclass from whomever you are passing the Observable to. <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>{@code asObservable} does not operate by default on a particular {@link Scheduler}.</dd>
1
PHP
PHP
add testcase method to drop plugins
91b4b45cfc85ba619fdf1d66b932afce16d16d66
<ide><path>config/bootstrap.php <ide> * @since 0.2.9 <ide> * @license https://opensource.org/licenses/mit-license.php MIT License <ide> */ <del> <ide> use Cake\Routing\Router; <ide> <ide> define('TIME_START', microtime(true)); <ide><path>src/TestSuite/TestCase.php <ide> <ide> use Cake\Core\App; <ide> use Cake\Core\Configure; <add>use Cake\Core\Plugin; <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\Event\EventManager; <ide> use Cake\Http\BaseApplication; <ide> public function loadPlugins(array $plugins = []) <ide> return $app; <ide> } <ide> <add> /** <add> * Remove plugins from the global plugin collection. <add> * <add> * Useful in test case teardown methods. <add> * <add> * @return void <add> */ <add> public function removePlugins(array $plugins = []) <add> { <add> $collection = Plugin::getCollection(); <add> foreach ($plugins as $plugin) { <add> $collection->remove($plugin); <add> } <add> } <add> <add> /** <add> * Clear all plugins from the global plugin collection. <add> * <add> * Useful in test case teardown methods. <add> * <add> * @return void <add> */ <add> public function clearPlugins() <add> { <add> Plugin::getCollection()->clear(); <add> } <add> <ide> /** <ide> * Asserts that a global event was fired. You must track events in your event manager for this assertion to work <ide> * <ide><path>tests/TestCase/Auth/FormAuthenticateTest.php <ide> public function testPluginModel() <ide> 'updated' => new Time('2007-03-17 01:18:31') <ide> ]; <ide> $this->assertEquals($expected, $result); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Auth/PasswordHasherFactoryTest.php <ide> public function testBuild() <ide> $this->loadPlugins(['TestPlugin']); <ide> $hasher = PasswordHasherFactory::build('TestPlugin.Legacy'); <ide> $this->assertInstanceof('TestPlugin\Auth\LegacyPasswordHasher', $hasher); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Cache/CacheTest.php <ide> public function testConfigWithLibAndPluginEngines() <ide> Cache::drop('libEngine'); <ide> Cache::drop('pluginLibEngine'); <ide> <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Command/HelpCommandTest.php <ide> public function setUp() <ide> parent::setUp(); <ide> $this->setAppNamespace(); <ide> $this->useCommandRunner(true); <del> Plugin::getCollection()->clear(); <ide> $app = $this->getMockForAbstractClass( <ide> BaseApplication::class, <ide> [''] <ide> public function setUp() <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide> public function testMainNoCommandsFallback() <ide> $this->exec('help'); <ide> $this->assertExitCode(Shell::CODE_SUCCESS); <ide> $this->assertCommandList(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Console/CommandCollectionTest.php <ide> public function testDiscoverPlugin() <ide> 'Long names are stored as well' <ide> ); <ide> $this->assertSame($result['company'], $result['company/test_plugin_three.company']); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> } <ide><path>tests/TestCase/Console/HelperRegistryTest.php <ide> public function testLoadWithAlias() <ide> <ide> $result = $this->helpers->loaded(); <ide> $this->assertEquals(['SimpleAliased', 'SomeHelper'], $result, 'loaded() results are wrong.'); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> } <ide><path>tests/TestCase/Console/ShellDispatcherTest.php <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <ide> ShellDispatcher::resetAliases(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Console/ShellTest.php <ide> public function testInitialize() <ide> 'TestPlugin\Model\Table\TestPluginCommentsTable', <ide> $this->Shell->TestPluginComments <ide> ); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide> public function testLoadModel() <ide> 'TestPlugin\Model\Table\TestPluginCommentsTable', <ide> $this->Shell->TestPluginComments <ide> ); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Console/TaskRegistryTest.php <ide> public function testLoadPluginTask() <ide> $result = $this->Tasks->load('TestPlugin.OtherTask'); <ide> $this->assertInstanceOf('TestPlugin\Shell\Task\OtherTaskTask', $result, 'Task class is wrong.'); <ide> $this->assertInstanceOf('TestPlugin\Shell\Task\OtherTaskTask', $this->Tasks->OtherTask, 'Class is wrong'); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide> public function testLoadWithAlias() <ide> <ide> $result = $this->Tasks->loaded(); <ide> $this->assertEquals(['CommandAliased', 'SomeTask'], $result, 'loaded() results are wrong.'); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> } <ide><path>tests/TestCase/Controller/ComponentRegistryTest.php <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <ide> unset($this->Components); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Controller/ControllerTest.php <ide> public function setUp() <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Core/AppTest.php <ide> class AppTest extends TestCase <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Core/BasePluginTest.php <ide> class BasePluginTest extends TestCase <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Core/Configure/Engine/IniConfigTest.php <ide> public function testReadPluginValue() <ide> <ide> $result = $engine->read('TestPlugin.nested'); <ide> $this->assertEquals('foo', $result['database']['db']['password']); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Core/Configure/Engine/JsonConfigTest.php <ide> public function testReadPluginValue() <ide> $result = $engine->read('TestPlugin.load'); <ide> $this->assertArrayHasKey('plugin_load', $result); <ide> <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Core/Configure/Engine/PhpConfigTest.php <ide> public function testReadPluginValue() <ide> $result = $engine->read('TestPlugin.load'); <ide> $this->assertArrayHasKey('plugin_load', $result); <ide> <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Core/ConfigureTest.php <ide> public function testLoadPlugin() <ide> $expected = '/test_app/Plugin/TestPlugin/Config/more.load.php'; <ide> $config = Configure::read('plugin_more_load'); <ide> $this->assertEquals($expected, $config); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Core/PluginTest.php <ide> class PluginTest extends TestCase <ide> public function setUp() <ide> { <ide> parent::setUp(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide> public function setUp() <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Datasource/ConnectionManagerTest.php <ide> class ConnectionManagerTest extends TestCase <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <add> $this->clearPlugins(); <ide> Plugin::getCollection()->clear(); <ide> ConnectionManager::drop('test_variant'); <ide> ConnectionManager::dropAlias('other_name'); <ide><path>tests/TestCase/Error/ErrorHandlerTest.php <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <ide> Log::reset(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> if ($this->_restoreError) { <ide> restore_error_handler(); <ide> restore_exception_handler(); <ide><path>tests/TestCase/Error/ExceptionRendererTest.php <ide> public function setUp() <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> if ($this->_restoreError) { <ide> restore_error_handler(); <ide> } <ide><path>tests/TestCase/Http/BaseApplicationTest.php <ide> public function setUp() <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Http/SessionTest.php <ide> public function tearDown() <ide> { <ide> unset($_SESSION); <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/I18n/I18nTest.php <ide> public function tearDown() <ide> I18n::clear(); <ide> I18n::setDefaultFormatter('default'); <ide> I18n::setLocale($this->locale); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> Cache::clear(false, '_cake_core_'); <ide> } <ide> <ide><path>tests/TestCase/Log/LogTest.php <ide> public function testImportingLoggers() <ide> <ide> Log::write(LOG_INFO, 'TestPluginLog is not a BaseLog descendant'); <ide> <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Mailer/EmailTest.php <ide> public function testSendRenderThemed() <ide> $this->assertContains('Message-ID: ', $result['headers']); <ide> $this->assertContains('To: ', $result['headers']); <ide> $this->assertContains('/test_theme/img/test.jpg', $result['message']); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide> public function testSendRenderPlugin() <ide> $result = $this->Email->send(); <ide> $this->assertContains('Here is your value: 12345', $result['message']); <ide> $this->assertContains('This email was sent using the TestPlugin.', $result['message']); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/ORM/AssociationTest.php <ide> public function testTargetPlugin() <ide> $this->assertSame('TestPlugin.ThisAssociationName', $table->getRegistryAlias()); <ide> $this->assertSame('comments', $table->getTable()); <ide> $this->assertSame('ThisAssociationName', $table->getAlias()); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/ORM/BehaviorRegistryTest.php <ide> public function setUp() <ide> */ <ide> public function tearDown() <ide> { <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> unset($this->Table, $this->EventManager, $this->Behaviors); <ide> parent::tearDown(); <ide> } <ide><path>tests/TestCase/ORM/Locator/TableLocatorTest.php <ide> public function setUp() <ide> */ <ide> public function tearDown() <ide> { <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> parent::tearDown(); <ide> } <ide> <ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> public function testPluginAssociationQueryGeneration() <ide> $result->author->id, <ide> 'No SQL error and author exists.' <ide> ); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/ORM/ResultSetTest.php <ide> public function testSourceOnContainAssociations() <ide> })->first(); <ide> $this->assertEquals('TestPlugin.Comments', $result->getSource()); <ide> $this->assertEquals('TestPlugin.Authors', $result->_matchingData['Authors']->getSource()); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <ide> $this->getTableLocator()->clear(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Routing/DispatcherTest.php <ide> public function tearDown() <ide> { <ide> error_reporting($this->errorLevel); <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Routing/Filter/AssetFilterTest.php <ide> public function setUp() <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Routing/Middleware/AssetMiddlewareTest.php <ide> public function setUp() <ide> */ <ide> public function tearDown() <ide> { <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> parent::tearDown(); <ide> } <ide> <ide><path>tests/TestCase/Routing/RequestActionTraitTest.php <ide> public function tearDown() <ide> parent::tearDown(); <ide> DispatcherFactory::clear(); <ide> Router::reload(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> <ide> error_reporting($this->errorLevel); <ide> } <ide><path>tests/TestCase/Routing/RouteBuilderTest.php <ide> public function setUp() <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Routing/RouterTest.php <ide> public function setUp() <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> Router::reload(); <ide> Router::defaultRouteClass('Cake\Routing\Route\Route'); <ide> } <ide> public function testUsingCustomRouteClassPluginDotSyntax() <ide> ['routeClass' => 'TestPlugin.TestRoute', 'slug' => '[a-z_-]+'] <ide> ); <ide> $this->assertTrue(true); // Just to make sure the connect do not throw exception <del> Plugin::getCollection()->remove('TestPlugin'); <add> $this->removePlugins(['TestPlugin']); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Shell/CommandListShellTest.php <ide> public function setUp() <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Shell/CompletionShellTest.php <ide> public function tearDown() <ide> parent::tearDown(); <ide> unset($this->Shell); <ide> static::setAppNamespace('App'); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Shell/Task/AssetsTaskTest.php <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <ide> unset($this->Task); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Shell/Task/ExtractTaskTest.php <ide> public function tearDown() <ide> <ide> $Folder = new Folder($this->path); <ide> $Folder->delete(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Shell/Task/UnloadTaskTest.php <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <ide> unset($this->shell); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> <ide> file_put_contents($this->bootstrap, $this->originalBootstrapContent); <ide> file_put_contents($this->app, $this->originalAppContent); <ide><path>tests/TestCase/TestSuite/FixtureManagerTest.php <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <ide> Log::reset(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/TestSuite/IntegrationTestTraitTest.php <ide> public function testGetUsingApplicationWithPluginRoutes() <ide> { <ide> // first clean routes to have Router::$initailized === false <ide> Router::reload(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> <ide> $this->configApplication(Configure::read('App.namespace') . '\ApplicationWithPluginRoutes', null); <ide> <ide><path>tests/TestCase/TestSuite/TestCaseTest.php <ide> public function testGetMockForModelWithPlugin() <ide> $TestPluginAuthors = $this->getMockForModel('TestPlugin.Authors', ['doSomething']); <ide> $this->assertInstanceOf('TestPlugin\Model\Table\AuthorsTable', $TestPluginAuthors); <ide> $this->assertEquals('TestPlugin\Model\Entity\Author', $TestPluginAuthors->getEntityClass()); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/CellTest.php <ide> public function setUp() <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> unset($this->View); <ide> } <ide> <ide><path>tests/TestCase/View/Helper/FlashHelperTest.php <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <ide> unset($this->View, $this->Flash); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php <ide> public function setUp() <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> unset($this->Html, $this->View); <ide> } <ide> <ide> public function testCssLink() <ide> $result = $this->Html->css('TestPlugin.style', ['plugin' => false]); <ide> $expected['link']['href'] = 'preg:/.*css\/TestPlugin\.style\.css/'; <ide> $this->assertHtml($expected, $result); <del> Plugin::getCollection()->remove('TestPlugin'); <add> $this->removePlugins(['TestPlugin']); <ide> <ide> $result = $this->Html->css('my.css.library'); <ide> $expected['link']['href'] = 'preg:/.*css\/my\.css\.library\.css/'; <ide> public function testPluginCssLink() <ide> $this->assertHtml($expected, $result[1]); <ide> $this->assertCount(2, $result); <ide> <del> Plugin::getCollection()->remove('TestPlugin'); <add> $this->removePlugin(['TestPlugin']); <ide> } <ide> <ide> /** <ide> public function testPluginCssTimestamping() <ide> $expected['link']['href'] = 'preg:/\/testing\/longer\/test_plugin\/css\/test_plugin_asset\.css\?[0-9]+/'; <ide> $this->assertHtml($expected, $result); <ide> <del> Plugin::getCollection()->remove('TestPlugin'); <add> $this->removePlugins(['TestPlugin']); <ide> } <ide> <ide> /** <ide> public function testPluginScriptTimestamping() <ide> unlink($pluginJsPath . DS . '__cake_js_test.js'); <ide> Configure::write('Asset.timestamp', false); <ide> <del> Plugin::getCollection()->remove('TestPlugin'); <add> $this->removePlugins(['TestPlugin']); <ide> } <ide> <ide> /** <ide> public function testPluginScript() <ide> ]; <ide> $this->assertHtml($expected, $result); <ide> <del> Plugin::getCollection()->remove('TestPlugin'); <add> $this->removePlugins(['TestPlugin']); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Helper/NumberHelperTest.php <ide> public function setUp() <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> static::setAppNamespace($this->_appNamespace); <ide> unset($this->View); <ide> } <ide> public function testEngineOverride() <ide> $this->loadPlugins(['TestPlugin']); <ide> $Number = new NumberHelperTestObject($this->View, ['engine' => 'TestPlugin.TestPluginEngine']); <ide> $this->assertInstanceOf('TestPlugin\Utility\TestPluginEngine', $Number->engine()); <del> Plugin::getCollection()->remove('TestPlugin'); <add> $this->removePlugins(['TestPlugin']); <ide> } <ide> } <ide><path>tests/TestCase/View/Helper/TextHelperTest.php <ide> public function testEngineOverride() <ide> $this->loadPlugins(['TestPlugin']); <ide> $Text = new TextHelperTestObject($this->View, ['engine' => 'TestPlugin.TestPluginEngine']); <ide> $this->assertInstanceOf('TestPlugin\Utility\TestPluginEngine', $Text->engine()); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Helper/UrlHelperTest.php <ide> public function tearDown() <ide> parent::tearDown(); <ide> Configure::delete('Asset'); <ide> <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> unset($this->Helper, $this->View); <ide> } <ide> <ide> public function testAssetUrlPlugin() <ide> $result = $this->Helper->assetUrl('TestPlugin.style', ['ext' => '.css', 'plugin' => false]); <ide> $this->assertEquals('TestPlugin.style.css', $result); <ide> <del> Plugin::getCollection()->remove('TestPlugin'); <add> $this->removePlugins(['TestPlugin']); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/HelperRegistryTest.php <ide> public function setUp() <ide> */ <ide> public function tearDown() <ide> { <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> unset($this->Helpers, $this->View); <ide> parent::tearDown(); <ide> } <ide><path>tests/TestCase/View/HelperTest.php <ide> public function tearDown() <ide> parent::tearDown(); <ide> Configure::delete('Asset'); <ide> <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> unset($this->View); <ide> } <ide> <ide><path>tests/TestCase/View/StringTemplateTest.php <ide> public function testLoadPlugin() <ide> $this->loadPlugins(['TestPlugin']); <ide> $this->assertNull($this->template->load('TestPlugin.test_templates')); <ide> $this->assertEquals('<em>{{text}}</em>', $this->template->get('italic')); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/ViewTest.php <ide> public function setUp() <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> unset($this->View); <ide> unset($this->PostsController); <ide> unset($this->Controller); <ide><path>tests/TestCase/View/Widget/WidgetLocatorTest.php <ide> public function testAddPluginWidgetsFromConfigInConstructor() <ide> ]; <ide> $inputs = new WidgetLocator($this->templates, $this->view, $widgets); <ide> $this->assertInstanceOf('Cake\View\Widget\LabelWidget', $inputs->get('text')); <del> Plugin::getCollection()->clear(); <add> $this->clearPlugins(); <ide> } <ide> <ide> /**
59
Ruby
Ruby
fix audit suggestion
5c24876d024e3789fe5e87e31e9315c0eb1dfee6
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_line(line, lineno) <ide> end <ide> <ide> if line =~ /if\s+ARGV\.include\?\s+'--(HEAD|devel)'/ <del> problem "Use \"if ARGV.build_#{$1.downcase}?\" instead" <add> problem "Use \"if build.#{$1.downcase}?\" instead" <ide> end <ide> <ide> if line =~ /make && make/
1
PHP
PHP
make check for `..` more specific
c685f6ca1372609b36844baeaf990b37a76d0cd2
<ide><path>lib/Cake/Core/App.php <ide> public static function load($className) { <ide> if (!isset(self::$_classMap[$className])) { <ide> return false; <ide> } <del> if (strpos($className, '..')) { <add> if (strpos($className, '..') !== false) { <ide> return false; <ide> } <ide>
1
Text
Text
fix broken link for shouldcomponentupdate
234142cdf7aacf441145be534b84957db0f73af5
<ide><path>docs/DirectManipulation.md <ide> properties directly on a DOM node. <ide> > and stores state in the native layer (DOM, UIView, etc.) and not <ide> > within your React components, which makes your code more difficult to <ide> > reason about. Before you use it, try to solve your problem with `setState` <del>> and [shouldComponentUpdate](react-native/docs/direct-manipulation.html#setnativeprops-shouldcomponentupdate). <add>> and [shouldComponentUpdate](http://facebook.github.io/react/docs/advanced-performance.html#shouldcomponentupdate-in-action). <ide> <ide> ## setNativeProps with TouchableOpacity <ide>
1
Javascript
Javascript
use deepstrictequal for false-y values
15d970d65c8da7970e6bacb9feccb4b830376881
<ide><path>test/parallel/test-repl-tab-complete.js <ide> var spaceTimeout = setTimeout(function() { <ide> }, 1000); <ide> <ide> testMe.complete(' ', common.mustCall(function(error, data) { <del> assert.deepEqual(data, [[], undefined]); <add> assert.deepStrictEqual(data, [[], undefined]); <ide> clearTimeout(spaceTimeout); <ide> })); <ide> <ide> putIn.run(['.clear']); <ide> putIn.run(['function a() {}']); <ide> <ide> testMe.complete('a().b.', common.mustCall((error, data) => { <del> assert.deepEqual(data, [[], undefined]); <add> assert.deepStrictEqual(data, [[], undefined]); <ide> }));
1
PHP
PHP
add strict typing to database types
99f41b86843a12fba3d6e53ed69f05ca408a0222
<ide><path>src/Database/Type/BaseType.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> abstract class BaseType implements TypeInterface <ide> * <ide> * @param string|null $name The name identifying this type <ide> */ <del> public function __construct($name = null) <add> public function __construct(?string $name = null) <ide> { <ide> $this->_name = $name; <ide> } <ide><path>src/Database/Type/BatchCastingInterface.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> interface BatchCastingInterface <ide> * @param \Cake\Database\Driver $driver Object from which database preferences and configuration will be extracted. <ide> * @return array <ide> */ <del> public function manyToPHP(array $values, array $fields, Driver $driver); <add> public function manyToPHP(array $values, array $fields, Driver $driver): array; <ide> } <ide><path>src/Database/Type/BinaryType.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function toPHP($value, Driver $driver) <ide> * @param \Cake\Database\Driver $driver The driver. <ide> * @return int <ide> */ <del> public function toStatement($value, Driver $driver) <add> public function toStatement($value, Driver $driver): int <ide> { <ide> return PDO::PARAM_LOB; <ide> } <ide><path>src/Database/Type/BinaryUuidType.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function toDatabase($value, Driver $driver) <ide> * <ide> * @return string A new primary key value. <ide> */ <del> public function newId() <add> public function newId(): string <ide> { <ide> return Text::uuid(); <ide> } <ide> public function toPHP($value, Driver $driver) <ide> * @param \Cake\Database\Driver $driver The driver. <ide> * @return int <ide> */ <del> public function toStatement($value, Driver $driver) <add> public function toStatement($value, Driver $driver): int <ide> { <ide> return PDO::PARAM_LOB; <ide> } <ide> public function marshal($value) <ide> * <ide> * @return string Converted value. <ide> */ <del> protected function convertBinaryUuidToString($binary) <add> protected function convertBinaryUuidToString($binary): string <ide> { <ide> $string = unpack("H*", $binary); <ide> <ide><path>src/Database/Type/BoolType.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class BoolType extends BaseType implements BatchCastingInterface <ide> * @param \Cake\Database\Driver $driver The driver instance to convert with. <ide> * @return bool|null <ide> */ <del> public function toDatabase($value, Driver $driver) <add> public function toDatabase($value, Driver $driver): ?bool <ide> { <ide> if ($value === true || $value === false || $value === null) { <ide> return $value; <ide> public function toDatabase($value, Driver $driver) <ide> * @param \Cake\Database\Driver $driver The driver instance to convert with. <ide> * @return bool|null <ide> */ <del> public function toPHP($value, Driver $driver) <add> public function toPHP($value, Driver $driver): ?bool <ide> { <ide> if ($value === null || $value === true || $value === false) { <ide> return $value; <ide> public function toPHP($value, Driver $driver) <ide> * <ide> * @return array <ide> */ <del> public function manyToPHP(array $values, array $fields, Driver $driver) <add> public function manyToPHP(array $values, array $fields, Driver $driver): array <ide> { <ide> foreach ($fields as $field) { <ide> if (!isset($values[$field]) || $values[$field] === true || $values[$field] === false) { <ide> public function manyToPHP(array $values, array $fields, Driver $driver) <ide> * @param \Cake\Database\Driver $driver The driver. <ide> * @return int <ide> */ <del> public function toStatement($value, Driver $driver) <add> public function toStatement($value, Driver $driver): int <ide> { <ide> if ($value === null) { <ide> return PDO::PARAM_NULL; <ide> public function toStatement($value, Driver $driver) <ide> * @param mixed $value The value to convert. <ide> * @return bool|null Converted value. <ide> */ <del> public function marshal($value) <add> public function marshal($value): ?bool <ide> { <ide> if ($value === null) { <ide> return null; <ide><path>src/Database/Type/DateTimeType.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function __construct($name = null) <ide> * @param \Cake\Database\Driver $driver The driver instance to convert with. <ide> * @return string|null <ide> */ <del> public function toDatabase($value, Driver $driver) <add> public function toDatabase($value, Driver $driver): ?string <ide> { <ide> if ($value === null || is_string($value)) { <ide> return $value; <ide> public function manyToPHP(array $values, array $fields, Driver $driver) <ide> * @param mixed $value Request data <ide> * @return \DateTimeInterface|null <ide> */ <del> public function marshal($value) <add> public function marshal($value): ?DateTimeInterface <ide> { <ide> if ($value instanceof DateTimeInterface) { <ide> return $value; <ide> public function marshal($value) <ide> $compare = true; <ide> } <ide> if ($compare && $date && !$this->_compare($date, $value)) { <del> return $value; <add> return null; <ide> } <ide> if ($date) { <ide> return $date; <ide> } <ide> } catch (Exception $e) { <del> return $value; <add> return null; <ide> } <ide> <ide> if (is_array($value) && implode('', $value) === '') { <ide> public function marshal($value) <ide> * @param mixed $value Request data <ide> * @return bool <ide> */ <del> protected function _compare($date, $value) <add> protected function _compare($date, $value): bool <ide> { <ide> foreach ((array)$this->_format as $format) { <ide> if ($date->format($format) === $value) { <ide> protected function _compare($date, $value) <ide> * @param bool $enable Whether or not to enable <ide> * @return $this <ide> */ <del> public function useLocaleParser($enable = true) <add> public function useLocaleParser(bool $enable = true) <ide> { <ide> if ($enable === false) { <ide> $this->_useLocaleParser = $enable; <ide> public function useImmutable() <ide> * @param string $fallback The classname to use when the preferred class does not exist. <ide> * @return void <ide> */ <del> protected function _setClassName($class, $fallback) <add> protected function _setClassName(string $class, string $fallback): void <ide> { <ide> if (!class_exists($class)) { <ide> $class = $fallback; <ide> protected function _setClassName($class, $fallback) <ide> * <ide> * @return string <ide> */ <del> public function getDateTimeClassName() <add> public function getDateTimeClassName(): string <ide> { <ide> return $this->_className; <ide> } <ide> public function useMutable() <ide> * @param string $value The value to parse and convert to an object. <ide> * @return \Cake\I18n\Time|null <ide> */ <del> protected function _parseValue($value) <add> protected function _parseValue(string $value) <ide> { <ide> /* @var \Cake\I18n\Time $class */ <ide> $class = $this->_className; <ide><path>src/Database/Type/DateType.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> use Cake\I18n\Date; <ide> use Cake\I18n\FrozenDate; <ide> use DateTime; <add>use DateTimeInterface; <ide> use DateTimeImmutable; <ide> <ide> /** <ide> public function useMutable() <ide> * Convert request data into a datetime object. <ide> * <ide> * @param mixed $value Request data <del> * @return \DateTimeInterface <add> * @return \DateTimeInterface|null <ide> */ <del> public function marshal($value) <add> public function marshal($value): ?DateTimeInterface <ide> { <ide> $date = parent::marshal($value); <ide> if ($date instanceof DateTime) { <ide><path>src/Database/Type/DecimalType.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class DecimalType extends BaseType implements BatchCastingInterface <ide> * @return string|null <ide> * @throws \InvalidArgumentException <ide> */ <del> public function toDatabase($value, Driver $driver) <add> public function toDatabase($value, Driver $driver): ?string <ide> { <ide> if ($value === null || $value === '') { <ide> return null; <ide> public function toDatabase($value, Driver $driver) <ide> * @return float|null <ide> * @throws \Cake\Core\Exception\Exception <ide> */ <del> public function toPHP($value, Driver $driver) <add> public function toPHP($value, Driver $driver): ?float <ide> { <ide> if ($value === null) { <ide> return $value; <ide> public function toPHP($value, Driver $driver) <ide> * <ide> * @return array <ide> */ <del> public function manyToPHP(array $values, array $fields, Driver $driver) <add> public function manyToPHP(array $values, array $fields, Driver $driver): array <ide> { <ide> foreach ($fields as $field) { <ide> if (!isset($values[$field])) { <ide> public function manyToPHP(array $values, array $fields, Driver $driver) <ide> * @param \Cake\Database\Driver $driver The driver. <ide> * @return int <ide> */ <del> public function toStatement($value, Driver $driver) <add> public function toStatement($value, Driver $driver): int <ide> { <ide> return PDO::PARAM_STR; <ide> } <ide> public function marshal($value) <ide> * @param bool $enable Whether or not to enable <ide> * @return $this <ide> */ <del> public function useLocaleParser($enable = true) <add> public function useLocaleParser(bool $enable = true) <ide> { <ide> if ($enable === false) { <ide> $this->_useLocaleParser = $enable; <ide> public function useLocaleParser($enable = true) <ide> * @param string $value The value to parse and convert to an float. <ide> * @return float <ide> */ <del> protected function _parseValue($value) <add> protected function _parseValue(string $value): float <ide> { <ide> /* @var \Cake\I18n\Number $class */ <ide> $class = static::$numberClass; <ide><path>src/Database/Type/ExpressionTypeCasterTrait.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> protected function _castToExpression($value, $type) <ide> * @param array $types List of type names <ide> * @return array <ide> */ <del> protected function _requiresToExpressionCasting($types) <add> protected function _requiresToExpressionCasting(array $types): array <ide> { <ide> $result = []; <ide> $types = array_filter($types); <ide><path>src/Database/Type/ExpressionTypeInterface.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> */ <ide> namespace Cake\Database\Type; <ide> <add>use Cake\Database\ExpressionInterface; <add> <ide> /** <ide> * An interface used by Type objects to signal whether the value should <ide> * be converted to an ExpressionInterface instead of a string when sent <ide> interface ExpressionTypeInterface <ide> * @param mixed $value The value to be converted to an expression <ide> * @return \Cake\Database\ExpressionInterface <ide> */ <del> public function toExpression($value); <add> public function toExpression($value): ExpressionInterface; <ide> } <ide><path>src/Database/Type/FloatType.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class FloatType extends BaseType implements BatchCastingInterface <ide> * @param \Cake\Database\Driver $driver The driver instance to convert with. <ide> * @return float|null <ide> */ <del> public function toDatabase($value, Driver $driver) <add> public function toDatabase($value, Driver $driver): ?float <ide> { <ide> if ($value === null || $value === '') { <ide> return null; <ide> public function toDatabase($value, Driver $driver) <ide> * @return float|null <ide> * @throws \Cake\Core\Exception\Exception <ide> */ <del> public function toPHP($value, Driver $driver) <add> public function toPHP($value, Driver $driver): ?float <ide> { <ide> if ($value === null) { <ide> return null; <ide> public function toPHP($value, Driver $driver) <ide> * <ide> * @return array <ide> */ <del> public function manyToPHP(array $values, array $fields, Driver $driver) <add> public function manyToPHP(array $values, array $fields, Driver $driver): array <ide> { <ide> foreach ($fields as $field) { <ide> if (!isset($values[$field])) { <ide> public function manyToPHP(array $values, array $fields, Driver $driver) <ide> * @param \Cake\Database\Driver $driver The driver. <ide> * @return int <ide> */ <del> public function toStatement($value, Driver $driver) <add> public function toStatement($value, Driver $driver): int <ide> { <ide> return PDO::PARAM_STR; <ide> } <ide> public function toStatement($value, Driver $driver) <ide> * @param mixed $value The value to convert. <ide> * @return float|null Converted value. <ide> */ <del> public function marshal($value) <add> public function marshal($value): ?float <ide> { <ide> if ($value === null || $value === '') { <ide> return null; <ide> public function marshal($value) <ide> return 1.0; <ide> } <ide> <del> return $value; <add> return null; <ide> } <ide> <ide> /** <ide> public function marshal($value) <ide> * @param bool $enable Whether or not to enable <ide> * @return $this <ide> */ <del> public function useLocaleParser($enable = true) <add> public function useLocaleParser(bool $enable = true) <ide> { <ide> if ($enable === false) { <ide> $this->_useLocaleParser = $enable; <ide> public function useLocaleParser($enable = true) <ide> * @param string $value The value to parse and convert to an float. <ide> * @return float <ide> */ <del> protected function _parseValue($value) <add> protected function _parseValue(string $value): float <ide> { <ide> $class = static::$numberClass; <ide> <ide><path>src/Database/Type/IntegerType.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class IntegerType extends BaseType implements BatchCastingInterface <ide> * @param \Cake\Database\Driver $driver The driver instance to convert with. <ide> * @return int|null <ide> */ <del> public function toDatabase($value, Driver $driver) <add> public function toDatabase($value, Driver $driver): ?int <ide> { <ide> if ($value === null || $value === '') { <ide> return null; <ide> public function toDatabase($value, Driver $driver) <ide> * @param \Cake\Database\Driver $driver The driver instance to convert with. <ide> * @return int|null <ide> */ <del> public function toPHP($value, Driver $driver) <add> public function toPHP($value, Driver $driver): ?int <ide> { <ide> if ($value === null) { <ide> return $value; <ide> public function toPHP($value, Driver $driver) <ide> * <ide> * @return array <ide> */ <del> public function manyToPHP(array $values, array $fields, Driver $driver) <add> public function manyToPHP(array $values, array $fields, Driver $driver): array <ide> { <ide> foreach ($fields as $field) { <ide> if (!isset($values[$field])) { <ide> public function manyToPHP(array $values, array $fields, Driver $driver) <ide> * @param \Cake\Database\Driver $driver The driver. <ide> * @return int <ide> */ <del> public function toStatement($value, Driver $driver) <add> public function toStatement($value, Driver $driver): int <ide> { <ide> return PDO::PARAM_INT; <ide> } <ide> public function toStatement($value, Driver $driver) <ide> * @param mixed $value The value to convert. <ide> * @return int|null Converted value. <ide> */ <del> public function marshal($value) <add> public function marshal($value): ?int <ide> { <ide> if ($value === null || $value === '') { <ide> return null; <ide><path>src/Database/Type/JsonType.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class JsonType extends BaseType implements BatchCastingInterface <ide> * @param \Cake\Database\Driver $driver The driver instance to convert with. <ide> * @return string|null <ide> */ <del> public function toDatabase($value, Driver $driver) <add> public function toDatabase($value, Driver $driver): ?string <ide> { <ide> if (is_resource($value)) { <ide> throw new InvalidArgumentException('Cannot convert a resource value to JSON'); <ide> public function toDatabase($value, Driver $driver) <ide> */ <ide> public function toPHP($value, Driver $driver) <ide> { <add> if (!is_string($value)) { <add> return null; <add> } <add> <ide> return json_decode($value, true); <ide> } <ide> <ide> public function toPHP($value, Driver $driver) <ide> * <ide> * @return array <ide> */ <del> public function manyToPHP(array $values, array $fields, Driver $driver) <add> public function manyToPHP(array $values, array $fields, Driver $driver): array <ide> { <ide> foreach ($fields as $field) { <ide> if (!isset($values[$field])) { <ide> public function manyToPHP(array $values, array $fields, Driver $driver) <ide> * @param \Cake\Database\Driver $driver The driver. <ide> * @return int <ide> */ <del> public function toStatement($value, Driver $driver) <add> public function toStatement($value, Driver $driver): int <ide> { <ide> return PDO::PARAM_STR; <ide> } <ide><path>src/Database/Type/OptionalConvertInterface.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> interface OptionalConvertInterface <ide> * <ide> * @return bool <ide> */ <del> public function requiresToPhpCast(); <add> public function requiresToPhpCast(): bool; <ide> } <ide><path>src/Database/Type/StringType.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class StringType extends BaseType implements OptionalConvertInterface <ide> * @param \Cake\Database\Driver $driver The driver instance to convert with. <ide> * @return string|null <ide> */ <del> public function toDatabase($value, Driver $driver) <add> public function toDatabase($value, Driver $driver): ?string <ide> { <ide> if ($value === null || is_string($value)) { <ide> return $value; <ide> public function toDatabase($value, Driver $driver) <ide> * @param \Cake\Database\Driver $driver The driver instance to convert with. <ide> * @return string|null <ide> */ <del> public function toPHP($value, Driver $driver) <add> public function toPHP($value, Driver $driver): ?string <ide> { <ide> if ($value === null) { <ide> return null; <ide> public function toPHP($value, Driver $driver) <ide> * @param \Cake\Database\Driver $driver The driver. <ide> * @return int <ide> */ <del> public function toStatement($value, Driver $driver) <add> public function toStatement($value, Driver $driver): int <ide> { <ide> return PDO::PARAM_STR; <ide> } <ide> public function toStatement($value, Driver $driver) <ide> * @param mixed $value The value to convert. <ide> * @return string|null Converted value. <ide> */ <del> public function marshal($value) <add> public function marshal($value): ?string <ide> { <ide> if ($value === null) { <ide> return null; <ide> public function marshal($value) <ide> * <ide> * @return bool False as database results are returned already as strings <ide> */ <del> public function requiresToPhpCast() <add> public function requiresToPhpCast(): bool <ide> { <ide> return false; <ide> } <ide><path>src/Database/Type/TimeType.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Database/Type/UuidType.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class UuidType extends StringType <ide> * @param \Cake\Database\Driver $driver object from which database preferences and configuration will be extracted <ide> * @return string|null <ide> */ <del> public function toDatabase($value, Driver $driver) <add> public function toDatabase($value, Driver $driver): ?string <ide> { <ide> if ($value === null || $value === '') { <ide> return null; <ide> public function toDatabase($value, Driver $driver) <ide> * <ide> * @return string A new primary key value. <ide> */ <del> public function newId() <add> public function newId(): string <ide> { <ide> return Text::uuid(); <ide> } <ide> public function newId() <ide> * @param mixed $value The value to convert. <ide> * @return string|null Converted value. <ide> */ <del> public function marshal($value) <add> public function marshal($value): ?string <ide> { <ide> if ($value === null || $value === '' || is_array($value)) { <ide> return null; <ide><path>tests/TestCase/Database/ExpressionTypeCastingIntegrationTest.php <ide> use Cake\Database\Driver; <ide> use Cake\Database\Driver\Sqlserver; <ide> use Cake\Database\Expression\FunctionExpression; <add>use Cake\Database\ExpressionInterface; <ide> use Cake\Database\Type\BaseType; <ide> use Cake\Database\Type\ExpressionTypeInterface; <ide> use Cake\Database\TypeFactory; <ide> public function toPHP($value, Driver $d) <ide> return new UuidValue($value); <ide> } <ide> <del> public function toExpression($value) <add> public function toExpression($value): ExpressionInterface <ide> { <ide> if ($value instanceof UuidValue) { <ide> $value = $value->value; <ide><path>tests/TestCase/Database/ExpressionTypeCastingTest.php <ide> use Cake\Database\Expression\Comparison; <ide> use Cake\Database\Expression\FunctionExpression; <ide> use Cake\Database\Expression\ValuesExpression; <add>use Cake\Database\ExpressionInterface; <ide> use Cake\Database\Type\ExpressionTypeInterface; <ide> use Cake\Database\Type\StringType; <ide> use Cake\Database\TypeFactory; <ide> <ide> class TestType extends StringType implements ExpressionTypeInterface <ide> { <del> public function toExpression($value) <add> public function toExpression($value): ExpressionInterface <ide> { <ide> return new FunctionExpression('CONCAT', [$value, ' - foo']); <ide> } <ide><path>tests/TestCase/Database/Type/BinaryTypeTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Database/Type/BinaryUuidTypeTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Database/Type/BoolTypeTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Database/Type/DateTimeTypeTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function marshalProvider() <ide> [false, null], <ide> [true, null], <ide> ['', null], <del> ['derpy', 'derpy'], <del> ['2013-nope!', '2013-nope!'], <del> ['13-06-26', '13-06-26'], <add> ['derpy', null], <add> ['2013-nope!', null], <add> ['13-06-26', null], <ide> <ide> // valid string types <ide> ['1392387900', new Time('@1392387900')], <ide><path>tests/TestCase/Database/Type/DateTypeTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function marshalProvider() <ide> [false, null], <ide> [true, null], <ide> ['', null], <del> ['derpy', 'derpy'], <del> ['2013-nope!', '2013-nope!'], <del> ['14-02-14', '14-02-14'], <del> ['2014-02-14 13:14:15', '2014-02-14 13:14:15'], <add> ['derpy', null], <add> ['2013-nope!', null], <add> ['14-02-14', null], <add> ['2014-02-14 13:14:15', null], <ide> <ide> // valid string types <ide> ['1392387900', $date], <ide><path>tests/TestCase/Database/Type/DecimalTypeTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Database/Type/FloatTypeTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function testToDatabase() <ide> public function testMarshal() <ide> { <ide> $result = $this->type->marshal('some data'); <del> $this->assertSame('some data', $result); <add> $this->assertNull($result); <ide> <ide> $result = $this->type->marshal(''); <ide> $this->assertNull($result); <ide> public function testMarshal() <ide> $this->assertSame(2.51, $result); <ide> <ide> $result = $this->type->marshal('3.5 bears'); <del> $this->assertSame('3.5 bears', $result); <add> $this->assertNull($result); <ide> <ide> $result = $this->type->marshal(['3', '4']); <ide> $this->assertSame(1.0, $result); <ide><path>tests/TestCase/Database/Type/IntegerTypeTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Database/Type/JsonTypeTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Database/Type/StringTypeTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Database/Type/TimeTypeTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function marshalProvider() <ide> [false, null], <ide> [true, null], <ide> ['', null], <del> ['derpy', 'derpy'], <del> ['16-nope!', '16-nope!'], <del> ['14:15', '14:15'], <del> ['2014-02-14 13:14:15', '2014-02-14 13:14:15'], <add> ['derpy', null], <add> ['16-nope!', null], <add> ['14:15', null], <add> ['2014-02-14 13:14:15', null], <ide> <ide> // valid string types <ide> ['1392387900', $date], <ide><path>tests/TestCase/Database/Type/UuidTypeTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
31
Ruby
Ruby
remove unused guard
ad291d7f06acefad08453d781b3bbc70edc71238
<ide><path>Library/Homebrew/bottles.rb <ide> def install_bottle? f, warn=false <ide> end <ide> <ide> def built_as_bottle? f <del> f = Formula.factory f unless f.kind_of? Formula <ide> return false unless f.installed? <ide> tab = Tab.for_keg(f.installed_prefix) <ide> # Need to still use the old "built_bottle" until all bottles are updated.
1
Go
Go
remove unused variable, fix
9c9b748ad8fefb059d0c6bf585593ae1b623cc51
<ide><path>pkg/term/windows/ansi_reader.go <ide> func keyToString(keyEvent *winterm.KEY_EVENT_RECORD, escapeSequence []byte) stri <ide> // formatVirtualKey converts a virtual key (e.g., up arrow) into the appropriate ANSI string. <ide> func formatVirtualKey(key winterm.WORD, controlState winterm.DWORD, escapeSequence []byte) string { <ide> shift, alt, control := getControlKeys(controlState) <del> modifier := getControlKeysModifier(shift, alt, control, false) <add> modifier := getControlKeysModifier(shift, alt, control) <ide> <ide> if format, ok := arrowKeyMapPrefix[key]; ok { <ide> return fmt.Sprintf(format, escapeSequence, modifier) <ide> func getControlKeys(controlState winterm.DWORD) (shift, alt, control bool) { <ide> } <ide> <ide> // getControlKeysModifier returns the ANSI modifier for the given combination of control keys. <del>func getControlKeysModifier(shift, alt, control, meta bool) string { <add>func getControlKeysModifier(shift, alt, control bool) string { <ide> if shift && alt && control { <ide> return ansiterm.KEY_CONTROL_PARAM_8 <ide> }
1
Javascript
Javascript
hide ishidden challenges from hotkey nav
48532d6ccb14e2430e1cd07e1da641f60d055562
<ide><path>client/gatsby-node.js <ide> exports.createPages = function createPages({ graphql, actions, reporter }) { <ide> } <ide> <ide> // Create challenge pages. <del> result.data.allChallengeNode.edges.forEach( <del> createChallengePages(createPage) <add> const challengeEdges = result.data.allChallengeNode.edges.filter( <add> ({ node: { isHidden } }) => !isHidden <ide> ); <ide> <add> challengeEdges.forEach(createChallengePages(createPage)); <add> <ide> // Create intro pages <ide> result.data.allMarkdownRemark.edges.forEach(edge => { <ide> const { <ide><path>client/utils/gatsby/challengePageCreator.js <ide> exports.createChallengePages = createPage => ({ node }, index, thisArray) => { <ide> required = [], <ide> template, <ide> challengeType, <del> id, <del> isHidden <add> id <ide> } = node; <ide> // TODO: challengeType === 7 and isPrivate are the same, right? If so, we <ide> // should remove one of them. <del> if (challengeType === 7 || isHidden) { <add> if (challengeType === 7) { <ide> return null; <ide> } <ide>
2
Ruby
Ruby
use safe navigation
ddcd6df27ff8fc984789923227dd1d27e92e45b7
<ide><path>lib/active_storage/service/gcs_service.rb <ide> def download(key) <ide> end <ide> <ide> def delete(key) <del> file_for(key).try(:delete) <add> file_for(key)&.delete <ide> end <ide> <ide> def exist?(key)
1
Python
Python
improve record module documentation
0b516d28e606d97266a95234a8deea268ecc3ec8
<ide><path>numpy/core/records.py <ide> def _deprecate_shape_0_as_None(shape): <ide> <ide> def fromarrays(arrayList, dtype=None, shape=None, formats=None, <ide> names=None, titles=None, aligned=False, byteorder=None): <del> """ create a record array from a (flat) list of arrays <add> """Create a record array from a (flat) list of arrays <ide> <add> Parameters <add> ---------- <add> arrayList : list or tuple <add> List of array-like objects (such as lists, tuples, <add> and ndarrays). <add> dtype : data-type, optional <add> valid dtype for all arrays <add> shape : int or tuple of ints, optional <add> Shape of the resulting array. If not provided, inferred from <add> ``arrayList[0]``. <add> formats, names, titles, aligned, byteorder : <add> If `dtype` is ``None``, these arguments are passed to <add> `numpy.format_parser` to construct a dtype. See that function for <add> detailed documentation. <add> <add> Returns <add> ------- <add> np.recarray <add> Record array consisting of given arrayList columns. <add> <add> Examples <add> -------- <ide> >>> x1=np.array([1,2,3,4]) <ide> >>> x2=np.array(['a','dd','xyz','12']) <ide> >>> x3=np.array([1.1,2,3,4]) <ide> def fromarrays(arrayList, dtype=None, shape=None, formats=None, <ide> >>> x1[1]=34 <ide> >>> r.a <ide> array([1, 2, 3, 4]) <add> <add> >>> x1 = np.array([1, 2, 3, 4]) <add> >>> x2 = np.array(['a', 'dd', 'xyz', '12']) <add> >>> x3 = np.array([1.1, 2, 3,4]) <add> >>> r = np.core.records.fromarrays( <add> ... [x1, x2, x3], <add> ... dtype=np.dtype([('a', np.int32), ('b', 'S3'), ('c', np.float32)])) <add> >>> r <add> rec.array([(1, b'a', 1.1), (2, b'dd', 2. ), (3, b'xyz', 3. ), <add> (4, b'12', 4. )], <add> dtype=[('a', '<i4'), ('b', 'S3'), ('c', '<f4')]) <ide> """ <ide> <ide> arrayList = [sb.asarray(x) for x in arrayList] <ide> def fromarrays(arrayList, dtype=None, shape=None, formats=None, <ide> <ide> def fromrecords(recList, dtype=None, shape=None, formats=None, names=None, <ide> titles=None, aligned=False, byteorder=None): <del> """ create a recarray from a list of records in text form <del> <del> The data in the same field can be heterogeneous, they will be promoted <del> to the highest data type. This method is intended for creating <del> smaller record arrays. If used to create large array without formats <del> defined <del> <del> r=fromrecords([(2,3.,'abc')]*100000) <add> """Create a recarray from a list of records in text form. <ide> <del> it can be slow. <add> Parameters <add> ---------- <add> recList : sequence <add> data in the same field may be heterogeneous - they will be promoted <add> to the highest data type. <add> dtype : data-type, optional <add> valid dtype for all arrays <add> shape : int or tuple of ints, optional <add> shape of each array. <add> formats, names, titles, aligned, byteorder : <add> If `dtype` is ``None``, these arguments are passed to <add> `numpy.format_parser` to construct a dtype. See that function for <add> detailed documentation. <add> <add> If both `formats` and `dtype` are None, then this will auto-detect <add> formats. Use list of tuples rather than list of lists for faster <add> processing. <ide> <del> If formats is None, then this will auto-detect formats. Use list of <del> tuples rather than list of lists for faster processing. <add> Returns <add> ------- <add> np.recarray <add> record array consisting of given recList rows. <ide> <add> Examples <add> -------- <ide> >>> r=np.core.records.fromrecords([(456,'dbe',1.2),(2,'de',1.3)], <ide> ... names='col1,col2,col3') <ide> >>> print(r[0]) <ide> def fromrecords(recList, dtype=None, shape=None, formats=None, names=None, <ide> <ide> def fromstring(datastring, dtype=None, shape=None, offset=0, formats=None, <ide> names=None, titles=None, aligned=False, byteorder=None): <del> """ create a (read-only) record array from binary data contained in <add> """Create a (read-only) record array from binary data contained in <ide> a string""" <ide> <ide> if dtype is None and formats is None: <ide> def fromfile(fd, dtype=None, shape=None, offset=0, formats=None, <ide> names=None, titles=None, aligned=False, byteorder=None): <ide> """Create an array from binary file data <ide> <del> If file is a string or a path-like object then that file is opened, <del> else it is assumed to be a file object. The file object must <del> support random access (i.e. it must have tell and seek methods). <add> Parameters <add> ---------- <add> fd : str or file type <add> If file is a string or a path-like object then that file is opened, <add> else it is assumed to be a file object. The file object must <add> support random access (i.e. it must have tell and seek methods). <add> dtype : data-type, optional <add> valid dtype for all arrays <add> shape : int or tuple of ints, optional <add> shape of each array. <add> offset : int, optional <add> Position in the file to start reading from. <add> formats, names, titles, aligned, byteorder : <add> If `dtype` is ``None``, these arguments are passed to <add> `numpy.format_parser` to construct a dtype. See that function for <add> detailed documentation <add> <add> Returns <add> ------- <add> np.recarray <add> record array consisting of data enclosed in file. <ide> <add> Examples <add> -------- <ide> >>> from tempfile import TemporaryFile <ide> >>> a = np.empty(10,dtype='f8,i4,a5') <ide> >>> a[5] = (0.5,10,'abcde')
1
Javascript
Javascript
add failing test
26519bc932b1e96fef2530449c22cb0dc3f0dad4
<ide><path>packages/ember-views/tests/views/container_view_test.js <ide> test("if a ContainerView starts with a currentView and then is set to null, the <ide> equal(get(container, 'childViews.length'), 0, "should not have any child views"); <ide> }); <ide> <del>test("if a ContainerView starts with a currentView and then is set to null, the ContainerView is updated", function() { <add>test("if a ContainerView starts with a currentView and then is set to null, the ContainerView is updated and the previous currentView is destroyed", function() { <ide> var container = Ember.ContainerView.create(); <ide> var mainView = Ember.View.create({ <ide> template: function() { <ide> test("if a ContainerView starts with a currentView and then is set to null, the <ide> set(container, 'currentView', null); <ide> }); <ide> <add> equal(mainView.isDestroyed, true, 'should destroy the previous currentView.'); <add> <ide> equal(container.$().text(), '', "has a empty contents"); <ide> equal(get(container, 'childViews.length'), 0, "should not have any child views"); <ide> }); <ide> <del>test("if a ContainerView starts with a currentView and then a different currentView is set, the old view is removed and the new one is added", function() { <add>test("if a ContainerView starts with a currentView and then a different currentView is set, the old view is destroyed and the new one is added", function() { <ide> var container = Ember.ContainerView.create(); <ide> var mainView = Ember.View.create({ <ide> template: function() { <ide> test("if a ContainerView starts with a currentView and then a different currentV <ide> set(container, 'currentView', secondaryView); <ide> }); <ide> <add> equal(mainView.isDestroyed, true, 'should destroy the previous currentView.'); <add> <ide> equal(container.$().text(), "This is the secondary view.", "should render its child"); <ide> equal(get(container, 'childViews.length'), 1, "should have one child view"); <ide> equal(get(container, 'childViews').objectAt(0), secondaryView, "should have the currentView as the only child view");
1
Text
Text
remove joke in security guide [ci skip]
600c4138dd778f4e5633846b5b68a89dbb77193d
<ide><path>guides/source/security.md <ide> Here are some ideas how to hide honeypot fields by JavaScript and/or CSS: <ide> * make the elements very small or color them the same as the background of the page <ide> * leave the fields displayed, but tell humans to leave them blank <ide> <del>The most simple negative CAPTCHA is one hidden honeypot field. On the server side, you will check the value of the field: If it contains any text, it must be a bot. Then, you can either ignore the post or return a positive result, but not saving the post to the database. This way the bot will be satisfied and moves on. You can do this with annoying users, too. <add>The most simple negative CAPTCHA is one hidden honeypot field. On the server side, you will check the value of the field: If it contains any text, it must be a bot. Then, you can either ignore the post or return a positive result, but not saving the post to the database. This way the bot will be satisfied and moves on. <ide> <ide> You can find more sophisticated negative CAPTCHAs in Ned Batchelder's [blog post](http://nedbatchelder.com/text/stopbots.html): <ide>
1
Text
Text
revise the performance table for applications
a9d9595101f7e38780f197dfde643fcfcc0814d3
<ide><path>docs/templates/applications.md <ide> model = InceptionV3(input_tensor=input_tensor, weights='imagenet', include_top=T <ide> <ide> | Model | Size | Top-1 Accuracy | Top-5 Accuracy | Parameters | Depth | <ide> | ----- | ----: | --------------: | --------------: | ----------: | -----: | <del>| [Xception](#xception) | 88 MB | 0.790 | 0.945| 22,910,480 | 126 | <del>| [VGG16](#vgg16) | 528 MB| 0.715 | 0.901 | 138,357,544 | 23 <del>| [VGG19](#vgg19) | 549 MB | 0.727 | 0.910 | 143,667,240 | 26 <del>| [ResNet50](#resnet50) | 99 MB | 0.759 | 0.929 | 25,636,712 | 168 <del>| [InceptionV3](#inceptionv3) | 92 MB | 0.788 | 0.944 | 23,851,784 | 159 | <del>| [InceptionResNetV2](#inceptionresnetv2) | 215 MB | 0.804 | 0.953 | 55,873,736 | 572 | <del>| [MobileNet](#mobilenet) | 17 MB | 0.665 | 0.871 | 4,253,864 | 88 <del>| [DenseNet121](#densenet) | 33 MB | 0.745 | 0.918 | 8,062,504 | 121 <del>| [DenseNet169](#densenet) | 57 MB | 0.759 | 0.928 | 14,307,880 | 169 <del>| [DenseNet201](#densenet) | 80 MB | 0.770 | 0.933 | 20,242,984 | 201 <del> <add>| [Xception](#xception) | 88 MB | 0.790 | 0.945 | 22,910,480 | 126 | <add>| [VGG16](#vgg16) | 528 MB | 0.713 | 0.901 | 138,357,544 | 23 | <add>| [VGG19](#vgg19) | 549 MB | 0.713 | 0.900 | 143,667,240 | 26 | <add>| [ResNet50](#resnet50) | 99 MB | 0.749 | 0.921 | 25,636,712 | 168 | <add>| [InceptionV3](#inceptionv3) | 92 MB | 0.779 | 0.937 | 23,851,784 | 159 | <add>| [InceptionResNetV2](#inceptionresnetv2) | 215 MB | 0.803 | 0.953 | 55,873,736 | 572 | <add>| [MobileNet](#mobilenet) | 16 MB | 0.704 | 0.895 | 4,253,864 | 88 | <add>| [MobileNetV2](#mobilenetv2) | 14 MB | 0.713 | 0.901 | 3,538,984 | 88 | <add>| [DenseNet121](#densenet) | 33 MB | 0.750 | 0.923 | 8,062,504 | 121 | <add>| [DenseNet169](#densenet) | 57 MB | 0.762 | 0.932 | 14,307,880 | 169 | <add>| [DenseNet201](#densenet) | 80 MB | 0.773 | 0.936 | 20,242,984 | 201 | <add>| [NASNetMobile](#nasnet) | 23 MB | 0.744 | 0.919 | 5,326,716 | - | <add>| [NASNetLarge](#nasnet) | 343 MB | 0.825 | 0.960 | 88,949,818 | - | <ide> <ide> The top-1 and top-5 accuracy refers to the model's performance on the ImageNet validation dataset. <ide>
1
Java
Java
remove thread.sleep from unit test to speed it up
413887485eaaff20d960fed8d0c5b10449cdf1d4
<ide><path>rxjava-core/src/main/java/rx/operators/OperationConcat.java <ide> /** <ide> * Copyright 2013 Netflix, Inc. <del> * <add> * <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> * You may obtain a copy of the License at <del> * <add> * <ide> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <add> * <ide> * Unless required by applicable law or agreed to in writing, software <ide> * distributed under the License is distributed on an "AS IS" BASIS, <ide> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <ide> package rx.operators; <ide> <ide> import static org.junit.Assert.*; <add>import static org.mockito.Matchers.*; <ide> import static org.mockito.Mockito.*; <ide> <del>import java.util.Arrays; <ide> import java.util.ArrayList; <add>import java.util.Arrays; <ide> import java.util.List; <ide> import java.util.Queue; <add>import java.util.concurrent.ConcurrentLinkedQueue; <ide> import java.util.concurrent.CountDownLatch; <ide> import java.util.concurrent.TimeUnit; <ide> import java.util.concurrent.atomic.AtomicBoolean; <ide> import java.util.concurrent.atomic.AtomicReference; <del>import java.util.concurrent.ConcurrentLinkedQueue; <ide> <del>import org.junit.Ignore; <ide> import org.junit.Test; <del> <ide> import org.mockito.InOrder; <ide> <ide> import rx.Observable; <ide> import rx.Observer; <ide> import rx.Subscription; <ide> import rx.subscriptions.BooleanSubscription; <del>import rx.util.Exceptions; <ide> import rx.util.functions.Func1; <ide> <ide> /** <ide> public final class OperationConcat { <ide> * observable sequence without any transformation. If either the outer <ide> * observable or an inner observable calls onError, we will call onError. <ide> * <p/> <del> * <del> * @param sequences An observable sequence of elements to project. <add> * <add> * @param sequences <add> * An observable sequence of elements to project. <ide> * @return An observable sequence whose elements are the result of combining the output from the list of Observables. <ide> */ <ide> public static <T> Func1<Observer<T>, Subscription> concat(final Observable<T>... sequences) { <ide> public Subscription call(final Observer<T> observer) { <ide> public void onNext(T item) { <ide> observer.onNext(item); <ide> } <add> <ide> @Override <ide> public void onError(Throwable e) { <ide> if (completedOrErred.compareAndSet(false, true)) { <ide> outerSubscription.unsubscribe(); <ide> observer.onError(e); <ide> } <ide> } <add> <ide> @Override <ide> public void onCompleted() { <ide> synchronized (nextSequences) { <ide> public void onNext(Observable<T> nextSequence) { <ide> } <ide> } <ide> } <add> <ide> @Override <ide> public void onError(Throwable e) { <ide> if (completedOrErred.compareAndSet(false, true)) { <ide> public void onError(Throwable e) { <ide> observer.onError(e); <ide> } <ide> } <add> <ide> @Override <ide> public void onCompleted() { <ide> allSequencesReceived.set(true); <ide> public void testConcatObservableOfObservables() { <ide> <ide> Observable<Observable<String>> observableOfObservables = Observable.create(new Func1<Observer<Observable<String>>, Subscription>() { <ide> <del> @Override <del> public Subscription call(Observer<Observable<String>> observer) { <del> // simulate what would happen in an observable <del> observer.onNext(odds); <del> observer.onNext(even); <del> observer.onCompleted(); <add> @Override <add> public Subscription call(Observer<Observable<String>> observer) { <add> // simulate what would happen in an observable <add> observer.onNext(odds); <add> observer.onNext(even); <add> observer.onCompleted(); <ide> <del> return new Subscription() { <add> return new Subscription() { <ide> <del> @Override <del> public void unsubscribe() { <del> // unregister ... will never be called here since we are executing synchronously <del> } <add> @Override <add> public void unsubscribe() { <add> // unregister ... will never be called here since we are executing synchronously <add> } <ide> <del> }; <del> } <add> }; <add> } <add> <add> }); <add> Observable<String> concat = Observable.create(concat(observableOfObservables)); <ide> <del> }); <del> Observable<String> concat = Observable.create(concat(observableOfObservables)); <del> <ide> concat.subscribe(observer); <del> <add> <ide> verify(observer, times(7)).onNext(anyString()); <ide> } <ide> <ide> public void testNestedAsyncConcat() throws Throwable { <ide> final AtomicReference<Thread> parent = new AtomicReference<Thread>(); <ide> Observable<Observable<String>> observableOfObservables = Observable.create(new Func1<Observer<Observable<String>>, Subscription>() { <ide> <del> @Override <del> public Subscription call(final Observer<Observable<String>> observer) { <del> final BooleanSubscription s = new BooleanSubscription(); <del> parent.set(new Thread(new Runnable() { <del> <del> @Override <del> public void run() { <del> try { <del> // emit first <del> if (!s.isUnsubscribed()) { <del> System.out.println("Emit o1"); <del> observer.onNext(o1); <del> } <del> // emit second <del> if (!s.isUnsubscribed()) { <del> System.out.println("Emit o2"); <del> observer.onNext(o2); <del> } <del> <del> // wait until sometime later and emit third <del> try { <del> allowThird.await(); <del> } catch (InterruptedException e) { <del> observer.onError(e); <del> } <del> if (!s.isUnsubscribed()) { <del> System.out.println("Emit o3"); <del> observer.onNext(o3); <del> } <del> <del> } catch (Throwable e) { <del> observer.onError(e); <del> } finally { <del> System.out.println("Done parent Observable"); <del> observer.onCompleted(); <del> } <add> @Override <add> public Subscription call(final Observer<Observable<String>> observer) { <add> final BooleanSubscription s = new BooleanSubscription(); <add> parent.set(new Thread(new Runnable() { <add> <add> @Override <add> public void run() { <add> try { <add> // emit first <add> if (!s.isUnsubscribed()) { <add> System.out.println("Emit o1"); <add> observer.onNext(o1); <add> } <add> // emit second <add> if (!s.isUnsubscribed()) { <add> System.out.println("Emit o2"); <add> observer.onNext(o2); <add> } <add> <add> // wait until sometime later and emit third <add> try { <add> allowThird.await(); <add> } catch (InterruptedException e) { <add> observer.onError(e); <add> } <add> if (!s.isUnsubscribed()) { <add> System.out.println("Emit o3"); <add> observer.onNext(o3); <ide> } <del> })); <del> parent.get().start(); <del> return s; <del> } <del> }); <add> <add> } catch (Throwable e) { <add> observer.onError(e); <add> } finally { <add> System.out.println("Done parent Observable"); <add> observer.onCompleted(); <add> } <add> } <add> })); <add> parent.get().start(); <add> return s; <add> } <add> }); <ide> <ide> Observable.create(concat(observableOfObservables)).subscribe(observer); <ide> <ide> public void testBlockedObservableOfObservables() { <ide> verify(observer, times(1)).onNext("4"); <ide> verify(observer, times(1)).onNext("6"); <ide> } <del> <add> <ide> @Test <del> public void testConcatConcurrentWithInfinity() { <add> public void testConcatConcurrentWithInfinity() { <ide> final TestObservable<String> w1 = new TestObservable<String>("one", "two", "three"); <ide> //This observable will send "hello" MAX_VALUE time. <ide> final TestObservable<String> w2 = new TestObservable<String>("hello", Integer.MAX_VALUE); <ide> <ide> @SuppressWarnings("unchecked") <ide> Observer<String> aObserver = mock(Observer.class); <ide> @SuppressWarnings("unchecked") <del> TestObservable<Observable<String>> observableOfObservables = new TestObservable<Observable<String>>(w1, w2); <add> TestObservable<Observable<String>> observableOfObservables = new TestObservable<Observable<String>>(w1, w2); <ide> Func1<Observer<String>, Subscription> concatF = concat(observableOfObservables); <del> <add> <ide> Observable<String> concat = Observable.create(concatF); <del> <add> <ide> concat.take(50).subscribe(aObserver); <ide> <ide> //Wait for the thread to start up. <ide> try { <del> Thread.sleep(25); <del> w1.t.join(); <del> w2.t.join(); <del> } catch (InterruptedException e) { <del> // TODO Auto-generated catch block <del> e.printStackTrace(); <del> } <del> <add> Thread.sleep(25); <add> w1.t.join(); <add> w2.t.join(); <add> } catch (InterruptedException e) { <add> // TODO Auto-generated catch block <add> e.printStackTrace(); <add> } <add> <ide> InOrder inOrder = inOrder(aObserver); <del> inOrder.verify(aObserver, times(1)).onNext("one"); <add> inOrder.verify(aObserver, times(1)).onNext("one"); <ide> inOrder.verify(aObserver, times(1)).onNext("two"); <ide> inOrder.verify(aObserver, times(1)).onNext("three"); <ide> inOrder.verify(aObserver, times(47)).onNext("hello"); <ide> verify(aObserver, times(1)).onCompleted(); <ide> verify(aObserver, never()).onError(any(Throwable.class)); <del> <del> } <del> <del> <del> <add> } <add> <ide> @Test <del> public void testConcatUnSubscribeNotBlockingObservables() { <del> <del> final CountDownLatch okToContinueW1 = new CountDownLatch(1); <del> final CountDownLatch okToContinueW2 = new CountDownLatch(1); <del> <del> final TestObservable<String> w1 = new TestObservable<String>(null, okToContinueW1, "one", "two", "three"); <del> final TestObservable<String> w2 = new TestObservable<String>(null, okToContinueW2, "four", "five", "six"); <del> <del> @SuppressWarnings("unchecked") <del> Observer<String> aObserver = mock(Observer.class); <del> Observable<Observable<String>> observableOfObservables = Observable.create(new Func1<Observer<Observable<String>>, Subscription>() { <del> <del> @Override <del> public Subscription call(Observer<Observable<String>> observer) { <del> // simulate what would happen in an observable <del> observer.onNext(w1); <del> observer.onNext(w2); <del> observer.onCompleted(); <del> <del> return new Subscription() { <del> <del> @Override <del> public void unsubscribe() { <del> } <del> <del> }; <del> } <del> <del> }); <del> Observable<String> concat = Observable.create(concat(observableOfObservables)); <del> <del> concat.subscribe(aObserver); <del> <del> verify(aObserver, times(0)).onCompleted(); <del> <del> <del> //Wait for the thread to start up. <del> try { <del> Thread.sleep(25); <del> w1.t.join(); <del> w2.t.join(); <del> okToContinueW1.countDown(); <del> okToContinueW2.countDown(); <del> } catch (InterruptedException e) { <del> // TODO Auto-generated catch block <del> e.printStackTrace(); <del> } <del> <add> public void testConcatNonBlockingObservables() { <add> <add> final CountDownLatch okToContinueW1 = new CountDownLatch(1); <add> final CountDownLatch okToContinueW2 = new CountDownLatch(1); <add> <add> final TestObservable<String> w1 = new TestObservable<String>(null, okToContinueW1, "one", "two", "three"); <add> final TestObservable<String> w2 = new TestObservable<String>(null, okToContinueW2, "four", "five", "six"); <add> <add> @SuppressWarnings("unchecked") <add> Observer<String> aObserver = mock(Observer.class); <add> Observable<Observable<String>> observableOfObservables = Observable.create(new Func1<Observer<Observable<String>>, Subscription>() { <add> <add> @Override <add> public Subscription call(Observer<Observable<String>> observer) { <add> // simulate what would happen in an observable <add> observer.onNext(w1); <add> observer.onNext(w2); <add> observer.onCompleted(); <add> <add> return new Subscription() { <add> <add> @Override <add> public void unsubscribe() { <add> } <add> <add> }; <add> } <add> <add> }); <add> Observable<String> concat = Observable.create(concat(observableOfObservables)); <add> concat.subscribe(aObserver); <add> <add> verify(aObserver, times(0)).onCompleted(); <add> <add> try { <add> // release both threads <add> okToContinueW1.countDown(); <add> okToContinueW2.countDown(); <add> // wait for both to finish <add> w1.t.join(); <add> w2.t.join(); <add> } catch (InterruptedException e) { <add> // TODO Auto-generated catch block <add> e.printStackTrace(); <add> } <add> <ide> InOrder inOrder = inOrder(aObserver); <del> inOrder.verify(aObserver, times(1)).onNext("one"); <add> inOrder.verify(aObserver, times(1)).onNext("one"); <ide> inOrder.verify(aObserver, times(1)).onNext("two"); <ide> inOrder.verify(aObserver, times(1)).onNext("three"); <del> inOrder.verify(aObserver, times(1)).onNext("four"); <add> inOrder.verify(aObserver, times(1)).onNext("four"); <ide> inOrder.verify(aObserver, times(1)).onNext("five"); <ide> inOrder.verify(aObserver, times(1)).onNext("six"); <ide> verify(aObserver, times(1)).onCompleted(); <del> <del> <del> } <del> <del> <add> <add> } <add> <ide> /** <ide> * Test unsubscribing the concatenated Observable in a single thread. <ide> */ <ide> public void testConcatUnsubscribe() { <ide> inOrder.verify(aObserver, never()).onCompleted(); <ide> <ide> } <del> <add> <ide> /** <del> * All observables will be running in different threads so subscribe() is unblocked. CountDownLatch is only used in order to call unsubscribe() in a predictable manner. <add> * All observables will be running in different threads so subscribe() is unblocked. CountDownLatch is only used in order to call unsubscribe() in a predictable manner. <ide> */ <ide> @Test <del> public void testConcatUnsubscribeConcurrent() { <add> public void testConcatUnsubscribeConcurrent() { <ide> final CountDownLatch callOnce = new CountDownLatch(1); <ide> final CountDownLatch okToContinue = new CountDownLatch(1); <ide> final TestObservable<String> w1 = new TestObservable<String>("one", "two", "three"); <ide> public void testConcatUnsubscribeConcurrent() { <ide> @SuppressWarnings("unchecked") <ide> Observer<String> aObserver = mock(Observer.class); <ide> @SuppressWarnings("unchecked") <del> TestObservable<Observable<String>> observableOfObservables = new TestObservable<Observable<String>>(w1, w2); <add> TestObservable<Observable<String>> observableOfObservables = new TestObservable<Observable<String>>(w1, w2); <ide> Func1<Observer<String>, Subscription> concatF = concat(observableOfObservables); <del> <add> <ide> Observable<String> concat = Observable.create(concatF); <del> <add> <ide> Subscription s1 = concat.subscribe(aObserver); <del> <add> <ide> try { <ide> //Block main thread to allow observable "w1" to complete and observable "w2" to call onNext exactly once. <del> callOnce.await(); <del> //"four" from w2 has been processed by onNext() <add> callOnce.await(); <add> //"four" from w2 has been processed by onNext() <ide> s1.unsubscribe(); <ide> //"five" and "six" will NOT be processed by onNext() <ide> //Unblock the observable to continue. <ide> okToContinue.countDown(); <del> w1.t.join(); <add> w1.t.join(); <ide> w2.t.join(); <ide> } catch (Throwable e) { <ide> e.printStackTrace(); <ide> public void testConcatUnsubscribeConcurrent() { <ide> verify(aObserver, never()).onCompleted(); <ide> verify(aObserver, never()).onError(any(Throwable.class)); <ide> } <del> <add> <ide> private static class TestObservable<T> extends Observable<T> { <ide> <ide> private final Subscription s = new Subscription() { <ide> <del> @Override <del> public void unsubscribe() { <del> subscribed = false; <del> } <add> @Override <add> public void unsubscribe() { <add> subscribed = false; <add> } <ide> <del> }; <add> }; <ide> private final List<T> values; <ide> private Thread t = null; <ide> private int count = 0; <ide> public void unsubscribe() { <ide> private final CountDownLatch okToContinue; <ide> private final T seed; <ide> private final int size; <del> <add> <ide> public TestObservable(T... values) { <ide> this(null, null, values); <ide> } <ide> public TestObservable(CountDownLatch once, CountDownLatch okToContinue, T... val <ide> } <ide> <ide> public TestObservable(T seed, int size) { <del> values = null; <del> once = null; <del> okToContinue = null; <del> this.seed = seed; <del> this.size = size; <add> values = null; <add> once = null; <add> okToContinue = null; <add> this.seed = seed; <add> this.size = size; <ide> } <del> <del> <add> <ide> @Override <ide> public Subscription subscribe(final Observer<T> observer) { <ide> t = new Thread(new Runnable() { <ide> <del> @Override <del> public void run() { <del> try { <del> while (count < size && subscribed) { <del> if (null != values) <del> observer.onNext(values.get(count)); <del> else <del> observer.onNext(seed); <del> count++; <del> //Unblock the main thread to call unsubscribe. <del> if (null != once) <del> once.countDown(); <del> //Block until the main thread has called unsubscribe. <del> if (null != okToContinue) <del> okToContinue.await(1, TimeUnit.SECONDS); <del> } <del> if (subscribed) <del> observer.onCompleted(); <del> } catch (InterruptedException e) { <del> e.printStackTrace(); <del> fail(e.getMessage()); <add> @Override <add> public void run() { <add> try { <add> while (count < size && subscribed) { <add> if (null != values) <add> observer.onNext(values.get(count)); <add> else <add> observer.onNext(seed); <add> count++; <add> //Unblock the main thread to call unsubscribe. <add> if (null != once) <add> once.countDown(); <add> //Block until the main thread has called unsubscribe. <add> if (null != okToContinue) <add> okToContinue.await(5, TimeUnit.SECONDS); <ide> } <add> if (subscribed) <add> observer.onCompleted(); <add> } catch (InterruptedException e) { <add> e.printStackTrace(); <add> fail(e.getMessage()); <ide> } <add> } <ide> <del> }); <add> }); <ide> t.start(); <ide> return s; <ide> }
1
Python
Python
add test for non-contiguous input to ufuncs
56201bb0cadbf36806aed14391d399f6a1cb6152
<ide><path>numpy/core/tests/test_ufunc.py <ide> def test_ufunc_types(ufunc): <ide> assert r.dtype == np.dtype(t) <ide> else: <ide> assert res.dtype == np.dtype(out) <add> <add>@pytest.mark.parametrize('ufunc', [getattr(np, x) for x in dir(np) <add> if isinstance(getattr(np, x), np.ufunc)]) <add>def test_ufunc_noncontiguous(ufunc): <add> ''' <add> Check that contiguous and non-contiguous calls to ufuncs <add> have the same results for values in range(9) <add> ''' <add> for typ in ufunc.types: <add> # types is a list of strings like ii->i <add> if any(set('O?mM') & set(typ)): <add> # bool, object, datetime are too irregular for this simple test <add> continue <add> inp, out = typ.split('->') <add> args_c = [np.empty(6, t) for t in inp] <add> args_n = [np.empty(18, t)[::3] for t in inp] <add> for a in args_c: <add> a.flat = range(6) <add> for a in args_n: <add> a.flat = range(6) <add> with warnings.catch_warnings(record=True): <add> warnings.filterwarnings("always") <add> res_c = ufunc(*args_c) <add> res_n = ufunc(*args_n) <add> assert_equal(res_c, res_n)
1
Javascript
Javascript
fix line length
82dec9b81e8e66d3fb63c3e7690b4bf5318dc65e
<ide><path>src/ngRoute/route.js <ide> function $RouteProvider(){ <ide> * `$location.path()` by applying the current route <ide> * <ide> * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should <del> * be injected into the controller. If any of these dependencies are promises, the router will <del> * wait for them all to be resolved or one to be rejected before the controller is instantiated. <del> * If all the promises are resolved successfully, the values of the resolved promises are injected <del> * and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is fired. <del> * If any of the promises are rejected the {@link ngRoute.$route#$routeChangeError $routeChangeError} <del> * event is fired. The map object is: <add> * be injected into the controller. If any of these dependencies are promises, the router <add> * will wait for them all to be resolved or one to be rejected before the controller is <add> * instantiated. <add> * If all the promises are resolved successfully, the values of the resolved promises are <add> * injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is <add> * fired. If any of the promises are rejected the <add> * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object <add> * is: <ide> * <ide> * - `key` – `{string}`: a name of a dependency to be injected into the controller. <ide> * - `factory` - `{string|function}`: If `string` then it is an alias for a service.
1
Text
Text
fix the inception link in resnet
fa32bb5f6627a386b352d18a2495ab2bbf7f6129
<ide><path>official/resnet/README.md <ide> Use `--data_dir` to specify the location of the CIFAR-10 data used in the previo <ide> ## ImageNet <ide> <ide> ### Setup <del>To begin, you will need to download the ImageNet dataset and convert it to TFRecord format. Follow along with the [Inception guide](https://github.com/tensorflow/models/tree/master/inception#getting-started) in order to prepare the dataset. <add>To begin, you will need to download the ImageNet dataset and convert it to TFRecord format. Follow along with the [Inception guide](https://github.com/tensorflow/models/tree/master/research/inception#getting-started) in order to prepare the dataset. <ide> <ide> Once your dataset is ready, you can begin training the model as follows: <ide>
1
Text
Text
explain dynamic hints in more depth
0418c594451e042dfb57ef4fa6ce0bcf38273b73
<ide><path>docs/how-to-work-on-coding-challenges.md <ide> Tests to run against user code, in pairs of markdown text and code block test co <ide> Code for test one <ide> ``` <ide> <del>If you want dynamic output based on the user's code, --fcc-expected-- and --fcc-actual-- will be replaced with the expected and actual values of the test's assertion: <add>If you want dynamic output based on the user's code, --fcc-expected-- and --fcc-actual-- will be replaced with the expected and actual values of the test's assertion. Take care if you have multiple assertions since the first failing assertion will determine the values of --fcc-expected-- and --fcc-actual--. <ide> <ide> ```js <ide> assert.equal(
1
Text
Text
add superstring core
57d70438c795273f236bc1b857ec3b7979fb418f
<ide><path>docs/build-instructions/build-status.md <ide> | [PathWatcher](https://github.com/atom/node-pathwatcher) | [![macOS Build Status](https://travis-ci.org/atom/node-pathwatcher.svg?branch=master)](https://travis-ci.org/atom/node-pathwatcher) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/li8dkoucdrc2ryts/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/node-pathwatcher) | [![Dependency Status](https://david-dm.org/atom/node-pathwatcher/status.svg)](https://david-dm.org/atom/node-pathwatcher) | <ide> | [Property Accessors](https://github.com/atom/property-accessors) | [![macOS Build Status](https://travis-ci.org/atom/property-accessors.svg?branch=master)](https://travis-ci.org/atom/property-accessors) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/ww4d10hi4v5h7kbp/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/property-accessors/branch/master) | [![Dependency Status](https://david-dm.org/atom/property-accessors.svg)](https://david-dm.org/atom/property-accessors) | <ide> | [Season](https://github.com/atom/season) | [![macOS Build Status](https://travis-ci.org/atom/season.svg?branch=master)](https://travis-ci.org/atom/season) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/v3bth3ooq5q8k8lx/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/season) | [![Dependency Status](https://david-dm.org/atom/season.svg)](https://david-dm.org/atom/season) | <add>| [Superstring](https://github.com/atom/superstring) | [![macOS Build Status](https://travis-ci.org/atom/superstring.svg?branch=master)](https://travis-ci.org/atom/superstring) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/n5pack4yk7w80fso/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/superstring/branch/master) | | [![Dependency Status](https://david-dm.org/atom/superstring.svg)](https://david-dm.org/atom/superstring) | <ide> | [TextBuffer](https://github.com/atom/text-buffer) | [![macOS Build Status](https://travis-ci.org/atom/text-buffer.svg?branch=master)](https://travis-ci.org/atom/text-buffer) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/48xl8do1sm2thf5p/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/text-buffer/branch/master) | [![Dependency Status](https://david-dm.org/atom/text-buffer.svg)](https://david-dm.org/atom/text-buffer) | <ide> | [Underscore-Plus](https://github.com/atom/underscore-plus) | [![macOS Build Status](https://travis-ci.org/atom/underscore-plus.svg?branch=master)](https://travis-ci.org/atom/underscore-plus) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/c7l8009vgpaojxcd/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/underscore-plus/branch/master) | [![Dependency Status](https://david-dm.org/atom/underscore-plus.svg)](https://david-dm.org/atom/underscore-plus) | <ide>
1
Javascript
Javascript
add an ngaria module to make a11y easier
d1434c999a66c6bb915ee1a8b091e497d288d940
<ide><path>Gruntfile.js <ide> module.exports = function(grunt) { <ide> }, <ide> ngTouch: { <ide> files: { src: 'src/ngTouch/**/*.js' }, <add> }, <add> ngAria: { <add> files: {src: 'src/ngAria/**/*.js'}, <ide> } <ide> }, <ide> <ide> module.exports = function(grunt) { <ide> dest: 'build/angular-cookies.js', <ide> src: util.wrap(files['angularModules']['ngCookies'], 'module') <ide> }, <add> aria: { <add> dest: 'build/angular-aria.js', <add> src: util.wrap(files['angularModules']['ngAria'], 'module') <add> }, <ide> "promises-aplus-adapter": { <ide> dest:'tmp/promises-aplus-adapter++.js', <ide> src:['src/ng/q.js','lib/promises-aplus/promises-aplus-test-adapter.js'] <ide> module.exports = function(grunt) { <ide> touch: 'build/angular-touch.js', <ide> resource: 'build/angular-resource.js', <ide> route: 'build/angular-route.js', <del> sanitize: 'build/angular-sanitize.js' <add> sanitize: 'build/angular-sanitize.js', <add> aria: 'build/angular-aria.js' <ide> }, <ide> <ide> <ide><path>angularFiles.js <ide> var angularFiles = { <ide> 'src/ngTouch/directive/ngClick.js', <ide> 'src/ngTouch/directive/ngSwipe.js' <ide> ], <add> 'ngAria': [ <add> 'src/ngAria/aria.js' <add> ] <ide> }, <ide> <ide> 'angularScenario': [ <ide> var angularFiles = { <ide> 'test/ngRoute/**/*.js', <ide> 'test/ngSanitize/**/*.js', <ide> 'test/ngMock/*.js', <del> 'test/ngTouch/**/*.js' <add> 'test/ngTouch/**/*.js', <add> 'test/ngAria/*.js' <ide> ], <ide> <ide> 'karma': [ <ide> var angularFiles = { <ide> 'test/ngRoute/**/*.js', <ide> 'test/ngResource/*.js', <ide> 'test/ngSanitize/**/*.js', <del> 'test/ngTouch/**/*.js' <add> 'test/ngTouch/**/*.js', <add> 'test/ngAria/*.js' <ide> ], <ide> <ide> 'karmaJquery': [ <ide> angularFiles['angularSrcModules'] = [].concat( <ide> angularFiles['angularModules']['ngRoute'], <ide> angularFiles['angularModules']['ngSanitize'], <ide> angularFiles['angularModules']['ngMock'], <del> angularFiles['angularModules']['ngTouch'] <add> angularFiles['angularModules']['ngTouch'], <add> angularFiles['angularModules']['ngAria'] <ide> ); <ide> <ide> if (exports) { <ide><path>src/ngAria/aria.js <add>'use strict'; <add> <add>/** <add> * @ngdoc module <add> * @name ngAria <add> * @description <add> * <add> * The `ngAria` module provides support for to embed aria tags that convey state or semantic information <add> * about the application in order to allow assistive technologies to convey appropriate information to <add> * persons with disabilities. <add> * <add> * <div doc-module-components="ngAria"></div> <add> * <add> * # Usage <add> * To enable the addition of the aria tags, just require the module into your application and the tags will <add> * hook into your ng-show/ng-hide, input, textarea, button, select and ng-required directives and adds the <add> * appropriate aria-tags. <add> * <add> * Currently, the following aria tags are implemented: <add> * <add> * + aria-hidden <add> * + aria-checked <add> * + aria-disabled <add> * + aria-required <add> * + aria-invalid <add> * + aria-multiline <add> * + aria-valuenow <add> * + aria-valuemin <add> * + aria-valuemax <add> * + tabindex <add> * <add> * You can disable individual aria tags by using the {@link ngAria.$ariaProvider#config config} method. <add> */ <add> <add> /* global -ngAriaModule */ <add>var ngAriaModule = angular.module('ngAria', ['ng']). <add> provider('$aria', $AriaProvider); <add> <add>/** <add> * @ngdoc provider <add> * @name $ariaProvider <add> * <add> * @description <add> * <add> * Used for configuring aria attributes. <add> * <add> * ## Dependencies <add> * Requires the {@link ngAria `ngAria`} module to be installed. <add> */ <add>function $AriaProvider() { <add> var config = { <add> ariaHidden : true, <add> ariaChecked: true, <add> ariaDisabled: true, <add> ariaRequired: true, <add> ariaInvalid: true, <add> ariaMultiline: true, <add> ariaValue: true, <add> tabindex: true <add> }; <add> <add> /** <add> * @ngdoc method <add> * @name $ariaProvider#config <add> * <add> * @param {object} config object to enable/disable specific aria tags <add> * <add> * - **ariaHidden** – `{boolean}` – Enables/disables aria-hidden tags <add> * - **ariaChecked** – `{boolean}` – Enables/disables aria-checked tags <add> * - **ariaDisabled** – `{boolean}` – Enables/disables aria-disabled tags <add> * - **ariaRequired** – `{boolean}` – Enables/disables aria-required tags <add> * - **ariaInvalid** – `{boolean}` – Enables/disables aria-invalid tags <add> * - **ariaMultiline** – `{boolean}` – Enables/disables aria-multiline tags <add> * - **ariaValue** – `{boolean}` – Enables/disables aria-valuemin, aria-valuemax and aria-valuenow tags <add> * - **tabindex** – `{boolean}` – Enables/disables tabindex tags <add> * <add> * @description <add> * Enables/disables various aria tags <add> */ <add> this.config = function(newConfig) { <add> config = angular.extend(config, newConfig); <add> }; <add> <add> function dashCase(input) { <add> return input.replace(/[A-Z]/g, function(letter, pos) { <add> return (pos ? '-' : '') + letter.toLowerCase(); <add> }); <add> } <add> <add> function watchAttr(attrName, ariaName) { <add> var ariaDashName = dashCase(ariaName); <add> return function(scope, elem, attr) { <add> if (!config[ariaName] || elem.attr(ariaDashName)) { <add> return; <add> } <add> var destroyWatcher = attr.$observe(attrName, function(newVal) { <add> elem.attr(ariaDashName, !angular.isUndefined(newVal)); <add> }); <add> scope.$on('$destroy', destroyWatcher); <add> }; <add> } <add> <add> function watchExpr(attrName, ariaName, negate) { <add> var ariaDashName = dashCase(ariaName); <add> return function(scope, elem, attr) { <add> if (config[ariaName] && !attr[ariaName]) { <add> scope.$watch(attr[attrName], function(boolVal) { <add> if (negate) { <add> boolVal = !boolVal; <add> } <add> elem.attr(ariaDashName, boolVal); <add> }); <add> } <add> }; <add> } <add> <add> function watchNgModelProperty (prop, watchFn) { <add> var ariaAttrName = 'aria-' + prop, <add> configName = 'aria' + prop[0].toUpperCase() + prop.substr(1); <add> return function watchNgModelPropertyLinkFn(scope, elem, attr, ngModel) { <add> if (!config[configName] || elem.attr(ariaAttrName) || !ngModel) { <add> return; <add> } <add> scope.$watch(watchFn(ngModel), function(newVal) { <add> elem.attr(ariaAttrName, !!newVal); <add> }); <add> }; <add> } <add> <add> this.$get = function() { <add> return { <add> watchExpr: watchExpr, <add> ariaChecked: watchExpr('ngModel', 'ariaChecked'), <add> ariaDisabled: watchExpr('ngDisabled', 'ariaDisabled'), <add> ariaRequired: watchNgModelProperty('required', function(ngModel) { <add> return function ngAriaModelWatch() { <add> return ngModel.$error.required; <add> }; <add> }), <add> ariaInvalid: watchNgModelProperty('invalid', function(ngModel) { <add> return function ngAriaModelWatch() { <add> return ngModel.$invalid; <add> }; <add> }), <add> ariaValue: function(scope, elem, attr, ngModel) { <add> if (config.ariaValue) { <add> if (attr.min && !elem.attr('aria-valuemin')) { <add> elem.attr('aria-valuemin', attr.min); <add> } <add> if (attr.max && !elem.attr('aria-valuemax')) { <add> elem.attr('aria-valuemax', attr.max); <add> } <add> if (ngModel && !elem.attr('aria-valuenow')) { <add> scope.$watch(function ngAriaModelWatch() { <add> return ngModel.$modelValue; <add> }, function ngAriaValueNowReaction(newVal) { <add> elem.attr('aria-valuenow', newVal); <add> }); <add> } <add> } <add> }, <add> radio: function(scope, elem, attr, ngModel) { <add> if (config.ariaChecked && ngModel && !elem.attr('aria-checked')) { <add> var needsTabIndex = config.tabindex && !elem.attr('tabindex'); <add> scope.$watch(function() { <add> return ngModel.$modelValue; <add> }, function(newVal) { <add> elem.attr('aria-checked', newVal === attr.value); <add> if (needsTabIndex) { <add> elem.attr('tabindex', 0 - (newVal !== attr.value)); <add> } <add> }); <add> } <add> }, <add> multiline: function(scope, elem, attr) { <add> if (config.ariaMultiline && !elem.attr('aria-multiline')) { <add> elem.attr('aria-multiline', true); <add> } <add> }, <add> roleChecked: function(scope, elem, attr) { <add> if (config.ariaChecked && attr.checked && !elem.attr('aria-checked')) { <add> elem.attr('aria-checked', true); <add> } <add> }, <add> tabindex: function(scope, elem, attr) { <add> if (config.tabindex && !elem.attr('tabindex')) { <add> elem.attr('tabindex', 0); <add> } <add> } <add> }; <add> }; <add>} <add> <add>var ngAriaRequired = ['$aria', function($aria) { <add> return { <add> require: '?ngModel', <add> link: $aria.ariaRequired <add> }; <add>}]; <add> <add>var ngAriaTabindex = ['$aria', function($aria) { <add> return $aria.tabindex; <add>}]; <add> <add>ngAriaModule.directive('ngShow', ['$aria', function($aria) { <add> return $aria.watchExpr('ngShow', 'ariaHidden', true); <add>}]) <add>.directive('ngHide', ['$aria', function($aria) { <add> return $aria.watchExpr('ngHide', 'ariaHidden', false); <add>}]) <add>.directive('input', ['$aria', function($aria) { <add> return { <add> restrict: 'E', <add> require: '?ngModel', <add> link: function(scope, elem, attr, ngModel) { <add> if (attr.type === 'checkbox') { <add> $aria.ariaChecked(scope, elem, attr); <add> } else if (attr.type === 'radio') { <add> $aria.radio(scope, elem, attr, ngModel); <add> } else if (attr.type === 'range') { <add> $aria.ariaValue(scope, elem, attr, ngModel); <add> } <add> $aria.ariaInvalid(scope, elem, attr, ngModel); <add> } <add> }; <add>}]) <add>.directive('textarea', ['$aria', function($aria) { <add> return { <add> restrict: 'E', <add> require: '?ngModel', <add> link: function(scope, elem, attr, ngModel) { <add> $aria.ariaInvalid(scope, elem, attr, ngModel); <add> $aria.multiline(scope, elem, attr); <add> } <add> }; <add>}]) <add>.directive('ngRequired', ngAriaRequired) <add>.directive('required', ngAriaRequired) <add>.directive('ngDisabled', ['$aria', function($aria) { <add> return $aria.ariaDisabled; <add>}]) <add>.directive('role', ['$aria', function($aria) { <add> return { <add> restrict: 'A', <add> require: '?ngModel', <add> link: function(scope, elem, attr, ngModel) { <add> if (attr.role === 'textbox') { <add> $aria.multiline(scope, elem, attr); <add> } else if (attr.role === 'progressbar' || attr.role === 'slider') { <add> $aria.ariaValue(scope, elem, attr, ngModel); <add> } else if (attr.role === 'checkbox' || attr.role === 'menuitemcheckbox') { <add> $aria.roleChecked(scope, elem, attr); <add> $aria.tabindex(scope, elem, attr); <add> } else if (attr.role === 'radio' || attr.role === 'menuitemradio') { <add> $aria.radio(scope, elem, attr, ngModel); <add> } else if (attr.role === 'button') { <add> $aria.tabindex(scope, elem, attr); <add> } <add> } <add> }; <add>}]) <add>.directive('ngClick', ngAriaTabindex) <add>.directive('ngDblclick', ngAriaTabindex); <ide><path>test/ngAria/ariaSpec.js <add>'use strict'; <add> <add>describe('$aria', function() { <add> var scope, $compile, element; <add> <add> beforeEach(module('ngAria')); <add> <add> function injectScopeAndCompiler() { <add> return inject(function(_$compile_, _$rootScope_) { <add> $compile = _$compile_; <add> scope = _$rootScope_; <add> }); <add> } <add> <add> function compileInput(inputHtml) { <add> element = $compile(inputHtml)(scope); <add> scope.$digest(); <add> } <add> <add> describe('aria-hidden', function() { <add> beforeEach(injectScopeAndCompiler); <add> <add> it('should attach aria-hidden to ng-show', function() { <add> compileInput('<div ng-show="val"></div>'); <add> scope.$apply('val = false'); <add> expect(element.attr('aria-hidden')).toBe('true'); <add> <add> scope.$apply('val = true'); <add> expect(element.attr('aria-hidden')).toBe('false'); <add> }); <add> <add> it('should attach aria-hidden to ng-hide', function() { <add> compileInput('<div ng-hide="val"></div>'); <add> scope.$apply('val = false'); <add> expect(element.attr('aria-hidden')).toBe('false'); <add> <add> scope.$apply('val = true'); <add> expect(element.attr('aria-hidden')).toBe('true'); <add> }); <add> <add> it('should not change aria-hidden if it is already present on ng-show', function() { <add> compileInput('<div ng-show="val" aria-hidden="userSetValue"></div>'); <add> expect(element.attr('aria-hidden')).toBe('userSetValue'); <add> <add> scope.$apply('val = true'); <add> expect(element.attr('aria-hidden')).toBe('userSetValue'); <add> }); <add> <add> it('should not change aria-hidden if it is already present on ng-hide', function() { <add> compileInput('<div ng-hide="val" aria-hidden="userSetValue"></div>'); <add> expect(element.attr('aria-hidden')).toBe('userSetValue'); <add> <add> scope.$apply('val = true'); <add> expect(element.attr('aria-hidden')).toBe('userSetValue'); <add> }); <add> }); <add> <add> <add> describe('aria-hidden when disabled', function() { <add> beforeEach(configAriaProvider({ <add> ariaHidden: false <add> })); <add> beforeEach(injectScopeAndCompiler); <add> <add> it('should not attach aria-hidden', function() { <add> scope.$apply('val = false'); <add> compileInput('<div ng-show="val"></div>'); <add> expect(element.attr('aria-hidden')).toBeUndefined(); <add> <add> compileInput('<div ng-hide="val"></div>'); <add> expect(element.attr('aria-hidden')).toBeUndefined(); <add> }); <add> }); <add> <add> describe('aria-checked', function() { <add> beforeEach(injectScopeAndCompiler); <add> <add> it('should attach itself to input type="checkbox"', function() { <add> compileInput('<input type="checkbox" ng-model="val">'); <add> <add> scope.$apply('val = true'); <add> expect(element.attr('aria-checked')).toBe('true'); <add> <add> scope.$apply('val = false'); <add> expect(element.attr('aria-checked')).toBe('false'); <add> }); <add> <add> it('should attach itself to input type="radio"', function() { <add> var element = $compile('<input type="radio" ng-model="val" value="one">' + <add> '<input type="radio" ng-model="val" value="two">')(scope); <add> <add> scope.$apply("val='one'"); <add> expect(element.eq(0).attr('aria-checked')).toBe('true'); <add> expect(element.eq(1).attr('aria-checked')).toBe('false'); <add> <add> scope.$apply("val='two'"); <add> expect(element.eq(0).attr('aria-checked')).toBe('false'); <add> expect(element.eq(1).attr('aria-checked')).toBe('true'); <add> }); <add> <add> it('should attach itself to role="radio"', function() { <add> scope.$apply("val = 'one'"); <add> compileInput('<div role="radio" ng-model="val" value="{{val}}"></div>'); <add> expect(element.attr('aria-checked')).toBe('true'); <add> }); <add> <add> it('should attach itself to role="checkbox"', function() { <add> compileInput('<div role="checkbox" checked="checked"></div>'); <add> expect(element.attr('aria-checked')).toBe('true'); <add> }); <add> <add> it('should attach itself to role="menuitemradio"', function() { <add> scope.$apply("val = 'one'"); <add> compileInput('<div role="menuitemradio" ng-model="val" value="{{val}}"></div>'); <add> expect(element.attr('aria-checked')).toBe('true'); <add> }); <add> <add> it('should attach itself to role="menuitemcheckbox"', function() { <add> compileInput('<div role="menuitemcheckbox" checked="checked"></div>'); <add> expect(element.attr('aria-checked')).toBe('true'); <add> }); <add> <add> it('should not attach itself if an aria-checked value is already present', function() { <add> var element = [ <add> $compile("<input type='checkbox' ng-model='val1' aria-checked='userSetValue'>")(scope), <add> $compile("<input type='radio' ng-model='val2' value='one' aria-checked='userSetValue'><input type='radio' ng-model='val2' value='two'>")(scope), <add> $compile("<div role='radio' ng-model='val' value='{{val3}}' aria-checked='userSetValue'></div>")(scope), <add> $compile("<div role='menuitemradio' ng-model='val' value='{{val3}}' aria-checked='userSetValue'></div>")(scope), <add> $compile("<div role='checkbox' checked='checked' aria-checked='userSetValue'></div>")(scope), <add> $compile("<div role='menuitemcheckbox' checked='checked' aria-checked='userSetValue'></div>")(scope) <add> ]; <add> scope.$apply("val1=true;val2='one';val3='1'"); <add> expectAriaAttrOnEachElement(element, 'aria-checked', 'userSetValue'); <add> }); <add> }); <add> <add> describe('aria-checked when disabled', function() { <add> beforeEach(configAriaProvider({ <add> ariaChecked: false <add> })); <add> beforeEach(injectScopeAndCompiler); <add> <add> it('should not attach aria-checked', function() { <add> compileInput("<div role='radio' ng-model='val' value='{{val}}'></div>"); <add> expect(element.attr('aria-checked')).toBeUndefined(); <add> <add> compileInput("<div role='menuitemradio' ng-model='val' value='{{val}}'></div>"); <add> expect(element.attr('aria-checked')).toBeUndefined(); <add> <add> compileInput("<div role='checkbox' checked='checked'></div>"); <add> expect(element.attr('aria-checked')).toBeUndefined(); <add> <add> compileInput("<div role='menuitemcheckbox' checked='checked'></div>"); <add> expect(element.attr('aria-checked')).toBeUndefined(); <add> }); <add> }); <add> <add> describe('aria-disabled', function() { <add> beforeEach(injectScopeAndCompiler); <add> <add> it('should attach itself to input elements', function() { <add> scope.$apply('val = false'); <add> compileInput("<input ng-disabled='val'>"); <add> expect(element.attr('aria-disabled')).toBe('false'); <add> <add> scope.$apply('val = true'); <add> expect(element.attr('aria-disabled')).toBe('true'); <add> }); <add> <add> it('should attach itself to textarea elements', function() { <add> scope.$apply('val = false'); <add> compileInput('<textarea ng-disabled="val"></textarea>'); <add> expect(element.attr('aria-disabled')).toBe('false'); <add> <add> scope.$apply('val = true'); <add> expect(element.attr('aria-disabled')).toBe('true'); <add> }); <add> <add> it('should attach itself to button elements', function() { <add> scope.$apply('val = false'); <add> compileInput('<button ng-disabled="val"></button>'); <add> expect(element.attr('aria-disabled')).toBe('false'); <add> <add> scope.$apply('val = true'); <add> expect(element.attr('aria-disabled')).toBe('true'); <add> }); <add> <add> it('should attach itself to select elements', function() { <add> scope.$apply('val = false'); <add> compileInput('<select ng-disabled="val"></select>'); <add> expect(element.attr('aria-disabled')).toBe('false'); <add> <add> scope.$apply('val = true'); <add> expect(element.attr('aria-disabled')).toBe('true'); <add> }); <add> <add> it('should not attach itself if an aria-disabled attribute is already present', function() { <add> var element = [ <add> $compile("<input aria-disabled='userSetValue' ng-disabled='val'>")(scope), <add> $compile("<textarea aria-disabled='userSetValue' ng-disabled='val'></textarea>")(scope), <add> $compile("<button aria-disabled='userSetValue' ng-disabled='val'></button>")(scope), <add> $compile("<select aria-disabled='userSetValue' ng-disabled='val'></select>")(scope) <add> ]; <add> <add> scope.$apply('val = true'); <add> expectAriaAttrOnEachElement(element, 'aria-disabled', 'userSetValue'); <add> }); <add> }); <add> <add> describe('aria-disabled when disabled', function() { <add> beforeEach(configAriaProvider({ <add> ariaDisabled: false <add> })); <add> beforeEach(injectScopeAndCompiler); <add> <add> it('should not attach aria-disabled', function() { <add> var element = [ <add> $compile("<input ng-disabled='val'>")(scope), <add> $compile("<textarea ng-disabled='val'></textarea>")(scope), <add> $compile("<button ng-disabled='val'></button>")(scope), <add> $compile("<select ng-disabled='val'></select>")(scope) <add> ]; <add> <add> scope.$apply('val = false'); <add> expectAriaAttrOnEachElement(element, 'aria-disabled', undefined); <add> }); <add> }); <add> <add> describe('aria-invalid', function() { <add> beforeEach(injectScopeAndCompiler); <add> <add> it('should attach aria-invalid to input', function() { <add> compileInput('<input ng-model="txtInput" ng-minlength="10">'); <add> scope.$apply("txtInput='LTten'"); <add> expect(element.attr('aria-invalid')).toBe('true'); <add> <add> scope.$apply("txtInput='morethantencharacters'"); <add> expect(element.attr('aria-invalid')).toBe('false'); <add> }); <add> <add> it('should not attach itself if aria-invalid is already present', function() { <add> compileInput('<input ng-model="txtInput" ng-minlength="10" aria-invalid="userSetValue">'); <add> scope.$apply("txtInput='LTten'"); <add> expect(element.attr('aria-invalid')).toBe('userSetValue'); <add> }); <add> }); <add> <add> describe('aria-invalid when disabled', function() { <add> beforeEach(configAriaProvider({ <add> ariaInvalid: false <add> })); <add> beforeEach(injectScopeAndCompiler); <add> <add> it('should not attach aria-invalid if the option is disabled', function() { <add> scope.$apply("txtInput='LTten'"); <add> compileInput('<input ng-model="txtInput" ng-minlength="10">'); <add> expect(element.attr('aria-invalid')).toBeUndefined(); <add> }); <add> }); <add> <add> describe('aria-required', function() { <add> beforeEach(injectScopeAndCompiler); <add> <add> it('should attach aria-required to input', function() { <add> compileInput('<input ng-model="val" required>'); <add> expect(element.attr('aria-required')).toBe('true'); <add> <add> scope.$apply("val='input is valid now'"); <add> expect(element.attr('aria-required')).toBe('false'); <add> }); <add> <add> it('should attach aria-required to textarea', function() { <add> compileInput('<textarea ng-model="val" required></textarea>'); <add> expect(element.attr('aria-required')).toBe('true'); <add> <add> scope.$apply("val='input is valid now'"); <add> expect(element.attr('aria-required')).toBe('false'); <add> }); <add> <add> it('should attach aria-required to select', function() { <add> compileInput('<select ng-model="val" required></select>'); <add> expect(element.attr('aria-required')).toBe('true'); <add> <add> scope.$apply("val='input is valid now'"); <add> expect(element.attr('aria-required')).toBe('false'); <add> }); <add> <add> it('should attach aria-required to ngRequired', function() { <add> compileInput('<input ng-model="val" ng-required="true">'); <add> expect(element.attr('aria-required')).toBe('true'); <add> <add> scope.$apply("val='input is valid now'"); <add> expect(element.attr('aria-required')).toBe('false'); <add> }); <add> <add> it('should not attach itself if aria-required is already present', function() { <add> compileInput("<input ng-model='val' required aria-required='userSetValue'>"); <add> expect(element.attr('aria-required')).toBe('userSetValue'); <add> <add> compileInput("<textarea ng-model='val' required aria-required='userSetValue'></textarea>"); <add> expect(element.attr('aria-required')).toBe('userSetValue'); <add> <add> compileInput("<select ng-model='val' required aria-required='userSetValue'></select>"); <add> expect(element.attr('aria-required')).toBe('userSetValue'); <add> <add> compileInput("<input ng-model='val' ng-required='true' aria-required='userSetValue'>"); <add> expect(element.attr('aria-required')).toBe('userSetValue'); <add> }); <add> }); <add> <add> describe('aria-required when disabled', function() { <add> beforeEach(configAriaProvider({ <add> ariaRequired: false <add> })); <add> beforeEach(injectScopeAndCompiler); <add> <add> it('should not add the aria-required attribute', function() { <add> compileInput("<input ng-model='val' required>"); <add> expect(element.attr('aria-required')).toBeUndefined(); <add> <add> compileInput("<textarea ng-model='val' required></textarea>"); <add> expect(element.attr('aria-required')).toBeUndefined(); <add> <add> compileInput("<select ng-model='val' required></select>"); <add> expect(element.attr('aria-required')).toBeUndefined(); <add> }); <add> }); <add> <add> describe('aria-multiline', function() { <add> beforeEach(injectScopeAndCompiler); <add> <add> it('should attach itself to textarea', function() { <add> compileInput('<textarea></textarea>'); <add> expect(element.attr('aria-multiline')).toBe('true'); <add> }); <add> <add> it('should attach itself role="textbox"', function() { <add> compileInput('<div role="textbox"></div>'); <add> expect(element.attr('aria-multiline')).toBe('true'); <add> }); <add> <add> it('should not attach itself if aria-multiline is already present', function() { <add> compileInput('<textarea aria-multiline="userSetValue"></textarea>'); <add> expect(element.attr('aria-multiline')).toBe('userSetValue'); <add> <add> compileInput('<div role="textbox" aria-multiline="userSetValue"></div>'); <add> expect(element.attr('aria-multiline')).toBe('userSetValue'); <add> }); <add> }); <add> <add> describe('aria-multiline when disabled', function() { <add> beforeEach(configAriaProvider({ <add> ariaMultiline: false <add> })); <add> beforeEach(injectScopeAndCompiler); <add> <add> it('should not attach itself to textarea', function() { <add> compileInput('<textarea></textarea>'); <add> expect(element.attr('aria-multiline')).toBeUndefined(); <add> }); <add> <add> it('should not attach itself role="textbox"', function() { <add> compileInput('<div role="textbox"></div>'); <add> expect(element.attr('aria-multiline')).toBeUndefined(); <add> }); <add> }); <add> <add> describe('aria-value', function() { <add> beforeEach(injectScopeAndCompiler); <add> <add> it('should attach to input type="range"', function() { <add> var element = [ <add> $compile('<input type="range" ng-model="val" min="0" max="100">')(scope), <add> $compile('<div role="progressbar" min="0" max="100" ng-model="val">')(scope), <add> $compile('<div role="slider" min="0" max="100" ng-model="val">')(scope) <add> ]; <add> <add> scope.$apply('val = 50'); <add> expectAriaAttrOnEachElement(element, 'aria-valuenow', "50"); <add> expectAriaAttrOnEachElement(element, 'aria-valuemin', "0"); <add> expectAriaAttrOnEachElement(element, 'aria-valuemax', "100"); <add> <add> scope.$apply('val = 90'); <add> expectAriaAttrOnEachElement(element, 'aria-valuenow', "90"); <add> }); <add> <add> it('should not attach if aria-value* is already present', function() { <add> var element = [ <add> $compile('<input type="range" ng-model="val" min="0" max="100" aria-valuenow="userSetValue1" aria-valuemin="userSetValue2" aria-valuemax="userSetValue3">')(scope), <add> $compile('<div role="progressbar" min="0" max="100" ng-model="val" aria-valuenow="userSetValue1" aria-valuemin="userSetValue2" aria-valuemax="userSetValue3">')(scope), <add> $compile('<div role="slider" min="0" max="100" ng-model="val" aria-valuenow="userSetValue1" aria-valuemin="userSetValue2" aria-valuemax="userSetValue3">')(scope) <add> ]; <add> <add> scope.$apply('val = 50'); <add> expectAriaAttrOnEachElement(element, 'aria-valuenow', 'userSetValue1'); <add> expectAriaAttrOnEachElement(element, 'aria-valuemin', 'userSetValue2'); <add> expectAriaAttrOnEachElement(element, 'aria-valuemax', 'userSetValue3'); <add> }); <add> }); <add> <add> <add> describe('aria-value when disabled', function() { <add> beforeEach(configAriaProvider({ <add> ariaValue: false <add> })); <add> beforeEach(injectScopeAndCompiler); <add> <add> it('should not attach itself', function() { <add> scope.$apply('val = 50'); <add> <add> compileInput('<input type="range" ng-model="val" min="0" max="100">'); <add> expect(element.attr('aria-valuenow')).toBeUndefined(); <add> expect(element.attr('aria-valuemin')).toBeUndefined(); <add> expect(element.attr('aria-valuemax')).toBeUndefined(); <add> <add> compileInput('<div role="progressbar" min="0" max="100" ng-model="val">'); <add> expect(element.attr('aria-valuenow')).toBeUndefined(); <add> expect(element.attr('aria-valuemin')).toBeUndefined(); <add> expect(element.attr('aria-valuemax')).toBeUndefined(); <add> }); <add> }); <add> <add> describe('tabindex', function() { <add> beforeEach(injectScopeAndCompiler); <add> <add> it('should attach tabindex to role=button, role=checkbox, ng-click and ng-dblclick', function() { <add> compileInput('<div role="button"></div>'); <add> expect(element.attr('tabindex')).toBe('0'); <add> <add> compileInput('<div role="checkbox"></div>'); <add> expect(element.attr('tabindex')).toBe('0'); <add> <add> compileInput('<div ng-click="someAction()"></div>'); <add> expect(element.attr('tabindex')).toBe('0'); <add> <add> compileInput('<div ng-dblclick="someAction()"></div>'); <add> expect(element.attr('tabindex')).toBe('0'); <add> }); <add> <add> it('should not attach tabindex if it is already on an element', function() { <add> compileInput('<div role="button" tabindex="userSetValue"></div>'); <add> expect(element.attr('tabindex')).toBe('userSetValue'); <add> <add> compileInput('<div role="checkbox" tabindex="userSetValue"></div>'); <add> expect(element.attr('tabindex')).toBe('userSetValue'); <add> <add> compileInput('<div ng-click="someAction()" tabindex="userSetValue"></div>'); <add> expect(element.attr('tabindex')).toBe('userSetValue'); <add> <add> compileInput('<div ng-dblclick="someAction()" tabindex="userSetValue"></div>'); <add> expect(element.attr('tabindex')).toBe('userSetValue'); <add> }); <add> <add> it('should set proper tabindex values for radiogroup', function() { <add> compileInput('<div role="radiogroup">' + <add> '<div role="radio" ng-model="val" value="one">1</div>' + <add> '<div role="radio" ng-model="val" value="two">2</div>' + <add> '</div>'); <add> <add> var one = element.contents().eq(0); <add> var two = element.contents().eq(1); <add> <add> scope.$apply("val = 'one'"); <add> expect(one.attr('tabindex')).toBe('0'); <add> expect(two.attr('tabindex')).toBe('-1'); <add> <add> scope.$apply("val = 'two'"); <add> expect(one.attr('tabindex')).toBe('-1'); <add> expect(two.attr('tabindex')).toBe('0'); <add> <add> dealoc(element); <add> }); <add> }); <add> <add> describe('tabindex when disabled', function() { <add> beforeEach(configAriaProvider({ <add> tabindex: false <add> })); <add> beforeEach(injectScopeAndCompiler); <add> <add> it('should not add a tabindex attribute', function() { <add> compileInput('<div role="button"></div>'); <add> expect(element.attr('tabindex')).toBeUndefined(); <add> <add> compileInput('<div role="checkbox"></div>'); <add> expect(element.attr('tabindex')).toBeUndefined(); <add> <add> compileInput('<div ng-click="someAction()"></div>'); <add> expect(element.attr('tabindex')).toBeUndefined(); <add> <add> compileInput('<div ng-dblclick="someAction()"></div>'); <add> expect(element.attr('tabindex')).toBeUndefined(); <add> }); <add> }); <add>}); <add> <add>function expectAriaAttrOnEachElement(elem, ariaAttr, expected) { <add> angular.forEach(elem, function(val) { <add> expect(angular.element(val).attr(ariaAttr)).toBe(expected); <add> }); <add>} <add> <add>function configAriaProvider (config) { <add> return function() { <add> angular.module('ariaTest', ['ngAria']).config(function($ariaProvider) { <add> $ariaProvider.config(config); <add> }); <add> module('ariaTest'); <add> }; <add>}
4
PHP
PHP
fix failing tests
6e9d8c283472aeaac7da5940eeda83d8dbe46027
<ide><path>lib/Cake/Network/Request.php <ide> protected static function _base() { <ide> protected function _processFiles($post, $files) { <ide> if (isset($files) && is_array($files)) { <ide> foreach ($files as $key => $data) { <del> $this->_processFileData($post, '', $data, $key); <add> if (!is_numeric($key)) { <add> $this->_processFileData($post, '', $data, $key); <add> } else { <add> $post[$key] = $data; <add> } <ide> } <ide> } <ide> return $post; <ide><path>lib/Cake/Network/Socket.php <ide> public function connect() { <ide> <ide> if (!$this->connection && $this->_connectionErrors) { <ide> $message = implode("\n", $this->_connectionErrors); <del> throw new SocketException($message, E_WARNING); <add> throw new Error\SocketException($message, E_WARNING); <ide> } <ide> <ide> $this->connected = is_resource($this->connection); <ide><path>lib/Cake/Test/TestCase/Network/Email/EmailTest.php <ide> public function testSendWithNoContentDispositionAttachments() { <ide> */ <ide> public function testSendWithLog() { <ide> $path = CAKE . 'Test/TestApp/tmp/'; <del> $log = $this->getMock('Cake\Log\Engine\BaseLog', ['write'], ['scopes' => 'email']); <add> $log = $this->getMock('Cake\Log\Engine\BaseLog', ['write'], [['scopes' => 'email']]); <ide> <ide> $message = 'Logging This'; <ide> <ide><path>lib/Cake/Test/TestCase/Network/RequestTest.php <ide> public function testPutParsingJSON() { <ide> $_SERVER['REQUEST_METHOD'] = 'PUT'; <ide> $_SERVER['CONTENT_TYPE'] = 'application/json'; <ide> <del> $data = '{Article":["title"]}'; <add> $data = '{"Article":["title"]}'; <ide> $request = new Request([ <ide> 'input' => $data <ide> ]); <ide> public function testFilesParsing() { <ide> <ide> /** <ide> * Test that files in the 0th index work. <add> * <add> * @return void <ide> */ <ide> public function testFilesZeroithIndex() { <del> $_FILES = array( <add> $files = array( <ide> 0 => array( <ide> 'name' => 'cake_sqlserver_patch.patch', <ide> 'type' => 'text/plain', <ide> public function testFilesZeroithIndex() { <ide> ), <ide> ); <ide> <del> $request = new Request('some/path'); <del> $this->assertEquals($_FILES, $request->params['form']); <add> $request = new Request([ <add> 'files' => $files <add> ]); <add> $this->assertEquals($files, $request->data); <ide> } <ide> <ide> /** <ide> public function testEnvironmentDetection($name, $env, $expected) { <ide> * @return void <ide> */ <ide> public function testQuery() { <del> $_GET = array(); <del> $_GET['foo'] = 'bar'; <del> <del> $request = new Request(); <add> $request = new Request([ <add> 'query' => ['foo' => 'bar'] <add> ]); <ide> <ide> $result = $request->query('foo'); <ide> $this->assertEquals('bar', $result); <ide> public function testQuery() { <ide> * @return void <ide> */ <ide> public function testQueryWithArray() { <del> $_GET = array(); <del> $_GET['test'] = array('foo', 'bar'); <add> $get['test'] = array('foo', 'bar'); <ide> <del> $request = new Request(); <add> $request = new Request([ <add> 'query' => $get <add> ]); <ide> <ide> $result = $request->query('test'); <ide> $this->assertEquals(array('foo', 'bar'), $result); <ide><path>lib/Cake/Test/TestCase/Network/SocketTest.php <ide> protected function _connectSocketToSslTls() { <ide> /** <ide> * testEnableCryptoBadMode <ide> * <del> * @expectedException InvalidArgumentException <add> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testEnableCryptoBadMode() { <ide> public function testGetContext() { <ide> 'ssl' => array('capture_peer' => true) <ide> ) <ide> ); <del> $this->Socket = new CakeSocket($config); <add> $this->Socket = new Socket($config); <ide> $this->Socket->connect(); <ide> $result = $this->Socket->context(); <ide> $this->assertEquals($config['context'], $result);
5
PHP
PHP
fix docblock on orm/table.php
c36e102c30604c82024cbd337a5003415af0127d
<ide><path>src/ORM/Table.php <ide> protected function _update($entity, $data) <ide> * any one of the records fails to save due to failed validation or database <ide> * error. <ide> * <del> * @param \Cake\Datasource\EntityInterface[]|\Cake\ORM\ResultSet $entities Entities to save. <add> * @param \Cake\Datasource\EntityInterface[]|\Cake\Datasource\ResultSetInterface $entities Entities to save. <ide> * @param array|\ArrayAccess $options Options used when calling Table::save() for each entity. <del> * @return bool|\Cake\Datasource\EntityInterface[]|\Cake\ORM\ResultSet False on failure, entities list on success. <add> * @return bool|\Cake\Datasource\EntityInterface[]|\Cake\Datasource\ResultSetInterface False on failure, entities list on success. <ide> */ <ide> public function saveMany($entities, $options = []) <ide> {
1
PHP
PHP
update latest cdn
6ab4004af9a6dce1f59278bf1134bfd7dd035907
<ide><path>resources/views/app.blade.php <ide> @yield('content') <ide> <ide> <!-- Scripts --> <del> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <del> <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script> <add> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <add> <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js"></script> <ide> </body> <ide> </html>
1
Go
Go
add helpers to create errdef errors
87a12421a94faac294079bebc97c8abb4180dde5
<ide><path>api/errdefs/defs.go <ide> type ErrNotModified interface { <ide> NotModified() <ide> } <ide> <add>// ErrAlreadyExists is a special case of ErrConflict which signals that the desired object already exists <add>type ErrAlreadyExists interface { <add> AlreadyExists() <add>} <add> <ide> // ErrNotImplemented signals that the requested action/feature is not implemented on the system as configured. <ide> type ErrNotImplemented interface { <ide> NotImplemented() <ide> type ErrNotImplemented interface { <ide> type ErrUnknown interface { <ide> Unknown() <ide> } <add> <add>// ErrCancelled signals that the action was cancelled. <add>type ErrCancelled interface { <add> Cancelled() <add>} <add> <add>// ErrDeadline signals that the deadline was reached before the action completed. <add>type ErrDeadline interface { <add> DeadlineExceeded() <add>} <add> <add>// ErrDataLoss indicates that data was lost or there is data corruption. <add>type ErrDataLoss interface { <add> DataLoss() <add>} <ide><path>api/errdefs/helpers.go <add>package errdefs <add> <add>import "context" <add> <add>type errNotFound struct{ error } <add> <add>func (errNotFound) NotFound() {} <add> <add>func (e errNotFound) Cause() error { <add> return e.error <add>} <add> <add>// NotFound is a helper to create an error of the class with the same name from any error type <add>func NotFound(err error) error { <add> if err == nil { <add> return nil <add> } <add> return errNotFound{err} <add>} <add> <add>type errInvalidParameter struct{ error } <add> <add>func (errInvalidParameter) InvalidParameter() {} <add> <add>func (e errInvalidParameter) Cause() error { <add> return e.error <add>} <add> <add>// InvalidParameter is a helper to create an error of the class with the same name from any error type <add>func InvalidParameter(err error) error { <add> if err == nil { <add> return nil <add> } <add> return errInvalidParameter{err} <add>} <add> <add>type errConflict struct{ error } <add> <add>func (errConflict) Conflict() {} <add> <add>func (e errConflict) Cause() error { <add> return e.error <add>} <add> <add>// Conflict is a helper to create an error of the class with the same name from any error type <add>func Conflict(err error) error { <add> if err == nil { <add> return nil <add> } <add> return errConflict{err} <add>} <add> <add>type errUnauthorized struct{ error } <add> <add>func (errUnauthorized) Unauthorized() {} <add> <add>func (e errUnauthorized) Cause() error { <add> return e.error <add>} <add> <add>// Unauthorized is a helper to create an error of the class with the same name from any error type <add>func Unauthorized(err error) error { <add> if err == nil { <add> return nil <add> } <add> return errUnauthorized{err} <add>} <add> <add>type errUnavailable struct{ error } <add> <add>func (errUnavailable) Unavailable() {} <add> <add>func (e errUnavailable) Cause() error { <add> return e.error <add>} <add> <add>// Unavailable is a helper to create an error of the class with the same name from any error type <add>func Unavailable(err error) error { <add> return errUnavailable{err} <add>} <add> <add>type errForbidden struct{ error } <add> <add>func (errForbidden) Forbidden() {} <add> <add>func (e errForbidden) Cause() error { <add> return e.error <add>} <add> <add>// Forbidden is a helper to create an error of the class with the same name from any error type <add>func Forbidden(err error) error { <add> if err == nil { <add> return nil <add> } <add> return errForbidden{err} <add>} <add> <add>type errSystem struct{ error } <add> <add>func (errSystem) System() {} <add> <add>func (e errSystem) Cause() error { <add> return e.error <add>} <add> <add>// System is a helper to create an error of the class with the same name from any error type <add>func System(err error) error { <add> if err == nil { <add> return nil <add> } <add> return errSystem{err} <add>} <add> <add>type errNotModified struct{ error } <add> <add>func (errNotModified) NotModified() {} <add> <add>func (e errNotModified) Cause() error { <add> return e.error <add>} <add> <add>// NotModified is a helper to create an error of the class with the same name from any error type <add>func NotModified(err error) error { <add> if err == nil { <add> return nil <add> } <add> return errNotModified{err} <add>} <add> <add>type errAlreadyExists struct{ error } <add> <add>func (errAlreadyExists) AlreadyExists() {} <add> <add>func (e errAlreadyExists) Cause() error { <add> return e.error <add>} <add> <add>// AlreadyExists is a helper to create an error of the class with the same name from any error type <add>func AlreadyExists(err error) error { <add> if err == nil { <add> return nil <add> } <add> return errAlreadyExists{err} <add>} <add> <add>type errNotImplemented struct{ error } <add> <add>func (errNotImplemented) NotImplemented() {} <add> <add>func (e errNotImplemented) Cause() error { <add> return e.error <add>} <add> <add>// NotImplemented is a helper to create an error of the class with the same name from any error type <add>func NotImplemented(err error) error { <add> if err == nil { <add> return nil <add> } <add> return errNotImplemented{err} <add>} <add> <add>type errUnknown struct{ error } <add> <add>func (errUnknown) Unknown() {} <add> <add>func (e errUnknown) Cause() error { <add> return e.error <add>} <add> <add>// Unknown is a helper to create an error of the class with the same name from any error type <add>func Unknown(err error) error { <add> if err == nil { <add> return nil <add> } <add> return errUnknown{err} <add>} <add> <add>type errCancelled struct{ error } <add> <add>func (errCancelled) Cancelled() {} <add> <add>func (e errCancelled) Cause() error { <add> return e.error <add>} <add> <add>// Cancelled is a helper to create an error of the class with the same name from any error type <add>func Cancelled(err error) error { <add> if err == nil { <add> return nil <add> } <add> return errCancelled{err} <add>} <add> <add>type errDeadline struct{ error } <add> <add>func (errDeadline) DeadlineExceeded() {} <add> <add>func (e errDeadline) Cause() error { <add> return e.error <add>} <add> <add>// Deadline is a helper to create an error of the class with the same name from any error type <add>func Deadline(err error) error { <add> if err == nil { <add> return nil <add> } <add> return errDeadline{err} <add>} <add> <add>type errDataLoss struct{ error } <add> <add>func (errDataLoss) DataLoss() {} <add> <add>func (e errDataLoss) Cause() error { <add> return e.error <add>} <add> <add>// DataLoss is a helper to create an error of the class with the same name from any error type <add>func DataLoss(err error) error { <add> if err == nil { <add> return nil <add> } <add> return errDataLoss{err} <add>} <add> <add>// FromContext returns the error class from the passed in context <add>func FromContext(ctx context.Context) error { <add> e := ctx.Err() <add> if e == nil { <add> return nil <add> } <add> <add> if e == context.Canceled { <add> return Cancelled(e) <add> } <add> if e == context.DeadlineExceeded { <add> return Deadline(e) <add> } <add> return Unknown(e) <add>} <ide><path>api/errdefs/helpers_test.go <add>package errdefs <add> <add>import ( <add> "errors" <add> "testing" <add>) <add> <add>var errTest = errors.New("this is a test") <add> <add>type causal interface { <add> Cause() error <add>} <add> <add>func TestNotFound(t *testing.T) { <add> e := NotFound(errTest) <add> if !IsNotFound(e) { <add> t.Fatalf("expected not found error, got: %T", e) <add> } <add> if cause := e.(causal).Cause(); cause != errTest { <add> t.Fatalf("causual should be errTest, got: %v", cause) <add> } <add>} <add> <add>func TestConflict(t *testing.T) { <add> e := Conflict(errTest) <add> if !IsConflict(e) { <add> t.Fatalf("expected conflcit error, got: %T", e) <add> } <add> if cause := e.(causal).Cause(); cause != errTest { <add> t.Fatalf("causual should be errTest, got: %v", cause) <add> } <add>} <add> <add>func TestForbidden(t *testing.T) { <add> e := Forbidden(errTest) <add> if !IsForbidden(e) { <add> t.Fatalf("expected forbidden error, got: %T", e) <add> } <add> if cause := e.(causal).Cause(); cause != errTest { <add> t.Fatalf("causual should be errTest, got: %v", cause) <add> } <add>} <add> <add>func TestInvalidParameter(t *testing.T) { <add> e := InvalidParameter(errTest) <add> if !IsInvalidParameter(e) { <add> t.Fatalf("expected invalid argument error, got %T", e) <add> } <add> if cause := e.(causal).Cause(); cause != errTest { <add> t.Fatalf("causual should be errTest, got: %v", cause) <add> } <add>} <add> <add>func TestNotImplemented(t *testing.T) { <add> e := NotImplemented(errTest) <add> if !IsNotImplemented(e) { <add> t.Fatalf("expected not implemented error, got %T", e) <add> } <add> if cause := e.(causal).Cause(); cause != errTest { <add> t.Fatalf("causual should be errTest, got: %v", cause) <add> } <add>} <add> <add>func TestNotModified(t *testing.T) { <add> e := NotModified(errTest) <add> if !IsNotModified(e) { <add> t.Fatalf("expected not modified error, got %T", e) <add> } <add> if cause := e.(causal).Cause(); cause != errTest { <add> t.Fatalf("causual should be errTest, got: %v", cause) <add> } <add>} <add> <add>func TestAlreadyExists(t *testing.T) { <add> e := AlreadyExists(errTest) <add> if !IsAlreadyExists(e) { <add> t.Fatalf("expected already exists error, got %T", e) <add> } <add> if cause := e.(causal).Cause(); cause != errTest { <add> t.Fatalf("causual should be errTest, got: %v", cause) <add> } <add>} <add> <add>func TestUnauthorized(t *testing.T) { <add> e := Unauthorized(errTest) <add> if !IsUnauthorized(e) { <add> t.Fatalf("expected unauthorized error, got %T", e) <add> } <add> if cause := e.(causal).Cause(); cause != errTest { <add> t.Fatalf("causual should be errTest, got: %v", cause) <add> } <add>} <add> <add>func TestUnknown(t *testing.T) { <add> e := Unknown(errTest) <add> if !IsUnknown(e) { <add> t.Fatalf("expected unknown error, got %T", e) <add> } <add> if cause := e.(causal).Cause(); cause != errTest { <add> t.Fatalf("causual should be errTest, got: %v", cause) <add> } <add>} <add> <add>func TestCancelled(t *testing.T) { <add> e := Cancelled(errTest) <add> if !IsCancelled(e) { <add> t.Fatalf("expected canclled error, got %T", e) <add> } <add> if cause := e.(causal).Cause(); cause != errTest { <add> t.Fatalf("causual should be errTest, got: %v", cause) <add> } <add>} <add> <add>func TestDeadline(t *testing.T) { <add> e := Deadline(errTest) <add> if !IsDeadline(e) { <add> t.Fatalf("expected deadline error, got %T", e) <add> } <add> if cause := e.(causal).Cause(); cause != errTest { <add> t.Fatalf("causual should be errTest, got: %v", cause) <add> } <add>} <add> <add>func TestIsDataLoss(t *testing.T) { <add> e := DataLoss(errTest) <add> if !IsDataLoss(e) { <add> t.Fatalf("expected data loss error, got %T", e) <add> } <add> if cause := e.(causal).Cause(); cause != errTest { <add> t.Fatalf("causual should be errTest, got: %v", cause) <add> } <add>} <ide><path>api/errdefs/is.go <ide> func getImplementer(err error) error { <ide> ErrForbidden, <ide> ErrSystem, <ide> ErrNotModified, <add> ErrAlreadyExists, <ide> ErrNotImplemented, <add> ErrCancelled, <add> ErrDeadline, <add> ErrDataLoss, <ide> ErrUnknown: <ide> return e <ide> case causer: <ide> func IsNotModified(err error) bool { <ide> return ok <ide> } <ide> <add>// IsAlreadyExists returns if the passed in error is a AlreadyExists error <add>func IsAlreadyExists(err error) bool { <add> _, ok := getImplementer(err).(ErrAlreadyExists) <add> return ok <add>} <add> <ide> // IsNotImplemented returns if the passed in error is an ErrNotImplemented <ide> func IsNotImplemented(err error) bool { <ide> _, ok := getImplementer(err).(ErrNotImplemented) <ide> func IsUnknown(err error) bool { <ide> _, ok := getImplementer(err).(ErrUnknown) <ide> return ok <ide> } <add> <add>// IsCancelled returns if the passed in error is an ErrCancelled <add>func IsCancelled(err error) bool { <add> _, ok := getImplementer(err).(ErrCancelled) <add> return ok <add>} <add> <add>// IsDeadline returns if the passed in error is an ErrDeadline <add>func IsDeadline(err error) bool { <add> _, ok := getImplementer(err).(ErrDeadline) <add> return ok <add>} <add> <add>// IsDataLoss returns if the passed in error is an ErrDataLoss <add>func IsDataLoss(err error) bool { <add> _, ok := getImplementer(err).(ErrDataLoss) <add> return ok <add>} <ide><path>api/server/httputils/errors.go <ide> func GetHTTPErrorStatusCode(err error) int { <ide> statusCode = http.StatusNotFound <ide> case errdefs.IsInvalidParameter(err): <ide> statusCode = http.StatusBadRequest <del> case errdefs.IsConflict(err): <add> case errdefs.IsConflict(err) || errdefs.IsAlreadyExists(err): <ide> statusCode = http.StatusConflict <ide> case errdefs.IsUnauthorized(err): <ide> statusCode = http.StatusUnauthorized <ide> func GetHTTPErrorStatusCode(err error) int { <ide> statusCode = http.StatusNotModified <ide> case errdefs.IsNotImplemented(err): <ide> statusCode = http.StatusNotImplemented <del> case errdefs.IsSystem(err) || errdefs.IsUnknown(err): <add> case errdefs.IsSystem(err) || errdefs.IsUnknown(err) || errdefs.IsDataLoss(err) || errdefs.IsDeadline(err) || errdefs.IsCancelled(err): <ide> statusCode = http.StatusInternalServerError <ide> default: <ide> statusCode = statusCodeFromGRPCError(err) <ide><path>api/server/httputils/httputils.go <ide> import ( <ide> "net/http" <ide> "strings" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> "golang.org/x/net/context" <ide> func CloseStreams(streams ...interface{}) { <ide> } <ide> } <ide> <del>type validationError struct { <del> cause error <del>} <del> <del>func (e validationError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e validationError) Cause() error { <del> return e.cause <del>} <del> <del>func (e validationError) InvalidParameter() {} <del> <ide> // CheckForJSON makes sure that the request's Content-Type is application/json. <ide> func CheckForJSON(r *http.Request) error { <ide> ct := r.Header.Get("Content-Type") <ide> func CheckForJSON(r *http.Request) error { <ide> if matchesContentType(ct, "application/json") { <ide> return nil <ide> } <del> return validationError{errors.Errorf("Content-Type specified (%s) must be 'application/json'", ct)} <add> return errdefs.InvalidParameter(errors.Errorf("Content-Type specified (%s) must be 'application/json'", ct)) <ide> } <ide> <ide> // ParseForm ensures the request form is parsed even with invalid content types. <ide> func ParseForm(r *http.Request) error { <ide> return nil <ide> } <ide> if err := r.ParseForm(); err != nil && !strings.HasPrefix(err.Error(), "mime:") { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> return nil <ide> } <ide><path>api/server/router/build/build_routes.go <ide> import ( <ide> "strings" <ide> "sync" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/server/httputils" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/backend" <ide> func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBui <ide> } <ide> p := system.ParsePlatform(apiPlatform) <ide> if err := system.ValidatePlatform(p); err != nil { <del> return nil, validationError{fmt.Errorf("invalid platform: %s", err)} <add> return nil, errdefs.InvalidParameter(errors.Errorf("invalid platform: %s", err)) <ide> } <ide> options.Platform = p.OS <ide> } <ide> func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBui <ide> } <ide> <ide> if runtime.GOOS != "windows" && options.SecurityOpt != nil { <del> return nil, validationError{fmt.Errorf("The daemon on this platform does not support setting security options on build")} <add> return nil, errdefs.InvalidParameter(errors.New("The daemon on this platform does not support setting security options on build")) <ide> } <ide> <ide> var buildUlimits = []*units.Ulimit{} <ide> ulimitsJSON := r.FormValue("ulimits") <ide> if ulimitsJSON != "" { <ide> if err := json.Unmarshal([]byte(ulimitsJSON), &buildUlimits); err != nil { <del> return nil, errors.Wrap(validationError{err}, "error reading ulimit settings") <add> return nil, errors.Wrap(errdefs.InvalidParameter(err), "error reading ulimit settings") <ide> } <ide> options.Ulimits = buildUlimits <ide> } <ide> func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBui <ide> if buildArgsJSON != "" { <ide> var buildArgs = map[string]*string{} <ide> if err := json.Unmarshal([]byte(buildArgsJSON), &buildArgs); err != nil { <del> return nil, errors.Wrap(validationError{err}, "error reading build args") <add> return nil, errors.Wrap(errdefs.InvalidParameter(err), "error reading build args") <ide> } <ide> options.BuildArgs = buildArgs <ide> } <ide> func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBui <ide> if labelsJSON != "" { <ide> var labels = map[string]string{} <ide> if err := json.Unmarshal([]byte(labelsJSON), &labels); err != nil { <del> return nil, errors.Wrap(validationError{err}, "error reading labels") <add> return nil, errors.Wrap(errdefs.InvalidParameter(err), "error reading labels") <ide> } <ide> options.Labels = labels <ide> } <ide> func (br *buildRouter) postPrune(ctx context.Context, w http.ResponseWriter, r * <ide> return httputils.WriteJSON(w, http.StatusOK, report) <ide> } <ide> <del>type validationError struct { <del> cause error <del>} <del> <del>func (e validationError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e validationError) InvalidParameter() {} <del> <ide> func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> var ( <ide> notVerboseBuffer = bytes.NewBuffer(nil) <ide> func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r * <ide> buildOptions.AuthConfigs = getAuthConfigs(r.Header) <ide> <ide> if buildOptions.Squash && !br.daemon.HasExperimental() { <del> return validationError{errors.New("squash is only supported with experimental mode")} <add> return errdefs.InvalidParameter(errors.New("squash is only supported with experimental mode")) <ide> } <ide> <ide> out := io.Writer(output) <ide><path>api/server/router/container/container.go <ide> import ( <ide> "github.com/docker/docker/api/server/router" <ide> ) <ide> <del>type validationError struct { <del> cause error <del>} <del> <del>func (e validationError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e validationError) Cause() error { <del> return e.cause <del>} <del> <del>func (e validationError) InvalidParameter() {} <del> <ide> // containerRouter is a router to talk with the container controller <ide> type containerRouter struct { <ide> backend Backend <ide><path>api/server/router/container/container_routes.go <ide> func (s *containerRouter) getContainersLogs(ctx context.Context, w http.Response <ide> // with the appropriate status code. <ide> stdout, stderr := httputils.BoolValue(r, "stdout"), httputils.BoolValue(r, "stderr") <ide> if !(stdout || stderr) { <del> return validationError{errors.New("Bad parameters: you must choose at least one stream")} <add> return errdefs.InvalidParameter(errors.New("Bad parameters: you must choose at least one stream")) <ide> } <ide> <ide> containerName := vars["name"] <ide> func (s *containerRouter) postContainersKill(ctx context.Context, w http.Respons <ide> if sigStr := r.Form.Get("signal"); sigStr != "" { <ide> var err error <ide> if sig, err = signal.ParseSignal(sigStr); err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> } <ide> <ide> func (s *containerRouter) postContainersResize(ctx context.Context, w http.Respo <ide> <ide> height, err := strconv.Atoi(r.Form.Get("h")) <ide> if err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> width, err := strconv.Atoi(r.Form.Get("w")) <ide> if err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> return s.backend.ContainerResize(vars["name"], height, width) <ide> func (s *containerRouter) postContainersAttach(ctx context.Context, w http.Respo <ide> <ide> hijacker, ok := w.(http.Hijacker) <ide> if !ok { <del> return validationError{errors.Errorf("error attaching to container %s, hijack connection missing", containerName)} <add> return errdefs.InvalidParameter(errors.Errorf("error attaching to container %s, hijack connection missing", containerName)) <ide> } <ide> <ide> setupStreams := func() (io.ReadCloser, io.Writer, io.Writer, error) { <ide> func (s *containerRouter) postContainersPrune(ctx context.Context, w http.Respon <ide> <ide> pruneFilters, err := filters.FromJSON(r.Form.Get("filters")) <ide> if err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> pruneReport, err := s.backend.ContainersPrune(ctx, pruneFilters) <ide><path>api/server/router/container/exec.go <ide> import ( <ide> "net/http" <ide> "strconv" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/server/httputils" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/versions" <ide> func (s *containerRouter) postContainerExecResize(ctx context.Context, w http.Re <ide> } <ide> height, err := strconv.Atoi(r.Form.Get("h")) <ide> if err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> width, err := strconv.Atoi(r.Form.Get("w")) <ide> if err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> return s.backend.ContainerExecResize(vars["name"], height, width) <ide><path>api/server/router/image/image_routes.go <ide> import ( <ide> "strconv" <ide> "strings" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/server/httputils" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/backend" <ide> func (s *imageRouter) postImagesCreate(ctx context.Context, w http.ResponseWrite <ide> return nil <ide> } <ide> <del>type validationError struct { <del> cause error <del>} <del> <del>func (e validationError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e validationError) Cause() error { <del> return e.cause <del>} <del> <del>func (validationError) InvalidParameter() {} <del> <ide> func (s *imageRouter) postImagesPush(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> metaHeaders := map[string][]string{} <ide> for k, v := range r.Header { <ide> func (s *imageRouter) postImagesPush(ctx context.Context, w http.ResponseWriter, <ide> } else { <ide> // the old format is supported for compatibility if there was no authConfig header <ide> if err := json.NewDecoder(r.Body).Decode(authConfig); err != nil { <del> return errors.Wrap(validationError{err}, "Bad parameters and missing X-Registry-Auth") <add> return errors.Wrap(errdefs.InvalidParameter(err), "Bad parameters and missing X-Registry-Auth") <ide> } <ide> } <ide> <ide><path>api/server/router/network/network_routes.go <ide> package network <ide> <ide> import ( <ide> "encoding/json" <del> "fmt" <ide> "net/http" <ide> "strconv" <ide> "strings" <ide> <ide> "golang.org/x/net/context" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/server/httputils" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <ide> func (e ambigousResultsError) Error() string { <ide> <ide> func (ambigousResultsError) InvalidParameter() {} <ide> <del>type conflictError struct { <del> cause error <del>} <del> <del>func (e conflictError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e conflictError) Cause() error { <del> return e.cause <del>} <del> <del>func (e conflictError) Conflict() {} <del> <ide> func nameConflict(name string) error { <del> return conflictError{libnetwork.NetworkNameError(name)} <add> return errdefs.Conflict(libnetwork.NetworkNameError(name)) <ide> } <ide> <ide> func (n *networkRouter) getNetwork(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> func (n *networkRouter) findUniqueNetwork(term string) (types.NetworkResource, e <ide> } <ide> } <ide> if len(listByFullName) > 1 { <del> return types.NetworkResource{}, fmt.Errorf("network %s is ambiguous (%d matches found based on name)", term, len(listByFullName)) <add> return types.NetworkResource{}, errdefs.InvalidParameter(errors.Errorf("network %s is ambiguous (%d matches found based on name)", term, len(listByFullName))) <ide> } <ide> <ide> // Find based on partial ID, returns true only if no duplicates <ide> func (n *networkRouter) findUniqueNetwork(term string) (types.NetworkResource, e <ide> } <ide> } <ide> if len(listByPartialID) > 1 { <del> return types.NetworkResource{}, fmt.Errorf("network %s is ambiguous (%d matches found based on ID prefix)", term, len(listByPartialID)) <add> return types.NetworkResource{}, errdefs.InvalidParameter(errors.Errorf("network %s is ambiguous (%d matches found based on ID prefix)", term, len(listByPartialID))) <ide> } <ide> <del> return types.NetworkResource{}, libnetwork.ErrNoSuchNetwork(term) <add> return types.NetworkResource{}, errdefs.NotFound(libnetwork.ErrNoSuchNetwork(term)) <ide> } <ide><path>api/server/router/session/session_routes.go <ide> package session <ide> import ( <ide> "net/http" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "golang.org/x/net/context" <ide> ) <ide> <del>type invalidRequest struct { <del> cause error <del>} <del> <del>func (e invalidRequest) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e invalidRequest) Cause() error { <del> return e.cause <del>} <del> <del>func (e invalidRequest) InvalidParameter() {} <del> <ide> func (sr *sessionRouter) startSession(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> err := sr.backend.HandleHTTPRequest(ctx, w, r) <ide> if err != nil { <del> return invalidRequest{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> return nil <ide> } <ide><path>api/server/router/swarm/cluster_routes.go <ide> import ( <ide> "net/http" <ide> "strconv" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/server/httputils" <ide> basictypes "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/backend" <ide> func (sr *swarmRouter) inspectCluster(ctx context.Context, w http.ResponseWriter <ide> return httputils.WriteJSON(w, http.StatusOK, swarm) <ide> } <ide> <del>type invalidRequestError struct { <del> err error <del>} <del> <del>func (e invalidRequestError) Error() string { <del> return e.err.Error() <del>} <del> <del>func (e invalidRequestError) Cause() error { <del> return e.err <del>} <del> <del>func (e invalidRequestError) InvalidParameter() {} <del> <ide> func (sr *swarmRouter) updateCluster(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> var swarm types.Spec <ide> if err := json.NewDecoder(r.Body).Decode(&swarm); err != nil { <ide> func (sr *swarmRouter) updateCluster(ctx context.Context, w http.ResponseWriter, <ide> version, err := strconv.ParseUint(rawVersion, 10, 64) <ide> if err != nil { <ide> err := fmt.Errorf("invalid swarm version '%s': %v", rawVersion, err) <del> return invalidRequestError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> var flags types.UpdateFlags <ide> func (sr *swarmRouter) updateCluster(ctx context.Context, w http.ResponseWriter, <ide> rot, err := strconv.ParseBool(value) <ide> if err != nil { <ide> err := fmt.Errorf("invalid value for rotateWorkerToken: %s", value) <del> return invalidRequestError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> flags.RotateWorkerToken = rot <ide> func (sr *swarmRouter) updateCluster(ctx context.Context, w http.ResponseWriter, <ide> rot, err := strconv.ParseBool(value) <ide> if err != nil { <ide> err := fmt.Errorf("invalid value for rotateManagerToken: %s", value) <del> return invalidRequestError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> flags.RotateManagerToken = rot <ide> func (sr *swarmRouter) updateCluster(ctx context.Context, w http.ResponseWriter, <ide> if value := r.URL.Query().Get("rotateManagerUnlockKey"); value != "" { <ide> rot, err := strconv.ParseBool(value) <ide> if err != nil { <del> return invalidRequestError{fmt.Errorf("invalid value for rotateManagerUnlockKey: %s", value)} <add> return errdefs.InvalidParameter(fmt.Errorf("invalid value for rotateManagerUnlockKey: %s", value)) <ide> } <ide> <ide> flags.RotateManagerUnlockKey = rot <ide> func (sr *swarmRouter) getServices(ctx context.Context, w http.ResponseWriter, r <ide> } <ide> filter, err := filters.FromJSON(r.Form.Get("filters")) <ide> if err != nil { <del> return invalidRequestError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> services, err := sr.backend.GetServices(basictypes.ServiceListOptions{Filters: filter}) <ide> func (sr *swarmRouter) getService(ctx context.Context, w http.ResponseWriter, r <ide> insertDefaults, err = strconv.ParseBool(value) <ide> if err != nil { <ide> err := fmt.Errorf("invalid value for insertDefaults: %s", value) <del> return errors.Wrapf(invalidRequestError{err}, "invalid value for insertDefaults: %s", value) <add> return errors.Wrapf(errdefs.InvalidParameter(err), "invalid value for insertDefaults: %s", value) <ide> } <ide> } <ide> <ide> func (sr *swarmRouter) updateService(ctx context.Context, w http.ResponseWriter, <ide> version, err := strconv.ParseUint(rawVersion, 10, 64) <ide> if err != nil { <ide> err := fmt.Errorf("invalid service version '%s': %v", rawVersion, err) <del> return invalidRequestError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> var flags basictypes.ServiceUpdateOptions <ide> func (sr *swarmRouter) updateNode(ctx context.Context, w http.ResponseWriter, r <ide> version, err := strconv.ParseUint(rawVersion, 10, 64) <ide> if err != nil { <ide> err := fmt.Errorf("invalid node version '%s': %v", rawVersion, err) <del> return invalidRequestError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> if err := sr.backend.UpdateNode(vars["id"], version, node); err != nil { <ide> func (sr *swarmRouter) getSecret(ctx context.Context, w http.ResponseWriter, r * <ide> func (sr *swarmRouter) updateSecret(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> var secret types.SecretSpec <ide> if err := json.NewDecoder(r.Body).Decode(&secret); err != nil { <del> return invalidRequestError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> rawVersion := r.URL.Query().Get("version") <ide> version, err := strconv.ParseUint(rawVersion, 10, 64) <ide> if err != nil { <del> return invalidRequestError{fmt.Errorf("invalid secret version")} <add> return errdefs.InvalidParameter(fmt.Errorf("invalid secret version")) <ide> } <ide> <ide> id := vars["id"] <ide> func (sr *swarmRouter) getConfig(ctx context.Context, w http.ResponseWriter, r * <ide> func (sr *swarmRouter) updateConfig(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> var config types.ConfigSpec <ide> if err := json.NewDecoder(r.Body).Decode(&config); err != nil { <del> return invalidRequestError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> rawVersion := r.URL.Query().Get("version") <ide> version, err := strconv.ParseUint(rawVersion, 10, 64) <ide> if err != nil { <del> return invalidRequestError{fmt.Errorf("invalid config version")} <add> return errdefs.InvalidParameter(fmt.Errorf("invalid config version")) <ide> } <ide> <ide> id := vars["id"] <ide><path>builder/dockerfile/builder.go <ide> import ( <ide> "strings" <ide> "time" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/backend" <ide> "github.com/docker/docker/api/types/container" <ide> func (b *Builder) build(source builder.Source, dockerfile *parser.Result) (*buil <ide> if instructions.IsUnknownInstruction(err) { <ide> buildsFailed.WithValues(metricsUnknownInstructionError).Inc() <ide> } <del> return nil, validationError{err} <add> return nil, errdefs.InvalidParameter(err) <ide> } <ide> if b.options.Target != "" { <ide> targetIx, found := instructions.HasStage(stages, b.options.Target) <ide> func BuildFromConfig(config *container.Config, changes []string) (*container.Con <ide> <ide> dockerfile, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n"))) <ide> if err != nil { <del> return nil, validationError{err} <add> return nil, errdefs.InvalidParameter(err) <ide> } <ide> <ide> os := runtime.GOOS <ide> func BuildFromConfig(config *container.Config, changes []string) (*container.Con <ide> // ensure that the commands are valid <ide> for _, n := range dockerfile.AST.Children { <ide> if !validCommitCommands[n.Value] { <del> return nil, validationError{errors.Errorf("%s is not a valid change command", n.Value)} <add> return nil, errdefs.InvalidParameter(errors.Errorf("%s is not a valid change command", n.Value)) <ide> } <ide> } <ide> <ide> func BuildFromConfig(config *container.Config, changes []string) (*container.Con <ide> for _, n := range dockerfile.AST.Children { <ide> cmd, err := instructions.ParseCommand(n) <ide> if err != nil { <del> return nil, validationError{err} <add> return nil, errdefs.InvalidParameter(err) <ide> } <ide> commands = append(commands, cmd) <ide> } <ide> func BuildFromConfig(config *container.Config, changes []string) (*container.Con <ide> for _, cmd := range commands { <ide> err := dispatch(dispatchRequest, cmd) <ide> if err != nil { <del> return nil, validationError{err} <add> return nil, errdefs.InvalidParameter(err) <ide> } <ide> dispatchRequest.state.updateRunConfig() <ide> } <ide><path>builder/dockerfile/dispatchers.go <ide> import ( <ide> "strings" <ide> <ide> "github.com/docker/docker/api" <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/api/types/strslice" <ide> "github.com/docker/docker/builder" <ide> func dispatchStopSignal(d dispatchRequest, c *instructions.StopSignalCommand) er <ide> <ide> _, err := signal.ParseSignal(c.Signal) <ide> if err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> d.state.runConfig.StopSignal = c.Signal <ide> return d.builder.commit(d.state, fmt.Sprintf("STOPSIGNAL %v", c.Signal)) <ide><path>builder/dockerfile/errors.go <del>package dockerfile <del> <del>type validationError struct { <del> err error <del>} <del> <del>func (e validationError) Error() string { <del> return e.err.Error() <del>} <del> <del>func (e validationError) InvalidParameter() {} <del> <del>func (e validationError) Cause() error { <del> return e.err <del>} <ide><path>builder/dockerfile/evaluator.go <ide> import ( <ide> "strconv" <ide> "strings" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/builder" <ide> "github.com/docker/docker/builder/dockerfile/instructions" <ide> func dispatch(d dispatchRequest, cmd instructions.Command) (err error) { <ide> optionsOS := system.ParsePlatform(d.builder.options.Platform).OS <ide> err := c.CheckPlatform(optionsOS) <ide> if err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> } <ide> runConfigEnv := d.state.runConfig.Env <ide> func dispatch(d dispatchRequest, cmd instructions.Command) (err error) { <ide> return d.shlex.ProcessWord(word, envs) <ide> }) <ide> if err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> } <ide> <ide><path>builder/remotecontext/errors.go <del>package remotecontext <del> <del>type notFoundError string <del> <del>func (e notFoundError) Error() string { <del> return string(e) <del>} <del> <del>func (notFoundError) NotFound() {} <del> <del>type requestError string <del> <del>func (e requestError) Error() string { <del> return string(e) <del>} <del> <del>func (e requestError) InvalidParameter() {} <del> <del>type unauthorizedError string <del> <del>func (e unauthorizedError) Error() string { <del> return string(e) <del>} <del> <del>func (unauthorizedError) Unauthorized() {} <del> <del>type forbiddenError string <del> <del>func (e forbiddenError) Error() string { <del> return string(e) <del>} <del> <del>func (forbiddenError) Forbidden() {} <del> <del>type dnsError struct { <del> cause error <del>} <del> <del>func (e dnsError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e dnsError) NotFound() {} <del> <del>func (e dnsError) Cause() error { <del> return e.cause <del>} <del> <del>type systemError struct { <del> cause error <del>} <del> <del>func (e systemError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e systemError) SystemError() {} <del> <del>func (e systemError) Cause() error { <del> return e.cause <del>} <del> <del>type unknownError struct { <del> cause error <del>} <del> <del>func (e unknownError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (unknownError) Unknown() {} <del> <del>func (e unknownError) Cause() error { <del> return e.cause <del>} <ide><path>builder/remotecontext/remote.go <ide> import ( <ide> "net/url" <ide> "regexp" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/pkg/ioutils" <ide> "github.com/pkg/errors" <ide> ) <ide> var mimeRe = regexp.MustCompile(acceptableRemoteMIME) <ide> func downloadRemote(remoteURL string) (string, io.ReadCloser, error) { <ide> response, err := GetWithStatusError(remoteURL) <ide> if err != nil { <del> return "", nil, fmt.Errorf("error downloading remote context %s: %v", remoteURL, err) <add> return "", nil, errors.Wrapf(err, "error downloading remote context %s", remoteURL) <ide> } <ide> <ide> contentType, contextReader, err := inspectResponse( <ide> func downloadRemote(remoteURL string) (string, io.ReadCloser, error) { <ide> response.ContentLength) <ide> if err != nil { <ide> response.Body.Close() <del> return "", nil, fmt.Errorf("error detecting content type for remote %s: %v", remoteURL, err) <add> return "", nil, errors.Wrapf(err, "error detecting content type for remote %s", remoteURL) <ide> } <ide> <ide> return contentType, ioutils.NewReadCloserWrapper(contextReader, response.Body.Close), nil <ide> func GetWithStatusError(address string) (resp *http.Response, err error) { <ide> if resp, err = http.Get(address); err != nil { <ide> if uerr, ok := err.(*url.Error); ok { <ide> if derr, ok := uerr.Err.(*net.DNSError); ok && !derr.IsTimeout { <del> return nil, dnsError{err} <add> return nil, errdefs.NotFound(err) <ide> } <ide> } <del> return nil, systemError{err} <add> return nil, errdefs.System(err) <ide> } <ide> if resp.StatusCode < 400 { <ide> return resp, nil <ide> func GetWithStatusError(address string) (resp *http.Response, err error) { <ide> body, err := ioutil.ReadAll(resp.Body) <ide> resp.Body.Close() <ide> if err != nil { <del> return nil, errors.Wrap(systemError{err}, msg+": error reading body") <add> return nil, errdefs.System(errors.New(msg + ": error reading body")) <ide> } <ide> <ide> msg += ": " + string(bytes.TrimSpace(body)) <ide> switch resp.StatusCode { <ide> case http.StatusNotFound: <del> return nil, notFoundError(msg) <add> return nil, errdefs.NotFound(errors.New(msg)) <ide> case http.StatusBadRequest: <del> return nil, requestError(msg) <add> return nil, errdefs.InvalidParameter(errors.New(msg)) <ide> case http.StatusUnauthorized: <del> return nil, unauthorizedError(msg) <add> return nil, errdefs.Unauthorized(errors.New(msg)) <ide> case http.StatusForbidden: <del> return nil, forbiddenError(msg) <add> return nil, errdefs.Forbidden(errors.New(msg)) <ide> } <del> return nil, unknownError{errors.New(msg)} <add> return nil, errdefs.Unknown(errors.New(msg)) <ide> } <ide> <ide> // inspectResponse looks into the http response data at r to determine whether its <ide><path>daemon/archive.go <ide> import ( <ide> "os" <ide> "strings" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/pkg/archive" <ide> func (daemon *Daemon) ContainerCopy(name string, res string) (io.ReadCloser, err <ide> <ide> // Make sure an online file-system operation is permitted. <ide> if err := daemon.isOnlineFSOperationPermitted(container); err != nil { <del> return nil, systemError{err} <add> return nil, errdefs.System(err) <ide> } <ide> <ide> data, err := daemon.containerCopy(container, res) <ide> func (daemon *Daemon) ContainerCopy(name string, res string) (io.ReadCloser, err <ide> if os.IsNotExist(err) { <ide> return nil, containerFileNotFound{res, name} <ide> } <del> return nil, systemError{err} <add> return nil, errdefs.System(err) <ide> } <ide> <ide> // ContainerStatPath stats the filesystem resource at the specified path in the <ide> func (daemon *Daemon) ContainerStatPath(name string, path string) (stat *types.C <ide> <ide> // Make sure an online file-system operation is permitted. <ide> if err := daemon.isOnlineFSOperationPermitted(container); err != nil { <del> return nil, systemError{err} <add> return nil, errdefs.System(err) <ide> } <ide> <ide> stat, err = daemon.containerStatPath(container, path) <ide> func (daemon *Daemon) ContainerStatPath(name string, path string) (stat *types.C <ide> if os.IsNotExist(err) { <ide> return nil, containerFileNotFound{path, name} <ide> } <del> return nil, systemError{err} <add> return nil, errdefs.System(err) <ide> } <ide> <ide> // ContainerArchivePath creates an archive of the filesystem resource at the <ide> func (daemon *Daemon) ContainerArchivePath(name string, path string) (content io <ide> <ide> // Make sure an online file-system operation is permitted. <ide> if err := daemon.isOnlineFSOperationPermitted(container); err != nil { <del> return nil, nil, systemError{err} <add> return nil, nil, errdefs.System(err) <ide> } <ide> <ide> content, stat, err = daemon.containerArchivePath(container, path) <ide> func (daemon *Daemon) ContainerArchivePath(name string, path string) (content io <ide> if os.IsNotExist(err) { <ide> return nil, nil, containerFileNotFound{path, name} <ide> } <del> return nil, nil, systemError{err} <add> return nil, nil, errdefs.System(err) <ide> } <ide> <ide> // ContainerExtractToDir extracts the given archive to the specified location <ide> func (daemon *Daemon) ContainerExtractToDir(name, path string, copyUIDGID, noOve <ide> <ide> // Make sure an online file-system operation is permitted. <ide> if err := daemon.isOnlineFSOperationPermitted(container); err != nil { <del> return systemError{err} <add> return errdefs.System(err) <ide> } <ide> <ide> err = daemon.containerExtractToDir(container, path, copyUIDGID, noOverwriteDirNonDir, content) <ide> func (daemon *Daemon) ContainerExtractToDir(name, path string, copyUIDGID, noOve <ide> if os.IsNotExist(err) { <ide> return containerFileNotFound{path, name} <ide> } <del> return systemError{err} <add> return errdefs.System(err) <ide> } <ide> <ide> // containerStatPath stats the filesystem resource at the specified path in this <ide><path>daemon/attach.go <ide> import ( <ide> "fmt" <ide> "io" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types/backend" <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/container/stream" <ide> func (daemon *Daemon) ContainerAttach(prefixOrName string, c *backend.ContainerA <ide> if c.DetachKeys != "" { <ide> keys, err = term.ToBytes(c.DetachKeys) <ide> if err != nil { <del> return validationError{errors.Errorf("Invalid detach keys (%s) provided", c.DetachKeys)} <add> return errdefs.InvalidParameter(errors.Errorf("Invalid detach keys (%s) provided", c.DetachKeys)) <ide> } <ide> } <ide> <ide> func (daemon *Daemon) ContainerAttach(prefixOrName string, c *backend.ContainerA <ide> } <ide> if container.IsPaused() { <ide> err := fmt.Errorf("container %s is paused, unpause the container before attach", prefixOrName) <del> return stateConflictError{err} <add> return errdefs.Conflict(err) <ide> } <ide> if container.IsRestarting() { <ide> err := fmt.Errorf("container %s is restarting, wait until the container is running", prefixOrName) <del> return stateConflictError{err} <add> return errdefs.Conflict(err) <ide> } <ide> <ide> cfg := stream.AttachConfig{ <ide><path>daemon/cluster/errors.go <ide> const ( <ide> errSwarmNotManager notAvailableError = "This node is not a swarm manager. Worker nodes can't be used to view or modify cluster state. Please run this command on a manager node or promote the current node to a manager." <ide> ) <ide> <del>type notFoundError struct { <del> cause error <del>} <del> <del>func (e notFoundError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e notFoundError) NotFound() {} <del> <del>func (e notFoundError) Cause() error { <del> return e.cause <del>} <del> <del>type ambiguousResultsError struct { <del> cause error <del>} <del> <del>func (e ambiguousResultsError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e ambiguousResultsError) InvalidParameter() {} <del> <del>func (e ambiguousResultsError) Cause() error { <del> return e.cause <del>} <del> <del>type convertError struct { <del> cause error <del>} <del> <del>func (e convertError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e convertError) InvalidParameter() {} <del> <del>func (e convertError) Cause() error { <del> return e.cause <del>} <del> <ide> type notAllowedError string <ide> <ide> func (e notAllowedError) Error() string { <ide> func (e notAllowedError) Error() string { <ide> <ide> func (e notAllowedError) Forbidden() {} <ide> <del>type validationError struct { <del> cause error <del>} <del> <del>func (e validationError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e validationError) InvalidParameter() {} <del> <del>func (e validationError) Cause() error { <del> return e.cause <del>} <del> <ide> type notAvailableError string <ide> <ide> func (e notAvailableError) Error() string { <ide><path>daemon/cluster/helpers.go <ide> package cluster <ide> import ( <ide> "fmt" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> swarmapi "github.com/docker/swarmkit/api" <ide> "github.com/pkg/errors" <ide> "golang.org/x/net/context" <ide> func getNode(ctx context.Context, c swarmapi.ControlClient, input string) (*swar <ide> <ide> if len(rl.Nodes) == 0 { <ide> err := fmt.Errorf("node %s not found", input) <del> return nil, notFoundError{err} <add> return nil, errdefs.NotFound(err) <ide> } <ide> <ide> if l := len(rl.Nodes); l > 1 { <del> return nil, ambiguousResultsError{fmt.Errorf("node %s is ambiguous (%d matches found)", input, l)} <add> return nil, errdefs.InvalidParameter(fmt.Errorf("node %s is ambiguous (%d matches found)", input, l)) <ide> } <ide> <ide> return rl.Nodes[0], nil <ide> func getService(ctx context.Context, c swarmapi.ControlClient, input string, ins <ide> <ide> if len(rl.Services) == 0 { <ide> err := fmt.Errorf("service %s not found", input) <del> return nil, notFoundError{err} <add> return nil, errdefs.NotFound(err) <ide> } <ide> <ide> if l := len(rl.Services); l > 1 { <del> return nil, ambiguousResultsError{fmt.Errorf("service %s is ambiguous (%d matches found)", input, l)} <add> return nil, errdefs.InvalidParameter(fmt.Errorf("service %s is ambiguous (%d matches found)", input, l)) <ide> } <ide> <ide> if !insertDefaults { <ide> func getTask(ctx context.Context, c swarmapi.ControlClient, input string) (*swar <ide> <ide> if len(rl.Tasks) == 0 { <ide> err := fmt.Errorf("task %s not found", input) <del> return nil, notFoundError{err} <add> return nil, errdefs.NotFound(err) <ide> } <ide> <ide> if l := len(rl.Tasks); l > 1 { <del> return nil, ambiguousResultsError{fmt.Errorf("task %s is ambiguous (%d matches found)", input, l)} <add> return nil, errdefs.InvalidParameter(fmt.Errorf("task %s is ambiguous (%d matches found)", input, l)) <ide> } <ide> <ide> return rl.Tasks[0], nil <ide> func getSecret(ctx context.Context, c swarmapi.ControlClient, input string) (*sw <ide> <ide> if len(rl.Secrets) == 0 { <ide> err := fmt.Errorf("secret %s not found", input) <del> return nil, notFoundError{err} <add> return nil, errdefs.NotFound(err) <ide> } <ide> <ide> if l := len(rl.Secrets); l > 1 { <del> return nil, ambiguousResultsError{fmt.Errorf("secret %s is ambiguous (%d matches found)", input, l)} <add> return nil, errdefs.InvalidParameter(fmt.Errorf("secret %s is ambiguous (%d matches found)", input, l)) <ide> } <ide> <ide> return rl.Secrets[0], nil <ide> func getConfig(ctx context.Context, c swarmapi.ControlClient, input string) (*sw <ide> <ide> if len(rl.Configs) == 0 { <ide> err := fmt.Errorf("config %s not found", input) <del> return nil, notFoundError{err} <add> return nil, errdefs.NotFound(err) <ide> } <ide> <ide> if l := len(rl.Configs); l > 1 { <del> return nil, ambiguousResultsError{fmt.Errorf("config %s is ambiguous (%d matches found)", input, l)} <add> return nil, errdefs.InvalidParameter(fmt.Errorf("config %s is ambiguous (%d matches found)", input, l)) <ide> } <ide> <ide> return rl.Configs[0], nil <ide> func getNetwork(ctx context.Context, c swarmapi.ControlClient, input string) (*s <ide> } <ide> <ide> if l := len(rl.Networks); l > 1 { <del> return nil, ambiguousResultsError{fmt.Errorf("network %s is ambiguous (%d matches found)", input, l)} <add> return nil, errdefs.InvalidParameter(fmt.Errorf("network %s is ambiguous (%d matches found)", input, l)) <ide> } <ide> <ide> return rl.Networks[0], nil <ide><path>daemon/cluster/networks.go <ide> package cluster <ide> import ( <ide> "fmt" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> apitypes "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/network" <ide> types "github.com/docker/docker/api/types/swarm" <ide> func (c *Cluster) populateNetworkID(ctx context.Context, client swarmapi.Control <ide> // and use its id for the request. <ide> apiNetwork, err = getNetwork(ctx, client, ln.Name()) <ide> if err != nil { <del> return errors.Wrap(notFoundError{err}, "could not find the corresponding predefined swarm network") <add> return errors.Wrap(errdefs.NotFound(err), "could not find the corresponding predefined swarm network") <ide> } <ide> goto setid <ide> } <ide><path>daemon/cluster/nodes.go <ide> package cluster <ide> <ide> import ( <add> "github.com/docker/docker/api/errdefs" <ide> apitypes "github.com/docker/docker/api/types" <ide> types "github.com/docker/docker/api/types/swarm" <ide> "github.com/docker/docker/daemon/cluster/convert" <ide> func (c *Cluster) UpdateNode(input string, version uint64, spec types.NodeSpec) <ide> return c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <ide> nodeSpec, err := convert.NodeSpecToGRPC(spec) <ide> if err != nil { <del> return convertError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> ctx, cancel := c.getRequestContext() <ide><path>daemon/cluster/services.go <ide> import ( <ide> "time" <ide> <ide> "github.com/docker/distribution/reference" <add> "github.com/docker/docker/api/errdefs" <ide> apitypes "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/backend" <ide> types "github.com/docker/docker/api/types/swarm" <ide> func (c *Cluster) CreateService(s types.ServiceSpec, encodedAuth string, queryRe <ide> <ide> serviceSpec, err := convert.ServiceSpecToGRPC(s) <ide> if err != nil { <del> return convertError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> resp = &apitypes.ServiceCreateResponse{} <ide> func (c *Cluster) UpdateService(serviceIDOrName string, version uint64, spec typ <ide> <ide> serviceSpec, err := convert.ServiceSpecToGRPC(spec) <ide> if err != nil { <del> return convertError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> currentService, err := getService(ctx, state.controlClient, serviceIDOrName, false) <ide><path>daemon/cluster/swarm.go <ide> import ( <ide> "strings" <ide> "time" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> apitypes "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <ide> types "github.com/docker/docker/api/types/swarm" <ide> func (c *Cluster) Init(req types.InitRequest) (string, error) { <ide> } <ide> <ide> if err := validateAndSanitizeInitRequest(&req); err != nil { <del> return "", validationError{err} <add> return "", errdefs.InvalidParameter(err) <ide> } <ide> <ide> listenHost, listenPort, err := resolveListenAddr(req.ListenAddr) <ide> func (c *Cluster) Join(req types.JoinRequest) error { <ide> c.mu.Unlock() <ide> <ide> if err := validateAndSanitizeJoinRequest(&req); err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> listenHost, listenPort, err := resolveListenAddr(req.ListenAddr) <ide> func (c *Cluster) Update(version uint64, spec types.Spec, flags types.UpdateFlag <ide> if spec.Annotations.Name == "" { <ide> spec.Annotations.Name = "default" <ide> } else if spec.Annotations.Name != "default" { <del> return validationError{errors.New(`swarm spec must be named "default"`)} <add> return errdefs.InvalidParameter(errors.New(`swarm spec must be named "default"`)) <ide> } <ide> <ide> // In update, client should provide the complete spec of the swarm, including <ide> // Name and Labels. If a field is specified with 0 or nil, then the default value <ide> // will be used to swarmkit. <ide> clusterSpec, err := convert.SwarmSpecToGRPC(spec) <ide> if err != nil { <del> return convertError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> _, err = state.controlClient.UpdateCluster( <ide> func (c *Cluster) UnlockSwarm(req types.UnlockRequest) error { <ide> <ide> key, err := encryption.ParseHumanReadableKey(req.UnlockKey) <ide> if err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> config := nr.config <ide><path>daemon/commit.go <ide> import ( <ide> "time" <ide> <ide> "github.com/docker/distribution/reference" <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types/backend" <ide> containertypes "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/builder/dockerfile" <ide> func (daemon *Daemon) Commit(name string, c *backend.ContainerCommitConfig) (str <ide> <ide> if container.IsDead() { <ide> err := fmt.Errorf("You cannot commit container %s which is Dead", container.ID) <del> return "", stateConflictError{err} <add> return "", errdefs.Conflict(err) <ide> } <ide> <ide> if container.IsRemovalInProgress() { <ide> err := fmt.Errorf("You cannot commit container %s which is being removed", container.ID) <del> return "", stateConflictError{err} <add> return "", errdefs.Conflict(err) <ide> } <ide> <ide> if c.Pause && !container.IsPaused() { <ide><path>daemon/container.go <ide> import ( <ide> "strings" <ide> "time" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> containertypes "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/api/types/strslice" <ide> "github.com/docker/docker/container" <ide> func (daemon *Daemon) GetContainer(prefixOrName string) (*container.Container, e <ide> if indexError == truncindex.ErrNotExist { <ide> return nil, containerNotFound(prefixOrName) <ide> } <del> return nil, systemError{indexError} <add> return nil, errdefs.System(indexError) <ide> } <ide> return daemon.containers.Get(containerID), nil <ide> } <ide> func (daemon *Daemon) newContainer(name string, operatingSystem string, config * <ide> if config.Hostname == "" { <ide> config.Hostname, err = os.Hostname() <ide> if err != nil { <del> return nil, systemError{err} <add> return nil, errdefs.System(err) <ide> } <ide> } <ide> } else { <ide><path>daemon/container_linux.go <ide> package daemon <ide> <ide> import ( <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/container" <ide> ) <ide> <ide> func (daemon *Daemon) saveApparmorConfig(container *container.Container) error { <ide> } <ide> <ide> if err := parseSecurityOpt(container, container.HostConfig); err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> if !container.HostConfig.Privileged { <ide><path>daemon/container_operations.go <ide> import ( <ide> "strings" <ide> "time" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> containertypes "github.com/docker/docker/api/types/container" <ide> networktypes "github.com/docker/docker/api/types/network" <ide> "github.com/docker/docker/container" <ide> func (daemon *Daemon) getNetworkedContainer(containerID, connectedContainerID st <ide> } <ide> if !nc.IsRunning() { <ide> err := fmt.Errorf("cannot join network of a non running container: %s", connectedContainerID) <del> return nil, stateConflictError{err} <add> return nil, errdefs.Conflict(err) <ide> } <ide> if nc.IsRestarting() { <ide> return nil, errContainerIsRestarting(connectedContainerID) <ide><path>daemon/container_operations_unix.go <ide> import ( <ide> "strconv" <ide> "time" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/daemon/links" <ide> "github.com/docker/docker/pkg/idtools" <ide> func (daemon *Daemon) getPidContainer(container *container.Container) (*containe <ide> <ide> func containerIsRunning(c *container.Container) error { <ide> if !c.IsRunning() { <del> return stateConflictError{errors.Errorf("container %s is not running", c.ID)} <add> return errdefs.Conflict(errors.Errorf("container %s is not running", c.ID)) <ide> } <ide> return nil <ide> } <ide><path>daemon/create.go <ide> import ( <ide> <ide> "github.com/pkg/errors" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> containertypes "github.com/docker/docker/api/types/container" <ide> networktypes "github.com/docker/docker/api/types/network" <ide> func (daemon *Daemon) ContainerCreate(params types.ContainerCreateConfig) (conta <ide> func (daemon *Daemon) containerCreate(params types.ContainerCreateConfig, managed bool) (containertypes.ContainerCreateCreatedBody, error) { <ide> start := time.Now() <ide> if params.Config == nil { <del> return containertypes.ContainerCreateCreatedBody{}, validationError{errors.New("Config cannot be empty in order to create a container")} <add> return containertypes.ContainerCreateCreatedBody{}, errdefs.InvalidParameter(errors.New("Config cannot be empty in order to create a container")) <ide> } <ide> <ide> os := runtime.GOOS <ide> func (daemon *Daemon) containerCreate(params types.ContainerCreateConfig, manage <ide> <ide> warnings, err := daemon.verifyContainerSettings(os, params.HostConfig, params.Config, false) <ide> if err != nil { <del> return containertypes.ContainerCreateCreatedBody{Warnings: warnings}, validationError{err} <add> return containertypes.ContainerCreateCreatedBody{Warnings: warnings}, errdefs.InvalidParameter(err) <ide> } <ide> <ide> err = verifyNetworkingConfig(params.NetworkingConfig) <ide> if err != nil { <del> return containertypes.ContainerCreateCreatedBody{Warnings: warnings}, validationError{err} <add> return containertypes.ContainerCreateCreatedBody{Warnings: warnings}, errdefs.InvalidParameter(err) <ide> } <ide> <ide> if params.HostConfig == nil { <ide> params.HostConfig = &containertypes.HostConfig{} <ide> } <ide> err = daemon.adaptContainerSettings(params.HostConfig, params.AdjustCPUShares) <ide> if err != nil { <del> return containertypes.ContainerCreateCreatedBody{Warnings: warnings}, validationError{err} <add> return containertypes.ContainerCreateCreatedBody{Warnings: warnings}, errdefs.InvalidParameter(err) <ide> } <ide> <ide> container, err := daemon.create(params, managed) <ide> func (daemon *Daemon) create(params types.ContainerCreateConfig, managed bool) ( <ide> } <ide> <ide> if err := daemon.mergeAndVerifyConfig(params.Config, img); err != nil { <del> return nil, validationError{err} <add> return nil, errdefs.InvalidParameter(err) <ide> } <ide> <ide> if err := daemon.mergeAndVerifyLogConfig(&params.HostConfig.LogConfig); err != nil { <del> return nil, validationError{err} <add> return nil, errdefs.InvalidParameter(err) <ide> } <ide> <ide> if container, err = daemon.newContainer(params.Name, os, params.Config, params.HostConfig, imgID, managed); err != nil { <ide> func (daemon *Daemon) create(params types.ContainerCreateConfig, managed bool) ( <ide> <ide> // Set RWLayer for container after mount labels have been set <ide> if err := daemon.setRWLayer(container); err != nil { <del> return nil, systemError{err} <add> return nil, errdefs.System(err) <ide> } <ide> <ide> rootIDs := daemon.idMappings.RootPair() <ide><path>daemon/delete.go <ide> import ( <ide> "strings" <ide> "time" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/layer" <ide> func (daemon *Daemon) ContainerRm(name string, config *types.ContainerRmConfig) <ide> // Container state RemovalInProgress should be used to avoid races. <ide> if inProgress := container.SetRemovalInProgress(); inProgress { <ide> err := fmt.Errorf("removal of container %s is already in progress", name) <del> return stateConflictError{err} <add> return errdefs.Conflict(err) <ide> } <ide> defer container.ResetRemovalInProgress() <ide> <ide> func (daemon *Daemon) cleanupContainer(container *container.Container, forceRemo <ide> procedure = "Unpause and then " + strings.ToLower(procedure) <ide> } <ide> err := fmt.Errorf("You cannot remove a %s container %s. %s", state, container.ID, procedure) <del> return stateConflictError{err} <add> return errdefs.Conflict(err) <ide> } <ide> if err := daemon.Kill(container); err != nil { <ide> return fmt.Errorf("Could not kill running container %s, cannot remove - %v", container.ID, err) <ide> func (daemon *Daemon) VolumeRm(name string, force bool) error { <ide> <ide> err = daemon.volumeRm(v) <ide> if err != nil && volumestore.IsInUse(err) { <del> return stateConflictError{err} <add> return errdefs.Conflict(err) <ide> } <ide> <ide> if err == nil || force { <ide><path>daemon/errors.go <ide> import ( <ide> "strings" <ide> "syscall" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/pkg/errors" <ide> "google.golang.org/grpc" <ide> ) <ide> <ide> func errNotRunning(id string) error { <del> return stateConflictError{errors.Errorf("Container %s is not running", id)} <add> return errdefs.Conflict(errors.Errorf("Container %s is not running", id)) <ide> } <ide> <ide> func containerNotFound(id string) error { <ide> func (e objNotFoundError) Error() string { <ide> <ide> func (e objNotFoundError) NotFound() {} <ide> <del>type stateConflictError struct { <del> cause error <del>} <del> <del>func (e stateConflictError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e stateConflictError) Cause() error { <del> return e.cause <del>} <del> <del>func (e stateConflictError) Conflict() {} <del> <ide> func errContainerIsRestarting(containerID string) error { <ide> cause := errors.Errorf("Container %s is restarting, wait until the container is running", containerID) <del> return stateConflictError{cause} <add> return errdefs.Conflict(cause) <ide> } <ide> <ide> func errExecNotFound(id string) error { <ide> func errExecNotFound(id string) error { <ide> <ide> func errExecPaused(id string) error { <ide> cause := errors.Errorf("Container %s is paused, unpause the container before exec", id) <del> return stateConflictError{cause} <add> return errdefs.Conflict(cause) <ide> } <ide> <ide> func errNotPaused(id string) error { <ide> cause := errors.Errorf("Container %s is already paused", id) <del> return stateConflictError{cause} <add> return errdefs.Conflict(cause) <ide> } <ide> <ide> type nameConflictError struct { <ide> func (e nameConflictError) Error() string { <ide> <ide> func (nameConflictError) Conflict() {} <ide> <del>type validationError struct { <del> cause error <del>} <del> <del>func (e validationError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e validationError) InvalidParameter() {} <del> <del>func (e validationError) Cause() error { <del> return e.cause <del>} <del> <del>type notAllowedError struct { <del> cause error <del>} <del> <del>func (e notAllowedError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e notAllowedError) Forbidden() {} <del> <del>func (e notAllowedError) Cause() error { <del> return e.cause <del>} <del> <ide> type containerNotModifiedError struct { <ide> running bool <ide> } <ide> func (e containerNotModifiedError) Error() string { <ide> <ide> func (e containerNotModifiedError) NotModified() {} <ide> <del>type systemError struct { <del> cause error <del>} <del> <del>func (e systemError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e systemError) SystemError() {} <del> <del>func (e systemError) Cause() error { <del> return e.cause <del>} <del> <ide> type invalidIdentifier string <ide> <ide> func (e invalidIdentifier) Error() string { <ide> func (e invalidFilter) Error() string { <ide> <ide> func (e invalidFilter) InvalidParameter() {} <ide> <del>type unknownError struct { <del> cause error <del>} <del> <del>func (e unknownError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (unknownError) Unknown() {} <del> <del>func (e unknownError) Cause() error { <del> return e.cause <del>} <del> <ide> type startInvalidConfigError string <ide> <ide> func (e startInvalidConfigError) Error() string { <ide> func translateContainerdStartErr(cmd string, setExitCode func(int), err error) e <ide> contains := func(s1, s2 string) bool { <ide> return strings.Contains(strings.ToLower(s1), s2) <ide> } <del> var retErr error = unknownError{errors.New(errDesc)} <add> var retErr = errdefs.Unknown(errors.New(errDesc)) <ide> // if we receive an internal error from the initial start of a container then lets <ide> // return it instead of entering the restart loop <ide> // set to 127 for container cmd not found/does not exist) <ide><path>daemon/exec.go <ide> import ( <ide> <ide> "golang.org/x/net/context" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/strslice" <ide> "github.com/docker/docker/container" <ide> func (d *Daemon) ContainerExecStart(ctx context.Context, name string, stdin io.R <ide> if ec.ExitCode != nil { <ide> ec.Unlock() <ide> err := fmt.Errorf("Error: Exec command %s has already run", ec.ID) <del> return stateConflictError{err} <add> return errdefs.Conflict(err) <ide> } <ide> <ide> if ec.Running { <ide> ec.Unlock() <del> return stateConflictError{fmt.Errorf("Error: Exec command %s is already running", ec.ID)} <add> return errdefs.Conflict(fmt.Errorf("Error: Exec command %s is already running", ec.ID)) <ide> } <ide> ec.Running = true <ide> ec.Unlock() <ide> func (d *Daemon) ContainerExecStart(ctx context.Context, name string, stdin io.R <ide> case err := <-attachErr: <ide> if err != nil { <ide> if _, ok := err.(term.EscapeError); !ok { <del> return errors.Wrap(systemError{err}, "exec attach failed") <add> return errdefs.System(errors.Wrap(err, "exec attach failed")) <ide> } <ide> d.LogContainerEvent(c, "exec_detach") <ide> } <ide><path>daemon/export.go <ide> import ( <ide> "io" <ide> "runtime" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/pkg/archive" <ide> "github.com/docker/docker/pkg/ioutils" <ide> func (daemon *Daemon) ContainerExport(name string, out io.Writer) error { <ide> <ide> if container.IsDead() { <ide> err := fmt.Errorf("You cannot export container %s which is Dead", container.ID) <del> return stateConflictError{err} <add> return errdefs.Conflict(err) <ide> } <ide> <ide> if container.IsRemovalInProgress() { <ide> err := fmt.Errorf("You cannot export container %s which is being removed", container.ID) <del> return stateConflictError{err} <add> return errdefs.Conflict(err) <ide> } <ide> <ide> data, err := daemon.containerExport(container) <ide><path>daemon/image.go <ide> import ( <ide> "runtime" <ide> <ide> "github.com/docker/distribution/reference" <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/image" <ide> ) <ide> <ide> func (e errImageDoesNotExist) NotFound() {} <ide> func (daemon *Daemon) GetImageIDAndOS(refOrID string) (image.ID, string, error) { <ide> ref, err := reference.ParseAnyReference(refOrID) <ide> if err != nil { <del> return "", "", validationError{err} <add> return "", "", errdefs.InvalidParameter(err) <ide> } <ide> namedRef, ok := ref.(reference.Named) <ide> if !ok { <ide><path>daemon/image_delete.go <ide> import ( <ide> "time" <ide> <ide> "github.com/docker/distribution/reference" <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/image" <ide> func (daemon *Daemon) ImageDelete(imageRef string, force, prune bool) ([]types.I <ide> // we really want to avoid that the client must <ide> // explicitly force its removal. <ide> err := errors.Errorf("conflict: unable to remove repository reference %q (must force) - container %s is using its referenced image %s", imageRef, stringid.TruncateID(container.ID), stringid.TruncateID(imgID.String())) <del> return nil, stateConflictError{err} <add> return nil, errdefs.Conflict(err) <ide> } <ide> } <ide> <ide><path>daemon/image_pull.go <ide> import ( <ide> <ide> dist "github.com/docker/distribution" <ide> "github.com/docker/distribution/reference" <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/distribution" <ide> progressutils "github.com/docker/docker/distribution/utils" <ide> func (daemon *Daemon) PullImage(ctx context.Context, image, tag, platform string <ide> <ide> ref, err := reference.ParseNormalizedNamed(image) <ide> if err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> if tag != "" { <ide> func (daemon *Daemon) PullImage(ctx context.Context, image, tag, platform string <ide> ref, err = reference.WithTag(ref, tag) <ide> } <ide> if err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> } <ide> <ide> func (daemon *Daemon) GetRepository(ctx context.Context, ref reference.Named, au <ide> } <ide> // makes sure name is not empty or `scratch` <ide> if err := distribution.ValidateRepoName(repoInfo.Name); err != nil { <del> return nil, false, validationError{err} <add> return nil, false, errdefs.InvalidParameter(err) <ide> } <ide> <ide> // get endpoints <ide><path>daemon/import.go <ide> import ( <ide> "time" <ide> <ide> "github.com/docker/distribution/reference" <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/builder/dockerfile" <ide> "github.com/docker/docker/builder/remotecontext" <ide> func (daemon *Daemon) ImportImage(src string, repository, os string, tag string, <ide> var err error <ide> newRef, err = reference.ParseNormalizedNamed(repository) <ide> if err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> if _, isCanonical := newRef.(reference.Canonical); isCanonical { <del> return validationError{errors.New("cannot import digest reference")} <add> return errdefs.InvalidParameter(errors.New("cannot import digest reference")) <ide> } <ide> <ide> if tag != "" { <ide> newRef, err = reference.WithTag(newRef, tag) <ide> if err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> } <ide> } <ide> func (daemon *Daemon) ImportImage(src string, repository, os string, tag string, <ide> } <ide> u, err := url.Parse(src) <ide> if err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> resp, err = remotecontext.GetWithStatusError(u.String()) <ide><path>daemon/inspect.go <ide> import ( <ide> "fmt" <ide> "time" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/backend" <ide> networktypes "github.com/docker/docker/api/types/network" <ide> func (daemon *Daemon) getInspectData(container *container.Container) (*types.Con <ide> // could have been removed, it will cause error if we try to get the metadata, <ide> // we can ignore the error if the container is dead. <ide> if err != nil && !container.Dead { <del> return nil, systemError{err} <add> return nil, errdefs.System(err) <ide> } <ide> contJSONBase.GraphDriver.Data = graphDriverData <ide> <ide> func (daemon *Daemon) VolumeInspect(name string) (*types.Volume, error) { <ide> if volumestore.IsNotExist(err) { <ide> return nil, volumeNotFound(name) <ide> } <del> return nil, systemError{err} <add> return nil, errdefs.System(err) <ide> } <ide> apiV := volumeToAPIType(v) <ide> apiV.Mountpoint = v.Path() <ide><path>daemon/list.go <ide> import ( <ide> "strconv" <ide> "strings" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <ide> "github.com/docker/docker/container" <ide> func (daemon *Daemon) foldFilter(view container.View, config *types.ContainerLis <ide> <ide> err = psFilters.WalkValues("health", func(value string) error { <ide> if !container.IsValidHealthString(value) { <del> return validationError{errors.Errorf("Unrecognised filter value for health: %s", value)} <add> return errdefs.InvalidParameter(errors.Errorf("Unrecognised filter value for health: %s", value)) <ide> } <ide> <ide> return nil <ide><path>daemon/logs.go <ide> import ( <ide> <ide> "golang.org/x/net/context" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/backend" <ide> containertypes "github.com/docker/docker/api/types/container" <ide> func (daemon *Daemon) ContainerLogs(ctx context.Context, containerName string, c <ide> }) <ide> <ide> if !(config.ShowStdout || config.ShowStderr) { <del> return nil, false, validationError{errors.New("You must choose at least one stream")} <add> return nil, false, errdefs.InvalidParameter(errors.New("You must choose at least one stream")) <ide> } <ide> container, err := daemon.GetContainer(containerName) <ide> if err != nil { <ide> return nil, false, err <ide> } <ide> <ide> if container.RemovalInProgress || container.Dead { <del> return nil, false, stateConflictError{errors.New("can not get logs from container which is dead or marked for removal")} <add> return nil, false, errdefs.Conflict(errors.New("can not get logs from container which is dead or marked for removal")) <ide> } <ide> <ide> if container.HostConfig.LogConfig.Type == "none" { <ide><path>daemon/names.go <ide> import ( <ide> "fmt" <ide> "strings" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/daemon/names" <ide> "github.com/docker/docker/pkg/namesgenerator" <ide> func (daemon *Daemon) generateIDAndName(name string) (string, string, error) { <ide> <ide> func (daemon *Daemon) reserveName(id, name string) (string, error) { <ide> if !validContainerNamePattern.MatchString(strings.TrimPrefix(name, "/")) { <del> return "", validationError{errors.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars)} <add> return "", errdefs.InvalidParameter(errors.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars)) <ide> } <ide> if name[0] != '/' { <ide> name = "/" + name <ide><path>daemon/network.go <ide> import ( <ide> "strings" <ide> "sync" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/network" <ide> clustertypes "github.com/docker/docker/daemon/cluster/provider" <ide> func (daemon *Daemon) FindUniqueNetwork(term string) (libnetwork.Network, error) <ide> case len(listByFullName) == 1: <ide> return listByFullName[0], nil <ide> case len(listByFullName) > 1: <del> return nil, fmt.Errorf("network %s is ambiguous (%d matches found based on name)", term, len(listByFullName)) <add> return nil, errdefs.InvalidParameter(errors.Errorf("network %s is ambiguous (%d matches found on name)", term, len(listByFullName))) <ide> case len(listByPartialID) == 1: <ide> return listByPartialID[0], nil <ide> case len(listByPartialID) > 1: <del> return nil, fmt.Errorf("network %s is ambiguous (%d matches found based on ID prefix)", term, len(listByPartialID)) <add> return nil, errdefs.InvalidParameter(errors.Errorf("network %s is ambiguous (%d matches found based on ID prefix)", term, len(listByPartialID))) <ide> } <del> return nil, libnetwork.ErrNoSuchNetwork(term) <add> <add> // Be very careful to change the error type here, the <add> // libnetwork.ErrNoSuchNetwork error is used by the controller <add> // to retry the creation of the network as managed through the swarm manager <add> return nil, errdefs.NotFound(libnetwork.ErrNoSuchNetwork(term)) <ide> } <ide> <ide> // GetNetworkByID function returns a network whose ID matches the given ID. <ide> func (daemon *Daemon) CreateNetwork(create types.NetworkCreateRequest) (*types.N <ide> func (daemon *Daemon) createNetwork(create types.NetworkCreateRequest, id string, agent bool) (*types.NetworkCreateResponse, error) { <ide> if runconfig.IsPreDefinedNetwork(create.Name) && !agent { <ide> err := fmt.Errorf("%s is a pre-defined network and cannot be created", create.Name) <del> return nil, notAllowedError{err} <add> return nil, errdefs.Forbidden(err) <ide> } <ide> <ide> var warning string <ide> func (daemon *Daemon) deleteLoadBalancerSandbox(n libnetwork.Network) { <ide> func (daemon *Daemon) deleteNetwork(nw libnetwork.Network, dynamic bool) error { <ide> if runconfig.IsPreDefinedNetwork(nw.Name()) && !dynamic { <ide> err := fmt.Errorf("%s is a pre-defined network and cannot be removed", nw.Name()) <del> return notAllowedError{err} <add> return errdefs.Forbidden(err) <ide> } <ide> <ide> if dynamic && !nw.Info().Dynamic() { <ide> func (daemon *Daemon) deleteNetwork(nw libnetwork.Network, dynamic bool) error { <ide> return nil <ide> } <ide> err := fmt.Errorf("%s is not a dynamic network", nw.Name()) <del> return notAllowedError{err} <add> return errdefs.Forbidden(err) <ide> } <ide> <ide> if err := nw.Delete(); err != nil { <ide><path>daemon/rename.go <ide> package daemon <ide> import ( <ide> "strings" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> dockercontainer "github.com/docker/docker/container" <ide> "github.com/docker/libnetwork" <ide> "github.com/pkg/errors" <ide> func (daemon *Daemon) ContainerRename(oldName, newName string) error { <ide> ) <ide> <ide> if oldName == "" || newName == "" { <del> return validationError{errors.New("Neither old nor new names may be empty")} <add> return errdefs.InvalidParameter(errors.New("Neither old nor new names may be empty")) <ide> } <ide> <ide> if newName[0] != '/' { <ide> func (daemon *Daemon) ContainerRename(oldName, newName string) error { <ide> oldIsAnonymousEndpoint := container.NetworkSettings.IsAnonymousEndpoint <ide> <ide> if oldName == newName { <del> return validationError{errors.New("Renaming a container with the same name as its current name")} <add> return errdefs.InvalidParameter(errors.New("Renaming a container with the same name as its current name")) <ide> } <ide> <ide> links := map[string]*dockercontainer.Container{} <ide> for k, v := range daemon.linkIndex.children(container) { <ide> if !strings.HasPrefix(k, oldName) { <del> return validationError{errors.Errorf("Linked container %s does not match parent %s", k, oldName)} <add> return errdefs.InvalidParameter(errors.Errorf("Linked container %s does not match parent %s", k, oldName)) <ide> } <ide> links[strings.TrimPrefix(k, oldName)] = v <ide> } <ide><path>daemon/start.go <ide> import ( <ide> "runtime" <ide> "time" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> containertypes "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/container" <ide> import ( <ide> // ContainerStart starts a container. <ide> func (daemon *Daemon) ContainerStart(name string, hostConfig *containertypes.HostConfig, checkpoint string, checkpointDir string) error { <ide> if checkpoint != "" && !daemon.HasExperimental() { <del> return validationError{errors.New("checkpoint is only supported in experimental mode")} <add> return errdefs.InvalidParameter(errors.New("checkpoint is only supported in experimental mode")) <ide> } <ide> <ide> container, err := daemon.GetContainer(name) <ide> func (daemon *Daemon) ContainerStart(name string, hostConfig *containertypes.Hos <ide> defer container.Unlock() <ide> <ide> if container.Paused { <del> return stateConflictError{errors.New("cannot start a paused container, try unpause instead")} <add> return errdefs.Conflict(errors.New("cannot start a paused container, try unpause instead")) <ide> } <ide> <ide> if container.Running { <ide> return containerNotModifiedError{running: true} <ide> } <ide> <ide> if container.RemovalInProgress || container.Dead { <del> return stateConflictError{errors.New("container is marked for removal and cannot be started")} <add> return errdefs.Conflict(errors.New("container is marked for removal and cannot be started")) <ide> } <ide> return nil <ide> } <ide> func (daemon *Daemon) ContainerStart(name string, hostConfig *containertypes.Hos <ide> logrus.Warn("DEPRECATED: Setting host configuration options when the container starts is deprecated and has been removed in Docker 1.12") <ide> oldNetworkMode := container.HostConfig.NetworkMode <ide> if err := daemon.setSecurityOptions(container, hostConfig); err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> if err := daemon.mergeAndVerifyLogConfig(&hostConfig.LogConfig); err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> if err := daemon.setHostConfig(container, hostConfig); err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> newNetworkMode := container.HostConfig.NetworkMode <ide> if string(oldNetworkMode) != string(newNetworkMode) { <ide> // if user has change the network mode on starting, clean up the <ide> // old networks. It is a deprecated feature and has been removed in Docker 1.12 <ide> container.NetworkSettings.Networks = nil <ide> if err := container.CheckpointTo(daemon.containersReplica); err != nil { <del> return systemError{err} <add> return errdefs.System(err) <ide> } <ide> } <ide> container.InitDNSHostConfig() <ide> } <ide> } else { <ide> if hostConfig != nil { <del> return validationError{errors.New("Supplying a hostconfig on start is not supported. It should be supplied on create")} <add> return errdefs.InvalidParameter(errors.New("Supplying a hostconfig on start is not supported. It should be supplied on create")) <ide> } <ide> } <ide> <ide> // check if hostConfig is in line with the current system settings. <ide> // It may happen cgroups are umounted or the like. <ide> if _, err = daemon.verifyContainerSettings(container.OS, container.HostConfig, nil, false); err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> // Adapt for old containers in case we have updates in this function and <ide> // old containers never have chance to call the new function in create stage. <ide> if hostConfig != nil { <ide> if err := daemon.adaptContainerSettings(container.HostConfig, false); err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> } <ide> <ide> func (daemon *Daemon) containerStart(container *container.Container, checkpoint <ide> } <ide> <ide> if container.RemovalInProgress || container.Dead { <del> return stateConflictError{errors.New("container is marked for removal and cannot be started")} <add> return errdefs.Conflict(errors.New("container is marked for removal and cannot be started")) <ide> } <ide> <ide> if checkpointDir != "" { <ide> // TODO(mlaventure): how would we support that? <del> return notAllowedError{errors.New("custom checkpointdir is not supported")} <add> return errdefs.Forbidden(errors.New("custom checkpointdir is not supported")) <ide> } <ide> <ide> // if we encounter an error during start we need to ensure that any other <ide> func (daemon *Daemon) containerStart(container *container.Container, checkpoint <ide> <ide> spec, err := daemon.createSpec(container) <ide> if err != nil { <del> return systemError{err} <add> return errdefs.System(err) <ide> } <ide> <ide> if resetRestartManager { <ide><path>daemon/start_unix.go <ide> import ( <ide> "path/filepath" <ide> <ide> "github.com/containerd/containerd/linux/runctypes" <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/container" <ide> "github.com/pkg/errors" <ide> ) <ide> func (daemon *Daemon) getRuntimeScript(container *container.Container) (string, <ide> name := container.HostConfig.Runtime <ide> rt := daemon.configStore.GetRuntime(name) <ide> if rt == nil { <del> return "", validationError{errors.Errorf("no such runtime '%s'", name)} <add> return "", errdefs.InvalidParameter(errors.Errorf("no such runtime '%s'", name)) <ide> } <ide> <ide> if len(rt.Args) > 0 { <ide><path>daemon/stop.go <ide> import ( <ide> "context" <ide> "time" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> containerpkg "github.com/docker/docker/container" <ide> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> func (daemon *Daemon) ContainerStop(name string, seconds *int) error { <ide> seconds = &stopTimeout <ide> } <ide> if err := daemon.containerStop(container, *seconds); err != nil { <del> return errors.Wrapf(systemError{err}, "cannot stop container: %s", name) <add> return errdefs.System(errors.Wrapf(err, "cannot stop container: %s", name)) <ide> } <ide> return nil <ide> } <ide><path>daemon/update.go <ide> import ( <ide> "context" <ide> "fmt" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types/container" <ide> "github.com/pkg/errors" <ide> ) <ide> func (daemon *Daemon) ContainerUpdate(name string, hostConfig *container.HostCon <ide> <ide> warnings, err = daemon.verifyContainerSettings(c.OS, hostConfig, nil, true) <ide> if err != nil { <del> return container.ContainerUpdateOKBody{Warnings: warnings}, validationError{err} <add> return container.ContainerUpdateOKBody{Warnings: warnings}, errdefs.InvalidParameter(err) <ide> } <ide> <ide> if err := daemon.update(name, hostConfig); err != nil { <ide> func (daemon *Daemon) update(name string, hostConfig *container.HostConfig) erro <ide> if err := daemon.containerd.UpdateResources(context.Background(), container.ID, toContainerdResources(hostConfig.Resources)); err != nil { <ide> restoreConfig = true <ide> // TODO: it would be nice if containerd responded with better errors here so we can classify this better. <del> return errCannotUpdate(container.ID, systemError{err}) <add> return errCannotUpdate(container.ID, errdefs.System(err)) <ide> } <ide> } <ide> <ide><path>daemon/volumes.go <ide> import ( <ide> "strings" <ide> "time" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> containertypes "github.com/docker/docker/api/types/container" <ide> mounttypes "github.com/docker/docker/api/types/mount" <ide> func (daemon *Daemon) registerMountPoints(container *container.Container, hostCo <ide> for _, cfg := range hostConfig.Mounts { <ide> mp, err := parser.ParseMountSpec(cfg) <ide> if err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> if binds[mp.Destination] { <ide><path>distribution/errors.go <ide> import ( <ide> "github.com/docker/distribution/registry/api/v2" <ide> "github.com/docker/distribution/registry/client" <ide> "github.com/docker/distribution/registry/client/auth" <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/distribution/xfer" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> func (e notFoundError) Cause() error { <ide> return e.cause <ide> } <ide> <del>type unknownError struct { <del> cause error <del>} <del> <del>func (e unknownError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e unknownError) Cause() error { <del> return e.cause <del>} <del> <del>func (e unknownError) Unknown() {} <del> <ide> // TranslatePullError is used to convert an error from a registry pull <ide> // operation to an error representing the entire pull operation. Any error <ide> // information which is not used by the returned error gets output to <ide> func TranslatePullError(err error, ref reference.Named) error { <ide> return TranslatePullError(v.Err, ref) <ide> } <ide> <del> return unknownError{err} <add> return errdefs.Unknown(err) <ide> } <ide> <ide> // continueOnError returns true if we should fallback to the next endpoint <ide><path>libcontainerd/client_daemon.go <ide> import ( <ide> "github.com/containerd/containerd/archive" <ide> "github.com/containerd/containerd/cio" <ide> "github.com/containerd/containerd/content" <del> "github.com/containerd/containerd/errdefs" <add> containerderrors "github.com/containerd/containerd/errdefs" <ide> "github.com/containerd/containerd/images" <ide> "github.com/containerd/containerd/linux/runctypes" <ide> "github.com/containerd/typeurl" <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/pkg/ioutils" <ide> "github.com/opencontainers/image-spec/specs-go/v1" <ide> specs "github.com/opencontainers/runtime-spec/specs-go" <ide> func (c *client) Create(ctx context.Context, id string, ociSpec *specs.Spec, run <ide> <ide> bdir, err := prepareBundleDir(filepath.Join(c.stateDir, id), ociSpec) <ide> if err != nil { <del> return wrapSystemError(errors.Wrap(err, "prepare bundle dir failed")) <add> return errdefs.System(errors.Wrap(err, "prepare bundle dir failed")) <ide> } <ide> <ide> c.logger.WithField("bundle", bdir).WithField("root", ociSpec.Root.Path).Debug("bundle dir created") <ide> func (c *client) CreateCheckpoint(ctx context.Context, containerID, checkpointDi <ide> <ide> b, err := content.ReadBlob(ctx, c.remote.ContentStore(), img.Target().Digest) <ide> if err != nil { <del> return wrapSystemError(errors.Wrapf(err, "failed to retrieve checkpoint data")) <add> return errdefs.System(errors.Wrapf(err, "failed to retrieve checkpoint data")) <ide> } <ide> var index v1.Index <ide> if err := json.Unmarshal(b, &index); err != nil { <del> return wrapSystemError(errors.Wrapf(err, "failed to decode checkpoint data")) <add> return errdefs.System(errors.Wrapf(err, "failed to decode checkpoint data")) <ide> } <ide> <ide> var cpDesc *v1.Descriptor <ide> func (c *client) CreateCheckpoint(ctx context.Context, containerID, checkpointDi <ide> } <ide> } <ide> if cpDesc == nil { <del> return wrapSystemError(errors.Wrapf(err, "invalid checkpoint")) <add> return errdefs.System(errors.Wrapf(err, "invalid checkpoint")) <ide> } <ide> <ide> rat, err := c.remote.ContentStore().ReaderAt(ctx, cpDesc.Digest) <ide> if err != nil { <del> return wrapSystemError(errors.Wrapf(err, "failed to get checkpoint reader")) <add> return errdefs.System(errors.Wrapf(err, "failed to get checkpoint reader")) <ide> } <ide> defer rat.Close() <ide> _, err = archive.Apply(ctx, checkpointDir, content.NewReader(rat)) <ide> if err != nil { <del> return wrapSystemError(errors.Wrapf(err, "failed to read checkpoint reader")) <add> return errdefs.System(errors.Wrapf(err, "failed to read checkpoint reader")) <ide> } <ide> <ide> return err <ide> func wrapError(err error) error { <ide> switch { <ide> case err == nil: <ide> return nil <del> case errdefs.IsNotFound(err): <del> return wrapNotFoundError(err) <add> case containerderrors.IsNotFound(err): <add> return errdefs.NotFound(err) <ide> } <ide> <ide> msg := err.Error() <ide> for _, s := range []string{"container does not exist", "not found", "no such container"} { <ide> if strings.Contains(msg, s) { <del> return wrapNotFoundError(err) <add> return errdefs.NotFound(err) <ide> } <ide> } <ide> return err <ide><path>libcontainerd/errors.go <ide> package libcontainerd <ide> <del>import "errors" <add>import ( <add> "errors" <ide> <del>type liberr struct { <del> err error <del>} <add> "github.com/docker/docker/api/errdefs" <add>) <ide> <del>func (e liberr) Error() string { <del> return e.err.Error() <del>} <add>func newNotFoundError(err string) error { return errdefs.NotFound(errors.New(err)) } <ide> <del>func (e liberr) Cause() error { <del> return e.err <del>} <add>func newInvalidParameterError(err string) error { return errdefs.InvalidParameter(errors.New(err)) } <ide> <del>type notFoundErr struct { <del> liberr <del>} <del> <del>func (notFoundErr) NotFound() {} <del> <del>func newNotFoundError(err string) error { return notFoundErr{liberr{errors.New(err)}} } <del>func wrapNotFoundError(err error) error { return notFoundErr{liberr{err}} } <del> <del>type invalidParamErr struct { <del> liberr <del>} <del> <del>func (invalidParamErr) InvalidParameter() {} <del> <del>func newInvalidParameterError(err string) error { return invalidParamErr{liberr{errors.New(err)}} } <del> <del>type conflictErr struct { <del> liberr <del>} <del> <del>func (conflictErr) ConflictErr() {} <del> <del>func newConflictError(err string) error { return conflictErr{liberr{errors.New(err)}} } <del> <del>type sysErr struct { <del> liberr <del>} <del> <del>func wrapSystemError(err error) error { return sysErr{liberr{err}} } <add>func newConflictError(err string) error { return errdefs.Conflict(errors.New(err)) } <ide><path>plugin/backend_linux.go <ide> import ( <ide> <ide> "github.com/docker/distribution/manifest/schema2" <ide> "github.com/docker/distribution/reference" <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <ide> "github.com/docker/docker/distribution" <ide> func (pm *Manager) Privileges(ctx context.Context, ref reference.Named, metaHead <ide> } <ide> var config types.PluginConfig <ide> if err := json.Unmarshal(cs.config, &config); err != nil { <del> return nil, systemError{err} <add> return nil, errdefs.System(err) <ide> } <ide> <ide> return computePrivileges(config), nil <ide> func (pm *Manager) Upgrade(ctx context.Context, ref reference.Named, name string <ide> <ide> // revalidate because Pull is public <ide> if _, err := reference.ParseNormalizedNamed(name); err != nil { <del> return errors.Wrapf(validationError{err}, "failed to parse %q", name) <add> return errors.Wrapf(errdefs.InvalidParameter(err), "failed to parse %q", name) <ide> } <ide> <ide> tmpRootFSDir, err := ioutil.TempDir(pm.tmpDir(), ".rootfs") <ide> if err != nil { <del> return errors.Wrap(systemError{err}, "error preparing upgrade") <add> return errors.Wrap(errdefs.System(err), "error preparing upgrade") <ide> } <ide> defer os.RemoveAll(tmpRootFSDir) <ide> <ide> func (pm *Manager) Pull(ctx context.Context, ref reference.Named, name string, m <ide> // revalidate because Pull is public <ide> nameref, err := reference.ParseNormalizedNamed(name) <ide> if err != nil { <del> return errors.Wrapf(validationError{err}, "failed to parse %q", name) <add> return errors.Wrapf(errdefs.InvalidParameter(err), "failed to parse %q", name) <ide> } <ide> name = reference.FamiliarString(reference.TagNameOnly(nameref)) <ide> <ide> if err := pm.config.Store.validateName(name); err != nil { <del> return validationError{err} <add> return errdefs.InvalidParameter(err) <ide> } <ide> <ide> tmpRootFSDir, err := ioutil.TempDir(pm.tmpDir(), ".rootfs") <ide> if err != nil { <del> return errors.Wrap(systemError{err}, "error preparing pull") <add> return errors.Wrap(errdefs.System(err), "error preparing pull") <ide> } <ide> defer os.RemoveAll(tmpRootFSDir) <ide> <ide><path>plugin/errors.go <ide> func (name errDisabled) Error() string { <ide> <ide> func (name errDisabled) Conflict() {} <ide> <del>type validationError struct { <del> cause error <del>} <del> <del>func (e validationError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (validationError) Conflict() {} <del> <del>func (e validationError) Cause() error { <del> return e.cause <del>} <del> <del>type systemError struct { <del> cause error <del>} <del> <del>func (e systemError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (systemError) SystemError() {} <del> <del>func (e systemError) Cause() error { <del> return e.cause <del>} <del> <ide> type invalidFilter struct { <ide> filter string <ide> value []string <ide><path>plugin/manager_linux.go <ide> import ( <ide> "path/filepath" <ide> "time" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/daemon/initlayer" <ide> "github.com/docker/docker/pkg/containerfs" <ide> func (pm *Manager) upgradePlugin(p *v2.Plugin, configDigest digest.Digest, blobs <ide> // This could happen if the plugin was disabled with `-f` with active mounts. <ide> // If there is anything in `orig` is still mounted, this should error out. <ide> if err := mount.RecursiveUnmount(orig); err != nil { <del> return systemError{err} <add> return errdefs.System(err) <ide> } <ide> <ide> backup := orig + "-old" <ide> if err := os.Rename(orig, backup); err != nil { <del> return errors.Wrap(systemError{err}, "error backing up plugin data before upgrade") <add> return errors.Wrap(errdefs.System(err), "error backing up plugin data before upgrade") <ide> } <ide> <ide> defer func() { <ide> func (pm *Manager) upgradePlugin(p *v2.Plugin, configDigest digest.Digest, blobs <ide> }() <ide> <ide> if err := os.Rename(tmpRootFSDir, orig); err != nil { <del> return errors.Wrap(systemError{err}, "error upgrading") <add> return errors.Wrap(errdefs.System(err), "error upgrading") <ide> } <ide> <ide> p.PluginObj.Config = config <ide> func (pm *Manager) setupNewPlugin(configDigest digest.Digest, blobsums []digest. <ide> // createPlugin creates a new plugin. take lock before calling. <ide> func (pm *Manager) createPlugin(name string, configDigest digest.Digest, blobsums []digest.Digest, rootFSDir string, privileges *types.PluginPrivileges, opts ...CreateOpt) (p *v2.Plugin, err error) { <ide> if err := pm.config.Store.validateName(name); err != nil { // todo: this check is wrong. remove store <del> return nil, validationError{err} <add> return nil, errdefs.InvalidParameter(err) <ide> } <ide> <ide> config, err := pm.setupNewPlugin(configDigest, blobsums, privileges) <ide><path>plugin/store.go <ide> import ( <ide> "strings" <ide> <ide> "github.com/docker/distribution/reference" <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/pkg/plugingetter" <ide> "github.com/docker/docker/pkg/plugins" <ide> "github.com/docker/docker/plugin/v2" <ide> func (ps *Store) Get(name, capability string, mode int) (plugingetter.CompatPlug <ide> if errors.Cause(err) == plugins.ErrNotFound { <ide> return nil, errNotFound(name) <ide> } <del> return nil, errors.Wrap(systemError{err}, "legacy plugin") <add> return nil, errors.Wrap(errdefs.System(err), "legacy plugin") <ide> } <ide> <ide> // GetAllManagedPluginsByCap returns a list of managed plugins matching the given capability. <ide> func (ps *Store) GetAllByCap(capability string) ([]plugingetter.CompatPlugin, er <ide> if allowV1PluginsFallback { <ide> pl, err := plugins.GetAll(capability) <ide> if err != nil { <del> return nil, errors.Wrap(systemError{err}, "legacy plugin") <add> return nil, errors.Wrap(errdefs.System(err), "legacy plugin") <ide> } <ide> for _, p := range pl { <ide> result = append(result, p) <ide><path>registry/auth.go <ide> import ( <ide> "github.com/docker/distribution/registry/client/auth" <ide> "github.com/docker/distribution/registry/client/auth/challenge" <ide> "github.com/docker/distribution/registry/client/transport" <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> registrytypes "github.com/docker/docker/api/types/registry" <ide> "github.com/pkg/errors" <ide> func loginV1(authConfig *types.AuthConfig, apiEndpoint APIEndpoint, userAgent st <ide> logrus.Debugf("attempting v1 login to registry endpoint %s", serverAddress) <ide> <ide> if serverAddress == "" { <del> return "", "", systemError{errors.New("server Error: Server Address not set")} <add> return "", "", errdefs.System(errors.New("server Error: Server Address not set")) <ide> } <ide> <ide> req, err := http.NewRequest("GET", serverAddress+"users/", nil) <ide> func loginV1(authConfig *types.AuthConfig, apiEndpoint APIEndpoint, userAgent st <ide> defer resp.Body.Close() <ide> body, err := ioutil.ReadAll(resp.Body) <ide> if err != nil { <del> return "", "", systemError{err} <add> return "", "", errdefs.System(err) <ide> } <ide> <ide> switch resp.StatusCode { <ide> case http.StatusOK: <ide> return "Login Succeeded", "", nil <ide> case http.StatusUnauthorized: <del> return "", "", unauthorizedError{errors.New("Wrong login/password, please try again")} <add> return "", "", errdefs.Unauthorized(errors.New("Wrong login/password, please try again")) <ide> case http.StatusForbidden: <ide> // *TODO: Use registry configuration to determine what this says, if anything? <del> return "", "", notActivatedError{errors.Errorf("Login: Account is not active. Please see the documentation of the registry %s for instructions how to activate it.", serverAddress)} <add> return "", "", errdefs.Forbidden(errors.Errorf("Login: Account is not active. Please see the documentation of the registry %s for instructions how to activate it.", serverAddress)) <ide> case http.StatusInternalServerError: <ide> logrus.Errorf("%s returned status code %d. Response Body :\n%s", req.URL.String(), resp.StatusCode, body) <del> return "", "", systemError{errors.New("Internal Server Error")} <add> return "", "", errdefs.System(errors.New("Internal Server Error")) <ide> } <del> return "", "", systemError{errors.Errorf("Login: %s (Code: %d; Headers: %s)", body, <del> resp.StatusCode, resp.Header)} <add> return "", "", errdefs.System(errors.Errorf("Login: %s (Code: %d; Headers: %s)", body, <add> resp.StatusCode, resp.Header)) <ide> } <ide> <ide> type loginCredentialStore struct { <ide><path>registry/errors.go <ide> import ( <ide> "net/url" <ide> <ide> "github.com/docker/distribution/registry/api/errcode" <add> "github.com/docker/docker/api/errdefs" <ide> ) <ide> <ide> type notFoundError string <ide> func (e notFoundError) Error() string { <ide> <ide> func (notFoundError) NotFound() {} <ide> <del>type validationError struct { <del> cause error <del>} <del> <del>func (e validationError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e validationError) InvalidParameter() {} <del> <del>func (e validationError) Cause() error { <del> return e.cause <del>} <del> <del>type unauthorizedError struct { <del> cause error <del>} <del> <del>func (e unauthorizedError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e unauthorizedError) Unauthorized() {} <del> <del>func (e unauthorizedError) Cause() error { <del> return e.cause <del>} <del> <del>type systemError struct { <del> cause error <del>} <del> <del>func (e systemError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e systemError) SystemError() {} <del> <del>func (e systemError) Cause() error { <del> return e.cause <del>} <del> <del>type notActivatedError struct { <del> cause error <del>} <del> <del>func (e notActivatedError) Error() string { <del> return e.cause.Error() <del>} <del> <del>func (e notActivatedError) Forbidden() {} <del> <del>func (e notActivatedError) Cause() error { <del> return e.cause <del>} <del> <ide> func translateV2AuthError(err error) error { <ide> switch e := err.(type) { <ide> case *url.Error: <ide> switch e2 := e.Err.(type) { <ide> case errcode.Error: <ide> switch e2.Code { <ide> case errcode.ErrorCodeUnauthorized: <del> return unauthorizedError{err} <add> return errdefs.Unauthorized(err) <ide> } <ide> } <ide> } <ide><path>registry/service.go <ide> import ( <ide> <ide> "github.com/docker/distribution/reference" <ide> "github.com/docker/distribution/registry/client/auth" <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> registrytypes "github.com/docker/docker/api/types/registry" <ide> "github.com/pkg/errors" <ide> func (s *DefaultService) Auth(ctx context.Context, authConfig *types.AuthConfig, <ide> } <ide> u, err := url.Parse(serverAddress) <ide> if err != nil { <del> return "", "", validationError{errors.Errorf("unable to parse server address: %v", err)} <add> return "", "", errdefs.InvalidParameter(errors.Errorf("unable to parse server address: %v", err)) <ide> } <ide> <ide> endpoints, err := s.LookupPushEndpoints(u.Host) <ide> if err != nil { <del> return "", "", validationError{err} <add> return "", "", errdefs.InvalidParameter(err) <ide> } <ide> <ide> for _, endpoint := range endpoints { <ide><path>registry/session.go <ide> import ( <ide> <ide> "github.com/docker/distribution/reference" <ide> "github.com/docker/distribution/registry/api/errcode" <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/api/types" <ide> registrytypes "github.com/docker/docker/api/types/registry" <ide> "github.com/docker/docker/pkg/ioutils" <ide> func shouldRedirect(response *http.Response) bool { <ide> // SearchRepositories performs a search against the remote repository <ide> func (r *Session) SearchRepositories(term string, limit int) (*registrytypes.SearchResults, error) { <ide> if limit < 1 || limit > 100 { <del> return nil, validationError{errors.Errorf("Limit %d is outside the range of [1, 100]", limit)} <add> return nil, errdefs.InvalidParameter(errors.Errorf("Limit %d is outside the range of [1, 100]", limit)) <ide> } <ide> logrus.Debugf("Index server: %s", r.indexEndpoint) <ide> u := r.indexEndpoint.String() + "search?q=" + url.QueryEscape(term) + "&n=" + url.QueryEscape(fmt.Sprintf("%d", limit)) <ide> <ide> req, err := http.NewRequest("GET", u, nil) <ide> if err != nil { <del> return nil, errors.Wrap(validationError{err}, "Error building request") <add> return nil, errors.Wrap(errdefs.InvalidParameter(err), "Error building request") <ide> } <ide> // Have the AuthTransport send authentication, when logged in. <ide> req.Header.Set("X-Docker-Token", "true") <ide> res, err := r.client.Do(req) <ide> if err != nil { <del> return nil, systemError{err} <add> return nil, errdefs.System(err) <ide> } <ide> defer res.Body.Close() <ide> if res.StatusCode != 200 { <ide><path>volume/local/local.go <ide> import ( <ide> "strings" <ide> "sync" <ide> <add> "github.com/docker/docker/api/errdefs" <ide> "github.com/docker/docker/daemon/names" <ide> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/mount" <ide> func (r *Root) Name() string { <ide> return volume.DefaultDriverName <ide> } <ide> <del>type systemError struct { <del> err error <del>} <del> <del>func (e systemError) Error() string { <del> return e.err.Error() <del>} <del> <del>func (e systemError) SystemError() {} <del> <del>func (e systemError) Cause() error { <del> return e.err <del>} <del> <ide> // Create creates a new volume.Volume with the provided name, creating <ide> // the underlying directory tree required for this volume in the <ide> // process. <ide> func (r *Root) Create(name string, opts map[string]string) (volume.Volume, error <ide> <ide> path := r.DataPath(name) <ide> if err := idtools.MkdirAllAndChown(path, 0755, r.rootIDs); err != nil { <del> return nil, errors.Wrapf(systemError{err}, "error while creating volume path '%s'", path) <add> return nil, errors.Wrapf(errdefs.System(err), "error while creating volume path '%s'", path) <ide> } <ide> <ide> var err error <ide> func (r *Root) Create(name string, opts map[string]string) (volume.Volume, error <ide> return nil, err <ide> } <ide> if err = ioutil.WriteFile(filepath.Join(filepath.Dir(path), "opts.json"), b, 600); err != nil { <del> return nil, errors.Wrap(systemError{err}, "error while persisting volume options") <add> return nil, errdefs.System(errors.Wrap(err, "error while persisting volume options")) <ide> } <ide> } <ide> <ide> func (r *Root) Remove(v volume.Volume) error { <ide> <ide> lv, ok := v.(*localVolume) <ide> if !ok { <del> return systemError{errors.Errorf("unknown volume type %T", v)} <add> return errdefs.System(errors.Errorf("unknown volume type %T", v)) <ide> } <ide> <ide> if lv.active.count > 0 { <del> return systemError{errors.Errorf("volume has active mounts")} <add> return errdefs.System(errors.Errorf("volume has active mounts")) <ide> } <ide> <ide> if err := lv.unmount(); err != nil { <ide> func (r *Root) Remove(v volume.Volume) error { <ide> } <ide> <ide> if !r.scopedPath(realPath) { <del> return systemError{errors.Errorf("Unable to remove a directory of out the Docker root %s: %s", r.scope, realPath)} <add> return errdefs.System(errors.Errorf("Unable to remove a directory of out the Docker root %s: %s", r.scope, realPath)) <ide> } <ide> <ide> if err := removePath(realPath); err != nil { <ide> func removePath(path string) error { <ide> if os.IsNotExist(err) { <ide> return nil <ide> } <del> return errors.Wrapf(systemError{err}, "error removing volume path '%s'", path) <add> return errdefs.System(errors.Wrapf(err, "error removing volume path '%s'", path)) <ide> } <ide> return nil <ide> } <ide> func (v *localVolume) Mount(id string) (string, error) { <ide> if v.opts != nil { <ide> if !v.active.mounted { <ide> if err := v.mount(); err != nil { <del> return "", systemError{err} <add> return "", errdefs.System(err) <ide> } <ide> v.active.mounted = true <ide> } <ide> func (v *localVolume) unmount() error { <ide> if v.opts != nil { <ide> if err := mount.Unmount(v.path); err != nil { <ide> if mounted, mErr := mount.Mounted(v.path); mounted || mErr != nil { <del> return errors.Wrapf(systemError{err}, "error while unmounting volume path '%s'", v.path) <add> return errdefs.System(errors.Wrapf(err, "error while unmounting volume path '%s'", v.path)) <ide> } <ide> } <ide> v.active.mounted = false
65
Java
Java
compare suffix patterns by length
0d3e5db3fff484a1d2812086044660b82c19c910
<ide><path>spring-core/src/main/java/org/springframework/util/AntPathMatcher.java <ide> else if (pattern2EqualsPath) { <ide> return 1; <ide> } <ide> <del> if (info1.isPrefixPattern() && info2.getDoubleWildcards() == 0) { <add> if (info1.isPrefixPattern() && info2.isPrefixPattern()) { <add> return info2.getLength() - info1.getLength(); <add> } <add> else if (info1.isPrefixPattern() && info2.getDoubleWildcards() == 0) { <ide> return 1; <ide> } <ide> else if (info2.isPrefixPattern() && info1.getDoubleWildcards() == 0) { <ide><path>spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java <ide> public void patternComparator() { <ide> assertThat(comparator.compare("/hotels/**", "/hotels/{hotel}/bookings/{booking}/cutomers/{customer}")).isEqualTo(1); <ide> assertThat(comparator.compare("/hotels/foo/bar/**", "/hotels/{hotel}")).isEqualTo(1); <ide> assertThat(comparator.compare("/hotels/{hotel}", "/hotels/foo/bar/**")).isEqualTo(-1); <del> assertThat(comparator.compare("/hotels/**/bookings/**", "/hotels/**")).isEqualTo(2); <del> assertThat(comparator.compare("/hotels/**", "/hotels/**/bookings/**")).isEqualTo(-2); <add> <add> // gh-23125 <add> assertThat(comparator.compare("/hotels/*/bookings/**", "/hotels/**")).isEqualTo(-11); <ide> <ide> // SPR-8683 <ide> assertThat(comparator.compare("/**", "/hotels/{hotel}")).isEqualTo(1);
2
Python
Python
fix error in seeding elastic `log_id` template
c97f0b3da09079778dc9317030cfacc5df01e88c
<ide><path>airflow/utils/db.py <ide> def log_template_exists(): <ide> session.add( <ide> LogTemplate( <ide> filename="{{ ti.dag_id }}/{{ ti.task_id }}/{{ ts }}/{{ try_number }}.log", <del> elasticsearch_id="{dag_id}-{task_id}-{execution_date}-{try_number}", <add> elasticsearch_id="{dag_id}_{task_id}_{execution_date}_{try_number}", <ide> ) <ide> ) <ide> session.flush() <add> wrong_log_id = "{dag_id}-{task_id}-{execution_date}-{try_number}" <add> correct_log_id = "{dag_id}_{task_id}_{execution_date}_{try_number}" <add> session.query(LogTemplate).filter(LogTemplate.elasticsearch_id == wrong_log_id).update( <add> {LogTemplate.elasticsearch_id: correct_log_id}, synchronize_session='fetch' <add> ) <ide> <ide> # Before checking if the _current_ value exists, we need to check if the old config value we upgraded in <ide> # place exists!
1