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
Javascript
Javascript
remove resolve rule
7ecf675834d392e8aeb90824a9f2db8a0a948b12
<ide><path>packages/next/build/webpack-config.js <ide> export default async function getBaseWebpackConfig (dir, {dev = false, isServer <ide> // Disable .mjs for node_modules bundling <ide> extensions: isServer ? ['.wasm', '.js', '.mjs', '.jsx', '.json'] : ['.wasm', '.mjs', '.js', '.jsx', '.json'], <ide> modules: [ <del> NEXT_PROJECT_ROOT_NODE_MODULES, <ide> 'node_modules', <ide> ...nodePathList // Support for NODE_PATH environment variable <ide> ],
1
Python
Python
ensure default fairness maps to `sched_fair`
0db172ef3b6b1771c763e0ec7937bdba63dacbc8
<ide><path>celery/concurrency/asynpool.py <ide> def unpack_from(fmt, iobuf, unpack=unpack): # noqa <ide> <ide> SCHED_STRATEGIES = { <ide> None: SCHED_STRATEGY_FAIR, <add> 'default': SCHED_STRATEGY_FAIR, <ide> 'fast': SCHED_STRATEGY_FCFS, <ide> 'fcfs': SCHED_STRATEGY_FCFS, <ide> 'fair': SCHED_STRATEGY_FAIR,
1
Javascript
Javascript
update example to use a module
28310583a9f746f920f47d04e289d1819edf12d0
<ide><path>src/ng/http.js <ide> function $HttpProvider() { <ide> * <ide> * <ide> * @example <del><example> <add><example module="httpExample"> <ide> <file name="index.html"> <del> <div ng-controller="FetchCtrl"> <add> <div ng-controller="FetchController"> <ide> <select ng-model="method"> <ide> <option>GET</option> <ide> <option>JSONP</option> <ide> function $HttpProvider() { <ide> </div> <ide> </file> <ide> <file name="script.js"> <del> function FetchCtrl($scope, $http, $templateCache) { <del> $scope.method = 'GET'; <del> $scope.url = 'http-hello.html'; <del> <del> $scope.fetch = function() { <del> $scope.code = null; <del> $scope.response = null; <del> <del> $http({method: $scope.method, url: $scope.url, cache: $templateCache}). <del> success(function(data, status) { <del> $scope.status = status; <del> $scope.data = data; <del> }). <del> error(function(data, status) { <del> $scope.data = data || "Request failed"; <del> $scope.status = status; <del> }); <del> }; <add> angular.module('httpExample', []) <add> .controller('FetchController', ['$scope', '$http', '$templateCache', <add> function($scope, $http, $templateCache) { <add> $scope.method = 'GET'; <add> $scope.url = 'http-hello.html'; <add> <add> $scope.fetch = function() { <add> $scope.code = null; <add> $scope.response = null; <add> <add> $http({method: $scope.method, url: $scope.url, cache: $templateCache}). <add> success(function(data, status) { <add> $scope.status = status; <add> $scope.data = data; <add> }). <add> error(function(data, status) { <add> $scope.data = data || "Request failed"; <add> $scope.status = status; <add> }); <add> }; <ide> <del> $scope.updateModel = function(method, url) { <del> $scope.method = method; <del> $scope.url = url; <del> }; <del> } <add> $scope.updateModel = function(method, url) { <add> $scope.method = method; <add> $scope.url = url; <add> }; <add> }]); <ide> </file> <ide> <file name="http-hello.html"> <ide> Hello, $http!
1
Go
Go
verify endpoint.info() before accessing it
54d22cbd9a04a965c935a693bf403d2c87109b5a
<ide><path>api/server/router/network/network_routes.go <ide> func buildNetworkResource(nw libnetwork.Network) *types.NetworkResource { <ide> <ide> epl := nw.Endpoints() <ide> for _, e := range epl { <del> sb := e.Info().Sandbox() <add> ei := e.Info() <add> if ei == nil { <add> continue <add> } <add> sb := ei.Sandbox() <ide> if sb == nil { <ide> continue <ide> } <ide> func buildEndpointResource(e libnetwork.Endpoint) types.EndpointResource { <ide> } <ide> <ide> er.EndpointID = e.ID() <del> if iface := e.Info().Iface(); iface != nil { <add> ei := e.Info() <add> if ei == nil { <add> return er <add> } <add> <add> if iface := ei.Iface(); iface != nil { <ide> if mac := iface.MacAddress(); mac != nil { <ide> er.MacAddress = mac.String() <ide> } <ide><path>daemon/container_unix.go <ide> func (container *Container) disconnectFromNetwork(n libnetwork.Network) error { <ide> ) <ide> <ide> s := func(current libnetwork.Endpoint) bool { <del> if sb := current.Info().Sandbox(); sb != nil { <add> epInfo := current.Info() <add> if epInfo == nil { <add> return false <add> } <add> if sb := epInfo.Sandbox(); sb != nil { <ide> if sb.ContainerID() == container.ID { <ide> ep = current <ide> sbox = sb
2
Javascript
Javascript
change concatenation to template literal
d4fbffded49b81dd599c803d1db6914c1f97bc88
<ide><path>test/parallel/test-fs-copyfile.js <ide> assert.throws(() => { <ide> <ide> // Throws if the source does not exist. <ide> assert.throws(() => { <del> fs.copyFileSync(src + '__does_not_exist', dest, COPYFILE_EXCL); <add> fs.copyFileSync(`${src}__does_not_exist`, dest, COPYFILE_EXCL); <ide> }, /^Error: ENOENT: no such file or directory, copyfile/); <ide> <ide> // Copies asynchronously.
1
Javascript
Javascript
fix name collisions between various tests
ee7209fe2676f836ef39ff77e3aa5c46572e817b
<ide><path>test/service/compilerSpec.js <ide> describe('$compile', function() { <ide> })); <ide> <ide> <del> it('should allow creation of new isolated scopes', inject(function($rootScope, $compile, log) { <add> it('should allow creation of new isolated scopes for directives', inject( <add> function($rootScope, $compile, log) { <ide> element = $compile('<div><span iscope><a log></a></span></div>')($rootScope); <ide> expect(log).toEqual('LOG; log-002-001; 002'); <ide> $rootScope.name = 'abc'; <ide> describe('$compile', function() { <ide> })); <ide> <ide> <del> it('should allow creation of new isolated scopes', inject( <add> it('should allow creation of new isolated scopes for directives with templates', inject( <ide> function($rootScope, $compile, log, $httpBackend) { <ide> $httpBackend.expect('GET', 'tiscope.html').respond('<a log></a>'); <ide> element = $compile('<div><span tiscope></span></div>')($rootScope); <ide> describe('$compile', function() { <ide> })); <ide> <ide> <del> it('should correctly create the scope hierachy properly', inject( <add> it('should correctly create the scope hierachy', inject( <ide> function($rootScope, $compile, log) { <ide> element = $compile( <ide> '<div>' + //1
1
PHP
PHP
fix httpsocket mishandling encoded uris
6aaac6b7e2f5b71ce649df9a109f83d17b3eb61f
<ide><path>lib/Cake/Network/Http/HttpSocket.php <ide> public function request($request = array()) { <ide> } <ide> <ide> if ($this->request['redirect'] && $this->response->isRedirect()) { <del> $request['uri'] = trim(urldecode($this->response->getHeader('Location')), '='); <add> $location = trim($this->response->getHeader('Location'), '='); <add> $request['uri'] = str_replace('%2F', '/', $location); <ide> $request['redirect'] = is_int($this->request['redirect']) ? $this->request['redirect'] - 1 : $this->request['redirect']; <ide> $this->response = $this->request($request); <ide> } <ide><path>lib/Cake/Test/Case/Network/Http/HttpSocketTest.php <ide> public function testRequestWithRedirectUrlEncoded() { <ide> 'uri' => 'http://localhost/oneuri', <ide> 'redirect' => 1 <ide> ); <del> $serverResponse1 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://i.cmpnet.com%2Ftechonline%2Fpdf%2Fa.pdf=\r\n\r\n"; <add> $serverResponse1 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://i.cmpnet.com%2Ftechonline%2Fpdf%2Fa+b.pdf=\r\n\r\n"; <ide> $serverResponse2 = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>You have been redirected</h1>"; <ide> <ide> $this->Socket->expects($this->at(1)) <ide> public function testRequestWithRedirectUrlEncoded() { <ide> ->method('write') <ide> ->with($this->logicalAnd( <ide> $this->stringContains('Host: i.cmpnet.com'), <del> $this->stringContains('GET /techonline/pdf/a.pdf') <add> $this->stringContains('GET /techonline/pdf/a+b.pdf') <ide> )); <ide> <ide> $this->Socket->expects($this->at(4))
2
Javascript
Javascript
remove unnecessary condition
411728b146345adb99960fd3bff38e1172bfba7f
<ide><path>lib/optimize/InnerGraphPlugin.js <ide> class InnerGraphPlugin { <ide> decl.init && <ide> decl.id.type === "Identifier" <ide> ) { <del> if ( <del> decl.init.type === "FunctionExpression" || <del> decl.init.type === "ArrowFunctionExpression" <del> ) { <del> const name = decl.id.name; <del> const fn = InnerGraph.tagTopLevelSymbol(parser, name); <del> declWithTopLevelSymbol.set(decl, fn); <del> return true; <del> } <ide> if (isPure(decl.init, parser, decl.id.range[1])) { <ide> const name = decl.id.name; <ide> const fn = InnerGraph.tagTopLevelSymbol(parser, name);
1
Text
Text
add comments about `nativeonly` props
bb79d034d2d415a280f391519c836a861c2dd31e
<ide><path>docs/NativeComponentsIOS.md <ide> MapView.propTypes = { <ide> <ide> Here you can see that the shape of the region is explicit in the JS documentation - ideally we could codegen some of this stuff, but that's not happening yet. <ide> <add>Sometimes you'll have some special properties that you need to expose for the native component, but don't actually want them as part of the API for the associated React component. For example, `Switch` has a custom `onChange` handler for the raw native event, and exposes an `onValueChange` handler property that is invoked with just the boolean value rather than the raw event. Since you don't want these native only properties to be part of the API, you don't want to put them in `propTypes`, but if you don't you'll get an error. The solution is simply to call them out via the `nativeOnly` option, e.g. <add> <add>```javascript <add>var RCTSwitch = requireNativeComponent('RCTSwitch', Switch, { <add> nativeOnly: { onChange: true } <add>}); <add>``` <add> <ide> ## Events <ide> <ide> So now we have a native map component that we can control easily from JS, but how do we deal with events from the user, like pinch-zooms or panning to change the visible region? The key is to make the `RCTMapManager` a delegate for all the views it vends, and forward the events to JS via the event dispatcher. This looks like so (simplified from the full implementation):
1
Text
Text
extend bash-head and add fixes
8f1af189c0d3d9e2b5d0f625ef92faa429c7dda4
<ide><path>guide/russian/bash/bash-head/index.md <ide> --- <ide> title: Bash Head <del>localeTitle: Голова баша <add>localeTitle: Баш Хэд <ide> --- <del>## Команда Bash <ide> <del>Head используется для печати первых десяти строк (по умолчанию) или любого другого количества, указанного для файла или файлов. Cat используется для последовательного чтения файла и печати его на стандартный вывод. т.е. распечатывает все содержимое всего файла. Это не всегда необходимо, возможно, вы просто хотите проверить содержимое файла, чтобы убедиться, что он правильный, или убедиться, что он действительно не пуст. Команда head позволяет просматривать первые N строк файла. <add>## Команда Bash: head(хэд) <add> <add><strong>Хэд(head)</strong> используется для печати первых десяти строк (по умолчанию) или любой другой суммы, указанной в файле или файлах. Команда <strong>Сat</strong>(кэт) используется для последовательного чтения файла и печати его на стандартный вывод. т.е. распечатывает все содержимое всего файла. - это не всегда необходимо, возможно, вы просто хотите проверить содержимое файла, чтобы убедиться, что он правильный, или убедитесь, что он действительно не пуст. Команда head позволяет просматривать первые N строк файла. <add> <ide> <del>Если вызывается больше, чем один файл, отображаются первые десять строк каждого файла, если не указано конкретное количество строк. Выбор отображения заголовка файла является необязательным, используя параметр ниже <ide> <ide> ### использование <ide> <ide> ```bash <del>head [options] [file_name(s)] <add>head [опции] [имя_файла] <ide> ``` <ide> <ide> Наиболее часто используемые опции: <ide> head [options] [file_name(s)] <ide> * `-q` , не распечатывает заголовки файлов <ide> * `-v` , всегда печатает заголовки файлов <ide> <del>### пример <add>### примеры <ide> <add>* Распечатывает в терминале первые десять строк файла file.txt (по умолчанию): <ide> ```bash <ide> head file.txt <ide> ``` <ide> <add> <ide> Печать в терминале первые десять строк файла file.txt (по умолчанию) <ide> <add> <ide> ```bash <ide> head -n 7 file.txt <ide> ``` <ide> <del>Печать в терминале первых семь строк файла file.txt <add> <add>* Печать в терминале первых 5 строк файла file1.txt, а затем первых 5 строк файла file2.txt (заголовки файлов будут отсуствовать благодаря опции `-q`) <add> <ide> <ide> ```bash <ide> head -q -n 5 file1.txt file2.txt <ide> ``` <ide> <del>Печать в терминале первых 5 строк файла file1.txt, а затем первых 5 строк файла file2.txt <ide> <ide> ### Дополнительная информация: <ide> <del>* [Википедия](https://en.wikipedia.org/wiki/Head_(Unix)) <add>* [Википедия](https://ru.wikipedia.org/wiki/Head_(Unix)) <add>
1
Text
Text
update documentation styling as per suggestions
30164588d6be5d5a07b079719f15cf2da06322d2
<ide><path>docs/reference/builder.md <ide> any point in an image's history, much like source control. <ide> The *exec* form makes it possible to avoid shell string munging, and to `RUN` <ide> commands using a base image that does not contain `/bin/sh`. <ide> <add>In the *shell* form you can use a `\` (backslash) to continue a single <add>RUN instruction onto the next line. For example, consider these two lines: <add>``` <add>RUN /bin/bash -c 'source $HOME/.bashrc ;\ <add>echo $HOME' <add>``` <add>Together they are equivalent to this single line: <add>``` <add>RUN /bin/bash -c 'source $HOME/.bashrc ; echo $HOME' <add>``` <add> <ide> > **Note**: <ide> > To use a different shell, other than '/bin/sh', use the *exec* form <ide> > passing in the desired shell. For example, <ide> commands using a base image that does not contain `/bin/sh`. <ide> > If you want shell processing then either use the *shell* form or execute <ide> > a shell directly, for example: `RUN [ "sh", "-c", "echo", "$HOME" ]`. <ide> <del>> **Note**: <del>> If you choose to use the *shell* form, any time you want to continue a single <del>> `RUN` instruction onto the next line, it has to be ended with a backslash `\`. <del>> For example, `RUN /bin/bash -c 'source $HOME/.bashrc ;\` then on the next <del>> line ` echo $HOME '`. <del> <ide> The cache for `RUN` instructions isn't invalidated automatically during <ide> the next build. The cache for an instruction like <ide> `RUN apt-get dist-upgrade -y` will be reused during the next build. The
1
PHP
PHP
provide pending request to retry callback
71bb3970522c90c66b358ff464d5c3cd3bd5f781
<ide><path>src/Illuminate/Http/Client/PendingRequest.php <ide> public function send(string $method, string $url, array $options = []) <ide> <ide> if (! $response->successful()) { <ide> try { <del> $shouldRetry = $this->retryWhenCallback ? call_user_func($this->retryWhenCallback, $response->toException()) : true; <add> $shouldRetry = $this->retryWhenCallback ? call_user_func($this->retryWhenCallback, $response->toException(), $this) : true; <ide> } catch (Exception $exception) { <ide> $shouldRetry = false; <ide> <ide><path>tests/Http/HttpClientTest.php <ide> public function testRequestExceptionIsNotThrownWithoutRetriesIfRetryNotNecessary <ide> $this->factory->assertSentCount(1); <ide> } <ide> <add> public function testRequestCanBeModifiedInRetryCallback() <add> { <add> $this->factory->fake([ <add> '*' => $this->factory->sequence() <add> ->push(['error'], 500) <add> ->push(['ok'], 200), <add> ]); <add> <add> $response = $this->factory <add> ->retry(2, 1000, function ($exception, $request) { <add> $this->assertInstanceOf(PendingRequest::class, $request); <add> <add> $request->withHeaders(['Foo' => 'Bar']); <add> <add> return true; <add> }, false) <add> ->get('http://foo.com/get'); <add> <add> $this->assertTrue($response->successful()); <add> <add> $this->factory->assertSent(function (Request $request) { <add> return $request->hasHeader('Foo') && $request->header('Foo') === ['Bar']; <add> }); <add> } <add> <ide> public function testExceptionThrownInRetryCallbackWithoutRetrying() <ide> { <ide> $this->factory->fake([
2
Javascript
Javascript
improve detection when auto publicpath can be used
5cf0b8288c4dcc21bde2073cf8f5cce491a0b65b
<ide><path>lib/config/defaults.js <ide> const applyOutputDefaults = ( <ide> }); <ide> D(output, "assetModuleFilename", "[hash][ext][query]"); <ide> D(output, "webassemblyModuleFilename", "[hash].module.wasm"); <del> D(output, "publicPath", tp ? (tp.web ? "auto" : "") : ""); <ide> D(output, "compareBeforeEmit", true); <ide> D(output, "charset", true); <ide> F(output, "hotUpdateGlobal", () => <ide> const applyOutputDefaults = ( <ide> D(output, "hotUpdateMainFilename", "[fullhash].hot-update.json"); <ide> D(output, "crossOriginLoading", false); <ide> F(output, "scriptType", () => (output.module ? "module" : false)); <add> D( <add> output, <add> "publicPath", <add> (tp && (tp.document || tp.importScripts)) || output.scriptType === "module" <add> ? "auto" <add> : "" <add> ); <ide> D(output, "chunkLoadTimeout", 120000); <ide> D(output, "hashFunction", "md4"); <ide> D(output, "hashDigest", "hex");
1
Text
Text
change the wordking from '給它` to '采用'
1208fa17f3b75b5c4b9577b05dfda54d2dbf3793
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-personal-portfolio-webpage.chinese.md <ide> localeTitle: 建立个人作品集网页 <ide> --- <ide> <ide> ## Description <del><section id="description"> <strong>目标:</strong>构建一个功能类似于此的<a href="https://codepen.io" target="_blank">CodePen.io</a>应用程序: <a href="https://codepen.io/freeCodeCamp/full/zNBOYG" target="_blank">https</a> <strong>:</strong> <a href="https://codepen.io" target="_blank">//codepen.io/freeCodeCamp/full/zNBOYG</a> 。完成以下<a href="https://en.wikipedia.org/wiki/User_story" target="_blank">用户故事</a>并通过所有测试。给它你自己的个人风格。您可以使用HTML,JavaScript和CSS来完成此项目。建议使用纯CSS,因为这是迄今为止所涵盖的课程,您应该使用纯CSS进行一些练习。如果您愿意,可以使用Bootstrap或SASS。此项目不建议使用其他技术(例如jQuery,React,Angular或Vue),使用它们需要您自担风险。其他项目将使您有机会使用不同的技术堆栈,如React。我们将接受并尝试修复所有使用建议的技术堆栈的问题报告。快乐的编码! <strong>用户故事#1:</strong>我的投资组合应该有一个欢迎部分,其ID为<code>welcome-section</code> 。 <strong>用户故事#2:</strong>欢迎部分应该包含一个包含文本的<code>h1</code>元素。 <strong>用户故事#3:</strong>我的投资组合应该有一个项目ID为id的<code>projects</code> 。 <strong>用户故事#4:</strong>项目部分应至少包含一个带有<code>project-tile</code>类的元素来保存项目。 <strong>用户故事#5:</strong>项目部分应至少包含一个项目链接。 <strong>用户故事#6:</strong>我的投资组合应该有一个id为<code>navbar</code> 。 <strong>用户故事#7:</strong>导航栏应至少包含一个链接,我可以单击该链接导航到页面的不同部分。 <strong>用户故事#8:</strong>我的投资组合应该有一个id <code>profile-link</code> ,它会在新标签中打开我的GitHub或FCC个人资料。 <strong>用户故事#9:</strong>我的投资组合应该至少有一个媒体查询。 <strong>用户故事#10:</strong>欢迎部分的高度应等于视口的高度。 <strong>用户故事#11:</strong>导航栏应始终位于视口的顶部。您可以通过分叉<a href="http://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">此CodePen笔</a>来构建项目。或者您可以使用此CDN链接在您喜欢的任何环境中运行测试: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> : <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code>完成后,将URL提交给您的工作通过所有测试的项目。如果卡住,请记住使用<a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a>方法。 </section> <add><section id="description"> <strong>目标:</strong>构建一个功能类似于此的<a href="https://codepen.io" target="_blank">CodePen.io</a>应用程序: <a href="https://codepen.io/freeCodeCamp/full/zNBOYG" target="_blank">https</a> <strong>:</strong> <a href="https://codepen.io" target="_blank">//codepen.io/freeCodeCamp/full/zNBOYG</a> 。完成以下<a href="https://en.wikipedia.org/wiki/User_story" target="_blank">用户故事</a>并通过所有测试。采用你自己的个人风格。您可以使用HTML,JavaScript和CSS来完成此项目。建议使用纯CSS,因为这是迄今为止所涵盖的课程,您应该使用纯CSS进行一些练习。如果您愿意,可以使用Bootstrap或SASS。此项目不建议使用其他技术(例如jQuery,React,Angular或Vue),使用它们需要您自担风险。其他项目将使您有机会使用不同的技术堆栈,如React。我们将接受并尝试修复所有使用建议的技术堆栈的问题报告。快乐的编码! <strong>用户故事#1:</strong>我的投资组合应该有一个欢迎部分,其ID为<code>welcome-section</code> 。 <strong>用户故事#2:</strong>欢迎部分应该包含一个包含文本的<code>h1</code>元素。 <strong>用户故事#3:</strong>我的投资组合应该有一个项目ID为id的<code>projects</code> 。 <strong>用户故事#4:</strong>项目部分应至少包含一个带有<code>project-tile</code>类的元素来保存项目。 <strong>用户故事#5:</strong>项目部分应至少包含一个项目链接。 <strong>用户故事#6:</strong>我的投资组合应该有一个id为<code>navbar</code> 。 <strong>用户故事#7:</strong>导航栏应至少包含一个链接,我可以单击该链接导航到页面的不同部分。 <strong>用户故事#8:</strong>我的投资组合应该有一个id <code>profile-link</code> ,它会在新标签中打开我的GitHub或FCC个人资料。 <strong>用户故事#9:</strong>我的投资组合应该至少有一个媒体查询。 <strong>用户故事#10:</strong>欢迎部分的高度应等于视口的高度。 <strong>用户故事#11:</strong>导航栏应始终位于视口的顶部。您可以通过分叉<a href="http://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">此CodePen笔</a>来构建项目。或者您可以使用此CDN链接在您喜欢的任何环境中运行测试: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> : <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code>完成后,将URL提交给您的工作通过所有测试的项目。如果卡住,请记住使用<a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a>方法。 </section> <ide> <ide> ## Instructions <ide> <section id="instructions">
1
Python
Python
restore state of _ml.py
85794c1167a2f15569003d04fe51211c22e747fe
<ide><path>spacy/_ml.py <ide> from thinc.neural.ops import NumpyOps, CupyOps <ide> from thinc.neural.util import get_array_module <ide> import random <add>import cytoolz <ide> <ide> from thinc.neural._classes.convolution import ExtractWindow <ide> from thinc.neural._classes.static_vectors import StaticVectors <ide> <ide> from .attrs import ID, ORTH, LOWER, NORM, PREFIX, SUFFIX, SHAPE, TAG, DEP <ide> from .tokens.doc import Doc <add>from . import util <ide> <ide> import numpy <ide> import io <ide> def logistic_bwd(dY, sgd=None): <ide> return Y, logistic_bwd <ide> <ide> <add>@layerize <add>def add_tuples(X, drop=0.): <add> """Give inputs of sequence pairs, where each sequence is (vals, length), <add> sum the values, returning a single sequence. <add> <add> If input is: <add> ((vals1, length), (vals2, length) <add> Output is: <add> (vals1+vals2, length) <add> <add> vals are a single tensor for the whole batch. <add> """ <add> (vals1, length1), (vals2, length2) = X <add> assert length1 == length2 <add> <add> def add_tuples_bwd(dY, sgd=None): <add> return (dY, dY) <add> <add> return (vals1+vals2, length), add_tuples_bwd <add> <add> <ide> def _zero_init(model): <ide> def _zero_init_impl(self, X, y): <ide> self.W.fill(0) <ide> def _zero_init_impl(self, X, y): <ide> model.W.fill(0.) <ide> return model <ide> <add> <ide> @layerize <ide> def _preprocess_doc(docs, drop=0.): <ide> keys = [doc.to_array([LOWER]) for doc in docs] <ide> def _preprocess_doc(docs, drop=0.): <ide> return (keys, vals, lengths), None <ide> <ide> <del> <ide> def _init_for_precomputed(W, ops): <ide> if (W**2).sum() != 0.: <ide> return <ide> reshaped = W.reshape((W.shape[1], W.shape[0] * W.shape[2])) <ide> ops.xavier_uniform_init(reshaped) <ide> W[:] = reshaped.reshape(W.shape) <ide> <add> <ide> @describe.on_data(_set_dimensions_if_needed) <ide> @describe.attributes( <ide> nI=Dimension("Input size"), <ide> def backward(dYp_ids, sgd=None): <ide> return Yfp, backward <ide> <ide> <add>def drop_layer(layer, factor=2.): <add> def drop_layer_fwd(X, drop=0.): <add> drop *= factor <add> mask = layer.ops.get_dropout_mask((1,), drop) <add> if mask is None or mask > 0: <add> return layer.begin_update(X, drop=drop) <add> else: <add> return X, lambda dX, sgd=None: dX <add> return wrap(drop_layer_fwd, layer) <add> <add> <ide> def Tok2Vec(width, embed_size, preprocess=None): <del> cols = [ID, NORM, PREFIX, SUFFIX, SHAPE] <add> cols = [ID, NORM, PREFIX, SUFFIX, SHAPE, ORTH] <ide> with Model.define_operators({'>>': chain, '|': concatenate, '**': clone, '+': add}): <del> norm = get_col(cols.index(NORM)) >> HashEmbed(width, embed_size, name='embed_lower') <add> norm = get_col(cols.index(NORM)) >> HashEmbed(width, embed_size, name='embed_lower') <ide> prefix = get_col(cols.index(PREFIX)) >> HashEmbed(width, embed_size//2, name='embed_prefix') <ide> suffix = get_col(cols.index(SUFFIX)) >> HashEmbed(width, embed_size//2, name='embed_suffix') <ide> shape = get_col(cols.index(SHAPE)) >> HashEmbed(width, embed_size//2, name='embed_shape') <ide> def _hook(self, X, y=None): <ide> <ide> <ide> def doc2feats(cols=None): <del> cols = [ID, NORM, PREFIX, SUFFIX, SHAPE] <add> if cols is None: <add> cols = [ID, NORM, PREFIX, SUFFIX, SHAPE, ORTH] <ide> def forward(docs, drop=0.): <ide> feats = [] <ide> for doc in docs: <ide> def fine_tune_fwd(docs_tokvecs, drop=0.): <ide> vecs, bp_vecs = embedding.begin_update(docs, drop=drop) <ide> flat_tokvecs = embedding.ops.flatten(tokvecs) <ide> flat_vecs = embedding.ops.flatten(vecs) <del> alpha = model.mix <del> minus = 1-model.mix <ide> output = embedding.ops.unflatten( <del> (alpha * flat_tokvecs + minus * flat_vecs), lengths) <add> (model.mix[0] * flat_vecs + model.mix[1] * flat_tokvecs), <add> lengths) <ide> <ide> def fine_tune_bwd(d_output, sgd=None): <add> bp_vecs(d_output, sgd=sgd) <ide> flat_grad = model.ops.flatten(d_output) <del> model.d_mix += flat_tokvecs.dot(flat_grad.T).sum() <del> model.d_mix += 1-flat_vecs.dot(flat_grad.T).sum() <del> <del> bp_vecs([d_o * minus for d_o in d_output], sgd=sgd) <del> d_output = [d_o * alpha for d_o in d_output] <del> sgd(model._mem.weights, model._mem.gradient, key=model.id) <del> model.mix = model.ops.xp.minimum(model.mix, 1.0) <add> model.d_mix[1] += flat_tokvecs.dot(flat_grad.T).sum() <add> model.d_mix[0] += flat_vecs.dot(flat_grad.T).sum() <add> if sgd is not None: <add> sgd(model._mem.weights, model._mem.gradient, key=model.id) <ide> return d_output <ide> return output, fine_tune_bwd <ide> model = wrap(fine_tune_fwd, embedding) <del> model.mix = model._mem.add((model.id, 'mix'), (1,)) <del> model.mix.fill(0.0) <add> model.mix = model._mem.add((model.id, 'mix'), (2,)) <add> model.mix.fill(1.) <ide> model.d_mix = model._mem.add_gradient((model.id, 'd_mix'), (model.id, 'mix')) <ide> return model <ide> <ide> def preprocess_doc(docs, drop=0.): <ide> vals = ops.allocate(keys.shape[0]) + 1 <ide> return (keys, vals, lengths), None <ide> <add>def getitem(i): <add> def getitem_fwd(X, drop=0.): <add> return X[i], None <add> return layerize(getitem_fwd) <add> <add>def build_tagger_model(nr_class, token_vector_width, **cfg): <add> embed_size = util.env_opt('embed_size', 7500) <add> with Model.define_operators({'>>': chain, '+': add}): <add> # Input: (doc, tensor) tuples <add> private_tok2vec = Tok2Vec(token_vector_width, embed_size, preprocess=doc2feats()) <add> <add> model = ( <add> fine_tune(private_tok2vec) <add> >> with_flatten( <add> Maxout(token_vector_width, token_vector_width) <add> >> Softmax(nr_class, token_vector_width) <add> ) <add> ) <add> model.nI = None <add> return model <add> <ide> <ide> def build_text_classifier(nr_class, width=64, **cfg): <ide> nr_vector = cfg.get('nr_vector', 200) <ide> def build_text_classifier(nr_class, width=64, **cfg): <ide> >> _flatten_add_lengths <ide> >> with_getitem(0, <ide> uniqued( <del> (embed_lower | embed_prefix | embed_suffix | embed_shape) <add> (embed_lower | embed_prefix | embed_suffix | embed_shape) <ide> >> Maxout(width, width+(width//2)*3)) <ide> >> Residual(ExtractWindow(nW=1) >> ReLu(width, width*3)) <ide> >> Residual(ExtractWindow(nW=1) >> ReLu(width, width*3)) <ide> def build_text_classifier(nr_class, width=64, **cfg): <ide> >> zero_init(Affine(nr_class, nr_class*2, drop_factor=0.0)) <ide> >> logistic <ide> ) <del> <add> <ide> model.lsuv = False <ide> return model <ide>
1
Javascript
Javascript
make socket destroy() re-entrance safe
d2de8ba34dc57d78a0bd0fedc4bd05e5c4457bac
<ide><path>lib/net.js <ide> Socket.prototype._destroy = function(exception, cb) { <ide> this._handle = null; <ide> } <ide> <del> fireErrorCallbacks(); <add> // we set destroyed to true before firing error callbacks in order <add> // to make it re-entrance safe in case Socket.prototype.destroy() <add> // is called within callbacks <ide> this.destroyed = true; <add> fireErrorCallbacks(); <ide> <ide> if (this.server) { <ide> COUNTER_NET_SERVER_CONNECTION_CLOSE(this); <ide><path>test/simple/test-net-stream.js <ide> s.destroy(); <ide> assert.equal(9, s.server.connections); <ide> s.destroy(); <ide> assert.equal(9, s.server.connections); <add> <add>var SIZE = 2E6; <add>var N = 10; <add>var buf = new Buffer(SIZE); <add>buf.fill(0x61); // 'a' <add> <add>var server = net.createServer(function(socket) { <add> socket.setNoDelay(); <add> <add> socket.on('error', function(err) { <add> socket.destroy(); <add> }).on('close', function() { <add> server.close(); <add> }) <add> <add> for (var i = 0; i < N; ++i) { <add> socket.write(buf, function() { }); <add> } <add> socket.end(); <add> <add>}).listen(common.PORT, function() { <add> var conn = net.connect(common.PORT); <add> conn.on('data', function(buf) { <add> conn.pause(); <add> setTimeout(function() { <add> conn.destroy(); <add> }, 20); <add> }); <add> }); <add> <add>process.on('exit', function() { <add> assert.equal(server.connections, 0); <add>});
2
Python
Python
fix cli for multitask objectives
86405e4ad1ea443c231a9a5a22b23959d8ddcd42
<ide><path>spacy/cli/train.py <ide> no_tagger=("Don't train tagger", "flag", "T", bool), <ide> no_parser=("Don't train parser", "flag", "P", bool), <ide> no_entities=("Don't train NER", "flag", "N", bool), <del> parser_multitasks=("Side objectives for parser CNN, e.g. dep dep,tag", "option", "pt", ","), <del> entity_multitasks=("Side objectives for ner CNN, e.g. dep dep,tag", "option", "et", ","), <add> parser_multitasks=("Side objectives for parser CNN, e.g. dep dep,tag", "option", "pt", str), <add> entity_multitasks=("Side objectives for ner CNN, e.g. dep dep,tag", "option", "et", str), <ide> gold_preproc=("Use gold preprocessing", "flag", "G", bool), <ide> version=("Model version", "option", "V", str), <ide> meta_path=("Optional path to meta.json. All relevant properties will be " <ide> def train(lang, output_dir, train_data, dev_data, n_iter=30, n_sents=0, <ide> lex.is_oov = False <ide> for name in pipeline: <ide> nlp.add_pipe(nlp.create_pipe(name), name=name) <del> for objective in parser_multitasks.split(','): <del> nlp.parser.add_multitask_objective(objective) <del> for objective in entity_multitasks.split(','): <del> nlp.entity.add_multitask_objective(objective) <add> if parser_multitasks: <add> for objective in parser_multitasks.split(','): <add> nlp.parser.add_multitask_objective(objective) <add> if entity_multitasks: <add> for objective in entity_multitasks.split(','): <add> nlp.entity.add_multitask_objective(objective) <ide> optimizer = nlp.begin_training(lambda: corpus.train_tuples, device=use_gpu) <ide> nlp._optimizer = None <ide>
1
Javascript
Javascript
add names to components in amp example
96f8455a03b7d4832929909396ebcb2e8bb5169f
<ide><path>examples/amp/components/Byline.js <del>export default ({ author }) => ( <del> <> <del> <div className="byline">By {author}</div> <del> <style jsx>{` <del> .byline { <del> color: green; <del> font-weight: bolder; <del> } <del> `}</style> <del> </> <del>) <add>export default function Byline({ author }) { <add> return ( <add> <> <add> <div className="byline">By {author}</div> <add> <style jsx>{` <add> .byline { <add> color: green; <add> font-weight: bolder; <add> } <add> `}</style> <add> </> <add> ) <add>} <ide><path>examples/amp/pages/dog.js <ide> export const config = { <ide> amp: 'hybrid', <ide> } <ide> <del>export default () => { <add>export default function DogPage() { <ide> const isAmp = useAmp() <ide> <ide> return ( <ide><path>examples/amp/pages/index.js <ide> export const config = { <ide> amp: true, <ide> } <ide> <del>export default () => { <add>export default function IndexPage() { <ide> const isAmp = useAmp() <ide> <ide> return ( <ide><path>examples/amp/pages/normal.js <del>export default () => <p>I'm just a normal old page, no AMP for me</p> <add>export default function NormalPage() { <add> return <p>I'm just a normal old page, no AMP for me</p> <add>}
4
Python
Python
remove unnecessary flags
cd00b9a7c367506397bc8752c95d27c31dffbd49
<ide><path>official/transformer/v2/misc.py <ide> def define_transformer_flags(): <ide> default=False, <ide> help=flags_core.help_wrap( <ide> 'Whether the model runs with custom training loop.')) <del> flags.DEFINE_bool( <del> name='use_tpu_2vm_config', <del> default=False, <del> help=flags_core.help_wrap( <del> 'Whether the model runs in 2VM mode, Headless server and unit test ' <del> 'all use 1VM config.')) <ide> flags.DEFINE_integer( <ide> name='decode_batch_size', <ide> default=32, <ide><path>official/transformer/v2/transformer_main.py <ide> def main(_): <ide> with logger.benchmark_context(flags_obj): <ide> task = TransformerTask(flags_obj) <ide> <del> def _run_task(task): <del> if flags_obj.mode == "train": <del> task.train() <del> elif flags_obj.mode == "predict": <del> task.predict() <del> elif flags_obj.mode == "eval": <del> task.eval() <del> else: <del> raise ValueError("Invalid mode {}".format(flags_obj.mode)) <del> <del> if flags_obj.distribution_strategy != "tpu": <del> _run_task(task) <add> if flags_obj.mode == "train": <add> task.train() <add> elif flags_obj.mode == "predict": <add> task.predict() <add> elif flags_obj.mode == "eval": <add> task.eval() <ide> else: <del> primary_cpu_task = "/job:worker" if flags_obj.use_tpu_2vm_config else "" <del> with tf.device(primary_cpu_task): <del> _run_task(task) <add> raise ValueError("Invalid mode {}".format(flags_obj.mode)) <ide> <ide> <ide> if __name__ == "__main__": <ide><path>official/transformer/v2/transformer_main_test.py <ide> import tensorflow as tf <ide> <ide> from official.transformer.v2 import misc <del>from official.transformer.v2 import transformer_main as tm <add>from official.transformer.v2 import transformer_main <ide> from official.utils.misc import keras_utils <ide> <ide> from tensorflow.python.eager import context # pylint: disable=ungrouped-imports <ide> def _assert_exists(self, filepath): <ide> def test_train_no_dist_strat(self): <ide> if context.num_gpus() >= 2: <ide> self.skipTest('No need to test 2+ GPUs without a distribution strategy.') <del> t = tm.TransformerTask(FLAGS) <add> t = transformer_main.TransformerTask(FLAGS) <ide> t.train() <ide> <ide> def test_train_static_batch(self): <ide> def test_train_static_batch(self): <ide> else: <ide> FLAGS.num_gpus = 0 <ide> FLAGS.static_batch = True <del> t = tm.TransformerTask(FLAGS) <add> t = transformer_main.TransformerTask(FLAGS) <ide> t.train() <ide> <ide> @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU') <ide> def test_train_1_gpu_with_dist_strat(self): <ide> FLAGS.distribution_strategy = 'one_device' <del> t = tm.TransformerTask(FLAGS) <add> t = transformer_main.TransformerTask(FLAGS) <ide> t.train() <ide> <ide> @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU') <ide> def test_train_fp16(self): <ide> FLAGS.distribution_strategy = 'one_device' <ide> FLAGS.dtype = 'fp16' <del> t = tm.TransformerTask(FLAGS) <add> t = transformer_main.TransformerTask(FLAGS) <ide> t.train() <ide> <ide> @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU') <ide> def test_train_2_gpu(self): <ide> FLAGS.distribution_strategy = 'mirrored' <ide> FLAGS.num_gpus = 2 <ide> FLAGS.param_set = 'base' <del> t = tm.TransformerTask(FLAGS) <add> t = transformer_main.TransformerTask(FLAGS) <ide> t.train() <ide> <ide> @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU') <ide> def test_train_2_gpu_fp16(self): <ide> FLAGS.num_gpus = 2 <ide> FLAGS.param_set = 'base' <ide> FLAGS.dtype = 'fp16' <del> t = tm.TransformerTask(FLAGS) <add> t = transformer_main.TransformerTask(FLAGS) <ide> t.train() <ide> <ide> def _prepare_files_and_flags(self, *extra_flags): <ide> def test_predict(self): <ide> if context.num_gpus() >= 2: <ide> self.skipTest('No need to test 2+ GPUs without a distribution strategy.') <ide> self._prepare_files_and_flags() <del> t = tm.TransformerTask(FLAGS) <add> t = transformer_main.TransformerTask(FLAGS) <ide> t.predict() <ide> <ide> def test_predict_fp16(self): <ide> if context.num_gpus() >= 2: <ide> self.skipTest('No need to test 2+ GPUs without a distribution strategy.') <ide> self._prepare_files_and_flags('--dtype=fp16') <del> t = tm.TransformerTask(FLAGS) <add> t = transformer_main.TransformerTask(FLAGS) <ide> t.predict() <ide> <ide> def test_eval(self): <ide> def test_eval(self): <ide> if 'test_xla' in sys.argv[0]: <ide> self.skipTest('TODO(xla): Make this test faster under XLA.') <ide> self._prepare_files_and_flags() <del> t = tm.TransformerTask(FLAGS) <add> t = transformer_main.TransformerTask(FLAGS) <ide> t.eval() <ide> <ide>
3
Text
Text
add a changelog entry for [ci skip]
84c1b107b9daab90b3ccf520f0f09752e4eaf425
<ide><path>actionpack/CHANGELOG.md <add>* Silence Puma start-up messages running system tests. <add> <add> Fixes #28109. <add> <add> *Yuji Yaginuma* (#28284) <add> <ide> * Commit flash changes when using a redirect route. <ide> <ide> Fixes #27992.
1
Text
Text
update devops guide
d9054df0a4aa148475cb85ca646ba911dac5daa9
<ide><path>docs/devops.md <ide> The dev-team merges changes from the `production-staging` branch to `production- <ide> <ide> We use Azure Pipelines and other CI software (Travis, GitHub Actions), to continiously test and deploy our applications. <ide> <del>### Triggering a build and deplyment <add>### Triggering a build <ide> <ide> Currently we have given access only to the developer team to push to the production branches, beacuse of the automated deplyements on live sites. The changes to the `production-*` branches can land only via fast-forward merge to the [`upstream`](https://github.com/freeCodeCamp/freeCodeCamp). <ide> <ide> upstream git@github.com:freeCodeCamp/freeCodeCamp.git (push) <ide> <ide> The below commands will move changes from `master` to the `production-*` branch: <ide> <add>> #### :rotating_light: Do not run the below, if you have not confirmed Travis is green on the master branch :rotating_light: <add> <ide> ```sh <ide> git checkout master <ide> git reset --hard upstream/master <ide> git push upstream <ide> <ide> You will not be able to force push and if you have re-written the history in anyway it will error out. <ide> <add>### Triggering a deployment <add> <ide> Once the changes are pushed, these should trigger our CI and CD pipilines: <ide> <ide> - Build Pipeline: https://dev.azure.com/freeCodeCamp-org/freeCodeCamp/_build
1
Python
Python
show rendered templates from the cli
265d47c4b10a4c1a0c77edb2296a54b923e31a4f
<ide><path>airflow/bin/cli.py <ide> import logging <ide> import os <ide> import subprocess <add>import textwrap <ide> from datetime import datetime <ide> <ide> from builtins import input <ide> def list_tasks(args): <ide> <ide> <ide> def test(args): <del> <ide> args.execution_date = dateutil.parser.parse(args.execution_date) <ide> dagbag = DagBag(process_subdir(args.subdir)) <ide> if args.dag_id not in dagbag.dags: <ide> def test(args): <ide> ti.run(force=True, ignore_dependencies=True, test_mode=True) <ide> <ide> <add>def render(args): <add> args.execution_date = dateutil.parser.parse(args.execution_date) <add> dagbag = DagBag(process_subdir(args.subdir)) <add> if args.dag_id not in dagbag.dags: <add> raise AirflowException('dag_id could not be found') <add> dag = dagbag.dags[args.dag_id] <add> task = dag.get_task(task_id=args.task_id) <add> ti = TaskInstance(task, args.execution_date) <add> ti.render_templates() <add> for attr in task.__class__.template_fields: <add> print(textwrap.dedent("""\ <add> # ---------------------------------------------------------- <add> # property: {} <add> # ---------------------------------------------------------- <add> {} <add> """.format(attr, getattr(task, attr)))) <add> <add> <ide> def clear(args): <ide> logging.basicConfig( <ide> level=settings.LOGGING_LEVEL, <ide> def get_parser(): <ide> nargs='?', default=configuration.get('kerberos', 'principal')) <ide> parser_kerberos.set_defaults(func=kerberos) <ide> <add> ht = "Render a task instance's template(s)" <add> parser_render = subparsers.add_parser('render', help=ht) <add> parser_render.add_argument("dag_id", help="The id of the dag to check") <add> parser_render.add_argument("task_id", help="The task_id to check") <add> parser_render.add_argument( <add> "execution_date", help="The execution date to check") <add> parser_render.add_argument( <add> "-sd", "--subdir", help=subdir_help, <add> default=DAGS_FOLDER) <add> parser_render.set_defaults(func=render) <add> <ide> return parser <ide><path>airflow/models.py <ide> def render_templates(self): <ide> for attr in task.__class__.template_fields: <ide> content = getattr(task, attr) <ide> if content: <del> rendered_content = self.task.render_template(content, jinja_context) <add> rendered_content = rt(content, jinja_context) <ide> setattr(task, attr, rendered_content) <ide> <ide> def email_alert(self, exception, is_retry=False):
2
Javascript
Javascript
fix error logging in getderivedstatefromprops
20da1dae4b9523ee94dc67797b11ec789e3acc68
<ide><path>packages/react-dom/src/__tests__/ReactErrorBoundaries-test.internal.js <ide> describe('ReactErrorBoundaries', () => { <ide> expect(container3.firstChild).toBe(null); <ide> }); <ide> <add> it('logs a single error when using error boundary', () => { <add> const container = document.createElement('div'); <add> expect(() => <add> ReactDOM.render( <add> <ErrorBoundary> <add> <BrokenRender /> <add> </ErrorBoundary>, <add> container, <add> ), <add> ).toWarnDev('The above error occurred in the <BrokenRender> component:', { <add> logAllErrors: true, <add> }); <add> <add> expect(container.firstChild.textContent).toBe('Caught an error: Hello.'); <add> expect(log).toEqual([ <add> 'ErrorBoundary constructor', <add> 'ErrorBoundary componentWillMount', <add> 'ErrorBoundary render success', <add> 'BrokenRender constructor', <add> 'BrokenRender componentWillMount', <add> 'BrokenRender render [!]', <add> // Catch and render an error message <add> 'ErrorBoundary static getDerivedStateFromError', <add> 'ErrorBoundary componentWillMount', <add> 'ErrorBoundary render error', <add> 'ErrorBoundary componentDidMount', <add> ]); <add> <add> log.length = 0; <add> ReactDOM.unmountComponentAtNode(container); <add> expect(log).toEqual(['ErrorBoundary componentWillUnmount']); <add> }); <add> <ide> it('renders an error state if child throws in render', () => { <ide> const container = document.createElement('div'); <ide> ReactDOM.render( <ide><path>packages/react-dom/src/__tests__/ReactLegacyErrorBoundaries-test.internal.js <ide> describe('ReactLegacyErrorBoundaries', () => { <ide> let BrokenComponentDidMountErrorBoundary; <ide> let BrokenRender; <ide> let ErrorBoundary; <add> let BothErrorBoundaries; <ide> let ErrorMessage; <ide> let NoopErrorBoundary; <ide> let RetryErrorBoundary; <ide> describe('ReactLegacyErrorBoundaries', () => { <ide> }, <ide> }; <ide> <add> BothErrorBoundaries = class extends React.Component { <add> constructor(props) { <add> super(props); <add> this.state = {error: null}; <add> log.push('BothErrorBoundaries constructor'); <add> } <add> <add> static getDerivedStateFromError(error) { <add> log.push('BothErrorBoundaries static getDerivedStateFromError'); <add> return {error}; <add> } <add> <add> render() { <add> if (this.state.error) { <add> log.push('BothErrorBoundaries render error'); <add> return <div>Caught an error: {this.state.error.message}.</div>; <add> } <add> log.push('BothErrorBoundaries render success'); <add> return <div>{this.props.children}</div>; <add> } <add> <add> componentDidCatch(error) { <add> log.push('BothErrorBoundaries componentDidCatch'); <add> this.setState({error}); <add> } <add> <add> UNSAFE_componentWillMount() { <add> log.push('BothErrorBoundaries componentWillMount'); <add> } <add> <add> componentDidMount() { <add> log.push('BothErrorBoundaries componentDidMount'); <add> } <add> <add> UNSAFE_componentWillReceiveProps() { <add> log.push('BothErrorBoundaries componentWillReceiveProps'); <add> } <add> <add> UNSAFE_componentWillUpdate() { <add> log.push('BothErrorBoundaries componentWillUpdate'); <add> } <add> <add> componentDidUpdate() { <add> log.push('BothErrorBoundaries componentDidUpdate'); <add> } <add> <add> componentWillUnmount() { <add> log.push('BothErrorBoundaries componentWillUnmount'); <add> } <add> }; <add> <ide> RetryErrorBoundary = class extends React.Component { <ide> constructor(props) { <ide> super(props); <ide> describe('ReactLegacyErrorBoundaries', () => { <ide> expect(container3.firstChild).toBe(null); <ide> }); <ide> <add> it('logs a single error using both error boundaries', () => { <add> const container = document.createElement('div'); <add> expect(() => <add> ReactDOM.render( <add> <BothErrorBoundaries> <add> <BrokenRender /> <add> </BothErrorBoundaries>, <add> container, <add> ), <add> ).toWarnDev('The above error occurred in the <BrokenRender> component', { <add> logAllErrors: true, <add> }); <add> <add> expect(container.firstChild.textContent).toBe('Caught an error: Hello.'); <add> expect(log).toEqual([ <add> 'BothErrorBoundaries constructor', <add> 'BothErrorBoundaries componentWillMount', <add> 'BothErrorBoundaries render success', <add> 'BrokenRender constructor', <add> 'BrokenRender componentWillMount', <add> 'BrokenRender render [!]', <add> // Both getDerivedStateFromError and componentDidCatch should be called <add> 'BothErrorBoundaries static getDerivedStateFromError', <add> 'BothErrorBoundaries componentWillMount', <add> 'BothErrorBoundaries render error', <add> // Fiber mounts with null children before capturing error <add> 'BothErrorBoundaries componentDidMount', <add> // Catch and render an error message <add> 'BothErrorBoundaries componentDidCatch', <add> 'BothErrorBoundaries componentWillUpdate', <add> 'BothErrorBoundaries render error', <add> 'BothErrorBoundaries componentDidUpdate', <add> ]); <add> <add> log.length = 0; <add> ReactDOM.unmountComponentAtNode(container); <add> expect(log).toEqual(['BothErrorBoundaries componentWillUnmount']); <add> }); <add> <ide> it('renders an error state if child throws in render', () => { <ide> const container = document.createElement('div'); <ide> ReactDOM.render( <ide><path>packages/react-reconciler/src/ReactFiberThrow.js <ide> function createClassErrorUpdate( <ide> if (typeof getDerivedStateFromError === 'function') { <ide> const error = errorInfo.value; <ide> update.payload = () => { <add> logError(fiber, errorInfo); <ide> return getDerivedStateFromError(error); <ide> }; <ide> } <ide> function createClassErrorUpdate( <ide> // TODO: Warn in strict mode if getDerivedStateFromError is <ide> // not defined. <ide> markLegacyErrorBoundaryAsFailed(this); <add> <add> // Only log here if componentDidCatch is the only error boundary method defined <add> logError(fiber, errorInfo); <ide> } <ide> const error = errorInfo.value; <ide> const stack = errorInfo.stack; <del> logError(fiber, errorInfo); <ide> this.componentDidCatch(error, { <ide> componentStack: stack !== null ? stack : '', <ide> }); <ide><path>scripts/jest/matchers/toWarnDev.js <ide> const createMatcherFor = consoleMethod => <ide> } <ide> <ide> const withoutStack = options.withoutStack; <add> const logAllErrors = options.logAllErrors; <ide> const warningsWithoutComponentStack = []; <ide> const warningsWithComponentStack = []; <ide> const unexpectedWarnings = []; <ide> const createMatcherFor = consoleMethod => <ide> // Ignore uncaught errors reported by jsdom <ide> // and React addendums because they're too noisy. <ide> if ( <add> !logAllErrors && <ide> consoleMethod === 'error' && <ide> shouldIgnoreConsoleError(format, args) <ide> ) {
4
PHP
PHP
correct doc blocks
6f535295206d5421626e522e0b09a949d439df53
<ide><path>lib/Cake/View/Helper/NumberHelper.php <ide> public function __construct(View $View, $settings = array()) { <ide> <ide> /** <ide> * Call methods from CakeNumber utility class <add> * <ide> * @return mixed Whatever is returned by called method, or false on failure <ide> */ <ide> public function __call($method, $params) { <ide> public function toReadableSize($size) { <ide> } <ide> <ide> /** <add> * Formats a number into a percentage string. <add> * <add> * Options: <add> * <ide> * - `multiply`: Multiply the input value by 100 for decimal percentages. <ide> * <ide> * @see CakeNumber::toPercentage() <ide> public function currency($number, $currency = null, $options = array()) { <ide> * @param string $formatName The format name to be used in the future. <ide> * @param array $options The array of options for this format. <ide> * @return void <del> * @see NumberHelper::currency() <ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::addFormat <ide> */ <ide> public function addFormat($formatName, $options) { <ide> public function addFormat($formatName, $options) { <ide> * @see CakeNumber::defaultCurrency() <ide> * <ide> * @param string $currency The currency to be used in the future. <del> * @return void <del> * @see NumberHelper::currency() <add> * @return string Currency <ide> */ <ide> public function defaultCurrency($currency) { <ide> return $this->_engine->defaultCurrency($currency);
1
Javascript
Javascript
address latest review comments by artur
b832aa5c1ec3a9874b68f090f9ea0d852165a6a7
<ide><path>pdf.js <ide> var Page = (function pagePage() { <ide> // Firefox error reporting from XHR callbacks. <ide> setTimeout(function pageSetTimeout() { <ide> var exc = null; <del> // try { <add> try { <ide> self.display(gfx, continuation); <del> // } catch (e) { <del> // exc = e.toString(); <del> // continuation(exc); <del> // throw e; <del> // } <add> } catch (e) { <add> exc = e.toString(); <add> continuation(exc); <add> throw e; <add> } <ide> }); <ide> }; <ide> <ide> var PartialEvaluator = (function partialEvaluator() { <ide> getIRQueue: function partialEvaluatorGetIRQueue(stream, resources, <ide> queue, dependency) { <ide> <add> var self = this; <ide> var xref = this.xref; <ide> var handler = this.handler; <ide> var uniquePrefix = this.uniquePrefix; <ide> var PartialEvaluator = (function partialEvaluator() { <ide> } <ide> } <ide> <del> var self = this; <ide> function handleSetFont(fontName, fontRef) { <ide> var loadedName = null; <ide> <ide> var PartialEvaluator = (function partialEvaluator() { <ide> // This adds the IRQueue of the xObj to the current queue. <ide> var depIdx = dependency.length; <ide> <del> this.getIRQueue(xobj, xobj.dict.get('Resources'), queue, <add> this.getIRQueue(xobj, xobj.dict.get('Resources'), queue, <ide> dependency); <ide> <ide> // Add the dependencies that are required to execute the <ide> function ScratchCanvas(width, height) { <ide> } <ide> <ide> var CanvasGraphics = (function canvasGraphics() { <del> // Defines the time the executeIRQueue gone be executing <add> // Defines the time the executeIRQueue gonna be executing <ide> // before it stops and shedules a continue of execution. <ide> var kExecutionTime = 50; <ide> // Number of IR commands to execute before checking <ide><path>worker.js <ide> var useWorker = false; <ide> <ide> var WorkerPage = (function() { <del> function constructor(workerPDF, page, objs) { <del> this.workerPDF = workerPDF; <add> function constructor(pdf, page, objs) { <add> this.pdf = pdf; <ide> this.page = page; <ide> this.objs = objs; <ide> <ide> var WorkerPage = (function() { <ide> // this.page.startRendering(ctx, callback, errback); <ide> <ide> this.startRenderingTime = Date.now(); <del> this.workerPDF.startRendering(this); <add> this.pdf.startRendering(this); <ide> }, <ide> <ide> startRenderingFromIRQueue: function(IRQueue, fonts) { <ide> var WorkerPage = (function() { <ide> console.log('page=%d - total time: time=%dms', <ide> pageNum, Date.now() - this.startRenderingTime); <ide> <del> this.callback(err); <add> if (this.callback) { <add> this.callback(err); <add> } <ide> }.bind(this); <ide> this.page.startRenderingFromIRQueue(gfx, IRQueue, fonts, callback); <ide> }, <ide> var PDFObjects = (function() { <ide> * Sets the data of an object but *doesn't* resolve it. <ide> */ <ide> setData: function(objId, data) { <del> // Watchout! If you call `this.ensureObj(objId, data)` you'll gone create <add> // Watchout! If you call `this.ensureObj(objId, data)` you'll gonna create <ide> // a *resolved* promise which shouldn't be the case! <ide> this.ensureObj(objId).data = data; <ide> } <ide><path>worker/processor_handler.js <ide> var WorkerProcessorHandler = { <ide> console.log('page=%d - getIRQueue: time=%dms, len=%d', pageNum, <ide> Date.now() - start, IRQueue.fnArray.length); <ide> <del> if (false /* show used commands */) { <del> var cmdMap = {}; <del> <del> var fnArray = IRQueue .fnArray; <del> for (var i = 0; i < fnArray.length; i++) { <del> var entry = fnArray[i]; <del> if (entry == 'paintReadyFormXObject') { <del> //console.log(preCompilation.argsArray[i]); <del> } <del> if (cmdMap[entry] == null) { <del> cmdMap[entry] = 1; <del> } else { <del> cmdMap[entry] += 1; <del> } <del> } <del> console.log('cmds', JSON.stringify(cmdMap)); <del> } <del> <ide> // Filter the dependecies for fonts. <ide> var fonts = {}; <ide> for (var i = 0; i < dependency.length; i++) {
3
Mixed
Javascript
assign missing deprecation code
360465dfe213aaf56cb81e1610d91aab2d53cf34
<ide><path>doc/api/deprecations.md <ide> The [Legacy URL API][] is deprecated. This includes [`url.format()`][], <ide> [`url.parse()`][], [`url.resolve()`][], and the [legacy `urlObject`][]. Please <ide> use the [WHATWG URL API][] instead. <ide> <del><a id="DEP00XX"></a> <del>### DEP00XX: Native crypto handles <add><a id="DEP0117"></a> <add>### DEP0117: Native crypto handles <ide> <!-- YAML <ide> changes: <ide> - version: REPLACEME <ide><path>lib/internal/crypto/util.js <ide> function legacyNativeHandle(obj, handle) { <ide> Object.defineProperty(obj, '_handle', { <ide> get: deprecate(() => handle, <ide> `${obj.constructor.name}._handle is deprecated. Use the ` + <del> 'public API instead.', 'DEP00XX'), <add> 'public API instead.', 'DEP0117'), <ide> set: deprecate((h) => obj[kHandle] = handle = h, <ide> `${obj.constructor.name}._handle is deprecated. Use the ` + <del> 'public API instead.', 'DEP00XX'), <add> 'public API instead.', 'DEP0117'), <ide> enumerable: false <ide> }); <ide> }
2
Text
Text
add note of options.stdio into child_process
e08ac04a1a6bcfa792c2a164c753f4fb16fa09b8
<ide><path>doc/api/child_process.md <ide> pipes between the parent and child. The value is one of the following: <ide> occurred). <ide> 6. Positive integer - The integer value is interpreted as a file descriptor <ide> that is currently open in the parent process. It is shared with the child <del> process, similar to how {Stream} objects can be shared. <add> process, similar to how {Stream} objects can be shared. Passing sockets <add> is not supported on Windows. <ide> 7. `null`, `undefined` - Use default value. For stdio fds 0, 1, and 2 (in other <ide> words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the <ide> default is `'ignore'`.
1
Python
Python
add missing docstring params
feddc517d7ea4a8f9403e430865df742237401dd
<ide><path>airflow/providers/airbyte/hooks/airbyte.py <ide> def submit_sync_connection(self, connection_id: str) -> Any: <ide> Submits a job to a Airbyte server. <ide> <ide> :param connection_id: Required. The ConnectionId of the Airbyte Connection. <del> :type connectiond_id: str <add> :type connection_id: str <ide> """ <ide> return self.run( <ide> endpoint=f"api/{self.api_version}/connections/sync", <ide><path>airflow/utils/timezone.py <ide> def parse(string: str, timezone=None) -> DateTime: <ide> Parse a time string and return an aware datetime <ide> <ide> :param string: time string <add> :param timezone: the timezone <ide> """ <ide> return pendulum.parse(string, tz=timezone or TIMEZONE, strict=False) # type: ignore <ide><path>docs/exts/docroles.py <ide> def get_template_field(env, fullname): <ide> """ <ide> Gets template fields for specific operator class. <ide> <add> :param env: env config <ide> :param fullname: Full path to operator class. <ide> For example: ``airflow.providers.google.cloud.operators.vision.CloudVisionCreateProductSetOperator`` <ide> :return: List of template field <ide><path>docs/exts/docs_build/errors.py <ide> def parse_sphinx_warnings(warning_text: str, docs_dir: str) -> List[DocBuildErro <ide> Parses warnings from Sphinx. <ide> <ide> :param warning_text: warning to parse <add> :param docs_dir: documentation directory <ide> :return: list of DocBuildErrors. <ide> """ <ide> sphinx_build_errors = [] <ide><path>docs/exts/docs_build/spelling_checks.py <ide> def parse_spelling_warnings(warning_text: str, docs_dir: str) -> List[SpellingEr <ide> Parses warnings from Sphinx. <ide> <ide> :param warning_text: warning to parse <add> :param docs_dir: documentation directory <ide> :return: list of SpellingError. <ide> """ <ide> sphinx_spelling_errors = [] <ide><path>tests/core/test_core_to_contrib.py <ide> def skip_test_with_mssql_in_py38(self, path_a="", path_b=""): <ide> @staticmethod <ide> def get_class_from_path(path_to_class, parent=False): <ide> """ <del> :param parent indicates if "path_to_class" arg is super class <add> :param path_to_class: the path to the class <add> :param parent: indicates if "path_to_class" arg is super class <ide> """ <ide> <ide> path, _, class_name = path_to_class.rpartition(".") <ide><path>tests/core/test_logging_config.py <ide> def settings_context(content, directory=None, name='LOGGING_CONFIG'): <ide> <ide> :param content: <ide> The content of the settings file <add> :param directory: the directory <add> :param name: str <ide> """ <ide> initial_logging_config = os.environ.get("AIRFLOW__LOGGING__LOGGING_CONFIG_CLASS", "") <ide> try:
7
Mixed
Javascript
limit onhover to chartarea
0ae0fd4b2a659f1ac3fde4ffd46608c3f747ca22
<ide><path>docs/configuration/interactions.md <ide> Namespace: `options` <ide> | Name | Type | Default | Description <ide> | ---- | ---- | ------- | ----------- <ide> | `events` | `string[]` | `['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove']` | The `events` option defines the browser events that the chart should listen to for. Each of these events trigger hover and are passed to plugins. [more...](#event-option) <del>| `onHover` | `function` | `null` | Called when any of the events fire. Passed the event, an array of active elements (bars, points, etc), and the chart. <del>| `onClick` | `function` | `null` | Called if the event is of type `'mouseup'` or `'click'`. Passed the event, an array of active elements, and the chart. <add>| `onHover` | `function` | `null` | Called when any of the events fire over chartArea. Passed the event, an array of active elements (bars, points, etc), and the chart. <add>| `onClick` | `function` | `null` | Called if the event is of type `'mouseup'`, `'click'` or '`'contextmenu'` over chartArea. Passed the event, an array of active elements, and the chart. <ide> <ide> ### Event Option <ide> <ide><path>src/core/core.controller.js <ide> class Chart { <ide> // This prevents recursion if the handler calls chart.update() <ide> me._lastEvent = null; <ide> <del> // Invoke onHover hook <del> callCallback(options.onHover, [e, active, me], me); <add> if (_isPointInArea(e, me.chartArea, me._minPadding)) { <add> // Invoke onHover hook <add> callCallback(options.onHover, [e, active, me], me); <ide> <del> if (e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu') { <del> if (_isPointInArea(e, me.chartArea, me._minPadding)) { <add> if (e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu') { <ide> callCallback(options.onClick, [e, active, me], me); <ide> } <ide> }
2
PHP
PHP
improve doc block
eacec3404a9dada6bfda13e4caf1a8c1d1d09e00
<ide><path>src/Controller/Component/CheckHttpCacheComponent.php <ide> * Use HTTP caching headers to see if rendering can be skipped. <ide> * <ide> * Checks if the response can be considered different according to the request <del> * headers, and the caching response headers. If it was not modified, then the <del> * controller and view render process is skipped. And the client will get a <del> * empty response with a "304 Not Modified" header. <add> * headers, and caching headers in the response. If the response was not modified, <add> * then the controller and view render process is skipped. And the client will get a <add> * response with an empty body and a "304 Not Modified" header. <ide> * <ide> * To use this component your controller actions must set either the `Last-Modified` <ide> * or `Etag` header. Without one of these headers being set this component
1
Python
Python
introduce tests for urlize_quoted_links() function
ef1d65282771c806f68d717d57172597184db26c
<ide><path>rest_framework/tests/test_urlizer.py <add>from __future__ import unicode_literals <add>from django.test import TestCase <add>from rest_framework.templatetags.rest_framework import urlize_quoted_links <add>import sys <add> <add> <add>class URLizerTests(TestCase): <add> """ <add> Test if both JSON and YAML URLs are transformed into links well <add> """ <add> def _urlize_dict_check(self, data): <add> """ <add> For all items in dict test assert that the value is urlized key <add> """ <add> for original, urlized in data.items(): <add> assert urlize_quoted_links(original, nofollow=False) == urlized <add> <add> def test_json_with_url(self): <add> """ <add> Test if JSON URLs are transformed into links well <add> """ <add> data = {} <add> data['"url": "http://api/users/1/", '] = \ <add> '&quot;url&quot;: &quot;<a href="http://api/users/1/">http://api/users/1/</a>&quot;, ' <add> data['"foo_set": [\n "http://api/foos/1/"\n], '] = \ <add> '&quot;foo_set&quot;: [\n &quot;<a href="http://api/foos/1/">http://api/foos/1/</a>&quot;\n], ' <add> self._urlize_dict_check(data) <add> <add> def test_yaml_with_url(self): <add> """ <add> Test if YAML URLs are transformed into links well <add> """ <add> data = {} <add> data['''{users: 'http://api/users/'}'''] = \ <add> '''{users: &#39;<a href="http://api/users/">http://api/users/</a>&#39;}''' <add> data['''foo_set: ['http://api/foos/1/']'''] = \ <add> '''foo_set: [&#39;<a href="http://api/foos/1/">http://api/foos/1/</a>&#39;]''' <add> self._urlize_dict_check(data)
1
Python
Python
remove old seq2seq file
61ed8890052eb628fe969ed440a38ff82577595c
<ide><path>transformers/modeling_seq2seq.py <del># coding=utf-8 <del># Copyright 2018 The HuggingFace Inc. team. <del># <del># Licensed under the Apache License, Version 2.0 (the "License"); <del># you may not use this file except in compliance with the License. <del># You may obtain a copy of the License at <del># <del># http://www.apache.org/licenses/LICENSE-2.0 <del># <del># Unless required by applicable law or agreed to in writing, software <del># distributed under the License is distributed on an "AS IS" BASIS, <del># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del># See the License for the specific language governing permissions and <del># limitations under the License. <del>""" Conditional generation class. """ <del> <del> <del>class Seq2SeqModel(object): <del> def __init__(self): <del> raise EnvironmentError( <del> """Seq2Seq is designed to be instantiated using the <del> `Seq2Seq.from_pretrained(encoder_name_or_path, decoder_name_or_path)` method.""" <del> ) <del> <del> @classmethod <del> def from_pretrained(cls, encoder_name, decoder_name): <del> # Here we should call AutoModel to initialize the models depending <del> # on the pretrained models taken as an input. <del> # For a first iteration we only work with Bert. <del> raise NotImplementedError <del> <del> def __call__(self): <del> # allows to call an instance of the class <del> # model = Seq2Seq(encode='bert', decoder='bert') <del> raise NotImplementedError <del> <del> def process(self): <del> # alternative API to __call__ it is more explicit. <del> raise NotImplementedError <ide><path>transformers/tests/modeling_bert_test.py <ide> def create_and_check_bert_for_multiple_choice(self, config, input_ids, token_typ <ide> [self.batch_size, self.num_choices]) <ide> self.check_loss_output(result) <ide> <del> def create_and_check_bert2bert(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <add> def create_and_check_bert2rnd(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> config.num_choices = self.num_choices <ide> model = Bert2Rnd(config=config) <ide> model.eval() <ide><path>transformers/tests/modeling_seq2seq_test.py <del># coding=utf-8 <del># Copyright 2018 The Google AI Language Team Authors. <del># <del># Licensed under the Apache License, Version 2.0 (the "License"); <del># you may not use this file except in compliance with the License. <del># You may obtain a copy of the License at <del># <del># http://www.apache.org/licenses/LICENSE-2.0 <del># <del># Unless required by applicable law or agreed to in writing, software <del># distributed under the License is distributed on an "AS IS" BASIS, <del># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del># See the License for the specific language governing permissions and <del># limitations under the License. <del>import unittest <del> <del> <del>class Seq2SeqTest(unittest.TestCase): <del> raise NotImplementedError <del> <del> <del>def __main__(): <del> unittest.main()
3
Python
Python
remove dropout in embedding layer of opt
adbf3a40de3524dcdce556914e2cb974d81854e5
<ide><path>src/transformers/models/opt/modeling_flax_opt.py <ide> def __call__( <ide> <ide> hidden_states = inputs_embeds + positions <ide> <del> hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic) <del> <ide> hidden_state, all_hidden_states, attentions = self.layers( <ide> hidden_states, <ide> attention_mask, <ide><path>src/transformers/models/opt/modeling_opt.py <ide> def forward( <ide> inputs_embeds = self.project_in(inputs_embeds) <ide> <ide> hidden_states = inputs_embeds + pos_embeds <del> hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) <ide> <ide> # decoder layers <ide> all_hidden_states = () if output_hidden_states else None <ide><path>src/transformers/models/opt/modeling_tf_opt.py <ide> def call( <ide> inputs_embeds = self.project_in(inputs_embeds) <ide> <ide> hidden_states = inputs_embeds + pos_embeds <del> hidden_states = self.dropout(hidden_states, training=training) <ide> <ide> # decoder layers <ide> all_hidden_states = () if output_hidden_states else None
3
Text
Text
fix opening bullets
5cdb23c722dbec0a4a5f74f2b64250bf410db5e2
<ide><path>guides/source/migrations.md <ide> In this guide, you'll learn all about migrations including: <ide> <ide> * The generators you can use to create them <ide> * The methods Active Record provides to manipulate your database <del>* The Rake tasks that manipulate them <del>* How they relate to `schema.rb` <add>* The Rake tasks that manipulate migrations and your schema <add>* How migrations relate to `schema.rb` <ide> <ide> -------------------------------------------------------------------------------- <ide>
1
Ruby
Ruby
remove conditional that is always true
e87ff501932eb1baecafcca64518e3763597163e
<ide><path>activerecord/lib/active_record/transactions.rb <ide> def rolledback!(force_restore_state: false, should_run_callbacks: true) #:nodoc: <ide> # Add the record to the current transaction so that the +after_rollback+ and +after_commit+ callbacks <ide> # can be called. <ide> def add_to_transaction <del> if self.class.connection.add_transaction_record(self) <del> remember_transaction_record_state <del> end <add> self.class.connection.add_transaction_record(self) <add> remember_transaction_record_state <ide> end <ide> <ide> # Executes +method+ within a transaction and captures its return value as a
1
PHP
PHP
use eventinterface instead of event for typehints
74c54232f663592a7f08d007a1a9a8cb71c3a26a
<ide><path>src/Auth/BaseAuthenticate.php <ide> public function unauthenticated(ServerRequest $request, Response $response) <ide> * <ide> * - `Auth.afterIdentify` - Fired after a user has been identified using one of <ide> * configured authenticate class. The callback function should have signature <del> * like `afterIdentify(Event $event, array $user)` when `$user` is the <add> * like `afterIdentify(EventInterface $event, array $user)` when `$user` is the <ide> * identified user record. <ide> * <ide> * - `Auth.logout` - Fired when AuthComponent::logout() is called. The callback <del> * function should have signature like `logout(Event $event, array $user)` <add> * function should have signature like `logout(EventInterface $event, array $user)` <ide> * where `$user` is the user about to be logged out. <ide> * <ide> * @return array List of events this class listens to. Defaults to `[]`. <ide><path>src/Controller/Component.php <ide> * Components can provide several callbacks that are fired at various stages of the request <ide> * cycle. The available callbacks are: <ide> * <del> * - `beforeFilter(Event $event)` <add> * - `beforeFilter(EventInterface $event)` <ide> * Called before the controller's beforeFilter method by default. <del> * - `startup(Event $event)` <add> * - `startup(EventInterface $event)` <ide> * Called after the controller's beforeFilter method, and before the <ide> * controller action is called. <del> * - `beforeRender(Event $event)` <add> * - `beforeRender(EventInterface $event)` <ide> * Called before the Controller beforeRender, and before the view class is loaded. <del> * - `shutdown(Event $event)` <add> * - `shutdown(EventInterface $event)` <ide> * Called after the action is complete and the view has been rendered but <ide> * before Controller::afterFilter(). <del> * - `beforeRedirect(Event $event $url, Response $response)` <add> * - `beforeRedirect(EventInterface $event $url, Response $response)` <ide> * Called before a redirect is done. Allows you to change the URL that will <ide> * be redirected to by returning a Response instance with new URL set using <ide> * Response::location(). Redirection can be prevented by stopping the event <ide> * propagation. <ide> * <ide> * While the controller is not an explicit argument for the callback methods it <del> * is the subject of each event and can be fetched using Event::getSubject(). <add> * is the subject of each event and can be fetched using EventInterface::getSubject(). <ide> * <ide> * @link https://book.cakephp.org/3.0/en/controllers/components.html <ide> * @see \Cake\Controller\Controller::$components <ide><path>src/Controller/Component/AuthComponent.php <ide> use Cake\Controller\Controller; <ide> use Cake\Core\App; <ide> use Cake\Core\Exception\Exception; <del>use Cake\Event\Event; <ide> use Cake\Event\EventDispatcherTrait; <add>use Cake\Event\EventInterface; <ide> use Cake\Http\Exception\ForbiddenException; <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> public function initialize(array $config) <ide> /** <ide> * Callback for Controller.startup event. <ide> * <del> * @param \Cake\Event\Event $event Event instance. <add> * @param \Cake\Event\EventInterface $event Event instance. <ide> * @return \Cake\Http\Response|null <ide> */ <del> public function startup(Event $event) <add> public function startup(EventInterface $event) <ide> { <ide> return $this->authCheck($event); <ide> } <ide> public function startup(Event $event) <ide> * The auth check is done when event name is same as the one configured in <ide> * `checkAuthIn` config. <ide> * <del> * @param \Cake\Event\Event $event Event instance. <add> * @param \Cake\Event\EventInterface $event Event instance. <ide> * @return \Cake\Http\Response|null <ide> * @throws \ReflectionException <ide> */ <del> public function authCheck(Event $event) <add> public function authCheck(EventInterface $event) <ide> { <ide> if ($this->_config['checkAuthIn'] !== $event->getName()) { <ide> return null; <ide><path>src/Controller/Component/RequestHandlerComponent.php <ide> use Cake\Controller\Controller; <ide> use Cake\Core\App; <ide> use Cake\Core\Configure; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Routing\Router; <ide> use Cake\Utility\Exception\XmlException; <ide> use Cake\Utility\Inflector; <ide> protected function _setExtension($request, $response) <ide> * If the XML data is POSTed, the data is parsed into an XML object, which is assigned <ide> * to the $data property of the controller, which can then be saved to a model object. <ide> * <del> * @param \Cake\Event\Event $event The startup event that was fired. <add> * @param \Cake\Event\EventInterface $event The startup event that was fired. <ide> * @return void <ide> */ <del> public function startup(Event $event) <add> public function startup(EventInterface $event) <ide> { <ide> /** @var \Cake\Controller\Controller $controller */ <ide> $controller = $event->getSubject(); <ide> public function convertXml($xml) <ide> * - If the extension is of a type that RequestHandler understands, it will <ide> * set that Content-type in the response header. <ide> * <del> * @param \Cake\Event\Event $event The Controller.beforeRender event. <add> * @param \Cake\Event\EventInterface $event The Controller.beforeRender event. <ide> * @return bool false if the render process should be aborted <ide> */ <del> public function beforeRender(Event $event) <add> public function beforeRender(EventInterface $event) <ide> { <ide> /** @var \Cake\Controller\Controller $controller */ <ide> $controller = $event->getSubject(); <ide><path>src/Controller/Component/SecurityComponent.php <ide> use Cake\Controller\Exception\AuthSecurityException; <ide> use Cake\Controller\Exception\SecurityException; <ide> use Cake\Core\Configure; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Http\Exception\BadRequestException; <ide> use Cake\Http\ServerRequest; <ide> use Cake\Routing\Router; <ide> class SecurityComponent extends Component <ide> /** <ide> * Component startup. All security checking happens here. <ide> * <del> * @param \Cake\Event\Event $event An Event instance <add> * @param \Cake\Event\EventInterface $event An Event instance <ide> * @return mixed <ide> */ <del> public function startup(Event $event) <add> public function startup(EventInterface $event) <ide> { <ide> /** @var \Cake\Controller\Controller $controller */ <ide> $controller = $event->getSubject(); <ide><path>src/Controller/Controller.php <ide> <ide> use Cake\Controller\Exception\MissingActionException; <ide> use Cake\Datasource\ModelAwareTrait; <del>use Cake\Event\Event; <ide> use Cake\Event\EventDispatcherInterface; <ide> use Cake\Event\EventDispatcherTrait; <add>use Cake\Event\EventInterface; <ide> use Cake\Event\EventListenerInterface; <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> * By implementing a method you can receive the related events. The available <ide> * callbacks are: <ide> * <del> * - `beforeFilter(Event $event)` <add> * - `beforeFilter(EventInterface $event)` <ide> * Called before each action. This is a good place to do general logic that <ide> * applies to all actions. <del> * - `beforeRender(Event $event)` <add> * - `beforeRender(EventInterface $event)` <ide> * Called before the view is rendered. <del> * - `beforeRedirect(Event $event, $url, Response $response)` <add> * - `beforeRedirect(EventInterface $event, $url, Response $response)` <ide> * Called before a redirect is done. <del> * - `afterFilter(Event $event)` <add> * - `afterFilter(EventInterface $event)` <ide> * Called after each action is complete and after the view is rendered. <ide> * <ide> * @property \Cake\Controller\Component\AuthComponent $Auth <ide> public function isAction($action) <ide> * Called before the controller action. You can use this method to configure and customize components <ide> * or perform logic that needs to happen before each controller action. <ide> * <del> * @param \Cake\Event\Event $event An Event instance <add> * @param \Cake\Event\EventInterface $event An Event instance <ide> * @return \Cake\Http\Response|null <ide> * @link https://book.cakephp.org/3.0/en/controllers.html#request-life-cycle-callbacks <ide> */ <del> public function beforeFilter(Event $event) <add> public function beforeFilter(EventInterface $event) <ide> { <ide> return null; <ide> } <ide> public function beforeFilter(Event $event) <ide> * Called after the controller action is run, but before the view is rendered. You can use this method <ide> * to perform logic or set view variables that are required on every request. <ide> * <del> * @param \Cake\Event\Event $event An Event instance <add> * @param \Cake\Event\EventInterface $event An Event instance <ide> * @return \Cake\Http\Response|null <ide> * @link https://book.cakephp.org/3.0/en/controllers.html#request-life-cycle-callbacks <ide> */ <del> public function beforeRender(Event $event) <add> public function beforeRender(EventInterface $event) <ide> { <ide> return null; <ide> } <ide> public function beforeRender(Event $event) <ide> * You can set the event result to response instance or modify the redirect location <ide> * using controller's response instance. <ide> * <del> * @param \Cake\Event\Event $event An Event instance <add> * @param \Cake\Event\EventInterface $event An Event instance <ide> * @param string|array $url A string or array-based URL pointing to another location within the app, <ide> * or an absolute URL <ide> * @param \Cake\Http\Response $response The response object. <ide> * @return \Cake\Http\Response|null <ide> * @link https://book.cakephp.org/3.0/en/controllers.html#request-life-cycle-callbacks <ide> */ <del> public function beforeRedirect(Event $event, $url, Response $response) <add> public function beforeRedirect(EventInterface $event, $url, Response $response) <ide> { <ide> return null; <ide> } <ide> <ide> /** <ide> * Called after the controller action is run and rendered. <ide> * <del> * @param \Cake\Event\Event $event An Event instance <add> * @param \Cake\Event\EventInterface $event An Event instance <ide> * @return \Cake\Http\Response|null <ide> * @link https://book.cakephp.org/3.0/en/controllers.html#request-life-cycle-callbacks <ide> */ <del> public function afterFilter(Event $event) <add> public function afterFilter(EventInterface $event) <ide> { <ide> return null; <ide> } <ide><path>src/Controller/ErrorController.php <ide> */ <ide> namespace Cake\Controller; <ide> <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> <ide> /** <ide> * Error Handling Controller <ide> public function initialize() <ide> /** <ide> * beforeRender callback. <ide> * <del> * @param \Cake\Event\Event $event Event. <add> * @param \Cake\Event\EventInterface $event Event. <ide> * @return void <ide> */ <del> public function beforeRender(Event $event) <add> public function beforeRender(EventInterface $event) <ide> { <ide> $this->viewBuilder()->setTemplatePath('Error'); <ide> } <ide><path>src/Event/Decorator/ConditionDecorator.php <ide> */ <ide> namespace Cake\Event\Decorator; <ide> <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use RuntimeException; <ide> <ide> /** <ide> public function __invoke() <ide> /** <ide> * Checks if the event is triggered for this listener. <ide> * <del> * @param \Cake\Event\Event $event Event object. <add> * @param \Cake\Event\EventInterface $event Event object. <ide> * @return bool <ide> */ <del> public function canTrigger(Event $event) <add> public function canTrigger(EventInterface $event) <ide> { <ide> $if = $this->_evaluateCondition('if', $event); <ide> $unless = $this->_evaluateCondition('unless', $event); <ide> public function canTrigger(Event $event) <ide> * Evaluates the filter conditions <ide> * <ide> * @param string $condition Condition type <del> * @param \Cake\Event\Event $event Event object <add> * @param \Cake\Event\EventInterface $event Event object <ide> * @return bool <ide> */ <del> protected function _evaluateCondition($condition, Event $event) <add> protected function _evaluateCondition($condition, EventInterface $event) <ide> { <ide> if (!isset($this->_options[$condition])) { <ide> return $condition !== 'unless'; <ide><path>src/Event/Decorator/SubjectFilterDecorator.php <ide> */ <ide> namespace Cake\Event\Decorator; <ide> <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use RuntimeException; <ide> <ide> /** <ide> public function __invoke() <ide> /** <ide> * Checks if the event is triggered for this listener. <ide> * <del> * @param \Cake\Event\Event $event Event object. <add> * @param \Cake\Event\EventInterface $event Event object. <ide> * @return bool <ide> */ <del> public function canTrigger(Event $event) <add> public function canTrigger(EventInterface $event) <ide> { <ide> $class = get_class($event->getSubject()); <ide> if (!isset($this->_options['allowedSubject'])) { <ide><path>src/Event/EventDispatcherInterface.php <ide> interface EventDispatcherInterface <ide> * @param object|null $subject The object that this event applies to <ide> * ($this by default). <ide> * <del> * @return \Cake\Event\Event <add> * @return \Cake\Event\EventInterface <ide> */ <ide> public function dispatchEvent($name, $data = null, $subject = null); <ide> <ide><path>src/Event/EventDispatcherTrait.php <ide> public function setEventManager(EventManagerInterface $eventManager) <ide> * @param object|null $subject The object that this event applies to <ide> * ($this by default). <ide> * <del> * @return \Cake\Event\Event <add> * @return \Cake\Event\EventInterface <ide> */ <ide> public function dispatchEvent($name, $data = null, $subject = null) <ide> { <ide><path>src/Event/EventList.php <ide> public function flush() <ide> /** <ide> * Adds an event to the list when event listing is enabled. <ide> * <del> * @param \Cake\Event\Event $event An event to the list of dispatched events. <add> * @param \Cake\Event\EventInterface $event An event to the list of dispatched events. <ide> * @return void <ide> */ <del> public function add(Event $event) <add> public function add(EventInterface $event) <ide> { <ide> $this->_events[] = $event; <ide> } <ide><path>src/Event/EventManager.php <ide> public function dispatch($event) <ide> * Calls a listener. <ide> * <ide> * @param callable $listener The listener to trigger. <del> * @param \Cake\Event\Event $event Event instance. <add> * @param \Cake\Event\EventInterface $event Event instance. <ide> * @return mixed The result of the $listener function. <ide> */ <del> protected function _callListener(callable $listener, Event $event) <add> protected function _callListener(callable $listener, EventInterface $event) <ide> { <ide> $data = $event->getData(); <ide> <ide> public function getEventList() <ide> /** <ide> * Adds an event to the list if the event list object is present. <ide> * <del> * @param \Cake\Event\Event $event An event to add to the list. <add> * @param \Cake\Event\EventInterface $event An event to add to the list. <ide> * @return $this <ide> */ <del> public function addEventToList(Event $event) <add> public function addEventToList(EventInterface $event) <ide> { <ide> if ($this->_eventList) { <ide> $this->_eventList->add($event); <ide><path>src/Mailer/Mailer.php <ide> * ]; <ide> * } <ide> * <del> * public function onRegistration(Event $event, Entity $entity, ArrayObject $options) <add> * public function onRegistration(EventInterface $event, Entity $entity, ArrayObject $options) <ide> * { <ide> * if ($entity->isNew()) { <ide> * $this->send('welcome', [$entity]); <ide><path>src/ORM/Behavior.php <ide> * CakePHP provides a number of lifecycle events your behaviors can <ide> * listen to: <ide> * <del> * - `beforeFind(Event $event, Query $query, ArrayObject $options, boolean $primary)` <add> * - `beforeFind(EventInterface $event, Query $query, ArrayObject $options, boolean $primary)` <ide> * Fired before each find operation. By stopping the event and supplying a <ide> * return value you can bypass the find operation entirely. Any changes done <ide> * to the $query instance will be retained for the rest of the find. The <ide> * $primary parameter indicates whether or not this is the root query, <ide> * or an associated query. <ide> * <del> * - `buildValidator(Event $event, Validator $validator, string $name)` <add> * - `buildValidator(EventInterface $event, Validator $validator, string $name)` <ide> * Fired when the validator object identified by $name is being built. You can use this <ide> * callback to add validation rules or add validation providers. <ide> * <del> * - `buildRules(Event $event, RulesChecker $rules)` <add> * - `buildRules(EventInterface $event, RulesChecker $rules)` <ide> * Fired when the rules checking object for the table is being built. You can use this <ide> * callback to add more rules to the set. <ide> * <del> * - `beforeRules(Event $event, EntityInterface $entity, ArrayObject $options, $operation)` <add> * - `beforeRules(EventInterface $event, EntityInterface $entity, ArrayObject $options, $operation)` <ide> * Fired before an entity is validated using by a rules checker. By stopping this event, <ide> * you can return the final value of the rules checking operation. <ide> * <del> * - `afterRules(Event $event, EntityInterface $entity, ArrayObject $options, bool $result, $operation)` <add> * - `afterRules(EventInterface $event, EntityInterface $entity, ArrayObject $options, bool $result, $operation)` <ide> * Fired after the rules have been checked on the entity. By stopping this event, <ide> * you can return the final value of the rules checking operation. <ide> * <del> * - `beforeSave(Event $event, EntityInterface $entity, ArrayObject $options)` <add> * - `beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)` <ide> * Fired before each entity is saved. Stopping this event will abort the save <ide> * operation. When the event is stopped the result of the event will be returned. <ide> * <del> * - `afterSave(Event $event, EntityInterface $entity, ArrayObject $options)` <add> * - `afterSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)` <ide> * Fired after an entity is saved. <ide> * <del> * - `beforeDelete(Event $event, EntityInterface $entity, ArrayObject $options)` <add> * - `beforeDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options)` <ide> * Fired before an entity is deleted. By stopping this event you will abort <ide> * the delete operation. <ide> * <del> * - `afterDelete(Event $event, EntityInterface $entity, ArrayObject $options)` <add> * - `afterDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options)` <ide> * Fired after an entity has been deleted. <ide> * <ide> * In addition to the core events, behaviors can respond to any <ide><path>src/ORM/Behavior/CounterCacheBehavior.php <ide> namespace Cake\ORM\Behavior; <ide> <ide> use Cake\Datasource\EntityInterface; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\ORM\Association; <ide> use Cake\ORM\Behavior; <ide> use RuntimeException; <ide> * ``` <ide> * [ <ide> * 'Users' => [ <del> * 'posts_published' => function (Event $event, EntityInterface $entity, Table $table) { <add> * 'posts_published' => function (EventInterface $event, EntityInterface $entity, Table $table) { <ide> * $query = $table->find('all')->where([ <ide> * 'published' => true, <ide> * 'user_id' => $entity->get('user_id') <ide> class CounterCacheBehavior extends Behavior <ide> * <ide> * Check if a field, which should be ignored, is dirty <ide> * <del> * @param \Cake\Event\Event $event The beforeSave event that was fired <add> * @param \Cake\Event\EventInterface $event The beforeSave event that was fired <ide> * @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved <ide> * @param \ArrayObject $options The options for the query <ide> * @return void <ide> */ <del> public function beforeSave(Event $event, EntityInterface $entity, $options) <add> public function beforeSave(EventInterface $event, EntityInterface $entity, $options) <ide> { <ide> if (isset($options['ignoreCounterCache']) && $options['ignoreCounterCache'] === true) { <ide> return; <ide> public function beforeSave(Event $event, EntityInterface $entity, $options) <ide> * <ide> * Makes sure to update counter cache when a new record is created or updated. <ide> * <del> * @param \Cake\Event\Event $event The afterSave event that was fired. <add> * @param \Cake\Event\EventInterface $event The afterSave event that was fired. <ide> * @param \Cake\Datasource\EntityInterface $entity The entity that was saved. <ide> * @param \ArrayObject $options The options for the query <ide> * @return void <ide> */ <del> public function afterSave(Event $event, EntityInterface $entity, $options) <add> public function afterSave(EventInterface $event, EntityInterface $entity, $options) <ide> { <ide> if (isset($options['ignoreCounterCache']) && $options['ignoreCounterCache'] === true) { <ide> return; <ide> public function afterSave(Event $event, EntityInterface $entity, $options) <ide> * <ide> * Makes sure to update counter cache when a record is deleted. <ide> * <del> * @param \Cake\Event\Event $event The afterDelete event that was fired. <add> * @param \Cake\Event\EventInterface $event The afterDelete event that was fired. <ide> * @param \Cake\Datasource\EntityInterface $entity The entity that was deleted. <ide> * @param \ArrayObject $options The options for the query <ide> * @return void <ide> */ <del> public function afterDelete(Event $event, EntityInterface $entity, $options) <add> public function afterDelete(EventInterface $event, EntityInterface $entity, $options) <ide> { <ide> if (isset($options['ignoreCounterCache']) && $options['ignoreCounterCache'] === true) { <ide> return; <ide> public function afterDelete(Event $event, EntityInterface $entity, $options) <ide> /** <ide> * Iterate all associations and update counter caches. <ide> * <del> * @param \Cake\Event\Event $event Event instance. <add> * @param \Cake\Event\EventInterface $event Event instance. <ide> * @param \Cake\Datasource\EntityInterface $entity Entity. <ide> * @return void <ide> */ <del> protected function _processAssociations(Event $event, EntityInterface $entity) <add> protected function _processAssociations(EventInterface $event, EntityInterface $entity) <ide> { <ide> foreach ($this->_config as $assoc => $settings) { <ide> $assoc = $this->_table->getAssociation($assoc); <ide> protected function _processAssociations(Event $event, EntityInterface $entity) <ide> /** <ide> * Updates counter cache for a single association <ide> * <del> * @param \Cake\Event\Event $event Event instance. <add> * @param \Cake\Event\EventInterface $event Event instance. <ide> * @param \Cake\Datasource\EntityInterface $entity Entity <ide> * @param \Cake\ORM\Association $assoc The association object <ide> * @param array $settings The settings for for counter cache for this association <ide> * @return void <ide> * @throws \RuntimeException If invalid callable is passed. <ide> */ <del> protected function _processAssociation(Event $event, EntityInterface $entity, Association $assoc, array $settings) <add> protected function _processAssociation(EventInterface $event, EntityInterface $entity, Association $assoc, array $settings) <ide> { <ide> $foreignKeys = (array)$assoc->getForeignKey(); <ide> $primaryKeys = (array)$assoc->getBindingKey(); <ide><path>src/ORM/Behavior/TimestampBehavior.php <ide> use Cake\Database\TypeFactory; <ide> use Cake\Database\Type\DateTimeType; <ide> use Cake\Datasource\EntityInterface; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\I18n\Time; <ide> use Cake\ORM\Behavior; <ide> use DateTime; <ide> public function initialize(array $config) <ide> /** <ide> * There is only one event handler, it can be configured to be called for any event <ide> * <del> * @param \Cake\Event\Event $event Event instance. <add> * @param \Cake\Event\EventInterface $event Event instance. <ide> * @param \Cake\Datasource\EntityInterface $entity Entity instance. <ide> * @throws \UnexpectedValueException if a field's when value is misdefined <ide> * @return bool Returns true irrespective of the behavior logic, the save will not be prevented. <ide> * @throws \UnexpectedValueException When the value for an event is not 'always', 'new' or 'existing' <ide> */ <del> public function handleEvent(Event $event, EntityInterface $entity) <add> public function handleEvent(EventInterface $event, EntityInterface $entity) <ide> { <ide> $eventName = $event->getName(); <ide> $events = $this->_config['events']; <ide><path>src/ORM/Behavior/TranslateBehavior.php <ide> use Cake\Collection\Collection; <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\Datasource\QueryInterface; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\I18n\I18n; <ide> use Cake\ORM\Behavior; <ide> use Cake\ORM\Entity; <ide> public function setupFieldAssociations($fields, $table, $model, $strategy) <ide> * table. It modifies the passed query by eager loading the translated fields <ide> * and adding a formatter to copy the values into the main table records. <ide> * <del> * @param \Cake\Event\Event $event The beforeFind event that was fired. <add> * @param \Cake\Event\EventInterface $event The beforeFind event that was fired. <ide> * @param \Cake\ORM\Query $query Query <ide> * @param \ArrayObject $options The options for the query <ide> * @return void <ide> */ <del> public function beforeFind(Event $event, Query $query, $options) <add> public function beforeFind(EventInterface $event, Query $query, $options) <ide> { <ide> $locale = $this->getLocale(); <ide> <ide> public function beforeFind(Event $event, Query $query, $options) <ide> * Modifies the entity before it is saved so that translated fields are persisted <ide> * in the database too. <ide> * <del> * @param \Cake\Event\Event $event The beforeSave event that was fired <add> * @param \Cake\Event\EventInterface $event The beforeSave event that was fired <ide> * @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved <ide> * @param \ArrayObject $options the options passed to the save method <ide> * @return void <ide> */ <del> public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options) <add> public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options) <ide> { <ide> $locale = $entity->get('_locale') ?: $this->getLocale(); <ide> $newOptions = [$this->_translationTable->getAlias() => ['validate' => false]]; <ide> public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $o <ide> /** <ide> * Unsets the temporary `_i18n` property after the entity has been saved <ide> * <del> * @param \Cake\Event\Event $event The beforeSave event that was fired <add> * @param \Cake\Event\EventInterface $event The beforeSave event that was fired <ide> * @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved <ide> * @return void <ide> */ <del> public function afterSave(Event $event, EntityInterface $entity) <add> public function afterSave(EventInterface $event, EntityInterface $entity) <ide> { <ide> $entity->unsetProperty('_i18n'); <ide> } <ide><path>src/ORM/Behavior/TreeBehavior.php <ide> use Cake\Database\Expression\IdentifierExpression; <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\Datasource\Exception\RecordNotFoundException; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\ORM\Behavior; <ide> use Cake\ORM\Query; <ide> use InvalidArgumentException; <ide> public function initialize(array $config) <ide> * Transparently manages setting the lft and rght fields if the parent field is <ide> * included in the parameters to be saved. <ide> * <del> * @param \Cake\Event\Event $event The beforeSave event that was fired <add> * @param \Cake\Event\EventInterface $event The beforeSave event that was fired <ide> * @param \Cake\Datasource\EntityInterface $entity the entity that is going to be saved <ide> * @return void <ide> * @throws \RuntimeException if the parent to set for the node is invalid <ide> */ <del> public function beforeSave(Event $event, EntityInterface $entity) <add> public function beforeSave(EventInterface $event, EntityInterface $entity) <ide> { <ide> $isNew = $entity->isNew(); <ide> $config = $this->getConfig(); <ide> public function beforeSave(Event $event, EntityInterface $entity) <ide> * <ide> * Manages updating level of descendants of currently saved entity. <ide> * <del> * @param \Cake\Event\Event $event The afterSave event that was fired <add> * @param \Cake\Event\EventInterface $event The afterSave event that was fired <ide> * @param \Cake\Datasource\EntityInterface $entity the entity that is going to be saved <ide> * @return void <ide> */ <del> public function afterSave(Event $event, EntityInterface $entity) <add> public function afterSave(EventInterface $event, EntityInterface $entity) <ide> { <ide> if (!$this->_config['level'] || $entity->isNew()) { <ide> return; <ide> protected function _setChildrenLevel($entity) <ide> /** <ide> * Also deletes the nodes in the subtree of the entity to be delete <ide> * <del> * @param \Cake\Event\Event $event The beforeDelete event that was fired <add> * @param \Cake\Event\EventInterface $event The beforeDelete event that was fired <ide> * @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved <ide> * @return void <ide> */ <del> public function beforeDelete(Event $event, EntityInterface $entity) <add> public function beforeDelete(EventInterface $event, EntityInterface $entity) <ide> { <ide> $config = $this->getConfig(); <ide> $this->_ensureFields($entity); <ide><path>src/ORM/Table.php <ide> * Table objects provide a few callbacks/events you can hook into to augment/replace <ide> * find operations. Each event uses the standard event subsystem in CakePHP <ide> * <del> * - `beforeFind(Event $event, Query $query, ArrayObject $options, boolean $primary)` <add> * - `beforeFind(EventInterface $event, Query $query, ArrayObject $options, boolean $primary)` <ide> * Fired before each find operation. By stopping the event and supplying a <ide> * return value you can bypass the find operation entirely. Any changes done <ide> * to the $query instance will be retained for the rest of the find. The <ide> * $primary parameter indicates whether or not this is the root query, <ide> * or an associated query. <ide> * <del> * - `buildValidator(Event $event, Validator $validator, string $name)` <add> * - `buildValidator(EventInterface $event, Validator $validator, string $name)` <ide> * Allows listeners to modify validation rules for the provided named validator. <ide> * <del> * - `buildRules(Event $event, RulesChecker $rules)` <add> * - `buildRules(EventInterface $event, RulesChecker $rules)` <ide> * Allows listeners to modify the rules checker by adding more rules. <ide> * <del> * - `beforeRules(Event $event, EntityInterface $entity, ArrayObject $options, string $operation)` <add> * - `beforeRules(EventInterface $event, EntityInterface $entity, ArrayObject $options, string $operation)` <ide> * Fired before an entity is validated using the rules checker. By stopping this event, <ide> * you can return the final value of the rules checking operation. <ide> * <del> * - `afterRules(Event $event, EntityInterface $entity, ArrayObject $options, bool $result, string $operation)` <add> * - `afterRules(EventInterface $event, EntityInterface $entity, ArrayObject $options, bool $result, string $operation)` <ide> * Fired after the rules have been checked on the entity. By stopping this event, <ide> * you can return the final value of the rules checking operation. <ide> * <del> * - `beforeSave(Event $event, EntityInterface $entity, ArrayObject $options)` <add> * - `beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)` <ide> * Fired before each entity is saved. Stopping this event will abort the save <ide> * operation. When the event is stopped the result of the event will be returned. <ide> * <del> * - `afterSave(Event $event, EntityInterface $entity, ArrayObject $options)` <add> * - `afterSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)` <ide> * Fired after an entity is saved. <ide> * <del> * - `afterSaveCommit(Event $event, EntityInterface $entity, ArrayObject $options)` <add> * - `afterSaveCommit(EventInterface $event, EntityInterface $entity, ArrayObject $options)` <ide> * Fired after the transaction in which the save operation is wrapped has been committed. <ide> * It’s also triggered for non atomic saves where database operations are implicitly committed. <ide> * The event is triggered only for the primary table on which save() is directly called. <ide> * The event is not triggered if a transaction is started before calling save. <ide> * <del> * - `beforeDelete(Event $event, EntityInterface $entity, ArrayObject $options)` <add> * - `beforeDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options)` <ide> * Fired before an entity is deleted. By stopping this event you will abort <ide> * the delete operation. <ide> * <del> * - `afterDelete(Event $event, EntityInterface $entity, ArrayObject $options)` <add> * - `afterDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options)` <ide> * Fired after an entity has been deleted. <ide> * <ide> * @see \Cake\Event\EventManager for reference on the events system. <ide><path>src/TestSuite/Constraint/EventFiredWith.php <ide> <?php <ide> namespace Cake\TestSuite\Constraint; <ide> <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use PHPUnit\Framework\AssertionFailedError; <ide> use PHPUnit\Framework\Constraint\Constraint; <ide> <ide> public function matches($other) <ide> } <ide> <ide> $eventGroup = collection($firedEvents) <del> ->groupBy(function (Event $event) { <add> ->groupBy(function (EventInterface $event) { <ide> return $event->getName(); <ide> }) <ide> ->toArray(); <ide> public function matches($other) <ide> throw new AssertionFailedError(sprintf('Event "%s" was fired %d times, cannot make data assertion', $other, count($events))); <ide> } <ide> <del> /* @var \Cake\Event\Event $event */ <add> /* @var \Cake\Event\EventInterface $event */ <ide> $event = $events[0]; <ide> <ide> if (array_key_exists($this->_dataKey, $event->getData()) === false) { <ide><path>src/TestSuite/IntegrationTestTrait.php <ide> protected function _makeDispatcher() <ide> /** <ide> * Adds additional event spies to the controller/view event manager. <ide> * <del> * @param \Cake\Event\Event $event A dispatcher event. <add> * @param \Cake\Event\EventInterface $event A dispatcher event. <ide> * @param \Cake\Controller\Controller|null $controller Controller instance. <ide> * @return void <ide> */ <ide><path>src/View/Helper.php <ide> * implementing a callback method subscribes a helper to the related event. The callback methods <ide> * are as follows: <ide> * <del> * - `beforeRender(Event $event, $viewFile)` - beforeRender is called before the view file is rendered. <del> * - `afterRender(Event $event, $viewFile)` - afterRender is called after the view file is rendered <add> * - `beforeRender(EventInterface $event, $viewFile)` - beforeRender is called before the view file is rendered. <add> * - `afterRender(EventInterface $event, $viewFile)` - afterRender is called after the view file is rendered <ide> * but before the layout has been rendered. <del> * - beforeLayout(Event $event, $layoutFile)` - beforeLayout is called before the layout is rendered. <del> * - `afterLayout(Event $event, $layoutFile)` - afterLayout is called after the layout has rendered. <del> * - `beforeRenderFile(Event $event, $viewFile)` - Called before any view fragment is rendered. <del> * - `afterRenderFile(Event $event, $viewFile, $content)` - Called after any view fragment is rendered. <add> * - beforeLayout(EventInterface $event, $layoutFile)` - beforeLayout is called before the layout is rendered. <add> * - `afterLayout(EventInterface $event, $layoutFile)` - afterLayout is called after the layout has rendered. <add> * - `beforeRenderFile(EventInterface $event, $viewFile)` - Called before any view fragment is rendered. <add> * - `afterRenderFile(EventInterface $event, $viewFile, $content)` - Called after any view fragment is rendered. <ide> * If a listener returns a non-null value, the output of the rendered file will be set to that. <ide> */ <ide> class Helper implements EventListenerInterface <ide><path>src/View/View.php <ide> * View class supports using plugins as themes. You can set <ide> * <ide> * ``` <del> * public function beforeRender(\Cake\Event\Event $event) <add> * public function beforeRender(\Cake\Event\EventInterface $event) <ide> * { <ide> * $this->viewBuilder()->setTheme('SuperHot'); <ide> * } <ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php <ide> use Cake\Controller\Component\AuthComponent; <ide> use Cake\Core\Configure; <ide> use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Event\EventManager; <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> public function testAfterIdentifyForStatelessAuthentication() <ide> ]); <ide> $this->Auth->setConfig('storage', 'Memory'); <ide> <del> EventManager::instance()->on('Auth.afterIdentify', function (Event $event) { <add> EventManager::instance()->on('Auth.afterIdentify', function (EventInterface $event) { <ide> $user = $event->getData(0); <ide> $user['from_callback'] = true; <ide> <ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> public function testRespondAsWithAttachment() <ide> */ <ide> public function testRenderAsCalledTwice() <ide> { <del> $this->Controller->getEventManager()->on('Controller.beforeRender', function (\Cake\Event\Event $e) { <add> $this->Controller->getEventManager()->on('Controller.beforeRender', function (\Cake\Event\EventInterface $e) { <ide> return $e->getSubject()->response; <ide> }); <ide> $this->Controller->render(); <ide><path>tests/TestCase/Controller/ControllerTest.php <ide> use Cake\Controller\Controller; <ide> use Cake\Core\Configure; <ide> use Cake\Core\Plugin; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\Routing\Router; <ide> class TestController extends ControllerTestAppController <ide> /** <ide> * beforeFilter handler <ide> * <del> * @param \Cake\Event\Event $event <add> * @param \Cake\Event\EventInterface $event <ide> * @return void <ide> */ <del> public function beforeFilter(Event $event) <add> public function beforeFilter(EventInterface $event) <ide> { <ide> } <ide> <ide> public function initialize(array $config) <ide> /** <ide> * startup method <ide> * <del> * @param Event $event <add> * @param \Cake\Event\EventInterface $event <ide> * @return void <ide> */ <del> public function startup(Event $event) <add> public function startup(EventInterface $event) <ide> { <ide> } <ide> <ide> /** <ide> * shutdown method <ide> * <del> * @param Event $event <add> * @param \Cake\Event\EventInterface $event <ide> * @return void <ide> */ <del> public function shutdown(Event $event) <add> public function shutdown(EventInterface $event) <ide> { <ide> } <ide> <ide> /** <ide> * beforeRender callback <ide> * <del> * @param Event $event <add> * @param \Cake\Event\EventInterface $event <ide> * @return void <ide> */ <del> public function beforeRender(Event $event) <add> public function beforeRender(EventInterface $event) <ide> { <ide> $controller = $event->getSubject(); <ide> if ($this->viewclass) { <ide> public function testBeforeRenderCallbackChangingViewClass() <ide> { <ide> $Controller = new Controller(new ServerRequest, new Response()); <ide> <del> $Controller->getEventManager()->on('Controller.beforeRender', function (Event $event) { <add> $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $event) { <ide> $controller = $event->getSubject(); <ide> $controller->viewBuilder()->setClassName('Json'); <ide> }); <ide> public function testBeforeRenderEventCancelsRender() <ide> { <ide> $Controller = new Controller(new ServerRequest, new Response()); <ide> <del> $Controller->getEventManager()->on('Controller.beforeRender', function (Event $event) { <add> $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $event) { <ide> return false; <ide> }); <ide> <ide> public function testRedirectBeforeRedirectModifyingUrl() <ide> { <ide> $Controller = new Controller(null, new Response()); <ide> <del> $Controller->getEventManager()->on('Controller.beforeRedirect', function (Event $event, $url, Response $response) { <add> $Controller->getEventManager()->on('Controller.beforeRedirect', function (EventInterface $event, $url, Response $response) { <ide> $controller = $event->getSubject(); <ide> $controller->setResponse($response->withLocation('https://book.cakephp.org')); <ide> }); <ide> public function testRedirectBeforeRedirectModifyingStatusCode() <ide> $response = new Response(); <ide> $Controller = new Controller(null, $response); <ide> <del> $Controller->getEventManager()->on('Controller.beforeRedirect', function (Event $event, $url, Response $response) { <add> $Controller->getEventManager()->on('Controller.beforeRedirect', function (EventInterface $event, $url, Response $response) { <ide> $controller = $event->getSubject(); <ide> $controller->setResponse($response->withStatus(302)); <ide> }); <ide> public function testRedirectBeforeRedirectListenerReturnResponse() <ide> $Controller = new Controller(null, $Response); <ide> <ide> $newResponse = new Response; <del> $Controller->getEventManager()->on('Controller.beforeRedirect', function (Event $event, $url, Response $response) use ($newResponse) { <add> $Controller->getEventManager()->on('Controller.beforeRedirect', function (EventInterface $event, $url, Response $response) use ($newResponse) { <ide> return $newResponse; <ide> }); <ide> <ide> public function testViewPathConventions() <ide> ]); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> $Controller = new \TestApp\Controller\Admin\PostsController($request, $response); <del> $Controller->getEventManager()->on('Controller.beforeRender', function (Event $e) { <add> $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) { <ide> return $e->getSubject()->response; <ide> }); <ide> $Controller->render(); <ide> public function testViewPathConventions() <ide> $request = $request->withParam('prefix', 'admin/super'); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> $Controller = new \TestApp\Controller\Admin\PostsController($request, $response); <del> $Controller->getEventManager()->on('Controller.beforeRender', function (Event $e) { <add> $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) { <ide> return $e->getSubject()->response; <ide> }); <ide> $Controller->render(); <ide> public function testViewPathConventions() <ide> ] <ide> ]); <ide> $Controller = new \TestApp\Controller\PagesController($request, $response); <del> $Controller->getEventManager()->on('Controller.beforeRender', function (Event $e) { <add> $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) { <ide> return $e->getSubject()->response; <ide> }); <ide> $Controller->render(); <ide> public function testBeforeRenderViewVariables() <ide> { <ide> $controller = new PostsController(); <ide> <del> $controller->getEventManager()->on('Controller.beforeRender', function (Event $event) { <add> $controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $event) { <ide> /* @var Controller $controller */ <ide> $controller = $event->getSubject(); <ide> <ide><path>tests/TestCase/Error/ExceptionRendererTest.php <ide> use Cake\Datasource\Exception\MissingDatasourceConfigException; <ide> use Cake\Datasource\Exception\MissingDatasourceException; <ide> use Cake\Error\ExceptionRenderer; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Event\EventManager; <ide> use Cake\Http\Exception\InternalErrorException; <ide> use Cake\Http\Exception\MethodNotAllowedException; <ide> class TestErrorController extends Controller <ide> * <ide> * @return void <ide> */ <del> public function beforeRender(Event $event) <add> public function beforeRender(EventInterface $event) <ide> { <ide> echo $this->Blueberry->testName; <ide> } <ide> public function testMissingLayoutPathRenderSafe() <ide> $ExceptionRenderer->controller = new Controller(); <ide> $ExceptionRenderer->controller->getEventManager()->on( <ide> 'Controller.beforeRender', <del> function (Event $event) { <add> function (EventInterface $event) { <ide> $this->called = true; <ide> $event->getSubject()->viewBuilder()->setLayoutPath('boom'); <ide> } <ide> public function testRenderWithNoRequest() <ide> public function testRenderShutdownEvents() <ide> { <ide> $fired = []; <del> $listener = function (Event $event) use (&$fired) { <add> $listener = function (EventInterface $event) use (&$fired) { <ide> $fired[] = $event->getName(); <ide> }; <ide> $events = EventManager::instance(); <ide> public function testRenderShutdownEvents() <ide> public function testSubclassTriggerShutdownEvents() <ide> { <ide> $fired = []; <del> $listener = function (Event $event) use (&$fired) { <add> $listener = function (EventInterface $event) use (&$fired) { <ide> $fired[] = $event->getName(); <ide> }; <ide> $events = EventManager::instance(); <ide><path>tests/TestCase/Event/Decorator/ConditionDecoratorTest.php <ide> <ide> use Cake\Event\Decorator\ConditionDecorator; <ide> use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Event\EventManager; <ide> use Cake\TestSuite\TestCase; <ide> <ide> class ConditionDecoratorTest extends TestCase <ide> */ <ide> public function testCanTriggerIf() <ide> { <del> $callable = function (Event $event) { <add> $callable = function (EventInterface $event) { <ide> return 'success'; <ide> }; <ide> <ide> $decorator = new ConditionDecorator($callable, [ <del> 'if' => function (Event $event) { <add> 'if' => function (EventInterface $event) { <ide> return $event->getData('canTrigger'); <ide> } <ide> ]); <ide> public function testCanTriggerIf() <ide> */ <ide> public function testCascadingEvents() <ide> { <del> $callable = function (Event $event) { <add> $callable = function (EventInterface $event) { <ide> $event->setData('counter', $event->getData('counter') + 1); <ide> <ide> return $event; <ide> }; <ide> <ide> $listener1 = new ConditionDecorator($callable, [ <del> 'if' => function (Event $event) { <add> 'if' => function (EventInterface $event) { <ide> return false; <ide> } <ide> ]); <ide> <del> $listener2 = function (Event $event) { <add> $listener2 = function (EventInterface $event) { <ide> $event->setData('counter', $event->getData('counter') + 1); <ide> <ide> return $event; <ide> public function testCallableRuntimeException() <ide> { <ide> $this->expectException(\RuntimeException::class); <ide> $this->expectExceptionMessage('Cake\Event\Decorator\ConditionDecorator the `if` condition is not a callable!'); <del> $callable = function (Event $event) { <add> $callable = function (EventInterface $event) { <ide> return 'success'; <ide> }; <ide> <ide><path>tests/TestCase/Event/Decorator/SubjectFilterDecoratorTest.php <ide> <ide> use Cake\Event\Decorator\SubjectFilterDecorator; <ide> use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\TestSuite\TestCase; <ide> <ide> /** <ide> class SubjectFilterDecoratorTest extends TestCase <ide> public function testCanTrigger() <ide> { <ide> $event = new Event('decorator.test', $this); <del> $callable = function (Event $event) { <add> $callable = function (EventInterface $event) { <ide> return 'success'; <ide> }; <ide> <ide><path>tests/TestCase/Event/EventManagerTest.php <ide> namespace Cake\Test\TestCase\Event; <ide> <ide> use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Event\EventList; <ide> use Cake\Event\EventListenerInterface; <ide> use Cake\Event\EventManager; <ide> public function secondListenerFunction() <ide> /** <ide> * Auxiliary function to help in stopPropagation testing <ide> * <del> * @param \Cake\Event\Event $event <add> * @param \Cake\Event\EventInterface $event <ide> * @return void <ide> */ <ide> public function stopListener($event) <ide> public function testDispatchGlobalBeforeLocal() <ide> /** <ide> * test callback <ide> * <del> * @param Event $event <add> * @param \Cake\Event\EventInterface $event <ide> */ <del> public function onMyEvent(Event $event) <add> public function onMyEvent(EventInterface $event) <ide> { <ide> $event->setData('callback', 'ok'); <ide> } <ide><path>tests/TestCase/Http/ActionDispatcherTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Http; <ide> <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Http\ActionDispatcher; <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> public function testDispatchAfterDispatchEventModifyResponse() <ide> 'session' => new Session <ide> ]); <ide> $res = new Response(); <del> $this->dispatcher->getEventManager()->on('Dispatcher.afterDispatch', function (Event $event) { <add> $this->dispatcher->getEventManager()->on('Dispatcher.afterDispatch', function (EventInterface $event) { <ide> $response = $event->getData('response'); <ide> $event->setData('response', $response->withStringBody('Filter body')); <ide> }); <ide><path>tests/TestCase/Http/ServerTest.php <ide> namespace Cake\Test\TestCase; <ide> <ide> use Cake\Core\HttpApplicationInterface; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Event\EventManager; <ide> use Cake\Http\BaseApplication; <ide> use Cake\Http\CallbackStream; <ide> public function testBuildMiddlewareEvent() <ide> $server = new Server($app); <ide> $this->called = false; <ide> <del> $server->getEventManager()->on('Server.buildMiddleware', function (Event $event, $middleware) { <add> $server->getEventManager()->on('Server.buildMiddleware', function (EventInterface $event, $middleware) { <ide> $this->assertInstanceOf('Cake\Http\MiddlewareQueue', $middleware); <ide> $middleware->add(function ($req, $res, $next) { <ide> $this->called = true; <ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php <ide> <ide> use Cake\Database\Expression\QueryExpression; <ide> use Cake\Datasource\ConnectionManager; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\ORM\Association\BelongsTo; <ide> use Cake\ORM\Association\BelongsToMany; <ide> use Cake\ORM\Association\HasMany; <ide> public function testReplaceLinkFailingDomainRules() <ide> { <ide> $articles = $this->getTableLocator()->get('Articles'); <ide> $tags = $this->getTableLocator()->get('Tags'); <del> $tags->getEventManager()->on('Model.buildRules', function (Event $event, $rules) { <add> $tags->getEventManager()->on('Model.buildRules', function (EventInterface $event, $rules) { <ide> $rules->add(function () { <ide> return false; <ide> }, 'rule', ['errorField' => 'name', 'message' => 'Bad data']); <ide><path>tests/TestCase/ORM/Behavior/CounterCacheBehaviorTest.php <ide> use Cake\Database\Query; <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\Datasource\EntityInterface; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\ORM\Entity; <ide> use Cake\ORM\Table; <ide> use Cake\TestSuite\TestCase; <ide> public function testLambdaNumber() <ide> <ide> $this->post->addBehavior('CounterCache', [ <ide> 'Users' => [ <del> 'posts_published' => function (Event $orgEvent, EntityInterface $orgEntity, Table $orgTable) use ($entity, $table) { <add> 'posts_published' => function (EventInterface $orgEvent, EntityInterface $orgEntity, Table $orgTable) use ($entity, $table) { <ide> $this->assertSame($orgTable, $table); <ide> $this->assertSame($orgEntity, $entity); <ide> <ide> public function testLambdaFalse() <ide> <ide> $this->post->addBehavior('CounterCache', [ <ide> 'Users' => [ <del> 'posts_published' => function (Event $orgEvent, EntityInterface $orgEntity, Table $orgTable) use ($entity, $table) { <add> 'posts_published' => function (EventInterface $orgEvent, EntityInterface $orgEntity, Table $orgTable) use ($entity, $table) { <ide> $this->assertSame($orgTable, $table); <ide> $this->assertSame($orgEntity, $entity); <ide> <ide> public function testLambdaNumberUpdate() <ide> <ide> $this->post->addBehavior('CounterCache', [ <ide> 'Users' => [ <del> 'posts_published' => function (Event $orgEvent, EntityInterface $orgEntity, Table $orgTable, $original) use ($entity, $table) { <add> 'posts_published' => function (EventInterface $orgEvent, EntityInterface $orgEntity, Table $orgTable, $original) use ($entity, $table) { <ide> $this->assertSame($orgTable, $table); <ide> $this->assertSame($orgEntity, $entity); <ide> <ide> public function testLambdaSubquery() <ide> <ide> $this->post->addBehavior('CounterCache', [ <ide> 'Users' => [ <del> 'posts_published' => function (Event $event, EntityInterface $entity, Table $table) { <add> 'posts_published' => function (EventInterface $event, EntityInterface $entity, Table $table) { <ide> $query = new Query($this->connection); <ide> <ide> return $query->select(4); <ide><path>tests/TestCase/ORM/MarshallerTest.php <ide> namespace Cake\Test\TestCase\ORM; <ide> <ide> use Cake\Database\Expression\IdentifierExpression; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\I18n\FrozenTime; <ide> use Cake\I18n\Time; <ide> use Cake\ORM\Entity; <ide> public function testMergeBelongsToManyFromArrayWithConditions() <ide> ]); <ide> <ide> $this->articles->Tags->getEventManager() <del> ->on('Model.beforeFind', function (Event $event, $query) use (&$called) { <add> ->on('Model.beforeFind', function (EventInterface $event, $query) use (&$called) { <ide> $called = true; <ide> <ide> return $query->where(['Tags.id >=' => 1]); <ide> public function testMergeManyExistingQueryAliases() <ide> ['id' => 1, 'comment' => 'Changed 1', 'user_id' => 1], <ide> ['id' => 2, 'comment' => 'Changed 2', 'user_id' => 2], <ide> ]; <del> $this->comments->getEventManager()->on('Model.beforeFind', function (Event $event, $query) { <add> $this->comments->getEventManager()->on('Model.beforeFind', function (EventInterface $event, $query) { <ide> return $query->contain(['Articles']); <ide> }); <ide> $marshall = new Marshaller($this->comments); <ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> use Cake\Database\Expression\Comparison; <ide> use Cake\Database\Expression\QueryExpression; <ide> use Cake\Datasource\EntityInterface; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\I18n\FrozenTime; <ide> use Cake\I18n\Time; <ide> use Cake\TestSuite\TestCase; <ide> public function testSaveWithCallbacks() <ide> $articles = $this->getTableLocator()->get('Articles'); <ide> $articles->belongsTo('Authors'); <ide> <del> $articles->getEventManager()->on('Model.beforeFind', function (Event $event, $query) { <add> $articles->getEventManager()->on('Model.beforeFind', function (EventInterface $event, $query) { <ide> return $query->contain('Authors'); <ide> }); <ide> <ide> public function testCountWithInnerJoinContain() <ide> $this->assertNotFalse($result); <ide> <ide> $table->getEventManager() <del> ->on('Model.beforeFind', function (Event $event, $query) { <add> ->on('Model.beforeFind', function (EventInterface $event, $query) { <ide> $query->contain(['Authors']); <ide> }); <ide> <ide><path>tests/TestCase/ORM/QueryTest.php <ide> use Cake\Database\TypeMap; <ide> use Cake\Database\ValueBinder; <ide> use Cake\Datasource\ConnectionManager; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\I18n\FrozenTime; <ide> use Cake\I18n\Time; <ide> use Cake\ORM\Query; <ide> public function testFormatResultsBelongsToMany() <ide> <ide> $articlesTags <ide> ->getEventManager() <del> ->on('Model.beforeFind', function (Event $event, $query) { <add> ->on('Model.beforeFind', function (EventInterface $event, $query) { <ide> $query->formatResults(function ($results) { <ide> foreach ($results as $result) { <ide> $result->beforeFind = true; <ide> public function testCountBeforeFind() <ide> $table = $this->getTableLocator()->get('Articles'); <ide> $table->hasMany('Comments'); <ide> $table->getEventManager() <del> ->on('Model.beforeFind', function (Event $event, $query) { <add> ->on('Model.beforeFind', function (EventInterface $event, $query) { <ide> $query <ide> ->limit(1) <ide> ->order(['Articles.title' => 'DESC']); <ide> public function testBeforeFindCalledOnce() <ide> $callCount = 0; <ide> $table = $this->getTableLocator()->get('Articles'); <ide> $table->getEventManager() <del> ->on('Model.beforeFind', function (Event $event, $query) use (&$callCount) { <add> ->on('Model.beforeFind', function (EventInterface $event, $query) use (&$callCount) { <ide> $valueBinder = new ValueBinder(); <ide> $query->sql($valueBinder); <ide> $callCount++; <ide> public function testCleanCopyBeforeFind() <ide> $table = $this->getTableLocator()->get('Articles'); <ide> $table->hasMany('Comments'); <ide> $table->getEventManager() <del> ->on('Model.beforeFind', function (Event $event, $query) { <add> ->on('Model.beforeFind', function (EventInterface $event, $query) { <ide> $query <ide> ->limit(5) <ide> ->order(['Articles.title' => 'DESC']); <ide><path>tests/TestCase/ORM/RulesCheckerIntegrationTest.php <ide> */ <ide> namespace Cake\Test\TestCase\ORM; <ide> <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\ORM\Entity; <ide> use Cake\ORM\RulesChecker; <ide> use Cake\TestSuite\TestCase; <ide> public function testUseBeforeRules() <ide> <ide> $table->getEventManager()->on( <ide> 'Model.beforeRules', <del> function (Event $event, Entity $entity, \ArrayObject $options, $operation) { <add> function (EventInterface $event, Entity $entity, \ArrayObject $options, $operation) { <ide> $this->assertEquals( <ide> [ <ide> 'atomic' => true, <ide> public function testUseAfterRules() <ide> <ide> $table->getEventManager()->on( <ide> 'Model.afterRules', <del> function (Event $event, Entity $entity, \ArrayObject $options, $result, $operation) { <add> function (EventInterface $event, Entity $entity, \ArrayObject $options, $result, $operation) { <ide> $this->assertEquals( <ide> [ <ide> 'atomic' => true, <ide> public function testUseBuildRulesEvent() <ide> ]); <ide> <ide> $table = $this->getTableLocator()->get('Articles'); <del> $table->getEventManager()->on('Model.buildRules', function (Event $event, RulesChecker $rules) { <add> $table->getEventManager()->on('Model.buildRules', function (EventInterface $event, RulesChecker $rules) { <ide> $rules->add($rules->existsIn('author_id', $this->getTableLocator()->get('Authors'), 'Nope')); <ide> }); <ide> <ide> public function testIsUniqueAliasPrefix() <ide> $rules = $table->rulesChecker(); <ide> $rules->add($rules->isUnique(['author_id'])); <ide> <del> $table->Authors->getEventManager()->on('Model.beforeFind', function (Event $event, $query) { <add> $table->Authors->getEventManager()->on('Model.beforeFind', function (EventInterface $event, $query) { <ide> $query->leftJoin(['a2' => 'authors']); <ide> }); <ide> <ide> public function testExistsInAliasPrefix() <ide> $rules = $table->rulesChecker(); <ide> $rules->add($rules->existsIn('author_id', 'Authors')); <ide> <del> $table->Authors->getEventManager()->on('Model.beforeFind', function (Event $event, $query) { <add> $table->Authors->getEventManager()->on('Model.beforeFind', function (EventInterface $event, $query) { <ide> $query->leftJoin(['a2' => 'authors']); <ide> }); <ide> <ide><path>tests/TestCase/ORM/TableTest.php <ide> use Cake\Database\TypeMap; <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\Datasource\EntityInterface; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Event\EventManager; <ide> use Cake\I18n\Time; <ide> use Cake\ORM\AssociationCollection; <ide> public function testFindBeforeFindEventMutateQuery() <ide> ]); <ide> $table->getEventManager()->on( <ide> 'Model.beforeFind', <del> function (Event $event, $query, $options) { <add> function (EventInterface $event, $query, $options) { <ide> $query->limit(1); <ide> } <ide> ); <ide> public function testFindBeforeFindEventOverrideReturn() <ide> $expected = ['One', 'Two', 'Three']; <ide> $table->getEventManager()->on( <ide> 'Model.beforeFind', <del> function (Event $event, $query, $options) use ($expected) { <add> function (EventInterface $event, $query, $options) use ($expected) { <ide> $query->setResult($expected); <ide> $event->stopPropagation(); <ide> } <ide> public function testBeforeSaveGetsCorrectPersistance() <ide> ]); <ide> $table = $this->getTableLocator()->get('users'); <ide> $called = false; <del> $listener = function (Event $event, $entity) use (&$called) { <add> $listener = function (EventInterface $event, $entity) use (&$called) { <ide> $this->assertFalse($entity->isNew()); <ide> $called = true; <ide> }; <ide> public function testDeleteBeforeDeleteAbort() <ide> $mock = $this->getMockBuilder('Cake\Event\EventManager')->getMock(); <ide> $mock->expects($this->at(2)) <ide> ->method('dispatch') <del> ->will($this->returnCallback(function (Event $event) { <add> ->will($this->returnCallback(function (EventInterface $event) { <ide> $event->stopPropagation(); <ide> })); <ide> <ide> public function testDeleteBeforeDeleteReturnResult() <ide> $mock = $this->getMockBuilder('Cake\Event\EventManager')->getMock(); <ide> $mock->expects($this->at(2)) <ide> ->method('dispatch') <del> ->will($this->returnCallback(function (Event $event) { <add> ->will($this->returnCallback(function (EventInterface $event) { <ide> $event->stopPropagation(); <ide> $event->setResult('got stopped'); <ide> })); <ide> public function testOptionsBeingPassedToImplicitBelongsToManyDeletesUsingSaveRep <ide> $actualOptions = null; <ide> $tags->junction()->getEventManager()->on( <ide> 'Model.beforeDelete', <del> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <ide> $actualOptions = $options->getArrayCopy(); <ide> } <ide> ); <ide> public function testOptionsBeingPassedToInternalSaveCallsUsingBelongsToManyLink( <ide> $actualOptions = null; <ide> $tags->junction()->getEventManager()->on( <ide> 'Model.beforeSave', <del> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <ide> $actualOptions = $options->getArrayCopy(); <ide> } <ide> ); <ide> public function testOptionsBeingPassedToInternalSaveCallsUsingBelongsToManyUnlin <ide> $actualOptions = null; <ide> $tags->junction()->getEventManager()->on( <ide> 'Model.beforeDelete', <del> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <ide> $actualOptions = $options->getArrayCopy(); <ide> } <ide> ); <ide> public function testOptionsBeingPassedToInternalSaveAndDeleteCallsUsingBelongsTo <ide> $actualDeleteOptions = null; <ide> $tags->junction()->getEventManager()->on( <ide> 'Model.beforeSave', <del> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualSaveOptions) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options) use (&$actualSaveOptions) { <ide> $actualSaveOptions = $options->getArrayCopy(); <ide> } <ide> ); <ide> $tags->junction()->getEventManager()->on( <ide> 'Model.beforeDelete', <del> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualDeleteOptions) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options) use (&$actualDeleteOptions) { <ide> $actualDeleteOptions = $options->getArrayCopy(); <ide> } <ide> ); <ide> public function testOptionsBeingPassedToImplicitHasManyDeletesUsingSaveReplace() <ide> $actualOptions = null; <ide> $articles->getTarget()->getEventManager()->on( <ide> 'Model.beforeDelete', <del> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <ide> $actualOptions = $options->getArrayCopy(); <ide> } <ide> ); <ide> public function testOptionsBeingPassedToInternalSaveCallsUsingHasManyLink() <ide> $actualOptions = null; <ide> $articles->getTarget()->getEventManager()->on( <ide> 'Model.beforeSave', <del> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <ide> $actualOptions = $options->getArrayCopy(); <ide> } <ide> ); <ide> public function testOptionsBeingPassedToInternalSaveCallsUsingHasManyUnlink() <ide> $actualOptions = null; <ide> $articles->getTarget()->getEventManager()->on( <ide> 'Model.beforeDelete', <del> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <ide> $actualOptions = $options->getArrayCopy(); <ide> } <ide> ); <ide> public function testOptionsBeingPassedToInternalSaveAndDeleteCallsUsingHasManyRe <ide> $actualDeleteOptions = null; <ide> $articles->getTarget()->getEventManager()->on( <ide> 'Model.beforeSave', <del> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualSaveOptions) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options) use (&$actualSaveOptions) { <ide> $actualSaveOptions = $options->getArrayCopy(); <ide> } <ide> ); <ide> $articles->getTarget()->getEventManager()->on( <ide> 'Model.beforeDelete', <del> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualDeleteOptions) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options) use (&$actualDeleteOptions) { <ide> $actualDeleteOptions = $options->getArrayCopy(); <ide> } <ide> ); <ide> public function testBackwardsCompatibilityForBelongsToManyUnlinkCleanPropertyOpt <ide> $actualOptions = null; <ide> $tags->junction()->getEventManager()->on( <ide> 'Model.beforeDelete', <del> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <ide> $actualOptions = $options->getArrayCopy(); <ide> } <ide> ); <ide> public function testBackwardsCompatibilityForHasManyUnlinkCleanPropertyOption() <ide> $actualOptions = null; <ide> $articles->getTarget()->getEventManager()->on( <ide> 'Model.beforeDelete', <del> function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options) use (&$actualOptions) { <ide> $actualOptions = $options->getArrayCopy(); <ide> } <ide> ); <ide> public function testFindOrCreateNoTransaction() <ide> public function testInitializeEvent() <ide> { <ide> $count = 0; <del> $cb = function (Event $event) use (&$count) { <add> $cb = function (EventInterface $event) use (&$count) { <ide> $count++; <ide> }; <ide> EventManager::instance()->on('Model.initialize', $cb); <ide> public function testHasFinder() <ide> public function testBuildValidatorEvent() <ide> { <ide> $count = 0; <del> $cb = function (Event $event) use (&$count) { <add> $cb = function (EventInterface $event) use (&$count) { <ide> $count++; <ide> }; <ide> EventManager::instance()->on('Model.buildValidator', $cb); <ide> public function testCallbackArgumentTypes() <ide> $associationBeforeFindCount = 0; <ide> $table->getAssociation('authors')->getTarget()->getEventManager()->on( <ide> 'Model.beforeFind', <del> function (Event $event, Query $query, ArrayObject $options, $primary) use (&$associationBeforeFindCount) { <add> function (EventInterface $event, Query $query, ArrayObject $options, $primary) use (&$associationBeforeFindCount) { <ide> $this->assertInternalType('bool', $primary); <ide> $associationBeforeFindCount ++; <ide> } <ide> function (Event $event, Query $query, ArrayObject $options, $primary) use (&$ass <ide> $beforeFindCount = 0; <ide> $eventManager->on( <ide> 'Model.beforeFind', <del> function (Event $event, Query $query, ArrayObject $options, $primary) use (&$beforeFindCount) { <add> function (EventInterface $event, Query $query, ArrayObject $options, $primary) use (&$beforeFindCount) { <ide> $this->assertInternalType('bool', $primary); <ide> $beforeFindCount ++; <ide> } <ide> function (Event $event, Query $query, ArrayObject $options, $primary) use (&$bef <ide> $buildValidatorCount = 0; <ide> $eventManager->on( <ide> 'Model.buildValidator', <del> $callback = function (Event $event, Validator $validator, $name) use (&$buildValidatorCount) { <add> $callback = function (EventInterface $event, Validator $validator, $name) use (&$buildValidatorCount) { <ide> $this->assertInternalType('string', $name); <ide> $buildValidatorCount ++; <ide> } <ide> function (Event $event, Query $query, ArrayObject $options, $primary) use (&$bef <ide> $afterSaveCount = 0; <ide> $eventManager->on( <ide> 'Model.buildRules', <del> function (Event $event, RulesChecker $rules) use (&$buildRulesCount) { <add> function (EventInterface $event, RulesChecker $rules) use (&$buildRulesCount) { <ide> $buildRulesCount ++; <ide> } <ide> ); <ide> $eventManager->on( <ide> 'Model.beforeRules', <del> function (Event $event, Entity $entity, ArrayObject $options, $operation) use (&$beforeRulesCount) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options, $operation) use (&$beforeRulesCount) { <ide> $this->assertInternalType('string', $operation); <ide> $beforeRulesCount ++; <ide> } <ide> ); <ide> $eventManager->on( <ide> 'Model.afterRules', <del> function (Event $event, Entity $entity, ArrayObject $options, $result, $operation) use (&$afterRulesCount) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options, $result, $operation) use (&$afterRulesCount) { <ide> $this->assertInternalType('bool', $result); <ide> $this->assertInternalType('string', $operation); <ide> $afterRulesCount ++; <ide> } <ide> ); <ide> $eventManager->on( <ide> 'Model.beforeSave', <del> function (Event $event, Entity $entity, ArrayObject $options) use (&$beforeSaveCount) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options) use (&$beforeSaveCount) { <ide> $beforeSaveCount ++; <ide> } <ide> ); <ide> $eventManager->on( <ide> 'Model.afterSave', <del> $afterSaveCallback = function (Event $event, Entity $entity, ArrayObject $options) use (&$afterSaveCount) { <add> $afterSaveCallback = function (EventInterface $event, Entity $entity, ArrayObject $options) use (&$afterSaveCount) { <ide> $afterSaveCount ++; <ide> } <ide> ); <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$beforeSaveC <ide> $afterDeleteCount = 0; <ide> $eventManager->on( <ide> 'Model.beforeDelete', <del> function (Event $event, Entity $entity, ArrayObject $options) use (&$beforeDeleteCount) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options) use (&$beforeDeleteCount) { <ide> $beforeDeleteCount ++; <ide> } <ide> ); <ide> $eventManager->on( <ide> 'Model.afterDelete', <del> function (Event $event, Entity $entity, ArrayObject $options) use (&$afterDeleteCount) { <add> function (EventInterface $event, Entity $entity, ArrayObject $options) use (&$afterDeleteCount) { <ide> $afterDeleteCount ++; <ide> } <ide> ); <ide> public function testSaveHasManyNoWasteSave() <ide> $counter = 0; <ide> $userTable->Comments <ide> ->getEventManager() <del> ->on('Model.afterSave', function (Event $event, $entity) use (&$counter) { <add> ->on('Model.afterSave', function (EventInterface $event, $entity) use (&$counter) { <ide> if ($entity->isDirty()) { <ide> $counter++; <ide> } <ide> public function testSaveBelongsToManyNoWasteSave() <ide> $counter = 0; <ide> $table->Tags->junction() <ide> ->getEventManager() <del> ->on('Model.afterSave', function (Event $event, $entity) use (&$counter) { <add> ->on('Model.afterSave', function (EventInterface $event, $entity) use (&$counter) { <ide> if ($entity->isDirty()) { <ide> $counter++; <ide> } <ide><path>tests/TestCase/View/ViewTest.php <ide> use Cake\Core\App; <ide> use Cake\Core\Configure; <ide> use Cake\Core\Plugin; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Event\EventListenerInterface; <ide> use Cake\Http\ServerRequest; <ide> use Cake\Routing\Router; <ide> public function implementedEvents() <ide> /** <ide> * beforeRender method <ide> * <del> * @param \Cake\Event\Event $event the event being sent <add> * @param \Cake\Event\EventInterface $event the event being sent <ide> * @return void <ide> */ <del> public function beforeRender(Event $event) <add> public function beforeRender(EventInterface $event) <ide> { <ide> $this->beforeRenderViewType = $event->getSubject()->getCurrentType(); <ide> } <ide> <ide> /** <ide> * afterRender method <ide> * <del> * @param \Cake\Event\Event $event the event being sent <add> * @param \Cake\Event\EventInterface $event the event being sent <ide> * @return void <ide> */ <del> public function afterRender(Event $event) <add> public function afterRender(EventInterface $event) <ide> { <ide> $this->afterRenderViewType = $event->getSubject()->getCurrentType(); <ide> } <ide> public function testElementInexistentPluginElement() <ide> public function testElementCallbacks() <ide> { <ide> $count = 0; <del> $callback = function (Event $event, $file) use (&$count) { <add> $callback = function (EventInterface $event, $file) use (&$count) { <ide> $count++; <ide> }; <ide> $events = $this->View->getEventManager(); <ide><path>tests/test_app/Plugin/TestPlugin/src/Routing/Filter/Test2DispatcherFilter.php <ide> */ <ide> namespace TestPlugin\Routing\Filter; <ide> <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Routing\DispatcherFilter; <ide> <ide> /** <ide> class Test2DispatcherFilter extends DispatcherFilter <ide> { <ide> <del> public function beforeDispatch(Event $event) <add> public function beforeDispatch(EventInterface $event) <ide> { <ide> $event->data('response')->statusCode(500); <ide> $event->stopPropagation(); <ide> <ide> return $event->data('response'); <ide> } <ide> <del> public function afterDispatch(Event $event) <add> public function afterDispatch(EventInterface $event) <ide> { <ide> $event->data('response')->statusCode(200); <ide> } <ide><path>tests/test_app/Plugin/TestPlugin/src/Routing/Filter/TestDispatcherFilter.php <ide> */ <ide> namespace TestPlugin\Routing\Filter; <ide> <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Routing\DispatcherFilter; <ide> <ide> /** <ide> class TestDispatcherFilter extends DispatcherFilter <ide> { <ide> <del> public function beforeDispatch(Event $event) <add> public function beforeDispatch(EventInterface $event) <ide> { <ide> $event->data('request')->params['altered'] = true; <ide> } <ide> <del> public function afterDispatch(Event $event) <add> public function afterDispatch(EventInterface $event) <ide> { <ide> $event->data('response')->statusCode(304); <ide> } <ide><path>tests/test_app/TestApp/Auth/TestAuthenticate.php <ide> namespace TestApp\Auth; <ide> <ide> use Cake\Auth\BaseAuthenticate; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> <ide> public function authenticate(ServerRequest $request, Response $response) <ide> } <ide> <ide> /** <del> * @param \Cake\Event\Event $event <add> * @param \Cake\Event\EventInterface $event <ide> * @param array $user <ide> * @return array <ide> */ <del> public function afterIdentify(Event $event, array $user) <add> public function afterIdentify(EventInterface $event, array $user) <ide> { <ide> $this->callStack[] = __FUNCTION__; <ide> $this->authenticationProvider = $event->getData(1); <ide> public function afterIdentify(Event $event, array $user) <ide> } <ide> <ide> /** <del> * @param \Cake\Event\Event $event <add> * @param \Cake\Event\EventInterface $event <ide> * @param array $user <ide> */ <del> public function logout(Event $event, array $user) <add> public function logout(EventInterface $event, array $user) <ide> { <ide> $this->callStack[] = __FUNCTION__; <ide> } <ide><path>tests/test_app/TestApp/Controller/Component/AppleComponent.php <ide> namespace TestApp\Controller\Component; <ide> <ide> use Cake\Controller\Component; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> <ide> /** <ide> * AppleComponent class <ide> class AppleComponent extends Component <ide> /** <ide> * startup method <ide> * <del> * @param Event $event <add> * @param \Cake\Event\EventInterface $event <ide> * @return void <ide> */ <del> public function startup(Event $event) <add> public function startup(EventInterface $event) <ide> { <ide> } <ide> } <ide><path>tests/test_app/TestApp/Controller/Component/OrangeComponent.php <ide> <ide> use Cake\Controller\Component; <ide> use Cake\Controller\Controller; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> <ide> /** <ide> * OrangeComponent class <ide> public function initialize(array $config) <ide> /** <ide> * startup method <ide> * <del> * @param Event $event <add> * @param \Cake\Event\EventInterface $event <ide> * @return void <ide> */ <del> public function startup(Event $event) <add> public function startup(EventInterface $event) <ide> { <ide> $this->Controller->foo = 'pass'; <ide> } <ide><path>tests/test_app/TestApp/Controller/Component/TestAuthComponent.php <ide> namespace TestApp\Controller\Component; <ide> <ide> use Cake\Controller\Component\AuthComponent; <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> <ide> /** <ide> * TestAuthComponent class <ide> class TestAuthComponent extends AuthComponent <ide> public $authCheckCalledFrom = null; <ide> <ide> /** <del> * @param Event $event <add> * @param \Cake\Event\EventInterface $event <ide> * @return \Cake\Http\Response|null <ide> */ <del> public function authCheck(Event $event) <add> public function authCheck(EventInterface $event) <ide> { <ide> if (isset($this->earlyAuthTest)) { <ide> if ($this->_config['checkAuthIn'] !== $event->getName()) { <ide><path>tests/test_app/TestApp/Controller/PostsController.php <ide> */ <ide> namespace TestApp\Controller; <ide> <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Utility\Security; <ide> <ide> /** <ide> public function initialize() <ide> * <ide> * @return void <ide> */ <del> public function beforeFilter(Event $event) <add> public function beforeFilter(EventInterface $event) <ide> { <ide> if ($this->request->getParam('action') !== 'securePost') { <ide> $this->getEventManager()->off($this->Security); <ide><path>tests/test_app/TestApp/Model/Behavior/SluggableBehavior.php <ide> */ <ide> namespace TestApp\Model\Behavior; <ide> <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\ORM\Behavior; <ide> use Cake\ORM\Query; <ide> use Cake\Utility\Text; <ide> <ide> class SluggableBehavior extends Behavior <ide> { <ide> <del> public function beforeFind(Event $event, Query $query, $options = []) <add> public function beforeFind(EventInterface $event, Query $query, $options = []) <ide> { <ide> $query->where(['slug' => 'test']); <ide> <ide><path>tests/test_app/TestApp/Routing/Filter/AppendFilter.php <ide> <?php <ide> namespace TestApp\Routing\Filter; <ide> <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Routing\DispatcherFilter; <ide> <ide> class AppendFilter extends DispatcherFilter <ide> { <del> public function afterDispatch(Event $event) <add> public function afterDispatch(EventInterface $event) <ide> { <ide> $response = $event->getData('response'); <ide> $response->body($response->body() . ' appended content'); <ide><path>tests/test_app/TestApp/View/Helper/EventListenerTestHelper.php <ide> */ <ide> namespace TestApp\View\Helper; <ide> <del>use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\View\Helper; <ide> <ide> class EventListenerTestHelper extends Helper <ide> class EventListenerTestHelper extends Helper <ide> /** <ide> * Before render callback. Stub. <ide> * <del> * @param \Cake\Event\Event $event The event instance. <add> * @param \Cake\Event\EventInterface $event The event instance. <ide> * @param string $viewFile The view file being rendered. <ide> * @return void <ide> */ <del> public function beforeRender(Event $event, $viewFile) <add> public function beforeRender(EventInterface $event, $viewFile) <ide> { <ide> $this->config('options.foo', 'bar'); <ide> }
51
Text
Text
replace es6 by webpack in the integration docs
9a295816b3ed406ff34d078746d8afd94d0b13a2
<ide><path>docs/getting-started/integration.md <ide> <ide> Chart.js can be integrated with plain JavaScript or with different module loaders. The examples below show how to load Chart.js in different systems. <ide> <del>## ES6 Modules <del> <del>```javascript <del>import Chart from 'chart.js'; <del>var myChart = new Chart(ctx, {...}); <del>``` <del> <ide> ## Script Tag <ide> <ide> ```html <ide> var myChart = new Chart(ctx, {...}); <ide> </script> <ide> ``` <ide> <add>## Webpack <add> <add>```javascript <add>import Chart from 'chart.js'; <add>var myChart = new Chart(ctx, {...}); <add>``` <add> <ide> ## Common JS <ide> <ide> ```javascript
1
Mixed
Python
remove useless code in doctests
61eedc16c392823e46ef37cc2a86864fa15e89fe
<ide><path>backtracking/hamiltonian_cycle.py <ide> def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int) <ide> >>> curr_ind = 1 <ide> >>> util_hamilton_cycle(graph, path, curr_ind) <ide> True <del> >>> print(path) <add> >>> path <ide> [0, 1, 2, 4, 3, 0] <ide> <ide> Case 2: Use exact graph as in previous case, but in the properties taken from <ide> def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int) <ide> >>> curr_ind = 3 <ide> >>> util_hamilton_cycle(graph, path, curr_ind) <ide> True <del> >>> print(path) <add> >>> path <ide> [0, 1, 2, 4, 3, 0] <ide> """ <ide> <ide><path>computer_vision/flip_augmentation.py <ide> def main() -> None: <ide> Get images list and annotations list from input dir. <ide> Update new images and annotations. <ide> Save images and annotations in output dir. <del> >>> pass # A doctest is not possible for this function. <ide> """ <ide> img_paths, annos = get_dataset(LABEL_DIR, IMAGE_DIR) <ide> print("Processing...") <ide> def get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]: <ide> - label_dir <type: str>: Path to label include annotation of images <ide> - img_dir <type: str>: Path to folder contain images <ide> Return <type: list>: List of images path and labels <del> >>> pass # A doctest is not possible for this function. <ide> """ <ide> img_paths = [] <ide> labels = [] <ide> def update_image_and_anno( <ide> - new_imgs_list <type: narray>: image after resize <ide> - new_annos_lists <type: list>: list of new annotation after scale <ide> - path_list <type: list>: list the name of image file <del> >>> pass # A doctest is not possible for this function. <ide> """ <ide> new_annos_lists = [] <ide> path_list = [] <ide><path>computer_vision/mosaic_augmentation.py <ide> def main() -> None: <ide> Get images list and annotations list from input dir. <ide> Update new images and annotations. <ide> Save images and annotations in output dir. <del> >>> pass # A doctest is not possible for this function. <ide> """ <ide> img_paths, annos = get_dataset(LABEL_DIR, IMG_DIR) <ide> for index in range(NUMBER_IMAGES): <ide> def get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]: <ide> - label_dir <type: str>: Path to label include annotation of images <ide> - img_dir <type: str>: Path to folder contain images <ide> Return <type: list>: List of images path and labels <del> >>> pass # A doctest is not possible for this function. <ide> """ <ide> img_paths = [] <ide> labels = [] <ide> def update_image_and_anno( <ide> - output_img <type: narray>: image after resize <ide> - new_anno <type: list>: list of new annotation after scale <ide> - path[0] <type: string>: get the name of image file <del> >>> pass # A doctest is not possible for this function. <ide> """ <ide> output_img = np.zeros([output_size[0], output_size[1], 3], dtype=np.uint8) <ide> scale_x = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) <ide><path>data_structures/heap/binomial_heap.py <ide> class BinomialHeap: <ide> ... first_heap.insert(number) <ide> <ide> Size test <del> >>> print(first_heap.size) <add> >>> first_heap.size <ide> 30 <ide> <ide> Deleting - delete() test <ide> class BinomialHeap: <ide> # # # # <ide> <ide> preOrder() test <del> >>> print(second_heap.preOrder()) <add> >>> second_heap.preOrder() <ide> [(17, 0), ('#', 1), (31, 1), (20, 2), ('#', 3), ('#', 3), (34, 2), ('#', 3), ('#', 3)] <ide> <ide> printing Heap - __str__() test <ide><path>data_structures/heap/heap.py <ide> class Heap: <ide> >>> unsorted = [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5] <ide> >>> h = Heap() <ide> >>> h.build_max_heap(unsorted) <del> >>> print(h) <add> >>> h <ide> [209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5] <ide> >>> <ide> >>> h.extract_max() <ide> 209 <del> >>> print(h) <add> >>> h <ide> [201, 107, 25, 103, 11, 15, 1, 9, 7, 5] <ide> >>> <ide> >>> h.insert(100) <del> >>> print(h) <add> >>> h <ide> [201, 107, 25, 103, 100, 15, 1, 9, 7, 5, 11] <ide> >>> <ide> >>> h.heap_sort() <del> >>> print(h) <add> >>> h <ide> [1, 5, 7, 9, 11, 15, 25, 100, 103, 107, 201] <ide> """ <ide> <ide><path>data_structures/heap/min_heap.py <ide> class MinHeap: <ide> >>> myMinHeap.decrease_key(b, -17) <ide> >>> print(b) <ide> Node(B, -17) <del> >>> print(myMinHeap["B"]) <add> >>> myMinHeap["B"] <ide> -17 <ide> """ <ide> <ide><path>data_structures/linked_list/skip_list.py <ide> def main(): <ide> <ide> <ide> if __name__ == "__main__": <add> import doctest <add> <add> doctest.testmod() <ide> main() <ide><path>graphs/gale_shapley_bigraph.py <ide> def stable_matching( <ide> <ide> >>> donor_pref = [[0, 1, 3, 2], [0, 2, 3, 1], [1, 0, 2, 3], [0, 3, 1, 2]] <ide> >>> recipient_pref = [[3, 1, 2, 0], [3, 1, 0, 2], [0, 3, 1, 2], [1, 0, 3, 2]] <del> >>> print(stable_matching(donor_pref, recipient_pref)) <add> >>> stable_matching(donor_pref, recipient_pref) <ide> [1, 2, 3, 0] <ide> """ <ide> assert len(donor_pref) == len(recipient_pref) <ide><path>graphs/graph_list.py <ide> class GraphAdjacencyList(Generic[T]): <ide> <ide> Directed graph example: <ide> >>> d_graph = GraphAdjacencyList() <del> >>> d_graph <add> >>> print(d_graph) <ide> {} <ide> >>> d_graph.add_edge(0, 1) <ide> {0: [1], 1: []} <ide> >>> d_graph.add_edge(1, 2).add_edge(1, 4).add_edge(1, 5) <ide> {0: [1], 1: [2, 4, 5], 2: [], 4: [], 5: []} <ide> >>> d_graph.add_edge(2, 0).add_edge(2, 6).add_edge(2, 7) <ide> {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []} <del> >>> print(d_graph) <add> >>> d_graph <ide> {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []} <ide> >>> print(repr(d_graph)) <ide> {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []} <ide> class GraphAdjacencyList(Generic[T]): <ide> {'a': ['b'], 'b': ['a']} <ide> >>> char_graph.add_edge('b', 'c').add_edge('b', 'e').add_edge('b', 'f') <ide> {'a': ['b'], 'b': ['a', 'c', 'e', 'f'], 'c': ['b'], 'e': ['b'], 'f': ['b']} <del> >>> print(char_graph) <add> >>> char_graph <ide> {'a': ['b'], 'b': ['a', 'c', 'e', 'f'], 'c': ['b'], 'e': ['b'], 'f': ['b']} <ide> """ <ide> <ide><path>graphs/minimum_spanning_tree_prims2.py <ide> class MinPriorityQueue(Generic[T]): <ide> >>> queue.push(3, 4000) <ide> >>> queue.push(4, 3000) <ide> <del> >>> print(queue.extract_min()) <add> >>> queue.extract_min() <ide> 2 <ide> <ide> >>> queue.update_key(4, 50) <ide> <del> >>> print(queue.extract_min()) <add> >>> queue.extract_min() <ide> 4 <del> >>> print(queue.extract_min()) <add> >>> queue.extract_min() <ide> 1 <del> >>> print(queue.extract_min()) <add> >>> queue.extract_min() <ide> 3 <ide> """ <ide> <ide><path>graphs/random_graph_generator.py <ide> def complete_graph(vertices_number: int) -> dict: <ide> @input: vertices_number (number of vertices), <ide> directed (False if the graph is undirected, True otherwise) <ide> @example: <del> >>> print(complete_graph(3)) <add> >>> complete_graph(3) <ide> {0: [1, 2], 1: [0, 2], 2: [0, 1]} <ide> """ <ide> return { <ide><path>machine_learning/local_weighted_learning/local_weighted_learning.py <ide> def local_weight_regression( <ide> def load_data(dataset_name: str, cola_name: str, colb_name: str) -> np.mat: <ide> """ <ide> Function used for loading data from the seaborn splitting into x and y points <del> >>> pass # this function has no doctest <ide> """ <ide> import seaborn as sns <ide> <ide> def plot_preds( <ide> ) -> plt.plot: <ide> """ <ide> This function used to plot predictions and display the graph <del> >>> pass #this function has no doctest <ide> """ <ide> xsort = training_data_x.copy() <ide> xsort.sort(axis=0) <ide><path>maths/polynomial_evaluation.py <ide> def horner(poly: Sequence[float], x: float) -> float: <ide> >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7.0x^4 + 9.3x^3 + 5.0x^2 <ide> >>> x = -13.0 <ide> >>> # f(-13) = 7.0(-13)^4 + 9.3(-13)^3 + 5.0(-13)^2 = 180339.9 <del> >>> print(evaluate_poly(poly, x)) <add> >>> evaluate_poly(poly, x) <ide> 180339.9 <ide> """ <ide> poly = (0.0, 0.0, 5.0, 9.3, 7.0) <ide><path>maths/radix2_fft.py <ide> class FFT: <ide> >>> x = FFT(A, B) <ide> <ide> Print product <del> >>> print(x.product) # 2x + 3x^2 + 8x^3 + 4x^4 + 6x^5 <add> >>> x.product # 2x + 3x^2 + 8x^3 + 4x^4 + 6x^5 <ide> [(-0+0j), (2+0j), (3+0j), (8+0j), (6+0j), (8+0j)] <ide> <ide> __str__ test <ide><path>matrix/matrix_class.py <ide> class Matrix: <ide> [7. 8. 9.]] <ide> <ide> Matrix rows and columns are available as 2D arrays <del> >>> print(matrix.rows) <add> >>> matrix.rows <ide> [[1, 2, 3], [4, 5, 6], [7, 8, 9]] <del> >>> print(matrix.columns()) <add> >>> matrix.columns() <ide> [[1, 4, 7], [2, 5, 8], [3, 6, 9]] <ide> <ide> Order is returned as a tuple <ide> class Matrix: <ide> [[-3. 6. -3.] <ide> [6. -12. 6.] <ide> [-3. 6. -3.]] <del> >>> print(matrix.inverse()) <add> >>> matrix.inverse() <ide> Traceback (most recent call last): <ide> ... <ide> TypeError: Only matrices with a non-zero determinant have an inverse <ide><path>searches/simple_binary_search.py <ide> def binary_search(a_list: list[int], item: int) -> bool: <ide> """ <ide> >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] <del> >>> print(binary_search(test_list, 3)) <add> >>> binary_search(test_list, 3) <ide> False <del> >>> print(binary_search(test_list, 13)) <add> >>> binary_search(test_list, 13) <ide> True <del> >>> print(binary_search([4, 4, 5, 6, 7], 4)) <add> >>> binary_search([4, 4, 5, 6, 7], 4) <ide> True <del> >>> print(binary_search([4, 4, 5, 6, 7], -10)) <add> >>> binary_search([4, 4, 5, 6, 7], -10) <ide> False <del> >>> print(binary_search([-18, 2], -18)) <add> >>> binary_search([-18, 2], -18) <ide> True <del> >>> print(binary_search([5], 5)) <add> >>> binary_search([5], 5) <ide> True <del> >>> print(binary_search(['a', 'c', 'd'], 'c')) <add> >>> binary_search(['a', 'c', 'd'], 'c') <ide> True <del> >>> print(binary_search(['a', 'c', 'd'], 'f')) <add> >>> binary_search(['a', 'c', 'd'], 'f') <ide> False <del> >>> print(binary_search([], 1)) <add> >>> binary_search([], 1) <ide> False <del> >>> print(binary_search([-.1, .1 , .8], .1)) <add> >>> binary_search([-.1, .1 , .8], .1) <ide> True <ide> >>> binary_search(range(-5000, 5000, 10), 80) <ide> True <ide><path>sorts/bitonic_sort.py <ide> def comp_and_swap(array: list[int], index1: int, index2: int, direction: int) -> <ide> <ide> >>> arr = [12, 42, -21, 1] <ide> >>> comp_and_swap(arr, 1, 2, 1) <del> >>> print(arr) <add> >>> arr <ide> [12, -21, 42, 1] <ide> <ide> >>> comp_and_swap(arr, 1, 2, 0) <del> >>> print(arr) <add> >>> arr <ide> [12, 42, -21, 1] <ide> <ide> >>> comp_and_swap(arr, 0, 3, 1) <del> >>> print(arr) <add> >>> arr <ide> [1, 42, -21, 12] <ide> <ide> >>> comp_and_swap(arr, 0, 3, 0) <del> >>> print(arr) <add> >>> arr <ide> [12, 42, -21, 1] <ide> """ <ide> if (direction == 1 and array[index1] > array[index2]) or ( <ide> def bitonic_merge(array: list[int], low: int, length: int, direction: int) -> No <ide> <ide> >>> arr = [12, 42, -21, 1] <ide> >>> bitonic_merge(arr, 0, 4, 1) <del> >>> print(arr) <add> >>> arr <ide> [-21, 1, 12, 42] <ide> <ide> >>> bitonic_merge(arr, 0, 4, 0) <del> >>> print(arr) <add> >>> arr <ide> [42, 12, 1, -21] <ide> """ <ide> if length > 1: <ide><path>sorts/normal_distribution_quick_sort.md <ide> The array elements are taken from a Standard Normal Distribution, having mean = <ide> >>> mu, sigma = 0, 1 # mean and standard deviation <ide> >>> X = np.random.normal(mu, sigma, p) <ide> >>> np.save(outfile, X) <del>>>> print('The array is') <del>>>> print(X) <add>>>> 'The array is' <add>>>> X <ide> <ide> ``` <ide> <ide><path>sorts/recursive_insertion_sort.py <ide> def rec_insertion_sort(collection: list, n: int): <ide> <ide> >>> col = [1, 2, 1] <ide> >>> rec_insertion_sort(col, len(col)) <del> >>> print(col) <add> >>> col <ide> [1, 1, 2] <ide> <ide> >>> col = [2, 1, 0, -1, -2] <ide> >>> rec_insertion_sort(col, len(col)) <del> >>> print(col) <add> >>> col <ide> [-2, -1, 0, 1, 2] <ide> <ide> >>> col = [1] <ide> >>> rec_insertion_sort(col, len(col)) <del> >>> print(col) <add> >>> col <ide> [1] <ide> """ <ide> # Checks if the entire collection has been sorted <ide> def insert_next(collection: list, index: int): <ide> <ide> >>> col = [3, 2, 4, 2] <ide> >>> insert_next(col, 1) <del> >>> print(col) <add> >>> col <ide> [2, 3, 4, 2] <ide> <ide> >>> col = [3, 2, 3] <ide> >>> insert_next(col, 2) <del> >>> print(col) <add> >>> col <ide> [3, 2, 3] <ide> <ide> >>> col = [] <ide> >>> insert_next(col, 1) <del> >>> print(col) <add> >>> col <ide> [] <ide> """ <ide> # Checks order between adjacent elements <ide><path>web_programming/reddit.py <ide> def get_subreddit_data( <ide> limit : Number of posts to fetch <ide> age : ["new", "top", "hot"] <ide> wanted_data : Get only the required data in the list <del> <del> >>> pass <ide> """ <ide> wanted_data = wanted_data or [] <ide> if invalid_search_terms := ", ".join(sorted(set(wanted_data) - valid_terms)): <ide><path>web_programming/search_books_by_isbn.py <ide> def get_openlibrary_data(olid: str = "isbn/0140328726") -> dict: <ide> {'publishers': ['Puffin'], 'number_of_pages': 96, 'isbn_10': ['0140328726'], ... <ide> # >>> get_openlibrary_data(olid='/authors/OL7353617A') # doctest: +ELLIPSIS <ide> {'name': 'Adrian Brisku', 'created': {'type': '/type/datetime', ... <del> >>> pass # Placate https://github.com/apps/algorithms-keeper <ide> """ <ide> new_olid = olid.strip().strip("/") # Remove leading/trailing whitespace & slashes <ide> if new_olid.count("/") != 1: <ide> def get_openlibrary_data(olid: str = "isbn/0140328726") -> dict: <ide> <ide> def summarize_book(ol_book_data: dict) -> dict: <ide> """ <del> Given Open Library book data, return a summary as a Python dict. <del> <del> >>> pass # Placate https://github.com/apps/algorithms-keeper <add> Given Open Library book data, return a summary as a Python dict. <ide> """ <ide> desired_keys = { <ide> "title": "Title",
21
Text
Text
specify woker node for docker swarm leave command
fd660e21bf6568c3f98424bdff3b9672cd2a3ef8
<ide><path>docs/reference/commandline/swarm_leave.md <ide> dkp8vy1dq1kxleu9g4u78tlag worker1 Ready Active Reachable <ide> dvfxp4zseq4s0rih1selh0d20 * manager1 Ready Active Leader <ide> ``` <ide> <del>On a worker node: <add>On a worker node, worker2 in the following example: <ide> ```bash <ide> $ docker swarm leave <ide> Node left the default swarm.
1
Python
Python
remove extra letter from docs
41e14f938587f95c2c0091c05b850bbd5b86354b
<ide><path>numpy/doc/basics.py <ide> >>> np.iinfo(np.int32) # Bounds of a 32-bit integer <ide> iinfo(min=-2147483648, max=2147483647, dtype=int32) <ide> >>> np.iinfo(np.int64) # Bounds of a 64-bit integer <del> iinfo(min=-9223372036854775808, max=9223372036854775807, dtype=int64)s <add> iinfo(min=-9223372036854775808, max=9223372036854775807, dtype=int64) <ide> <ide> If 64-bit integers are still too small the result may be cast to a <ide> floating point number. Floating point numbers offer a larger, but inexact,
1
PHP
PHP
fix import order
061f54e319c72e320e9759860ef5a44fc37bda2b
<ide><path>src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php <ide> use Illuminate\Contracts\View\View; <ide> use PHPUnit_Framework_Assert as PHPUnit; <ide> use PHPUnit_Framework_ExpectationFailedException; <del>use Symfony\Component\HttpFoundation\File\UploadedFile as SymfonyUploadedFile; <ide> use Symfony\Component\HttpFoundation\Request as SymfonyRequest; <add>use Symfony\Component\HttpFoundation\File\UploadedFile as SymfonyUploadedFile; <ide> <ide> trait MakesHttpRequests <ide> {
1
Python
Python
fix broken master - dlp
1b533f617e2e0200597d114d7570f6c0d69da1a0
<ide><path>airflow/providers/google/cloud/example_dags/example_dlp.py <ide> "example_gcp_dlp_job", schedule_interval=None, start_date=days_ago(1), tags=["example", "dlp_job"] <ide> ) as dag3: # [START howto_operator_dlp_create_job_trigger] <ide> create_trigger = CloudDLPCreateJobTriggerOperator( <del> project_id=GCP_PROJECT, <del> job_trigger=JOB_TRIGGER, <del> trigger_id=TRIGGER_ID, <del> task_id="create_trigger", <add> project_id=GCP_PROJECT, job_trigger=JOB_TRIGGER, trigger_id=TRIGGER_ID, task_id="create_trigger", <ide> ) <ide> # [END howto_operator_dlp_create_job_trigger] <ide> <ide> ) <ide> # [END howto_operator_dlp_delete_job_trigger] <ide> create_trigger >> update_trigger >> delete_trigger <del> <ide><path>airflow/providers/google/cloud/operators/dlp.py <ide> """ <ide> from typing import Dict, Optional, Sequence, Tuple, Union <ide> <del>from google.api_core.exceptions import AlreadyExists, NotFound <add>from google.api_core.exceptions import AlreadyExists, NotFound, InvalidArgument <ide> from google.api_core.retry import Retry <ide> from google.cloud.dlp_v2.types import ( <ide> ByteContentItem,
2
PHP
PHP
add abstract methods for required driver features
be8b9669665246ca4186178d1c3b32f4cc93b467
<ide><path>src/Database/Driver.php <ide> public abstract function commitTransaction(); <ide> */ <ide> public abstract function rollbackTransaction(); <ide> <add>/** <add> * Get the SQL for releasing a save point. <add> * <add> * @param string $name The table name <add> * @return string <add> */ <add> public abstract function releaseSavePointSQL($name); <add> <add>/** <add> * Get the SQL for creating a save point. <add> * <add> * @param string $name The table name <add> * @return string <add> */ <add> public abstract function savePointSQL($name); <add> <add>/** <add> * Get the SQL for rollingback a save point. <add> * <add> * @param string $name The table name <add> * @return string <add> */ <add> public abstract function rollbackSavePointSQL($name); <add> <ide> /** <ide> * Returns whether this driver supports save points for nested transactions <ide> * <ide> public function supportsSavePoints() { <ide> return true; <ide> } <ide> <add> <ide> /** <ide> * Returns a value in a safe representation to be used in a query string <ide> *
1
Python
Python
make test_histogramdd_too_many_bins a bit clearer
5b466f329c536c2535ba867ff536062fcbaa5b60
<ide><path>numpy/lib/tests/test_regression.py <ide> def test_polydiv_type(self) : <ide> <ide> def test_histogramdd_too_many_bins(self) : <ide> """Ticket 928.""" <del> assert_raises(ValueError, np.histogramdd, [np.ones(10)]*32) <add> assert_raises(ValueError, np.histogramdd, np.ones((1,10)), bins=2**10) <ide> <ide> <ide> if __name__ == "__main__":
1
Ruby
Ruby
add test for multiple suggested generator names
b3a16b61fa0b734523e5d225c88d50632b22e9f7
<ide><path>railties/test/generators_test.rb <ide> def test_generator_suggestions <ide> assert_match "Maybe you meant 'migration'", output <ide> end <ide> <add> def test_generator_multiple_suggestions <add> name = :tas <add> output = capture(:stdout){ Rails::Generators.invoke name } <add> assert_match "Maybe you meant 'task', 'job' or 'assets'", output <add> end <add> <ide> def test_help_when_a_generator_with_required_arguments_is_invoked_without_arguments <ide> output = capture(:stdout){ Rails::Generators.invoke :model, [] } <ide> assert_match(/Description:/, output)
1
Javascript
Javascript
add showcase for xiaoxian
2bb4e69382c91f97e838f51b3adeb8fa0d11ed62
<ide><path>website/src/react-native/showcase.js <ide> var apps = [ <ide> icon: 'https://lh3.googleusercontent.com/H0SILVHcDUxSMoSQwMb2QYtLjTBCqvK5ZEjOEwKQQ-2qnRV6Hd9Hn-gtSGPaoIOPwA=w300-rw', <ide> link: 'https://play.google.com/store/apps/details?id=com.biideal.biichat', <ide> author: 'biideal Inc.' <del> } <add> }, <add> { <add> name: '饿小闲', <add> icon: 'https://xiaoxian.ele.me/download/images/share_page/ic_launcher.png', <add> linkAppStore: 'https://itunes.apple.com/cn/app/e-xiao-xian/id1092025196', <add> author: 'Eleme', <add> }, <ide> ]; <ide> <ide> var AppList = React.createClass({
1
Javascript
Javascript
remove unused import from scrollviewviewconfig
719d52fb6bd40892aca582eca5173346ee28f21b
<ide><path>Libraries/Components/ScrollView/ScrollViewViewConfig.js <ide> <ide> 'use strict'; <ide> <del>import {} from '../../Utilities/differ/pointsDiffer'; <del> <ide> import type {GeneratedViewConfig} from '../../Utilities/registerGeneratedViewConfig'; <ide> <ide> const ScrollViewViewConfig = {
1
Python
Python
raise diff tolerance value for tfvitmaemodeltest
2b483230a1f79e2127b62032ef42d388ba1f991f
<ide><path>tests/vit_mae/test_modeling_tf_vit_mae.py <ide> def check_outputs(tf_outputs, pt_outputs, model_class, names): <ide> tf_outputs[pt_nans] = 0 <ide> <ide> max_diff = np.amax(np.abs(tf_outputs - pt_outputs)) <del> self.assertLessEqual(max_diff, 1e-5) <add> # Set a higher tolerance (2e-5) here than the one in the common test (1e-5). <add> # TODO: A deeper look to decide the best (common) tolerance for the test to be strict but not too flaky. <add> self.assertLessEqual(max_diff, 2e-5) <ide> else: <ide> raise ValueError( <ide> f"`tf_outputs` should be a `tuple` or an instance of `tf.Tensor`. Got {type(tf_outputs)} instead."
1
Text
Text
clarify file naming in release verification doc
efdfd15477f92da059fa86b4fa18b6f29cb97feb
<ide><path>dev/README_RELEASE_AIRFLOW.md <ide> The files should be present in the sub-folder of <ide> <ide> The following files should be present (9 files): <ide> <del>* -bin-tar.gz + .asc + .sha512 <ide> * -source.tar.gz + .asc + .sha512 <del>* -.whl + .asc + .sha512 <add>* .tar.gz + .asc + .sha512 <add>* -py3-none-any.whl + .asc + .sha512 <ide> <ide> As a PMC you should be able to clone the SVN repository: <ide> <ide> warning. By importing the server in the previous step and importing it via ID fr <ide> this is a valid Key already. <ide> <ide> ``` <del>Checking apache-airflow-2.0.2rc4-bin.tar.gz.asc <del>gpg: assuming signed data in 'apache-airflow-2.0.2rc4-bin.tar.gz' <add>Checking apache-airflow-2.0.2rc4.tar.gz.asc <add>gpg: assuming signed data in 'apache-airflow-2.0.2rc4.tar.gz' <ide> gpg: Signature made sob, 22 sie 2020, 20:28:28 CEST <ide> gpg: using RSA key 12717556040EEF2EEAF1B9C275FCCD0A25FA0E4B <ide> gpg: Good signature from "Kaxil Naik <kaxilnaik@gmail.com>" [unknown] <ide> done <ide> You should get output similar to: <ide> <ide> ``` <del>Checking apache-airflow-2.0.2rc4-bin.tar.gz.sha512 <add>Checking apache-airflow-2.0.2rc4.tar.gz.sha512 <ide> Checking apache_airflow-2.0.2rc4-py2.py3-none-any.whl.sha512 <ide> Checking apache-airflow-2.0.2rc4-source.tar.gz.sha512 <ide> ``` <ide><path>dev/README_RELEASE_AIRFLOW_UPGRADE_CHECK.md <ide> official Apache releases must not include the rcN suffix. <ide> - Rename the sdist <ide> <ide> ```shell script <del> mv dist/apache-airflow-upgrade-check-${VERSION%rc?}.tar.gz apache-airflow-upgrade-check-${VERSION}-bin.tar.gz <add> mv dist/apache-airflow-upgrade-check-${VERSION%rc?}.tar.gz apache-airflow-upgrade-check-${VERSION}.tar.gz <ide> mv dist/apache_airflow_upgrade_check-${VERSION%rc?}-py2.py3-none-any.whl apache_airflow_upgrade_check-${VERSION}-py2.py3-none-any.whl <ide> ``` <ide> <ide> official Apache releases must not include the rcN suffix. <ide> <ide> ```shell script <ide> ${AIRFLOW_REPO_ROOT}/dev/sign.sh apache-airflow-upgrade-check-${VERSION}-source.tar.gz <del> ${AIRFLOW_REPO_ROOT}/dev/sign.sh apache-airflow-upgrade-check-${VERSION}-bin.tar.gz <add> ${AIRFLOW_REPO_ROOT}/dev/sign.sh apache-airflow-upgrade-check-${VERSION}.tar.gz <ide> ${AIRFLOW_REPO_ROOT}/dev/sign.sh apache_airflow_upgrade_check-${VERSION}-py2.py3-none-any.whl <ide> ``` <ide> <ide> The files can be downloaded from https://dist.apache.org/repos/dist/dev/airflow/ <ide> - apache-airflow-upgrade-check-1.3.0rc1-source.tar.gz is a source <ide> release containing the files that made up the binary and wheel <ide> releases. <del>- apache-airflow-upgrade-check-1.3.0rc1-bin.tar.gz is the binary <add>- apache-airflow-upgrade-check-1.3.0rc1.tar.gz is the binary <ide> Python "sdist" release. <ide> - apache_airflow_upgrade_check-1.3.0rc1-py2.py3-none-any.whl is the <ide> binary Python pre-compiled wheel file. <ide> The files should be present in the sub-folder of <ide> <ide> The following files should be present (9 files): <ide> <del>* -bin-tar.gz + .asc + .sha512 <ide> * -source.tar.gz + .asc + .sha512 <del>* -.whl + .asc + .sha512 <add>* .tar.gz + .asc + .sha512 <add>* -py3-none-any.whl + .asc + .sha512 <ide> <ide> As a PMC you should be able to clone the SVN repository: <ide> <ide> warning. By importing the server in the previous step and importing it via ID fr <ide> this is a valid Key already. <ide> <ide> ``` <del>Checking apache-airflow-upgrade-check-1.3.0rc1-bin.tar.gz.asc <del>gpg: assuming signed data in 'apache-airflow-upgrade-check-1.3.0rc1-bin.tar.gz' <add>Checking apache-airflow-upgrade-check-1.3.0rc1.tar.gz.asc <add>gpg: assuming signed data in 'apache-airflow-upgrade-check-1.3.0rc1.tar.gz' <ide> gpg: Signature made Tue 9 Mar 23:22:24 2021 GMT <ide> gpg: using RSA key CDE15C6E4D3A8EC4ECF4BA4B6674E08AD7DE406F <ide> gpg: Good signature from "Kaxil Naik <kaxilnaik@apache.org>" [ultimate] <ide> done <ide> You should get output similar to: <ide> <ide> ``` <del>Checking apache-airflow-upgrade-check-1.3.0rc1-bin.tar.gz.sha512 <add>Checking apache-airflow-upgrade-check-1.3.0rc1.tar.gz.sha512 <ide> Checking apache_airflow_upgrade_check-1.3.0rc1-py2.py3-none-any.whl.sha512 <ide> Checking apache-airflow-upgrade-check-1.3.0rc1-source.tar.gz.sha512 <ide> ``` <ide><path>dev/README_RELEASE_PROVIDER_PACKAGES.md <ide> Consider this my (binding) +1. <ide> Airflow Providers are available at: <ide> https://dist.apache.org/repos/dist/dev/airflow/providers/ <ide> <del>*apache-airflow-providers-<PROVIDER>-*-bin.tar.gz* are the binary <add>*apache-airflow-providers-<PROVIDER>-*.tar.gz* are the binary <ide> Python "sdist" release - they are also official "sources" for the provider packages. <ide> <ide> *apache_airflow_providers_<PROVIDER>-*.whl are the binary <ide> Please modify the message above accordingly to clearly exclude those packages. <ide> The files should be present in <ide> [Airflow dist](https://dist.apache.org/repos/dist/dev/airflow/providers/) <ide> <del>The following files should be present (9 files): <add>The following files should be present (6 files): <ide> <del>* -source.tar.gz + .asc + .sha512 (one set of files) <del>* -bin-tar.gz + .asc + .sha512 (one set of files per provider) <del>* -.whl + .asc + .sha512 (one set of files per provider) <add>* .tar.gz + .asc + .sha512 (one set of files per provider) <add>* -py3-none-any.whl + .asc + .sha512 (one set of files per provider) <ide> <ide> As a PMC you should be able to clone the SVN repository: <ide> <ide> warning. By importing the server in the previous step and importing it via ID fr <ide> this is a valid Key already. <ide> <ide> ``` <del>Checking apache-airflow-2.0.2rc4-bin.tar.gz.asc <del>gpg: assuming signed data in 'apache-airflow-2.0.2rc4-bin.tar.gz' <add>Checking apache-airflow-2.0.2rc4.tar.gz.asc <add>gpg: assuming signed data in 'apache-airflow-2.0.2rc4.tar.gz' <ide> gpg: Signature made sob, 22 sie 2020, 20:28:28 CEST <ide> gpg: using RSA key 12717556040EEF2EEAF1B9C275FCCD0A25FA0E4B <ide> gpg: Good signature from "Kaxil Naik <kaxilnaik@gmail.com>" [unknown] <ide> done <ide> You should get output similar to: <ide> <ide> ``` <del>Checking apache-airflow-providers-google-1.0.0rc1-bin.tar.gz.sha512 <add>Checking apache-airflow-providers-google-1.0.0rc1.tar.gz.sha512 <ide> Checking apache_airflow-providers-google-1.0.0rc1-py3-none-any.whl.sha512 <ide> ``` <ide>
3
Ruby
Ruby
improve the performance of writing attributes
c879649a733d982fba9e70f5a280d13636b67c37
<ide><path>activerecord/lib/active_record/attribute_methods/primary_key.rb <ide> def id <ide> # Sets the primary key value. <ide> def id=(value) <ide> sync_with_transaction_state <del> write_attribute(self.class.primary_key, value) if self.class.primary_key <add> _write_attribute(self.class.primary_key, value) if self.class.primary_key <ide> end <ide> <ide> # Queries the primary key value. <ide><path>activerecord/lib/active_record/attribute_methods/write.rb <ide> def define_method_attribute=(name) <ide> generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 <ide> def __temp__#{safe_name}=(value) <ide> name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name} <del> write_attribute(name, value) <add> _write_attribute(name, value) <ide> end <ide> alias_method #{(name + '=').inspect}, :__temp__#{safe_name}= <ide> undef_method :__temp__#{safe_name}= <ide> def write_attribute(attr_name, value) <ide> end <ide> <ide> name = self.class.primary_key if name == "id".freeze && self.class.primary_key <del> @attributes.write_from_user(name, value) <del> value <add> _write_attribute(name, value) <ide> end <ide> <ide> def raw_write_attribute(attr_name, value) # :nodoc: <ide> def raw_write_attribute(attr_name, value) # :nodoc: <ide> value <ide> end <ide> <add> # This method exists to avoid the expensive primary_key check internally, without <add> # breaking compatibility with the write_attribute API <add> def _write_attribute(attr_name, value) # :nodoc: <add> @attributes.write_from_user(attr_name.to_s, value) <add> value <add> end <add> <ide> private <ide> # Handle *= for method_missing. <ide> def attribute=(attribute_name, value) <del> write_attribute(attribute_name, value) <add> _write_attribute(attribute_name, value) <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/inheritance.rb <ide> def initialize_internals_callback <ide> def ensure_proper_type <ide> klass = self.class <ide> if klass.finder_needs_type_condition? <del> write_attribute(klass.inheritance_column, klass.sti_name) <add> _write_attribute(klass.inheritance_column, klass.sti_name) <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/timestamp.rb <ide> def _create_record <ide> <ide> all_timestamp_attributes_in_model.each do |column| <ide> if !attribute_present?(column) <del> write_attribute(column, current_time) <add> _write_attribute(column, current_time) <ide> end <ide> end <ide> end <ide> def _update_record(*args, touch: true, **options) <ide> <ide> timestamp_attributes_for_update_in_model.each do |column| <ide> next if will_save_change_to_attribute?(column) <del> write_attribute(column, current_time) <add> _write_attribute(column, current_time) <ide> end <ide> end <ide> super(*args)
4
Go
Go
implement docker volume with standalone client lib
73bca058ae5d1e4ad2b94835fb1593ba3ca3983b
<ide><path>api/client/lib/volume.go <add>package lib <add> <add>import ( <add> "encoding/json" <add> "net/url" <add> <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/pkg/parsers/filters" <add>) <add> <add>// VolumeList returns the volumes configured in the docker host. <add>func (cli *Client) VolumeList(filter filters.Args) (types.VolumesListResponse, error) { <add> var volumes types.VolumesListResponse <add> var query url.Values <add> <add> if filter.Len() > 0 { <add> filterJSON, err := filters.ToParam(filter) <add> if err != nil { <add> return volumes, err <add> } <add> query.Set("filters", filterJSON) <add> } <add> resp, err := cli.GET("/volumes", query, nil) <add> if err != nil { <add> return volumes, err <add> } <add> defer ensureReaderClosed(resp) <add> <add> err = json.NewDecoder(resp.body).Decode(&volumes) <add> return volumes, err <add>} <add> <add>// VolumeInspect returns the information about a specific volume in the docker host. <add>func (cli *Client) VolumeInspect(volumeID string) (types.Volume, error) { <add> var volume types.Volume <add> resp, err := cli.GET("/volumes"+volumeID, nil, nil) <add> if err != nil { <add> return volume, err <add> } <add> defer ensureReaderClosed(resp) <add> err = json.NewDecoder(resp.body).Decode(&volume) <add> return volume, err <add>} <add> <add>// VolumeCreate creates a volume in the docker host. <add>func (cli *Client) VolumeCreate(options types.VolumeCreateRequest) (types.Volume, error) { <add> var volume types.Volume <add> resp, err := cli.POST("/volumes/create", nil, options, nil) <add> if err != nil { <add> return volume, err <add> } <add> defer ensureReaderClosed(resp) <add> err = json.NewDecoder(resp.body).Decode(&volume) <add> return volume, err <add>} <add> <add>// VolumeRemove removes a volume from the docker host. <add>func (cli *Client) VolumeRemove(volumeID string) error { <add> resp, err := cli.DELETE("/volumes"+volumeID, nil, nil) <add> ensureReaderClosed(resp) <add> return err <add>} <ide><path>api/client/volume.go <ide> import ( <ide> "encoding/json" <ide> "fmt" <ide> "io" <del> "net/http" <del> "net/url" <ide> "text/tabwriter" <ide> "text/template" <ide> <ide> func (cli *DockerCli) CmdVolumeLs(args ...string) error { <ide> } <ide> } <ide> <del> v := url.Values{} <del> if volFilterArgs.Len() > 0 { <del> filterJSON, err := filters.ToParam(volFilterArgs) <del> if err != nil { <del> return err <del> } <del> v.Set("filters", filterJSON) <del> } <del> <del> resp, err := cli.call("GET", "/volumes?"+v.Encode(), nil, nil) <add> volumes, err := cli.client.VolumeList(volFilterArgs) <ide> if err != nil { <ide> return err <ide> } <ide> <del> var volumes types.VolumesListResponse <del> if err := json.NewDecoder(resp.body).Decode(&volumes); err != nil { <del> return err <del> } <del> <ide> w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0) <ide> if !*quiet { <ide> fmt.Fprintf(w, "DRIVER \tVOLUME NAME") <ide> func (cli *DockerCli) CmdVolumeInspect(args ...string) error { <ide> var volumes []*types.Volume <ide> <ide> for _, name := range cmd.Args() { <del> resp, err := cli.call("GET", "/volumes/"+name, nil, nil) <add> volume, err := cli.client.VolumeInspect(name) <ide> if err != nil { <del> if resp.statusCode != http.StatusNotFound { <del> return err <del> } <del> status = 1 <del> fmt.Fprintf(cli.err, "Error: No such volume: %s\n", name) <del> continue <del> } <del> <del> var volume types.Volume <del> if err := json.NewDecoder(resp.body).Decode(&volume); err != nil { <ide> fmt.Fprintf(cli.err, "Unable to read inspect data: %v\n", err) <ide> status = 1 <ide> break <ide> func (cli *DockerCli) CmdVolumeCreate(args ...string) error { <ide> cmd.Require(flag.Exact, 0) <ide> cmd.ParseFlags(args, true) <ide> <del> volReq := &types.VolumeCreateRequest{ <add> volReq := types.VolumeCreateRequest{ <ide> Driver: *flDriver, <ide> DriverOpts: flDriverOpts.GetAll(), <add> Name: *flName, <ide> } <ide> <del> if *flName != "" { <del> volReq.Name = *flName <del> } <del> <del> resp, err := cli.call("POST", "/volumes/create", volReq, nil) <add> vol, err := cli.client.VolumeCreate(volReq) <ide> if err != nil { <ide> return err <ide> } <ide> <del> var vol types.Volume <del> if err := json.NewDecoder(resp.body).Decode(&vol); err != nil { <del> return err <del> } <ide> fmt.Fprintf(cli.out, "%s\n", vol.Name) <ide> return nil <ide> } <ide> func (cli *DockerCli) CmdVolumeRm(args ...string) error { <ide> <ide> var status = 0 <ide> for _, name := range cmd.Args() { <del> _, err := cli.call("DELETE", "/volumes/"+name, nil, nil) <del> if err != nil { <add> if err := cli.client.VolumeRemove(name); err != nil { <ide> fmt.Fprintf(cli.err, "%s\n", err) <ide> status = 1 <ide> continue
2
PHP
PHP
improve function `retry()`
ba6e666dc7c5ed84213472387fe0851f625d131a
<ide><path>src/Illuminate/Support/helpers.php <ide> function preg_replace_array($pattern, array $replacements, $subject) <ide> function retry($times, callable $callback, $sleep = 0, $when = null) <ide> { <ide> $attempts = 0; <del> $times--; <ide> <ide> beginning: <ide> $attempts++; <add> $times--; <ide> <ide> try { <ide> return $callback($attempts); <ide> } catch (Exception $e) { <del> if (! $times || ($when && ! $when($e))) { <add> if ($times < 1 || ($when && ! $when($e))) { <ide> throw $e; <ide> } <ide> <del> $times--; <del> <ide> if ($sleep) { <ide> usleep($sleep * 1000); <ide> }
1
Text
Text
fix example comment spacings
521138726b66e7d519f415018eefb345e3d5c9e4
<ide><path>guide/english/javascript/logical-operators/index.md <ide> If the first evaluates as ["falsy"](https://developer.mozilla.org/en-US/docs/Glo <ide> <ide> When only involving boolean values (either `true` or `false`), it returns true if only if both expressions are true. If one or both expressions are false, the entire statement will return false. <ide> ```js <del>true && true //returns the second value, true <del>true && false //returns the second value, false <del>false && false //returns the first value, false <del>123 && 'abc' // returns the second value, 'abc' <del>'abc' && null //returns the second value, null <del>undefined && 'abc' //returns the first value, undefined <del>0 && false //returns the first value, 0 <add>true && true //returns the second value, true <add>true && false //returns the second value, false <add>false && false //returns the first value, false <add>123 && 'abc' //returns the second value, 'abc' <add>'abc' && null //returns the second value, null <add>undefined && 'abc' //returns the first value, undefined <add>0 && false //returns the first value, 0 <ide> ``` <ide> <ide> #### Logical OR ( || ) <ide> The OR operator compares two expressions. If the first evaluates as "falsy", the <ide> <ide> When only involving boolean values (either `true` or `false`), it returns true if either expression is true. Both expressions can be true, but only one is needed to get true as a result. <ide> ```js <del>true || true //returns the first value, true <del>true || false //returns the first value, true <del>false || false //returns the second value, false <del>123 || 'abc' // returns the first value, 123 <del>'abc' || null //returns the first value, 'abc' <add>true || true //returns the first value, true <add>true || false //returns the first value, true <add>false || false //returns the second value, false <add>123 || 'abc' //returns the first value, 123 <add>'abc' || null //returns the first value, 'abc' <ide> undefined || 'abc' //returns the second value, 'abc' <del>0 || false //returns the second value, false <add>0 || false //returns the second value, false <ide> ``` <ide> #### Short-circuit evaluation <ide> && and || behave as a short-circuit operators.
1
Ruby
Ruby
use xcode 10.2 for new taps too
9050d0a7b1f4f2126beb152212be34fe419c5297
<ide><path>Library/Homebrew/dev-cmd/tap-new.rb <ide> def tap_new <ide> steps: <ide> - bash: | <ide> set -e <del> sudo xcode-select --switch /Applications/Xcode_10.1.app/Contents/Developer <add> sudo xcode-select --switch /Applications/Xcode_10.2.app/Contents/Developer <ide> brew update <ide> HOMEBREW_TAP_DIR="/usr/local/Homebrew/Library/Taps/#{tap.full_name}" <ide> mkdir -p "$HOMEBREW_TAP_DIR"
1
Text
Text
revise description of process.ppid
dcf708d6526d0707c15e786797bcf11e22a15f08
<ide><path>doc/api/process.md <ide> added: <ide> <ide> * {integer} <ide> <del>The `process.ppid` property returns the PID of the current parent process. <add>The `process.ppid` property returns the PID of the parent of the <add>current process. <ide> <ide> ```js <ide> console.log(`The parent process is pid ${process.ppid}`);
1
Ruby
Ruby
add check for outdated compilers
4dc1a7bdce4d2b311c2ca2507ecdd5654a813f2b
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def check_cc <ide> end <ide> end <ide> <add>def check_standard_compilers <add> return if check_for_latest_xcode # only check if Xcode is up to date <add> if !MacOS.compilers_standard? then <<-EOS.undent <add> Your compilers are different from the standard versions for your Xcode. <add> If you have Xcode 4.3 or newer, you should install the Command Line Tools for <add> Xcode from within Xcode's Download preferences. <add> Otherwise, you should reinstall Xcode. <add> EOS <add> end <add>end <add> <ide> def __check_subdir_access base <ide> target = HOMEBREW_PREFIX+base <ide> return unless target.exist? <ide><path>Library/Homebrew/utils.rb <ide> def mountain_lion? <ide> def prefer_64_bit? <ide> Hardware.is_64_bit? and not leopard? <ide> end <add> <add> StandardCompilers = { <add> "3.1.4" => {:gcc_40_build_version=>5493, :gcc_42_build_version=>5577, :llvm_build_version=>2064}, <add> "3.2.6" => {:gcc_40_build_version=>5494, :gcc_42_build_version=>5666, :llvm_build_version=>2335, :clang_version=>"1.7", :clang_build_version=>77}, <add> "4.0.0" => {:gcc_40_build_version=>5494, :gcc_42_build_version=>5666, :llvm_build_version=>2335, :clang_version=>"2.0", :clang_build_version=>137}, <add> "4.0.1" => {:gcc_40_build_version=>5494, :gcc_42_build_version=>5666, :llvm_build_version=>2335, :clang_version=>"2.0", :clang_build_version=>137}, <add> "4.0.2" => {:gcc_40_build_version=>5494, :gcc_42_build_version=>5666, :llvm_build_version=>2335, :clang_version=>"2.0", :clang_build_version=>137}, <add> "4.2.0" => {:llvm_build_version=>2336, :clang_version=>"3.0", :clang_build_version=>211}, <add> "4.3.0" => {:llvm_build_version=>2336, :clang_version=>"3.1", :clang_build_version=>318}, <add> "4.3.1" => {:llvm_build_version=>2336, :clang_version=>"3.1", :clang_build_version=>318}, <add> "4.3.2" => {:llvm_build_version=>2336, :clang_version=>"3.1", :clang_build_version=>318} <add> } <add> <add> def compilers_standard? <add> xcode = MacOS.xcode_version <add> return unless StandardCompilers.keys.include? xcode <add> <add> StandardCompilers[xcode].all? {|k,v| MacOS.send(k) == v} <add> end <ide> end <ide> <ide> module GitHub extend self
2
Ruby
Ruby
remove unused guard in canonical_name
9903e7cd92397323fdfaa05f778d5f16ae27e9d6
<ide><path>Library/Homebrew/formula.rb <ide> def self.aliases <ide> end <ide> <ide> def self.canonical_name name <del> name = name.to_s if name.kind_of? Pathname <del> <ide> # if name includes a '/', it may be a tap reference, path, or URL <ide> if name.include? "/" <ide> if name =~ %r{(.+)/(.+)/(.+)}
1
Ruby
Ruby
pass the link mode to resolve_any_conflicts
75af625c17867d6336096e43dadf5a668e3f436b
<ide><path>Library/Homebrew/keg.rb <ide> def delete_pyc_files! <ide> <ide> protected <ide> <del> def resolve_any_conflicts dst <add> def resolve_any_conflicts dst, mode <ide> # if it isn't a directory then a severe conflict is about to happen. Let <ide> # it, and the exception that is generated will message to the user about <ide> # the situation <ide> if dst.symlink? and dst.directory? <ide> src = (dst.parent+dst.readlink).cleanpath <ide> keg = Keg.for(src) <del> dst.unlink <del> keg.link_dir(src) { :mkpath } <add> dst.unlink unless mode.dry_run <add> keg.link_dir(src, mode) { :mkpath } <ide> return true <ide> end <ide> rescue NotAKegError <ide> def link_dir foo, mode=OpenStruct.new <ide> when :skip_dir <ide> Find.prune <ide> when :mkpath <del> dst.mkpath unless resolve_any_conflicts(dst) <add> dst.mkpath unless resolve_any_conflicts(dst, mode) <ide> else <del> unless resolve_any_conflicts(dst) <add> unless resolve_any_conflicts(dst, mode) <ide> make_relative_symlink dst, src, mode <ide> Find.prune <ide> end
1
Text
Text
remove mentions of airflow gitter
27339a5a0f9e382dbc7d32a128f0831a48ef9a12
<ide><path>airflow/providers/apache/hive/example_dags/example_twitter_README.md <ide> CREATE TABLE toTwitter_A(id BIGINT, id_str STRING <ide> <ide> When you review the code for the DAG, you will notice that these tasks are generated using for loop. These two for loops could be combined into one loop. However, in most cases, you will be running different analysis on your incoming incoming and outgoing tweets, and hence they are kept separated in this example. <ide> Final step is a running the broker script, brokerapi.py, which will run queries in Hive and store the summarized data to MySQL in our case. To connect to Hive, pyhs2 library is extremely useful and easy to use. To insert data into MySQL from Python, sqlalchemy is also a good one to use. <del>I hope you find this tutorial useful. If you have question feel free to ask me on [Twitter](https://twitter.com/EkhtiarSyed) or via the live Airflow chatroom room in [Gitter](https://gitter.im/apache/airflow).<p> <add>I hope you find this tutorial useful. If you have question feel free to ask me on [Twitter](https://twitter.com/EkhtiarSyed).<p> <ide> -Ekhtiar Syed <ide> Last Update: 8-April-2016
1
Javascript
Javascript
combine flags and subtreeflags types
7baf9d4128d41903de125527b50285ea9862cf9a
<ide><path>packages/react-reconciler/src/ReactFiber.new.js <ide> import { <ide> enableBlocksAPI, <ide> } from 'shared/ReactFeatureFlags'; <ide> import {NoFlags, Placement, StaticMask} from './ReactFiberFlags'; <del>import {NoFlags as NoSubtreeEffect} from './ReactSubtreeFlags'; <ide> import {ConcurrentRoot, BlockingRoot} from './ReactRootTags'; <ide> import { <ide> IndeterminateComponent, <ide> function FiberNode( <ide> <ide> // Effects <ide> this.flags = NoFlags; <del> this.subtreeFlags = NoSubtreeEffect; <add> this.subtreeFlags = NoFlags; <ide> this.deletions = null; <ide> <ide> this.lanes = NoLanes; <ide> export function createWorkInProgress(current: Fiber, pendingProps: any): Fiber { <ide> workInProgress.type = current.type; <ide> <ide> // We already have an alternate. <del> workInProgress.subtreeFlags = NoSubtreeEffect; <add> workInProgress.subtreeFlags = NoFlags; <ide> workInProgress.deletions = null; <ide> <ide> if (enableProfilerTimer) { <ide> export function resetWorkInProgress(workInProgress: Fiber, renderLanes: Lanes) { <ide> workInProgress.lanes = renderLanes; <ide> <ide> workInProgress.child = null; <del> workInProgress.subtreeFlags = NoSubtreeEffect; <add> workInProgress.subtreeFlags = NoFlags; <ide> workInProgress.memoizedProps = null; <ide> workInProgress.memoizedState = null; <ide> workInProgress.updateQueue = null; <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js <ide> import { <ide> Placement, <ide> Snapshot, <ide> Update, <add> PassiveMask, <ide> } from './ReactFiberFlags'; <ide> import getComponentName from 'shared/getComponentName'; <ide> import invariant from 'shared/invariant'; <ide> import { <ide> Passive as HookPassive, <ide> } from './ReactHookEffectTags'; <ide> import {didWarnAboutReassigningProps} from './ReactFiberBeginWork.new'; <del>import { <del> NoFlags as NoSubtreeFlags, <del> Passive as PassiveSubtreeFlags, <del>} from './ReactSubtreeFlags'; <ide> <ide> let didWarnAboutUndefinedSnapshotBeforeUpdate: Set<mixed> | null = null; <ide> if (__DEV__) { <ide> function commitLifeCycles( <ide> commitHookEffectListMount(HookLayout | HookHasEffect, finishedWork); <ide> } <ide> <del> if ( <del> (finishedWork.subtreeFlags & PassiveSubtreeFlags) !== <del> NoSubtreeFlags <del> ) { <add> if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags) { <ide> schedulePassiveEffectCallback(); <ide> } <ide> return; <ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.new.js <ide> import { <ide> Snapshot, <ide> MutationMask, <ide> } from './ReactFiberFlags'; <del>import {NoFlags as NoSubtreeFlags, Mutation} from './ReactSubtreeFlags'; <ide> import invariant from 'shared/invariant'; <ide> <ide> import { <ide> function hadNoMutationsEffects(current: null | Fiber, completedWork: Fiber) { <ide> if ((child.flags & MutationMask) !== NoFlags) { <ide> return false; <ide> } <del> if ((child.subtreeFlags & Mutation) !== NoSubtreeFlags) { <add> if ((child.subtreeFlags & MutationMask) !== NoFlags) { <ide> return false; <ide> } <ide> child = child.sibling; <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js <ide> import { <ide> MutationMask, <ide> LayoutMask, <ide> PassiveMask, <add> StaticMask, <ide> } from './ReactFiberFlags'; <del>import { <del> NoFlags as NoSubtreeFlags, <del> BeforeMutation as BeforeMutationSubtreeFlags, <del> Mutation as MutationSubtreeFlags, <del> Layout as LayoutSubtreeFlags, <del> Passive as PassiveSubtreeFlags, <del> PassiveStatic as PassiveStaticSubtreeFlags, <del>} from './ReactSubtreeFlags'; <ide> import { <ide> NoLanePriority, <ide> SyncLanePriority, <ide> function completeUnitOfWork(unitOfWork: Fiber): void { <ide> if (returnFiber !== null) { <ide> // Mark the parent fiber as incomplete <ide> returnFiber.flags |= Incomplete; <del> returnFiber.subtreeFlags = NoSubtreeFlags; <add> returnFiber.subtreeFlags = NoFlags; <ide> returnFiber.deletions = null; <ide> } <ide> } <ide> function resetChildLanes(completedWork: Fiber) { <ide> completedWork.alternate.child === completedWork.child; <ide> <ide> let newChildLanes = NoLanes; <del> let subtreeFlags = NoSubtreeFlags; <add> let subtreeFlags = NoFlags; <ide> <ide> if (!didBailout) { <ide> // Bubble up the earliest expiration time. <ide> function resetChildLanes(completedWork: Fiber) { <ide> ); <ide> <ide> subtreeFlags |= child.subtreeFlags; <del> <del> const flags = child.flags; <del> if ((flags & BeforeMutationMask) !== NoFlags) { <del> subtreeFlags |= BeforeMutationSubtreeFlags; <del> } <del> if ((flags & MutationMask) !== NoFlags) { <del> subtreeFlags |= MutationSubtreeFlags; <del> } <del> if ((flags & LayoutMask) !== NoFlags) { <del> subtreeFlags |= LayoutSubtreeFlags; <del> } <del> if ((flags & PassiveMask) !== NoFlags) { <del> subtreeFlags |= PassiveSubtreeFlags; <del> } <del> if ((flags & PassiveStatic) !== NoFlags) { <del> subtreeFlags |= PassiveStaticSubtreeFlags; <del> } <add> subtreeFlags |= child.flags; <ide> <ide> // When a fiber is cloned, its actualDuration is reset to 0. This value will <ide> // only be updated if work is done on the fiber (i.e. it doesn't bailout). <ide> function resetChildLanes(completedWork: Fiber) { <ide> ); <ide> <ide> subtreeFlags |= child.subtreeFlags; <del> <del> const flags = child.flags; <del> if ((flags & BeforeMutationMask) !== NoFlags) { <del> subtreeFlags |= BeforeMutationSubtreeFlags; <del> } <del> if ((flags & MutationMask) !== NoFlags) { <del> subtreeFlags |= MutationSubtreeFlags; <del> } <del> if ((flags & LayoutMask) !== NoFlags) { <del> subtreeFlags |= LayoutSubtreeFlags; <del> } <del> if ((flags & PassiveMask) !== NoFlags) { <del> subtreeFlags |= PassiveSubtreeFlags; <del> } <del> if ((flags & PassiveStatic) !== NoFlags) { <del> subtreeFlags |= PassiveStaticSubtreeFlags; <del> } <add> subtreeFlags |= child.flags; <ide> <ide> child = child.sibling; <ide> } <ide> function resetChildLanes(completedWork: Fiber) { <ide> mergeLanes(child.lanes, child.childLanes), <ide> ); <ide> <del> // Preserve passive static flag even in the case of a bailout; <del> // otherwise a subsequent unmount may bailout before calling destroy functions. <del> subtreeFlags |= child.subtreeFlags & PassiveStaticSubtreeFlags; <del> const flags = child.flags; <del> if ((flags & PassiveStatic) !== NoFlags) { <del> subtreeFlags |= PassiveStaticSubtreeFlags; <del> } <add> // "Static" flags share the lifetime of the fiber/hook they belong to, <add> // so we should bubble those up even during a bailout. All the other <add> // flags have a lifetime only of a single render + commit, so we should <add> // ignore them. <add> subtreeFlags |= child.subtreeFlags & StaticMask; <add> subtreeFlags |= child.flags & StaticMask; <ide> <ide> treeBaseDuration += child.treeBaseDuration; <ide> child = child.sibling; <ide> function resetChildLanes(completedWork: Fiber) { <ide> mergeLanes(child.lanes, child.childLanes), <ide> ); <ide> <del> // Preserve passive static flag even in the case of a bailout; <del> // otherwise a subsequent unmount may bailout before calling destroy functions. <del> subtreeFlags |= child.subtreeFlags & PassiveStaticSubtreeFlags; <del> const flags = child.flags; <del> if ((flags & PassiveStatic) !== NoFlags) { <del> subtreeFlags |= PassiveStaticSubtreeFlags; <del> } <add> // "Static" flags share the lifetime of the fiber/hook they belong to, <add> // so we should bubble those up even during a bailout. All the other <add> // flags have a lifetime only of a single render + commit, so we should <add> // ignore them. <add> subtreeFlags |= child.subtreeFlags & StaticMask; <add> subtreeFlags |= child.flags & StaticMask; <ide> <ide> child = child.sibling; <ide> } <ide> function commitRootImpl(root, renderPriorityLevel) { <ide> // Reconsider whether this is necessary. <ide> const subtreeHasEffects = <ide> (finishedWork.subtreeFlags & <del> (BeforeMutationSubtreeFlags | <del> MutationSubtreeFlags | <del> LayoutSubtreeFlags | <del> PassiveSubtreeFlags)) !== <del> NoSubtreeFlags; <add> (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== <add> NoFlags; <ide> const rootHasEffect = <ide> (finishedWork.flags & <ide> (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== <ide> function commitRootImpl(root, renderPriorityLevel) { <ide> <ide> // If there are pending passive effects, schedule a callback to process them. <ide> if ( <del> (finishedWork.subtreeFlags & PassiveSubtreeFlags) !== NoSubtreeFlags || <add> (finishedWork.subtreeFlags & PassiveMask) !== NoFlags || <ide> (finishedWork.flags & PassiveMask) !== NoFlags <ide> ) { <ide> if (!rootDoesHavePassiveEffects) { <ide> function commitBeforeMutationEffects(firstChild: Fiber) { <ide> } <ide> <ide> if (fiber.child !== null) { <del> const primarySubtreeFlags = <del> fiber.subtreeFlags & BeforeMutationSubtreeFlags; <del> if (primarySubtreeFlags !== NoSubtreeFlags) { <add> const primarySubtreeFlags = fiber.subtreeFlags & BeforeMutationMask; <add> if (primarySubtreeFlags !== NoFlags) { <ide> commitBeforeMutationEffects(fiber.child); <ide> } <ide> } <ide> function commitMutationEffects( <ide> } <ide> <ide> if (fiber.child !== null) { <del> const primarySubtreeFlags = fiber.subtreeFlags & MutationSubtreeFlags; <del> if (primarySubtreeFlags !== NoSubtreeFlags) { <add> const mutationFlags = fiber.subtreeFlags & MutationMask; <add> if (mutationFlags !== NoFlags) { <ide> commitMutationEffects(fiber.child, root, renderPriorityLevel); <ide> } <ide> } <ide> function commitLayoutEffects( <ide> let fiber = firstChild; <ide> while (fiber !== null) { <ide> if (fiber.child !== null) { <del> const primarySubtreeFlags = fiber.subtreeFlags & LayoutSubtreeFlags; <del> if (primarySubtreeFlags !== NoSubtreeFlags) { <add> const primarySubtreeFlags = fiber.subtreeFlags & LayoutMask; <add> if (primarySubtreeFlags !== NoFlags) { <ide> commitLayoutEffects(fiber.child, root, committedLanes); <ide> } <ide> } <ide> export function enqueuePendingPassiveProfilerEffect(fiber: Fiber): void { <ide> function flushPassiveMountEffects(firstChild: Fiber): void { <ide> let fiber = firstChild; <ide> while (fiber !== null) { <del> const primarySubtreeFlags = fiber.subtreeFlags & PassiveSubtreeFlags; <add> const primarySubtreeFlags = fiber.subtreeFlags & PassiveMask; <ide> <del> if (fiber.child !== null && primarySubtreeFlags !== NoSubtreeFlags) { <add> if (fiber.child !== null && primarySubtreeFlags !== NoFlags) { <ide> flushPassiveMountEffects(fiber.child); <ide> } <ide> <ide> function flushPassiveUnmountEffects(firstChild: Fiber): void { <ide> // Note that this requires checking subtreeFlags of the current Fiber, <ide> // rather than the subtreeFlags/effectsTag of the first child, <ide> // since that would not cover passive effects in siblings. <del> const primarySubtreeFlags = fiber.subtreeFlags & PassiveSubtreeFlags; <del> if (primarySubtreeFlags !== NoSubtreeFlags) { <add> const passiveFlags = fiber.subtreeFlags & PassiveMask; <add> if (passiveFlags !== NoFlags) { <ide> flushPassiveUnmountEffects(child); <ide> } <ide> } <ide> function flushPassiveUnmountEffectsInsideOfDeletedTree( <ide> fiberToDelete: Fiber, <ide> nearestMountedAncestor: Fiber, <ide> ): void { <del> if ( <del> (fiberToDelete.subtreeFlags & PassiveStaticSubtreeFlags) !== <del> NoSubtreeFlags <del> ) { <add> if ((fiberToDelete.subtreeFlags & PassiveStatic) !== NoFlags) { <ide> // If any children have passive effects then traverse the subtree. <ide> // Note that this requires checking subtreeFlags of the current Fiber, <ide> // rather than the subtreeFlags/effectsTag of the first child, <ide><path>packages/react-reconciler/src/ReactInternalTypes.js <ide> import type {SuspenseInstance} from './ReactFiberHostConfig'; <ide> import type {WorkTag} from './ReactWorkTags'; <ide> import type {TypeOfMode} from './ReactTypeOfMode'; <ide> import type {Flags} from './ReactFiberFlags'; <del>import type {SubtreeFlags} from './ReactSubtreeFlags'; <ide> import type {Lane, LanePriority, Lanes, LaneMap} from './ReactFiberLane'; <ide> import type {HookType} from './ReactFiberHooks.old'; <ide> import type {RootTag} from './ReactRootTags'; <ide> export type Fiber = {| <ide> <ide> // Effect <ide> flags: Flags, <del> subtreeFlags: SubtreeFlags, <add> subtreeFlags: Flags, <ide> deletions: Array<Fiber> | null, <ide> <ide> // Singly linked list fast path to the next fiber with side-effects. <ide><path>packages/react-reconciler/src/ReactSubtreeFlags.js <del>/** <del> * Copyright (c) Facebook, Inc. and its affiliates. <del> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <del> * <del> * @flow <del> */ <del> <del>// TODO: Move this to ReactFiberFlags so it's easier to line up the bits <del>export type SubtreeFlags = number; <del> <del>export const NoFlags = /* */ 0b00000; <del>export const BeforeMutation = /* */ 0b00001; <del>export const Mutation = /* */ 0b00010; <del>export const Layout = /* */ 0b00100; <del>export const Passive = /* */ 0b01000; <del>export const PassiveStatic = /* */ 0b10000;
6
PHP
PHP
add missing throws docblocks
99da7163fa53631b0449b11569fddc660e4806a7
<ide><path>src/Illuminate/Auth/AuthManager.php <ide> public function guard($name = null) <ide> * <ide> * @param string $name <ide> * @return \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard <add> * <add> * @throws \InvalidArgumentException <ide> */ <ide> protected function resolve($name) <ide> { <ide><path>src/Illuminate/Auth/Passwords/PasswordBrokerManager.php <ide> public function broker($name = null) <ide> * <ide> * @param string $name <ide> * @return \Illuminate\Contracts\Auth\PasswordBroker <add> * <add> * @throws \InvalidArgumentException <ide> */ <ide> protected function resolve($name) <ide> { <ide><path>src/Illuminate/Console/Parser.php <ide> class Parser <ide> * <ide> * @param string $expression <ide> * @return array <add> * <add> * @throws \InvalidArgumentException <ide> */ <ide> public static function parse($expression) <ide> { <ide><path>src/Illuminate/Console/Scheduling/CallbackEvent.php <ide> class CallbackEvent extends Event <ide> * @param string $callback <ide> * @param array $parameters <ide> * @return void <add> * <add> * @throws \InvalidArgumentException <ide> */ <ide> public function __construct($callback, array $parameters = []) <ide> { <ide> protected function removeMutex() <ide> * Do not allow the event to overlap each other. <ide> * <ide> * @return $this <add> * <add> * @throws \LogicException <ide> */ <ide> public function withoutOverlapping() <ide> { <ide><path>src/Illuminate/Container/Container.php <ide> protected function addDependencyForCallParameter(ReflectionParameter $parameter, <ide> * @param array $parameters <ide> * @param string|null $defaultMethod <ide> * @return mixed <add> * <add> * @throws \InvalidArgumentException <ide> */ <ide> protected function callClass($target, array $parameters = [], $defaultMethod = null) <ide> { <ide><path>src/Illuminate/Database/Connection.php <ide> public function prepareBindings(array $bindings) <ide> * @param \Closure $callback <ide> * @return mixed <ide> * <del> * @throws \Throwable <add> * @throws \Exception|\Throwable <ide> */ <ide> public function transaction(Closure $callback) <ide> { <ide> public function getReadPdo() <ide> * <ide> * @param \PDO|null $pdo <ide> * @return $this <add> * <add> * @throws \RuntimeException <ide> */ <ide> public function setPdo($pdo) <ide> { <ide><path>src/Illuminate/Database/Eloquent/FactoryBuilder.php <ide> public function make(array $attributes = []) <ide> * <ide> * @param array $attributes <ide> * @return \Illuminate\Database\Eloquent\Model <add> * <add> * @throws \InvalidArgumentException <ide> */ <ide> protected function makeInstance(array $attributes = []) <ide> { <ide><path>src/Illuminate/Database/Eloquent/QueueEntityResolver.php <ide> class QueueEntityResolver implements EntityResolverContract <ide> * @param string $type <ide> * @param mixed $id <ide> * @return mixed <add> * <add> * @throws \Illuminate\Contracts\Queue\EntityNotFoundException <ide> */ <ide> public function resolve($type, $id) <ide> { <ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function selectRaw($expression, array $bindings = []) <ide> * @param \Closure|\Illuminate\Database\Query\Builder|string $query <ide> * @param string $as <ide> * @return \Illuminate\Database\Query\Builder|static <add> * <add> * @throws \InvalidArgumentException <ide> */ <ide> public function selectSub($query, $as) <ide> { <ide><path>src/Illuminate/Database/Schema/Grammars/Grammar.php <ide> protected function getDoctrineTableDiff(Blueprint $blueprint, SchemaManager $sch <ide> * @param \Illuminate\Support\Fluent $command <ide> * @param \Illuminate\Database\Connection $connection <ide> * @return array <add> * <add> * @throws \RuntimeException <ide> */ <ide> public function compileChange(Blueprint $blueprint, Fluent $command, Connection $connection) <ide> { <ide><path>src/Illuminate/Database/SqlServerConnection.php <ide> class SqlServerConnection extends Connection <ide> * @param \Closure $callback <ide> * @return mixed <ide> * <del> * @throws \Throwable <add> * @throws \Exception|\Throwable <ide> */ <ide> public function transaction(Closure $callback) <ide> { <ide><path>src/Illuminate/Encryption/EncryptionServiceProvider.php <ide> class EncryptionServiceProvider extends ServiceProvider <ide> * Register the service provider. <ide> * <ide> * @return void <add> * <add> * @throws \RuntimeException <ide> */ <ide> public function register() <ide> { <ide><path>src/Illuminate/Filesystem/FilesystemAdapter.php <ide> protected function filterContentsByType($contents, $type) <ide> * <ide> * @param string|null $visibility <ide> * @return string|null <add> * <ide> * @throws \InvalidArgumentException <ide> */ <ide> protected function parseVisibility($visibility) <ide><path>src/Illuminate/Foundation/Http/FormRequest.php <ide> protected function getValidatorInstance() <ide> * <ide> * @param \Illuminate\Contracts\Validation\Validator $validator <ide> * @return mixed <add> * <add> * @throws \Illuminate\Http\Exception\HttpResponseException <ide> */ <ide> protected function failedValidation(Validator $validator) <ide> { <ide> protected function passesAuthorization() <ide> * Handle a failed authorization attempt. <ide> * <ide> * @return mixed <add> * <add> * @throws \\Illuminate\Http\Exception\HttpResponseExceptio <ide> */ <ide> protected function failedAuthorization() <ide> { <ide><path>src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php <ide> protected function seePageIs($uri) <ide> * @param string $uri <ide> * @param string|null $message <ide> * @return void <add> * <add> * @throws \Illuminate\Foundation\Testing\HttpException <ide> */ <ide> protected function assertPageLoaded($uri, $message = null) <ide> { <ide> protected function isChecked($selector) <ide> * <ide> * @param string $name <ide> * @return $this <add> * <add> * @throws \InvalidArgumentException <ide> */ <ide> protected function click($name) <ide> { <ide> protected function fillForm($buttonText, $inputs = []) <ide> * <ide> * @param string|null $buttonText <ide> * @return \Symfony\Component\DomCrawler\Form <add> * <add> * @throws \InvalidArgumentException <ide> */ <ide> protected function getForm($buttonText = null) <ide> { <ide> protected function storeInput($element, $text) <ide> * <ide> * @param string $filter <ide> * @return void <add> * <add> * @throws \InvalidArgumentException <ide> */ <ide> protected function assertFilterProducesResults($filter) <ide> { <ide><path>src/Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php <ide> trait MocksApplicationServices <ide> * <ide> * @param array|string $events <ide> * @return $this <add> * <add> * @throws \Exception <ide> */ <ide> public function expectsEvents($events) <ide> { <ide><path>src/Illuminate/Foundation/Testing/WithoutEvents.php <ide> <ide> trait WithoutEvents <ide> { <add> /** <add> * @throws \Exception <add> */ <ide> public function disableEventsForAllTests() <ide> { <ide> if (method_exists($this, 'withoutEvents')) { <ide><path>src/Illuminate/Foundation/Testing/WithoutMiddleware.php <ide> <ide> trait WithoutMiddleware <ide> { <add> /** <add> * @throws \Exception <add> */ <ide> public function disableMiddlewareForAllTests() <ide> { <ide> if (method_exists($this, 'withoutMiddleware')) { <ide><path>src/Illuminate/Foundation/Validation/ValidatesRequests.php <ide> trait ValidatesRequests <ide> * @param array $messages <ide> * @param array $customAttributes <ide> * @return void <del> * <del> * @throws \Illuminate\Foundation\Validation\ValidationException <ide> */ <ide> public function validate(Request $request, array $rules, array $messages = [], array $customAttributes = []) <ide> { <ide><path>src/Illuminate/Foundation/helpers.php <ide> function csrf_field() <ide> * <ide> * @return string <ide> * <del> * @throws RuntimeException <add> * @throws \RuntimeException <ide> */ <ide> function csrf_token() <ide> { <ide><path>src/Illuminate/Http/Request.php <ide> public function route($param = null) <ide> * Get a unique fingerprint for the request / route / IP address. <ide> * <ide> * @return string <add> * <add> * @throws \RuntimeException <ide> */ <ide> public function fingerprint() <ide> { <ide><path>src/Illuminate/Queue/SyncQueue.php <ide> class SyncQueue extends Queue implements QueueContract <ide> * @param mixed $data <ide> * @param string $queue <ide> * @return mixed <del> * @throws \Throwable <add> * <add> * @throws \Exception|\Throwable <ide> */ <ide> public function push($job, $data = '', $queue = null) <ide> { <ide><path>src/Illuminate/Routing/UrlGenerator.php <ide> public function route($name, $parameters = [], $absolute = true) <ide> * @param mixed $parameters <ide> * @param bool $absolute <ide> * @return string <add> * <add> * @throws \Illuminate\Routing\Exceptions\UrlGenerationException <ide> */ <ide> protected function toRoute($route, $parameters, $absolute) <ide> { <ide><path>src/Illuminate/Support/Facades/Facade.php <ide> public static function setFacadeApplication($app) <ide> * @param string $method <ide> * @param array $args <ide> * @return mixed <add> * <add> * @throws \RuntimeException <ide> */ <ide> public static function __callStatic($method, $args) <ide> { <ide><path>src/Illuminate/Support/ServiceProvider.php <ide> public static function compiles() <ide> * @param string $method <ide> * @param array $parameters <ide> * @return mixed <add> * <add> * @throws \BadMethodCallException <ide> */ <ide> public function __call($method, $parameters) <ide> { <ide><path>src/Illuminate/Validation/ValidatesWhenResolvedTrait.php <ide> protected function getValidatorInstance() <ide> * <ide> * @param \Illuminate\Validation\Validator $validator <ide> * @return mixed <add> * <add> * @throws \Illuminate\Contracts\Validation\ValidationExceptio <ide> */ <ide> protected function failedValidation(Validator $validator) <ide> { <ide> protected function passesAuthorization() <ide> /** <ide> * Handle a failed authorization attempt. <ide> * <del> * @return mixed <add> * @throws \Illuminate\Contracts\Validation\UnauthorizedException <ide> */ <ide> protected function failedAuthorization() <ide> { <ide><path>src/Illuminate/Validation/Validator.php <ide> protected function callClassBasedReplacer($callback, $message, $attribute, $rule <ide> * @param array $parameters <ide> * @param string $rule <ide> * @return void <add> * <ide> * @throws \InvalidArgumentException <ide> */ <ide> protected function requireParameterCount($count, $parameters, $rule)
27
Javascript
Javascript
add newline at end of file
c57b480e7b7f93c8808bfcd0bd9735e0cb774e26
<ide><path>utils/modularize.js <ide> function convert( path, ignoreList ) { <ide> <ide> var keys = Object.keys( dependencies ).sort().map( value => '\n\t' + value ).toString(); <ide> var imports = `import {${keys}\n} from "../../../build/three.module.js";`; <del> var exports = `export { ${className} };`; <add> var exports = `export { ${className} };\n`; <ide> <ide> var output = contents.replace( '_IMPORTS_', imports ) + '\n' + exports; <ide>
1
Python
Python
improve the return value
aeafa0c28c611bb12efd1fa1c00fe035f9ded23f
<ide><path>libcloud/compute/drivers/hostvirtual.py <ide> def reboot_node(self, node): <ide> API_ROOT + '/cloud/server/reboot', <ide> data=json.dumps(params), <ide> method='POST').object <del> if result: <del> return True <add> <add> return bool(result) <ide> <ide> def destroy_node(self, node): <ide> params = {'mbpkgid': node.id} <ide> result = self.connection.request( <ide> API_ROOT + '/cloud/cancel', data=json.dumps(params), <ide> method='POST').object <del> if result: <del> return True <add> <add> return bool(result) <ide> <ide> def ex_stop_node(self, node): <ide> params = {'force': 0, 'mbpkgid': node.id} <ide> result = self.connection.request( <ide> API_ROOT + '/cloud/server/stop', <ide> data=json.dumps(params), <ide> method='POST').object <del> if result: <del> return True <add> <add> return bool(result) <ide> <ide> def ex_start_node(self, node): <ide> params = {'mbpkgid': node.id} <ide> result = self.connection.request( <ide> API_ROOT + '/cloud/server/start', <ide> data=json.dumps(params), <ide> method='POST').object <del> if result: <del> return True <add> <add> return bool(result)
1
Javascript
Javascript
remove unnecessary subscriptions
5bd24d9e0581cf50dce575ba169bc18c1d7c530e
<ide><path>src/workspace.js <ide> module.exports = class Workspace extends Model { <ide> deserializerManager: this.deserializerManager, <ide> viewRegistry: this.viewRegistry <ide> }) <del> this.paneContainer.onDidDestroyPaneItem(this.didDestroyPaneItem) <ide> <ide> this.defaultDirectorySearcher = new DefaultDirectorySearcher() <ide> this.consumeServices(this.packageManager) <ide> module.exports = class Workspace extends Model { <ide> didChangeActivePaneItem: this.didChangeActivePaneItemOnPaneContainer, <ide> didDestroyPaneItem: this.didDestroyPaneItem <ide> }) <del> dock.onDidDestroyPaneItem(this.didDestroyPaneItem) <ide> return dock <ide> } <ide>
1
PHP
PHP
add rough implementation of mocked responses
bbdd7f9d63f6c9fce25aac5f2b2a969f1d827b81
<ide><path>src/Http/Client.php <ide> use Cake\Core\InstanceConfigTrait; <ide> use Cake\Http\Client\Adapter\Curl; <ide> use Cake\Http\Client\Adapter\Stream; <add>use Cake\Http\Client\Adapter\Mock as MockAdapter; <ide> use Cake\Http\Client\AdapterInterface; <ide> use Cake\Http\Client\Request; <ide> use Cake\Http\Client\Response; <ide> class Client implements ClientInterface <ide> */ <ide> protected $_cookies; <ide> <add> /** <add> * Mock adapter for stubbing requests in tests. <add> * <add> * @var \Cake\Http\Client\Adapter\Mock <add> */ <add> protected static $_mockAdapter; <add> <ide> /** <ide> * Adapter for sending requests. <ide> * <ide> public function send(RequestInterface $request, array $options = []): Response <ide> return $response; <ide> } <ide> <add> /** <add> * Add a mocked response. <add> * <add> * Mocked responses are stored in an adapter that is called <add> * _before_ the network adapter is called. <add> * <add> * ### Matching Requests <add> * <add> * TODO finish this. <add> * <add> * ### Options <add> * <add> * - `match` An additional closure to match requests with. <add> * <add> * @param string $method The HTTP method being mocked. <add> * @param string $url The URL being matched. See above for examples. <add> * @param \Cake\Http\Client\Response $response The response that matches the request. <add> * @param array $options See above. <add> * @return void <add> */ <add> public static function addMockResponse(string $method, string $url, Response $response, array $options = []): void <add> { <add> if (!static::$_mockAdapter) { <add> static::$_mockAdapter = new MockAdapter(); <add> } <add> $request = new Request($url, $method); <add> static::$_mockAdapter->addResponse($request, $response, $options); <add> } <add> <ide> /** <ide> * Send a request without redirection. <ide> * <ide> public function send(RequestInterface $request, array $options = []): Response <ide> */ <ide> protected function _sendRequest(RequestInterface $request, array $options): Response <ide> { <del> $responses = $this->_adapter->send($request, $options); <add> if (static::$_mockAdapter) { <add> $responses = static::$_mockAdapter->send($request, $options); <add> } <add> if (empty($responses)) { <add> $responses = $this->_adapter->send($request, $options); <add> } <ide> foreach ($responses as $response) { <ide> $this->_cookies = $this->_cookies->addFromResponse($response, $request); <ide> } <ide><path>src/Http/Client/Adapter/Mock.php <add><?php <add>declare(strict_types=1); <add> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.3.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Http\Client\Adapter; <add> <add>use Cake\Http\Client\AdapterInterface; <add>use Cake\Http\Client\Response; <add>use InvalidArgumentException; <add>use Psr\Http\Message\RequestInterface; <add> <add>/** <add> * Implements sending requests to an array of stubbed responses <add> * <add> * This adapter is not intended for production use. Instead <add> * it is the backend used by `Client::addMockResponse()` <add> */ <add>class Mock implements AdapterInterface <add>{ <add> /** <add> * List of mocked responses. <add> * <add> * @var array <add> */ <add> protected $responses = []; <add> <add> /** <add> * Add a mocked response. <add> * <add> * ### Options <add> * <add> * - `match` An additional closure to match requests with. <add> * <add> * @param \Psr\Http\Message\RequestInterface $request A partial request to use for matching. <add> * @param \Cake\Http\Client\Response $response The response that matches the request. <add> * @param array $options See above. <add> * @return void <add> */ <add> public function addResponse(RequestInterface $request, Response $response, array $options): void <add> { <add> if (isset($mock['options']['match']) && !is_callable($mock['options']['match'])) { <add> throw new InvalidArgumentException('The `match` option must be a callable'); <add> } <add> $this->responses[] = [ <add> 'request' => $request, <add> 'response' => $response, <add> 'options' => $options, <add> ]; <add> } <add> <add> /** <add> * Find a response if one exists. <add> * <add> * @param \Psr\Http\Message\RequestInterface $request The request to match <add> * @param array $options Unused. <add> * @return \Cake\Http\Client\Response[] The matched response or an empty array for no matches. <add> */ <add> public function send(RequestInterface $request, array $options): array <add> { <add> $found = null; <add> foreach ($this->responses as $mock) { <add> if ($request->getMethod() !== $mock['request']->getMethod()) { <add> continue; <add> } <add> if (!$this->urlMatches($request, $mock['request'])) { <add> continue; <add> } <add> if (isset($mock['options']['match'])) { <add> $match = $mock['options']['match']($request); <add> if (!is_bool($match)) { <add> throw new InvalidArgumentException('Match callback return a non-boolean value.'); <add> } <add> if (!$match) { <add> continue; <add> } <add> } <add> $found = $mock['response']; <add> break; <add> } <add> <add> return $found ? [$found] : []; <add> } <add> <add> /** <add> * Check if the request URI matches the mock URI. <add> * <add> * @param \Psr\Http\Message\RequestInterface $request The request being sent. <add> * @param \Psr\Http\Message\RequestInterface $mock The request being mocked. <add> * @return bool <add> */ <add> protected function urlMatches(RequestInterface $request, RequestInterface $mock): bool <add> { <add> $requestUri = (string)$request->getUri(); <add> $mockUri = (string)$mock->getUri(); <add> if ($requestUri === $mockUri) { <add> return true; <add> } <add> $starPosition = strrpos($mockUri, '/%2A'); <add> if ($starPosition === strlen($mockUri) - 4) { <add> $mockUri = substr($mockUri, 0, $starPosition); <add> <add> return strpos($requestUri, $mockUri) === 0; <add> } <add> <add> return false; <add> } <add>} <ide><path>tests/TestCase/Http/ClientTest.php <ide> public function testCreateFromUrlOnlySetSchemePortHostBasePath(): void <ide> ]; <ide> $this->assertSame($expected, $config); <ide> } <add> <add> /** <add> * Test adding and sending to a mocked URL. <add> */ <add> public function testAddMockResponseSimpleMatch(): void <add> { <add> $stub = new Response(['HTTP/1.0 200'], 'hello world'); <add> Client::addMockResponse('POST', 'http://example.com/path', $stub); <add> <add> $client = new Client(); <add> $response = $client->post('http://example.com/path'); <add> $this->assertSame($stub, $response); <add> } <add> <add> /** <add> * Test adding and sending to a mocked URL. <add> */ <add> public function testAddMockResponseMethodMatchFailure(): void <add> { <add> $stub = new Response(['HTTP/1.0 200'], 'hello world'); <add> Client::addMockResponse('POST', 'http://example.com/path', $stub); <add> <add> $mock = $this->getMockBuilder(Stream::class) <add> ->onlyMethods(['send']) <add> ->getMock(); <add> $mock->expects($this->once()) <add> ->method('send') <add> ->will($this->throwException(new InvalidArgumentException('No match'))); <add> <add> $client = new Client(['adapter' => $mock]); <add> $this->expectException(InvalidArgumentException::class); <add> $client->get('http://example.com/path'); <add> } <add> <add> /** <add> * Test adding and sending to a mocked URL. <add> */ <add> public function testAddMockResponseGlobMatch(): void <add> { <add> $stub = new Response(['HTTP/1.0 200'], 'hello world'); <add> Client::addMockResponse('POST', 'http://example.com/path/*', $stub); <add> <add> $client = new Client(); <add> $response = $client->post('http://example.com/path/more/thing'); <add> $this->assertSame($stub, $response); <add> <add> $client = new Client(); <add> $response = $client->post('http://example.com/path/?query=value'); <add> $this->assertSame($stub, $response); <add> } <ide> }
3
PHP
PHP
adapt assertredirectnotcontains to use constraints
de8c639ed569e565b3fcc43a9d32e35fff88ee57
<ide><path>src/TestSuite/IntegrationTestTrait.php <ide> use Cake\TestSuite\Constraint\Response\FileSentAs; <ide> use Cake\TestSuite\Constraint\Response\HeaderContains; <ide> use Cake\TestSuite\Constraint\Response\HeaderEquals; <add>use Cake\TestSuite\Constraint\Response\HeaderNotContains; <ide> use Cake\TestSuite\Constraint\Response\HeaderNotSet; <ide> use Cake\TestSuite\Constraint\Response\HeaderSet; <ide> use Cake\TestSuite\Constraint\Response\StatusCode; <ide> public function assertRedirectContains($url, $message = '') <ide> */ <ide> public function assertRedirectNotContains($url, $message = '') <ide> { <del> if (!$this->_response) { <del> $this->fail('No response set, cannot assert location header. ' . $message); <del> } <del> $result = $this->_response->header(); <del> if (empty($result['Location'])) { <del> $this->fail('No location header set. ' . $message); <del> } <del> $this->assertNotContains($url, $result['Location'], $message); <add> $this->assertThat(null, new HeaderSet($this->_response, 'Location'), $message); <add> $this->assertThat(null, new HeaderNotContains($this->_response, 'Location'), $message); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/TestSuite/IntegrationTestTraitTest.php <ide> public function testAssertRedirect() <ide> public function testAssertRedirectNotContains() <ide> { <ide> $this->_response = new Response(); <del> $this->_response->header('Location', 'http://localhost/tasks/index'); <add> $this->_response = $this->_response->withHeader('Location', 'http://localhost/tasks/index'); <ide> $this->assertRedirectNotContains('test'); <ide> } <ide>
2
Go
Go
fix a typo
1d61f11e34ba6f1efdfd29a03d92181586bdcb93
<ide><path>cli/command/registry/search.go <ide> func NewSearchCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> flags.BoolVar(&opts.automated, "automated", false, "Only show automated builds") <ide> flags.UintVarP(&opts.stars, "stars", "s", 0, "Only displays with at least x stars") <ide> <del> flags.MarkDeprecated("automated", "use --filter=automated=true instead") <add> flags.MarkDeprecated("automated", "use --filter=is-automated=true instead") <ide> flags.MarkDeprecated("stars", "use --filter=stars=3 instead") <ide> <ide> return cmd
1
Javascript
Javascript
remove raf export from reactdomframescheduling
372445735eda4d7960419947c49499019adb79db
<ide><path>src/renderers/shared/ReactDOMFrameScheduling.js <ide> import type {Deadline} from 'ReactFiberReconciler'; <ide> var invariant = require('fbjs/lib/invariant'); <ide> var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment'); <ide> <del>// TODO: There's no way to cancel these, because Fiber doesn't atm. <del>let rAF: (callback: (time: number) => void) => number; <add>// TODO: There's no way to cancel, because Fiber doesn't atm. <ide> let rIC: (callback: (deadline: Deadline) => void) => number; <ide> <ide> if (!ExecutionEnvironment.canUseDOM) { <del> rAF = function(frameCallback: (time: number) => void): number { <del> setTimeout(frameCallback, 16); <del> return 0; <del> }; <del> <ide> rIC = function(frameCallback: (deadline: Deadline) => void): number { <ide> setTimeout(() => { <ide> frameCallback({ <ide> if (!ExecutionEnvironment.canUseDOM) { <ide> 'polyfill in older browsers.', <ide> ); <ide> } else if (typeof requestIdleCallback !== 'function') { <del> // Wrap requestAnimationFrame and polyfill requestIdleCallback. <add> // Polyfill requestIdleCallback. <ide> <ide> var scheduledRAFCallback = null; <ide> var scheduledRICCallback = null; <ide> if (!ExecutionEnvironment.canUseDOM) { <ide> isIdleScheduled = false; <ide> var callback = scheduledRICCallback; <ide> scheduledRICCallback = null; <del> if (callback) { <add> if (callback !== null) { <ide> callback(frameDeadlineObject); <ide> } <ide> }; <ide> if (!ExecutionEnvironment.canUseDOM) { <ide> } <ide> var callback = scheduledRAFCallback; <ide> scheduledRAFCallback = null; <del> if (callback) { <add> if (callback !== null) { <ide> callback(rafTime); <ide> } <ide> }; <ide> <del> rAF = function(callback: (time: number) => void): number { <del> // This assumes that we only schedule one callback at a time because that's <del> // how Fiber uses it. <del> scheduledRAFCallback = callback; <del> if (!isAnimationFrameScheduled) { <del> // If rIC didn't already schedule one, we need to schedule a frame. <del> isAnimationFrameScheduled = true; <del> requestAnimationFrame(animationTick); <del> } <del> return 0; <del> }; <del> <ide> rIC = function(callback: (deadline: Deadline) => void): number { <ide> // This assumes that we only schedule one callback at a time because that's <ide> // how Fiber uses it. <ide> if (!ExecutionEnvironment.canUseDOM) { <ide> return 0; <ide> }; <ide> } else { <del> rAF = requestAnimationFrame; <ide> rIC = requestIdleCallback; <ide> } <ide> <del>exports.rAF = rAF; <ide> exports.rIC = rIC;
1
Python
Python
add int_shape to theano backend
766572b5b8c0617e1261809f1916d29bb770a769
<ide><path>keras/backend/theano_backend.py <ide> def to_dense(tensor): <ide> <ide> <ide> def variable(value, dtype=None, name=None): <del> '''Instantiates a variable. <add> '''Instantiates a variable and returns it. <add> <add> # Arguments <add> value: Numpy array, initial value of the tensor. <add> dtype: Tensor type. <add> name: Optional name string for the tensor. <add> <add> # Returns <add> A variable instance (with Keras metadata included). <ide> ''' <ide> if dtype is None: <ide> dtype = floatx() <ide> if hasattr(value, 'tocoo'): <ide> _assert_sparse_module() <del> return th_sparse_module.as_sparse_variable(value) <add> variable = th_sparse_module.as_sparse_variable(value) <ide> else: <ide> value = np.asarray(value, dtype=dtype) <del> return theano.shared(value=value, name=name, strict=False) <add> variable = theano.shared(value=value, name=name, strict=False) <add> variable._keras_shape = value.shape <add> variable._uses_learning_phase = False <add> return variable <ide> <ide> <ide> def placeholder(shape=None, ndim=None, dtype=None, sparse=False, name=None): <ide> def shape(x): <ide> return x.shape <ide> <ide> <add>def int_shape(x): <add> '''Returns the shape of a Keras tensor or a Keras variable as a tuple of <add> integers or None entries. <add> <add> # Arguments <add> x: Tensor or variable. <add> <add> # Returns <add> A tuple of integers (or None entries). <add> ''' <add> if hasattr(x, '_keras_shape'): <add> return x._keras_shape <add> else: <add> raise Exception('Not a Keras tensor:', x) <add> <add> <ide> def ndim(x): <ide> return x.ndim <ide>
1
Python
Python
add speed benchmarks to metadata
0f41b25f60d1681edbb2ab74d4e23ccd45516b61
<ide><path>spacy/cli/train.py <ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=10, n_sents=0, <ide> nlp.to_disk(epoch_model_path) <ide> nlp_loaded = lang_class(pipeline=pipeline) <ide> nlp_loaded = nlp_loaded.from_disk(epoch_model_path) <del> scorer = nlp_loaded.evaluate( <del> list(corpus.dev_docs( <add> dev_docs = list(corpus.dev_docs( <ide> nlp_loaded, <del> gold_preproc=gold_preproc))) <add> gold_preproc=gold_preproc)) <add> nwords = sum(len(doc_gold[0]) for doc_gold in dev_docs) <add> start_time = timer() <add> scorer = nlp_loaded.evaluate(dev_docs) <add> end_time = timer() <add> if use_gpu < 0: <add> gpu_wps = None <add> cpu_wps = nwords/(end_time-start_time) <add> else: <add> gpu_wps = nwords/(end_time-start_time) <add> with Model.use_device('cpu'): <add> nlp_loaded = lang_class(pipeline=pipeline) <add> nlp_loaded = nlp_loaded.from_disk(epoch_model_path) <add> dev_docs = list(corpus.dev_docs( <add> nlp_loaded, gold_preproc=gold_preproc)) <add> start_time = timer() <add> scorer = nlp_loaded.evaluate(dev_docs) <add> end_time = timer() <add> cpu_wps = nwords/(end_time-start_time) <ide> acc_loc =(output_path / ('model%d' % i) / 'accuracy.json') <ide> with acc_loc.open('w') as file_: <ide> file_.write(json_dumps(scorer.scores)) <ide> meta_loc = output_path / ('model%d' % i) / 'meta.json' <ide> meta['accuracy'] = scorer.scores <add> meta['speed'] = {'nwords': nwords, 'cpu':cpu_wps, 'gpu': gpu_wps} <ide> meta['lang'] = nlp.lang <ide> meta['pipeline'] = pipeline <ide> meta['spacy_version'] = '>=%s' % about.__version__ <ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=10, n_sents=0, <ide> with meta_loc.open('w') as file_: <ide> file_.write(json_dumps(meta)) <ide> util.set_env_log(True) <del> print_progress(i, losses, scorer.scores) <add> print_progress(i, losses, scorer.scores, cpu_wps=cpu_wps, gpu_wps=gpu_wps) <ide> finally: <ide> print("Saving model...") <ide> try: <ide> def _render_parses(i, to_render): <ide> file_.write(html) <ide> <ide> <del>def print_progress(itn, losses, dev_scores, wps=0.0): <add>def print_progress(itn, losses, dev_scores, cpu_wps=0.0, gpu_wps=0.0): <add> print(locals()) <ide> scores = {} <ide> for col in ['dep_loss', 'tag_loss', 'uas', 'tags_acc', 'token_acc', <del> 'ents_p', 'ents_r', 'ents_f', 'wps']: <add> 'ents_p', 'ents_r', 'ents_f', 'cpu_wps', 'gpu_wps']: <ide> scores[col] = 0.0 <ide> scores['dep_loss'] = losses.get('parser', 0.0) <ide> scores['ner_loss'] = losses.get('ner', 0.0) <ide> scores['tag_loss'] = losses.get('tagger', 0.0) <ide> scores.update(dev_scores) <del> scores['wps'] = wps <add> scores['cpu_wps'] = cpu_wps <add> scores['gpu_wps'] = gpu_wps or 0.0 <ide> tpl = '\t'.join(( <ide> '{:d}', <ide> '{dep_loss:.3f}', <ide> def print_progress(itn, losses, dev_scores, wps=0.0): <ide> '{ents_f:.3f}', <ide> '{tags_acc:.3f}', <ide> '{token_acc:.3f}', <del> '{wps:.1f}')) <add> '{cpu_wps:.1f}', <add> '{gpu_wps:.1f}', <add> )) <ide> print(tpl.format(itn, **scores)) <ide> <ide>
1
Javascript
Javascript
replace symbol.species by symbolspecies
437b6d5d4fb00c40575e03fd040c8a663e9cc7b1
<ide><path>lib/buffer.js <ide> const { <ide> ObjectDefineProperties, <ide> ObjectDefineProperty, <ide> ObjectSetPrototypeOf, <del> Symbol, <add> SymbolSpecies, <ide> SymbolToPrimitive, <ide> } = primordials; <ide> <ide> function Buffer(arg, encodingOrOffset, length) { <ide> return Buffer.from(arg, encodingOrOffset, length); <ide> } <ide> <del>ObjectDefineProperty(Buffer, Symbol.species, { <add>ObjectDefineProperty(Buffer, SymbolSpecies, { <ide> enumerable: false, <ide> configurable: true, <ide> get() { return FastBuffer; }
1
Java
Java
fix checkbox casting crash in old android versions
58437cd10a667bbcbc16781df855fd7c3d73bf49
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/checkbox/ReactCheckBoxManager.java <ide> */ <ide> package com.facebook.react.views.checkbox; <ide> <add>import android.content.Context; <add>import android.support.v7.widget.TintContextWrapper; <ide> import android.widget.CompoundButton; <ide> import com.facebook.react.bridge.ReactContext; <ide> import com.facebook.react.uimanager.SimpleViewManager; <ide> import com.facebook.react.uimanager.ThemedReactContext; <ide> import com.facebook.react.uimanager.UIManagerModule; <ide> import com.facebook.react.uimanager.ViewProps; <ide> import com.facebook.react.uimanager.annotations.ReactProp; <del>import com.facebook.react.uimanager.events.EventDispatcher; <ide> <ide> /** View manager for {@link ReactCheckBox} components. */ <ide> public class ReactCheckBoxManager extends SimpleViewManager<ReactCheckBox> { <ide> public class ReactCheckBoxManager extends SimpleViewManager<ReactCheckBox> { <ide> new CompoundButton.OnCheckedChangeListener() { <ide> @Override <ide> public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { <del> ReactContext reactContext = (ReactContext) buttonView.getContext(); <add> ReactContext reactContext = getReactContext(buttonView); <ide> reactContext <ide> .getNativeModule(UIManagerModule.class).getEventDispatcher() <ide> .dispatchEvent(new ReactCheckBoxEvent(buttonView.getId(), isChecked)); <ide> } <add> <add> private ReactContext getReactContext(CompoundButton buttonView) { <add> ReactContext reactContext; <add> Context ctx = buttonView.getContext(); <add> if (ctx instanceof TintContextWrapper) { <add> reactContext = (ReactContext) ((TintContextWrapper) ctx).getBaseContext(); <add> } else { <add> reactContext = (ReactContext) buttonView.getContext(); <add> } <add> return reactContext; <add> } <ide> }; <ide> <ide> @Override
1
Python
Python
add rankine scale
99b40e2a267045a7e3d69acc338b85c525f51eda
<ide><path>conversions/temperature_conversions.py <ide> """ Convert between different units of temperature """ <ide> <ide> <del>def celsius_to_fahrenheit(celsius: float) -> float: <add>def celsius_to_fahrenheit(celsius: float, ndigits: int = 2) -> float: <ide> """ <ide> Convert a given value from Celsius to Fahrenheit and round it to 2 decimal places. <add> Wikipedia reference: https://en.wikipedia.org/wiki/Celsius <add> Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit <ide> <ide> >>> celsius_to_fahrenheit(-40.0) <ide> -40.0 <ide> def celsius_to_fahrenheit(celsius: float) -> float: <ide> ... <ide> ValueError: could not convert string to float: 'celsius' <ide> """ <del> return round((float(celsius) * 9 / 5) + 32, 2) <add> return round((float(celsius) * 9 / 5) + 32, ndigits) <ide> <ide> <del>def fahrenheit_to_celsius(fahrenheit: float) -> float: <add>def celsius_to_kelvin(celsius: float, ndigits: int = 2) -> float: <add> """ <add> Convert a given value from Celsius to Kelvin and round it to 2 decimal places. <add> Wikipedia reference: https://en.wikipedia.org/wiki/Celsius <add> Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin <add> <add> >>> celsius_to_kelvin(0) <add> 273.15 <add> >>> celsius_to_kelvin(20.0) <add> 293.15 <add> >>> celsius_to_kelvin("40") <add> 313.15 <add> >>> celsius_to_kelvin("celsius") <add> Traceback (most recent call last): <add> ... <add> ValueError: could not convert string to float: 'celsius' <add> """ <add> return round(float(celsius) + 273.15, ndigits) <add> <add> <add>def celsius_to_rankine(celsius: float, ndigits: int = 2) -> float: <add> """ <add> Convert a given value from Celsius to Rankine and round it to 2 decimal places. <add> Wikipedia reference: https://en.wikipedia.org/wiki/Celsius <add> Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale <add> <add> >>> celsius_to_rankine(0) <add> 491.67 <add> >>> celsius_to_rankine(20.0) <add> 527.67 <add> >>> celsius_to_rankine("40") <add> 563.67 <add> >>> celsius_to_rankine("celsius") <add> Traceback (most recent call last): <add> ... <add> ValueError: could not convert string to float: 'celsius' <add> """ <add> return round((float(celsius) * 9 / 5) + 491.67, ndigits) <add> <add> <add>def fahrenheit_to_celsius(fahrenheit: float, ndigits: int = 2) -> float: <ide> """ <ide> Convert a given value from Fahrenheit to Celsius and round it to 2 decimal places. <add> Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit <add> Wikipedia reference: https://en.wikipedia.org/wiki/Celsius <ide> <ide> >>> fahrenheit_to_celsius(0) <ide> -17.78 <ide> def fahrenheit_to_celsius(fahrenheit: float) -> float: <ide> ... <ide> ValueError: could not convert string to float: 'fahrenheit' <ide> """ <del> return round((float(fahrenheit) - 32) * 5 / 9, 2) <add> return round((float(fahrenheit) - 32) * 5 / 9, ndigits) <ide> <ide> <del>def celsius_to_kelvin(celsius: float) -> float: <add>def fahrenheit_to_kelvin(fahrenheit: float, ndigits: int = 2) -> float: <ide> """ <del> Convert a given value from Celsius to Kelvin and round it to 2 decimal places. <add> Convert a given value from Fahrenheit to Kelvin and round it to 2 decimal places. <add> Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit <add> Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin <ide> <del> >>> celsius_to_kelvin(0) <del> 273.15 <del> >>> celsius_to_kelvin(20.0) <del> 293.15 <del> >>> celsius_to_kelvin("40") <del> 313.15 <del> >>> celsius_to_kelvin("celsius") <add> >>> fahrenheit_to_kelvin(0) <add> 255.37 <add> >>> fahrenheit_to_kelvin(20.0) <add> 266.48 <add> >>> fahrenheit_to_kelvin(40.0) <add> 277.59 <add> >>> fahrenheit_to_kelvin(60) <add> 288.71 <add> >>> fahrenheit_to_kelvin(80) <add> 299.82 <add> >>> fahrenheit_to_kelvin("100") <add> 310.93 <add> >>> fahrenheit_to_kelvin("fahrenheit") <ide> Traceback (most recent call last): <ide> ... <del> ValueError: could not convert string to float: 'celsius' <add> ValueError: could not convert string to float: 'fahrenheit' <add> """ <add> return round(((float(fahrenheit) - 32) * 5 / 9) + 273.15, ndigits) <add> <add> <add>def fahrenheit_to_rankine(fahrenheit: float, ndigits: int = 2) -> float: <add> """ <add> Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places. <add> Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit <add> Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale <add> <add> >>> fahrenheit_to_rankine(0) <add> 459.67 <add> >>> fahrenheit_to_rankine(20.0) <add> 479.67 <add> >>> fahrenheit_to_rankine(40.0) <add> 499.67 <add> >>> fahrenheit_to_rankine(60) <add> 519.67 <add> >>> fahrenheit_to_rankine(80) <add> 539.67 <add> >>> fahrenheit_to_rankine("100") <add> 559.67 <add> >>> fahrenheit_to_rankine("fahrenheit") <add> Traceback (most recent call last): <add> ... <add> ValueError: could not convert string to float: 'fahrenheit' <ide> """ <del> return round(float(celsius) + 273.15, 2) <add> return round(float(fahrenheit) + 459.67, ndigits) <ide> <ide> <del>def kelvin_to_celsius(kelvin: float) -> float: <add>def kelvin_to_celsius(kelvin: float, ndigits: int = 2) -> float: <ide> """ <ide> Convert a given value from Kelvin to Celsius and round it to 2 decimal places. <add> Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin <add> Wikipedia reference: https://en.wikipedia.org/wiki/Celsius <ide> <ide> >>> kelvin_to_celsius(273.15) <ide> 0.0 <ide> def kelvin_to_celsius(kelvin: float) -> float: <ide> ... <ide> ValueError: could not convert string to float: 'kelvin' <ide> """ <del> return round(float(kelvin) - 273.15, 2) <add> return round(float(kelvin) - 273.15, ndigits) <add> <add> <add>def kelvin_to_fahrenheit(kelvin: float, ndigits: int = 2) -> float: <add> """ <add> Convert a given value from Kelvin to Fahrenheit and round it to 2 decimal places. <add> Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin <add> Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit <add> <add> >>> kelvin_to_fahrenheit(273.15) <add> 32.0 <add> >>> kelvin_to_fahrenheit(300) <add> 80.33 <add> >>> kelvin_to_fahrenheit("315.5") <add> 108.23 <add> >>> kelvin_to_fahrenheit("kelvin") <add> Traceback (most recent call last): <add> ... <add> ValueError: could not convert string to float: 'kelvin' <add> """ <add> return round(((float(kelvin) - 273.15) * 9 / 5) + 32, ndigits) <add> <add> <add>def kelvin_to_rankine(kelvin: float, ndigits: int = 2) -> float: <add> """ <add> Convert a given value from Kelvin to Rankine and round it to 2 decimal places. <add> Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin <add> Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale <add> <add> >>> kelvin_to_rankine(0) <add> 0.0 <add> >>> kelvin_to_rankine(20.0) <add> 36.0 <add> >>> kelvin_to_rankine("40") <add> 72.0 <add> >>> kelvin_to_rankine("kelvin") <add> Traceback (most recent call last): <add> ... <add> ValueError: could not convert string to float: 'kelvin' <add> """ <add> return round((float(kelvin) * 9 / 5), ndigits) <add> <add> <add>def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float: <add> """ <add> Convert a given value from Rankine to Celsius and round it to 2 decimal places. <add> Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale <add> Wikipedia reference: https://en.wikipedia.org/wiki/Celsius <add> <add> >>> rankine_to_celsius(273.15) <add> -121.4 <add> >>> rankine_to_celsius(300) <add> -106.48 <add> >>> rankine_to_celsius("315.5") <add> -97.87 <add> >>> rankine_to_celsius("rankine") <add> Traceback (most recent call last): <add> ... <add> ValueError: could not convert string to float: 'rankine' <add> """ <add> return round((float(rankine) - 491.67) * 5 / 9, ndigits) <add> <add> <add>def rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float: <add> """ <add> Convert a given value from Rankine to Fahrenheit and round it to 2 decimal places. <add> Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale <add> Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit <add> <add> >>> rankine_to_fahrenheit(273.15) <add> -186.52 <add> >>> rankine_to_fahrenheit(300) <add> -159.67 <add> >>> rankine_to_fahrenheit("315.5") <add> -144.17 <add> >>> rankine_to_fahrenheit("rankine") <add> Traceback (most recent call last): <add> ... <add> ValueError: could not convert string to float: 'rankine' <add> """ <add> return round(float(rankine) - 459.67, ndigits) <add> <add> <add>def rankine_to_kelvin(rankine: float, ndigits: int = 2) -> float: <add> """ <add> Convert a given value from Rankine to Kelvin and round it to 2 decimal places. <add> Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale <add> Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin <add> <add> >>> rankine_to_kelvin(0) <add> 0.0 <add> >>> rankine_to_kelvin(20.0) <add> 11.11 <add> >>> rankine_to_kelvin("40") <add> 22.22 <add> >>> rankine_to_kelvin("rankine") <add> Traceback (most recent call last): <add> ... <add> ValueError: could not convert string to float: 'rankine' <add> """ <add> return round((float(rankine) * 5 / 9), ndigits) <ide> <ide> <ide> if __name__ == "__main__": <add> <ide> import doctest <add> <ide> doctest.testmod()
1
PHP
PHP
fix psalm errors
b72f27a962b4fd04ff0e2b36eb4d1685567f2620
<ide><path>src/View/Exception/MissingTemplateException.php <ide> class MissingTemplateException extends CakeException <ide> { <ide> /** <del> * @var string <add> * @var string|null <ide> */ <ide> protected $templateName; <ide> <ide> public function __construct($file, array $paths = [], ?int $code = null, ?Throwa <ide> $this->templateName = array_pop($file); <ide> } else { <ide> $this->file = $file; <add> $this->templateName = null; <ide> } <ide> $this->paths = $paths; <ide>
1
Javascript
Javascript
fix return value in reject code example
ed2fe07eac1f94efd5e849233ceeeba95776c9b3
<ide><path>packages/@ember/-internals/runtime/lib/mixins/array.js <ide> const ArrayMixin = Mixin.create(Enumerable, { <ide> ]; <ide> const nonFruits = food.reject(function(thing) { <ide> return thing.isFruit; <del> }); // [{food: 'beans', isFruit: false}] <add> }); // [{food: 'bread', isFruit: false}] <ide> ``` <ide> <ide> @method reject
1
Text
Text
update bibtex entry
8fc5b90e9a8c6d6fcedf35bad1c6692e40c92f74
<ide><path>docs/templates/getting-started/faq.md <ide> Please cite Keras in your publications if it helps your research. Here is an exa <ide> <ide> ``` <ide> @misc{chollet2015keras, <del> author = {Chollet, Francois}, <del> title = {Keras}, <del> year = {2015}, <del> publisher = {GitHub}, <del> journal = {GitHub repository}, <del> howpublished = {\url{https://github.com/fchollet/keras}} <add> title={Keras}, <add> author={Chollet, Fran\c{c}ois}, <add> year={2015}, <add> publisher={GitHub}, <add> howpublished={\url{https://github.com/fchollet/keras}}, <ide> } <ide> ``` <ide>
1
Ruby
Ruby
remove specs accessor
460e8055923068b4438de2137f34320fb1173010
<ide><path>Library/Homebrew/formula.rb <ide> def validate_attributes(*attrs) <ide> <ide> def url; active_spec.url; end <ide> def version; active_spec.version; end <del> def specs; active_spec.specs; end <ide> def mirrors; active_spec.mirrors; end <ide> <ide> # if the dir is there, but it's empty we consider it not installed
1
Javascript
Javascript
fix argument order in assertions
6b3b64fa73ea31aa68ffc88f3d61ce4b8317809d
<ide><path>test/pummel/test-net-timeout.js <ide> echo_server.listen(common.PORT, function() { <ide> }); <ide> <ide> client.on('data', function(chunk) { <del> assert.strictEqual('hello\r\n', chunk); <add> assert.strictEqual(chunk, 'hello\r\n'); <ide> if (exchanges++ < 5) { <ide> setTimeout(function() { <ide> console.log('client write "hello"');
1
Javascript
Javascript
remove rtl scraping from preparse
db2d2a837fcd22bb790b591925a6453256fdcfd6
<ide><path>src/locale/ar-ly.js <ide> export default moment.defineLocale('ar-ly', { <ide> yy : pluralize('y') <ide> }, <ide> preparse: function (string) { <del> return string.replace(/\u200f/g, '').replace(/،/g, ','); <add> return string.replace(/،/g, ','); <ide> }, <ide> postformat: function (string) { <ide> return string.replace(/\d/g, function (match) { <ide><path>src/locale/ar.js <ide> export default moment.defineLocale('ar', { <ide> yy : pluralize('y') <ide> }, <ide> preparse: function (string) { <del> return string.replace(/\u200f/g, '').replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) { <add> return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) { <ide> return numberMap[match]; <ide> }).replace(/،/g, ','); <ide> }, <ide> export default moment.defineLocale('ar', { <ide> doy : 12 // The week that contains Jan 1st is the first week of the year. <ide> } <ide> }); <del> <ide><path>src/test/locale/ar-ly.js <ide> test('no leading zeros in long date formats', function (assert) { <ide> } <ide> } <ide> }); <add> <add>// locale-specific <add>test('ar-ly strict mode parsing works', function (assert) { <add> const m = moment().locale('ar-ly'); <add> const formattedDate = m.format('l'); <add> assert.equal(moment.utc(formattedDate, 'l', 'ar-ly', false).isValid(), true, 'Non-strict parsing works'); <add> assert.equal(moment.utc(formattedDate, 'l', 'ar-ly', true).isValid(), true,'Strict parsing must work'); <add>}); <ide><path>src/test/locale/ar.js <ide> test('no leading zeros in long date formats', function (assert) { <ide> } <ide> } <ide> }); <add> <add>// locale-specific <add>test('ar strict mode parsing works', function (assert) { <add> const m = moment().locale('ar'); <add> const formattedDate = m.format('l'); <add> assert.equal(moment.utc(formattedDate, 'l', 'ar', false).isValid(), true, 'Non-strict parsing works'); <add> assert.equal(moment.utc(formattedDate, 'l', 'ar', true).isValid(), true,'Strict parsing must work'); <add>});
4
Text
Text
add rexagod to collaborators
78cd10860818725a1197b34a76e8b8cc81f53326
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Stephen Belanger** &lt;admin@stephenbelanger.com&gt; (he/him) <ide> * [refack](https://github.com/refack) - <ide> **Refael Ackermann (רפאל פלחי)** &lt;refack@gmail.com&gt; (he/him/הוא/אתה) <add>* [rexagod](https://github.com/rexagod) - <add>**Pranshu Srivastava** &lt;rexagod@gmail.com&gt; (he/him) <ide> * [richardlau](https://github.com/richardlau) - <ide> **Richard Lau** &lt;riclau@uk.ibm.com&gt; <ide> * [ronag](https://github.com/ronag) -
1
Javascript
Javascript
remove duplicate "required" export
ef2e3fdd3ec46506d29c70fecf00d508351a873d
<ide><path>packages/ember-metal/lib/mixin.js <ide> export function _beforeObserver(...args) { <ide> <ide> export { <ide> Mixin, <del> required, <ide> REQUIRED <ide> };
1
Javascript
Javascript
fix unit tests in open source environment
d3f2081d9091179ed0ac6511c6c660947b950e45
<ide><path>Libraries/Animated/src/Interpolation.js <ide> /* eslint no-bitwise: 0 */ <ide> 'use strict'; <ide> <add>var invariant = require('fbjs/lib/invariant'); <ide> var normalizeColor = require('normalizeColor'); <ide> <del>// TODO(#7644673): fix this hack once github jest actually checks invariants <del>var invariant = function(condition, message) { <del> if (!condition) { <del> var error = new Error(message); <del> (error: any).framesToPop = 1; // $FlowIssue <del> throw error; <del> } <del>}; <del> <ide> type ExtrapolateType = 'extend' | 'identity' | 'clamp'; <ide> <ide> export type InterpolationConfigType = { <ide><path>Libraries/vendor/core/Map.js <ide> */ <ide> <ide> var guid = require('guid'); <del>var isNode = require('isNode'); <add>var isNode = require('fbjs/lib/isNode'); <ide> var toIterator = require('toIterator'); <ide> var _shouldPolyfillES6Collection = require('_shouldPolyfillES6Collection'); <ide>
2
Text
Text
fix typo in swc plugin destructuring example
fa1261cbfbc79fa3f6c491a186b18204d6b71847
<ide><path>docs/advanced-features/compiler.md <ide> You can configure swc's transform to use SWC's experimental plugin support writt <ide> module.exports = { <ide> experimental: { <ide> swcPlugins: [ <del> ['plugin', { <del> ..pluginOptions <del> }] <del> ] <del> } <add> [ <add> 'plugin', <add> { <add> ...pluginOptions, <add> }, <add> ], <add> ], <add> }, <ide> } <ide> ``` <ide>
1
Javascript
Javascript
make _cycle reentrant
19b4c27ebf6d0b1aa2ded64d57fa44ec70e8756e
<ide><path>lib/tls.js <ide> CryptoStream.prototype.write = function(data /* , encoding, cb */) { <ide> this._pending.push(data); <ide> this._pendingCallbacks.push(cb); <ide> <add> this.pair._writeCalled = true; <ide> this.pair._cycle(); <add> <ide> return this._writeState; <ide> }; <ide> <ide> SecurePair.prototype._cycle = function() { <ide> return; <ide> } <ide> <add> // Make this function reentrant. <add> if (this._cycleLock) return; <add> this._cycleLock = true; <add> this._writeCalled = false; <add> <ide> var established = this._secureEstablished; <ide> <ide> this.encrypted._pull(); <ide> this.cleartext._pull(); <ide> this.cleartext._push(); <ide> this.encrypted._push(); <ide> <del> if (!established && this._secureEstablished) { <add> this._cycleLock = false; <add> <add> if (this._done) { <add> return; <add> } <add> <add> if ((!established && this._secureEstablished) || this._writeCalled) { <ide> // If we were not established but now we are, let's cycle again. <add> // Or if there is some data to write... <ide> this._cycle(); <ide> } <ide> };
1
Javascript
Javascript
switch ordering of logical and
e2e7fcce7e137e6e6fbc23cfadea1a0abaa0e6ce
<ide><path>packages/react-dom/src/shared/DOMProperty.js <ide> export function shouldSetAttribute(name, value) { <ide> return false; <ide> } <ide> if ( <add> name.length > 2 && <ide> (name[0] === 'o' || name[0] === 'O') && <del> (name[1] === 'n' || name[1] === 'N') && <del> name.length > 2 <add> (name[1] === 'n' || name[1] === 'N') <ide> ) { <ide> return false; <ide> }
1
Go
Go
update windows and lcow to use v1.0.0 runtime-spec
7c29103ad9b4e02ecc6cdde01da9c3675a377fc4
<ide><path>daemon/monitor_windows.go <ide> func (daemon *Daemon) postRunProcessing(container *container.Container, e libcon <ide> return err <ide> } <ide> <del> newOpts := []libcontainerd.CreateOption{&libcontainerd.ServicingOption{ <del> IsServicing: true, <del> }} <add> // Turn on servicing <add> spec.Windows.Servicing = true <ide> <ide> copts, err := daemon.getLibcontainerdCreateOptions(container) <ide> if err != nil { <ide> return err <ide> } <ide> <del> if copts != nil { <del> newOpts = append(newOpts, copts...) <del> } <del> <ide> // Create a new servicing container, which will start, complete the update, and merge back the <ide> // results if it succeeded, all as part of the below function call. <del> if err := daemon.containerd.Create((container.ID + "_servicing"), "", "", *spec, container.InitializeStdio, newOpts...); err != nil { <add> if err := daemon.containerd.Create((container.ID + "_servicing"), "", "", *spec, container.InitializeStdio, copts...); err != nil { <ide> container.SetExitCode(-1) <ide> return fmt.Errorf("Post-run update servicing failed: %s", err) <ide> } <ide><path>daemon/oci_windows.go <ide> package daemon <ide> <ide> import ( <add> "fmt" <add> "io/ioutil" <add> "path/filepath" <add> "strings" <add> <ide> containertypes "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/container" <add> "github.com/docker/docker/layer" <ide> "github.com/docker/docker/oci" <ide> "github.com/docker/docker/pkg/sysinfo" <ide> "github.com/docker/docker/pkg/system" <ide> "github.com/opencontainers/runtime-spec/specs-go" <ide> "golang.org/x/sys/windows" <add> "golang.org/x/sys/windows/registry" <add>) <add> <add>const ( <add> credentialSpecRegistryLocation = `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\Containers\CredentialSpecs` <add> credentialSpecFileLocation = "CredentialSpecs" <ide> ) <ide> <ide> func (daemon *Daemon) createSpec(c *container.Container) (*specs.Spec, error) { <ide> func (daemon *Daemon) createSpec(c *container.Container) (*specs.Spec, error) { <ide> isHyperV = c.HostConfig.Isolation.IsHyperV() <ide> } <ide> <add> if isHyperV { <add> s.Windows.HyperV = &specs.WindowsHyperV{} <add> } <add> <ide> // If the container has not been started, and has configs or secrets <ide> // secrets, create symlinks to each config and secret. If it has been <ide> // started before, the symlinks should have already been created. Also, it <ide> func (daemon *Daemon) createSpec(c *container.Container) (*specs.Spec, error) { <ide> s.Process.Env = c.CreateDaemonEnvironment(c.Config.Tty, linkedEnv) <ide> if c.Config.Tty { <ide> s.Process.Terminal = c.Config.Tty <del> s.Process.ConsoleSize.Height = c.HostConfig.ConsoleSize[0] <del> s.Process.ConsoleSize.Width = c.HostConfig.ConsoleSize[1] <add> s.Process.ConsoleSize = &specs.Box{ <add> Height: c.HostConfig.ConsoleSize[0], <add> Width: c.HostConfig.ConsoleSize[1], <add> } <ide> } <ide> s.Process.User.Username = c.Config.User <ide> <add> // Get the layer path for each layer. <add> max := len(img.RootFS.DiffIDs) <add> for i := 1; i <= max; i++ { <add> img.RootFS.DiffIDs = img.RootFS.DiffIDs[:i] <add> layerPath, err := layer.GetLayerPath(daemon.stores[c.Platform].layerStore, img.RootFS.ChainID()) <add> if err != nil { <add> return nil, fmt.Errorf("failed to get layer path from graphdriver %s for ImageID %s - %s", daemon.stores[c.Platform].layerStore, img.RootFS.ChainID(), err) <add> } <add> // Reverse order, expecting parent most first <add> s.Windows.LayerFolders = append([]string{layerPath}, s.Windows.LayerFolders...) <add> } <add> m, err := c.RWLayer.Metadata() <add> if err != nil { <add> return nil, fmt.Errorf("failed to get layer metadata - %s", err) <add> } <add> s.Windows.LayerFolders = append(s.Windows.LayerFolders, m["dir"]) <add> <add> dnsSearch := daemon.getDNSSearchSettings(c) <add> <add> // Get endpoints for the libnetwork allocated networks to the container <add> var epList []string <add> AllowUnqualifiedDNSQuery := false <add> gwHNSID := "" <add> if c.NetworkSettings != nil { <add> for n := range c.NetworkSettings.Networks { <add> sn, err := daemon.FindNetwork(n) <add> if err != nil { <add> continue <add> } <add> <add> ep, err := c.GetEndpointInNetwork(sn) <add> if err != nil { <add> continue <add> } <add> <add> data, err := ep.DriverInfo() <add> if err != nil { <add> continue <add> } <add> <add> if data["GW_INFO"] != nil { <add> gwInfo := data["GW_INFO"].(map[string]interface{}) <add> if gwInfo["hnsid"] != nil { <add> gwHNSID = gwInfo["hnsid"].(string) <add> } <add> } <add> <add> if data["hnsid"] != nil { <add> epList = append(epList, data["hnsid"].(string)) <add> } <add> <add> if data["AllowUnqualifiedDNSQuery"] != nil { <add> AllowUnqualifiedDNSQuery = true <add> } <add> } <add> } <add> <add> var networkSharedContainerID string <add> if c.HostConfig.NetworkMode.IsContainer() { <add> networkSharedContainerID = c.NetworkSharedContainerID <add> for _, ep := range c.SharedEndpointList { <add> epList = append(epList, ep) <add> } <add> } <add> <add> if gwHNSID != "" { <add> epList = append(epList, gwHNSID) <add> } <add> <add> s.Windows.Network = &specs.WindowsNetwork{ <add> AllowUnqualifiedDNSQuery: AllowUnqualifiedDNSQuery, <add> DNSSearchList: dnsSearch, <add> EndpointList: epList, <add> NetworkSharedContainerName: networkSharedContainerID, <add> } <add> <ide> if img.OS == "windows" { <del> daemon.createSpecWindowsFields(c, &s, isHyperV) <add> if err := daemon.createSpecWindowsFields(c, &s, isHyperV); err != nil { <add> return nil, err <add> } <ide> } else { <ide> // TODO @jhowardmsft LCOW Support. Modify this check when running in dual-mode <ide> if system.LCOWSupported() && img.OS == "linux" { <ide> func (daemon *Daemon) createSpec(c *container.Container) (*specs.Spec, error) { <ide> } <ide> <ide> // Sets the Windows-specific fields of the OCI spec <del>func (daemon *Daemon) createSpecWindowsFields(c *container.Container, s *specs.Spec, isHyperV bool) { <add>func (daemon *Daemon) createSpecWindowsFields(c *container.Container, s *specs.Spec, isHyperV bool) error { <ide> if len(s.Process.Cwd) == 0 { <ide> // We default to C:\ to workaround the oddity of the case that the <ide> // default directory for cmd running as LocalSystem (or <ide> func (daemon *Daemon) createSpecWindowsFields(c *container.Container, s *specs.S <ide> s.Root.Readonly = false // Windows does not support a read-only root filesystem <ide> if !isHyperV { <ide> s.Root.Path = c.BaseFS // This is not set for Hyper-V containers <add> if !strings.HasSuffix(s.Root.Path, `\`) { <add> s.Root.Path = s.Root.Path + `\` // Ensure a correctly formatted volume GUID path \\?\Volume{GUID}\ <add> } <ide> } <ide> <add> // First boot optimization <add> s.Windows.IgnoreFlushesDuringBoot = !c.HasBeenStartedBefore <add> <ide> // In s.Windows.Resources <ide> cpuShares := uint16(c.HostConfig.CPUShares) <ide> cpuMaximum := uint16(c.HostConfig.CPUPercent) * 100 <ide> func (daemon *Daemon) createSpecWindowsFields(c *container.Container, s *specs.S <ide> Iops: &c.HostConfig.IOMaximumIOps, <ide> }, <ide> } <add> <add> // Read and add credentials from the security options if a credential spec has been provided. <add> if c.HostConfig.SecurityOpt != nil { <add> cs := "" <add> for _, sOpt := range c.HostConfig.SecurityOpt { <add> sOpt = strings.ToLower(sOpt) <add> if !strings.Contains(sOpt, "=") { <add> return fmt.Errorf("invalid security option: no equals sign in supplied value %s", sOpt) <add> } <add> var splitsOpt []string <add> splitsOpt = strings.SplitN(sOpt, "=", 2) <add> if len(splitsOpt) != 2 { <add> return fmt.Errorf("invalid security option: %s", sOpt) <add> } <add> if splitsOpt[0] != "credentialspec" { <add> return fmt.Errorf("security option not supported: %s", splitsOpt[0]) <add> } <add> <add> var ( <add> match bool <add> csValue string <add> err error <add> ) <add> if match, csValue = getCredentialSpec("file://", splitsOpt[1]); match { <add> if csValue == "" { <add> return fmt.Errorf("no value supplied for file:// credential spec security option") <add> } <add> if cs, err = readCredentialSpecFile(c.ID, daemon.root, filepath.Clean(csValue)); err != nil { <add> return err <add> } <add> } else if match, csValue = getCredentialSpec("registry://", splitsOpt[1]); match { <add> if csValue == "" { <add> return fmt.Errorf("no value supplied for registry:// credential spec security option") <add> } <add> if cs, err = readCredentialSpecRegistry(c.ID, csValue); err != nil { <add> return err <add> } <add> } else { <add> return fmt.Errorf("invalid credential spec security option - value must be prefixed file:// or registry:// followed by a value") <add> } <add> } <add> s.Windows.CredentialSpec = cs <add> } <add> <add> // Assume we are not starting a container for a servicing operation <add> s.Windows.Servicing = false <add> <add> return nil <ide> } <ide> <ide> // Sets the Linux-specific fields of the OCI spec <ide> func escapeArgs(args []string) []string { <ide> func (daemon *Daemon) mergeUlimits(c *containertypes.HostConfig) { <ide> return <ide> } <add> <add>// getCredentialSpec is a helper function to get the value of a credential spec supplied <add>// on the CLI, stripping the prefix <add>func getCredentialSpec(prefix, value string) (bool, string) { <add> if strings.HasPrefix(value, prefix) { <add> return true, strings.TrimPrefix(value, prefix) <add> } <add> return false, "" <add>} <add> <add>// readCredentialSpecRegistry is a helper function to read a credential spec from <add>// the registry. If not found, we return an empty string and warn in the log. <add>// This allows for staging on machines which do not have the necessary components. <add>func readCredentialSpecRegistry(id, name string) (string, error) { <add> var ( <add> k registry.Key <add> err error <add> val string <add> ) <add> if k, err = registry.OpenKey(registry.LOCAL_MACHINE, credentialSpecRegistryLocation, registry.QUERY_VALUE); err != nil { <add> return "", fmt.Errorf("failed handling spec %q for container %s - %s could not be opened", name, id, credentialSpecRegistryLocation) <add> } <add> if val, _, err = k.GetStringValue(name); err != nil { <add> if err == registry.ErrNotExist { <add> return "", fmt.Errorf("credential spec %q for container %s as it was not found", name, id) <add> } <add> return "", fmt.Errorf("error %v reading credential spec %q from registry for container %s", err, name, id) <add> } <add> return val, nil <add>} <add> <add>// readCredentialSpecFile is a helper function to read a credential spec from <add>// a file. If not found, we return an empty string and warn in the log. <add>// This allows for staging on machines which do not have the necessary components. <add>func readCredentialSpecFile(id, root, location string) (string, error) { <add> if filepath.IsAbs(location) { <add> return "", fmt.Errorf("invalid credential spec - file:// path cannot be absolute") <add> } <add> base := filepath.Join(root, credentialSpecFileLocation) <add> full := filepath.Join(base, location) <add> if !strings.HasPrefix(full, base) { <add> return "", fmt.Errorf("invalid credential spec - file:// path must be under %s", base) <add> } <add> bcontents, err := ioutil.ReadFile(full) <add> if err != nil { <add> return "", fmt.Errorf("credential spec '%s' for container %s as the file could not be read: %q", full, id, err) <add> } <add> return string(bcontents[:]), nil <add>} <ide><path>daemon/start_windows.go <ide> package daemon <ide> <ide> import ( <del> "fmt" <del> "io/ioutil" <del> "path/filepath" <del> "strings" <del> <ide> "github.com/Microsoft/opengcs/client" <ide> "github.com/docker/docker/container" <del> "github.com/docker/docker/layer" <ide> "github.com/docker/docker/libcontainerd" <del> "golang.org/x/sys/windows/registry" <del>) <del> <del>const ( <del> credentialSpecRegistryLocation = `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\Containers\CredentialSpecs` <del> credentialSpecFileLocation = "CredentialSpecs" <ide> ) <ide> <ide> func (daemon *Daemon) getLibcontainerdCreateOptions(container *container.Container) ([]libcontainerd.CreateOption, error) { <ide> createOptions := []libcontainerd.CreateOption{} <ide> <del> // Are we going to run as a Hyper-V container? <del> hvOpts := &libcontainerd.HyperVIsolationOption{} <del> if container.HostConfig.Isolation.IsDefault() { <del> // Container is set to use the default, so take the default from the daemon configuration <del> hvOpts.IsHyperV = daemon.defaultIsolation.IsHyperV() <del> } else { <del> // Container is requesting an isolation mode. Honour it. <del> hvOpts.IsHyperV = container.HostConfig.Isolation.IsHyperV() <del> } <del> <del> dnsSearch := daemon.getDNSSearchSettings(container) <del> <del> // Generate the layer folder of the layer options <del> layerOpts := &libcontainerd.LayerOption{} <del> m, err := container.RWLayer.Metadata() <del> if err != nil { <del> return nil, fmt.Errorf("failed to get layer metadata - %s", err) <del> } <del> layerOpts.LayerFolderPath = m["dir"] <del> <del> // Generate the layer paths of the layer options <del> img, err := daemon.stores[container.Platform].imageStore.Get(container.ImageID) <del> if err != nil { <del> return nil, fmt.Errorf("failed to graph.Get on ImageID %s - %s", container.ImageID, err) <del> } <del> // Get the layer path for each layer. <del> max := len(img.RootFS.DiffIDs) <del> for i := 1; i <= max; i++ { <del> img.RootFS.DiffIDs = img.RootFS.DiffIDs[:i] <del> layerPath, err := layer.GetLayerPath(daemon.stores[container.Platform].layerStore, img.RootFS.ChainID()) <del> if err != nil { <del> return nil, fmt.Errorf("failed to get layer path from graphdriver %s for ImageID %s - %s", daemon.stores[container.Platform].layerStore, img.RootFS.ChainID(), err) <del> } <del> // Reverse order, expecting parent most first <del> layerOpts.LayerPaths = append([]string{layerPath}, layerOpts.LayerPaths...) <del> } <del> <del> // Get endpoints for the libnetwork allocated networks to the container <del> var epList []string <del> AllowUnqualifiedDNSQuery := false <del> gwHNSID := "" <del> if container.NetworkSettings != nil { <del> for n := range container.NetworkSettings.Networks { <del> sn, err := daemon.FindNetwork(n) <del> if err != nil { <del> continue <del> } <del> <del> ep, err := container.GetEndpointInNetwork(sn) <del> if err != nil { <del> continue <del> } <del> <del> data, err := ep.DriverInfo() <del> if err != nil { <del> continue <del> } <del> <del> if data["GW_INFO"] != nil { <del> gwInfo := data["GW_INFO"].(map[string]interface{}) <del> if gwInfo["hnsid"] != nil { <del> gwHNSID = gwInfo["hnsid"].(string) <del> } <del> } <del> <del> if data["hnsid"] != nil { <del> epList = append(epList, data["hnsid"].(string)) <del> } <del> <del> if data["AllowUnqualifiedDNSQuery"] != nil { <del> AllowUnqualifiedDNSQuery = true <del> } <del> } <del> } <del> <del> if gwHNSID != "" { <del> epList = append(epList, gwHNSID) <del> } <del> <del> // Read and add credentials from the security options if a credential spec has been provided. <del> if container.HostConfig.SecurityOpt != nil { <del> for _, sOpt := range container.HostConfig.SecurityOpt { <del> sOpt = strings.ToLower(sOpt) <del> if !strings.Contains(sOpt, "=") { <del> return nil, fmt.Errorf("invalid security option: no equals sign in supplied value %s", sOpt) <del> } <del> var splitsOpt []string <del> splitsOpt = strings.SplitN(sOpt, "=", 2) <del> if len(splitsOpt) != 2 { <del> return nil, fmt.Errorf("invalid security option: %s", sOpt) <del> } <del> if splitsOpt[0] != "credentialspec" { <del> return nil, fmt.Errorf("security option not supported: %s", splitsOpt[0]) <del> } <del> <del> credentialsOpts := &libcontainerd.CredentialsOption{} <del> var ( <del> match bool <del> csValue string <del> err error <del> ) <del> if match, csValue = getCredentialSpec("file://", splitsOpt[1]); match { <del> if csValue == "" { <del> return nil, fmt.Errorf("no value supplied for file:// credential spec security option") <del> } <del> if credentialsOpts.Credentials, err = readCredentialSpecFile(container.ID, daemon.root, filepath.Clean(csValue)); err != nil { <del> return nil, err <del> } <del> } else if match, csValue = getCredentialSpec("registry://", splitsOpt[1]); match { <del> if csValue == "" { <del> return nil, fmt.Errorf("no value supplied for registry:// credential spec security option") <del> } <del> if credentialsOpts.Credentials, err = readCredentialSpecRegistry(container.ID, csValue); err != nil { <del> return nil, err <del> } <del> } else { <del> return nil, fmt.Errorf("invalid credential spec security option - value must be prefixed file:// or registry:// followed by a value") <del> } <del> createOptions = append(createOptions, credentialsOpts) <del> } <del> } <del> <ide> // LCOW options. <ide> if container.Platform == "linux" { <ide> config := &client.Config{} <ide> func (daemon *Daemon) getLibcontainerdCreateOptions(container *container.Contain <ide> createOptions = append(createOptions, lcowOpts) <ide> } <ide> <del> // Now add the remaining options. <del> createOptions = append(createOptions, &libcontainerd.FlushOption{IgnoreFlushesDuringBoot: !container.HasBeenStartedBefore}) <del> createOptions = append(createOptions, hvOpts) <del> createOptions = append(createOptions, layerOpts) <del> <del> var networkSharedContainerID string <del> if container.HostConfig.NetworkMode.IsContainer() { <del> networkSharedContainerID = container.NetworkSharedContainerID <del> for _, ep := range container.SharedEndpointList { <del> epList = append(epList, ep) <del> } <del> } <del> <del> createOptions = append(createOptions, &libcontainerd.NetworkEndpointsOption{ <del> Endpoints: epList, <del> AllowUnqualifiedDNSQuery: AllowUnqualifiedDNSQuery, <del> DNSSearchList: dnsSearch, <del> NetworkSharedContainerID: networkSharedContainerID, <del> }) <ide> return createOptions, nil <ide> } <del> <del>// getCredentialSpec is a helper function to get the value of a credential spec supplied <del>// on the CLI, stripping the prefix <del>func getCredentialSpec(prefix, value string) (bool, string) { <del> if strings.HasPrefix(value, prefix) { <del> return true, strings.TrimPrefix(value, prefix) <del> } <del> return false, "" <del>} <del> <del>// readCredentialSpecRegistry is a helper function to read a credential spec from <del>// the registry. If not found, we return an empty string and warn in the log. <del>// This allows for staging on machines which do not have the necessary components. <del>func readCredentialSpecRegistry(id, name string) (string, error) { <del> var ( <del> k registry.Key <del> err error <del> val string <del> ) <del> if k, err = registry.OpenKey(registry.LOCAL_MACHINE, credentialSpecRegistryLocation, registry.QUERY_VALUE); err != nil { <del> return "", fmt.Errorf("failed handling spec %q for container %s - %s could not be opened", name, id, credentialSpecRegistryLocation) <del> } <del> if val, _, err = k.GetStringValue(name); err != nil { <del> if err == registry.ErrNotExist { <del> return "", fmt.Errorf("credential spec %q for container %s as it was not found", name, id) <del> } <del> return "", fmt.Errorf("error %v reading credential spec %q from registry for container %s", err, name, id) <del> } <del> return val, nil <del>} <del> <del>// readCredentialSpecFile is a helper function to read a credential spec from <del>// a file. If not found, we return an empty string and warn in the log. <del>// This allows for staging on machines which do not have the necessary components. <del>func readCredentialSpecFile(id, root, location string) (string, error) { <del> if filepath.IsAbs(location) { <del> return "", fmt.Errorf("invalid credential spec - file:// path cannot be absolute") <del> } <del> base := filepath.Join(root, credentialSpecFileLocation) <del> full := filepath.Join(base, location) <del> if !strings.HasPrefix(full, base) { <del> return "", fmt.Errorf("invalid credential spec - file:// path must be under %s", base) <del> } <del> bcontents, err := ioutil.ReadFile(full) <del> if err != nil { <del> return "", fmt.Errorf("credential spec '%s' for container %s as the file could not be read: %q", full, id, err) <del> } <del> return string(bcontents[:]), nil <del>} <ide><path>libcontainerd/client_windows.go <ide> import ( <ide> "io/ioutil" <ide> "os" <ide> "path/filepath" <add> "regexp" <ide> "strings" <ide> "syscall" <ide> "time" <ide> func (clnt *client) Create(containerID string, checkpoint string, checkpointDir <ide> if b, err := json.Marshal(spec); err == nil { <ide> logrus.Debugln("libcontainerd: client.Create() with spec", string(b)) <ide> } <del> osName := spec.Platform.OS <del> if osName == "windows" { <add> <add> // spec.Linux must be nil for Windows containers, but spec.Windows will be filled in regardless of container platform. <add> // This is a temporary workaround due to LCOW requiring layer folder paths, which are stored under spec.Windows. <add> // TODO: @darrenstahlmsft fix this once the OCI spec is updated to support layer folder paths for LCOW <add> if spec.Linux == nil { <ide> return clnt.createWindows(containerID, checkpoint, checkpointDir, spec, attachStdio, options...) <ide> } <ide> return clnt.createLinux(containerID, checkpoint, checkpointDir, spec, attachStdio, options...) <ide> func (clnt *client) createWindows(containerID string, checkpoint string, checkpo <ide> SystemType: "Container", <ide> Name: containerID, <ide> Owner: defaultOwner, <del> IgnoreFlushesDuringBoot: false, <add> IgnoreFlushesDuringBoot: spec.Windows.IgnoreFlushesDuringBoot, <ide> HostName: spec.Hostname, <ide> HvPartition: false, <add> Servicing: spec.Windows.Servicing, <ide> } <ide> <ide> if spec.Windows.Resources != nil { <ide> func (clnt *client) createWindows(containerID string, checkpoint string, checkpo <ide> } <ide> } <ide> <del> var layerOpt *LayerOption <del> for _, option := range options { <del> if s, ok := option.(*ServicingOption); ok { <del> configuration.Servicing = s.IsServicing <del> continue <del> } <del> if f, ok := option.(*FlushOption); ok { <del> configuration.IgnoreFlushesDuringBoot = f.IgnoreFlushesDuringBoot <del> continue <del> } <del> if h, ok := option.(*HyperVIsolationOption); ok { <del> configuration.HvPartition = h.IsHyperV <del> continue <del> } <del> if l, ok := option.(*LayerOption); ok { <del> layerOpt = l <del> } <del> if n, ok := option.(*NetworkEndpointsOption); ok { <del> configuration.EndpointList = n.Endpoints <del> configuration.AllowUnqualifiedDNSQuery = n.AllowUnqualifiedDNSQuery <del> if n.DNSSearchList != nil { <del> configuration.DNSSearchList = strings.Join(n.DNSSearchList, ",") <del> } <del> configuration.NetworkSharedContainerName = n.NetworkSharedContainerID <del> continue <del> } <del> if c, ok := option.(*CredentialsOption); ok { <del> configuration.Credentials = c.Credentials <del> continue <add> if spec.Windows.HyperV != nil { <add> configuration.HvPartition = true <add> } <add> <add> if spec.Windows.Network != nil { <add> configuration.EndpointList = spec.Windows.Network.EndpointList <add> configuration.AllowUnqualifiedDNSQuery = spec.Windows.Network.AllowUnqualifiedDNSQuery <add> if spec.Windows.Network.DNSSearchList != nil { <add> configuration.DNSSearchList = strings.Join(spec.Windows.Network.DNSSearchList, ",") <ide> } <add> configuration.NetworkSharedContainerName = spec.Windows.Network.NetworkSharedContainerName <add> } <add> <add> if cs, ok := spec.Windows.CredentialSpec.(string); ok { <add> configuration.Credentials = cs <ide> } <ide> <del> // We must have a layer option with at least one path <del> if layerOpt == nil || layerOpt.LayerPaths == nil { <del> return fmt.Errorf("no layer option or paths were supplied to the runtime") <add> // We must have least two layers in the spec, the bottom one being a base image, <add> // the top one being the RW layer. <add> if spec.Windows.LayerFolders == nil || len(spec.Windows.LayerFolders) < 2 { <add> return fmt.Errorf("OCI spec is invalid - at least two LayerFolders must be supplied to the runtime") <ide> } <ide> <add> // Strip off the top-most layer as that's passed in separately to HCS <add> configuration.LayerFolderPath = spec.Windows.LayerFolders[len(spec.Windows.LayerFolders)-1] <add> layerFolders := spec.Windows.LayerFolders[:len(spec.Windows.LayerFolders)-1] <add> <ide> if configuration.HvPartition { <del> // Find the upper-most utility VM image, since the utility VM does not <del> // use layering in RS1. <del> // TODO @swernli/jhowardmsft at some point post RS1 this may be re-locatable. <add> // We don't currently support setting the utility VM image explicitly. <add> // TODO @swernli/jhowardmsft circa RS3/4, this may be re-locatable. <add> if spec.Windows.HyperV.UtilityVMPath != "" { <add> return errors.New("runtime does not support an explicit utility VM path for Hyper-V containers") <add> } <add> <add> // Find the upper-most utility VM image. <ide> var uvmImagePath string <del> for _, path := range layerOpt.LayerPaths { <add> for _, path := range layerFolders { <ide> fullPath := filepath.Join(path, "UtilityVM") <ide> _, err := os.Stat(fullPath) <ide> if err == nil { <ide> func (clnt *client) createWindows(containerID string, checkpoint string, checkpo <ide> return errors.New("utility VM image could not be found") <ide> } <ide> configuration.HvRuntime = &hcsshim.HvRuntime{ImagePath: uvmImagePath} <add> <add> if spec.Root.Path != "" { <add> return errors.New("OCI spec is invalid - Root.Path must be omitted for a Hyper-V container") <add> } <ide> } else { <del> configuration.VolumePath = spec.Root.Path <add> const volumeGUIDRegex = `^\\\\\?\\(Volume)\{{0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}\}\\$` <add> if _, err := regexp.MatchString(volumeGUIDRegex, spec.Root.Path); err != nil { <add> return fmt.Errorf(`OCI spec is invalid - Root.Path '%s' must be a volume GUID path in the format '\\?\Volume{GUID}\'`, spec.Root.Path) <add> } <add> // HCS API requires the trailing backslash to be removed <add> configuration.VolumePath = spec.Root.Path[:len(spec.Root.Path)-1] <ide> } <ide> <del> configuration.LayerFolderPath = layerOpt.LayerFolderPath <add> if spec.Root.Readonly { <add> return errors.New(`OCI spec is invalid - Root.Readonly must not be set on Windows`) <add> } <ide> <del> for _, layerPath := range layerOpt.LayerPaths { <add> for _, layerPath := range layerFolders { <ide> _, filename := filepath.Split(layerPath) <ide> g, err := hcsshim.NameToGuid(filename) <ide> if err != nil { <ide> func (clnt *client) createWindows(containerID string, checkpoint string, checkpo <ide> var mps []hcsshim.MappedPipe <ide> for _, mount := range spec.Mounts { <ide> const pipePrefix = `\\.\pipe\` <add> if mount.Type != "" { <add> return fmt.Errorf("OCI spec is invalid - Mount.Type '%s' must not be set", mount.Type) <add> } <ide> if strings.HasPrefix(mount.Destination, pipePrefix) { <ide> mp := hcsshim.MappedPipe{ <ide> HostPath: mount.Source, <ide> func (clnt *client) createWindows(containerID string, checkpoint string, checkpo <ide> }, <ide> processes: make(map[string]*process), <ide> }, <add> isWindows: true, <ide> ociSpec: spec, <ide> hcsContainer: hcsContainer, <ide> } <ide> func (clnt *client) createWindows(containerID string, checkpoint string, checkpo <ide> func (clnt *client) createLinux(containerID string, checkpoint string, checkpointDir string, spec specs.Spec, attachStdio StdioCallback, options ...CreateOption) error { <ide> logrus.Debugf("libcontainerd: createLinux(): containerId %s ", containerID) <ide> <del> var layerOpt *LayerOption <ide> var lcowOpt *LCOWOption <ide> for _, option := range options { <del> if layer, ok := option.(*LayerOption); ok { <del> layerOpt = layer <del> } <ide> if lcow, ok := option.(*LCOWOption); ok { <ide> lcowOpt = lcow <ide> } <ide> func (clnt *client) createLinux(containerID string, checkpoint string, checkpoin <ide> } <ide> } <ide> <del> // We must have a layer option with at least one path <del> if layerOpt == nil || layerOpt.LayerPaths == nil { <del> return fmt.Errorf("no layer option or paths were supplied to the runtime") <add> if spec.Windows == nil { <add> return fmt.Errorf("spec.Windows must not be nil for LCOW containers") <add> } <add> <add> // We must have least one layer in the spec <add> if spec.Windows.LayerFolders == nil || len(spec.Windows.LayerFolders) == 0 { <add> return fmt.Errorf("OCI spec is invalid - at least one LayerFolders must be supplied to the runtime") <ide> } <ide> <del> // LayerFolderPath (writeable layer) + Layers (Guid + path) <del> configuration.LayerFolderPath = layerOpt.LayerFolderPath <del> for _, layerPath := range layerOpt.LayerPaths { <add> // Strip off the top-most layer as that's passed in separately to HCS <add> configuration.LayerFolderPath = spec.Windows.LayerFolders[len(spec.Windows.LayerFolders)-1] <add> layerFolders := spec.Windows.LayerFolders[:len(spec.Windows.LayerFolders)-1] <add> <add> for _, layerPath := range layerFolders { <ide> _, filename := filepath.Split(layerPath) <ide> g, err := hcsshim.NameToGuid(filename) <ide> if err != nil { <ide> func (clnt *client) createLinux(containerID string, checkpoint string, checkpoin <ide> }) <ide> } <ide> <del> for _, option := range options { <del> if n, ok := option.(*NetworkEndpointsOption); ok { <del> configuration.EndpointList = n.Endpoints <del> configuration.AllowUnqualifiedDNSQuery = n.AllowUnqualifiedDNSQuery <del> if n.DNSSearchList != nil { <del> configuration.DNSSearchList = strings.Join(n.DNSSearchList, ",") <del> } <del> configuration.NetworkSharedContainerName = n.NetworkSharedContainerID <del> break <add> if spec.Windows.Network != nil { <add> configuration.EndpointList = spec.Windows.Network.EndpointList <add> configuration.AllowUnqualifiedDNSQuery = spec.Windows.Network.AllowUnqualifiedDNSQuery <add> if spec.Windows.Network.DNSSearchList != nil { <add> configuration.DNSSearchList = strings.Join(spec.Windows.Network.DNSSearchList, ",") <ide> } <add> configuration.NetworkSharedContainerName = spec.Windows.Network.NetworkSharedContainerName <ide> } <ide> <ide> hcsContainer, err := hcsshim.CreateContainer(containerID, configuration) <ide> func (clnt *client) AddProcess(ctx context.Context, containerID, processFriendly <ide> } <ide> if procToAdd.Terminal { <ide> createProcessParms.EmulateConsole = true <del> createProcessParms.ConsoleSize[0] = uint(procToAdd.ConsoleSize.Height) <del> createProcessParms.ConsoleSize[1] = uint(procToAdd.ConsoleSize.Width) <add> if procToAdd.ConsoleSize != nil { <add> createProcessParms.ConsoleSize[0] = uint(procToAdd.ConsoleSize.Height) <add> createProcessParms.ConsoleSize[1] = uint(procToAdd.ConsoleSize.Width) <add> } <ide> } <ide> <ide> // Take working directory from the process to add if it is defined, <ide> func (clnt *client) AddProcess(ctx context.Context, containerID, processFriendly <ide> <ide> // Configure the environment for the process <ide> createProcessParms.Environment = setupEnvironmentVariables(procToAdd.Env) <del> if container.ociSpec.Platform.OS == "windows" { <add> if container.isWindows { <ide> createProcessParms.CommandLine = strings.Join(procToAdd.Args, " ") <ide> } else { <ide> createProcessParms.CommandArgs = procToAdd.Args <ide> func (clnt *client) Pause(containerID string) error { <ide> return err <ide> } <ide> <del> for _, option := range container.options { <del> if h, ok := option.(*HyperVIsolationOption); ok { <del> if !h.IsHyperV { <del> return errors.New("cannot pause Windows Server Containers") <del> } <del> break <del> } <add> if container.ociSpec.Windows.HyperV == nil { <add> return errors.New("cannot pause Windows Server Containers") <ide> } <ide> <ide> err = container.hcsContainer.Pause() <ide> func (clnt *client) Resume(containerID string) error { <ide> } <ide> <ide> // This should never happen, since Windows Server Containers cannot be paused <del> for _, option := range container.options { <del> if h, ok := option.(*HyperVIsolationOption); ok { <del> if !h.IsHyperV { <del> return errors.New("cannot resume Windows Server Containers") <del> } <del> break <del> } <add> <add> if container.ociSpec.Windows.HyperV == nil { <add> return errors.New("cannot resume Windows Server Containers") <ide> } <ide> <ide> err = container.hcsContainer.Resume() <ide><path>libcontainerd/container_windows.go <ide> type container struct { <ide> // otherwise have access to the Spec <ide> ociSpec specs.Spec <ide> <add> isWindows bool <ide> manualStopRequested bool <ide> hcsContainer hcsshim.Container <ide> } <ide> func (ctr *container) newProcess(friendlyName string) *process { <ide> // Caller needs to lock container ID before calling this method. <ide> func (ctr *container) start(attachStdio StdioCallback) error { <ide> var err error <del> isServicing := false <del> <del> for _, option := range ctr.options { <del> if s, ok := option.(*ServicingOption); ok && s.IsServicing { <del> isServicing = true <del> } <del> } <ide> <ide> // Start the container. If this is a servicing container, this call will block <ide> // until the container is done with the servicing execution. <ide> func (ctr *container) start(attachStdio StdioCallback) error { <ide> // docker can always grab the output through logs. We also tell HCS to always <ide> // create stdin, even if it's not used - it will be closed shortly. Stderr <ide> // is only created if it we're not -t. <add> var ( <add> emulateConsole bool <add> createStdErrPipe bool <add> ) <add> if ctr.ociSpec.Process != nil { <add> emulateConsole = ctr.ociSpec.Process.Terminal <add> createStdErrPipe = !ctr.ociSpec.Process.Terminal && !ctr.ociSpec.Windows.Servicing <add> } <add> <ide> createProcessParms := &hcsshim.ProcessConfig{ <del> EmulateConsole: ctr.ociSpec.Process.Terminal, <add> EmulateConsole: emulateConsole, <ide> WorkingDirectory: ctr.ociSpec.Process.Cwd, <del> CreateStdInPipe: !isServicing, <del> CreateStdOutPipe: !isServicing, <del> CreateStdErrPipe: !ctr.ociSpec.Process.Terminal && !isServicing, <add> CreateStdInPipe: !ctr.ociSpec.Windows.Servicing, <add> CreateStdOutPipe: !ctr.ociSpec.Windows.Servicing, <add> CreateStdErrPipe: createStdErrPipe, <add> } <add> <add> if ctr.ociSpec.Process != nil && ctr.ociSpec.Process.ConsoleSize != nil { <add> createProcessParms.ConsoleSize[0] = uint(ctr.ociSpec.Process.ConsoleSize.Height) <add> createProcessParms.ConsoleSize[1] = uint(ctr.ociSpec.Process.ConsoleSize.Width) <ide> } <del> createProcessParms.ConsoleSize[0] = uint(ctr.ociSpec.Process.ConsoleSize.Height) <del> createProcessParms.ConsoleSize[1] = uint(ctr.ociSpec.Process.ConsoleSize.Width) <ide> <ide> // Configure the environment for the process <ide> createProcessParms.Environment = setupEnvironmentVariables(ctr.ociSpec.Process.Env) <del> if ctr.ociSpec.Platform.OS == "windows" { <add> if ctr.isWindows { <ide> createProcessParms.CommandLine = strings.Join(ctr.ociSpec.Process.Args, " ") <ide> } else { <ide> createProcessParms.CommandArgs = ctr.ociSpec.Process.Args <ide> } <ide> createProcessParms.User = ctr.ociSpec.Process.User.Username <ide> <del> // Linux containers requires the raw OCI spec passed through HCS and onwards to GCS for the utility VM. <del> if ctr.ociSpec.Platform.OS == "linux" { <add> // LCOW requires the raw OCI spec passed through HCS and onwards to GCS for the utility VM. <add> if !ctr.isWindows { <ide> ociBuf, err := json.Marshal(ctr.ociSpec) <ide> if err != nil { <ide> return err <ide> func (ctr *container) start(attachStdio StdioCallback) error { <ide> <ide> // If this is a servicing container, wait on the process synchronously here and <ide> // if it succeeds, wait for it cleanly shutdown and merge into the parent container. <del> if isServicing { <add> if ctr.ociSpec.Windows.Servicing { <ide> exitCode := ctr.waitProcessExitCode(&ctr.process) <ide> <ide> if exitCode != 0 { <ide> func (ctr *container) waitExit(process *process, isFirstProcessToStart bool) err <ide> si.State = StateExitProcess <ide> } else { <ide> // Pending updates is only applicable for WCOW <del> if ctr.ociSpec.Platform.OS == "windows" { <add> if ctr.isWindows { <ide> updatePending, err := ctr.hcsContainer.HasPendingUpdates() <ide> if err != nil { <ide> logrus.Warnf("libcontainerd: HasPendingUpdates() failed (container may have been killed): %s", err) <ide><path>libcontainerd/types_windows.go <ide> type LCOWOption struct { <ide> Config *opengcs.Config <ide> } <ide> <del>// ServicingOption is a CreateOption with a no-op application that signifies <del>// the container needs to be used for a Windows servicing operation. <del>type ServicingOption struct { <del> IsServicing bool <del>} <del> <del>// FlushOption is a CreateOption that signifies if the container should be <del>// started with flushes ignored until boot has completed. This is an optimisation <del>// for first boot of a container. <del>type FlushOption struct { <del> IgnoreFlushesDuringBoot bool <del>} <del> <del>// HyperVIsolationOption is a CreateOption that indicates whether the runtime <del>// should start the container as a Hyper-V container. <del>type HyperVIsolationOption struct { <del> IsHyperV bool <del>} <del> <del>// LayerOption is a CreateOption that indicates to the runtime the layer folder <del>// and layer paths for a container. <del>type LayerOption struct { <del> // LayerFolderPath is the path to the current layer folder. Empty for Hyper-V containers. <del> LayerFolderPath string `json:",omitempty"` <del> // Layer paths of the parent layers <del> LayerPaths []string <del>} <del> <del>// NetworkEndpointsOption is a CreateOption that provides the runtime list <del>// of network endpoints to which a container should be attached during its creation. <del>type NetworkEndpointsOption struct { <del> Endpoints []string <del> AllowUnqualifiedDNSQuery bool <del> DNSSearchList []string <del> NetworkSharedContainerID string <del>} <del> <del>// CredentialsOption is a CreateOption that indicates the credentials from <del>// a credential spec to be used to the runtime <del>type CredentialsOption struct { <del> Credentials string <del>} <del> <ide> // Checkpoint holds the details of a checkpoint (not supported in windows) <ide> type Checkpoint struct { <ide> Name string <ide><path>libcontainerd/utils_windows.go <ide> func setupEnvironmentVariables(a []string) map[string]string { <ide> return r <ide> } <ide> <del>// Apply for a servicing option is a no-op. <del>func (s *ServicingOption) Apply(interface{}) error { <del> return nil <del>} <del> <del>// Apply for the flush option is a no-op. <del>func (f *FlushOption) Apply(interface{}) error { <del> return nil <del>} <del> <del>// Apply for the hypervisolation option is a no-op. <del>func (h *HyperVIsolationOption) Apply(interface{}) error { <del> return nil <del>} <del> <del>// Apply for the layer option is a no-op. <del>func (h *LayerOption) Apply(interface{}) error { <del> return nil <del>} <del> <del>// Apply for the network endpoints option is a no-op. <del>func (s *NetworkEndpointsOption) Apply(interface{}) error { <del> return nil <del>} <del> <del>// Apply for the credentials option is a no-op. <del>func (s *CredentialsOption) Apply(interface{}) error { <del> return nil <del>} <del> <ide> // Apply for the LCOW option is a no-op. <ide> func (s *LCOWOption) Apply(interface{}) error { <ide> return nil <ide><path>oci/defaults.go <ide> func DefaultWindowsSpec() specs.Spec { <ide> return specs.Spec{ <ide> Version: specs.Version, <ide> Windows: &specs.Windows{}, <add> Process: &specs.Process{}, <add> Root: &specs.Root{}, <ide> } <ide> } <ide> <ide> func DefaultLinuxSpec() specs.Spec { <ide> s := specs.Spec{ <ide> Version: specs.Version, <ide> Process: &specs.Process{}, <add> Root: &specs.Root{}, <ide> } <ide> s.Mounts = []specs.Mount{ <ide> { <ide> func DefaultLinuxSpec() specs.Spec { <ide> Options: []string{"nosuid", "noexec", "nodev", "mode=1777"}, <ide> }, <ide> } <del> s.Process.Capabilities = &specs.LinuxCapabilities{ <del> Bounding: defaultCapabilities(), <del> Permitted: defaultCapabilities(), <del> Inheritable: defaultCapabilities(), <del> Effective: defaultCapabilities(), <add> s.Process = &specs.Process{ <add> Capabilities: &specs.LinuxCapabilities{ <add> Bounding: defaultCapabilities(), <add> Permitted: defaultCapabilities(), <add> Inheritable: defaultCapabilities(), <add> Effective: defaultCapabilities(), <add> }, <ide> } <ide> <ide> s.Linux = &specs.Linux{ <ide> func DefaultLinuxSpec() specs.Spec { <ide> }, <ide> } <ide> <add> // For LCOW support, populate a blank Windows spec <add> if runtime.GOOS == "windows" { <add> s.Windows = &specs.Windows{} <add> } <add> <ide> // For LCOW support, don't mask /sys/firmware <ide> if runtime.GOOS != "windows" { <ide> s.Linux.MaskedPaths = append(s.Linux.MaskedPaths, "/sys/firmware")
8
Text
Text
fix wordy sentence
1917ba851bd8851a3f27f56b1c1f4b5476cdc124
<ide><path>doc/guides/contributing/code-of-conduct.md <ide> All contributors to Node.js tacitly agree to abide by both the letter and <ide> spirit of the [Code of Conduct][]. Failure, or unwillingness, to do so will <ide> result in contributions being respectfully declined. <ide> <del>A *bad actor* is someone who repeatedly violates the *spirit* of the Code of <del>Conduct through consistent failure to self-regulate the way in which they <del>interact with other contributors in the project. In doing so, bad actors <add>A *bad actor* is someone who repeatedly violates the spirit of the Code of <add>Conduct through failure to regulate how they <add>interact with others. In doing so, bad actors <ide> alienate other contributors, discourage collaboration, and generally reflect <ide> poorly on the project as a whole. <ide>
1
Javascript
Javascript
fix bug with metamorph views and outlets
3c489d6f3263895c672692b9b3b171fea7191924
<ide><path>packages/ember-routing/lib/handlebars_ext.js <ide> Ember.onLoad('Ember.Handlebars', function(Handlebars) { <ide> property = 'main'; <ide> } <ide> <del> options.hash.currentViewBinding = "view._outlets." + property; <add> options.hash.currentViewBinding = "_view._outlets." + property; <ide> <ide> return Handlebars.helpers.view.call(this, Handlebars.OutletView, options); <ide> }); <ide><path>packages/ember-routing/tests/helpers/outlet_test.js <ide> test("outlet should support an optional name", function() { <ide> <ide> equal(view.$().text(), 'HIBYE'); <ide> }); <add> <add>test("Outlets bind to the current view, not the current concrete view", function() { <add> var parentTemplate = "<h1>HI</h1>{{outlet}}"; <add> var middleTemplate = "<h2>MIDDLE</h2>{{outlet}}"; <add> var bottomTemplate = "<h3>BOTTOM</h3>"; <add> <add> view = Ember.View.create({ <add> template: compile(parentTemplate) <add> }); <add> <add> var middleView = Ember._MetamorphView.create({ <add> template: compile(middleTemplate) <add> }); <add> <add> var bottomView = Ember._MetamorphView.create({ <add> template: compile(bottomTemplate) <add> }); <add> <add> appendView(view); <add> <add> Ember.run(function() { <add> view.connectOutlet('main', middleView); <add> }); <add> <add> Ember.run(function() { <add> middleView.connectOutlet('main', bottomView); <add> }); <add> <add> var output = Ember.$('#qunit-fixture h1 ~ h2 ~ h3').text(); <add> equal(output, "BOTTOM", "all templates were rendered"); <add>}); <ide><path>packages/ember-views/lib/views/view.js <ide> Ember.View = Ember.CoreView.extend( <ide> <ide> var keywords = templateData ? Ember.copy(templateData.keywords) : {}; <ide> set(keywords, 'view', get(this, 'concreteView')); <add> set(keywords, '_view', this); <ide> set(keywords, 'controller', get(this, 'controller')); <ide> <ide> return keywords;
3
Javascript
Javascript
use requirerepl() to load debugger repl
616343bc61d389cae571191c52abe97708878570
<ide><path>lib/_debugger.js <ide> var util = require('util'), <ide> path = require('path'), <ide> net = require('net'), <ide> vm = require('vm'), <del> repl = require('repl'), <add> module = require('module'), <add> repl = module.requireRepl(), <ide> inherits = util.inherits, <ide> assert = require('assert'), <ide> spawn = require('child_process').spawn; <ide> function Interface(stdin, stdout, args) { <ide> if (parseInt(process.env['NODE_DISABLE_COLORS'], 10)) { <ide> opts.useColors = false; <ide> } <add> <ide> this.repl = repl.start(opts); <ide> <ide> // Do not print useless warning <ide> Interface.prototype.list = function(delta) { <ide> if (lineno == 1) { <ide> // The first line needs to have the module wrapper filtered out of <ide> // it. <del> var wrapper = require('module').wrapper[0]; <add> var wrapper = module.wrapper[0]; <ide> lines[i] = lines[i].slice(wrapper.length); <ide> <ide> client.currentSourceColumn -= wrapper.length; <ide><path>test/simple/test-repl-tab-complete.js <ide> testMe.complete(' ', function(error, data) { <ide> testMe.complete('toSt', function(error, data) { <ide> assert.deepEqual(data, [['toString'], 'toSt']); <ide> }); <add> <add>// Tab complete provides built in libs for require() <add>putIn.run(['.clear']); <add> <add>testMe.complete('require(\'', function(error, data) { <add> assert.strictEqual(error, null); <add> repl._builtinLibs.forEach(function(lib) { <add> assert.notStrictEqual(data[0].indexOf(lib), -1, lib + ' not found'); <add> }); <add>}); <add> <add>testMe.complete('require(\'n', function(error, data) { <add> assert.strictEqual(error, null); <add> assert.deepEqual(data, [['net'], 'n']); <add>});
2
Text
Text
fix text for dep0085
0b03d91d62afba2b0e52633982dbbd0dcf3c38a6
<ide><path>doc/api/deprecations.md <ide> code modification is necessary if that is done. <ide> <ide> Type: End-of-Life <ide> <del>The AsyncHooks Sensitive API was never documented and had various of minor <del>issues, see https://github.com/nodejs/node/issues/15572. Use the `AsyncResource` <add>The AsyncHooks Sensitive API was never documented and had various minor issues. <add>(See https://github.com/nodejs/node/issues/15572.) Use the `AsyncResource` <ide> API instead. <ide> <ide> <a id="DEP0086"></a>
1
Text
Text
adjust changelog to clarify `client` revert
d29034b34b97a0c23e93e9d40feae132c622c0fd
<ide><path>CHANGELOG.md <ide> <ide> ### Notable changes <ide> <del>* **http**: reverts the removal of an undocumented `client` property on client connections, this property is being used in the wild, most notably by [request](https://github.com/request/request) which is used by npm. (Michaël Zasso) [#1852](https://github.com/nodejs/io.js/pull/1852). <add>* **http**: Reverts the move of the `client` property of `IncomingMessage` to its prototype. Although undocumented, this property was used and assumed to be an "own property" in the wild, most notably by [request](https://github.com/request/request) which is used by npm. (Michaël Zasso) [#1852](https://github.com/nodejs/io.js/pull/1852). <ide> <ide> ### Known issues <ide>
1
PHP
PHP
accomodate immutable dates and use named formats
8deb66f03c2151c78727a221e6f30bc16c77be28
<ide><path>src/I18n/DateFormatTrait.php <ide> public function jsonSerialize() <ide> public function __debugInfo() <ide> { <ide> return [ <del> 'time' => $this->format(DateTime::ISO8601), <add> 'time' => $this->toIso8601String(), <ide> 'timezone' => $this->getTimezone()->getName(), <del> 'fixedNowTime' => $this->hasTestNow() ? $this->getTestNow()->format(DateTime::ISO8601) : false <add> 'fixedNowTime' => $this->hasTestNow() ? $this->getTestNow()->toIso8601String() : false <ide> ]; <ide> } <ide> } <ide><path>tests/TestCase/Controller/Component/CookieComponentTest.php <ide> public function testWriteFarFuture() <ide> $this->Cookie->configKey('Testing', 'expires', '+90 years'); <ide> $this->Cookie->write('Testing', 'value'); <ide> $future = new Time('now'); <del> $future->modify('+90 years'); <add> $future = $future->modify('+90 years'); <ide> <ide> $expected = [ <ide> 'name' => 'Testing', <ide><path>tests/TestCase/I18n/TimeTest.php <ide> public function testDebugInfo() <ide> { <ide> $time = new Time('2014-04-20 10:10:10'); <ide> $expected = [ <del> 'time' => '2014-04-20T10:10:10+0000', <add> 'time' => '2014-04-20T10:10:10+00:00', <ide> 'timezone' => 'UTC', <del> 'fixedNowTime' => Time::getTestNow()->toISO8601String() <add> 'fixedNowTime' => Time::getTestNow()->toIso8601String() <ide> ]; <ide> $this->assertEquals($expected, $time->__debugInfo()); <ide> }
3
Text
Text
add changelog entry for
bf545b73b74dd9f66fcf300a7a3fa6528511ed5b
<ide><path>actionview/CHANGELOG.md <add>* Remove legacy default `media=screen` from `stylesheet_link_tag`. <add> <add> *André Luis Leal Cardoso Junior* <add> <ide> * Change `ActionView::Helpers::FormBuilder#button` to transform `formmethod` <ide> attributes into `_method="$VERB"` Form Data to enable varied same-form actions: <ide>
1
Go
Go
use prefix naming for ps tests
00b82fcab6492a853958a3a5f43f95469a60e12f
<ide><path>integration-cli/docker_cli_ps_test.go <ide> import ( <ide> "time" <ide> ) <ide> <del>func TestListContainers(t *testing.T) { <add>func TestPsListContainers(t *testing.T) { <ide> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top") <ide> out, _, err := runCommandWithOutput(runCmd) <ide> errorOut(err, t, out) <ide> func assertContainerList(out string, expected []string) bool { <ide> return true <ide> } <ide> <del>func TestListContainersSize(t *testing.T) { <add>func TestPsListContainersSize(t *testing.T) { <ide> name := "test_size" <ide> runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo 1 > test") <ide> out, _, err := runCommandWithOutput(runCmd)
1
Python
Python
remove db call from `databrickshook.__init__()`
66f94f95c2e92baad2761b5a1fa405e36c17808a
<ide><path>airflow/providers/databricks/hooks/databricks.py <ide> def __init__( <ide> ) -> None: <ide> super().__init__() <ide> self.databricks_conn_id = databricks_conn_id <del> self.databricks_conn = self.get_connection(databricks_conn_id) <del> if 'host' in self.databricks_conn.extra_dejson: <del> self.host = self._parse_host(self.databricks_conn.extra_dejson['host']) <del> else: <del> self.host = self._parse_host(self.databricks_conn.host) <add> self.databricks_conn = None <ide> self.timeout_seconds = timeout_seconds <ide> if retry_limit < 1: <ide> raise ValueError('Retry limit must be greater than equal to 1') <ide> def _do_api_call(self, endpoint_info, json): <ide> :rtype: dict <ide> """ <ide> method, endpoint = endpoint_info <add> <add> if self.databricks_conn is None: <add> self.databricks_conn = self.get_connection(self.databricks_conn_id) <add> <add> if 'host' in self.databricks_conn.extra_dejson: <add> self.host = self._parse_host(self.databricks_conn.extra_dejson['host']) <add> else: <add> self.host = self._parse_host(self.databricks_conn.host) <add> <ide> url = f'https://{self.host}/{endpoint}' <ide> <ide> aad_headers = self._get_aad_headers()
1
Javascript
Javascript
update event dispatcher to use sc.eventmanager api
e39d5f81ea9a2cd0e66c669200930042c6f17ed2
<ide><path>packages/sproutcore-views/lib/system/event_dispatcher.js <ide> SC.EventDispatcher = SC.Object.extend( <ide> setupHandler: function(rootElement, event, eventName) { <ide> rootElement.delegate('.sc-view', event + '.sproutcore', function(evt) { <ide> var view = SC.View.views[this.id], <del> result = true, handler; <add> result = true, manager = null, <add> self = this; <add> <add> manager = self._findNearestEventManager(view,eventName); <add> <add> if (manager) { <add> result = self._dispatchEvent(manager, evt, eventName); <add> } <add> else { <add> result = self._bubbleEvent(view,evt,eventName); <add> } <add> <add> evt.stopPropagation(); <add> <add> return result; <add> }); <add> }, <add> <add> /** @private */ <add> _findNearestEventManager: function(view, eventName) { <add> var manager = null; <add> <add> while (view) { <add> manager = get(view, 'eventManager'); <add> if (manager && manager[eventName]) { break; } <add> <add> view = get(view, 'parentView'); <add> } <add> <add> return manager; <add> }, <add> <add> /** @private */ <add> _dispatchEvent: function(object, evt, eventName) { <add> handler = object[eventName]; <add> if (SC.typeOf(handler) === 'function') { <add> result = handler.call(object, evt); <add> } <add> <add> return result; <add> }, <add> <add> /** @private */ <add> _bubbleEvent: function(view, evt, eventName) { <add> var result = true, handler, <add> self = this; <ide> <ide> SC.run(function() { <ide> handler = view[eventName]; <ide> SC.EventDispatcher = SC.Object.extend( <ide> }); <ide> <ide> return result; <del> }); <ide> }, <ide> <ide> /** @private */
1
Ruby
Ruby
add constants for json files
4ae72e0bdfeab8258da4caf4103f75ec14c8b09c
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit <ide> audit_tap_audit_exceptions <ide> end <ide> <del> HOMEBREW_TAP_JSON_FILES = %w[ <del> formula_renames.json <del> tap_migrations.json <del> audit_exceptions/*.json <del> ].freeze <del> <ide> def audit_json_files <del> json_patterns = HOMEBREW_TAP_JSON_FILES.map { |pattern| @path/pattern } <add> json_patterns = Tap::HOMEBREW_TAP_JSON_FILES.map { |pattern| @path/pattern } <ide> Pathname.glob(json_patterns).each do |file| <ide> JSON.parse file.read <ide> rescue JSON::ParserError <ide><path>Library/Homebrew/tap.rb <ide> class Tap <ide> <ide> TAP_DIRECTORY = (HOMEBREW_LIBRARY/"Taps").freeze <ide> <add> HOMEBREW_TAP_FORMULA_RENAMES_FILE = "formula_renames.json" <add> HOMEBREW_TAP_MIGRATIONS_FILE = "tap_migrations.json" <add> HOMEBREW_TAP_AUDIT_EXCEPTIONS_DIR = "audit_exceptions" <add> <add> HOMEBREW_TAP_JSON_FILES = %W[ <add> #{HOMEBREW_TAP_FORMULA_RENAMES_FILE} <add> #{HOMEBREW_TAP_MIGRATIONS_FILE} <add> #{HOMEBREW_TAP_AUDIT_EXCEPTIONS_DIR}/*.json <add> ].freeze <add> <ide> def self.fetch(*args) <ide> case args.length <ide> when 1 <ide> def to_hash <ide> <ide> # Hash with tap formula renames <ide> def formula_renames <del> @formula_renames ||= if (rename_file = path/"formula_renames.json").file? <add> @formula_renames ||= if (rename_file = path/HOMEBREW_TAP_FORMULA_RENAMES_FILE).file? <ide> JSON.parse(rename_file.read) <ide> else <ide> {} <ide> def formula_renames <ide> <ide> # Hash with tap migrations <ide> def tap_migrations <del> @tap_migrations ||= if (migration_file = path/"tap_migrations.json").file? <add> @tap_migrations ||= if (migration_file = path/HOMEBREW_TAP_MIGRATIONS_FILE).file? <ide> JSON.parse(migration_file.read) <ide> else <ide> {} <ide> def tap_migrations <ide> def audit_exceptions <ide> @audit_exceptions = {} <ide> <del> Pathname.glob(path/"audit_exceptions/*").each do |exception_file| <add> Pathname.glob(path/HOMEBREW_TAP_AUDIT_EXCEPTIONS_DIR/"*").each do |exception_file| <ide> list_name = exception_file.basename.to_s.chomp(".json").to_sym <ide> list_contents = begin <ide> JSON.parse exception_file.read
2
Text
Text
update installation from binaries for 1.11
f5336c737086a4c1807bb2b6ab57116b5ed9d769
<ide><path>docs/installation/binaries.md <ide> weight = 110 <ide> +++ <ide> <![end-metadata]--> <ide> <del># Binaries <add># Installation from binaries <ide> <ide> **This instruction set is meant for hackers who want to try out Docker <ide> on a variety of environments.** <ide> exhibit unexpected behaviour. <ide> > vendor for the system, and might break regulations and security <ide> > policies in heavily regulated environments. <ide> <del>## Get the Docker binary <add>## Get the Docker Engine binaries <ide> <del>You can download either the latest release binary or a specific version. <del>After downloading a binary file, you must set the file's execute bit to run it. <add>You can download either the latest release binaries or a specific version. To get <add>the list of stable release version numbers from GitHub, view the `docker/docker` <add>[releases page](https://github.com/docker/docker/releases). You can get the MD5 <add>and SHA256 hashes by appending .md5 and .sha256 to the URLs respectively <ide> <del>To set the file's execute bit on Linux and OS X: <ide> <del> $ chmod +x docker <del> <del>To get the list of stable release version numbers from GitHub, view the <del>`docker/docker` [releases page](https://github.com/docker/docker/releases). <del> <del>> **Note** <del>> <del>> 1) You can get the MD5 and SHA256 hashes by appending .md5 and .sha256 to the URLs respectively <del>> <del>> 2) You can get the compressed binaries by appending .tgz to the URLs <del> <del>### Get the Linux binary <add>### Get the Linux binaries <ide> <ide> To download the latest version for Linux, use the <ide> following URLs: <ide> <del> https://get.docker.com/builds/Linux/i386/docker-latest <add> https://get.docker.com/builds/Linux/i386/docker-latest.tgz <ide> <del> https://get.docker.com/builds/Linux/x86_64/docker-latest <add> https://get.docker.com/builds/Linux/x86_64/docker-latest.tgz <ide> <ide> To download a specific version for Linux, use the <ide> following URL patterns: <ide> <del> https://get.docker.com/builds/Linux/i386/docker-<version> <add> https://get.docker.com/builds/Linux/i386/docker-<version>.tgz <ide> <del> https://get.docker.com/builds/Linux/x86_64/docker-<version> <add> https://get.docker.com/builds/Linux/x86_64/docker-<version>.tgz <ide> <ide> For example: <ide> <del> https://get.docker.com/builds/Linux/i386/docker-1.9.1 <add> https://get.docker.com/builds/Linux/i386/docker-1.11.0.tgz <add> <add> https://get.docker.com/builds/Linux/x86_64/docker-1.11.0.tgz <add> <add>> **Note** These instructions are for Docker Engine 1.11 and up. Engine 1.10 and <add>> under consists of a single binary, and instructions for those versions are <add>> different. To install version 1.10 or below, follow the instructions in the <add>> <a href="/v1.10/engine/installation/binaries/" target="_blank">1.10 documentation</a>. <add> <add> <add>#### Install the Linux binaries <add> <add>After downloading, you extract the archive, which puts the binaries in a <add>directory named `docker` in your current location. <add> <add>```bash <add>$ tar -xvzf docker-latest.tgz <add> <add>docker/ <add>docker/docker-containerd-ctr <add>docker/docker <add>docker/docker-containerd <add>docker/docker-runc <add>docker/docker-containerd-shim <add>``` <add> <add>Engine requires these binaries to be installed in your host's `$PATH`. <add>For example, to install the binaries in `/usr/bin`: <add> <add>```bash <add>$ mv docker/* /usr/bin/ <add>``` <ide> <del> https://get.docker.com/builds/Linux/x86_64/docker-1.9.1 <add>> **Note**: If you already have Engine installed on your host, make sure you <add>> stop Engine before installing (`killall docker`), and install the binaries <add>> in the same location. You can find the location of the current installation <add>> with `dirname $(which docker)`. <ide> <add>#### Run the Engine daemon on Linux <add> <add>You can manually start the Engine in daemon mode using: <add> <add>```bash <add>$ sudo docker daemon & <add>``` <add> <add>The GitHub repository provides samples of init-scripts you can use to control <add>the daemon through a process manager, such as upstart or systemd. You can find <add>these scripts in the <a href="https://github.com/docker/docker/tree/master/contrib/init"> <add>contrib directory</a>. <add> <add>For additional information about running the Engine in daemon mode, refer to <add>the [daemon command](../reference/commandline/daemon.md) in the Engine command <add>line reference. <ide> <ide> ### Get the Mac OS X binary <ide> <ide> The Mac OS X binary is only a client. You cannot use it to run the `docker` <ide> daemon. To download the latest version for Mac OS X, use the following URLs: <ide> <del> https://get.docker.com/builds/Darwin/x86_64/docker-latest <add> https://get.docker.com/builds/Darwin/x86_64/docker-latest.tgz <ide> <ide> To download a specific version for Mac OS X, use the <del>following URL patterns: <add>following URL pattern: <ide> <del> https://get.docker.com/builds/Darwin/x86_64/docker-<version> <add> https://get.docker.com/builds/Darwin/x86_64/docker-<version>.tgz <ide> <ide> For example: <ide> <del> https://get.docker.com/builds/Darwin/x86_64/docker-1.9.1 <add> https://get.docker.com/builds/Darwin/x86_64/docker-1.11.0.tgz <add> <add>You can extract the downloaded archive either by double-clicking the downloaded <add>`.tgz` or on the command line, using `tar -xvzf docker-1.11.0.tgz`. The client <add>binary can be executed from any location on your filesystem. <add> <ide> <ide> ### Get the Windows binary <ide> <del>You can only download the Windows client binary for version `1.9.1` onwards. <del>Moreover, the binary is only a client, you cannot use it to run the `docker` daemon. <add>You can only download the Windows binary for version `1.9.1` onwards. <add>Moreover, the 32-bit (`i386`) binary is only a client, you cannot use it to <add>run the `docker` daemon. The 64-bit binary (`x86_64`) is both a client and <add>daemon. <add> <ide> To download the latest version for Windows, use the following URLs: <ide> <del> https://get.docker.com/builds/Windows/i386/docker-latest.exe <add> https://get.docker.com/builds/Windows/i386/docker-latest.zip <ide> <del> https://get.docker.com/builds/Windows/x86_64/docker-latest.exe <add> https://get.docker.com/builds/Windows/x86_64/docker-latest.zip <ide> <ide> To download a specific version for Windows, use the following URL pattern: <ide> <del> https://get.docker.com/builds/Windows/i386/docker-<version>.exe <add> https://get.docker.com/builds/Windows/i386/docker-<version>.zip <ide> <del> https://get.docker.com/builds/Windows/x86_64/docker-<version>.exe <add> https://get.docker.com/builds/Windows/x86_64/docker-<version>.zip <ide> <ide> For example: <ide> <del> https://get.docker.com/builds/Windows/i386/docker-1.9.1.exe <del> <del> https://get.docker.com/builds/Windows/x86_64/docker-1.9.1.exe <add> https://get.docker.com/builds/Windows/i386/docker-1.11.0.zip <ide> <add> https://get.docker.com/builds/Windows/x86_64/docker-1.11.0.zip <ide> <del>## Run the Docker daemon <ide> <del> # start the docker in daemon mode from the directory you unpacked <del> $ sudo ./docker daemon & <add>> **Note** These instructions are for Engine 1.11 and up. Instructions for older <add>> versions are slightly different. To install version 1.10 or below, follow the <add>> instructions in the <a href="/v1.10/engine/installation/binaries/" target="_blank">1.10 documentation</a>. <ide> <ide> ## Giving non-root access <ide> <ide> need to add `sudo` to all the client commands. <ide> > The *docker* group (or the group specified with `-G`) is root-equivalent; <ide> > see [*Docker Daemon Attack Surface*](../security/security.md#docker-daemon-attack-surface) details. <ide> <del>## Upgrades <add>## Upgrade Docker Engine <ide> <del>To upgrade your manual installation of Docker, first kill the docker <add>To upgrade your manual installation of Docker Engine on Linux, first kill the docker <ide> daemon: <ide> <ide> $ killall docker <ide> <del>Then follow the regular installation steps. <del> <del>## Run your first container! <del> <del> # check your docker version <del> $ sudo ./docker version <add>Then follow the [regular installation steps](#get-the-linux-binaries). <ide> <del> # run a container and open an interactive shell in the container <del> $ sudo ./docker run -i -t ubuntu /bin/bash <add>## Next steps <ide> <ide> Continue with the [User Guide](../userguide/index.md).
1
Javascript
Javascript
add reference to module
d96f03d9470321996cad163b61bac37e41c89d9a
<ide><path>examples/js/loaders/DRACOLoader.js <ide> THREE.DRACOLoader = function(manager) { <ide> this.materials = null; <ide> }; <ide> <add>const DracoModule = Module; <ide> <ide> THREE.DRACOLoader.prototype = { <ide> <ide> THREE.DRACOLoader.prototype = { <ide> */ <ide> const geometryType = wrapper.GetEncodedGeometryType(buffer); <ide> if (geometryType == DracoModule.TRIANGULAR_MESH) { <del> fileDisplayArea.innerText = "Loaded a mesh.\n"; <add> //fileDisplayArea.innerText = "Loaded a mesh.\n"; <ide> } else if (geometryType == DracoModule.POINT_CLOUD) { <del> fileDisplayArea.innerText = "Loaded a point cloud.\n"; <add> //fileDisplayArea.innerText = "Loaded a point cloud.\n"; <ide> } else { <ide> const errorMsg = "Error: Unknown geometry type."; <del> fileDisplayArea.innerText = errorMsg; <add> //fileDisplayArea.innerText = errorMsg; <ide> throw new Error(errorMsg); <ide> } <ide> return scope.convertDracoGeometryTo3JS(wrapper, geometryType, buffer); <ide> THREE.DRACOLoader.prototype = { <ide> Module.POSITION); <ide> if (posAttId == -1) { <ide> const errorMsg = "No position attribute found in the mesh."; <del> fileDisplayArea.innerText = errorMsg; <add> //fileDisplayArea.innerText = errorMsg; <ide> DracoModule.destroy(wrapper); <ide> DracoModule.destroy(dracoGeometry); <ide> throw new Error(errorMsg); <ide> THREE.DRACOLoader.prototype = { <ide> DracoModule.destroy(wrapper); <ide> DracoModule.destroy(dracoGeometry); <ide> <del> fileDisplayArea.innerText += geometryInfoStr; <add> //fileDisplayArea.innerText += geometryInfoStr; <ide> <ide> // Import data to Three JS geometry. <ide> const geometry = new THREE.BufferGeometry();
1
Ruby
Ruby
check bind for development versions
57fa2137b29a2f93a478a2038af626c0949fa306
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit_specs <ide> problem "#{stable.version} is a development release" if minor_version.odd? <ide> end <ide> end <add> <add> case formula.name <add> when /bind/ <add> version = Version.parse(stable.url) <add> return if version.to_s.split(".").second.to_i.even? <add> <add> problem "BIND releases with odd minor version numbers (9.13.x, 9.15.x, etc) are " \ <add> "for testing, and can be unstable and are not suitable for general deployment. " \ <add> end <ide> end <ide> <ide> def audit_revision_and_version_scheme
1